Debian Codegraph @

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

raw
1 /*
2 * On NetBSD, defining standard requirements like this removes symbols
3 * from the namespace; however, we need non-standard symbols for
4 * endian.h.
5 */
6 #if defined(__NetBSD__) && defined(_POSIX_C_SOURCE)
7 #undef _POSIX_C_SOURCE
8 #endif
9
10 #include "tree_sitter/api.h"
11 #include "./alloc.h"
12 #include "./array.h"
13 #include "./language.h"
14 #include "./point.h"
15 #include "./tree_cursor.h"
16 #include "./unicode.h"
17 #include <wctype.h>
18
19 // #define DEBUG_ANALYZE_QUERY
20 // #define DEBUG_EXECUTE_QUERY
21
22 #define MAX_STEP_CAPTURE_COUNT 3
23 #define MAX_NEGATED_FIELD_COUNT 8
24 #define MAX_STATE_PREDECESSOR_COUNT 256
25 #define MAX_ANALYSIS_STATE_DEPTH 8
26 #define MAX_ANALYSIS_ITERATION_COUNT 256
27
28 /*
29 * Stream - A sequence of unicode characters derived from a UTF8 string.
30 * This struct is used in parsing queries from S-expressions.
31 */
32 typedef struct {
33 const char *input;
34 const char *start;
35 const char *end;
36 int32_t next;
37 uint8_t next_size;
38 } Stream;
39
40 /*
41 * QueryStep - A step in the process of matching a query. Each node within
42 * a query S-expression corresponds to one of these steps. An entire pattern
43 * is represented as a sequence of these steps. The basic properties of a
44 * node are represented by these fields:
45 * - `symbol` - The grammar symbol to match. A zero value represents the
46 * wildcard symbol, '_'.
47 * - `field` - The field name to match. A zero value means that a field name
48 * was not specified.
49 * - `capture_ids` - An array of integers representing the names of captures
50 * associated with this node in the pattern, terminated by a `NONE` value.
51 * - `depth` - The depth where this node occurs in the pattern. The root node
52 * of the pattern has depth zero.
53 * - `negated_field_list_id` - An id representing a set of fields that must
54 * not be present on a node matching this step.
55 *
56 * Steps have some additional fields in order to handle the `.` (or "anchor") operator,
57 * which forbids additional child nodes:
58 * - `is_immediate` - Indicates that the node matching this step cannot be preceded
59 * by other sibling nodes that weren't specified in the pattern.
60 * - `is_last_child` - Indicates that the node matching this step cannot have any
61 * subsequent named siblings.
62 *
63 * For simple patterns, steps are matched in sequential order. But in order to
64 * handle alternative/repeated/optional sub-patterns, query steps are not always
65 * structured as a linear sequence; they sometimes need to split and merge. This
66 * is done using the following fields:
67 * - `alternative_index` - The index of a different query step that serves as
68 * an alternative to this step. A `NONE` value represents no alternative.
69 * When a query state reaches a step with an alternative index, the state
70 * is duplicated, with one copy remaining at the original step, and one copy
71 * moving to the alternative step. The alternative may have its own alternative
72 * step, so this splitting is an iterative process.
73 * - `is_dead_end` - Indicates that this state cannot be passed directly, and
74 * exists only in order to redirect to an alternative index, with no splitting.
75 * - `is_pass_through` - Indicates that state has no matching logic of its own,
76 * and exists only to split a state. One copy of the state advances immediately
77 * to the next step, and one moves to the alternative step.
78 * - `is_inside_alternation` - Indicates that state is inside an alternation.
79 * Currently only written to quantifier steps, read by logic that maintains
80 * correctness for quantifiers inside alternations.
81 *
82 * Steps also store some derived state that summarizes how they relate to other
83 * steps within the same pattern. This is used to optimize the matching process:
84 * - `contains_captures` - Indicates that this step or one of its child steps
85 * has a non-empty `capture_ids` list.
86 * - `parent_pattern_guaranteed` - Indicates that if this step is reached, then
87 * it and all of its subsequent sibling steps within the same parent pattern
88 * are guaranteed to match.
89 * - `root_pattern_guaranteed` - Similar to `parent_pattern_guaranteed`, but
90 * for the entire top-level pattern. When iterating through a query's
91 * captures using `ts_query_cursor_next_capture`, this field is used to
92 * detect that a capture can safely be returned from a match that has not
93 * even completed yet.
94 */
95 typedef struct {
96 TSSymbol symbol;
97 TSSymbol supertype_symbol;
98 TSFieldId field;
99 uint16_t capture_ids[MAX_STEP_CAPTURE_COUNT];
100 uint16_t depth;
101 uint16_t alternative_index;
102 uint16_t negated_field_list_id;
103 bool is_named: 1;
104 bool is_immediate: 1;
105 bool is_last_child: 1;
106 bool is_pass_through: 1;
107 bool is_dead_end: 1;
108 bool is_inside_alternation: 1;
109 bool contains_captures: 1;
110 bool root_pattern_guaranteed: 1;
111 bool parent_pattern_guaranteed: 1;
112 bool is_missing: 1;
113 } QueryStep;
114
115 /*
116 * Slice - A slice of an external array. Within a query, capture names,
117 * literal string values, and predicate step information are stored in three
118 * contiguous arrays. Individual captures, string values, and predicates are
119 * represented as slices of these three arrays.
120 */
121 typedef struct {
122 uint32_t offset;
123 uint32_t length;
124 } Slice;
125
126 /*
127 * SymbolTable - a two-way mapping of strings to ids.
128 */
129 typedef struct {
130 Array(char) characters;
131 Array(Slice) slices;
132 } SymbolTable;
133
134 /**
135 * CaptureQuantifiers - a data structure holding the quantifiers of pattern captures.
136 */
137 typedef Array(uint8_t) CaptureQuantifiers;
138
139 /*
140 * PatternEntry - Information about the starting point for matching a particular
141 * pattern. These entries are stored in a 'pattern map' - a sorted array that
142 * makes it possible to efficiently lookup patterns based on the symbol for their
143 * first step. The entry consists of the following fields:
144 * - `pattern_index` - the index of the pattern within the query
145 * - `step_index` - the index of the pattern's first step in the shared `steps` array
146 * - `is_rooted` - whether or not the pattern has a single root node. This property
147 * affects decisions about whether or not to start the pattern for nodes outside
148 * of a QueryCursor's range restriction.
149 */
150 typedef struct {
151 uint16_t step_index;
152 uint16_t pattern_index;
153 bool is_rooted;
154 } PatternEntry;
155
156 typedef struct {
157 Slice steps;
158 Slice predicate_steps;
159 uint32_t start_byte;
160 uint32_t end_byte;
161 bool is_non_local;
162 } QueryPattern;
163
164 typedef struct {
165 uint32_t byte_offset;
166 uint16_t step_index;
167 } StepOffset;
168
169 /*
170 * QueryState - The state of an in-progress match of a particular pattern
171 * in a query. While executing, a `TSQueryCursor` must keep track of a number
172 * of possible in-progress matches. Each of those possible matches is
173 * represented as one of these states. Fields:
174 * - `id` - A numeric id that is exposed to the public API. This allows the
175 * caller to remove a given match, preventing any more of its captures
176 * from being returned.
177 * - `start_depth` - The depth in the tree where the first step of the state's
178 * pattern was matched.
179 * - `pattern_index` - The pattern that the state is matching.
180 * - `consumed_capture_count` - The number of captures from this match that
181 * have already been returned.
182 * - `capture_list_id` - A numeric id that can be used to retrieve the state's
183 * list of captures from the `CaptureListPool`.
184 * - `heap_insert_order` - A sequence number used to preserve discovery order
185 * among finished states with the same capture position and pattern.
186 * - `seeking_immediate_match` - A flag that indicates that the state's next
187 * step must be matched by the very next sibling. This is used when
188 * processing repetitions, or when processing a wildcard node followed by
189 * an anchor.
190 * - `has_in_progress_alternatives` - A flag that indicates that there is are
191 * other states that have the same captures as this state, but are at
192 * different steps in their pattern. This means that in order to obey the
193 * 'longest-match' rule, this state should not be returned as a match until
194 * it is clear that there can be no other alternative match with more captures.
195 */
196 typedef struct {
197 uint32_t id;
198 uint32_t capture_list_id;
199 uint32_t heap_insert_order;
200 uint16_t start_depth;
201 uint16_t step_index;
202 uint16_t pattern_index;
203 uint16_t consumed_capture_count: 12;
204 bool seeking_immediate_match: 1;
205 bool has_in_progress_alternatives: 1;
206 bool dead: 1;
207 bool needs_parent: 1;
208 } QueryState;
209
210 typedef Array(QueryState) QueryStateList;
211 typedef Array(TSQueryCapture) CaptureList;
212
213 /*
214 * CaptureListPool - A collection of *lists* of captures. Each query state needs
215 * to maintain its own list of captures. To avoid repeated allocations, this struct
216 * maintains a fixed set of capture lists, and keeps track of which ones are
217 * currently in use by a query state.
218 */
219 typedef struct {
220 Array(CaptureList) list;
221 CaptureList empty_list;
222 // The maximum number of capture lists that we are allowed to allocate. We
223 // never allow `list` to allocate more entries than this, dropping pending
224 // matches if needed to stay under the limit.
225 uint32_t max_capture_list_count;
226 // The number of capture lists allocated in `list` that are not currently in
227 // use. We reuse those existing-but-unused capture lists before trying to
228 // allocate any new ones. We use an invalid value (UINT32_MAX) for a capture
229 // list's length to indicate that it's not in use.
230 uint32_t free_capture_list_count;
231 } CaptureListPool;
232
233 /*
234 * AnalysisState - The state needed for walking the parse table when analyzing
235 * a query pattern, to determine at which steps the pattern might fail to match.
236 */
237 typedef struct {
238 TSStateId parse_state;
239 TSSymbol parent_symbol;
240 uint16_t child_index;
241 TSFieldId field_id: 15;
242 bool done: 1;
243 } AnalysisStateEntry;
244
245 typedef struct {
246 AnalysisStateEntry stack[MAX_ANALYSIS_STATE_DEPTH];
247 uint16_t depth;
248 uint16_t step_index;
249 TSSymbol root_symbol;
250 } AnalysisState;
251
252 typedef Array(AnalysisState *) AnalysisStateSet;
253
254 typedef struct {
255 AnalysisStateSet states;
256 AnalysisStateSet next_states;
257 AnalysisStateSet deeper_states;
258 AnalysisStateSet state_pool;
259 Array(uint16_t) final_step_indices;
260 Array(TSSymbol) finished_parent_symbols;
261 bool did_abort;
262 } QueryAnalysis;
263
264 /*
265 * AnalysisSubgraph - A subset of the states in the parse table that are used
266 * in constructing nodes with a certain symbol. Each state is accompanied by
267 * some information about the possible node that could be produced in
268 * downstream states.
269 */
270 typedef struct {
271 TSStateId state;
272 uint16_t production_id;
273 uint8_t child_index: 7;
274 bool done: 1;
275 } AnalysisSubgraphNode;
276
277 typedef struct {
278 TSSymbol symbol;
279 Array(TSStateId) start_states;
280 Array(AnalysisSubgraphNode) nodes;
281 } AnalysisSubgraph;
282
283 typedef Array(AnalysisSubgraph) AnalysisSubgraphArray;
284
285 /*
286 * StatePredecessorMap - A map that stores the predecessors of each parse state.
287 * This is used during query analysis to determine which parse states can lead
288 * to which reduce actions.
289 */
290 typedef struct {
291 TSStateId *contents;
292 } StatePredecessorMap;
293
294 /*
295 * TSQuery - A tree query, compiled from a string of S-expressions. The query
296 * itself is immutable. The mutable state used in the process of executing the
297 * query is stored in a `TSQueryCursor`.
298 */
299 struct TSQuery {
300 SymbolTable captures;
301 SymbolTable predicate_values;
302 Array(CaptureQuantifiers) capture_quantifiers;
303 Array(QueryStep) steps;
304 Array(PatternEntry) pattern_map;
305 Array(TSQueryPredicateStep) predicate_steps;
306 Array(QueryPattern) patterns;
307 Array(StepOffset) step_offsets;
308 Array(TSFieldId) negated_fields;
309 Array(char) string_buffer;
310 Array(TSSymbol) repeat_symbols_with_rootless_patterns;
311 const TSLanguage *language;
312 uint16_t wildcard_root_pattern_count;
313 };
314
315 /*
316 * TSQueryCursor - A stateful struct used to execute a query on a tree.
317 */
318 struct TSQueryCursor {
319 const TSQuery *query;
320 TSTreeCursor cursor;
321 QueryStateList states;
322 QueryStateList finished_states;
323 // Tracks how much of finished_states is in heap order. Elements at indices
324 // < this value satisfy the min-heap property; elements >= this value are
325 // newly pushed and need to be sifted into place. Only used by `next_capture`.
326 uint32_t finished_states_heap_size;
327 CaptureListPool capture_list_pool;
328 uint32_t depth;
329 uint32_t max_start_depth;
330 TSRange included_range;
331 TSRange containing_range;
332 uint32_t next_state_id;
333 uint32_t next_finished_state_id;
334 const TSQueryCursorOptions *query_options;
335 TSQueryCursorState query_state;
336 unsigned operation_count;
337 bool on_visible_node;
338 bool ascending;
339 bool halted;
340 bool did_exceed_match_limit;
341 };
342
343 static const TSQueryError PARENT_DONE = -1;
344 static const uint16_t PATTERN_DONE_MARKER = UINT16_MAX;
345 static const uint16_t NONE = UINT16_MAX;
346 static const uint32_t CAPTURE_LIST_NONE = UINT32_MAX;
347 static const TSSymbol WILDCARD_SYMBOL = 0;
348 static const unsigned OP_COUNT_PER_QUERY_CALLBACK_CHECK = 100;
349
350 /**********
351 * Stream
352 **********/
353
354 // Advance to the next unicode code point in the stream.
355 static bool stream_advance(Stream *self) {
356 self->input += self->next_size;
357 if (self->input < self->end) {
358 uint32_t size = ts_decode_utf8(
359 (const uint8_t *)self->input,
360 (uint32_t)(self->end - self->input),
361 &self->next
362 );
363 if (size > 0) {
364 self->next_size = size;
365 return true;
366 }
367 } else {
368 self->next_size = 0;
369 self->next = '\0';
370 }
371 return false;
372 }
373
374 // Reset the stream to the given input position, represented as a pointer
375 // into the input string.
376 static void stream_reset(Stream *self, const char *input) {
377 self->input = input;
378 self->next_size = 0;
379 stream_advance(self);
380 }
381
382 static Stream stream_new(const char *string, uint32_t length) {
383 Stream self = {
384 .next = 0,
385 .input = string,
386 .start = string,
387 .end = string + length,
388 };
389 stream_advance(&self);
390 return self;
391 }
392
393 static void stream_skip_whitespace(Stream *self) {
394 for (;;) {
395 if (iswspace(self->next)) {
396 stream_advance(self);
397 } else if (self->next == ';') {
398 // skip over comments
399 stream_advance(self);
400 while (self->next && self->next != '\n') {
401 if (!stream_advance(self)) break;
402 }
403 } else {
404 break;
405 }
406 }
407 }
408
409 static bool stream_is_ident_start(Stream *self) {
410 return iswalnum(self->next) || self->next == '_' || self->next == '-';
411 }
412
413 static void stream_scan_identifier(Stream *stream) {
414 do {
415 stream_advance(stream);
416 } while (
417 iswalnum(stream->next) ||
418 stream->next == '_' ||
419 stream->next == '-' ||
420 stream->next == '.'
421 );
422 }
423
424 static uint32_t stream_offset(Stream *self) {
425 return (uint32_t)(self->input - self->start);
426 }
427
428 /******************
429 * CaptureListPool
430 ******************/
431
432 static CaptureListPool capture_list_pool_new(void) {
433 return (CaptureListPool) {
434 .list = array_new(),
435 .empty_list = array_new(),
436 .max_capture_list_count = UINT32_MAX,
437 .free_capture_list_count = 0,
438 };
439 }
440
441 static void capture_list_pool_reset(CaptureListPool *self) {
442 for (uint32_t i = 0; i < self->list.size; i++) {
443 // This invalid size means that the list is not in use.
444 array_get(&self->list, i)->size = UINT32_MAX;
445 }
446 self->free_capture_list_count = self->list.size;
447 }
448
449 static void capture_list_pool_delete(CaptureListPool *self) {
450 for (uint32_t i = 0; i < self->list.size; i++) {
451 array_delete(array_get(&self->list, i));
452 }
453 array_delete(&self->list);
454 }
455
456 static const CaptureList *capture_list_pool_get(const CaptureListPool *self, uint32_t id) {
457 if (id >= self->list.size) return &self->empty_list;
458 return array_get(&self->list, id);
459 }
460
461 static CaptureList *capture_list_pool_get_mut(CaptureListPool *self, uint32_t id) {
462 ts_assert(id < self->list.size);
463 return array_get(&self->list, id);
464 }
465
466 static bool capture_list_pool_is_empty(const CaptureListPool *self) {
467 // The capture list pool is empty if all allocated lists are in use, and we
468 // have reached the maximum allowed number of allocated lists.
469 return self->free_capture_list_count == 0 && self->list.size >= self->max_capture_list_count;
470 }
471
472 static uint32_t capture_list_pool_acquire(CaptureListPool *self) {
473 // First see if any already allocated capture list is currently unused.
474 if (self->free_capture_list_count > 0) {
475 for (uint32_t i = 0; i < self->list.size; i++) {
476 if (array_get(&self->list, i)->size == UINT32_MAX) {
477 array_clear(array_get(&self->list, i));
478 self->free_capture_list_count--;
479 return i;
480 }
481 }
482 }
483
484 // Otherwise allocate and initialize a new capture list, as long as that
485 // doesn't put us over the requested maximum.
486 uint32_t i = self->list.size;
487 if (i >= self->max_capture_list_count) {
488 return CAPTURE_LIST_NONE;
489 }
490 CaptureList list;
491 array_init(&list);
492 array_push(&self->list, list);
493 return i;
494 }
495
496 static void capture_list_pool_release(CaptureListPool *self, uint32_t id) {
497 if (id >= self->list.size) return;
498 array_get(&self->list, id)->size = UINT32_MAX;
499 self->free_capture_list_count++;
500 }
501
502 /********************
503 * FinishedStateHeap
504 *
505 * A min-heap of finished query states, ordered by (byte offset of next
506 * unconsumed capture, pattern_index, insertion order). This allows
507 * ts_query_cursor_next_capture to find the earliest capture in O(1) instead
508 * of scanning all finished states. The heap is maintained lazily -
509 * ts_query_cursor__advance uses plain array_push, and next_capture sifts
510 * new elements into place via a tracked heap_size boundary.
511 ********************/
512
513 static void finished_state_swap(QueryStateList *states, uint32_t a, uint32_t b) {
514 QueryState tmp = *array_get(states, a);
515 *array_get(states, a) = *array_get(states, b);
516 *array_get(states, b) = tmp;
517 }
518
519 // Compare two finished states by (byte offset of next unconsumed capture,
520 // pattern_index, insertion order).
521 static inline bool finished_state_precedes(
522 const QueryState *a,
523 const QueryState *b,
524 const CaptureListPool *pool
525 ) {
526 const CaptureList *a_caps = capture_list_pool_get(pool, a->capture_list_id);
527 const CaptureList *b_caps = capture_list_pool_get(pool, b->capture_list_id);
528 if (a->consumed_capture_count >= a_caps->size) return false;
529 if (b->consumed_capture_count >= b_caps->size) return true;
530 uint32_t a_byte = ts_node_start_byte(a_caps->contents[a->consumed_capture_count].node);
531 uint32_t b_byte = ts_node_start_byte(b_caps->contents[b->consumed_capture_count].node);
532 if (a_byte != b_byte) return a_byte < b_byte;
533 if (a->pattern_index != b->pattern_index) return a->pattern_index < b->pattern_index;
534 return a->heap_insert_order < b->heap_insert_order;
535 }
536
537 static void finished_state_sift_down(
538 QueryStateList *states,
539 uint32_t index,
540 const CaptureListPool *pool
541 ) {
542 uint32_t size = states->size;
543 while (true) {
544 uint32_t smallest = index;
545 uint32_t left = 2 * index + 1;
546 uint32_t right = 2 * index + 2;
547 if (left < size && finished_state_precedes(
548 array_get(states, left),
549 array_get(states, smallest),
550 pool
551 )) {
552 smallest = left;
553 }
554 if (right < size && finished_state_precedes(
555 array_get(states, right),
556 array_get(states, smallest),
557 pool
558 )) {
559 smallest = right;
560 }
561 if (smallest == index) break;
562 finished_state_swap(states, index, smallest);
563 index = smallest;
564 }
565 }
566
567 static void finished_state_sift_up(
568 QueryStateList *states,
569 uint32_t index,
570 const CaptureListPool *pool
571 ) {
572 while (index > 0) {
573 uint32_t parent = (index - 1) / 2;
574 if (finished_state_precedes(
575 array_get(states, index),
576 array_get(states, parent),
577 pool
578 )) {
579 finished_state_swap(states, index, parent);
580 index = parent;
581 } else {
582 break;
583 }
584 }
585 }
586
587 static inline void finished_state_pop(QueryStateList *states, const CaptureListPool *pool) {
588 if (states->size > 1) *array_front(states) = *array_back(states);
589 states->size--;
590 if (states->size > 0) finished_state_sift_down(states, 0, pool);
591 }
592
593 // Remove an element at an arbitrary index and restore heap order.
594 static void finished_state_erase(
595 QueryStateList *states,
596 uint32_t index,
597 const CaptureListPool *pool
598 ) {
599 if (index == states->size - 1) {
600 states->size--;
601 return;
602 }
603 *array_get(states, index) = *array_back(states);
604 states->size--;
605 // The replacement element may need to go up or down.
606 if (index > 0 && finished_state_precedes(
607 array_get(states, index),
608 array_get(states, (index - 1) / 2),
609 pool
610 )) {
611 finished_state_sift_up(states, index, pool);
612 } else {
613 finished_state_sift_down(states, index, pool);
614 }
615 }
616
617 static void ts_query_cursor__push_finished_state(
618 TSQueryCursor *self,
619 QueryState *state
620 ) {
621 state->heap_insert_order = self->next_finished_state_id++;
622 array_push(&self->finished_states, *state);
623 }
624
625 static void ts_query_cursor__heapify_finished_states(TSQueryCursor *self) {
626 while (self->finished_states_heap_size < self->finished_states.size) {
627 finished_state_sift_up(
628 &self->finished_states,
629 self->finished_states_heap_size,
630 &self->capture_list_pool
631 );
632 self->finished_states_heap_size++;
633 }
634 }
635
636 /**************
637 * Quantifiers
638 **************/
639
640 static TSQuantifier quantifier_mul(
641 TSQuantifier left,
642 TSQuantifier right
643 ) {
644 switch (left)
645 {
646 case TSQuantifierZero:
647 return TSQuantifierZero;
648 case TSQuantifierZeroOrOne:
649 switch (right) {
650 case TSQuantifierZero:
651 return TSQuantifierZero;
652 case TSQuantifierZeroOrOne:
653 case TSQuantifierOne:
654 return TSQuantifierZeroOrOne;
655 case TSQuantifierZeroOrMore:
656 case TSQuantifierOneOrMore:
657 return TSQuantifierZeroOrMore;
658 };
659 break;
660 case TSQuantifierZeroOrMore:
661 switch (right) {
662 case TSQuantifierZero:
663 return TSQuantifierZero;
664 case TSQuantifierZeroOrOne:
665 case TSQuantifierZeroOrMore:
666 case TSQuantifierOne:
667 case TSQuantifierOneOrMore:
668 return TSQuantifierZeroOrMore;
669 };
670 break;
671 case TSQuantifierOne:
672 return right;
673 case TSQuantifierOneOrMore:
674 switch (right) {
675 case TSQuantifierZero:
676 return TSQuantifierZero;
677 case TSQuantifierZeroOrOne:
678 case TSQuantifierZeroOrMore:
679 return TSQuantifierZeroOrMore;
680 case TSQuantifierOne:
681 case TSQuantifierOneOrMore:
682 return TSQuantifierOneOrMore;
683 };
684 break;
685 }
686 return TSQuantifierZero; // to make compiler happy, but all cases should be covered above!
687 }
688
689 static TSQuantifier quantifier_join(
690 TSQuantifier left,
691 TSQuantifier right
692 ) {
693 switch (left)
694 {
695 case TSQuantifierZero:
696 switch (right) {
697 case TSQuantifierZero:
698 return TSQuantifierZero;
699 case TSQuantifierZeroOrOne:
700 case TSQuantifierOne:
701 return TSQuantifierZeroOrOne;
702 case TSQuantifierZeroOrMore:
703 case TSQuantifierOneOrMore:
704 return TSQuantifierZeroOrMore;
705 };
706 break;
707 case TSQuantifierZeroOrOne:
708 switch (right) {
709 case TSQuantifierZero:
710 case TSQuantifierZeroOrOne:
711 case TSQuantifierOne:
712 return TSQuantifierZeroOrOne;
713 break;
714 case TSQuantifierZeroOrMore:
715 case TSQuantifierOneOrMore:
716 return TSQuantifierZeroOrMore;
717 break;
718 };
719 break;
720 case TSQuantifierZeroOrMore:
721 return TSQuantifierZeroOrMore;
722 case TSQuantifierOne:
723 switch (right) {
724 case TSQuantifierZero:
725 case TSQuantifierZeroOrOne:
726 return TSQuantifierZeroOrOne;
727 case TSQuantifierZeroOrMore:
728 return TSQuantifierZeroOrMore;
729 case TSQuantifierOne:
730 return TSQuantifierOne;
731 case TSQuantifierOneOrMore:
732 return TSQuantifierOneOrMore;
733 };
734 break;
735 case TSQuantifierOneOrMore:
736 switch (right) {
737 case TSQuantifierZero:
738 case TSQuantifierZeroOrOne:
739 case TSQuantifierZeroOrMore:
740 return TSQuantifierZeroOrMore;
741 case TSQuantifierOne:
742 case TSQuantifierOneOrMore:
743 return TSQuantifierOneOrMore;
744 };
745 break;
746 }
747 return TSQuantifierZero; // to make compiler happy, but all cases should be covered above!
748 }
749
750 static TSQuantifier quantifier_add(
751 TSQuantifier left,
752 TSQuantifier right
753 ) {
754 switch (left)
755 {
756 case TSQuantifierZero:
757 return right;
758 case TSQuantifierZeroOrOne:
759 switch (right) {
760 case TSQuantifierZero:
761 return TSQuantifierZeroOrOne;
762 case TSQuantifierZeroOrOne:
763 case TSQuantifierZeroOrMore:
764 return TSQuantifierZeroOrMore;
765 case TSQuantifierOne:
766 case TSQuantifierOneOrMore:
767 return TSQuantifierOneOrMore;
768 };
769 break;
770 case TSQuantifierZeroOrMore:
771 switch (right) {
772 case TSQuantifierZero:
773 return TSQuantifierZeroOrMore;
774 case TSQuantifierZeroOrOne:
775 case TSQuantifierZeroOrMore:
776 return TSQuantifierZeroOrMore;
777 case TSQuantifierOne:
778 case TSQuantifierOneOrMore:
779 return TSQuantifierOneOrMore;
780 };
781 break;
782 case TSQuantifierOne:
783 switch (right) {
784 case TSQuantifierZero:
785 return TSQuantifierOne;
786 case TSQuantifierZeroOrOne:
787 case TSQuantifierZeroOrMore:
788 case TSQuantifierOne:
789 case TSQuantifierOneOrMore:
790 return TSQuantifierOneOrMore;
791 };
792 break;
793 case TSQuantifierOneOrMore:
794 return TSQuantifierOneOrMore;
795 }
796 return TSQuantifierZero; // to make compiler happy, but all cases should be covered above!
797 }
798
799 // Create new capture quantifiers structure
800 static CaptureQuantifiers capture_quantifiers_new(void) {
801 return (CaptureQuantifiers) array_new();
802 }
803
804 // Delete capture quantifiers structure
805 static void capture_quantifiers_delete(
806 CaptureQuantifiers *self
807 ) {
808 array_delete(self);
809 }
810
811 // Clear capture quantifiers structure
812 static void capture_quantifiers_clear(
813 CaptureQuantifiers *self
814 ) {
815 array_clear(self);
816 }
817
818 // Replace capture quantifiers with the given quantifiers
819 static void capture_quantifiers_replace(
820 CaptureQuantifiers *self,
821 CaptureQuantifiers *quantifiers
822 ) {
823 array_clear(self);
824 array_push_all(self, quantifiers);
825 }
826
827 // Return capture quantifier for the given capture id
828 static TSQuantifier capture_quantifier_for_id(
829 const CaptureQuantifiers *self,
830 uint16_t id
831 ) {
832 return (self->size <= id) ? TSQuantifierZero : (TSQuantifier) *array_get(self, id);
833 }
834
835 // Add the given quantifier to the current value for id
836 static void capture_quantifiers_add_for_id(
837 CaptureQuantifiers *self,
838 uint16_t id,
839 TSQuantifier quantifier
840 ) {
841 if (self->size <= id) {
842 array_grow_by(self, id + 1 - self->size);
843 }
844 uint8_t *own_quantifier = array_get(self, id);
845 *own_quantifier = (uint8_t) quantifier_add((TSQuantifier) *own_quantifier, quantifier);
846 }
847
848 // Point-wise add the given quantifiers to the current values
849 static void capture_quantifiers_add_all(
850 CaptureQuantifiers *self,
851 CaptureQuantifiers *quantifiers
852 ) {
853 if (self->size < quantifiers->size) {
854 array_grow_by(self, quantifiers->size - self->size);
855 }
856 for (uint16_t id = 0; id < (uint16_t)quantifiers->size; id++) {
857 uint8_t *quantifier = array_get(quantifiers, id);
858 uint8_t *own_quantifier = array_get(self, id);
859 *own_quantifier = (uint8_t) quantifier_add((TSQuantifier) *own_quantifier, (TSQuantifier) *quantifier);
860 }
861 }
862
863 // Join the given quantifier with the current values
864 static void capture_quantifiers_mul(
865 CaptureQuantifiers *self,
866 TSQuantifier quantifier
867 ) {
868 for (uint16_t id = 0; id < (uint16_t)self->size; id++) {
869 uint8_t *own_quantifier = array_get(self, id);
870 *own_quantifier = (uint8_t) quantifier_mul((TSQuantifier) *own_quantifier, quantifier);
871 }
872 }
873
874 // Point-wise join the quantifiers from a list of alternatives with the current values
875 static void capture_quantifiers_join_all(
876 CaptureQuantifiers *self,
877 CaptureQuantifiers *quantifiers
878 ) {
879 if (self->size < quantifiers->size) {
880 array_grow_by(self, quantifiers->size - self->size);
881 }
882 for (uint32_t id = 0; id < quantifiers->size; id++) {
883 uint8_t *quantifier = array_get(quantifiers, id);
884 uint8_t *own_quantifier = array_get(self, id);
885 *own_quantifier = (uint8_t) quantifier_join((TSQuantifier) *own_quantifier, (TSQuantifier) *quantifier);
886 }
887 for (uint32_t id = quantifiers->size; id < self->size; id++) {
888 uint8_t *own_quantifier = array_get(self, id);
889 *own_quantifier = (uint8_t) quantifier_join((TSQuantifier) *own_quantifier, TSQuantifierZero);
890 }
891 }
892
893 /**************
894 * SymbolTable
895 **************/
896
897 static SymbolTable symbol_table_new(void) {
898 return (SymbolTable) {
899 .characters = array_new(),
900 .slices = array_new(),
901 };
902 }
903
904 static void symbol_table_delete(SymbolTable *self) {
905 array_delete(&self->characters);
906 array_delete(&self->slices);
907 }
908
909 static int symbol_table_id_for_name(
910 const SymbolTable *self,
911 const char *name,
912 uint32_t length
913 ) {
914 for (unsigned i = 0; i < self->slices.size; i++) {
915 Slice slice = *array_get(&self->slices, i);
916 if (
917 slice.length == length &&
918 !strncmp(array_get(&self->characters, slice.offset), name, length)
919 ) return i;
920 }
921 return -1;
922 }
923
924 static const char *symbol_table_name_for_id(
925 const SymbolTable *self,
926 uint16_t id,
927 uint32_t *length
928 ) {
929 Slice slice = *(array_get(&self->slices,id));
930 *length = slice.length;
931 return array_get(&self->characters, slice.offset);
932 }
933
934 static uint16_t symbol_table_insert_name(
935 SymbolTable *self,
936 const char *name,
937 uint32_t length
938 ) {
939 int id = symbol_table_id_for_name(self, name, length);
940 if (id >= 0) return (uint16_t)id;
941 Slice slice = {
942 .offset = self->characters.size,
943 .length = length,
944 };
945 array_grow_by(&self->characters, length + 1);
946 memcpy(array_get(&self->characters, slice.offset), name, length);
947 *array_get(&self->characters, self->characters.size - 1) = 0;
948 array_push(&self->slices, slice);
949 return self->slices.size - 1;
950 }
951
952 /************
953 * QueryStep
954 ************/
955
956 static QueryStep query_step__new(
957 TSSymbol symbol,
958 uint16_t depth,
959 bool is_immediate
960 ) {
961 QueryStep step = {
962 .symbol = symbol,
963 .depth = depth,
964 .alternative_index = NONE,
965 .is_immediate = is_immediate,
966 };
967 for (unsigned i = 0; i < MAX_STEP_CAPTURE_COUNT; i++) {
968 step.capture_ids[i] = NONE;
969 }
970 return step;
971 }
972
973 static void query_step__add_capture(QueryStep *self, uint16_t capture_id) {
974 for (unsigned i = 0; i < MAX_STEP_CAPTURE_COUNT; i++) {
975 if (self->capture_ids[i] == NONE) {
976 self->capture_ids[i] = capture_id;
977 break;
978 }
979 }
980 }
981
982 static void query_step__remove_capture(QueryStep *self, uint16_t capture_id) {
983 for (unsigned i = 0; i < MAX_STEP_CAPTURE_COUNT; i++) {
984 if (self->capture_ids[i] == capture_id) {
985 self->capture_ids[i] = NONE;
986 while (i + 1 < MAX_STEP_CAPTURE_COUNT) {
987 if (self->capture_ids[i + 1] == NONE) break;
988 self->capture_ids[i] = self->capture_ids[i + 1];
989 self->capture_ids[i + 1] = NONE;
990 i++;
991 }
992 break;
993 }
994 }
995 }
996
997 /**********************
998 * StatePredecessorMap
999 **********************/
1000
1001 static inline StatePredecessorMap state_predecessor_map_new(
1002 const TSLanguage *language
1003 ) {
1004 return (StatePredecessorMap) {
1005 .contents = ts_calloc(
1006 (size_t)language->state_count * (MAX_STATE_PREDECESSOR_COUNT + 1),
1007 sizeof(TSStateId)
1008 ),
1009 };
1010 }
1011
1012 static inline void state_predecessor_map_delete(StatePredecessorMap *self) {
1013 ts_free(self->contents);
1014 }
1015
1016 static inline void state_predecessor_map_add(
1017 StatePredecessorMap *self,
1018 TSStateId state,
1019 TSStateId predecessor
1020 ) {
1021 size_t index = (size_t)state * (MAX_STATE_PREDECESSOR_COUNT + 1);
1022 TSStateId *count = &self->contents[index];
1023 if (
1024 *count == 0 ||
1025 (*count < MAX_STATE_PREDECESSOR_COUNT && self->contents[index + *count] != predecessor)
1026 ) {
1027 (*count)++;
1028 self->contents[index + *count] = predecessor;
1029 }
1030 }
1031
1032 static inline const TSStateId *state_predecessor_map_get(
1033 const StatePredecessorMap *self,
1034 TSStateId state,
1035 unsigned *count
1036 ) {
1037 size_t index = (size_t)state * (MAX_STATE_PREDECESSOR_COUNT + 1);
1038 *count = self->contents[index];
1039 return &self->contents[index + 1];
1040 }
1041
1042 /****************
1043 * AnalysisState
1044 ****************/
1045
1046 static unsigned analysis_state__recursion_depth(const AnalysisState *self) {
1047 unsigned result = 0;
1048 for (unsigned i = 0; i < self->depth; i++) {
1049 TSSymbol symbol = self->stack[i].parent_symbol;
1050 for (unsigned j = 0; j < i; j++) {
1051 if (self->stack[j].parent_symbol == symbol) {
1052 result++;
1053 break;
1054 }
1055 }
1056 }
1057 return result;
1058 }
1059
1060 static inline int analysis_state__compare(
1061 AnalysisState *const *self,
1062 AnalysisState *const *other
1063 ) {
1064 if ((*self)->depth < (*other)->depth) return 1;
1065 for (unsigned i = 0; i < (*self)->depth; i++) {
1066 if (i >= (*other)->depth) return -1;
1067 AnalysisStateEntry s1 = (*self)->stack[i];
1068 AnalysisStateEntry s2 = (*other)->stack[i];
1069 if (s1.child_index < s2.child_index) return -1;
1070 if (s1.child_index > s2.child_index) return 1;
1071 if (s1.parent_symbol < s2.parent_symbol) return -1;
1072 if (s1.parent_symbol > s2.parent_symbol) return 1;
1073 if (s1.parse_state < s2.parse_state) return -1;
1074 if (s1.parse_state > s2.parse_state) return 1;
1075 if (s1.field_id < s2.field_id) return -1;
1076 if (s1.field_id > s2.field_id) return 1;
1077 }
1078 if ((*self)->step_index < (*other)->step_index) return -1;
1079 if ((*self)->step_index > (*other)->step_index) return 1;
1080 return 0;
1081 }
1082
1083 static inline AnalysisStateEntry *analysis_state__top(AnalysisState *self) {
1084 if (self->depth == 0) {
1085 return &self->stack[0];
1086 }
1087 return &self->stack[self->depth - 1];
1088 }
1089
1090 static inline bool analysis_state__has_supertype(AnalysisState *self, TSSymbol symbol) {
1091 for (unsigned i = 0; i < self->depth; i++) {
1092 if (self->stack[i].parent_symbol == symbol) return true;
1093 }
1094 return false;
1095 }
1096
1097 /******************
1098 * AnalysisStateSet
1099 ******************/
1100
1101 // Obtains an `AnalysisState` instance, either by consuming one from this set's object pool, or by
1102 // cloning one from scratch.
1103 static inline AnalysisState *analysis_state_pool__clone_or_reuse(
1104 AnalysisStateSet *self,
1105 AnalysisState *borrowed_item
1106 ) {
1107 AnalysisState *new_item;
1108 if (self->size) {
1109 new_item = array_pop(self);
1110 } else {
1111 new_item = ts_malloc(sizeof(AnalysisState));
1112 }
1113 *new_item = *borrowed_item;
1114 return new_item;
1115 }
1116
1117 // Inserts a clone of the passed-in item at the appropriate position to maintain ordering in this
1118 // set. The set does not contain duplicates, so if the item is already present, it will not be
1119 // inserted, and no clone will be made.
1120 //
1121 // The caller retains ownership of the passed-in memory. However, the clone that is created by this
1122 // function will be managed by the state set.
1123 static inline void analysis_state_set__insert_sorted(
1124 AnalysisStateSet *self,
1125 AnalysisStateSet *pool,
1126 AnalysisState *borrowed_item
1127 ) {
1128 unsigned index, exists;
1129 array_search_sorted_with(self, analysis_state__compare, &borrowed_item, &index, &exists);
1130 if (!exists) {
1131 AnalysisState *new_item = analysis_state_pool__clone_or_reuse(pool, borrowed_item);
1132 array_insert(self, index, new_item);
1133 }
1134 }
1135
1136 // Inserts a clone of the passed-in item at the end position of this list.
1137 //
1138 // IMPORTANT: The caller MUST ENSURE that this item is larger (by the comparison function
1139 // `analysis_state__compare`) than largest item already in this set. If items are inserted in the
1140 // wrong order, the set will not function properly for future use.
1141 //
1142 // The caller retains ownership of the passed-in memory. However, the clone that is created by this
1143 // function will be managed by the state set.
1144 static inline void analysis_state_set__push(
1145 AnalysisStateSet *self,
1146 AnalysisStateSet *pool,
1147 AnalysisState *borrowed_item
1148 ) {
1149 AnalysisState *new_item = analysis_state_pool__clone_or_reuse(pool, borrowed_item);
1150 array_push(self, new_item);
1151 }
1152
1153 // Removes all items from this set, returning it to an empty state.
1154 static inline void analysis_state_set__clear(AnalysisStateSet *self, AnalysisStateSet *pool) {
1155 array_push_all(pool, self);
1156 array_clear(self);
1157 }
1158
1159 // Releases all memory that is managed with this state set, including any items currently present.
1160 // After calling this function, the set is no longer suitable for use.
1161 static inline void analysis_state_set__delete(AnalysisStateSet *self) {
1162 for (unsigned i = 0; i < self->size; i++) {
1163 ts_free(self->contents[i]);
1164 }
1165 array_delete(self);
1166 }
1167
1168 /****************
1169 * QueryAnalyzer
1170 ****************/
1171
1172 static inline QueryAnalysis query_analysis__new(void) {
1173 return (QueryAnalysis) {
1174 .states = array_new(),
1175 .next_states = array_new(),
1176 .deeper_states = array_new(),
1177 .state_pool = array_new(),
1178 .final_step_indices = array_new(),
1179 .finished_parent_symbols = array_new(),
1180 .did_abort = false,
1181 };
1182 }
1183
1184 static inline void query_analysis__delete(QueryAnalysis *self) {
1185 analysis_state_set__delete(&self->states);
1186 analysis_state_set__delete(&self->next_states);
1187 analysis_state_set__delete(&self->deeper_states);
1188 analysis_state_set__delete(&self->state_pool);
1189 array_delete(&self->final_step_indices);
1190 array_delete(&self->finished_parent_symbols);
1191 }
1192
1193 /***********************
1194 * AnalysisSubgraphNode
1195 ***********************/
1196
1197 static inline int analysis_subgraph_node__compare(const AnalysisSubgraphNode *self, const AnalysisSubgraphNode *other) {
1198 if (self->state < other->state) return -1;
1199 if (self->state > other->state) return 1;
1200 if (self->child_index < other->child_index) return -1;
1201 if (self->child_index > other->child_index) return 1;
1202 if (self->done < other->done) return -1;
1203 if (self->done > other->done) return 1;
1204 if (self->production_id < other->production_id) return -1;
1205 if (self->production_id > other->production_id) return 1;
1206 return 0;
1207 }
1208
1209 /*********
1210 * Query
1211 *********/
1212
1213 // The `pattern_map` contains a mapping from TSSymbol values to indices in the
1214 // `steps` array. For a given syntax node, the `pattern_map` makes it possible
1215 // to quickly find the starting steps of all of the patterns whose root matches
1216 // that node. Each entry has two fields: a `pattern_index`, which identifies one
1217 // of the patterns in the query, and a `step_index`, which indicates the start
1218 // offset of that pattern's steps within the `steps` array.
1219 //
1220 // The entries are sorted by the patterns' root symbols, and lookups use a
1221 // binary search. This ensures that the cost of this initial lookup step
1222 // scales logarithmically with the number of patterns in the query.
1223 //
1224 // This returns `true` if the symbol is present and `false` otherwise.
1225 // If the symbol is not present `*result` is set to the index where the
1226 // symbol should be inserted.
1227 static inline bool ts_query__pattern_map_search(
1228 const TSQuery *self,
1229 TSSymbol needle,
1230 uint32_t *result
1231 ) {
1232 uint32_t base_index = self->wildcard_root_pattern_count;
1233 uint32_t size = self->pattern_map.size - base_index;
1234 if (size == 0) {
1235 *result = base_index;
1236 return false;
1237 }
1238 while (size > 1) {
1239 uint32_t half_size = size / 2;
1240 uint32_t mid_index = base_index + half_size;
1241 TSSymbol mid_symbol = array_get(&self->steps,
1242 array_get(&self->pattern_map, mid_index)->step_index
1243 )->symbol;
1244 if (needle > mid_symbol) base_index = mid_index;
1245 size -= half_size;
1246 }
1247
1248 TSSymbol symbol = array_get(&self->steps,
1249 array_get(&self->pattern_map, base_index)->step_index
1250 )->symbol;
1251
1252 if (needle > symbol) {
1253 base_index++;
1254 if (base_index < self->pattern_map.size) {
1255 symbol = array_get(&self->steps,
1256 array_get(&self->pattern_map, base_index)->step_index
1257 )->symbol;
1258 }
1259 }
1260
1261 *result = base_index;
1262 return needle == symbol;
1263 }
1264
1265 // Insert a new pattern's start index into the pattern map, maintaining
1266 // the pattern map's ordering invariant.
1267 static inline void ts_query__pattern_map_insert(
1268 TSQuery *self,
1269 TSSymbol symbol,
1270 PatternEntry new_entry
1271 ) {
1272 uint32_t index;
1273 ts_query__pattern_map_search(self, symbol, &index);
1274
1275 // Ensure that the entries are sorted not only by symbol, but also
1276 // by pattern_index. This way, states for earlier patterns will be
1277 // initiated first, which allows the ordering of the states array
1278 // to be maintained more efficiently.
1279 while (index < self->pattern_map.size) {
1280 PatternEntry *entry = array_get(&self->pattern_map, index);
1281 if (
1282 array_get(&self->steps, entry->step_index)->symbol == symbol &&
1283 entry->pattern_index < new_entry.pattern_index
1284 ) {
1285 index++;
1286 } else {
1287 break;
1288 }
1289 }
1290
1291 array_insert(&self->pattern_map, index, new_entry);
1292 }
1293
1294 // Walk the subgraph for this non-terminal, tracking all of the possible
1295 // sequences of progress within the pattern.
1296 static void ts_query__perform_analysis(
1297 TSQuery *self,
1298 const AnalysisSubgraphArray *subgraphs,
1299 QueryAnalysis *analysis
1300 ) {
1301 unsigned recursion_depth_limit = 0;
1302 unsigned prev_final_step_count = 0;
1303 array_clear(&analysis->final_step_indices);
1304 array_clear(&analysis->finished_parent_symbols);
1305
1306 for (unsigned iteration = 0;; iteration++) {
1307 if (iteration == MAX_ANALYSIS_ITERATION_COUNT) {
1308 analysis->did_abort = true;
1309 break;
1310 }
1311
1312 #ifdef DEBUG_ANALYZE_QUERY
1313 printf("Iteration: %u. Final step indices:", iteration);
1314 for (unsigned j = 0; j < analysis->final_step_indices.size; j++) {
1315 printf(" %4u", *array_get(&analysis->final_step_indices, j));
1316 }
1317 printf("\n");
1318 for (unsigned j = 0; j < analysis->states.size; j++) {
1319 AnalysisState *state = *array_get(&analysis->states, j);
1320 printf(" %3u: step: %u, stack: [", j, state->step_index);
1321 for (unsigned k = 0; k < state->depth; k++) {
1322 printf(
1323 " {%s, child: %u, state: %4u",
1324 self->language->symbol_names[state->stack[k].parent_symbol],
1325 state->stack[k].child_index,
1326 state->stack[k].parse_state
1327 );
1328 if (state->stack[k].field_id) printf(", field: %s", self->language->field_names[state->stack[k].field_id]);
1329 if (state->stack[k].done) printf(", DONE");
1330 printf("}");
1331 }
1332 printf(" ]\n");
1333 }
1334 #endif
1335
1336 // If no further progress can be made within the current recursion depth limit, then
1337 // bump the depth limit by one, and continue to process the states the exceeded the
1338 // limit. But only allow this if progress has been made since the last time the depth
1339 // limit was increased.
1340 if (analysis->states.size == 0) {
1341 if (
1342 analysis->deeper_states.size > 0 &&
1343 analysis->final_step_indices.size > prev_final_step_count
1344 ) {
1345 #ifdef DEBUG_ANALYZE_QUERY
1346 printf("Increase recursion depth limit to %u\n", recursion_depth_limit + 1);
1347 #endif
1348
1349 prev_final_step_count = analysis->final_step_indices.size;
1350 recursion_depth_limit++;
1351 AnalysisStateSet _states = analysis->states;
1352 analysis->states = analysis->deeper_states;
1353 analysis->deeper_states = _states;
1354 continue;
1355 }
1356
1357 break;
1358 }
1359
1360 analysis_state_set__clear(&analysis->next_states, &analysis->state_pool);
1361 for (unsigned j = 0; j < analysis->states.size; j++) {
1362 AnalysisState * const state = *array_get(&analysis->states, j);
1363
1364 // For efficiency, it's important to avoid processing the same analysis state more
1365 // than once. To achieve this, keep the states in order of ascending position within
1366 // their hypothetical syntax trees. In each iteration of this loop, start by advancing
1367 // the states that have made the least progress. Avoid advancing states that have already
1368 // made more progress.
1369 if (analysis->next_states.size > 0) {
1370 int comparison = analysis_state__compare(
1371 &state,
1372 array_back(&analysis->next_states)
1373 );
1374 if (comparison == 0) {
1375 analysis_state_set__insert_sorted(&analysis->next_states, &analysis->state_pool, state);
1376 continue;
1377 } else if (comparison > 0) {
1378 #ifdef DEBUG_ANALYZE_QUERY
1379 printf("Terminate iteration at state %u\n", j);
1380 #endif
1381 while (j < analysis->states.size) {
1382 analysis_state_set__push(
1383 &analysis->next_states,
1384 &analysis->state_pool,
1385 *array_get(&analysis->states, j)
1386 );
1387 j++;
1388 }
1389 break;
1390 }
1391 }
1392
1393 const TSStateId parse_state = analysis_state__top(state)->parse_state;
1394 const TSSymbol parent_symbol = analysis_state__top(state)->parent_symbol;
1395 const TSFieldId parent_field_id = analysis_state__top(state)->field_id;
1396 const unsigned child_index = analysis_state__top(state)->child_index;
1397 const QueryStep * const step = array_get(&self->steps, state->step_index);
1398
1399 unsigned subgraph_index, exists;
1400 array_search_sorted_by(subgraphs, .symbol, parent_symbol, &subgraph_index, &exists);
1401 if (!exists) continue;
1402 const AnalysisSubgraph *subgraph = array_get(subgraphs, subgraph_index);
1403
1404 // Follow every possible path in the parse table, but only visit states that
1405 // are part of the subgraph for the current symbol.
1406 LookaheadIterator lookahead_iterator = ts_language_lookaheads(self->language, parse_state);
1407 while (ts_lookahead_iterator__next(&lookahead_iterator)) {
1408 TSSymbol sym = lookahead_iterator.symbol;
1409
1410 AnalysisSubgraphNode successor = {
1411 .state = parse_state,
1412 .child_index = child_index,
1413 };
1414 if (lookahead_iterator.action_count) {
1415 const TSParseAction *action = &lookahead_iterator.actions[lookahead_iterator.action_count - 1];
1416 if (action->type == TSParseActionTypeShift) {
1417 if (!action->shift.extra) {
1418 successor.state = action->shift.state;
1419 successor.child_index++;
1420 }
1421 } else {
1422 continue;
1423 }
1424 } else if (lookahead_iterator.next_state != 0) {
1425 successor.state = lookahead_iterator.next_state;
1426 successor.child_index++;
1427 } else {
1428 continue;
1429 }
1430
1431 unsigned node_index;
1432 array_search_sorted_with(
1433 &subgraph->nodes,
1434 analysis_subgraph_node__compare, &successor,
1435 &node_index, &exists
1436 );
1437 while (node_index < subgraph->nodes.size) {
1438 AnalysisSubgraphNode *node = array_get(&subgraph->nodes, node_index);
1439 node_index++;
1440 if (node->state != successor.state || node->child_index != successor.child_index) break;
1441
1442 // Use the subgraph to determine what alias and field will eventually be applied
1443 // to this child node.
1444 TSSymbol alias = ts_language_alias_at(self->language, node->production_id, child_index);
1445 TSSymbol visible_symbol = alias
1446 ? alias
1447 : self->language->symbol_metadata[sym].visible
1448 ? self->language->public_symbol_map[sym]
1449 : 0;
1450 TSFieldId field_id = parent_field_id;
1451 if (!field_id) {
1452 const TSFieldMapEntry *field_map, *field_map_end;
1453 ts_language_field_map(self->language, node->production_id, &field_map, &field_map_end);
1454 for (; field_map != field_map_end; field_map++) {
1455 if (!field_map->inherited && field_map->child_index == child_index) {
1456 field_id = field_map->field_id;
1457 break;
1458 }
1459 }
1460 }
1461
1462 // Create a new state that has advanced past this hypothetical subtree.
1463 AnalysisState next_state = *state;
1464 AnalysisStateEntry *next_state_top = analysis_state__top(&next_state);
1465 next_state_top->child_index = successor.child_index;
1466 next_state_top->parse_state = successor.state;
1467 if (node->done) next_state_top->done = true;
1468
1469 // Determine if this hypothetical child node would match the current step
1470 // of the query pattern.
1471 bool does_match = false;
1472
1473 // ERROR nodes can appear anywhere, so if the step is
1474 // looking for an ERROR node, consider it potentially matchable.
1475 if (step->symbol == ts_builtin_sym_error) {
1476 does_match = true;
1477 } else if (visible_symbol) {
1478 does_match = true;
1479 if (step->symbol == WILDCARD_SYMBOL) {
1480 if (
1481 step->is_named &&
1482 !self->language->symbol_metadata[visible_symbol].named
1483 ) does_match = false;
1484 } else if (step->symbol != visible_symbol) {
1485 does_match = false;
1486 }
1487 if (step->field && step->field != field_id) {
1488 does_match = false;
1489 }
1490 if (
1491 step->supertype_symbol &&
1492 !analysis_state__has_supertype(state, step->supertype_symbol)
1493 ) does_match = false;
1494 }
1495
1496 // If this child is hidden, then descend into it and walk through its children.
1497 // If the top entry of the stack is at the end of its rule, then that entry can
1498 // be replaced. Otherwise, push a new entry onto the stack.
1499 else if (sym >= self->language->token_count) {
1500 if (!next_state_top->done) {
1501 if (next_state.depth + 1 >= MAX_ANALYSIS_STATE_DEPTH) {
1502 #ifdef DEBUG_ANALYZE_QUERY
1503 printf("Exceeded depth limit for state %u\n", j);
1504 #endif
1505
1506 analysis->did_abort = true;
1507 continue;
1508 }
1509
1510 next_state.depth++;
1511 next_state_top = analysis_state__top(&next_state);
1512 }
1513
1514 *next_state_top = (AnalysisStateEntry) {
1515 .parse_state = parse_state,
1516 .parent_symbol = sym,
1517 .child_index = 0,
1518 .field_id = field_id,
1519 .done = false,
1520 };
1521
1522 if (analysis_state__recursion_depth(&next_state) > recursion_depth_limit) {
1523 analysis_state_set__insert_sorted(
1524 &analysis->deeper_states,
1525 &analysis->state_pool,
1526 &next_state
1527 );
1528 continue;
1529 }
1530 }
1531
1532 // Pop from the stack when this state reached the end of its current syntax node.
1533 while (next_state.depth > 0 && next_state_top->done) {
1534 next_state.depth--;
1535 next_state_top = analysis_state__top(&next_state);
1536 }
1537
1538 // If this hypothetical child did match the current step of the query pattern,
1539 // then advance to the next step at the current depth. This involves skipping
1540 // over any descendant steps of the current child.
1541 const QueryStep *next_step = step;
1542 if (does_match) {
1543 for (;;) {
1544 next_state.step_index++;
1545 next_step = array_get(&self->steps, next_state.step_index);
1546 if (
1547 next_step->depth == PATTERN_DONE_MARKER ||
1548 next_step->depth <= step->depth
1549 ) break;
1550 }
1551 } else if (successor.state == parse_state) {
1552 continue;
1553 }
1554
1555 for (;;) {
1556 // Skip pass-through states. Although these states have alternatives, they are only
1557 // used to implement repetitions, and query analysis does not need to process
1558 // repetitions in order to determine whether steps are possible and definite.
1559 if (next_step->is_pass_through) {
1560 next_state.step_index++;
1561 next_step++;
1562 continue;
1563 }
1564
1565 // If the pattern is finished or hypothetical parent node is complete, then
1566 // record that matching can terminate at this step of the pattern. Otherwise,
1567 // add this state to the list of states to process on the next iteration.
1568 if (!next_step->is_dead_end) {
1569 bool did_finish_pattern = array_get(&self->steps, next_state.step_index)->depth != step->depth;
1570 if (did_finish_pattern) {
1571 array_insert_sorted_by(&analysis->finished_parent_symbols, , state->root_symbol);
1572 } else if (next_state.depth == 0) {
1573 array_insert_sorted_by(&analysis->final_step_indices, , next_state.step_index);
1574 } else {
1575 analysis_state_set__insert_sorted(&analysis->next_states, &analysis->state_pool, &next_state);
1576 }
1577 }
1578
1579 // If the state has advanced to a step with an alternative step, then add another state
1580 // at that alternative step. This process is simpler than the process of actually matching a
1581 // pattern during query execution, because for the purposes of query analysis, there is no
1582 // need to process repetitions.
1583 if (
1584 does_match &&
1585 next_step->alternative_index != NONE &&
1586 next_step->alternative_index > next_state.step_index
1587 ) {
1588 next_state.step_index = next_step->alternative_index;
1589 next_step = array_get(&self->steps, next_state.step_index);
1590 } else {
1591 break;
1592 }
1593 }
1594 }
1595 }
1596 }
1597
1598 AnalysisStateSet _states = analysis->states;
1599 analysis->states = analysis->next_states;
1600 analysis->next_states = _states;
1601 }
1602 }
1603
1604 static bool ts_query__analyze_patterns(TSQuery *self, unsigned *error_offset) {
1605 Array(uint16_t) non_rooted_pattern_start_steps = array_new();
1606 for (unsigned i = 0; i < self->pattern_map.size; i++) {
1607 PatternEntry *pattern = array_get(&self->pattern_map, i);
1608 if (!pattern->is_rooted) {
1609 QueryStep *step = array_get(&self->steps, pattern->step_index);
1610 if (step->symbol != WILDCARD_SYMBOL) {
1611 array_push(&non_rooted_pattern_start_steps, i);
1612 }
1613 }
1614 }
1615
1616 // Walk forward through all of the steps in the query, computing some
1617 // basic information about each step. Mark all of the steps that contain
1618 // captures, and record the indices of all of the steps that have child steps.
1619 Array(uint32_t) parent_step_indices = array_new();
1620 bool all_patterns_are_valid = true;
1621 for (unsigned i = 0; i < self->steps.size; i++) {
1622 QueryStep *step = array_get(&self->steps, i);
1623 if (step->depth == PATTERN_DONE_MARKER) {
1624 step->parent_pattern_guaranteed = true;
1625 step->root_pattern_guaranteed = true;
1626 continue;
1627 }
1628
1629 bool has_children = false;
1630 bool is_wildcard = step->symbol == WILDCARD_SYMBOL;
1631 step->contains_captures = step->capture_ids[0] != NONE;
1632 for (unsigned j = i + 1; j < self->steps.size; j++) {
1633 QueryStep *next_step = array_get(&self->steps, j);
1634 if (
1635 next_step->depth == PATTERN_DONE_MARKER ||
1636 next_step->depth <= step->depth
1637 ) break;
1638 if (next_step->capture_ids[0] != NONE) {
1639 step->contains_captures = true;
1640 }
1641 if (!is_wildcard) {
1642 next_step->root_pattern_guaranteed = true;
1643 next_step->parent_pattern_guaranteed = true;
1644 }
1645 has_children = true;
1646 }
1647
1648 if (has_children) {
1649 if (!is_wildcard) {
1650 array_push(&parent_step_indices, i);
1651 } else if (step->supertype_symbol && self->language->abi_version >= LANGUAGE_VERSION_WITH_RESERVED_WORDS) {
1652 // Look at the child steps to see if any aren't valid subtypes for this supertype.
1653 uint32_t subtype_length;
1654 const TSSymbol *subtypes = ts_language_subtypes(
1655 self->language,
1656 step->supertype_symbol,
1657 &subtype_length
1658 );
1659
1660 for (unsigned j = i + 1; j < self->steps.size; j++) {
1661 QueryStep *child_step = array_get(&self->steps, j);
1662 if (child_step->depth == PATTERN_DONE_MARKER || child_step->depth <= step->depth) {
1663 break;
1664 }
1665 if (child_step->depth == step->depth + 1 && child_step->symbol != WILDCARD_SYMBOL) {
1666 bool is_valid_subtype = false;
1667 for (uint32_t k = 0; k < subtype_length; k++) {
1668 if (child_step->symbol == subtypes[k]) {
1669 is_valid_subtype = true;
1670 break;
1671 }
1672 }
1673
1674 if (!is_valid_subtype) {
1675 for (unsigned offset_idx = 0; offset_idx < self->step_offsets.size; offset_idx++) {
1676 StepOffset *step_offset = array_get(&self->step_offsets, offset_idx);
1677 if (step_offset->step_index >= j) {
1678 *error_offset = step_offset->byte_offset;
1679 all_patterns_are_valid = false;
1680 goto supertype_cleanup;
1681 }
1682 }
1683 }
1684 }
1685 }
1686 }
1687 }
1688 }
1689
1690 // For every parent symbol in the query, initialize an 'analysis subgraph'.
1691 // This subgraph lists all of the states in the parse table that are directly
1692 // involved in building subtrees for this symbol.
1693 //
1694 // In addition to the parent symbols in the query, construct subgraphs for all
1695 // of the hidden symbols in the grammar, because these might occur within
1696 // one of the parent nodes, such that their children appear to belong to the
1697 // parent.
1698 AnalysisSubgraphArray subgraphs = array_new();
1699 for (unsigned i = 0; i < parent_step_indices.size; i++) {
1700 uint32_t parent_step_index = *array_get(&parent_step_indices, i);
1701 TSSymbol parent_symbol = array_get(&self->steps, parent_step_index)->symbol;
1702 AnalysisSubgraph subgraph = { .symbol = parent_symbol };
1703 array_insert_sorted_by(&subgraphs, .symbol, subgraph);
1704 }
1705 for (TSSymbol sym = (uint16_t)self->language->token_count; sym < (uint16_t)self->language->symbol_count; sym++) {
1706 if (!ts_language_symbol_metadata(self->language, sym).visible) {
1707 AnalysisSubgraph subgraph = { .symbol = sym };
1708 array_insert_sorted_by(&subgraphs, .symbol, subgraph);
1709 }
1710 }
1711
1712 // Scan the parse table to find the data needed to populate these subgraphs.
1713 // Collect three things during this scan:
1714 // 1) All of the parse states where one of these symbols can start.
1715 // 2) All of the parse states where one of these symbols can end, along
1716 // with information about the node that would be created.
1717 // 3) A list of predecessor states for each state.
1718 StatePredecessorMap predecessor_map = state_predecessor_map_new(self->language);
1719 for (TSStateId state = 1; state < (uint16_t)self->language->state_count; state++) {
1720 unsigned subgraph_index, exists;
1721 LookaheadIterator lookahead_iterator = ts_language_lookaheads(self->language, state);
1722 while (ts_lookahead_iterator__next(&lookahead_iterator)) {
1723 if (lookahead_iterator.action_count) {
1724 for (unsigned i = 0; i < lookahead_iterator.action_count; i++) {
1725 const TSParseAction *action = &lookahead_iterator.actions[i];
1726 if (action->type == TSParseActionTypeReduce) {
1727 const TSSymbol *aliases, *aliases_end;
1728 ts_language_aliases_for_symbol(
1729 self->language,
1730 action->reduce.symbol,
1731 &aliases,
1732 &aliases_end
1733 );
1734 for (const TSSymbol *symbol = aliases; symbol < aliases_end; symbol++) {
1735 array_search_sorted_by(
1736 &subgraphs,
1737 .symbol,
1738 *symbol,
1739 &subgraph_index,
1740 &exists
1741 );
1742 if (exists) {
1743 AnalysisSubgraph *subgraph = array_get(&subgraphs, subgraph_index);
1744 if (subgraph->nodes.size == 0 || array_back(&subgraph->nodes)->state != state) {
1745 array_push(&subgraph->nodes, ((AnalysisSubgraphNode) {
1746 .state = state,
1747 .production_id = action->reduce.production_id,
1748 .child_index = action->reduce.child_count,
1749 .done = true,
1750 }));
1751 }
1752 }
1753 }
1754 } else if (action->type == TSParseActionTypeShift && !action->shift.extra) {
1755 TSStateId next_state = action->shift.state;
1756 state_predecessor_map_add(&predecessor_map, next_state, state);
1757 }
1758 }
1759 } else if (lookahead_iterator.next_state != 0) {
1760 if (lookahead_iterator.next_state != state) {
1761 state_predecessor_map_add(&predecessor_map, lookahead_iterator.next_state, state);
1762 }
1763 if (ts_language_state_is_primary(self->language, state)) {
1764 const TSSymbol *aliases, *aliases_end;
1765 ts_language_aliases_for_symbol(
1766 self->language,
1767 lookahead_iterator.symbol,
1768 &aliases,
1769 &aliases_end
1770 );
1771 for (const TSSymbol *symbol = aliases; symbol < aliases_end; symbol++) {
1772 array_search_sorted_by(
1773 &subgraphs,
1774 .symbol,
1775 *symbol,
1776 &subgraph_index,
1777 &exists
1778 );
1779 if (exists) {
1780 AnalysisSubgraph *subgraph = array_get(&subgraphs, subgraph_index);
1781 if (
1782 subgraph->start_states.size == 0 ||
1783 *array_back(&subgraph->start_states) != state
1784 )
1785 array_push(&subgraph->start_states, state);
1786 }
1787 }
1788 }
1789 }
1790 }
1791 }
1792
1793 // For each subgraph, compute the preceding states by walking backward
1794 // from the end states using the predecessor map.
1795 Array(AnalysisSubgraphNode) next_nodes = array_new();
1796 for (unsigned i = 0; i < subgraphs.size; i++) {
1797 AnalysisSubgraph *subgraph = array_get(&subgraphs, i);
1798 if (subgraph->nodes.size == 0) {
1799 array_delete(&subgraph->start_states);
1800 array_erase(&subgraphs, i);
1801 i--;
1802 continue;
1803 }
1804 array_assign(&next_nodes, &subgraph->nodes);
1805 while (next_nodes.size > 0) {
1806 AnalysisSubgraphNode node = array_pop(&next_nodes);
1807 if (node.child_index > 1) {
1808 unsigned predecessor_count;
1809 const TSStateId *predecessors = state_predecessor_map_get(
1810 &predecessor_map,
1811 node.state,
1812 &predecessor_count
1813 );
1814 for (unsigned j = 0; j < predecessor_count; j++) {
1815 AnalysisSubgraphNode predecessor_node = {
1816 .state = predecessors[j],
1817 .child_index = node.child_index - 1,
1818 .production_id = node.production_id,
1819 .done = false,
1820 };
1821 unsigned index, exists;
1822 array_search_sorted_with(
1823 &subgraph->nodes, analysis_subgraph_node__compare, &predecessor_node,
1824 &index, &exists
1825 );
1826 if (!exists) {
1827 array_insert(&subgraph->nodes, index, predecessor_node);
1828 array_push(&next_nodes, predecessor_node);
1829 }
1830 }
1831 }
1832 }
1833 }
1834
1835 #ifdef DEBUG_ANALYZE_QUERY
1836 printf("\nSubgraphs:\n");
1837 for (unsigned i = 0; i < subgraphs.size; i++) {
1838 AnalysisSubgraph *subgraph = array_get(&subgraphs, i);
1839 printf(" %u, %s:\n", subgraph->symbol, ts_language_symbol_name(self->language, subgraph->symbol));
1840 for (unsigned j = 0; j < subgraph->start_states.size; j++) {
1841 printf(
1842 " {state: %u}\n",
1843 *array_get(&subgraph->start_states, j)
1844 );
1845 }
1846 for (unsigned j = 0; j < subgraph->nodes.size; j++) {
1847 AnalysisSubgraphNode *node = array_get(&subgraph->nodes, j);
1848 printf(
1849 " {state: %u, child_index: %u, production_id: %u, done: %d}\n",
1850 node->state, node->child_index, node->production_id, node->done
1851 );
1852 }
1853 printf("\n");
1854 }
1855 #endif
1856
1857 // For each non-terminal pattern, determine if the pattern can successfully match,
1858 // and identify all of the possible children within the pattern where matching could fail.
1859 QueryAnalysis analysis = query_analysis__new();
1860 for (unsigned i = 0; i < parent_step_indices.size; i++) {
1861 uint16_t parent_step_index = *array_get(&parent_step_indices, i);
1862 uint16_t parent_depth = array_get(&self->steps, parent_step_index)->depth;
1863 TSSymbol parent_symbol = array_get(&self->steps, parent_step_index)->symbol;
1864 if (parent_symbol == ts_builtin_sym_error) continue;
1865
1866 // Find the subgraph that corresponds to this pattern's root symbol. If the pattern's
1867 // root symbol is a terminal, then return an error.
1868 unsigned subgraph_index, exists;
1869 array_search_sorted_by(&subgraphs, .symbol, parent_symbol, &subgraph_index, &exists);
1870 if (!exists) {
1871 unsigned first_child_step_index = parent_step_index + 1;
1872 uint32_t j, child_exists;
1873 array_search_sorted_by(&self->step_offsets, .step_index, first_child_step_index, &j, &child_exists);
1874 ts_assert(child_exists);
1875 *error_offset = array_get(&self->step_offsets, j)->byte_offset;
1876 all_patterns_are_valid = false;
1877 break;
1878 }
1879
1880 // Initialize an analysis state at every parse state in the table where
1881 // this parent symbol can occur.
1882 AnalysisSubgraph *subgraph = array_get(&subgraphs, subgraph_index);
1883 analysis_state_set__clear(&analysis.states, &analysis.state_pool);
1884 analysis_state_set__clear(&analysis.deeper_states, &analysis.state_pool);
1885 for (unsigned j = 0; j < subgraph->start_states.size; j++) {
1886 TSStateId parse_state = *array_get(&subgraph->start_states, j);
1887 analysis_state_set__push(&analysis.states, &analysis.state_pool, &((AnalysisState) {
1888 .step_index = parent_step_index + 1,
1889 .stack = {
1890 [0] = {
1891 .parse_state = parse_state,
1892 .parent_symbol = parent_symbol,
1893 .child_index = 0,
1894 .field_id = 0,
1895 .done = false,
1896 },
1897 },
1898 .depth = 1,
1899 .root_symbol = parent_symbol,
1900 }));
1901 }
1902
1903 #ifdef DEBUG_ANALYZE_QUERY
1904 printf(
1905 "\nWalk states for %s:\n",
1906 ts_language_symbol_name(self->language, (*array_get(&analysis.states, 0))->stack[0].parent_symbol)
1907 );
1908 #endif
1909
1910 analysis.did_abort = false;
1911 ts_query__perform_analysis(self, &subgraphs, &analysis);
1912
1913 // If this pattern could not be fully analyzed, then every step should
1914 // be considered fallible.
1915 if (analysis.did_abort) {
1916 for (unsigned j = parent_step_index + 1; j < self->steps.size; j++) {
1917 QueryStep *step = array_get(&self->steps, j);
1918 if (
1919 step->depth <= parent_depth ||
1920 step->depth == PATTERN_DONE_MARKER
1921 ) break;
1922 if (!step->is_dead_end) {
1923 step->parent_pattern_guaranteed = false;
1924 step->root_pattern_guaranteed = false;
1925 }
1926 }
1927 continue;
1928 }
1929
1930 // If this pattern cannot match, store the pattern index so that it can be
1931 // returned to the caller.
1932 if (analysis.finished_parent_symbols.size == 0) {
1933 uint16_t impossible_step_index;
1934 if (analysis.final_step_indices.size > 0) {
1935 impossible_step_index = *array_back(&analysis.final_step_indices);
1936 } else {
1937 // If there isn't a final step, then that means the parent step itself is unreachable.
1938 impossible_step_index = parent_step_index;
1939 }
1940 uint32_t j, impossible_exists;
1941 array_search_sorted_by(&self->step_offsets, .step_index, impossible_step_index, &j, &impossible_exists);
1942 if (j >= self->step_offsets.size) j = self->step_offsets.size - 1;
1943 *error_offset = array_get(&self->step_offsets, j)->byte_offset;
1944 all_patterns_are_valid = false;
1945 break;
1946 }
1947
1948 // Mark as fallible any step where a match terminated.
1949 // Later, this property will be propagated to all of the step's predecessors.
1950 for (unsigned j = 0; j < analysis.final_step_indices.size; j++) {
1951 uint32_t final_step_index = *array_get(&analysis.final_step_indices, j);
1952 QueryStep *step = array_get(&self->steps, final_step_index);
1953 if (
1954 step->depth != PATTERN_DONE_MARKER &&
1955 step->depth > parent_depth &&
1956 !step->is_dead_end
1957 ) {
1958 step->parent_pattern_guaranteed = false;
1959 step->root_pattern_guaranteed = false;
1960 }
1961 }
1962 }
1963
1964 // Mark as indefinite any step with captures that are used in predicates.
1965 Array(uint16_t) predicate_capture_ids = array_new();
1966 for (unsigned i = 0; i < self->patterns.size; i++) {
1967 QueryPattern *pattern = array_get(&self->patterns, i);
1968
1969 // Gather all of the captures that are used in predicates for this pattern.
1970 array_clear(&predicate_capture_ids);
1971 for (
1972 unsigned start = pattern->predicate_steps.offset,
1973 end = start + pattern->predicate_steps.length,
1974 j = start; j < end; j++
1975 ) {
1976 TSQueryPredicateStep *step = array_get(&self->predicate_steps, j);
1977 if (step->type == TSQueryPredicateStepTypeCapture) {
1978 uint16_t value_id = step->value_id;
1979 array_insert_sorted_by(&predicate_capture_ids, , value_id);
1980 }
1981 }
1982
1983 // Find all of the steps that have these captures.
1984 for (
1985 unsigned start = pattern->steps.offset,
1986 end = start + pattern->steps.length,
1987 j = start; j < end; j++
1988 ) {
1989 QueryStep *step = array_get(&self->steps, j);
1990 for (unsigned k = 0; k < MAX_STEP_CAPTURE_COUNT; k++) {
1991 uint16_t capture_id = step->capture_ids[k];
1992 if (capture_id == NONE) break;
1993 unsigned index, exists;
1994 array_search_sorted_by(&predicate_capture_ids, , capture_id, &index, &exists);
1995 if (exists) {
1996 step->root_pattern_guaranteed = false;
1997 break;
1998 }
1999 }
2000 }
2001 }
2002
2003 // Propagate fallibility. If a pattern is fallible at a given step, then it is
2004 // fallible at all of its preceding steps.
2005 bool done = self->steps.size == 0;
2006 while (!done) {
2007 done = true;
2008 for (unsigned i = self->steps.size - 1; i > 0; i--) {
2009 QueryStep *step = array_get(&self->steps, i);
2010 if (step->depth == PATTERN_DONE_MARKER) continue;
2011
2012 // Determine if this step is definite or has definite alternatives.
2013 bool parent_pattern_guaranteed = false;
2014 for (;;) {
2015 if (step->root_pattern_guaranteed) {
2016 parent_pattern_guaranteed = true;
2017 break;
2018 }
2019 if (step->alternative_index == NONE || step->alternative_index < i) {
2020 break;
2021 }
2022 step = array_get(&self->steps, step->alternative_index);
2023 }
2024
2025 // If not, mark its predecessor as indefinite.
2026 if (!parent_pattern_guaranteed) {
2027 QueryStep *prev_step = array_get(&self->steps, i - 1);
2028 if (
2029 !prev_step->is_dead_end &&
2030 prev_step->depth != PATTERN_DONE_MARKER &&
2031 prev_step->root_pattern_guaranteed
2032 ) {
2033 prev_step->root_pattern_guaranteed = false;
2034 done = false;
2035 }
2036 }
2037 }
2038 }
2039
2040 #ifdef DEBUG_ANALYZE_QUERY
2041 printf("Steps:\n");
2042 for (unsigned i = 0; i < self->steps.size; i++) {
2043 QueryStep *step = array_get(&self->steps, i);
2044 if (step->depth == PATTERN_DONE_MARKER) {
2045 printf(" %u: DONE\n", i);
2046 } else {
2047 printf(
2048 " %u: {symbol: %s, field: %s, depth: %u, parent_pattern_guaranteed: %d, root_pattern_guaranteed: %d}\n",
2049 i,
2050 (step->symbol == WILDCARD_SYMBOL)
2051 ? "ANY"
2052 : ts_language_symbol_name(self->language, step->symbol),
2053 (step->field ? ts_language_field_name_for_id(self->language, step->field) : "-"),
2054 step->depth,
2055 step->parent_pattern_guaranteed,
2056 step->root_pattern_guaranteed
2057 );
2058 }
2059 }
2060 #endif
2061
2062 // Determine which repetition symbols in this language have the possibility
2063 // of matching non-rooted patterns in this query. These repetition symbols
2064 // prevent certain optimizations with range restrictions.
2065 analysis.did_abort = false;
2066 for (uint32_t i = 0; i < non_rooted_pattern_start_steps.size; i++) {
2067 uint16_t pattern_entry_index = *array_get(&non_rooted_pattern_start_steps, i);
2068 PatternEntry *pattern_entry = array_get(&self->pattern_map, pattern_entry_index);
2069
2070 analysis_state_set__clear(&analysis.states, &analysis.state_pool);
2071 analysis_state_set__clear(&analysis.deeper_states, &analysis.state_pool);
2072 for (unsigned j = 0; j < subgraphs.size; j++) {
2073 AnalysisSubgraph *subgraph = array_get(&subgraphs, j);
2074 TSSymbolMetadata metadata = ts_language_symbol_metadata(self->language, subgraph->symbol);
2075 if (metadata.visible || metadata.named) continue;
2076
2077 for (uint32_t k = 0; k < subgraph->start_states.size; k++) {
2078 TSStateId parse_state = *array_get(&subgraph->start_states, k);
2079 analysis_state_set__push(&analysis.states, &analysis.state_pool, &((AnalysisState) {
2080 .step_index = pattern_entry->step_index,
2081 .stack = {
2082 [0] = {
2083 .parse_state = parse_state,
2084 .parent_symbol = subgraph->symbol,
2085 .child_index = 0,
2086 .field_id = 0,
2087 .done = false,
2088 },
2089 },
2090 .root_symbol = subgraph->symbol,
2091 .depth = 1,
2092 }));
2093 }
2094 }
2095
2096 #ifdef DEBUG_ANALYZE_QUERY
2097 printf("\nWalk states for rootless pattern step %u:\n", pattern_entry->step_index);
2098 #endif
2099
2100 ts_query__perform_analysis(
2101 self,
2102 &subgraphs,
2103 &analysis
2104 );
2105
2106 if (analysis.finished_parent_symbols.size > 0) {
2107 array_get(&self->patterns, pattern_entry->pattern_index)->is_non_local = true;
2108 }
2109
2110 for (unsigned k = 0; k < analysis.finished_parent_symbols.size; k++) {
2111 TSSymbol symbol = *array_get(&analysis.finished_parent_symbols, k);
2112 array_insert_sorted_by(&self->repeat_symbols_with_rootless_patterns, , symbol);
2113 }
2114 }
2115
2116 #ifdef DEBUG_ANALYZE_QUERY
2117 if (self->repeat_symbols_with_rootless_patterns.size > 0) {
2118 printf("\nRepetition symbols with rootless patterns:\n");
2119 printf("aborted analysis: %d\n", analysis.did_abort);
2120 for (unsigned i = 0; i < self->repeat_symbols_with_rootless_patterns.size; i++) {
2121 TSSymbol symbol = *array_get(&self->repeat_symbols_with_rootless_patterns, i);
2122 printf(" %u, %s\n", symbol, ts_language_symbol_name(self->language, symbol));
2123 }
2124 printf("\n");
2125 }
2126 #endif
2127
2128 // Cleanup
2129 for (unsigned i = 0; i < subgraphs.size; i++) {
2130 array_delete(&array_get(&subgraphs, i)->start_states);
2131 array_delete(&array_get(&subgraphs, i)->nodes);
2132 }
2133 array_delete(&subgraphs);
2134 query_analysis__delete(&analysis);
2135 array_delete(&next_nodes);
2136 array_delete(&predicate_capture_ids);
2137 state_predecessor_map_delete(&predecessor_map);
2138
2139 supertype_cleanup:
2140 array_delete(&non_rooted_pattern_start_steps);
2141 array_delete(&parent_step_indices);
2142
2143 return all_patterns_are_valid;
2144 }
2145
2146 static void ts_query__add_negated_fields(
2147 TSQuery *self,
2148 uint16_t step_index,
2149 TSFieldId *field_ids,
2150 uint16_t field_count
2151 ) {
2152 QueryStep *step = array_get(&self->steps, step_index);
2153
2154 // The negated field array stores a list of field lists, separated by zeros.
2155 // Try to find the start index of an existing list that matches this new list.
2156 bool failed_match = false;
2157 unsigned match_count = 0;
2158 unsigned start_i = 0;
2159 for (unsigned i = 0; i < self->negated_fields.size; i++) {
2160 TSFieldId existing_field_id = *array_get(&self->negated_fields, i);
2161
2162 // At each zero value, terminate the match attempt. If we've exactly
2163 // matched the new field list, then reuse this index. Otherwise,
2164 // start over the matching process.
2165 if (existing_field_id == 0) {
2166 if (match_count == field_count) {
2167 step->negated_field_list_id = start_i;
2168 return;
2169 } else {
2170 start_i = i + 1;
2171 match_count = 0;
2172 failed_match = false;
2173 }
2174 }
2175
2176 // If the existing list matches our new list so far, then advance
2177 // to the next element of the new list.
2178 else if (
2179 match_count < field_count &&
2180 existing_field_id == field_ids[match_count] &&
2181 !failed_match
2182 ) {
2183 match_count++;
2184 }
2185
2186 // Otherwise, this existing list has failed to match.
2187 else {
2188 match_count = 0;
2189 failed_match = true;
2190 }
2191 }
2192
2193 step->negated_field_list_id = self->negated_fields.size;
2194 array_extend(&self->negated_fields, field_count, field_ids);
2195 array_push(&self->negated_fields, 0);
2196 }
2197
2198 static TSQueryError ts_query__parse_string_literal(
2199 TSQuery *self,
2200 Stream *stream
2201 ) {
2202 const char *string_start = stream->input;
2203 if (stream->next != '"') return TSQueryErrorSyntax;
2204 stream_advance(stream);
2205 const char *prev_position = stream->input;
2206
2207 bool is_escaped = false;
2208 array_clear(&self->string_buffer);
2209 for (;;) {
2210 if (is_escaped) {
2211 is_escaped = false;
2212 switch (stream->next) {
2213 case 'n':
2214 array_push(&self->string_buffer, '\n');
2215 break;
2216 case 'r':
2217 array_push(&self->string_buffer, '\r');
2218 break;
2219 case 't':
2220 array_push(&self->string_buffer, '\t');
2221 break;
2222 case '0':
2223 array_push(&self->string_buffer, '\0');
2224 break;
2225 default:
2226 array_extend(&self->string_buffer, stream->next_size, stream->input);
2227 break;
2228 }
2229 prev_position = stream->input + stream->next_size;
2230 } else {
2231 if (stream->next == '\\') {
2232 array_extend(&self->string_buffer, (uint32_t)(stream->input - prev_position), prev_position);
2233 prev_position = stream->input + 1;
2234 is_escaped = true;
2235 } else if (stream->next == '"') {
2236 array_extend(&self->string_buffer, (uint32_t)(stream->input - prev_position), prev_position);
2237 stream_advance(stream);
2238 return TSQueryErrorNone;
2239 } else if (stream->next == '\n') {
2240 stream_reset(stream, string_start);
2241 return TSQueryErrorSyntax;
2242 }
2243 }
2244 if (!stream_advance(stream)) {
2245 stream_reset(stream, string_start);
2246 return TSQueryErrorSyntax;
2247 }
2248 }
2249 }
2250
2251 // Parse a single predicate associated with a pattern, adding it to the
2252 // query's internal `predicate_steps` array. Predicates are arbitrary
2253 // S-expressions associated with a pattern which are meant to be handled at
2254 // a higher level of abstraction, such as the Rust/JavaScript bindings. They
2255 // can contain '@'-prefixed capture names, double-quoted strings, and bare
2256 // symbols, which also represent strings.
2257 static TSQueryError ts_query__parse_predicate(
2258 TSQuery *self,
2259 Stream *stream
2260 ) {
2261 if (!stream_is_ident_start(stream)) return TSQueryErrorSyntax;
2262 const char *predicate_name = stream->input;
2263 stream_scan_identifier(stream);
2264 if (stream->next != '?' && stream->next != '!') {
2265 return TSQueryErrorSyntax;
2266 }
2267 stream_advance(stream);
2268 uint32_t length = (uint32_t)(stream->input - predicate_name);
2269 uint16_t id = symbol_table_insert_name(
2270 &self->predicate_values,
2271 predicate_name,
2272 length
2273 );
2274 array_push(&self->predicate_steps, ((TSQueryPredicateStep) {
2275 .type = TSQueryPredicateStepTypeString,
2276 .value_id = id,
2277 }));
2278 stream_skip_whitespace(stream);
2279
2280 for (;;) {
2281 if (stream->next == ')') {
2282 stream_advance(stream);
2283 stream_skip_whitespace(stream);
2284 array_push(&self->predicate_steps, ((TSQueryPredicateStep) {
2285 .type = TSQueryPredicateStepTypeDone,
2286 .value_id = 0,
2287 }));
2288 break;
2289 }
2290
2291 // Parse an '@'-prefixed capture name
2292 else if (stream->next == '@') {
2293 stream_advance(stream);
2294
2295 // Parse the capture name
2296 if (!stream_is_ident_start(stream)) return TSQueryErrorSyntax;
2297 const char *capture_name = stream->input;
2298 stream_scan_identifier(stream);
2299 uint32_t capture_length = (uint32_t)(stream->input - capture_name);
2300
2301 // Add the capture id to the first step of the pattern
2302 int capture_id = symbol_table_id_for_name(
2303 &self->captures,
2304 capture_name,
2305 capture_length
2306 );
2307 if (capture_id == -1) {
2308 stream_reset(stream, capture_name);
2309 return TSQueryErrorCapture;
2310 }
2311
2312 array_push(&self->predicate_steps, ((TSQueryPredicateStep) {
2313 .type = TSQueryPredicateStepTypeCapture,
2314 .value_id = capture_id,
2315 }));
2316 }
2317
2318 // Parse a string literal
2319 else if (stream->next == '"') {
2320 TSQueryError e = ts_query__parse_string_literal(self, stream);
2321 if (e) return e;
2322 uint16_t query_id = symbol_table_insert_name(
2323 &self->predicate_values,
2324 self->string_buffer.contents,
2325 self->string_buffer.size
2326 );
2327 array_push(&self->predicate_steps, ((TSQueryPredicateStep) {
2328 .type = TSQueryPredicateStepTypeString,
2329 .value_id = query_id,
2330 }));
2331 }
2332
2333 // Parse a bare symbol
2334 else if (stream_is_ident_start(stream)) {
2335 const char *symbol_start = stream->input;
2336 stream_scan_identifier(stream);
2337 uint32_t symbol_length = (uint32_t)(stream->input - symbol_start);
2338 uint16_t query_id = symbol_table_insert_name(
2339 &self->predicate_values,
2340 symbol_start,
2341 symbol_length
2342 );
2343 array_push(&self->predicate_steps, ((TSQueryPredicateStep) {
2344 .type = TSQueryPredicateStepTypeString,
2345 .value_id = query_id,
2346 }));
2347 }
2348
2349 else {
2350 return TSQueryErrorSyntax;
2351 }
2352
2353 stream_skip_whitespace(stream);
2354 }
2355
2356 return 0;
2357 }
2358
2359 // Read one S-expression pattern from the stream, and incorporate it into
2360 // the query's internal state machine representation. For nested patterns,
2361 // this function calls itself recursively.
2362 //
2363 // The caller is responsible for passing in a dedicated CaptureQuantifiers.
2364 // These should not be shared between different calls to ts_query__parse_pattern!
2365 static TSQueryError ts_query__parse_pattern(
2366 TSQuery *self,
2367 Stream *stream,
2368 uint32_t depth,
2369 bool is_immediate,
2370 bool is_inside_alternation,
2371 CaptureQuantifiers *capture_quantifiers
2372 ) {
2373 if (stream->next == 0) return TSQueryErrorSyntax;
2374 if (stream->next == ')' || stream->next == ']') return PARENT_DONE;
2375
2376 const uint32_t starting_step_index = self->steps.size;
2377
2378 // Store the byte offset of each step in the query.
2379 if (
2380 self->step_offsets.size == 0 ||
2381 array_back(&self->step_offsets)->step_index != starting_step_index
2382 ) {
2383 array_push(&self->step_offsets, ((StepOffset) {
2384 .step_index = starting_step_index,
2385 .byte_offset = stream_offset(stream),
2386 }));
2387 }
2388
2389 // An open bracket is the start of an alternation.
2390 if (stream->next == '[') {
2391 stream_advance(stream);
2392 stream_skip_whitespace(stream);
2393
2394 // Parse each branch, and add a placeholder step in between the branches.
2395 Array(uint32_t) branch_step_indices = array_new();
2396 CaptureQuantifiers branch_capture_quantifiers = capture_quantifiers_new();
2397 for (;;) {
2398 uint32_t start_index = self->steps.size;
2399 TSQueryError e = ts_query__parse_pattern(
2400 self,
2401 stream,
2402 depth,
2403 is_immediate,
2404 true,
2405 &branch_capture_quantifiers
2406 );
2407
2408 if (e == PARENT_DONE) {
2409 if (stream->next == ']' && branch_step_indices.size > 0) {
2410 stream_advance(stream);
2411 break;
2412 }
2413 e = TSQueryErrorSyntax;
2414 }
2415 if (e) {
2416 capture_quantifiers_delete(&branch_capture_quantifiers);
2417 array_delete(&branch_step_indices);
2418 return e;
2419 }
2420
2421 if (start_index == starting_step_index) {
2422 capture_quantifiers_replace(capture_quantifiers, &branch_capture_quantifiers);
2423 } else {
2424 capture_quantifiers_join_all(capture_quantifiers, &branch_capture_quantifiers);
2425 }
2426
2427 array_push(&branch_step_indices, start_index);
2428 array_push(&self->steps, query_step__new(0, depth, false));
2429 capture_quantifiers_clear(&branch_capture_quantifiers);
2430 }
2431 (void)array_pop(&self->steps);
2432
2433 // For all of the branches except for the last one, add the subsequent branch as an
2434 // alternative, and link the end of the branch to the current end of the steps.
2435 for (unsigned i = 0; i < branch_step_indices.size - 1; i++) {
2436 uint32_t step_index = *array_get(&branch_step_indices, i);
2437 uint32_t next_step_index = *array_get(&branch_step_indices, i + 1);
2438 QueryStep *start_step = array_get(&self->steps, step_index);
2439 QueryStep *end_step = array_get(&self->steps, next_step_index - 1);
2440 start_step->alternative_index = next_step_index;
2441 end_step->alternative_index = self->steps.size;
2442 end_step->is_dead_end = true;
2443 }
2444
2445 capture_quantifiers_delete(&branch_capture_quantifiers);
2446 array_delete(&branch_step_indices);
2447 }
2448
2449 // An open parenthesis can be the start of three possible constructs:
2450 // * A grouped sequence
2451 // * A predicate
2452 // * A named node
2453 else if (stream->next == '(') {
2454 stream_advance(stream);
2455 stream_skip_whitespace(stream);
2456
2457 // If this parenthesis is followed by a node, then it represents a grouped sequence.
2458 if (stream->next == '(' || stream->next == '"' || stream->next == '[') {
2459 bool child_is_immediate = is_immediate;
2460 CaptureQuantifiers child_capture_quantifiers = capture_quantifiers_new();
2461 for (;;) {
2462 if (stream->next == '.') {
2463 child_is_immediate = true;
2464 stream_advance(stream);
2465 stream_skip_whitespace(stream);
2466 }
2467 TSQueryError e = ts_query__parse_pattern(
2468 self,
2469 stream,
2470 depth,
2471 child_is_immediate,
2472 is_inside_alternation,
2473 &child_capture_quantifiers
2474 );
2475 if (e == PARENT_DONE) {
2476 if (stream->next == ')') {
2477 stream_advance(stream);
2478 break;
2479 }
2480 e = TSQueryErrorSyntax;
2481 }
2482 if (e) {
2483 capture_quantifiers_delete(&child_capture_quantifiers);
2484 return e;
2485 }
2486
2487 capture_quantifiers_add_all(capture_quantifiers, &child_capture_quantifiers);
2488 capture_quantifiers_clear(&child_capture_quantifiers);
2489 child_is_immediate = false;
2490 }
2491
2492 capture_quantifiers_delete(&child_capture_quantifiers);
2493 }
2494
2495 // A dot/pound character indicates the start of a predicate.
2496 else if (stream->next == '.' || stream->next == '#') {
2497 stream_advance(stream);
2498 return ts_query__parse_predicate(self, stream);
2499 }
2500
2501 // Otherwise, this parenthesis is the start of a named node.
2502 else {
2503 TSSymbol symbol;
2504 bool is_missing = false;
2505 const char *node_name = stream->input;
2506
2507 // Parse a normal node name
2508 if (stream_is_ident_start(stream)) {
2509 stream_scan_identifier(stream);
2510 uint32_t length = (uint32_t)(stream->input - node_name);
2511
2512 // Parse the wildcard symbol
2513 if (length == 1 && node_name[0] == '_') {
2514 symbol = WILDCARD_SYMBOL;
2515 } else if (!strncmp(node_name, "MISSING", length)) {
2516 is_missing = true;
2517 stream_skip_whitespace(stream);
2518
2519 if (stream_is_ident_start(stream)) {
2520 const char *missing_node_name = stream->input;
2521 stream_scan_identifier(stream);
2522 uint32_t missing_node_length = (uint32_t)(stream->input - missing_node_name);
2523 symbol = ts_language_symbol_for_name(
2524 self->language,
2525 missing_node_name,
2526 missing_node_length,
2527 true
2528 );
2529 if (!symbol) {
2530 stream_reset(stream, missing_node_name);
2531 return TSQueryErrorNodeType;
2532 }
2533 }
2534
2535 else if (stream->next == '"') {
2536 const char *string_start = stream->input;
2537 TSQueryError e = ts_query__parse_string_literal(self, stream);
2538 if (e) return e;
2539
2540 symbol = ts_language_symbol_for_name(
2541 self->language,
2542 self->string_buffer.contents,
2543 self->string_buffer.size,
2544 false
2545 );
2546 if (!symbol) {
2547 stream_reset(stream, string_start + 1);
2548 return TSQueryErrorNodeType;
2549 }
2550 }
2551
2552 else if (stream->next == ')') {
2553 symbol = WILDCARD_SYMBOL;
2554 }
2555
2556 else {
2557 stream_reset(stream, stream->input);
2558 return TSQueryErrorSyntax;
2559 }
2560 }
2561
2562 else {
2563 symbol = ts_language_symbol_for_name(
2564 self->language,
2565 node_name,
2566 length,
2567 true
2568 );
2569 if (!symbol) {
2570 stream_reset(stream, node_name);
2571 return TSQueryErrorNodeType;
2572 }
2573 }
2574 } else {
2575 return TSQueryErrorSyntax;
2576 }
2577
2578 // Add a step for the node.
2579 array_push(&self->steps, query_step__new(symbol, depth, is_immediate));
2580 QueryStep *step = array_back(&self->steps);
2581 if (ts_language_symbol_metadata(self->language, symbol).supertype) {
2582 step->supertype_symbol = step->symbol;
2583 step->symbol = WILDCARD_SYMBOL;
2584 }
2585 if (is_missing) {
2586 step->is_missing = true;
2587 }
2588 if (symbol == WILDCARD_SYMBOL) {
2589 step->is_named = true;
2590 }
2591
2592 // Parse a supertype symbol
2593 if (stream->next == '/') {
2594 if (!step->supertype_symbol) {
2595 stream_reset(stream, node_name - 1); // reset to the start of the node
2596 return TSQueryErrorStructure;
2597 }
2598
2599 stream_advance(stream);
2600
2601 const char *subtype_node_name = stream->input;
2602
2603 if (stream_is_ident_start(stream)) { // Named node
2604 stream_scan_identifier(stream);
2605 uint32_t length = (uint32_t)(stream->input - subtype_node_name);
2606 step->symbol = ts_language_symbol_for_name(
2607 self->language,
2608 subtype_node_name,
2609 length,
2610 true
2611 );
2612 } else if (stream->next == '"') { // Anonymous leaf node
2613 TSQueryError e = ts_query__parse_string_literal(self, stream);
2614 if (e) return e;
2615 step->symbol = ts_language_symbol_for_name(
2616 self->language,
2617 self->string_buffer.contents,
2618 self->string_buffer.size,
2619 false
2620 );
2621 } else {
2622 return TSQueryErrorSyntax;
2623 }
2624
2625 if (!step->symbol) {
2626 stream_reset(stream, subtype_node_name);
2627 return TSQueryErrorNodeType;
2628 }
2629
2630 // Get all the possible subtypes for the given supertype,
2631 // and check if the given subtype is valid.
2632 if (self->language->abi_version >= LANGUAGE_VERSION_WITH_RESERVED_WORDS) {
2633 uint32_t subtype_length;
2634 const TSSymbol *subtypes = ts_language_subtypes(
2635 self->language,
2636 step->supertype_symbol,
2637 &subtype_length
2638 );
2639
2640 bool subtype_is_valid = false;
2641 for (uint32_t i = 0; i < subtype_length; i++) {
2642 if (subtypes[i] == step->symbol) {
2643 subtype_is_valid = true;
2644 break;
2645 }
2646 }
2647
2648 // This subtype is not valid for the given supertype.
2649 if (!subtype_is_valid) {
2650 stream_reset(stream, node_name - 1); // reset to the start of the node
2651 return TSQueryErrorStructure;
2652 }
2653 }
2654 }
2655
2656 stream_skip_whitespace(stream);
2657
2658 // Parse the child patterns
2659 bool child_is_immediate = false;
2660 uint16_t last_child_step_index = 0;
2661 uint16_t negated_field_count = 0;
2662 TSFieldId negated_field_ids[MAX_NEGATED_FIELD_COUNT];
2663 CaptureQuantifiers child_capture_quantifiers = capture_quantifiers_new();
2664 for (;;) {
2665 // Parse a negated field assertion
2666 if (stream->next == '!') {
2667 stream_advance(stream);
2668 stream_skip_whitespace(stream);
2669 if (!stream_is_ident_start(stream)) {
2670 capture_quantifiers_delete(&child_capture_quantifiers);
2671 return TSQueryErrorSyntax;
2672 }
2673 const char *field_name = stream->input;
2674 stream_scan_identifier(stream);
2675 uint32_t length = (uint32_t)(stream->input - field_name);
2676 stream_skip_whitespace(stream);
2677
2678 TSFieldId field_id = ts_language_field_id_for_name(
2679 self->language,
2680 field_name,
2681 length
2682 );
2683 if (!field_id) {
2684 stream->input = field_name;
2685 capture_quantifiers_delete(&child_capture_quantifiers);
2686 return TSQueryErrorField;
2687 }
2688
2689 // Keep the field ids sorted.
2690 if (negated_field_count < MAX_NEGATED_FIELD_COUNT) {
2691 negated_field_ids[negated_field_count] = field_id;
2692 negated_field_count++;
2693 }
2694
2695 continue;
2696 }
2697
2698 // Parse a sibling anchor
2699 if (stream->next == '.') {
2700 child_is_immediate = true;
2701 stream_advance(stream);
2702 stream_skip_whitespace(stream);
2703 }
2704
2705 uint16_t step_index = self->steps.size;
2706 TSQueryError e = ts_query__parse_pattern(
2707 self,
2708 stream,
2709 depth + 1,
2710 child_is_immediate,
2711 is_inside_alternation,
2712 &child_capture_quantifiers
2713 );
2714 // In the event we only parsed a predicate, meaning no new steps were added,
2715 // then subtract one so we're not indexing past the end of the array
2716 if (step_index == self->steps.size) step_index--;
2717 if (e == PARENT_DONE) {
2718 if (stream->next == ')') {
2719 if (child_is_immediate) {
2720 if (last_child_step_index == 0) {
2721 capture_quantifiers_delete(&child_capture_quantifiers);
2722 return TSQueryErrorSyntax;
2723 }
2724 // Mark this step *and* its alternatives as the last child of the parent.
2725 QueryStep *last_child_step = array_get(&self->steps, last_child_step_index);
2726 last_child_step->is_last_child = true;
2727 if (
2728 last_child_step->alternative_index != NONE &&
2729 last_child_step->alternative_index < self->steps.size
2730 ) {
2731 QueryStep *alternative_step = array_get(&self->steps, last_child_step->alternative_index);
2732 alternative_step->is_last_child = true;
2733 while (
2734 alternative_step->alternative_index != NONE &&
2735 alternative_step->alternative_index < self->steps.size
2736 ) {
2737 alternative_step = array_get(&self->steps, alternative_step->alternative_index);
2738 alternative_step->is_last_child = true;
2739 }
2740 }
2741 }
2742
2743 if (negated_field_count) {
2744 ts_query__add_negated_fields(
2745 self,
2746 starting_step_index,
2747 negated_field_ids,
2748 negated_field_count
2749 );
2750 }
2751
2752 stream_advance(stream);
2753 break;
2754 }
2755 e = TSQueryErrorSyntax;
2756 }
2757 if (e) {
2758 capture_quantifiers_delete(&child_capture_quantifiers);
2759 return e;
2760 }
2761
2762 capture_quantifiers_add_all(capture_quantifiers, &child_capture_quantifiers);
2763
2764 last_child_step_index = step_index;
2765 child_is_immediate = false;
2766 capture_quantifiers_clear(&child_capture_quantifiers);
2767 }
2768 capture_quantifiers_delete(&child_capture_quantifiers);
2769 }
2770 }
2771
2772 // Parse a wildcard pattern
2773 else if (stream->next == '_') {
2774 stream_advance(stream);
2775 stream_skip_whitespace(stream);
2776
2777 // Add a step that matches any kind of node
2778 array_push(&self->steps, query_step__new(WILDCARD_SYMBOL, depth, is_immediate));
2779 }
2780
2781 // Parse a double-quoted anonymous leaf node expression
2782 else if (stream->next == '"') {
2783 const char *string_start = stream->input;
2784 TSQueryError e = ts_query__parse_string_literal(self, stream);
2785 if (e) return e;
2786
2787 // Add a step for the node
2788 TSSymbol symbol = ts_language_symbol_for_name(
2789 self->language,
2790 self->string_buffer.contents,
2791 self->string_buffer.size,
2792 false
2793 );
2794 if (!symbol) {
2795 stream_reset(stream, string_start + 1);
2796 return TSQueryErrorNodeType;
2797 }
2798 array_push(&self->steps, query_step__new(symbol, depth, is_immediate));
2799 }
2800
2801 // Parse a field-prefixed pattern
2802 else if (stream_is_ident_start(stream)) {
2803 // Parse the field name
2804 const char *field_name = stream->input;
2805 stream_scan_identifier(stream);
2806 uint32_t length = (uint32_t)(stream->input - field_name);
2807 stream_skip_whitespace(stream);
2808
2809 if (stream->next != ':') {
2810 stream_reset(stream, field_name);
2811 return TSQueryErrorSyntax;
2812 }
2813 stream_advance(stream);
2814 stream_skip_whitespace(stream);
2815
2816 // Parse the pattern
2817 CaptureQuantifiers field_capture_quantifiers = capture_quantifiers_new();
2818 TSQueryError e = ts_query__parse_pattern(
2819 self,
2820 stream,
2821 depth,
2822 is_immediate,
2823 is_inside_alternation,
2824 &field_capture_quantifiers
2825 );
2826 if (e) {
2827 capture_quantifiers_delete(&field_capture_quantifiers);
2828 if (e == PARENT_DONE) e = TSQueryErrorSyntax;
2829 return e;
2830 }
2831
2832 // Add the field name to the first step of the pattern
2833 TSFieldId field_id = ts_language_field_id_for_name(
2834 self->language,
2835 field_name,
2836 length
2837 );
2838 if (!field_id) {
2839 stream->input = field_name;
2840 return TSQueryErrorField;
2841 }
2842
2843 uint32_t step_index = starting_step_index;
2844 QueryStep *step = array_get(&self->steps, step_index);
2845 for (;;) {
2846 step->field = field_id;
2847 if (
2848 step->alternative_index != NONE &&
2849 step->alternative_index > step_index &&
2850 step->alternative_index < self->steps.size
2851 ) {
2852 step_index = step->alternative_index;
2853 step = array_get(&self->steps, step_index);
2854 } else {
2855 break;
2856 }
2857 }
2858
2859 capture_quantifiers_add_all(capture_quantifiers, &field_capture_quantifiers);
2860 capture_quantifiers_delete(&field_capture_quantifiers);
2861 }
2862
2863 else {
2864 return TSQueryErrorSyntax;
2865 }
2866
2867 stream_skip_whitespace(stream);
2868
2869 // Parse suffixes modifiers for this pattern
2870 TSQuantifier quantifier = TSQuantifierOne;
2871 for (;;) {
2872 // Parse the one-or-more operator.
2873 if (stream->next == '+') {
2874 quantifier = quantifier_join(TSQuantifierOneOrMore, quantifier);
2875
2876 stream_advance(stream);
2877 stream_skip_whitespace(stream);
2878 }
2879
2880 // Parse the zero-or-more repetition operator.
2881 else if (stream->next == '*') {
2882 quantifier = quantifier_join(TSQuantifierZeroOrMore, quantifier);
2883
2884 stream_advance(stream);
2885 stream_skip_whitespace(stream);
2886 }
2887
2888 // Parse the optional operator.
2889 else if (stream->next == '?') {
2890 quantifier = quantifier_join(TSQuantifierZeroOrOne, quantifier);
2891
2892 stream_advance(stream);
2893 stream_skip_whitespace(stream);
2894 }
2895
2896 // Parse an '@'-prefixed capture pattern
2897 else if (stream->next == '@') {
2898 stream_advance(stream);
2899 if (!stream_is_ident_start(stream)) return TSQueryErrorSyntax;
2900 const char *capture_name = stream->input;
2901 stream_scan_identifier(stream);
2902 uint32_t length = (uint32_t)(stream->input - capture_name);
2903 stream_skip_whitespace(stream);
2904
2905 // Add the capture id to the first step of the pattern
2906 uint16_t capture_id = symbol_table_insert_name(
2907 &self->captures,
2908 capture_name,
2909 length
2910 );
2911
2912 // Add the capture quantifier
2913 capture_quantifiers_add_for_id(capture_quantifiers, capture_id, TSQuantifierOne);
2914
2915 uint32_t step_index = starting_step_index;
2916 for (;;) {
2917 QueryStep *step = array_get(&self->steps, step_index);
2918 query_step__add_capture(step, capture_id);
2919 if (
2920 step->alternative_index != NONE &&
2921 step->alternative_index > step_index &&
2922 step->alternative_index < self->steps.size
2923 ) {
2924 step_index = step->alternative_index;
2925 } else {
2926 break;
2927 }
2928 }
2929 }
2930
2931 // No more suffix modifiers
2932 else {
2933 break;
2934 }
2935 }
2936
2937 QueryStep repeat_step;
2938 QueryStep *step;
2939 switch (quantifier) {
2940 case TSQuantifierOneOrMore:
2941 repeat_step = query_step__new(WILDCARD_SYMBOL, depth, false);
2942 repeat_step.is_inside_alternation = is_inside_alternation;
2943 repeat_step.alternative_index = starting_step_index;
2944 repeat_step.is_pass_through = true;
2945 array_push(&self->steps, repeat_step);
2946 break;
2947 case TSQuantifierZeroOrMore:
2948 repeat_step = query_step__new(WILDCARD_SYMBOL, depth, false);
2949 repeat_step.is_inside_alternation = is_inside_alternation;
2950 repeat_step.alternative_index = starting_step_index;
2951 repeat_step.is_pass_through = true;
2952 array_push(&self->steps, repeat_step);
2953
2954 // Stop when `step->alternative_index` is `NONE` or it points to
2955 // `repeat_step` or beyond. Note that having just been pushed,
2956 // `repeat_step` occupies slot `self->steps.size - 1`.
2957 step = array_get(&self->steps, starting_step_index);
2958 while (step->alternative_index != NONE && step->alternative_index < self->steps.size - 1) {
2959 step = array_get(&self->steps, step->alternative_index);
2960 }
2961 step->alternative_index = self->steps.size;
2962 break;
2963 case TSQuantifierZeroOrOne:
2964 step = array_get(&self->steps, starting_step_index);
2965 while (step->alternative_index != NONE && step->alternative_index < self->steps.size) {
2966 step = array_get(&self->steps, step->alternative_index);
2967 }
2968 step->alternative_index = self->steps.size;
2969 break;
2970 default:
2971 break;
2972 }
2973
2974 capture_quantifiers_mul(capture_quantifiers, quantifier);
2975
2976 return 0;
2977 }
2978
2979 TSQuery *ts_query_new(
2980 const TSLanguage *language,
2981 const char *source,
2982 uint32_t source_len,
2983 uint32_t *error_offset,
2984 TSQueryError *error_type
2985 ) {
2986 if (
2987 !language ||
2988 language->abi_version > TREE_SITTER_LANGUAGE_VERSION ||
2989 language->abi_version < TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION
2990 ) {
2991 *error_type = TSQueryErrorLanguage;
2992 return NULL;
2993 }
2994
2995 TSQuery *self = ts_malloc(sizeof(TSQuery));
2996 *self = (TSQuery) {
2997 .steps = array_new(),
2998 .pattern_map = array_new(),
2999 .captures = symbol_table_new(),
3000 .capture_quantifiers = array_new(),
3001 .predicate_values = symbol_table_new(),
3002 .predicate_steps = array_new(),
3003 .patterns = array_new(),
3004 .step_offsets = array_new(),
3005 .string_buffer = array_new(),
3006 .negated_fields = array_new(),
3007 .repeat_symbols_with_rootless_patterns = array_new(),
3008 .wildcard_root_pattern_count = 0,
3009 .language = ts_language_copy(language),
3010 };
3011
3012 array_push(&self->negated_fields, 0);
3013
3014 // Parse all of the S-expressions in the given string.
3015 Stream stream = stream_new(source, source_len);
3016 stream_skip_whitespace(&stream);
3017 while (stream.input < stream.end) {
3018 uint32_t pattern_index = self->patterns.size;
3019 uint32_t start_step_index = self->steps.size;
3020 uint32_t start_predicate_step_index = self->predicate_steps.size;
3021 array_push(&self->patterns, ((QueryPattern) {
3022 .steps = (Slice) {.offset = start_step_index},
3023 .predicate_steps = (Slice) {.offset = start_predicate_step_index},
3024 .start_byte = stream_offset(&stream),
3025 .is_non_local = false,
3026 }));
3027 CaptureQuantifiers capture_quantifiers = capture_quantifiers_new();
3028 *error_type = ts_query__parse_pattern(self, &stream, 0, false, false, &capture_quantifiers);
3029 array_push(&self->steps, query_step__new(0, PATTERN_DONE_MARKER, false));
3030
3031 QueryPattern *pattern = array_back(&self->patterns);
3032 pattern->steps.length = self->steps.size - start_step_index;
3033 pattern->predicate_steps.length = self->predicate_steps.size - start_predicate_step_index;
3034 pattern->end_byte = stream_offset(&stream);
3035
3036 // If any pattern could not be parsed, then report the error information
3037 // and terminate.
3038 if (*error_type) {
3039 if (*error_type == PARENT_DONE) *error_type = TSQueryErrorSyntax;
3040 *error_offset = stream_offset(&stream);
3041 capture_quantifiers_delete(&capture_quantifiers);
3042 ts_query_delete(self);
3043 return NULL;
3044 }
3045
3046 // Maintain a list of capture quantifiers for each pattern
3047 array_push(&self->capture_quantifiers, capture_quantifiers);
3048
3049 // Maintain a map that can look up patterns for a given root symbol.
3050 uint16_t wildcard_root_alternative_index = NONE;
3051 for (;;) {
3052 QueryStep *step = array_get(&self->steps, start_step_index);
3053
3054 // If a pattern has a wildcard at its root, but it has a non-wildcard child,
3055 // then optimize the matching process by skipping matching the wildcard.
3056 // Later, during the matching process, the query cursor will check that
3057 // there is a parent node, and capture it if necessary.
3058 if (step->symbol == WILDCARD_SYMBOL && step->depth == 0 && !step->field) {
3059 QueryStep *second_step = array_get(&self->steps, start_step_index + 1);
3060 if (second_step->symbol != WILDCARD_SYMBOL && second_step->depth == 1 && !second_step->is_immediate) {
3061 wildcard_root_alternative_index = step->alternative_index;
3062 start_step_index += 1;
3063 step = second_step;
3064 }
3065 }
3066
3067 // Determine whether the pattern has a single root node. This affects
3068 // decisions about whether or not to start matching the pattern when
3069 // a query cursor has a range restriction or when immediately within an
3070 // error node.
3071 uint32_t start_depth = step->depth;
3072 bool is_rooted = start_depth == 0;
3073 for (uint32_t step_index = start_step_index + 1; step_index < self->steps.size; step_index++) {
3074 QueryStep *child_step = array_get(&self->steps, step_index);
3075 if (child_step->is_dead_end) break;
3076 if (child_step->depth == start_depth) {
3077 is_rooted = false;
3078 break;
3079 }
3080 }
3081
3082 ts_query__pattern_map_insert(self, step->symbol, (PatternEntry) {
3083 .step_index = start_step_index,
3084 .pattern_index = pattern_index,
3085 .is_rooted = is_rooted
3086 });
3087 if (step->symbol == WILDCARD_SYMBOL) {
3088 self->wildcard_root_pattern_count++;
3089 }
3090
3091 // If there are alternatives or options at the root of the pattern,
3092 // then add multiple entries to the pattern map.
3093 if (step->alternative_index != NONE) {
3094 start_step_index = step->alternative_index;
3095 } else if (wildcard_root_alternative_index != NONE) {
3096 start_step_index = wildcard_root_alternative_index;
3097 wildcard_root_alternative_index = NONE;
3098 } else {
3099 break;
3100 }
3101 }
3102
3103 // Fix up quantifier loop-backs within alternations. When a branch of an
3104 // alternation has a + or * quantifier, the quantifier's pass_through step
3105 // loops back to the branch's first step. However, the alternation linking
3106 // assigns that same step's `alternative_index` to point to the _next_ branch.
3107 // This causes the quantifier loop to incorrectly explore other alternation branches,
3108 // when a quantified branch matches, loops back, and then fails to match. To correct
3109 // this, we create "clean" copies of the branches' first steps without the link to the
3110 // next branch. After a quantified branch matches, it loops back to the cleaned copy.
3111 {
3112 uint32_t pat_start = pattern->steps.offset;
3113 uint32_t pat_end = pat_start + pattern->steps.length - 1; // exclude DONE
3114
3115 for (uint32_t i = pat_start; i < pat_end; i++) {
3116 QueryStep *s = array_get(&self->steps, i);
3117 // Ensure this step is a pass_through with a _backward_ alternative (a quantifier loop-back)
3118 if (!s->is_pass_through || !s->is_inside_alternation
3119 || s->alternative_index == NONE || s->alternative_index >= i) continue;
3120
3121 uint32_t target_idx = s->alternative_index;
3122 QueryStep *target = array_get(&self->steps, target_idx);
3123
3124 // Check if the target has a forward alternative from alternation linking
3125 uint16_t target_alt_index = target->alternative_index;
3126 if (target_alt_index == NONE
3127 || target_alt_index <= target_idx || target_alt_index >= pat_end) continue;
3128
3129 // Create a clean copy of the target step without the alternation alternative.
3130 uint32_t copy_idx = self->steps.size;
3131 QueryStep copy = *target;
3132 copy.alternative_index = NONE;
3133 uint16_t target_depth = target->depth;
3134 array_push(&self->steps, copy);
3135
3136 // Add a dead_end that redirects to the pass through step after the target,
3137 // so the pattern continues correctly after the cleaned copy matches.
3138 QueryStep redirect = query_step__new(0, target_depth, false);
3139 redirect.is_dead_end = true;
3140 redirect.alternative_index = target_idx + 1;
3141 array_push(&self->steps, redirect);
3142
3143 // Update the pass_through to loop back to the copy. Reacquire `s` since
3144 // `self->steps` may have been reallocated.
3145 s = array_get(&self->steps, i);
3146 s->alternative_index = copy_idx;
3147 }
3148 }
3149 }
3150
3151 if (!ts_query__analyze_patterns(self, error_offset)) {
3152 *error_type = TSQueryErrorStructure;
3153 ts_query_delete(self);
3154 return NULL;
3155 }
3156
3157 array_delete(&self->string_buffer);
3158 return self;
3159 }
3160
3161 void ts_query_delete(TSQuery *self) {
3162 if (self) {
3163 array_delete(&self->steps);
3164 array_delete(&self->pattern_map);
3165 array_delete(&self->predicate_steps);
3166 array_delete(&self->patterns);
3167 array_delete(&self->step_offsets);
3168 array_delete(&self->string_buffer);
3169 array_delete(&self->negated_fields);
3170 array_delete(&self->repeat_symbols_with_rootless_patterns);
3171 ts_language_delete(self->language);
3172 symbol_table_delete(&self->captures);
3173 symbol_table_delete(&self->predicate_values);
3174 for (uint32_t index = 0; index < self->capture_quantifiers.size; index++) {
3175 CaptureQuantifiers *capture_quantifiers = array_get(&self->capture_quantifiers, index);
3176 capture_quantifiers_delete(capture_quantifiers);
3177 }
3178 array_delete(&self->capture_quantifiers);
3179 ts_free(self);
3180 }
3181 }
3182
3183 uint32_t ts_query_pattern_count(const TSQuery *self) {
3184 return self->patterns.size;
3185 }
3186
3187 uint32_t ts_query_capture_count(const TSQuery *self) {
3188 return self->captures.slices.size;
3189 }
3190
3191 uint32_t ts_query_string_count(const TSQuery *self) {
3192 return self->predicate_values.slices.size;
3193 }
3194
3195 const char *ts_query_capture_name_for_id(
3196 const TSQuery *self,
3197 uint32_t index,
3198 uint32_t *length
3199 ) {
3200 return symbol_table_name_for_id(&self->captures, index, length);
3201 }
3202
3203 TSQuantifier ts_query_capture_quantifier_for_id(
3204 const TSQuery *self,
3205 uint32_t pattern_index,
3206 uint32_t capture_index
3207 ) {
3208 CaptureQuantifiers *capture_quantifiers = array_get(&self->capture_quantifiers, pattern_index);
3209 return capture_quantifier_for_id(capture_quantifiers, capture_index);
3210 }
3211
3212 const char *ts_query_string_value_for_id(
3213 const TSQuery *self,
3214 uint32_t index,
3215 uint32_t *length
3216 ) {
3217 return symbol_table_name_for_id(&self->predicate_values, index, length);
3218 }
3219
3220 const TSQueryPredicateStep *ts_query_predicates_for_pattern(
3221 const TSQuery *self,
3222 uint32_t pattern_index,
3223 uint32_t *step_count
3224 ) {
3225 Slice slice = array_get(&self->patterns, pattern_index)->predicate_steps;
3226 *step_count = slice.length;
3227 if (slice.length == 0) return NULL;
3228 return array_get(&self->predicate_steps, slice.offset);
3229 }
3230
3231 uint32_t ts_query_start_byte_for_pattern(
3232 const TSQuery *self,
3233 uint32_t pattern_index
3234 ) {
3235 return array_get(&self->patterns, pattern_index)->start_byte;
3236 }
3237
3238 uint32_t ts_query_end_byte_for_pattern(
3239 const TSQuery *self,
3240 uint32_t pattern_index
3241 ) {
3242 return array_get(&self->patterns, pattern_index)->end_byte;
3243 }
3244
3245 bool ts_query_is_pattern_rooted(
3246 const TSQuery *self,
3247 uint32_t pattern_index
3248 ) {
3249 for (unsigned i = 0; i < self->pattern_map.size; i++) {
3250 PatternEntry *entry = array_get(&self->pattern_map, i);
3251 if (entry->pattern_index == pattern_index) {
3252 if (!entry->is_rooted) return false;
3253 }
3254 }
3255 return true;
3256 }
3257
3258 bool ts_query_is_pattern_non_local(
3259 const TSQuery *self,
3260 uint32_t pattern_index
3261 ) {
3262 if (pattern_index < self->patterns.size) {
3263 return array_get(&self->patterns, pattern_index)->is_non_local;
3264 } else {
3265 return false;
3266 }
3267 }
3268
3269 bool ts_query_is_pattern_guaranteed_at_step(
3270 const TSQuery *self,
3271 uint32_t byte_offset
3272 ) {
3273 uint32_t step_index = UINT32_MAX;
3274 for (unsigned i = 0; i < self->step_offsets.size; i++) {
3275 StepOffset *step_offset = array_get(&self->step_offsets, i);
3276 if (step_offset->byte_offset > byte_offset) break;
3277 step_index = step_offset->step_index;
3278 }
3279 if (step_index < self->steps.size) {
3280 return array_get(&self->steps, step_index)->root_pattern_guaranteed;
3281 } else {
3282 return false;
3283 }
3284 }
3285
3286 bool ts_query__step_is_fallible(
3287 const TSQuery *self,
3288 uint16_t step_index
3289 ) {
3290 ts_assert((uint32_t)step_index + 1 < self->steps.size);
3291 QueryStep *step = array_get(&self->steps, step_index);
3292 QueryStep *next_step = array_get(&self->steps, step_index + 1);
3293 return (
3294 next_step->depth != PATTERN_DONE_MARKER &&
3295 next_step->depth > step->depth &&
3296 (!next_step->parent_pattern_guaranteed || step->symbol == WILDCARD_SYMBOL)
3297 );
3298 }
3299
3300 void ts_query_disable_capture(
3301 TSQuery *self,
3302 const char *name,
3303 uint32_t length
3304 ) {
3305 // Remove capture information for any pattern step that previously
3306 // captured with the given name.
3307 int id = symbol_table_id_for_name(&self->captures, name, length);
3308 if (id != -1) {
3309 for (unsigned i = 0; i < self->steps.size; i++) {
3310 QueryStep *step = array_get(&self->steps, i);
3311 query_step__remove_capture(step, id);
3312 }
3313 }
3314 }
3315
3316 void ts_query_disable_pattern(
3317 TSQuery *self,
3318 uint32_t pattern_index
3319 ) {
3320 // Remove the given pattern from the pattern map. Its steps will still
3321 // be in the `steps` array, but they will never be read.
3322 for (unsigned i = 0; i < self->pattern_map.size; i++) {
3323 PatternEntry *pattern = array_get(&self->pattern_map, i);
3324 if (pattern->pattern_index == pattern_index) {
3325 array_erase(&self->pattern_map, i);
3326 i--;
3327 }
3328 }
3329 }
3330
3331 /***************
3332 * QueryCursor
3333 ***************/
3334
3335 TSQueryCursor *ts_query_cursor_new(void) {
3336 TSQueryCursor *self = ts_malloc(sizeof(TSQueryCursor));
3337 *self = (TSQueryCursor) {
3338 .did_exceed_match_limit = false,
3339 .ascending = false,
3340 .halted = false,
3341 .states = array_new(),
3342 .finished_states = array_new(),
3343 .capture_list_pool = capture_list_pool_new(),
3344 .included_range = {
3345 .start_point = {0, 0},
3346 .end_point = POINT_MAX,
3347 .start_byte = 0,
3348 .end_byte = UINT32_MAX,
3349 },
3350 .containing_range = {
3351 .start_point = {0, 0},
3352 .end_point = POINT_MAX,
3353 .start_byte = 0,
3354 .end_byte = UINT32_MAX,
3355 },
3356 .max_start_depth = UINT32_MAX,
3357 .operation_count = 0,
3358 };
3359 array_reserve(&self->states, 8);
3360 array_reserve(&self->finished_states, 8);
3361 return self;
3362 }
3363
3364 void ts_query_cursor_delete(TSQueryCursor *self) {
3365 array_delete(&self->states);
3366 array_delete(&self->finished_states);
3367 ts_tree_cursor_delete(&self->cursor);
3368 capture_list_pool_delete(&self->capture_list_pool);
3369 ts_free(self);
3370 }
3371
3372 bool ts_query_cursor_did_exceed_match_limit(const TSQueryCursor *self) {
3373 return self->did_exceed_match_limit;
3374 }
3375
3376 uint32_t ts_query_cursor_match_limit(const TSQueryCursor *self) {
3377 return self->capture_list_pool.max_capture_list_count;
3378 }
3379
3380 void ts_query_cursor_set_match_limit(TSQueryCursor *self, uint32_t limit) {
3381 self->capture_list_pool.max_capture_list_count = limit;
3382 }
3383
3384 #ifdef DEBUG_EXECUTE_QUERY
3385 #define LOG(...) fprintf(stderr, __VA_ARGS__)
3386 #else
3387 #define LOG(...)
3388 #endif
3389
3390 void ts_query_cursor_exec(
3391 TSQueryCursor *self,
3392 const TSQuery *query,
3393 TSNode node
3394 ) {
3395 if (query) {
3396 LOG("query steps:\n");
3397 for (unsigned i = 0; i < query->steps.size; i++) {
3398 QueryStep *step = array_get(&query->steps, i);
3399 LOG(" %u: {", i);
3400 if (step->depth == PATTERN_DONE_MARKER) {
3401 LOG("DONE");
3402 } else if (step->is_dead_end) {
3403 LOG("dead_end");
3404 } else if (step->is_pass_through) {
3405 LOG("pass_through");
3406 } else if (step->symbol != WILDCARD_SYMBOL) {
3407 LOG("symbol: %s", query->language->symbol_names[step->symbol]);
3408 } else {
3409 LOG("symbol: *");
3410 }
3411 if (step->field) {
3412 LOG(", field: %s", query->language->field_names[step->field]);
3413 }
3414 if (step->alternative_index != NONE) {
3415 LOG(", alternative: %u", step->alternative_index);
3416 }
3417 LOG("},\n");
3418 }
3419 }
3420
3421 array_clear(&self->states);
3422 array_clear(&self->finished_states);
3423 self->finished_states_heap_size = 0;
3424 ts_tree_cursor_reset(&self->cursor, node);
3425 capture_list_pool_reset(&self->capture_list_pool);
3426 self->on_visible_node = true;
3427 self->next_state_id = 0;
3428 self->next_finished_state_id = 0;
3429 self->depth = 0;
3430 self->ascending = false;
3431 self->halted = false;
3432 self->query = query;
3433 self->did_exceed_match_limit = false;
3434 self->operation_count = 0;
3435 self->query_options = NULL;
3436 self->query_state = (TSQueryCursorState) {0};
3437 }
3438
3439 void ts_query_cursor_exec_with_options(
3440 TSQueryCursor *self,
3441 const TSQuery *query,
3442 TSNode node,
3443 const TSQueryCursorOptions *query_options
3444 ) {
3445 ts_query_cursor_exec(self, query, node);
3446 if (query_options) {
3447 self->query_options = query_options;
3448 self->query_state = (TSQueryCursorState) {
3449 .payload = query_options->payload
3450 };
3451 }
3452 }
3453
3454 bool ts_query_cursor_set_byte_range(
3455 TSQueryCursor *self,
3456 uint32_t start_byte,
3457 uint32_t end_byte
3458 ) {
3459 if (end_byte == 0) {
3460 end_byte = UINT32_MAX;
3461 }
3462 if (start_byte > end_byte) {
3463 return false;
3464 }
3465 self->included_range.start_byte = start_byte;
3466 self->included_range.end_byte = end_byte;
3467 return true;
3468 }
3469
3470 bool ts_query_cursor_set_point_range(
3471 TSQueryCursor *self,
3472 TSPoint start_point,
3473 TSPoint end_point
3474 ) {
3475 if (end_point.row == 0 && end_point.column == 0) {
3476 end_point = POINT_MAX;
3477 }
3478 if (point_gt(start_point, end_point)) {
3479 return false;
3480 }
3481 self->included_range.start_point = start_point;
3482 self->included_range.end_point = end_point;
3483 return true;
3484 }
3485
3486 bool ts_query_cursor_set_containing_byte_range(
3487 TSQueryCursor *self,
3488 uint32_t start_byte,
3489 uint32_t end_byte
3490 ) {
3491 if (end_byte == 0) {
3492 end_byte = UINT32_MAX;
3493 }
3494 if (start_byte > end_byte) {
3495 return false;
3496 }
3497 self->containing_range.start_byte = start_byte;
3498 self->containing_range.end_byte = end_byte;
3499 return true;
3500 }
3501
3502 bool ts_query_cursor_set_containing_point_range(
3503 TSQueryCursor *self,
3504 TSPoint start_point,
3505 TSPoint end_point
3506 ) {
3507 if (end_point.row == 0 && end_point.column == 0) {
3508 end_point = POINT_MAX;
3509 }
3510 if (point_gt(start_point, end_point)) {
3511 return false;
3512 }
3513 self->containing_range.start_point = start_point;
3514 self->containing_range.end_point = end_point;
3515 return true;
3516 }
3517
3518 // Search through all of the in-progress states, and find the captured
3519 // node that occurs earliest in the document.
3520 static bool ts_query_cursor__first_in_progress_capture(
3521 TSQueryCursor *self,
3522 uint32_t *state_index,
3523 uint32_t *byte_offset,
3524 uint32_t *pattern_index,
3525 bool *is_definite
3526 ) {
3527 bool result = false;
3528 *state_index = UINT32_MAX;
3529 *byte_offset = UINT32_MAX;
3530 *pattern_index = UINT32_MAX;
3531 for (unsigned i = 0; i < self->states.size; i++) {
3532 QueryState *state = array_get(&self->states, i);
3533 if (state->dead) continue;
3534
3535 const CaptureList *captures = capture_list_pool_get(
3536 &self->capture_list_pool,
3537 state->capture_list_id
3538 );
3539 if (state->consumed_capture_count >= captures->size) {
3540 continue;
3541 }
3542
3543 TSNode node = array_get(captures, state->consumed_capture_count)->node;
3544 if (
3545 ts_node_end_byte(node) <= self->included_range.start_byte ||
3546 point_lte(ts_node_end_point(node), self->included_range.start_point)
3547 ) {
3548 state->consumed_capture_count++;
3549 i--;
3550 continue;
3551 }
3552
3553 uint32_t node_start_byte = ts_node_start_byte(node);
3554 if (
3555 !result ||
3556 node_start_byte < *byte_offset ||
3557 (node_start_byte == *byte_offset && state->pattern_index < *pattern_index)
3558 ) {
3559 QueryStep *step = array_get(&self->query->steps, state->step_index);
3560 if (is_definite) {
3561 // We're being a bit conservative here by asserting that the following step
3562 // is not immediate, because this capture might end up being discarded if the
3563 // following symbol in the tree isn't the required symbol for this step.
3564 *is_definite = step->root_pattern_guaranteed && !step->is_immediate;
3565 } else if (step->root_pattern_guaranteed) {
3566 continue;
3567 }
3568
3569 result = true;
3570 *state_index = i;
3571 *byte_offset = node_start_byte;
3572 *pattern_index = state->pattern_index;
3573 }
3574 }
3575 return result;
3576 }
3577
3578 // Determine which node is first in a depth-first traversal
3579 int ts_query_cursor__compare_nodes(TSNode left, TSNode right) {
3580 if (left.id != right.id) {
3581 uint32_t left_start = ts_node_start_byte(left);
3582 uint32_t right_start = ts_node_start_byte(right);
3583 if (left_start < right_start) return -1;
3584 if (left_start > right_start) return 1;
3585 uint32_t left_node_count = ts_node_end_byte(left);
3586 uint32_t right_node_count = ts_node_end_byte(right);
3587 if (left_node_count > right_node_count) return -1;
3588 if (left_node_count < right_node_count) return 1;
3589 }
3590 return 0;
3591 }
3592
3593 // Determine if either state contains a superset of the other state's captures.
3594 void ts_query_cursor__compare_captures(
3595 TSQueryCursor *self,
3596 QueryState *left_state,
3597 QueryState *right_state,
3598 bool *left_contains_right,
3599 bool *right_contains_left
3600 ) {
3601 const CaptureList *left_captures = capture_list_pool_get(
3602 &self->capture_list_pool,
3603 left_state->capture_list_id
3604 );
3605 const CaptureList *right_captures = capture_list_pool_get(
3606 &self->capture_list_pool,
3607 right_state->capture_list_id
3608 );
3609 *left_contains_right = true;
3610 *right_contains_left = true;
3611 unsigned i = 0, j = 0;
3612 for (;;) {
3613 if (i < left_captures->size) {
3614 if (j < right_captures->size) {
3615 TSQueryCapture *left = array_get(left_captures, i);
3616 TSQueryCapture *right = array_get(right_captures, j);
3617 if (left->node.id == right->node.id && left->index == right->index) {
3618 i++;
3619 j++;
3620 } else {
3621 switch (ts_query_cursor__compare_nodes(left->node, right->node)) {
3622 case -1:
3623 *right_contains_left = false;
3624 i++;
3625 break;
3626 case 1:
3627 *left_contains_right = false;
3628 j++;
3629 break;
3630 default:
3631 *right_contains_left = false;
3632 *left_contains_right = false;
3633 i++;
3634 j++;
3635 break;
3636 }
3637 }
3638 } else {
3639 *right_contains_left = false;
3640 break;
3641 }
3642 } else {
3643 if (j < right_captures->size) {
3644 *left_contains_right = false;
3645 }
3646 break;
3647 }
3648 }
3649 }
3650
3651 static void ts_query_cursor__add_state(
3652 TSQueryCursor *self,
3653 const PatternEntry *pattern
3654 ) {
3655 QueryStep *step = array_get(&self->query->steps, pattern->step_index);
3656 uint32_t start_depth = self->depth - step->depth;
3657
3658 // Keep the states array in ascending order of start_depth and pattern_index,
3659 // so that it can be processed more efficiently elsewhere. Usually, there is
3660 // no work to do here because of two facts:
3661 // * States with lower start_depth are naturally added first due to the
3662 // order in which nodes are visited.
3663 // * Earlier patterns are naturally added first because of the ordering of the
3664 // pattern_map data structure that's used to initiate matches.
3665 //
3666 // This loop is only needed in cases where two conditions hold:
3667 // * A pattern consists of more than one sibling node, so that its states
3668 // remain in progress after exiting the node that started the match.
3669 // * The first node in the pattern matches against multiple nodes at the
3670 // same depth.
3671 //
3672 // An example of this is the pattern '((comment)* (function))'. If multiple
3673 // `comment` nodes appear in a row, then we may initiate a new state for this
3674 // pattern while another state for the same pattern is already in progress.
3675 // If there are multiple patterns like this in a query, then this loop will
3676 // need to execute in order to keep the states ordered by pattern_index.
3677 uint32_t index = self->states.size;
3678 while (index > 0) {
3679 QueryState *prev_state = array_get(&self->states, index - 1);
3680 if (prev_state->start_depth < start_depth) break;
3681 if (prev_state->start_depth == start_depth) {
3682 // Avoid inserting an unnecessary duplicate state, which would be
3683 // immediately pruned by the longest-match criteria.
3684 if (
3685 prev_state->pattern_index == pattern->pattern_index &&
3686 prev_state->step_index == pattern->step_index
3687 ) return;
3688 if (prev_state->pattern_index <= pattern->pattern_index) break;
3689 }
3690 index--;
3691 }
3692
3693 LOG(
3694 " start state. pattern:%u, step:%u\n",
3695 pattern->pattern_index,
3696 pattern->step_index
3697 );
3698 array_insert(&self->states, index, ((QueryState) {
3699 .id = UINT32_MAX,
3700 .capture_list_id = CAPTURE_LIST_NONE,
3701 .heap_insert_order = UINT32_MAX,
3702 .step_index = pattern->step_index,
3703 .pattern_index = pattern->pattern_index,
3704 .start_depth = start_depth,
3705 .consumed_capture_count = 0,
3706 .seeking_immediate_match = true,
3707 .has_in_progress_alternatives = false,
3708 .needs_parent = step->depth == 1,
3709 .dead = false,
3710 }));
3711 }
3712
3713 // Acquire a capture list for this state. If there are no capture lists left in the
3714 // pool, this will steal the capture list from another existing state, and mark that
3715 // other state as 'dead'.
3716 static CaptureList *ts_query_cursor__prepare_to_capture(
3717 TSQueryCursor *self,
3718 QueryState *state,
3719 unsigned state_index_to_preserve
3720 ) {
3721 if (state->capture_list_id == CAPTURE_LIST_NONE) {
3722 state->capture_list_id = capture_list_pool_acquire(&self->capture_list_pool);
3723
3724 // If there are no capture lists left in the pool, then terminate whichever
3725 // state has captured the earliest node in the document, and steal its
3726 // capture list.
3727 if (state->capture_list_id == CAPTURE_LIST_NONE) {
3728 self->did_exceed_match_limit = true;
3729 uint32_t state_index, byte_offset, pattern_index;
3730 if (
3731 ts_query_cursor__first_in_progress_capture(
3732 self,
3733 &state_index,
3734 &byte_offset,
3735 &pattern_index,
3736 NULL
3737 ) &&
3738 state_index != state_index_to_preserve
3739 ) {
3740 LOG(
3741 " abandon state. index:%u, pattern:%u, offset:%u.\n",
3742 state_index, pattern_index, byte_offset
3743 );
3744 QueryState *other_state = array_get(&self->states, state_index);
3745 state->capture_list_id = other_state->capture_list_id;
3746 other_state->capture_list_id = CAPTURE_LIST_NONE;
3747 other_state->dead = true;
3748 CaptureList *list = capture_list_pool_get_mut(
3749 &self->capture_list_pool,
3750 state->capture_list_id
3751 );
3752 array_clear(list);
3753 return list;
3754 } else {
3755 LOG(" ran out of capture lists");
3756 return NULL;
3757 }
3758 }
3759 }
3760 return capture_list_pool_get_mut(&self->capture_list_pool, state->capture_list_id);
3761 }
3762
3763 static void ts_query_cursor__capture(
3764 TSQueryCursor *self,
3765 QueryState *state,
3766 QueryStep *step,
3767 TSNode node
3768 ) {
3769 if (state->dead) return;
3770 CaptureList *capture_list = ts_query_cursor__prepare_to_capture(self, state, UINT32_MAX);
3771 if (!capture_list) {
3772 state->dead = true;
3773 return;
3774 }
3775
3776 for (unsigned j = 0; j < MAX_STEP_CAPTURE_COUNT; j++) {
3777 uint16_t capture_id = step->capture_ids[j];
3778 if (step->capture_ids[j] == NONE) break;
3779 array_push(capture_list, ((TSQueryCapture) { node, capture_id }));
3780 LOG(
3781 " capture node. type:%s, pattern:%u, capture_id:%u, capture_count:%u\n",
3782 ts_node_type(node),
3783 state->pattern_index,
3784 capture_id,
3785 capture_list->size
3786 );
3787 }
3788 }
3789
3790 // Duplicate the given state and insert the newly-created state immediately after
3791 // the given state in the `states` array. Ensures that the given state reference is
3792 // still valid, even if the states array is reallocated.
3793 static QueryState *ts_query_cursor__copy_state(
3794 TSQueryCursor *self,
3795 QueryState **state_ref
3796 ) {
3797 const QueryState *state = *state_ref;
3798 uint32_t state_index = (uint32_t)(state - self->states.contents);
3799 QueryState copy = *state;
3800 copy.capture_list_id = CAPTURE_LIST_NONE;
3801
3802 // If the state has captures, copy its capture list.
3803 if (state->capture_list_id != CAPTURE_LIST_NONE) {
3804 CaptureList *new_captures = ts_query_cursor__prepare_to_capture(self, &copy, state_index);
3805 if (!new_captures) return NULL;
3806 const CaptureList *old_captures = capture_list_pool_get(
3807 &self->capture_list_pool,
3808 state->capture_list_id
3809 );
3810 array_push_all(new_captures, old_captures);
3811 }
3812
3813 array_insert(&self->states, state_index + 1, copy);
3814 *state_ref = array_get(&self->states, state_index);
3815 return array_get(&self->states, state_index + 1);
3816 }
3817
3818 static inline bool ts_query_cursor__should_descend(
3819 TSQueryCursor *self,
3820 bool node_intersects_range
3821 ) {
3822
3823 if (node_intersects_range && self->depth < self->max_start_depth) {
3824 return true;
3825 }
3826
3827 // If there are in-progress matches whose remaining steps occur
3828 // deeper in the tree, then descend.
3829 for (unsigned i = 0; i < self->states.size; i++) {
3830 QueryState *state = array_get(&self->states, i);
3831 QueryStep *next_step = array_get(&self->query->steps, state->step_index);
3832 if (
3833 next_step->depth != PATTERN_DONE_MARKER &&
3834 state->start_depth + next_step->depth > self->depth
3835 ) {
3836 return true;
3837 }
3838 }
3839
3840 if (self->depth >= self->max_start_depth) {
3841 return false;
3842 }
3843
3844 // If the current node is hidden, then a non-rooted pattern might match
3845 // one if its roots inside of this node, and match another of its roots
3846 // as part of a sibling node, so we may need to descend.
3847 if (!self->on_visible_node) {
3848 // Descending into a repetition node outside of the range can be
3849 // expensive, because these nodes can have many visible children.
3850 // Avoid descending into repetition nodes unless we have already
3851 // determined that this query can match rootless patterns inside
3852 // of this type of repetition node.
3853 Subtree subtree = ts_tree_cursor_current_subtree(&self->cursor);
3854 if (ts_subtree_is_repetition(subtree)) {
3855 bool exists;
3856 uint32_t index;
3857 array_search_sorted_by(
3858 &self->query->repeat_symbols_with_rootless_patterns,,
3859 ts_subtree_symbol(subtree),
3860 &index,
3861 &exists
3862 );
3863 return exists;
3864 }
3865
3866 return true;
3867 }
3868
3869 return false;
3870 }
3871
3872 bool range_intersects(const TSRange *a, const TSRange *b) {
3873 bool is_empty = a->start_byte == a->end_byte;
3874 return (
3875 (
3876 a->end_byte > b->start_byte ||
3877 (is_empty && a->end_byte == b->start_byte)
3878 ) &&
3879 (
3880 point_gt(a->end_point, b->start_point) ||
3881 (is_empty && point_eq(a->end_point, b->start_point))
3882 ) &&
3883 a->start_byte < b->end_byte &&
3884 point_lt(a->start_point, b->end_point)
3885 );
3886 }
3887
3888 bool range_within(const TSRange *a, const TSRange *b) {
3889 return (
3890 a->start_byte >= b->start_byte &&
3891 point_gte(a->start_point, b->start_point) &&
3892 a->end_byte <= b->end_byte &&
3893 point_lte(a->end_point, b->end_point)
3894 );
3895 }
3896
3897 // Walk the tree, processing patterns until at least one pattern finishes,
3898 // If one or more patterns finish, return `true` and store their states in the
3899 // `finished_states` array. Multiple patterns can finish on the same node. If
3900 // there are no more matches, return `false`.
3901 static inline bool ts_query_cursor__advance(
3902 TSQueryCursor *self,
3903 bool stop_on_definite_step
3904 ) {
3905 bool did_match = false;
3906 for (;;) {
3907 if (self->halted) {
3908 while (self->states.size > 0) {
3909 QueryState state = array_pop(&self->states);
3910 capture_list_pool_release(
3911 &self->capture_list_pool,
3912 state.capture_list_id
3913 );
3914 }
3915 }
3916
3917 if (++self->operation_count == OP_COUNT_PER_QUERY_CALLBACK_CHECK) {
3918 self->operation_count = 0;
3919 }
3920
3921 if (self->query_options && self->query_options->progress_callback) {
3922 self->query_state.current_byte_offset = ts_node_start_byte(ts_tree_cursor_current_node(&self->cursor));
3923 }
3924 if (
3925 did_match ||
3926 self->halted ||
3927 (
3928 self->operation_count == 0 &&
3929 (
3930 (self->query_options && self->query_options->progress_callback && self->query_options->progress_callback(&self->query_state))
3931 )
3932 )
3933 ) {
3934 return did_match;
3935 }
3936
3937 // Exit the current node.
3938 if (self->ascending) {
3939 if (self->on_visible_node) {
3940 LOG(
3941 "leave node. depth:%u, type:%s\n",
3942 self->depth,
3943 ts_node_type(ts_tree_cursor_current_node(&self->cursor))
3944 );
3945
3946 // After leaving a node, remove any states that cannot make further progress.
3947 uint32_t deleted_count = 0;
3948 for (unsigned i = 0, n = self->states.size; i < n; i++) {
3949 QueryState *state = array_get(&self->states, i);
3950 QueryStep *step = array_get(&self->query->steps, state->step_index);
3951
3952 // If a state completed its pattern inside of this node, but was deferred from finishing
3953 // in order to search for longer matches, mark it as finished.
3954 if (
3955 step->depth == PATTERN_DONE_MARKER &&
3956 (state->start_depth > self->depth || self->depth == 0)
3957 ) {
3958 LOG(" finish pattern %u\n", state->pattern_index);
3959 ts_query_cursor__push_finished_state(self, state);
3960 did_match = true;
3961 deleted_count++;
3962 }
3963
3964 // If a state needed to match something within this node, then remove that state
3965 // as it has failed to match.
3966 else if (
3967 step->depth != PATTERN_DONE_MARKER &&
3968 (uint32_t)state->start_depth + (uint32_t)step->depth > self->depth
3969 ) {
3970 LOG(
3971 " failed to match. pattern:%u, step:%u\n",
3972 state->pattern_index,
3973 state->step_index
3974 );
3975 capture_list_pool_release(
3976 &self->capture_list_pool,
3977 state->capture_list_id
3978 );
3979 deleted_count++;
3980 }
3981
3982 else if (deleted_count > 0) {
3983 *array_get(&self->states, i - deleted_count) = *state;
3984 }
3985 }
3986 self->states.size -= deleted_count;
3987 }
3988
3989 // Leave this node by stepping to its next sibling or to its parent.
3990 switch (ts_tree_cursor_goto_next_sibling_internal(&self->cursor)) {
3991 case TreeCursorStepVisible:
3992 if (!self->on_visible_node) {
3993 self->depth++;
3994 self->on_visible_node = true;
3995 }
3996 self->ascending = false;
3997 break;
3998 case TreeCursorStepHidden:
3999 if (self->on_visible_node) {
4000 self->depth--;
4001 self->on_visible_node = false;
4002 }
4003 self->ascending = false;
4004 break;
4005 default:
4006 if (ts_tree_cursor_goto_parent(&self->cursor)) {
4007 self->depth--;
4008 } else {
4009 LOG("halt at root\n");
4010 self->halted = true;
4011 }
4012 }
4013 }
4014
4015 // Enter a new node.
4016 else {
4017 TSNode node = ts_tree_cursor_current_node(&self->cursor);
4018 TSNode parent_node = ts_tree_cursor_parent_node(&self->cursor);
4019
4020 bool parent_intersects_range =
4021 ts_node_is_null(parent_node) ||
4022 range_intersects(&(TSRange) {
4023 .start_point = ts_node_start_point(parent_node),
4024 .end_point = ts_node_end_point(parent_node),
4025 .start_byte = ts_node_start_byte(parent_node),
4026 .end_byte = ts_node_end_byte(parent_node),
4027 }, &self->included_range);
4028 TSRange node_range = (TSRange) {
4029 .start_point = ts_node_start_point(node),
4030 .end_point = ts_node_end_point(node),
4031 .start_byte = ts_node_start_byte(node),
4032 .end_byte = ts_node_end_byte(node),
4033 };
4034 bool node_intersects_range =
4035 parent_intersects_range && range_intersects(&node_range, &self->included_range);
4036 bool node_intersects_containing_range =
4037 range_intersects(&node_range, &self->containing_range);
4038 bool node_within_containing_range =
4039 range_within(&node_range, &self->containing_range);
4040
4041 if (node_within_containing_range && self->on_visible_node) {
4042 TSSymbol symbol = ts_node_symbol(node);
4043 bool is_named = ts_node_is_named(node);
4044 bool is_missing = ts_node_is_missing(node);
4045 bool has_later_siblings;
4046 bool has_later_named_siblings;
4047 bool can_have_later_siblings_with_this_field;
4048 TSFieldId field_id = 0;
4049 TSSymbol supertypes[8] = {0};
4050 unsigned supertype_count = 8;
4051 ts_tree_cursor_current_status(
4052 &self->cursor,
4053 &field_id,
4054 &has_later_siblings,
4055 &has_later_named_siblings,
4056 &can_have_later_siblings_with_this_field,
4057 supertypes,
4058 &supertype_count
4059 );
4060 LOG(
4061 "enter node. depth:%u, type:%s, field:%s, row:%u state_count:%u, finished_state_count:%u\n",
4062 self->depth,
4063 ts_node_type(node),
4064 ts_language_field_name_for_id(self->query->language, field_id),
4065 ts_node_start_point(node).row,
4066 self->states.size,
4067 self->finished_states.size
4068 );
4069
4070 bool node_is_error = symbol == ts_builtin_sym_error;
4071 bool parent_is_error =
4072 !ts_node_is_null(parent_node) &&
4073 ts_node_symbol(parent_node) == ts_builtin_sym_error;
4074
4075 // Add new states for any patterns whose root node is a wildcard.
4076 if (!node_is_error) {
4077 for (unsigned i = 0; i < self->query->wildcard_root_pattern_count; i++) {
4078 PatternEntry *pattern = array_get(&self->query->pattern_map, i);
4079
4080 // If this node matches the first step of the pattern, then add a new
4081 // state at the start of this pattern.
4082 QueryStep *step = array_get(&self->query->steps, pattern->step_index);
4083 uint32_t start_depth = self->depth - step->depth;
4084 if (
4085 (pattern->is_rooted ?
4086 node_intersects_range :
4087 (parent_intersects_range && !parent_is_error)) &&
4088 (!step->field || field_id == step->field) &&
4089 (!step->supertype_symbol || supertype_count > 0) &&
4090 (start_depth <= self->max_start_depth)
4091 ) {
4092 ts_query_cursor__add_state(self, pattern);
4093 }
4094 }
4095 }
4096
4097 // Add new states for any patterns whose root node matches this node.
4098 unsigned i;
4099 if (ts_query__pattern_map_search(self->query, symbol, &i)) {
4100 PatternEntry *pattern = array_get(&self->query->pattern_map, i);
4101
4102 QueryStep *step = array_get(&self->query->steps, pattern->step_index);
4103 uint32_t start_depth = self->depth - step->depth;
4104 do {
4105 // If this node matches the first step of the pattern, then add a new
4106 // state at the start of this pattern.
4107 if (
4108 (pattern->is_rooted ?
4109 node_intersects_range :
4110 (parent_intersects_range && !parent_is_error)) &&
4111 (!step->field || field_id == step->field) &&
4112 (start_depth <= self->max_start_depth)
4113 ) {
4114 ts_query_cursor__add_state(self, pattern);
4115 }
4116
4117 // Advance to the next pattern whose root node matches this node.
4118 i++;
4119 if (i == self->query->pattern_map.size) break;
4120 pattern = array_get(&self->query->pattern_map, i);
4121 step = array_get(&self->query->steps, pattern->step_index);
4122 } while (step->symbol == symbol);
4123 }
4124
4125 // Update all of the in-progress states with current node.
4126 for (unsigned j = 0, copy_count = 0; j < self->states.size; j += 1 + copy_count) {
4127 QueryState *state = array_get(&self->states, j);
4128 QueryStep *step = array_get(&self->query->steps, state->step_index);
4129 state->has_in_progress_alternatives = false;
4130 copy_count = 0;
4131
4132 // Check that the node matches all of the criteria for the next
4133 // step of the pattern.
4134 if ((uint32_t)state->start_depth + (uint32_t)step->depth != self->depth) continue;
4135
4136 // Determine if this node matches this step of the pattern, and also
4137 // if this node can have later siblings that match this step of the
4138 // pattern.
4139 bool node_does_match = false;
4140 if (step->symbol == WILDCARD_SYMBOL) {
4141 if (step->is_missing) {
4142 node_does_match = is_missing;
4143 } else {
4144 node_does_match = !node_is_error && (is_named || !step->is_named);
4145 }
4146 } else {
4147 node_does_match = symbol == step->symbol && (!step->is_missing || is_missing);
4148 }
4149 bool later_sibling_can_match = has_later_siblings;
4150 if ((step->is_immediate && is_named) || state->seeking_immediate_match) {
4151 later_sibling_can_match = false;
4152 }
4153 if (step->is_last_child && has_later_named_siblings) {
4154 node_does_match = false;
4155 }
4156 if (step->supertype_symbol) {
4157 bool has_supertype = false;
4158 for (unsigned k = 0; k < supertype_count; k++) {
4159 if (supertypes[k] == step->supertype_symbol) {
4160 has_supertype = true;
4161 break;
4162 }
4163 }
4164 if (!has_supertype) node_does_match = false;
4165 }
4166 if (step->field) {
4167 if (step->field == field_id) {
4168 if (!can_have_later_siblings_with_this_field) {
4169 later_sibling_can_match = false;
4170 }
4171 } else {
4172 node_does_match = false;
4173 }
4174 }
4175
4176 if (step->negated_field_list_id) {
4177 TSFieldId *negated_field_ids = array_get(&self->query->negated_fields, step->negated_field_list_id);
4178 for (;;) {
4179 TSFieldId negated_field_id = *negated_field_ids;
4180 if (negated_field_id) {
4181 negated_field_ids++;
4182 if (ts_node_child_by_field_id(node, negated_field_id).id) {
4183 node_does_match = false;
4184 break;
4185 }
4186 } else {
4187 break;
4188 }
4189 }
4190 }
4191
4192 // Remove states immediately if it is ever clear that they cannot match.
4193 if (!node_does_match) {
4194 if (!later_sibling_can_match) {
4195 LOG(
4196 " discard state. pattern:%u, step:%u\n",
4197 state->pattern_index,
4198 state->step_index
4199 );
4200 capture_list_pool_release(
4201 &self->capture_list_pool,
4202 state->capture_list_id
4203 );
4204 array_erase(&self->states, j);
4205 j--;
4206 }
4207 continue;
4208 }
4209
4210 // Some patterns can match their root node in multiple ways, capturing different
4211 // children. If this pattern step could match later children within the same
4212 // parent, then this query state cannot simply be updated in place. It must be
4213 // split into two states: one that matches this node, and one which skips over
4214 // this node, to preserve the possibility of matching later siblings.
4215 if (later_sibling_can_match && (
4216 step->contains_captures ||
4217 ts_query__step_is_fallible(self->query, state->step_index)
4218 )) {
4219 if (ts_query_cursor__copy_state(self, &state)) {
4220 LOG(
4221 " split state for capture. pattern:%u, step:%u\n",
4222 state->pattern_index,
4223 state->step_index
4224 );
4225 copy_count++;
4226 }
4227 }
4228
4229 // If this pattern started with a wildcard, such that the pattern map
4230 // actually points to the *second* step of the pattern, then check
4231 // that the node has a parent, and capture the parent node if necessary.
4232 if (state->needs_parent) {
4233 TSNode parent = ts_tree_cursor_parent_node(&self->cursor);
4234 if (ts_node_is_null(parent)) {
4235 LOG(" missing parent node\n");
4236 state->dead = true;
4237 } else {
4238 state->needs_parent = false;
4239 QueryStep *skipped_wildcard_step = step;
4240 do {
4241 skipped_wildcard_step--;
4242 } while (
4243 skipped_wildcard_step->is_dead_end ||
4244 skipped_wildcard_step->is_pass_through ||
4245 skipped_wildcard_step->depth > 0
4246 );
4247 if (skipped_wildcard_step->capture_ids[0] != NONE) {
4248 LOG(" capture wildcard parent\n");
4249 ts_query_cursor__capture(
4250 self,
4251 state,
4252 skipped_wildcard_step,
4253 parent
4254 );
4255 }
4256 }
4257 }
4258
4259 // If the current node is captured in this pattern, add it to the capture list.
4260 if (step->capture_ids[0] != NONE) {
4261 ts_query_cursor__capture(self, state, step, node);
4262 }
4263
4264 if (state->dead) {
4265 array_erase(&self->states, j);
4266 j--;
4267 continue;
4268 }
4269
4270 // Advance this state to the next step of its pattern.
4271 state->step_index++;
4272 LOG(
4273 " advance state. pattern:%u, step:%u\n",
4274 state->pattern_index,
4275 state->step_index
4276 );
4277
4278 QueryStep *next_step = array_get(&self->query->steps, state->step_index);
4279
4280 // For a given step, if the current symbol is the wildcard symbol, `_`, and it is **not**
4281 // named, meaning it should capture anonymous nodes, **and** the next step is immediate,
4282 // we reuse the `seeking_immediate_match` flag to indicate that we are looking for an
4283 // immediate match due to an unnamed wildcard symbol.
4284 //
4285 // The reason for this is that typically, anchors will not consider anonymous nodes,
4286 // but we're special casing the wildcard symbol to allow for any immediate matches,
4287 // regardless of whether they are named or not.
4288 if (step->symbol == WILDCARD_SYMBOL && !step->is_named && next_step->is_immediate) {
4289 state->seeking_immediate_match = true;
4290 } else {
4291 state->seeking_immediate_match = false;
4292 }
4293
4294 if (stop_on_definite_step && next_step->root_pattern_guaranteed) did_match = true;
4295
4296 // If this state's next step has an alternative step, then copy the state in order
4297 // to pursue both alternatives. The alternative step itself may have an alternative,
4298 // so this is an interactive process.
4299 unsigned end_index = j + 1;
4300 for (unsigned k = j; k < end_index; k++) {
4301 QueryState *child_state = array_get(&self->states, k);
4302 QueryStep *child_step = array_get(&self->query->steps, child_state->step_index);
4303 if (child_step->alternative_index != NONE) {
4304 // A "dead-end" step exists only to add a non-sequential jump into the step sequence,
4305 // via its alternative index. When a state reaches a dead-end step, it jumps straight
4306 // to the step's alternative.
4307 if (child_step->is_dead_end) {
4308 child_state->step_index = child_step->alternative_index;
4309 k--;
4310 continue;
4311 }
4312
4313 // A "pass-through" step exists only to add a branch into the step sequence,
4314 // via its alternative_index. When a state reaches a pass-through step, it splits
4315 // in order to process the alternative step, and then it advances to the next step.
4316 if (child_step->is_pass_through) {
4317 child_state->step_index++;
4318 k--;
4319 }
4320
4321 QueryState *copy = ts_query_cursor__copy_state(self, &child_state);
4322 if (copy) {
4323 LOG(
4324 " split state for branch. pattern:%u, from_step:%u, to_step:%u, pass_through:%d, capture_count:%u\n",
4325 copy->pattern_index,
4326 copy->step_index,
4327 next_step->alternative_index,
4328 next_step->is_pass_through,
4329 capture_list_pool_get(&self->capture_list_pool, copy->capture_list_id)->size
4330 );
4331 end_index++;
4332 copy_count++;
4333 copy->step_index = child_step->alternative_index;
4334 if (child_step->is_pass_through) {
4335 copy->seeking_immediate_match = true;
4336 }
4337 }
4338 }
4339 }
4340 }
4341
4342 for (unsigned j = 0; j < self->states.size; j++) {
4343 QueryState *state = array_get(&self->states, j);
4344 if (state->dead) {
4345 array_erase(&self->states, j);
4346 j--;
4347 continue;
4348 }
4349
4350 // Enforce the longest-match criteria. When a query pattern contains optional or
4351 // repeated nodes, this is necessary to avoid multiple redundant states, where
4352 // one state has a strict subset of another state's captures.
4353 bool did_remove = false;
4354 for (unsigned k = j + 1; k < self->states.size; k++) {
4355 QueryState *other_state = array_get(&self->states, k);
4356
4357 // Query states are kept in ascending order of start_depth and pattern_index.
4358 // Since the longest-match criteria is only used for deduping matches of the same
4359 // pattern and root node, we only need to perform pairwise comparisons within a
4360 // small slice of the states array.
4361 if (
4362 other_state->start_depth != state->start_depth ||
4363 other_state->pattern_index != state->pattern_index
4364 ) break;
4365
4366 bool left_contains_right, right_contains_left;
4367 ts_query_cursor__compare_captures(
4368 self,
4369 state,
4370 other_state,
4371 &left_contains_right,
4372 &right_contains_left
4373 );
4374 if (left_contains_right) {
4375 if (state->step_index == other_state->step_index) {
4376 LOG(
4377 " drop shorter state. pattern: %u, step_index: %u\n",
4378 state->pattern_index,
4379 state->step_index
4380 );
4381 capture_list_pool_release(&self->capture_list_pool, other_state->capture_list_id);
4382 array_erase(&self->states, k);
4383 k--;
4384 continue;
4385 }
4386 other_state->has_in_progress_alternatives = true;
4387 }
4388 if (right_contains_left) {
4389 if (state->step_index == other_state->step_index) {
4390 LOG(
4391 " drop shorter state. pattern: %u, step_index: %u\n",
4392 state->pattern_index,
4393 state->step_index
4394 );
4395 capture_list_pool_release(&self->capture_list_pool, state->capture_list_id);
4396 array_erase(&self->states, j);
4397 j--;
4398 did_remove = true;
4399 break;
4400 }
4401 state->has_in_progress_alternatives = true;
4402 }
4403 }
4404
4405 // If the state is at the end of its pattern, remove it from the list
4406 // of in-progress states and add it to the list of finished states.
4407 if (!did_remove) {
4408 LOG(
4409 " keep state. pattern: %u, start_depth: %u, step_index: %u, capture_count: %u\n",
4410 state->pattern_index,
4411 state->start_depth,
4412 state->step_index,
4413 capture_list_pool_get(&self->capture_list_pool, state->capture_list_id)->size
4414 );
4415 QueryStep *next_step = array_get(&self->query->steps, state->step_index);
4416 if (next_step->depth == PATTERN_DONE_MARKER) {
4417 if (state->has_in_progress_alternatives) {
4418 LOG(" defer finishing pattern %u\n", state->pattern_index);
4419 } else {
4420 LOG(" finish pattern %u\n", state->pattern_index);
4421 ts_query_cursor__push_finished_state(self, state);
4422 array_erase(&self->states, (uint32_t)(state - self->states.contents));
4423 did_match = true;
4424 j--;
4425 }
4426 }
4427 }
4428 }
4429 }
4430
4431 if (node_intersects_containing_range && ts_query_cursor__should_descend(self, node_intersects_range)) {
4432 switch (ts_tree_cursor_goto_first_child_internal(&self->cursor)) {
4433 case TreeCursorStepVisible:
4434 self->depth++;
4435 self->on_visible_node = true;
4436 continue;
4437 case TreeCursorStepHidden:
4438 self->on_visible_node = false;
4439 continue;
4440 default:
4441 break;
4442 }
4443 }
4444
4445 self->ascending = true;
4446 }
4447 }
4448 }
4449
4450 bool ts_query_cursor_next_match(
4451 TSQueryCursor *self,
4452 TSQueryMatch *match
4453 ) {
4454 if (self->finished_states.size == 0) {
4455 if (!ts_query_cursor__advance(self, false)) {
4456 return false;
4457 }
4458 }
4459 if (self->finished_states_heap_size > 0) {
4460 ts_query_cursor__heapify_finished_states(self);
4461 }
4462
4463 uint32_t state_index = 0;
4464 if (self->finished_states_heap_size > 0) {
4465 for (uint32_t i = 1; i < self->finished_states.size; i++) {
4466 QueryState *state = array_get(&self->finished_states, i);
4467 QueryState *earliest_state = array_get(&self->finished_states, state_index);
4468 if (state->heap_insert_order < earliest_state->heap_insert_order) {
4469 state_index = i;
4470 }
4471 }
4472 }
4473
4474 QueryState *state = array_get(&self->finished_states, state_index);
4475 if (state->id == UINT32_MAX) state->id = self->next_state_id++;
4476 match->id = state->id;
4477 match->pattern_index = state->pattern_index;
4478 const CaptureList *captures = capture_list_pool_get(
4479 &self->capture_list_pool,
4480 state->capture_list_id
4481 );
4482 match->captures = captures->contents;
4483 match->capture_count = captures->size;
4484 capture_list_pool_release(&self->capture_list_pool, state->capture_list_id);
4485 if (self->finished_states_heap_size > 0) {
4486 finished_state_erase(&self->finished_states, state_index, &self->capture_list_pool);
4487 self->finished_states_heap_size = self->finished_states.size;
4488 } else {
4489 array_erase(&self->finished_states, state_index);
4490 }
4491 return true;
4492 }
4493
4494 void ts_query_cursor_remove_match(
4495 TSQueryCursor *self,
4496 uint32_t match_id
4497 ) {
4498 if (self->finished_states_heap_size > 0) {
4499 ts_query_cursor__heapify_finished_states(self);
4500 }
4501
4502 for (unsigned i = 0; i < self->finished_states.size; i++) {
4503 const QueryState *state = array_get(&self->finished_states, i);
4504 if (state->id == match_id) {
4505 capture_list_pool_release(
4506 &self->capture_list_pool,
4507 state->capture_list_id
4508 );
4509 if (self->finished_states_heap_size > 0) {
4510 finished_state_erase(&self->finished_states, i, &self->capture_list_pool);
4511 self->finished_states_heap_size = self->finished_states.size;
4512 } else {
4513 array_erase(&self->finished_states, i);
4514 }
4515 return;
4516 }
4517 }
4518
4519 // Remove unfinished query states as well to prevent future
4520 // captures for a match being removed.
4521 for (unsigned i = 0; i < self->states.size; i++) {
4522 const QueryState *state = array_get(&self->states, i);
4523 if (state->id == match_id) {
4524 capture_list_pool_release(
4525 &self->capture_list_pool,
4526 state->capture_list_id
4527 );
4528 array_erase(&self->states, i);
4529 return;
4530 }
4531 }
4532 }
4533
4534 bool ts_query_cursor_next_capture(
4535 TSQueryCursor *self,
4536 TSQueryMatch *match,
4537 uint32_t *capture_index
4538 ) {
4539 // The goal here is to return captures in order, even though they may not
4540 // be discovered in order, because patterns can overlap. Search for matches
4541 // until there is a finished capture that is before any unfinished capture.
4542 for (;;) {
4543 // Sift any newly pushed finished states into the heap.
4544 ts_query_cursor__heapify_finished_states(self);
4545
4546 // First, find the earliest capture in an unfinished match.
4547 uint32_t first_unfinished_capture_byte;
4548 uint32_t first_unfinished_pattern_index;
4549 uint32_t first_unfinished_state_index;
4550 bool first_unfinished_state_is_definite = false;
4551 bool found_unfinished_state = ts_query_cursor__first_in_progress_capture(
4552 self,
4553 &first_unfinished_state_index,
4554 &first_unfinished_capture_byte,
4555 &first_unfinished_pattern_index,
4556 &first_unfinished_state_is_definite
4557 );
4558
4559 // Then find the earliest capture in a finished match. The finished_states
4560 // array is maintained as a min-heap, so the earliest is always at index 0.
4561 // Clean up fully-consumed and out-of-range states from the heap root first.
4562 QueryState *first_finished_state = NULL;
4563 uint32_t first_finished_capture_byte = first_unfinished_capture_byte;
4564 uint32_t first_finished_pattern_index = first_unfinished_pattern_index;
4565 while (self->finished_states.size > 0) {
4566 QueryState *state = array_get(&self->finished_states, 0);
4567 const CaptureList *captures = capture_list_pool_get(
4568 &self->capture_list_pool,
4569 state->capture_list_id
4570 );
4571
4572 // Remove states whose captures are all consumed.
4573 if (state->consumed_capture_count >= captures->size) {
4574 capture_list_pool_release(
4575 &self->capture_list_pool,
4576 state->capture_list_id
4577 );
4578 finished_state_pop(&self->finished_states, &self->capture_list_pool);
4579 self->finished_states_heap_size = self->finished_states.size;
4580 continue;
4581 }
4582
4583 TSNode node = array_get(captures, state->consumed_capture_count)->node;
4584
4585 bool node_precedes_range = (
4586 ts_node_end_byte(node) <= self->included_range.start_byte ||
4587 point_lte(ts_node_end_point(node), self->included_range.start_point)
4588 );
4589 bool node_follows_range = (
4590 ts_node_start_byte(node) >= self->included_range.end_byte ||
4591 point_gte(ts_node_start_point(node), self->included_range.end_point)
4592 );
4593 bool node_outside_of_range = node_precedes_range || node_follows_range;
4594
4595 // Skip captures that are outside of the cursor's range.
4596 if (node_outside_of_range) {
4597 state->consumed_capture_count++;
4598 finished_state_sift_down(&self->finished_states, 0, &self->capture_list_pool);
4599 continue;
4600 }
4601
4602 uint32_t node_start_byte = ts_node_start_byte(node);
4603 if (
4604 node_start_byte < first_finished_capture_byte ||
4605 (
4606 node_start_byte == first_finished_capture_byte &&
4607 state->pattern_index < first_finished_pattern_index
4608 )
4609 ) {
4610 first_finished_state = state;
4611 first_finished_capture_byte = node_start_byte;
4612 first_finished_pattern_index = state->pattern_index;
4613 }
4614 break;
4615 }
4616
4617 // If there is finished capture that is clearly before any unfinished
4618 // capture, then return its match, and its capture index. Internally
4619 // record the fact that the capture has been 'consumed'.
4620 QueryState *state;
4621 if (first_finished_state) {
4622 state = first_finished_state;
4623 } else if (first_unfinished_state_is_definite) {
4624 state = array_get(&self->states, first_unfinished_state_index);
4625 } else {
4626 state = NULL;
4627 }
4628
4629 if (state) {
4630 if (state->id == UINT32_MAX) state->id = self->next_state_id++;
4631 match->id = state->id;
4632 match->pattern_index = state->pattern_index;
4633 const CaptureList *captures = capture_list_pool_get(
4634 &self->capture_list_pool,
4635 state->capture_list_id
4636 );
4637 match->captures = captures->contents;
4638 match->capture_count = captures->size;
4639 *capture_index = state->consumed_capture_count;
4640 state->consumed_capture_count++;
4641 // If this state is in the finished_states heap, its sort key has changed
4642 // (next capture is now later in the document). Restore heap order.
4643 if (state == first_finished_state) {
4644 finished_state_sift_down(&self->finished_states, 0, &self->capture_list_pool);
4645 }
4646 return true;
4647 }
4648
4649 if (capture_list_pool_is_empty(&self->capture_list_pool) && found_unfinished_state) {
4650 LOG(
4651 " abandon state. index:%u, pattern:%u, offset:%u.\n",
4652 first_unfinished_state_index,
4653 first_unfinished_pattern_index,
4654 first_unfinished_capture_byte
4655 );
4656 capture_list_pool_release(
4657 &self->capture_list_pool,
4658 array_get(&self->states, first_unfinished_state_index)->capture_list_id
4659 );
4660 array_erase(&self->states, first_unfinished_state_index);
4661 }
4662
4663 // If there are no finished matches that are ready to be returned, then
4664 // continue finding more matches.
4665 if (
4666 !ts_query_cursor__advance(self, true) &&
4667 self->finished_states.size == 0
4668 ) return false;
4669 }
4670 }
4671
4672 void ts_query_cursor_set_max_start_depth(
4673 TSQueryCursor *self,
4674 uint32_t max_start_depth
4675 ) {
4676 self->max_start_depth = max_start_depth;
4677 }
4678
4679 #undef LOG