Debian Codegraph @

Xtree-house/bindings/vendor/src/parser.c

raw
1 #include <stdio.h>
2 #include <limits.h>
3 #include <stdbool.h>
4 #include <inttypes.h>
5 #include "tree_sitter/api.h"
6 #include "./alloc.h"
7 #include "./array.h"
8 #include "./error_costs.h"
9 #include "./get_changed_ranges.h"
10 #include "./language.h"
11 #include "./length.h"
12 #include "./lexer.h"
13 #include "./reduce_action.h"
14 #include "./reusable_node.h"
15 #include "./stack.h"
16 #include "./subtree.h"
17 #include "./tree.h"
18 #include "./ts_assert.h"
19 #include "./wasm_store.h"
20
21 #define LOG(...) \
22 if (self->lexer.logger.log || self->dot_graph_file) { \
23 snprintf(self->lexer.debug_buffer, TREE_SITTER_SERIALIZATION_BUFFER_SIZE, __VA_ARGS__); \
24 ts_parser__log(self); \
25 }
26
27 #define LOG_LOOKAHEAD(symbol_name, size) \
28 if (self->lexer.logger.log || self->dot_graph_file) { \
29 char *buf = self->lexer.debug_buffer; \
30 const char *symbol = symbol_name; \
31 int off = snprintf( \
32 buf, \
33 TREE_SITTER_SERIALIZATION_BUFFER_SIZE, \
34 "lexed_lookahead sym:" \
35 ); \
36 for ( \
37 int i = 0; \
38 symbol[i] != '\0' \
39 && off < TREE_SITTER_SERIALIZATION_BUFFER_SIZE; \
40 i++ \
41 ) { \
42 switch (symbol[i]) { \
43 case '\t': buf[off++] = '\\'; buf[off++] = 't'; break; \
44 case '\n': buf[off++] = '\\'; buf[off++] = 'n'; break; \
45 case '\v': buf[off++] = '\\'; buf[off++] = 'v'; break; \
46 case '\f': buf[off++] = '\\'; buf[off++] = 'f'; break; \
47 case '\r': buf[off++] = '\\'; buf[off++] = 'r'; break; \
48 case '\\': buf[off++] = '\\'; buf[off++] = '\\'; break; \
49 default: buf[off++] = symbol[i]; break; \
50 } \
51 } \
52 snprintf( \
53 buf + off, \
54 TREE_SITTER_SERIALIZATION_BUFFER_SIZE - off, \
55 ", size:%u", \
56 size \
57 ); \
58 ts_parser__log(self); \
59 }
60
61 #define LOG_STACK() \
62 if (self->dot_graph_file) { \
63 ts_stack_print_dot_graph(self->stack, self->language, self->dot_graph_file); \
64 fputs("\n\n", self->dot_graph_file); \
65 }
66
67 #define LOG_TREE(tree) \
68 if (self->dot_graph_file) { \
69 ts_subtree_print_dot_graph(tree, self->language, self->dot_graph_file); \
70 fputs("\n", self->dot_graph_file); \
71 }
72
73 #define SYM_NAME(symbol) ts_language_symbol_name(self->language, symbol)
74
75 #define TREE_NAME(tree) SYM_NAME(ts_subtree_symbol(tree))
76
77 static const unsigned MAX_VERSION_COUNT = 6;
78 static const unsigned MAX_VERSION_COUNT_OVERFLOW = 4;
79 static const unsigned MAX_SUMMARY_DEPTH = 16;
80 static const unsigned MAX_COST_DIFFERENCE = 18 * ERROR_COST_PER_SKIPPED_TREE;
81 static const unsigned OP_COUNT_PER_PARSER_CALLBACK_CHECK = 100;
82
83 typedef struct {
84 Subtree token;
85 Subtree last_external_token;
86 uint32_t byte_index;
87 } TokenCache;
88
89 struct TSParser {
90 Lexer lexer;
91 Stack *stack;
92 SubtreePool tree_pool;
93 const TSLanguage *language;
94 TSWasmStore *wasm_store;
95 ReduceActionSet reduce_actions;
96 Subtree finished_tree;
97 SubtreeArray trailing_extras;
98 SubtreeArray trailing_extras2;
99 SubtreeArray scratch_trees;
100 TokenCache token_cache;
101 ReusableNode reusable_node;
102 void *external_scanner_payload;
103 FILE *dot_graph_file;
104 unsigned accept_count;
105 unsigned operation_count;
106 Subtree old_tree;
107 TSRangeArray included_range_differences;
108 TSParseOptions parse_options;
109 TSParseState parse_state;
110 unsigned included_range_difference_index;
111 bool has_scanner_error;
112 bool canceled_balancing;
113 bool has_error;
114 };
115
116 typedef struct {
117 unsigned cost;
118 unsigned node_count;
119 int dynamic_precedence;
120 bool is_in_error;
121 } ErrorStatus;
122
123 typedef enum {
124 ErrorComparisonTakeLeft,
125 ErrorComparisonPreferLeft,
126 ErrorComparisonNone,
127 ErrorComparisonPreferRight,
128 ErrorComparisonTakeRight,
129 } ErrorComparison;
130
131 typedef struct {
132 const char *string;
133 uint32_t length;
134 } TSStringInput;
135
136 // StringInput
137
138 static const char *ts_string_input_read(
139 void *_self,
140 uint32_t byte,
141 TSPoint point,
142 uint32_t *length
143 ) {
144 (void)point;
145 TSStringInput *self = (TSStringInput *)_self;
146 if (byte >= self->length) {
147 *length = 0;
148 return "";
149 } else {
150 *length = self->length - byte;
151 return self->string + byte;
152 }
153 }
154
155 // Parser - Private
156
157 static void ts_parser__log(TSParser *self) {
158 if (self->lexer.logger.log) {
159 self->lexer.logger.log(
160 self->lexer.logger.payload,
161 TSLogTypeParse,
162 self->lexer.debug_buffer
163 );
164 }
165
166 if (self->dot_graph_file) {
167 fprintf(self->dot_graph_file, "graph {\nlabel=\"");
168 for (char *chr = &self->lexer.debug_buffer[0]; *chr != 0; chr++) {
169 if (*chr == '"' || *chr == '\\') fputc('\\', self->dot_graph_file);
170 fputc(*chr, self->dot_graph_file);
171 }
172 fprintf(self->dot_graph_file, "\"\n}\n\n");
173 }
174 }
175
176 static bool ts_parser__breakdown_top_of_stack(
177 TSParser *self,
178 StackVersion version
179 ) {
180 bool did_break_down = false;
181 bool pending = false;
182
183 do {
184 StackSliceArray pop = ts_stack_pop_pending(self->stack, version);
185 if (!pop.size) break;
186
187 did_break_down = true;
188 pending = false;
189 for (uint32_t i = 0; i < pop.size; i++) {
190 StackSlice slice = *array_get(&pop, i);
191 TSStateId state = ts_stack_state(self->stack, slice.version);
192 Subtree parent = *array_front(&slice.subtrees);
193
194 for (uint32_t j = 0, n = ts_subtree_child_count(parent); j < n; j++) {
195 Subtree child = ts_subtree_children(parent)[j];
196 pending = ts_subtree_child_count(child) > 0;
197
198 if (ts_subtree_is_error(child)) {
199 state = ERROR_STATE;
200 } else if (!ts_subtree_extra(child)) {
201 state = ts_language_next_state(self->language, state, ts_subtree_symbol(child));
202 }
203
204 ts_subtree_retain(child);
205 ts_stack_push(self->stack, slice.version, child, pending, state);
206 }
207
208 for (uint32_t j = 1; j < slice.subtrees.size; j++) {
209 Subtree tree = *array_get(&slice.subtrees, j);
210 ts_stack_push(self->stack, slice.version, tree, false, state);
211 }
212
213 ts_subtree_release(&self->tree_pool, parent);
214 array_delete(&slice.subtrees);
215
216 LOG("breakdown_top_of_stack tree:%s", TREE_NAME(parent));
217 LOG_STACK();
218 }
219 } while (pending);
220
221 return did_break_down;
222 }
223
224 static void ts_parser__breakdown_lookahead(
225 TSParser *self,
226 Subtree *lookahead,
227 TSStateId state,
228 ReusableNode *reusable_node
229 ) {
230 bool did_descend = false;
231 Subtree tree = reusable_node_tree(reusable_node);
232 while (ts_subtree_child_count(tree) > 0 && ts_subtree_parse_state(tree) != state) {
233 LOG("state_mismatch sym:%s", TREE_NAME(tree));
234 reusable_node_descend(reusable_node);
235 tree = reusable_node_tree(reusable_node);
236 did_descend = true;
237 }
238
239 if (did_descend) {
240 ts_subtree_release(&self->tree_pool, *lookahead);
241 *lookahead = tree;
242 ts_subtree_retain(*lookahead);
243 }
244 }
245
246 static ErrorComparison ts_parser__compare_versions(
247 TSParser *self,
248 ErrorStatus a,
249 ErrorStatus b
250 ) {
251 (void)self;
252 if (!a.is_in_error && b.is_in_error) {
253 if (a.cost < b.cost) {
254 return ErrorComparisonTakeLeft;
255 } else {
256 return ErrorComparisonPreferLeft;
257 }
258 }
259
260 if (a.is_in_error && !b.is_in_error) {
261 if (b.cost < a.cost) {
262 return ErrorComparisonTakeRight;
263 } else {
264 return ErrorComparisonPreferRight;
265 }
266 }
267
268 if (a.cost < b.cost) {
269 if ((b.cost - a.cost) * (1 + a.node_count) > MAX_COST_DIFFERENCE) {
270 return ErrorComparisonTakeLeft;
271 } else {
272 return ErrorComparisonPreferLeft;
273 }
274 }
275
276 if (b.cost < a.cost) {
277 if ((a.cost - b.cost) * (1 + b.node_count) > MAX_COST_DIFFERENCE) {
278 return ErrorComparisonTakeRight;
279 } else {
280 return ErrorComparisonPreferRight;
281 }
282 }
283
284 if (a.dynamic_precedence > b.dynamic_precedence) return ErrorComparisonPreferLeft;
285 if (b.dynamic_precedence > a.dynamic_precedence) return ErrorComparisonPreferRight;
286 return ErrorComparisonNone;
287 }
288
289 static ErrorStatus ts_parser__version_status(
290 TSParser *self,
291 StackVersion version
292 ) {
293 unsigned cost = ts_stack_error_cost(self->stack, version);
294 bool is_paused = ts_stack_is_paused(self->stack, version);
295 if (is_paused) cost += ERROR_COST_PER_SKIPPED_TREE;
296 return (ErrorStatus) {
297 .cost = cost,
298 .node_count = ts_stack_node_count_since_error(self->stack, version),
299 .dynamic_precedence = ts_stack_dynamic_precedence(self->stack, version),
300 .is_in_error = is_paused || ts_stack_state(self->stack, version) == ERROR_STATE
301 };
302 }
303
304 static bool ts_parser__better_version_exists(
305 TSParser *self,
306 StackVersion version,
307 bool is_in_error,
308 unsigned cost
309 ) {
310 if (self->finished_tree.ptr && ts_subtree_error_cost(self->finished_tree) <= cost) {
311 return true;
312 }
313
314 Length position = ts_stack_position(self->stack, version);
315 ErrorStatus status = {
316 .cost = cost,
317 .is_in_error = is_in_error,
318 .dynamic_precedence = ts_stack_dynamic_precedence(self->stack, version),
319 .node_count = ts_stack_node_count_since_error(self->stack, version),
320 };
321
322 for (StackVersion i = 0, n = ts_stack_version_count(self->stack); i < n; i++) {
323 if (i == version ||
324 !ts_stack_is_active(self->stack, i) ||
325 ts_stack_position(self->stack, i).bytes < position.bytes) continue;
326 ErrorStatus status_i = ts_parser__version_status(self, i);
327 switch (ts_parser__compare_versions(self, status, status_i)) {
328 case ErrorComparisonTakeRight:
329 return true;
330 case ErrorComparisonPreferRight:
331 if (ts_stack_can_merge(self->stack, i, version)) return true;
332 break;
333 default:
334 break;
335 }
336 }
337
338 return false;
339 }
340
341 static bool ts_parser__call_main_lex_fn(TSParser *self, TSLexerMode lex_mode) {
342 if (ts_language_is_wasm(self->language)) {
343 return ts_wasm_store_call_lex_main(self->wasm_store, lex_mode.lex_state);
344 } else {
345 return self->language->lex_fn(&self->lexer.data, lex_mode.lex_state);
346 }
347 }
348
349 static bool ts_parser__call_keyword_lex_fn(TSParser *self) {
350 if (ts_language_is_wasm(self->language)) {
351 return ts_wasm_store_call_lex_keyword(self->wasm_store, 0);
352 } else {
353 return self->language->keyword_lex_fn(&self->lexer.data, 0);
354 }
355 }
356
357 static void ts_parser__external_scanner_create(
358 TSParser *self
359 ) {
360 if (self->language && self->language->external_scanner.states) {
361 if (ts_language_is_wasm(self->language)) {
362 self->external_scanner_payload = (void *)(uintptr_t)ts_wasm_store_call_scanner_create(
363 self->wasm_store
364 );
365 if (ts_wasm_store_has_error(self->wasm_store)) {
366 self->has_scanner_error = true;
367 }
368 } else if (self->language->external_scanner.create) {
369 self->external_scanner_payload = self->language->external_scanner.create();
370 }
371 }
372 }
373
374 static void ts_parser__external_scanner_destroy(
375 TSParser *self
376 ) {
377 if (
378 self->language &&
379 self->external_scanner_payload &&
380 self->language->external_scanner.destroy &&
381 !ts_language_is_wasm(self->language)
382 ) {
383 self->language->external_scanner.destroy(
384 self->external_scanner_payload
385 );
386 }
387 self->external_scanner_payload = NULL;
388 }
389
390 static unsigned ts_parser__external_scanner_serialize(
391 TSParser *self
392 ) {
393 uint32_t length;
394 if (ts_language_is_wasm(self->language)) {
395 length = ts_wasm_store_call_scanner_serialize(
396 self->wasm_store,
397 (uintptr_t)self->external_scanner_payload,
398 self->lexer.debug_buffer
399 );
400 if (ts_wasm_store_has_error(self->wasm_store)) {
401 self->has_scanner_error = true;
402 }
403 } else {
404 length = self->language->external_scanner.serialize(
405 self->external_scanner_payload,
406 self->lexer.debug_buffer
407 );
408 }
409 ts_assert(length <= TREE_SITTER_SERIALIZATION_BUFFER_SIZE);
410 return length;
411 }
412
413 static void ts_parser__external_scanner_deserialize(
414 TSParser *self,
415 Subtree external_token
416 ) {
417 const char *data = NULL;
418 uint32_t length = 0;
419 if (external_token.ptr) {
420 data = ts_external_scanner_state_data(&external_token.ptr->external_scanner_state);
421 length = external_token.ptr->external_scanner_state.length;
422 }
423
424 if (ts_language_is_wasm(self->language)) {
425 ts_wasm_store_call_scanner_deserialize(
426 self->wasm_store,
427 (uintptr_t)self->external_scanner_payload,
428 data,
429 length
430 );
431 if (ts_wasm_store_has_error(self->wasm_store)) {
432 self->has_scanner_error = true;
433 }
434 } else {
435 self->language->external_scanner.deserialize(
436 self->external_scanner_payload,
437 data,
438 length
439 );
440 }
441 }
442
443 static bool ts_parser__external_scanner_scan(
444 TSParser *self,
445 TSStateId external_lex_state
446 ) {
447 if (ts_language_is_wasm(self->language)) {
448 bool result = ts_wasm_store_call_scanner_scan(
449 self->wasm_store,
450 (uintptr_t)self->external_scanner_payload,
451 external_lex_state * self->language->external_token_count
452 );
453 if (ts_wasm_store_has_error(self->wasm_store)) {
454 self->has_scanner_error = true;
455 }
456 return result;
457 } else {
458 const bool *valid_external_tokens = ts_language_enabled_external_tokens(
459 self->language,
460 external_lex_state
461 );
462 return self->language->external_scanner.scan(
463 self->external_scanner_payload,
464 &self->lexer.data,
465 valid_external_tokens
466 );
467 }
468 }
469
470 static bool ts_parser__can_reuse_first_leaf(
471 TSParser *self,
472 TSStateId state,
473 Subtree tree,
474 TableEntry *table_entry
475 ) {
476 TSSymbol leaf_symbol = ts_subtree_leaf_symbol(tree);
477 TSStateId leaf_state = ts_subtree_leaf_parse_state(tree);
478 TSLexerMode current_lex_mode = ts_language_lex_mode_for_state(self->language, state);
479 TSLexerMode leaf_lex_mode = ts_language_lex_mode_for_state(self->language, leaf_state);
480
481 // At the end of a non-terminal extra node, the lexer normally returns
482 // NULL, which indicates that the parser should look for a reduce action
483 // at symbol `0`. Avoid reusing tokens in this situation to ensure that
484 // the same thing happens when incrementally reparsing.
485 if (current_lex_mode.lex_state == (uint16_t)(-1)) return false;
486
487 // If the token was created in a state with the same set of lookaheads, it is reusable.
488 if (
489 table_entry->action_count > 0 &&
490 memcmp(&leaf_lex_mode, &current_lex_mode, sizeof(TSLexerMode)) == 0 &&
491 (
492 leaf_symbol != self->language->keyword_capture_token ||
493 (!ts_subtree_is_keyword(tree) && ts_subtree_parse_state(tree) == state)
494 )
495 ) return true;
496
497 // Empty tokens are not reusable in states with different lookaheads.
498 if (ts_subtree_size(tree).bytes == 0 && leaf_symbol != ts_builtin_sym_end) return false;
499
500 // If the current state allows external tokens or other tokens that conflict with this
501 // token, this token is not reusable.
502 return current_lex_mode.external_lex_state == 0 && table_entry->is_reusable;
503 }
504
505 static Subtree ts_parser__lex(
506 TSParser *self,
507 StackVersion version,
508 TSStateId parse_state
509 ) {
510 TSLexerMode lex_mode = ts_language_lex_mode_for_state(self->language, parse_state);
511 if (lex_mode.lex_state == (uint16_t)-1) {
512 LOG("no_lookahead_after_non_terminal_extra");
513 return NULL_SUBTREE;
514 }
515
516 const Length start_position = ts_stack_position(self->stack, version);
517 const Subtree external_token = ts_stack_last_external_token(self->stack, version);
518
519 bool found_external_token = false;
520 bool error_mode = parse_state == ERROR_STATE;
521 bool skipped_error = false;
522 bool called_get_column = false;
523 int32_t first_error_character = 0;
524 Length error_start_position = length_zero();
525 Length error_end_position = length_zero();
526 uint32_t lookahead_end_byte = 0;
527 uint32_t external_scanner_state_len = 0;
528 bool external_scanner_state_changed = false;
529 ts_lexer_reset(&self->lexer, start_position);
530
531 for (;;) {
532 bool found_token = false;
533 Length current_position = self->lexer.current_position;
534 ColumnData column_data = self->lexer.column_data;
535
536 if (lex_mode.external_lex_state != 0) {
537 LOG(
538 "lex_external state:%d, row:%u, column:%u",
539 lex_mode.external_lex_state,
540 current_position.extent.row,
541 current_position.extent.column
542 );
543 ts_lexer_start(&self->lexer);
544 ts_parser__external_scanner_deserialize(self, external_token);
545 found_token = ts_parser__external_scanner_scan(self, lex_mode.external_lex_state);
546 if (self->has_scanner_error) return NULL_SUBTREE;
547 ts_lexer_finish(&self->lexer, &lookahead_end_byte);
548
549 if (found_token) {
550 external_scanner_state_len = ts_parser__external_scanner_serialize(self);
551 external_scanner_state_changed = !ts_external_scanner_state_eq(
552 ts_subtree_external_scanner_state(external_token),
553 self->lexer.debug_buffer,
554 external_scanner_state_len
555 );
556
557 // Avoid infinite loops caused by the external scanner returning empty tokens.
558 // Empty tokens are needed in some circumstances, e.g. indent/dedent tokens
559 // in Python. Ignore the following classes of empty tokens:
560 //
561 // * Tokens produced during error recovery. When recovering from an error,
562 // all tokens are allowed, so it's easy to accidentally return unwanted
563 // empty tokens.
564 // * Tokens that are marked as 'extra' in the grammar. These don't change
565 // the parse state, so they would definitely cause an infinite loop.
566 if (
567 self->lexer.token_end_position.bytes <= current_position.bytes &&
568 !external_scanner_state_changed
569 ) {
570 TSSymbol symbol = self->language->external_scanner.symbol_map[self->lexer.data.result_symbol];
571 TSStateId next_parse_state = ts_language_next_state(self->language, parse_state, symbol);
572 bool token_is_extra = (next_parse_state == parse_state);
573 if (error_mode || !ts_stack_has_advanced_since_error(self->stack, version) || token_is_extra) {
574 LOG(
575 "ignore_empty_external_token symbol:%s",
576 SYM_NAME(self->language->external_scanner.symbol_map[self->lexer.data.result_symbol])
577 );
578 found_token = false;
579 }
580 }
581 }
582
583 if (found_token) {
584 found_external_token = true;
585 called_get_column = self->lexer.did_get_column;
586 break;
587 }
588
589 ts_lexer_reset(&self->lexer, current_position);
590 self->lexer.column_data = column_data;
591 }
592
593 LOG(
594 "lex_internal state:%d, row:%u, column:%u",
595 lex_mode.lex_state,
596 current_position.extent.row,
597 current_position.extent.column
598 );
599 ts_lexer_start(&self->lexer);
600 found_token = ts_parser__call_main_lex_fn(self, lex_mode);
601 ts_lexer_finish(&self->lexer, &lookahead_end_byte);
602 if (found_token) break;
603
604 if (!error_mode) {
605 error_mode = true;
606 lex_mode = ts_language_lex_mode_for_state(self->language, ERROR_STATE);
607 ts_lexer_reset(&self->lexer, start_position);
608 continue;
609 }
610
611 if (!skipped_error) {
612 LOG("skip_unrecognized_character");
613 skipped_error = true;
614 error_start_position = self->lexer.token_start_position;
615 error_end_position = self->lexer.token_start_position;
616 first_error_character = self->lexer.data.lookahead;
617 }
618
619 if (self->lexer.current_position.bytes == error_end_position.bytes) {
620 if (self->lexer.data.eof(&self->lexer.data)) {
621 self->lexer.data.result_symbol = ts_builtin_sym_error;
622 break;
623 }
624 self->lexer.data.advance(&self->lexer.data, false);
625 }
626
627 error_end_position = self->lexer.current_position;
628 }
629
630 Subtree result;
631 if (skipped_error) {
632 Length padding = length_sub(error_start_position, start_position);
633 Length size = length_sub(error_end_position, error_start_position);
634 uint32_t lookahead_bytes = lookahead_end_byte - error_end_position.bytes;
635 result = ts_subtree_new_error(
636 &self->tree_pool,
637 first_error_character,
638 padding,
639 size,
640 lookahead_bytes,
641 parse_state,
642 self->language
643 );
644 } else {
645 bool is_keyword = false;
646 TSSymbol symbol = self->lexer.data.result_symbol;
647 Length padding = length_sub(self->lexer.token_start_position, start_position);
648 Length size = length_sub(self->lexer.token_end_position, self->lexer.token_start_position);
649 uint32_t lookahead_bytes = lookahead_end_byte - self->lexer.token_end_position.bytes;
650
651 if (found_external_token) {
652 symbol = self->language->external_scanner.symbol_map[symbol];
653 } else if (symbol == self->language->keyword_capture_token && symbol != 0) {
654 uint32_t end_byte = self->lexer.token_end_position.bytes;
655 ts_lexer_reset(&self->lexer, self->lexer.token_start_position);
656 ts_lexer_start(&self->lexer);
657
658 is_keyword = ts_parser__call_keyword_lex_fn(self);
659
660 if (
661 is_keyword &&
662 self->lexer.token_end_position.bytes == end_byte &&
663 (
664 ts_language_has_actions(self->language, parse_state, self->lexer.data.result_symbol) ||
665 ts_language_is_reserved_word(self->language, parse_state, self->lexer.data.result_symbol)
666 )
667 ) {
668 symbol = self->lexer.data.result_symbol;
669 }
670 }
671
672 result = ts_subtree_new_leaf(
673 &self->tree_pool,
674 symbol,
675 padding,
676 size,
677 lookahead_bytes,
678 parse_state,
679 found_external_token,
680 called_get_column,
681 is_keyword,
682 self->language
683 );
684
685 if (found_external_token) {
686 MutableSubtree mut_result = ts_subtree_to_mut_unsafe(result);
687 ts_external_scanner_state_init(
688 &mut_result.ptr->external_scanner_state,
689 self->lexer.debug_buffer,
690 external_scanner_state_len
691 );
692 mut_result.ptr->has_external_scanner_state_change = external_scanner_state_changed;
693 }
694 }
695
696 LOG_LOOKAHEAD(
697 SYM_NAME(ts_subtree_symbol(result)),
698 ts_subtree_total_size(result).bytes
699 );
700 return result;
701 }
702
703 static Subtree ts_parser__get_cached_token(
704 TSParser *self,
705 TSStateId state,
706 size_t position,
707 Subtree last_external_token,
708 TableEntry *table_entry
709 ) {
710 TokenCache *cache = &self->token_cache;
711 if (
712 cache->token.ptr && cache->byte_index == position &&
713 ts_subtree_external_scanner_state_eq(cache->last_external_token, last_external_token)
714 ) {
715 ts_language_table_entry(self->language, state, ts_subtree_symbol(cache->token), table_entry);
716 if (ts_parser__can_reuse_first_leaf(self, state, cache->token, table_entry)) {
717 ts_subtree_retain(cache->token);
718 return cache->token;
719 }
720 }
721 return NULL_SUBTREE;
722 }
723
724 static void ts_parser__set_cached_token(
725 TSParser *self,
726 uint32_t byte_index,
727 Subtree last_external_token,
728 Subtree token
729 ) {
730 TokenCache *cache = &self->token_cache;
731 if (token.ptr) ts_subtree_retain(token);
732 if (last_external_token.ptr) ts_subtree_retain(last_external_token);
733 if (cache->token.ptr) ts_subtree_release(&self->tree_pool, cache->token);
734 if (cache->last_external_token.ptr) ts_subtree_release(&self->tree_pool, cache->last_external_token);
735 cache->token = token;
736 cache->byte_index = byte_index;
737 cache->last_external_token = last_external_token;
738 }
739
740 static bool ts_parser__has_included_range_difference(
741 const TSParser *self,
742 uint32_t start_position,
743 uint32_t end_position
744 ) {
745 return ts_range_array_intersects(
746 &self->included_range_differences,
747 self->included_range_difference_index,
748 start_position,
749 end_position
750 );
751 }
752
753 static Subtree ts_parser__reuse_node(
754 TSParser *self,
755 StackVersion version,
756 TSStateId *state,
757 uint32_t position,
758 Subtree last_external_token,
759 TableEntry *table_entry
760 ) {
761 Subtree result;
762 while ((result = reusable_node_tree(&self->reusable_node)).ptr) {
763 uint32_t byte_offset = reusable_node_byte_offset(&self->reusable_node);
764 uint32_t end_byte_offset = byte_offset + ts_subtree_total_bytes(result);
765
766 // Do not reuse an EOF node if the included ranges array has changes
767 // later on in the file.
768 if (ts_subtree_is_eof(result)) end_byte_offset = UINT32_MAX;
769
770 if (byte_offset > position) {
771 LOG("before_reusable_node symbol:%s", TREE_NAME(result));
772 break;
773 }
774
775 if (byte_offset < position) {
776 LOG("past_reusable_node symbol:%s", TREE_NAME(result));
777 if (end_byte_offset <= position || !reusable_node_descend(&self->reusable_node)) {
778 reusable_node_advance(&self->reusable_node);
779 }
780 continue;
781 }
782
783 if (!ts_subtree_external_scanner_state_eq(self->reusable_node.last_external_token, last_external_token)) {
784 LOG("reusable_node_has_different_external_scanner_state symbol:%s", TREE_NAME(result));
785 reusable_node_advance(&self->reusable_node);
786 continue;
787 }
788
789 const char *reason = NULL;
790 if (ts_subtree_has_changes(result)) {
791 reason = "has_changes";
792 } else if (ts_subtree_is_error(result)) {
793 reason = "is_error";
794 } else if (ts_subtree_missing(result)) {
795 reason = "is_missing";
796 } else if (ts_subtree_is_fragile(result)) {
797 reason = "is_fragile";
798 } else if (ts_parser__has_included_range_difference(self, byte_offset, end_byte_offset)) {
799 reason = "contains_different_included_range";
800 }
801
802 if (reason) {
803 LOG("cant_reuse_node_%s tree:%s", reason, TREE_NAME(result));
804 if (!reusable_node_descend(&self->reusable_node)) {
805 reusable_node_advance(&self->reusable_node);
806 ts_parser__breakdown_top_of_stack(self, version);
807 *state = ts_stack_state(self->stack, version);
808 }
809 continue;
810 }
811
812 TSSymbol leaf_symbol = ts_subtree_leaf_symbol(result);
813 ts_language_table_entry(self->language, *state, leaf_symbol, table_entry);
814 if (!ts_parser__can_reuse_first_leaf(self, *state, result, table_entry)) {
815 LOG(
816 "cant_reuse_node symbol:%s, first_leaf_symbol:%s",
817 TREE_NAME(result),
818 SYM_NAME(leaf_symbol)
819 );
820 reusable_node_advance_past_leaf(&self->reusable_node);
821 break;
822 }
823
824 LOG("reuse_node symbol:%s", TREE_NAME(result));
825 ts_subtree_retain(result);
826 return result;
827 }
828
829 return NULL_SUBTREE;
830 }
831
832 // Determine if a given tree should be replaced by an alternative tree.
833 //
834 // The decision is based on the trees' error costs (if any), their dynamic precedence,
835 // and finally, as a default, by a recursive comparison of the trees' symbols.
836 static bool ts_parser__select_tree(TSParser *self, Subtree left, Subtree right) {
837 if (!left.ptr) return true;
838 if (!right.ptr) return false;
839
840 if (ts_subtree_error_cost(right) < ts_subtree_error_cost(left)) {
841 LOG("select_smaller_error symbol:%s, over_symbol:%s", TREE_NAME(right), TREE_NAME(left));
842 return true;
843 }
844
845 if (ts_subtree_error_cost(left) < ts_subtree_error_cost(right)) {
846 LOG("select_smaller_error symbol:%s, over_symbol:%s", TREE_NAME(left), TREE_NAME(right));
847 return false;
848 }
849
850 if (ts_subtree_dynamic_precedence(right) > ts_subtree_dynamic_precedence(left)) {
851 LOG("select_higher_precedence symbol:%s, prec:%" PRId32 ", over_symbol:%s, other_prec:%" PRId32,
852 TREE_NAME(right), ts_subtree_dynamic_precedence(right), TREE_NAME(left),
853 ts_subtree_dynamic_precedence(left));
854 return true;
855 }
856
857 if (ts_subtree_dynamic_precedence(left) > ts_subtree_dynamic_precedence(right)) {
858 LOG("select_higher_precedence symbol:%s, prec:%" PRId32 ", over_symbol:%s, other_prec:%" PRId32,
859 TREE_NAME(left), ts_subtree_dynamic_precedence(left), TREE_NAME(right),
860 ts_subtree_dynamic_precedence(right));
861 return false;
862 }
863
864 if (ts_subtree_error_cost(left) > 0) return true;
865
866 int comparison = ts_subtree_compare(left, right, &self->tree_pool);
867 switch (comparison) {
868 case -1:
869 LOG("select_earlier symbol:%s, over_symbol:%s", TREE_NAME(left), TREE_NAME(right));
870 return false;
871 break;
872 case 1:
873 LOG("select_earlier symbol:%s, over_symbol:%s", TREE_NAME(right), TREE_NAME(left));
874 return true;
875 default:
876 LOG("select_existing symbol:%s, over_symbol:%s", TREE_NAME(left), TREE_NAME(right));
877 return false;
878 }
879 }
880
881 // Determine if a given tree's children should be replaced by an alternative
882 // array of children.
883 static bool ts_parser__select_children(
884 TSParser *self,
885 Subtree left,
886 const SubtreeArray *children
887 ) {
888 array_assign(&self->scratch_trees, children);
889
890 // Create a temporary subtree using the scratch trees array. This node does
891 // not perform any allocation except for possibly growing the array to make
892 // room for its own heap data. The scratch tree is never explicitly released,
893 // so the same 'scratch trees' array can be reused again later.
894 MutableSubtree scratch_tree = ts_subtree_new_node(
895 ts_subtree_symbol(left),
896 &self->scratch_trees,
897 0,
898 self->language
899 );
900
901 return ts_parser__select_tree(
902 self,
903 left,
904 ts_subtree_from_mut(scratch_tree)
905 );
906 }
907
908 static void ts_parser__shift(
909 TSParser *self,
910 StackVersion version,
911 TSStateId state,
912 Subtree lookahead,
913 bool extra
914 ) {
915 bool is_leaf = ts_subtree_child_count(lookahead) == 0;
916 Subtree subtree_to_push = lookahead;
917 if (extra != ts_subtree_extra(lookahead) && is_leaf) {
918 MutableSubtree result = ts_subtree_make_mut(&self->tree_pool, lookahead);
919 ts_subtree_set_extra(&result, extra);
920 subtree_to_push = ts_subtree_from_mut(result);
921 }
922
923 ts_stack_push(self->stack, version, subtree_to_push, !is_leaf, state);
924 if (ts_subtree_has_external_tokens(subtree_to_push)) {
925 ts_stack_set_last_external_token(
926 self->stack, version, ts_subtree_last_external_token(subtree_to_push)
927 );
928 }
929 }
930
931 static StackVersion ts_parser__reduce(
932 TSParser *self,
933 StackVersion version,
934 TSSymbol symbol,
935 uint32_t count,
936 int dynamic_precedence,
937 uint16_t production_id,
938 bool is_fragile,
939 bool end_of_non_terminal_extra
940 ) {
941 uint32_t initial_version_count = ts_stack_version_count(self->stack);
942
943 // Pop the given number of nodes from the given version of the parse stack.
944 // If stack versions have previously merged, then there may be more than one
945 // path back through the stack. For each path, create a new parent node to
946 // contain the popped children, and push it onto the stack in place of the
947 // children.
948 StackSliceArray pop = ts_stack_pop_count(self->stack, version, count);
949 uint32_t removed_version_count = 0;
950 uint32_t halted_version_count = ts_stack_halted_version_count(self->stack);
951 for (uint32_t i = 0; i < pop.size; i++) {
952 StackSlice slice = *array_get(&pop, i);
953 StackVersion slice_version = slice.version - removed_version_count;
954
955 // This is where new versions are added to the parse stack. The versions
956 // will all be sorted and truncated at the end of the outer parsing loop.
957 // Allow the maximum version count to be temporarily exceeded, but only
958 // by a limited threshold.
959 if (slice_version > MAX_VERSION_COUNT + MAX_VERSION_COUNT_OVERFLOW + halted_version_count) {
960 ts_stack_remove_version(self->stack, slice_version);
961 ts_subtree_array_delete(&self->tree_pool, &slice.subtrees);
962 removed_version_count++;
963 while (i + 1 < pop.size) {
964 LOG("aborting reduce with too many versions")
965 StackSlice next_slice = *array_get(&pop, i + 1);
966 if (next_slice.version != slice.version) break;
967 ts_subtree_array_delete(&self->tree_pool, &next_slice.subtrees);
968 i++;
969 }
970 continue;
971 }
972
973 // Extra tokens on top of the stack should not be included in this new parent
974 // node. They will be re-pushed onto the stack after the parent node is
975 // created and pushed.
976 SubtreeArray children = slice.subtrees;
977 ts_subtree_array_remove_trailing_extras(&children, &self->trailing_extras);
978
979 MutableSubtree parent = ts_subtree_new_node(
980 symbol, &children, production_id, self->language
981 );
982
983 // This pop operation may have caused multiple stack versions to collapse
984 // into one, because they all diverged from a common state. In that case,
985 // choose one of the arrays of trees to be the parent node's children, and
986 // delete the rest of the tree arrays.
987 while (i + 1 < pop.size) {
988 StackSlice next_slice = *array_get(&pop, i + 1);
989 if (next_slice.version != slice.version) break;
990 i++;
991
992 SubtreeArray next_slice_children = next_slice.subtrees;
993 ts_subtree_array_remove_trailing_extras(&next_slice_children, &self->trailing_extras2);
994
995 if (ts_parser__select_children(
996 self,
997 ts_subtree_from_mut(parent),
998 &next_slice_children
999 )) {
1000 ts_subtree_array_clear(&self->tree_pool, &self->trailing_extras);
1001 ts_subtree_release(&self->tree_pool, ts_subtree_from_mut(parent));
1002 array_swap(&self->trailing_extras, &self->trailing_extras2);
1003 parent = ts_subtree_new_node(
1004 symbol, &next_slice_children, production_id, self->language
1005 );
1006 } else {
1007 array_clear(&self->trailing_extras2);
1008 ts_subtree_array_delete(&self->tree_pool, &next_slice.subtrees);
1009 }
1010 }
1011
1012 TSStateId state = ts_stack_state(self->stack, slice_version);
1013 TSStateId next_state = ts_language_next_state(self->language, state, symbol);
1014 if (end_of_non_terminal_extra && next_state == state) {
1015 parent.ptr->extra = true;
1016 }
1017 if (is_fragile || pop.size > 1 || initial_version_count > 1) {
1018 parent.ptr->fragile_left = true;
1019 parent.ptr->fragile_right = true;
1020 parent.ptr->parse_state = TS_TREE_STATE_NONE;
1021 } else {
1022 parent.ptr->parse_state = state;
1023 }
1024 parent.ptr->dynamic_precedence += dynamic_precedence;
1025
1026 // Push the parent node onto the stack, along with any extra tokens that
1027 // were previously on top of the stack.
1028 ts_stack_push(self->stack, slice_version, ts_subtree_from_mut(parent), false, next_state);
1029 for (uint32_t j = 0; j < self->trailing_extras.size; j++) {
1030 ts_stack_push(self->stack, slice_version, *array_get(&self->trailing_extras, j), false, next_state);
1031 }
1032
1033 for (StackVersion j = 0; j < slice_version; j++) {
1034 if (j == version) continue;
1035 if (ts_stack_merge(self->stack, j, slice_version)) {
1036 removed_version_count++;
1037 break;
1038 }
1039 }
1040 }
1041
1042 // Return the first new stack version that was created.
1043 return ts_stack_version_count(self->stack) > initial_version_count
1044 ? initial_version_count
1045 : STACK_VERSION_NONE;
1046 }
1047
1048 static void ts_parser__accept(
1049 TSParser *self,
1050 StackVersion version,
1051 Subtree lookahead
1052 ) {
1053 ts_assert(ts_subtree_is_eof(lookahead));
1054 ts_stack_push(self->stack, version, lookahead, false, 1);
1055
1056 StackSliceArray pop = ts_stack_pop_all(self->stack, version);
1057 for (uint32_t i = 0; i < pop.size; i++) {
1058 SubtreeArray trees = array_get(&pop, i)->subtrees;
1059
1060 Subtree root = NULL_SUBTREE;
1061 for (uint32_t j = trees.size - 1; j + 1 > 0; j--) {
1062 Subtree tree = *array_get(&trees, j);
1063 if (!ts_subtree_extra(tree)) {
1064 ts_assert(!tree.data.is_inline);
1065 uint32_t child_count = ts_subtree_child_count(tree);
1066 const Subtree *children = ts_subtree_children(tree);
1067 for (uint32_t k = 0; k < child_count; k++) {
1068 ts_subtree_retain(children[k]);
1069 }
1070 array_splice(&trees, j, 1, child_count, children);
1071 root = ts_subtree_from_mut(ts_subtree_new_node(
1072 ts_subtree_symbol(tree),
1073 &trees,
1074 tree.ptr->production_id,
1075 self->language
1076 ));
1077 ts_subtree_release(&self->tree_pool, tree);
1078 break;
1079 }
1080 }
1081
1082 ts_assert(root.ptr);
1083 self->accept_count++;
1084
1085 if (self->finished_tree.ptr) {
1086 if (ts_parser__select_tree(self, self->finished_tree, root)) {
1087 ts_subtree_release(&self->tree_pool, self->finished_tree);
1088 self->finished_tree = root;
1089 } else {
1090 ts_subtree_release(&self->tree_pool, root);
1091 }
1092 } else {
1093 self->finished_tree = root;
1094 }
1095 }
1096
1097 ts_stack_remove_version(self->stack, array_get(&pop, 0)->version);
1098 ts_stack_halt(self->stack, version);
1099 }
1100
1101 static bool ts_parser__do_all_potential_reductions(
1102 TSParser *self,
1103 StackVersion starting_version,
1104 TSSymbol lookahead_symbol
1105 ) {
1106 uint32_t initial_version_count = ts_stack_version_count(self->stack);
1107
1108 bool can_shift_lookahead_symbol = false;
1109 StackVersion version = starting_version;
1110 for (unsigned i = 0; true; i++) {
1111 uint32_t version_count = ts_stack_version_count(self->stack);
1112 if (version >= version_count) break;
1113
1114 bool merged = false;
1115 for (StackVersion j = initial_version_count; j < version; j++) {
1116 if (ts_stack_merge(self->stack, j, version)) {
1117 merged = true;
1118 break;
1119 }
1120 }
1121 if (merged) continue;
1122
1123 TSStateId state = ts_stack_state(self->stack, version);
1124 bool has_shift_action = false;
1125 array_clear(&self->reduce_actions);
1126
1127 TSSymbol first_symbol, end_symbol;
1128 if (lookahead_symbol != 0) {
1129 first_symbol = lookahead_symbol;
1130 end_symbol = lookahead_symbol + 1;
1131 } else {
1132 first_symbol = 1;
1133 end_symbol = self->language->token_count;
1134 }
1135
1136 for (TSSymbol symbol = first_symbol; symbol < end_symbol; symbol++) {
1137 TableEntry entry;
1138 ts_language_table_entry(self->language, state, symbol, &entry);
1139 for (uint32_t j = 0; j < entry.action_count; j++) {
1140 TSParseAction action = entry.actions[j];
1141 switch (action.type) {
1142 case TSParseActionTypeShift:
1143 case TSParseActionTypeRecover:
1144 if (!action.shift.extra && !action.shift.repetition) has_shift_action = true;
1145 break;
1146 case TSParseActionTypeReduce:
1147 if (action.reduce.child_count > 0)
1148 ts_reduce_action_set_add(&self->reduce_actions, (ReduceAction) {
1149 .symbol = action.reduce.symbol,
1150 .count = action.reduce.child_count,
1151 .dynamic_precedence = action.reduce.dynamic_precedence,
1152 .production_id = action.reduce.production_id,
1153 });
1154 break;
1155 default:
1156 break;
1157 }
1158 }
1159 }
1160
1161 StackVersion reduction_version = STACK_VERSION_NONE;
1162 for (uint32_t j = 0; j < self->reduce_actions.size; j++) {
1163 ReduceAction action = *array_get(&self->reduce_actions, j);
1164
1165 reduction_version = ts_parser__reduce(
1166 self, version, action.symbol, action.count,
1167 action.dynamic_precedence, action.production_id,
1168 true, false
1169 );
1170 }
1171
1172 if (has_shift_action) {
1173 can_shift_lookahead_symbol = true;
1174 } else if (reduction_version != STACK_VERSION_NONE && i < MAX_VERSION_COUNT) {
1175 ts_stack_renumber_version(self->stack, reduction_version, version);
1176 continue;
1177 } else if (lookahead_symbol != 0) {
1178 ts_stack_remove_version(self->stack, version);
1179 }
1180
1181 if (version == starting_version) {
1182 version = version_count;
1183 } else {
1184 version++;
1185 }
1186 }
1187
1188 return can_shift_lookahead_symbol;
1189 }
1190
1191 static bool ts_parser__recover_to_state(
1192 TSParser *self,
1193 StackVersion version,
1194 unsigned depth,
1195 TSStateId goal_state
1196 ) {
1197 StackSliceArray pop = ts_stack_pop_count(self->stack, version, depth);
1198 StackVersion previous_version = STACK_VERSION_NONE;
1199
1200 for (unsigned i = 0; i < pop.size; i++) {
1201 StackSlice slice = *array_get(&pop, i);
1202
1203 if (slice.version == previous_version) {
1204 ts_subtree_array_delete(&self->tree_pool, &slice.subtrees);
1205 array_erase(&pop, i--);
1206 continue;
1207 }
1208
1209 if (ts_stack_state(self->stack, slice.version) != goal_state) {
1210 ts_stack_halt(self->stack, slice.version);
1211 ts_subtree_array_delete(&self->tree_pool, &slice.subtrees);
1212 array_erase(&pop, i--);
1213 continue;
1214 }
1215
1216 SubtreeArray error_trees = ts_stack_pop_error(self->stack, slice.version);
1217 if (error_trees.size > 0) {
1218 ts_assert(error_trees.size == 1);
1219 Subtree error_tree = *array_get(&error_trees, 0);
1220 uint32_t error_child_count = ts_subtree_child_count(error_tree);
1221 if (error_child_count > 0) {
1222 array_splice(&slice.subtrees, 0, 0, error_child_count, ts_subtree_children(error_tree));
1223 for (unsigned j = 0; j < error_child_count; j++) {
1224 ts_subtree_retain(*array_get(&slice.subtrees, j));
1225 }
1226 }
1227 ts_subtree_array_delete(&self->tree_pool, &error_trees);
1228 }
1229
1230 ts_subtree_array_remove_trailing_extras(&slice.subtrees, &self->trailing_extras);
1231
1232 if (slice.subtrees.size > 0) {
1233 Subtree error = ts_subtree_new_error_node(&slice.subtrees, true, self->language);
1234 ts_stack_push(self->stack, slice.version, error, false, goal_state);
1235 } else {
1236 array_delete(&slice.subtrees);
1237 }
1238
1239 for (unsigned j = 0; j < self->trailing_extras.size; j++) {
1240 Subtree tree = *array_get(&self->trailing_extras, j);
1241 ts_stack_push(self->stack, slice.version, tree, false, goal_state);
1242 }
1243
1244 previous_version = slice.version;
1245 }
1246
1247 return previous_version != STACK_VERSION_NONE;
1248 }
1249
1250 static void ts_parser__recover(
1251 TSParser *self,
1252 StackVersion version,
1253 Subtree lookahead
1254 ) {
1255 bool did_recover = false;
1256 unsigned previous_version_count = ts_stack_version_count(self->stack);
1257 Length position = ts_stack_position(self->stack, version);
1258 StackSummary *summary = ts_stack_get_summary(self->stack, version);
1259 unsigned node_count_since_error = ts_stack_node_count_since_error(self->stack, version);
1260 unsigned current_error_cost = ts_stack_error_cost(self->stack, version);
1261
1262 // When the parser is in the error state, there are two strategies for recovering with a
1263 // given lookahead token:
1264 // 1. Find a previous state on the stack in which that lookahead token would be valid. Then,
1265 // create a new stack version that is in that state again. This entails popping all of the
1266 // subtrees that have been pushed onto the stack since that previous state, and wrapping
1267 // them in an ERROR node.
1268 // 2. Wrap the lookahead token in an ERROR node, push that ERROR node onto the stack, and
1269 // move on to the next lookahead token, remaining in the error state.
1270 //
1271 // First, try the strategy 1. Upon entering the error state, the parser recorded a summary
1272 // of the previous parse states and their depths. Look at each state in the summary, to see
1273 // if the current lookahead token would be valid in that state.
1274 if (summary && !ts_subtree_is_error(lookahead)) {
1275 for (unsigned i = 0; i < summary->size; i++) {
1276 StackSummaryEntry entry = *array_get(summary, i);
1277
1278 if (entry.state == ERROR_STATE) continue;
1279 if (entry.position.bytes == position.bytes) continue;
1280 unsigned depth = entry.depth;
1281 if (node_count_since_error > 0) depth++;
1282
1283 // Do not recover in ways that create redundant stack versions.
1284 bool would_merge = false;
1285 for (unsigned j = 0; j < previous_version_count; j++) {
1286 if (
1287 ts_stack_state(self->stack, j) == entry.state &&
1288 ts_stack_position(self->stack, j).bytes == position.bytes
1289 ) {
1290 would_merge = true;
1291 break;
1292 }
1293 }
1294 if (would_merge) continue;
1295
1296 // Do not recover if the result would clearly be worse than some existing stack version.
1297 unsigned new_cost =
1298 current_error_cost +
1299 entry.depth * ERROR_COST_PER_SKIPPED_TREE +
1300 (position.bytes - entry.position.bytes) * ERROR_COST_PER_SKIPPED_CHAR +
1301 (position.extent.row - entry.position.extent.row) * ERROR_COST_PER_SKIPPED_LINE;
1302 if (ts_parser__better_version_exists(self, version, false, new_cost)) break;
1303
1304 // If the current lookahead token is valid in some previous state, recover to that state.
1305 // Then stop looking for further recoveries.
1306 if (ts_language_has_actions(self->language, entry.state, ts_subtree_symbol(lookahead))) {
1307 if (ts_parser__recover_to_state(self, version, depth, entry.state)) {
1308 did_recover = true;
1309 LOG("recover_to_previous state:%u, depth:%u", entry.state, depth);
1310 LOG_STACK();
1311 break;
1312 }
1313 }
1314 }
1315 }
1316
1317 // In the process of attempting to recover, some stack versions may have been created
1318 // and subsequently halted. Remove those versions.
1319 for (unsigned i = previous_version_count; i < ts_stack_version_count(self->stack); i++) {
1320 if (!ts_stack_is_active(self->stack, i)) {
1321 LOG("removed paused version:%u", i);
1322 ts_stack_remove_version(self->stack, i--);
1323 LOG_STACK();
1324 }
1325 }
1326
1327 // If the parser is still in the error state at the end of the file, just wrap everything
1328 // in an ERROR node and terminate.
1329 if (ts_subtree_is_eof(lookahead)) {
1330 LOG("recover_eof");
1331 SubtreeArray children = array_new();
1332 Subtree parent = ts_subtree_new_error_node(&children, false, self->language);
1333 ts_stack_push(self->stack, version, parent, false, 1);
1334 ts_parser__accept(self, version, lookahead);
1335 return;
1336 }
1337
1338 // If strategy 1 succeeded, a new stack version will have been created which is able to handle
1339 // the current lookahead token. Now, in addition, try strategy 2 described above: skip the
1340 // current lookahead token by wrapping it in an ERROR node.
1341
1342 // Don't pursue this additional strategy if there are already too many stack versions.
1343 if (did_recover && ts_stack_version_count(self->stack) > MAX_VERSION_COUNT) {
1344 ts_stack_halt(self->stack, version);
1345 ts_subtree_release(&self->tree_pool, lookahead);
1346 return;
1347 }
1348
1349 if (
1350 did_recover &&
1351 ts_subtree_has_external_scanner_state_change(lookahead)
1352 ) {
1353 ts_stack_halt(self->stack, version);
1354 ts_subtree_release(&self->tree_pool, lookahead);
1355 return;
1356 }
1357
1358 // Do not recover if the result would clearly be worse than some existing stack version.
1359 unsigned new_cost =
1360 current_error_cost + ERROR_COST_PER_SKIPPED_TREE +
1361 ts_subtree_total_bytes(lookahead) * ERROR_COST_PER_SKIPPED_CHAR +
1362 ts_subtree_total_size(lookahead).extent.row * ERROR_COST_PER_SKIPPED_LINE;
1363 if (ts_parser__better_version_exists(self, version, false, new_cost)) {
1364 ts_stack_halt(self->stack, version);
1365 ts_subtree_release(&self->tree_pool, lookahead);
1366 return;
1367 }
1368
1369 // If the current lookahead token is an extra token, mark it as extra. This means it won't
1370 // be counted in error cost calculations.
1371 unsigned n;
1372 const TSParseAction *actions = ts_language_actions(self->language, 1, ts_subtree_symbol(lookahead), &n);
1373 if (n > 0 && actions[n - 1].type == TSParseActionTypeShift && actions[n - 1].shift.extra) {
1374 MutableSubtree mutable_lookahead = ts_subtree_make_mut(&self->tree_pool, lookahead);
1375 ts_subtree_set_extra(&mutable_lookahead, true);
1376 lookahead = ts_subtree_from_mut(mutable_lookahead);
1377 }
1378
1379 // Wrap the lookahead token in an ERROR.
1380 LOG("skip_token symbol:%s", TREE_NAME(lookahead));
1381 SubtreeArray children = array_new();
1382 array_reserve(&children, 1);
1383 array_push(&children, lookahead);
1384 MutableSubtree error_repeat = ts_subtree_new_node(
1385 ts_builtin_sym_error_repeat,
1386 &children,
1387 0,
1388 self->language
1389 );
1390
1391 // If other tokens have already been skipped, so there is already an ERROR at the top of the
1392 // stack, then pop that ERROR off the stack and wrap the two ERRORs together into one larger
1393 // ERROR.
1394 if (node_count_since_error > 0) {
1395 StackSliceArray pop = ts_stack_pop_count(self->stack, version, 1);
1396
1397 // TODO: Figure out how to make this condition occur.
1398 // See https://github.com/atom/atom/issues/18450#issuecomment-439579778
1399 // If multiple stack versions have merged at this point, just pick one of the errors
1400 // arbitrarily and discard the rest.
1401 if (pop.size > 1) {
1402 for (unsigned i = 1; i < pop.size; i++) {
1403 ts_subtree_array_delete(&self->tree_pool, &array_get(&pop, i)->subtrees);
1404 }
1405 while (ts_stack_version_count(self->stack) > array_get(&pop, 0)->version + 1) {
1406 ts_stack_remove_version(self->stack, array_get(&pop, 0)->version + 1);
1407 }
1408 }
1409
1410 ts_stack_renumber_version(self->stack, array_get(&pop, 0)->version, version);
1411 array_push(&array_get(&pop, 0)->subtrees, ts_subtree_from_mut(error_repeat));
1412 error_repeat = ts_subtree_new_node(
1413 ts_builtin_sym_error_repeat,
1414 &array_get(&pop, 0)->subtrees,
1415 0,
1416 self->language
1417 );
1418 }
1419
1420 // Push the new ERROR onto the stack.
1421 ts_stack_push(self->stack, version, ts_subtree_from_mut(error_repeat), false, ERROR_STATE);
1422 if (ts_subtree_has_external_tokens(lookahead)) {
1423 ts_stack_set_last_external_token(
1424 self->stack, version, ts_subtree_last_external_token(lookahead)
1425 );
1426 }
1427
1428 bool has_error = true;
1429 for (unsigned i = 0; i < ts_stack_version_count(self->stack); i++) {
1430 ErrorStatus status = ts_parser__version_status(self, i);
1431 if (!status.is_in_error) {
1432 has_error = false;
1433 break;
1434 }
1435 }
1436 self->has_error = has_error;
1437 }
1438
1439 static void ts_parser__handle_error(
1440 TSParser *self,
1441 StackVersion version,
1442 Subtree lookahead
1443 ) {
1444 uint32_t previous_version_count = ts_stack_version_count(self->stack);
1445
1446 // Perform any reductions that can happen in this state, regardless of the lookahead. After
1447 // skipping one or more invalid tokens, the parser might find a token that would have allowed
1448 // a reduction to take place.
1449 ts_parser__do_all_potential_reductions(self, version, 0);
1450 uint32_t version_count = ts_stack_version_count(self->stack);
1451 Length position = ts_stack_position(self->stack, version);
1452
1453 // Push a discontinuity onto the stack. Merge all of the stack versions that
1454 // were created in the previous step.
1455 bool did_insert_missing_token = false;
1456 for (StackVersion v = version; v < version_count;) {
1457 if (!did_insert_missing_token) {
1458 TSStateId state = ts_stack_state(self->stack, v);
1459 for (
1460 TSSymbol missing_symbol = 1;
1461 missing_symbol < (uint16_t)self->language->token_count;
1462 missing_symbol++
1463 ) {
1464 TSStateId state_after_missing_symbol = ts_language_next_state(
1465 self->language, state, missing_symbol
1466 );
1467 if (state_after_missing_symbol == 0 || state_after_missing_symbol == state) {
1468 continue;
1469 }
1470
1471 if (ts_language_has_reduce_action(
1472 self->language,
1473 state_after_missing_symbol,
1474 ts_subtree_leaf_symbol(lookahead)
1475 )) {
1476 // In case the parser is currently outside of any included range, the lexer will
1477 // snap to the beginning of the next included range. The missing token's padding
1478 // must be assigned to position it within the next included range.
1479 ts_lexer_reset(&self->lexer, position);
1480 ts_lexer_mark_end(&self->lexer);
1481 Length padding = length_sub(self->lexer.token_end_position, position);
1482 uint32_t lookahead_bytes = ts_subtree_total_bytes(lookahead) + ts_subtree_lookahead_bytes(lookahead);
1483
1484 StackVersion version_with_missing_tree = ts_stack_copy_version(self->stack, v);
1485 Subtree missing_tree = ts_subtree_new_missing_leaf(
1486 &self->tree_pool, missing_symbol,
1487 padding, lookahead_bytes,
1488 self->language
1489 );
1490 ts_stack_push(
1491 self->stack, version_with_missing_tree,
1492 missing_tree, false,
1493 state_after_missing_symbol
1494 );
1495
1496 if (ts_parser__do_all_potential_reductions(
1497 self, version_with_missing_tree,
1498 ts_subtree_leaf_symbol(lookahead)
1499 )) {
1500 LOG(
1501 "recover_with_missing symbol:%s, state:%u",
1502 SYM_NAME(missing_symbol),
1503 ts_stack_state(self->stack, version_with_missing_tree)
1504 );
1505 did_insert_missing_token = true;
1506 break;
1507 }
1508 }
1509 }
1510 }
1511
1512 ts_stack_push(self->stack, v, NULL_SUBTREE, false, ERROR_STATE);
1513 v = (v == version) ? previous_version_count : v + 1;
1514 }
1515
1516 for (unsigned i = previous_version_count; i < version_count; i++) {
1517 bool did_merge = ts_stack_merge(self->stack, version, previous_version_count);
1518 ts_assert(did_merge);
1519 }
1520
1521 ts_stack_record_summary(self->stack, version, MAX_SUMMARY_DEPTH);
1522
1523 // Begin recovery with the current lookahead node, rather than waiting for the
1524 // next turn of the parse loop. This ensures that the tree accounts for the
1525 // current lookahead token's "lookahead bytes" value, which describes how far
1526 // the lexer needed to look ahead beyond the content of the token in order to
1527 // recognize it.
1528 if (ts_subtree_child_count(lookahead) > 0) {
1529 ts_parser__breakdown_lookahead(self, &lookahead, ERROR_STATE, &self->reusable_node);
1530 }
1531 ts_parser__recover(self, version, lookahead);
1532
1533 LOG_STACK();
1534 }
1535
1536 static bool ts_parser__check_progress(TSParser *self, Subtree *lookahead, const uint32_t *position, unsigned operations) {
1537 self->operation_count += operations;
1538 if (self->operation_count >= OP_COUNT_PER_PARSER_CALLBACK_CHECK) {
1539 self->operation_count = 0;
1540 }
1541 if (position != NULL) {
1542 self->parse_state.current_byte_offset = *position;
1543 self->parse_state.has_error = self->has_error;
1544 }
1545 if (
1546 self->operation_count == 0 &&
1547 (self->parse_options.progress_callback && self->parse_options.progress_callback(&self->parse_state))
1548 ) {
1549 if (lookahead && lookahead->ptr) {
1550 ts_subtree_release(&self->tree_pool, *lookahead);
1551 }
1552 return false;
1553 }
1554 return true;
1555 }
1556
1557 static bool ts_parser__advance(
1558 TSParser *self,
1559 StackVersion version,
1560 bool allow_node_reuse
1561 ) {
1562 TSStateId state = ts_stack_state(self->stack, version);
1563 uint32_t position = ts_stack_position(self->stack, version).bytes;
1564 Subtree last_external_token = ts_stack_last_external_token(self->stack, version);
1565
1566 bool did_reuse = true;
1567 Subtree lookahead = NULL_SUBTREE;
1568 TableEntry table_entry = {.action_count = 0};
1569
1570 // If possible, reuse a node from the previous syntax tree.
1571 if (allow_node_reuse) {
1572 lookahead = ts_parser__reuse_node(
1573 self, version, &state, position, last_external_token, &table_entry
1574 );
1575 }
1576
1577 // If no node from the previous syntax tree could be reused, then try to
1578 // reuse the token previously returned by the lexer.
1579 if (!lookahead.ptr) {
1580 did_reuse = false;
1581 lookahead = ts_parser__get_cached_token(
1582 self, state, position, last_external_token, &table_entry
1583 );
1584 }
1585
1586 bool needs_lex = !lookahead.ptr;
1587 for (;;) {
1588 // Otherwise, re-run the lexer.
1589 if (needs_lex) {
1590 needs_lex = false;
1591 lookahead = ts_parser__lex(self, version, state);
1592 if (self->has_scanner_error) return false;
1593
1594 if (lookahead.ptr) {
1595 ts_parser__set_cached_token(self, position, last_external_token, lookahead);
1596 ts_language_table_entry(self->language, state, ts_subtree_symbol(lookahead), &table_entry);
1597 }
1598
1599 // When parsing a non-terminal extra, a null lookahead indicates the
1600 // end of the rule. The reduction is stored in the EOF table entry.
1601 // After the reduction, the lexer needs to be run again.
1602 else {
1603 ts_language_table_entry(self->language, state, ts_builtin_sym_end, &table_entry);
1604 }
1605 }
1606
1607 // If a progress callback was provided, then check every
1608 // time a fixed number of parse actions has been processed.
1609 if (!ts_parser__check_progress(self, &lookahead, &position, 1)) {
1610 return false;
1611 }
1612
1613 // Process each parse action for the current lookahead token in
1614 // the current state. If there are multiple actions, then this is
1615 // an ambiguous state. REDUCE actions always create a new stack
1616 // version, whereas SHIFT actions update the existing stack version
1617 // and terminate this loop.
1618 bool did_reduce = false;
1619 StackVersion last_reduction_version = STACK_VERSION_NONE;
1620 for (uint32_t i = 0; i < table_entry.action_count; i++) {
1621 TSParseAction action = table_entry.actions[i];
1622
1623 switch (action.type) {
1624 case TSParseActionTypeShift: {
1625 if (action.shift.repetition) break;
1626 TSStateId next_state;
1627 if (action.shift.extra) {
1628 next_state = state;
1629 LOG("shift_extra");
1630 } else {
1631 next_state = action.shift.state;
1632 LOG("shift state:%u", next_state);
1633 }
1634
1635 if (ts_subtree_child_count(lookahead) > 0) {
1636 ts_parser__breakdown_lookahead(self, &lookahead, state, &self->reusable_node);
1637 next_state = ts_language_next_state(self->language, state, ts_subtree_symbol(lookahead));
1638 }
1639
1640 ts_parser__shift(self, version, next_state, lookahead, action.shift.extra);
1641 if (did_reuse) reusable_node_advance(&self->reusable_node);
1642 return true;
1643 }
1644
1645 case TSParseActionTypeReduce: {
1646 bool is_fragile = table_entry.action_count > 1;
1647 bool end_of_non_terminal_extra = lookahead.ptr == NULL;
1648 LOG("reduce sym:%s, child_count:%u", SYM_NAME(action.reduce.symbol), action.reduce.child_count);
1649 StackVersion reduction_version = ts_parser__reduce(
1650 self, version, action.reduce.symbol, action.reduce.child_count,
1651 action.reduce.dynamic_precedence, action.reduce.production_id,
1652 is_fragile, end_of_non_terminal_extra
1653 );
1654 did_reduce = true;
1655 if (reduction_version != STACK_VERSION_NONE) {
1656 last_reduction_version = reduction_version;
1657 }
1658 break;
1659 }
1660
1661 case TSParseActionTypeAccept: {
1662 LOG("accept");
1663 ts_parser__accept(self, version, lookahead);
1664 return true;
1665 }
1666
1667 case TSParseActionTypeRecover: {
1668 if (ts_subtree_child_count(lookahead) > 0) {
1669 ts_parser__breakdown_lookahead(self, &lookahead, ERROR_STATE, &self->reusable_node);
1670 }
1671
1672 ts_parser__recover(self, version, lookahead);
1673 if (did_reuse) reusable_node_advance(&self->reusable_node);
1674 return true;
1675 }
1676 }
1677 }
1678
1679 // If a reduction was performed, then replace the current stack version
1680 // with one of the stack versions created by a reduction, and continue
1681 // processing this version of the stack with the same lookahead symbol.
1682 if (last_reduction_version != STACK_VERSION_NONE) {
1683 ts_stack_renumber_version(self->stack, last_reduction_version, version);
1684 LOG_STACK();
1685 state = ts_stack_state(self->stack, version);
1686
1687 // At the end of a non-terminal extra rule, the lexer will return a
1688 // null subtree, because the parser needs to perform a fixed reduction
1689 // regardless of the lookahead node. After performing that reduction,
1690 // (and completing the non-terminal extra rule) run the lexer again based
1691 // on the current parse state.
1692 if (!lookahead.ptr) {
1693 needs_lex = true;
1694 } else {
1695 ts_language_table_entry(
1696 self->language,
1697 state,
1698 ts_subtree_leaf_symbol(lookahead),
1699 &table_entry
1700 );
1701 }
1702
1703 continue;
1704 }
1705
1706 // A reduction was performed, but was merged into an existing stack version.
1707 // This version can be discarded.
1708 if (did_reduce) {
1709 if (lookahead.ptr) {
1710 ts_subtree_release(&self->tree_pool, lookahead);
1711 }
1712 ts_stack_halt(self->stack, version);
1713 return true;
1714 }
1715
1716 // If the current lookahead token is a keyword that is not valid, but the
1717 // default word token *is* valid, then treat the lookahead token as the word
1718 // token instead.
1719 if (
1720 ts_subtree_is_keyword(lookahead) &&
1721 ts_subtree_symbol(lookahead) != self->language->keyword_capture_token &&
1722 !ts_language_is_reserved_word(self->language, state, ts_subtree_symbol(lookahead))
1723 ) {
1724 ts_language_table_entry(
1725 self->language,
1726 state,
1727 self->language->keyword_capture_token,
1728 &table_entry
1729 );
1730 if (table_entry.action_count > 0) {
1731 LOG(
1732 "switch from_keyword:%s, to_word_token:%s",
1733 TREE_NAME(lookahead),
1734 SYM_NAME(self->language->keyword_capture_token)
1735 );
1736
1737 MutableSubtree mutable_lookahead = ts_subtree_make_mut(&self->tree_pool, lookahead);
1738 ts_subtree_set_symbol(&mutable_lookahead, self->language->keyword_capture_token, self->language);
1739 lookahead = ts_subtree_from_mut(mutable_lookahead);
1740 continue;
1741 }
1742 }
1743
1744 // If the current lookahead token is not valid and the previous subtree on
1745 // the stack was reused from an old tree, then it wasn't actually valid to
1746 // reuse that previous subtree. Remove it from the stack, and in its place,
1747 // push each of its children. Then try again to process the current lookahead.
1748 if (ts_parser__breakdown_top_of_stack(self, version)) {
1749 state = ts_stack_state(self->stack, version);
1750 ts_subtree_release(&self->tree_pool, lookahead);
1751 needs_lex = true;
1752 continue;
1753 }
1754
1755 // Otherwise, there is definitely an error in this version of the parse stack.
1756 // Mark this version as paused and continue processing any other stack
1757 // versions that exist. If some other version advances successfully, then
1758 // this version can simply be removed. But if all versions end up paused,
1759 // then error recovery is needed.
1760 LOG("detect_error lookahead:%s", TREE_NAME(lookahead));
1761 ts_stack_pause(self->stack, version, lookahead);
1762 return true;
1763 }
1764 }
1765
1766 static unsigned ts_parser__condense_stack(TSParser *self) {
1767 bool made_changes = false;
1768 unsigned min_error_cost = UINT_MAX;
1769 for (StackVersion i = 0; i < ts_stack_version_count(self->stack); i++) {
1770 // Prune any versions that have been marked for removal.
1771 if (ts_stack_is_halted(self->stack, i)) {
1772 ts_stack_remove_version(self->stack, i);
1773 i--;
1774 continue;
1775 }
1776
1777 // Keep track of the minimum error cost of any stack version so
1778 // that it can be returned.
1779 ErrorStatus status_i = ts_parser__version_status(self, i);
1780 if (!status_i.is_in_error && status_i.cost < min_error_cost) {
1781 min_error_cost = status_i.cost;
1782 }
1783
1784 // Examine each pair of stack versions, removing any versions that
1785 // are clearly worse than another version. Ensure that the versions
1786 // are ordered from most promising to least promising.
1787 for (StackVersion j = 0; j < i; j++) {
1788 ErrorStatus status_j = ts_parser__version_status(self, j);
1789
1790 switch (ts_parser__compare_versions(self, status_j, status_i)) {
1791 case ErrorComparisonTakeLeft:
1792 made_changes = true;
1793 ts_stack_remove_version(self->stack, i);
1794 i--;
1795 j = i;
1796 break;
1797
1798 case ErrorComparisonPreferLeft:
1799 case ErrorComparisonNone:
1800 if (ts_stack_merge(self->stack, j, i)) {
1801 made_changes = true;
1802 i--;
1803 j = i;
1804 }
1805 break;
1806
1807 case ErrorComparisonPreferRight:
1808 made_changes = true;
1809 if (ts_stack_merge(self->stack, j, i)) {
1810 i--;
1811 j = i;
1812 } else {
1813 ts_stack_swap_versions(self->stack, i, j);
1814 }
1815 break;
1816
1817 case ErrorComparisonTakeRight:
1818 made_changes = true;
1819 ts_stack_remove_version(self->stack, j);
1820 i--;
1821 j--;
1822 break;
1823 }
1824 }
1825 }
1826
1827 // Enforce a hard upper bound on the number of stack versions by
1828 // discarding the least promising versions.
1829 while (ts_stack_version_count(self->stack) > MAX_VERSION_COUNT) {
1830 ts_stack_remove_version(self->stack, MAX_VERSION_COUNT);
1831 made_changes = true;
1832 }
1833
1834 // If the best-performing stack version is currently paused, or all
1835 // versions are paused, then resume the best paused version and begin
1836 // the error recovery process. Otherwise, remove the paused versions.
1837 if (ts_stack_version_count(self->stack) > 0) {
1838 bool has_unpaused_version = false;
1839 for (StackVersion i = 0, n = ts_stack_version_count(self->stack); i < n; i++) {
1840 if (ts_stack_is_paused(self->stack, i)) {
1841 if (!has_unpaused_version && self->accept_count < MAX_VERSION_COUNT) {
1842 LOG("resume version:%u", i);
1843 min_error_cost = ts_stack_error_cost(self->stack, i);
1844 Subtree lookahead = ts_stack_resume(self->stack, i);
1845 ts_parser__handle_error(self, i, lookahead);
1846 has_unpaused_version = true;
1847 } else {
1848 ts_stack_remove_version(self->stack, i);
1849 made_changes = true;
1850 i--;
1851 n--;
1852 }
1853 } else {
1854 has_unpaused_version = true;
1855 }
1856 }
1857 }
1858
1859 if (made_changes) {
1860 LOG("condense");
1861 LOG_STACK();
1862 }
1863
1864 return min_error_cost;
1865 }
1866
1867 static bool ts_parser__balance_subtree(TSParser *self) {
1868 Subtree finished_tree = self->finished_tree;
1869
1870 // If we haven't canceled balancing in progress before, then we want to clear the tree stack and
1871 // push the initial finished tree onto it. Otherwise, if we're resuming balancing after a
1872 // cancellation, we don't want to clear the tree stack.
1873 if (!self->canceled_balancing) {
1874 array_clear(&self->tree_pool.tree_stack);
1875 if (ts_subtree_child_count(finished_tree) > 0 && finished_tree.ptr->ref_count == 1) {
1876 array_push(&self->tree_pool.tree_stack, ts_subtree_to_mut_unsafe(finished_tree));
1877 }
1878 }
1879
1880 while (self->tree_pool.tree_stack.size > 0) {
1881 if (!ts_parser__check_progress(self, NULL, NULL, 1)) {
1882 return false;
1883 }
1884
1885 MutableSubtree tree = *array_get(&self->tree_pool.tree_stack,
1886 self->tree_pool.tree_stack.size - 1
1887 );
1888
1889 if (tree.ptr->repeat_depth > 0) {
1890 Subtree child1 = ts_subtree_children(tree)[0];
1891 Subtree child2 = ts_subtree_children(tree)[tree.ptr->child_count - 1];
1892 long repeat_delta = (long)ts_subtree_repeat_depth(child1) - (long)ts_subtree_repeat_depth(child2);
1893 if (repeat_delta > 0) {
1894 unsigned n = (unsigned)repeat_delta;
1895
1896 for (unsigned i = n / 2; i > 0; i /= 2) {
1897 ts_subtree_compress(tree, i, self->language, &self->tree_pool.tree_stack);
1898 n -= i;
1899
1900 // We scale the operation count increment in `ts_parser__check_progress` proportionately to the compression
1901 // size since larger values of i take longer to process. Shifting by 4 empirically provides good check
1902 // intervals (e.g. 193 operations when i=3100) to prevent blocking during large compressions.
1903 uint8_t operations = i >> 4 > 0 ? i >> 4 : 1;
1904 if (!ts_parser__check_progress(self, NULL, NULL, operations)) {
1905 return false;
1906 }
1907 }
1908 }
1909 }
1910
1911 (void)array_pop(&self->tree_pool.tree_stack);
1912
1913 for (uint32_t i = 0; i < tree.ptr->child_count; i++) {
1914 Subtree child = ts_subtree_children(tree)[i];
1915 if (ts_subtree_child_count(child) > 0 && child.ptr->ref_count == 1) {
1916 array_push(&self->tree_pool.tree_stack, ts_subtree_to_mut_unsafe(child));
1917 }
1918 }
1919 }
1920
1921 return true;
1922 }
1923
1924 static bool ts_parser_has_outstanding_parse(TSParser *self) {
1925 return (
1926 self->canceled_balancing ||
1927 self->external_scanner_payload ||
1928 ts_stack_state(self->stack, 0) != 1 ||
1929 ts_stack_node_count_since_error(self->stack, 0) != 0
1930 );
1931 }
1932
1933 // Parser - Public
1934
1935 TSParser *ts_parser_new(void) {
1936 TSParser *self = ts_calloc(1, sizeof(TSParser));
1937 ts_lexer_init(&self->lexer);
1938 array_init(&self->reduce_actions);
1939 array_reserve(&self->reduce_actions, 4);
1940 self->tree_pool = ts_subtree_pool_new(32);
1941 self->stack = ts_stack_new(&self->tree_pool);
1942 self->finished_tree = NULL_SUBTREE;
1943 self->reusable_node = reusable_node_new();
1944 self->dot_graph_file = NULL;
1945 self->language = NULL;
1946 self->has_scanner_error = false;
1947 self->has_error = false;
1948 self->canceled_balancing = false;
1949 self->external_scanner_payload = NULL;
1950 self->operation_count = 0;
1951 self->old_tree = NULL_SUBTREE;
1952 self->included_range_differences = (TSRangeArray) array_new();
1953 self->included_range_difference_index = 0;
1954 ts_parser__set_cached_token(self, 0, NULL_SUBTREE, NULL_SUBTREE);
1955 return self;
1956 }
1957
1958 void ts_parser_delete(TSParser *self) {
1959 if (!self) return;
1960
1961 ts_parser_set_language(self, NULL);
1962 ts_stack_delete(self->stack);
1963 if (self->reduce_actions.contents) {
1964 array_delete(&self->reduce_actions);
1965 }
1966 if (self->included_range_differences.contents) {
1967 array_delete(&self->included_range_differences);
1968 }
1969 if (self->old_tree.ptr) {
1970 ts_subtree_release(&self->tree_pool, self->old_tree);
1971 self->old_tree = NULL_SUBTREE;
1972 }
1973 ts_wasm_store_delete(self->wasm_store);
1974 ts_lexer_delete(&self->lexer);
1975 ts_parser__set_cached_token(self, 0, NULL_SUBTREE, NULL_SUBTREE);
1976 ts_subtree_pool_delete(&self->tree_pool);
1977 reusable_node_delete(&self->reusable_node);
1978 array_delete(&self->trailing_extras);
1979 array_delete(&self->trailing_extras2);
1980 array_delete(&self->scratch_trees);
1981 ts_free(self);
1982 }
1983
1984 const TSLanguage *ts_parser_language(const TSParser *self) {
1985 return self->language;
1986 }
1987
1988 bool ts_parser_set_language(TSParser *self, const TSLanguage *language) {
1989 ts_parser_reset(self);
1990 ts_language_delete(self->language);
1991 self->language = NULL;
1992
1993 if (language) {
1994 if (
1995 language->abi_version > TREE_SITTER_LANGUAGE_VERSION ||
1996 language->abi_version < TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION
1997 ) return false;
1998
1999 if (ts_language_is_wasm(language)) {
2000 if (
2001 !self->wasm_store ||
2002 !ts_wasm_store_start(self->wasm_store, &self->lexer.data, language)
2003 ) return false;
2004 }
2005 }
2006
2007 self->language = ts_language_copy(language);
2008 return true;
2009 }
2010
2011 TSLogger ts_parser_logger(const TSParser *self) {
2012 return self->lexer.logger;
2013 }
2014
2015 void ts_parser_set_logger(TSParser *self, TSLogger logger) {
2016 self->lexer.logger = logger;
2017 }
2018
2019 void ts_parser_print_dot_graphs(TSParser *self, int fd) {
2020 if (self->dot_graph_file) {
2021 fclose(self->dot_graph_file);
2022 }
2023
2024 if (fd >= 0) {
2025 #ifdef _WIN32
2026 self->dot_graph_file = _fdopen(fd, "a");
2027 #else
2028 self->dot_graph_file = fdopen(fd, "a");
2029 #endif
2030 } else {
2031 self->dot_graph_file = NULL;
2032 }
2033 }
2034
2035 bool ts_parser_set_included_ranges(
2036 TSParser *self,
2037 const TSRange *ranges,
2038 uint32_t count
2039 ) {
2040 return ts_lexer_set_included_ranges(&self->lexer, ranges, count);
2041 }
2042
2043 const TSRange *ts_parser_included_ranges(const TSParser *self, uint32_t *count) {
2044 return ts_lexer_included_ranges(&self->lexer, count);
2045 }
2046
2047 void ts_parser_reset(TSParser *self) {
2048 ts_parser__external_scanner_destroy(self);
2049 if (self->wasm_store) {
2050 ts_wasm_store_reset(self->wasm_store);
2051 }
2052
2053 if (self->old_tree.ptr) {
2054 ts_subtree_release(&self->tree_pool, self->old_tree);
2055 self->old_tree = NULL_SUBTREE;
2056 }
2057
2058 reusable_node_clear(&self->reusable_node);
2059 ts_lexer_reset(&self->lexer, length_zero());
2060 ts_stack_clear(self->stack);
2061 ts_parser__set_cached_token(self, 0, NULL_SUBTREE, NULL_SUBTREE);
2062 if (self->finished_tree.ptr) {
2063 ts_subtree_release(&self->tree_pool, self->finished_tree);
2064 self->finished_tree = NULL_SUBTREE;
2065 }
2066 self->accept_count = 0;
2067 self->has_scanner_error = false;
2068 self->has_error = false;
2069 self->canceled_balancing = false;
2070 self->parse_options = (TSParseOptions) {0};
2071 self->parse_state = (TSParseState) {0};
2072 }
2073
2074 TSTree *ts_parser_parse(
2075 TSParser *self,
2076 const TSTree *old_tree,
2077 TSInput input
2078 ) {
2079 TSTree *result = NULL;
2080 if (!self->language || !input.read) return NULL;
2081
2082 if (ts_language_is_wasm(self->language)) {
2083 if (!self->wasm_store) return NULL;
2084 ts_wasm_store_start(self->wasm_store, &self->lexer.data, self->language);
2085 }
2086
2087 ts_lexer_set_input(&self->lexer, input);
2088 array_clear(&self->included_range_differences);
2089 self->included_range_difference_index = 0;
2090
2091 self->operation_count = 0;
2092
2093 if (ts_parser_has_outstanding_parse(self)) {
2094 LOG("resume_parsing");
2095 if (self->canceled_balancing) goto balance;
2096 } else {
2097 ts_parser__external_scanner_create(self);
2098 if (self->has_scanner_error) goto exit;
2099
2100 if (old_tree) {
2101 ts_subtree_retain(old_tree->root);
2102 self->old_tree = old_tree->root;
2103 ts_range_array_get_changed_ranges(
2104 old_tree->included_ranges, old_tree->included_range_count,
2105 self->lexer.included_ranges, self->lexer.included_range_count,
2106 &self->included_range_differences
2107 );
2108 reusable_node_reset(&self->reusable_node, old_tree->root);
2109 LOG("parse_after_edit");
2110 LOG_TREE(self->old_tree);
2111 for (unsigned i = 0; i < self->included_range_differences.size; i++) {
2112 TSRange *range = array_get(&self->included_range_differences, i);
2113 LOG("different_included_range %u - %u", range->start_byte, range->end_byte);
2114 }
2115 } else {
2116 reusable_node_clear(&self->reusable_node);
2117 LOG("new_parse");
2118 }
2119 }
2120
2121 uint32_t position = 0, last_position = 0, version_count = 0;
2122 do {
2123 for (
2124 StackVersion version = 0;
2125 version_count = ts_stack_version_count(self->stack),
2126 version < version_count;
2127 version++
2128 ) {
2129 bool allow_node_reuse = version_count == 1;
2130 while (ts_stack_is_active(self->stack, version)) {
2131 LOG(
2132 "process version:%u, version_count:%u, state:%d, row:%u, col:%u",
2133 version,
2134 ts_stack_version_count(self->stack),
2135 ts_stack_state(self->stack, version),
2136 ts_stack_position(self->stack, version).extent.row,
2137 ts_stack_position(self->stack, version).extent.column
2138 );
2139
2140 if (!ts_parser__advance(self, version, allow_node_reuse)) {
2141 if (self->has_scanner_error) goto exit;
2142 return NULL;
2143 }
2144
2145 LOG_STACK();
2146
2147 position = ts_stack_position(self->stack, version).bytes;
2148 if (position > last_position || (version > 0 && position == last_position)) {
2149 last_position = position;
2150 break;
2151 }
2152 }
2153 }
2154
2155 // After advancing each version of the stack, re-sort the versions by their cost,
2156 // removing any versions that are no longer worth pursuing.
2157 unsigned min_error_cost = ts_parser__condense_stack(self);
2158
2159 // If there's already a finished parse tree that's better than any in-progress version,
2160 // then terminate parsing. Clear the parse stack to remove any extra references to subtrees
2161 // within the finished tree, ensuring that these subtrees can be safely mutated in-place
2162 // for rebalancing.
2163 if (self->finished_tree.ptr && ts_subtree_error_cost(self->finished_tree) < min_error_cost) {
2164 ts_stack_clear(self->stack);
2165 break;
2166 }
2167
2168 while (self->included_range_difference_index < self->included_range_differences.size) {
2169 TSRange *range = array_get(&self->included_range_differences, self->included_range_difference_index);
2170 if (range->end_byte <= position) {
2171 self->included_range_difference_index++;
2172 } else {
2173 break;
2174 }
2175 }
2176 } while (version_count != 0);
2177
2178 balance:
2179 ts_assert(self->finished_tree.ptr);
2180 if (!ts_parser__balance_subtree(self)) {
2181 self->canceled_balancing = true;
2182 return NULL;
2183 }
2184 self->canceled_balancing = false;
2185 LOG("done");
2186 LOG_TREE(self->finished_tree);
2187
2188 result = ts_tree_new(
2189 self->finished_tree,
2190 self->language,
2191 self->lexer.included_ranges,
2192 self->lexer.included_range_count
2193 );
2194 self->finished_tree = NULL_SUBTREE;
2195
2196 exit:
2197 ts_parser_reset(self);
2198 return result;
2199 }
2200
2201 TSTree *ts_parser_parse_with_options(
2202 TSParser *self,
2203 const TSTree *old_tree,
2204 TSInput input,
2205 TSParseOptions parse_options
2206 ) {
2207 self->parse_options = parse_options;
2208 self->parse_state.payload = parse_options.payload;
2209 TSTree *result = ts_parser_parse(self, old_tree, input);
2210 // Reset parser options before further parse calls.
2211 self->parse_options = (TSParseOptions) {0};
2212 return result;
2213 }
2214
2215 TSTree *ts_parser_parse_string(
2216 TSParser *self,
2217 const TSTree *old_tree,
2218 const char *string,
2219 uint32_t length
2220 ) {
2221 return ts_parser_parse_string_encoding(self, old_tree, string, length, TSInputEncodingUTF8);
2222 }
2223
2224 TSTree *ts_parser_parse_string_encoding(
2225 TSParser *self,
2226 const TSTree *old_tree,
2227 const char *string,
2228 uint32_t length,
2229 TSInputEncoding encoding
2230 ) {
2231 TSStringInput input = {string, length};
2232 return ts_parser_parse(self, old_tree, (TSInput) {
2233 &input,
2234 ts_string_input_read,
2235 encoding,
2236 NULL,
2237 });
2238 }
2239
2240 void ts_parser_set_wasm_store(TSParser *self, TSWasmStore *store) {
2241 if (self->language && ts_language_is_wasm(self->language)) {
2242 // Copy the assigned language into the new store.
2243 const TSLanguage *copy = ts_language_copy(self->language);
2244 ts_parser_set_language(self, copy);
2245 ts_language_delete(copy);
2246 }
2247
2248 ts_wasm_store_delete(self->wasm_store);
2249 self->wasm_store = store;
2250 }
2251
2252 TSWasmStore *ts_parser_take_wasm_store(TSParser *self) {
2253 if (self->language && ts_language_is_wasm(self->language)) {
2254 ts_parser_set_language(self, NULL);
2255 }
2256
2257 TSWasmStore *result = self->wasm_store;
2258 self->wasm_store = NULL;
2259 return result;
2260 }
2261
2262 #undef LOG