tree-sitter/src/runtime/lexer.c

77 lines
2.4 KiB
C
Raw Normal View History

#include "runtime/lexer.h"
#include "tree_sitter/parser.h"
2014-07-17 23:29:11 -07:00
#include "runtime/tree.h"
#include "runtime/length.h"
2014-09-13 00:15:24 -07:00
#include "utf8proc.h"
static int advance(TSLexer *lexer) {
2014-08-31 16:24:27 -07:00
static const char *empty_chunk = "";
2014-09-13 00:15:24 -07:00
lexer->lookahead = 0;
if (lexer->chunk == empty_chunk) {
lexer->lookahead_size = 0;
2014-08-31 16:24:27 -07:00
return 0;
2014-09-13 00:15:24 -07:00
}
2014-08-31 16:24:27 -07:00
if (lexer->chunk_start + lexer->chunk_size <= lexer->current_position.bytes + 1) {
if (lexer->lookahead_size) {
lexer->current_position.bytes += lexer->lookahead_size;
lexer->current_position.chars += 1;
}
2014-09-13 00:15:24 -07:00
lexer->lookahead_size = 0;
lexer->chunk_start += lexer->chunk_size;
lexer->chunk = lexer->input.read_fn(lexer->input.data, &lexer->chunk_size);
}
if (lexer->chunk_size == 0) {
lexer->lookahead_size = 0;
2014-08-31 16:24:27 -07:00
lexer->chunk = empty_chunk;
2014-09-13 00:15:24 -07:00
} else {
if (lexer->lookahead_size) {
lexer->current_position.bytes += lexer->lookahead_size;
lexer->current_position.chars += 1;
}
2014-09-13 00:15:24 -07:00
lexer->lookahead_size = utf8proc_iterate(
(const uint8_t *)lexer->chunk + (lexer->current_position.bytes - lexer->chunk_start),
lexer->chunk_start + lexer->chunk_size - lexer->current_position.bytes + 1,
2014-09-13 00:15:24 -07:00
&lexer->lookahead);
}
2014-08-31 16:24:27 -07:00
2014-07-20 20:27:33 -07:00
return 1;
}
2014-07-31 13:11:39 -07:00
static TSTree *accept(TSLexer *lexer, TSSymbol symbol, int is_hidden) {
TSLength size = ts_length_sub(lexer->current_position, lexer->token_start_position);
TSLength padding = ts_length_sub(lexer->token_start_position, lexer->token_end_position);
lexer->token_end_position = lexer->current_position;
return (symbol == ts_builtin_sym_error)
? ts_tree_make_error(size, padding, ts_lexer_lookahead_char(lexer))
: ts_tree_make_leaf(symbol, size, padding, is_hidden);
}
2014-08-31 16:24:27 -07:00
/*
* The `advance` and `accept` methods are stored as fields on the Lexer so
* that generated parsers can call them without needing to be linked against
* this library.
*/
TSLexer ts_lexer_make() {
TSLexer result = (TSLexer) { .debug = 0,
.advance_fn = advance,
.accept_fn = accept, };
ts_lexer_reset(&result);
return result;
}
void ts_lexer_reset(TSLexer *lexer) {
lexer->chunk = NULL;
lexer->chunk_start = 0;
lexer->chunk_size = 0;
lexer->current_position = ts_length_zero(),
lexer->token_start_position = ts_length_zero(),
lexer->token_end_position = ts_length_zero(),
2014-09-13 00:15:24 -07:00
lexer->lookahead = 0;
lexer->lookahead_size = 0;
}