tree-sitter/src/runtime/document.c

90 lines
2.5 KiB
C
Raw Normal View History

2014-02-18 09:07:00 -08:00
#include "tree_sitter/runtime.h"
#include "tree_sitter/parser.h"
#include "runtime/tree.h"
#include <string.h>
2014-01-07 21:50:32 -08:00
2014-06-28 18:37:29 -07:00
struct TSDocument {
TSParser *parser;
2014-06-28 18:45:22 -07:00
const TSTree *tree;
2014-06-28 18:56:04 -07:00
TSInput input;
size_t error_count;
2014-01-07 21:50:32 -08:00
};
2014-06-28 18:37:29 -07:00
TSDocument * ts_document_make() {
return malloc(sizeof(TSDocument));
2014-01-07 21:50:32 -08:00
}
2014-06-28 18:37:29 -07:00
void ts_document_free(TSDocument *document) {
ts_parser_free(document->parser);
2014-06-09 13:02:39 -07:00
if (document->input.release_fn)
document->input.release_fn(document->input.data);
free(document);
2014-02-20 18:38:31 -08:00
}
void ts_document_set_parser(TSDocument *document, TSParser *parser) {
document->parser = parser;
2014-01-07 21:50:32 -08:00
}
2014-06-28 18:45:22 -07:00
const TSTree * ts_document_tree(const TSDocument *document) {
2014-01-07 21:50:32 -08:00
return document->tree;
}
2014-06-28 18:37:29 -07:00
const char * ts_document_string(const TSDocument *document) {
return ts_tree_string(document->tree, ts_parser_config(document->parser).symbol_names);
}
2014-06-28 18:56:04 -07:00
void ts_document_set_input(TSDocument *document, TSInput input) {
document->input = input;
document->tree = ts_parser_parse(document->parser, document->input, NULL);
}
void ts_document_edit(TSDocument *document, TSInputEdit edit) {
document->tree = ts_parser_parse(document->parser, document->input, &edit);
}
2014-06-28 18:45:22 -07:00
const char * ts_document_symbol_name(const TSDocument *document, const TSTree *tree) {
return ts_parser_config(document->parser).symbol_names[tree->symbol];
}
typedef struct {
const char *string;
size_t position;
size_t length;
} TSStringInput;
const char * ts_string_input_read(void *d, size_t *bytes_read) {
TSStringInput *data = (TSStringInput *)d;
if (data->position >= data->length) {
*bytes_read = 0;
return "";
}
size_t previous_position = data->position;
data->position = data->length;
*bytes_read = data->position - previous_position;
return data->string + previous_position;
}
int ts_string_input_seek(void *d, size_t position) {
TSStringInput *data = (TSStringInput *)d;
data->position = position;
return (position < data->length);
}
2014-06-28 18:56:04 -07:00
TSInput ts_string_input_make(const char *string) {
TSStringInput *data = malloc(sizeof(TSStringInput));
data->string = string;
data->position = 0;
data->length = strlen(string);
2014-06-28 18:56:04 -07:00
TSInput input = {
.data = (void *)data,
.read_fn = ts_string_input_read,
.seek_fn = ts_string_input_seek,
.release_fn = free,
};
return input;
}
2014-06-28 18:37:29 -07:00
void ts_document_set_input_string(TSDocument *document, const char *text) {
ts_document_set_input(document, ts_string_input_make(text));
2014-01-07 21:50:32 -08:00
}