tree-sitter/src/runtime/parser.c

82 lines
2 KiB
C
Raw Normal View History

#include "parser.h"
#include <stdio.h>
2013-12-17 13:14:41 -08:00
static int INITIAL_STACK_SIZE = 100;
2013-12-17 13:14:41 -08:00
2014-01-07 21:50:32 -08:00
struct TSStackEntry {
TSState state;
TSTree *node;
};
2013-12-17 13:14:41 -08:00
TSParser TSParserMake(const char *input) {
TSParser result = {
2014-01-07 21:50:32 -08:00
.tree = NULL,
.input = input,
2013-12-17 13:14:41 -08:00
.position = 0,
2014-01-07 21:50:32 -08:00
.lookahead_node = NULL,
.lex_state = 0,
.stack = calloc(INITIAL_STACK_SIZE, sizeof(TSStackEntry)),
.stack_size = 0,
2013-12-17 13:14:41 -08:00
};
return result;
}
void TSParserShift(TSParser *parser, TSState parse_state) {
TSStackEntry *entry = (parser->stack + parser->stack_size);
entry->state = parse_state;
2014-01-07 21:50:32 -08:00
entry->node = parser->lookahead_node;
parser->lookahead_node = NULL;
parser->stack_size++;
2013-12-17 13:14:41 -08:00
}
void TSParserReduce(TSParser *parser, TSSymbol symbol, int child_count) {
parser->stack_size -= child_count;
2014-01-07 21:50:32 -08:00
TSTree **children = malloc(child_count * sizeof(TSTree *));
for (int i = 0; i < child_count; i++) {
size_t j = parser->stack_size + i;
children[i] = parser->stack[j].node;
}
parser->lookahead_node = TSTreeMake(symbol, child_count, children);
2013-12-17 13:14:41 -08:00
}
void TSParserError(TSParser *parser) {
}
void TSParserAdvance(TSParser *parser, TSState lex_state) {
parser->position++;
parser->lex_state = lex_state;
}
char TSParserLookaheadChar(const TSParser *parser) {
return parser->input[parser->position];
}
2014-01-07 21:50:32 -08:00
long TSParserLookaheadSym(const TSParser *parser) {
TSTree *node = parser->lookahead_node;
return node ? node->value : -1;
}
void TSParserSetLookaheadSym(TSParser *parser, TSSymbol symbol) {
2014-01-07 21:50:32 -08:00
parser->lookahead_node = TSTreeMake(symbol, 0, NULL);
2013-12-17 13:14:41 -08:00
}
2013-12-27 17:31:08 -08:00
TSState TSParserParseState(const TSParser *parser) {
return parser->stack[parser->stack_size - 1].state;
2013-12-17 13:14:41 -08:00
}
2013-12-27 17:31:08 -08:00
TSState TSParserLexState(const TSParser *parser) {
return parser->lex_state;
2013-12-27 17:31:08 -08:00
}
void TSParserSetLexState(TSParser *parser, TSState lex_state) {
parser->lex_state = lex_state;
}
2014-01-07 21:50:32 -08:00
void TSParserAcceptInput(TSParser *parser) {
parser->tree = parser->stack[parser->stack_size - 1].node;
}