@singapore-editor/tree-sitter-x 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2871 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/edit.ts
5
+ var Edit = class {
6
+ static {
7
+ __name(this, "Edit");
8
+ }
9
+ /** The start position of the change. */
10
+ startPosition;
11
+ /** The end position of the change before the edit. */
12
+ oldEndPosition;
13
+ /** The end position of the change after the edit. */
14
+ newEndPosition;
15
+ /** The start index of the change. */
16
+ startIndex;
17
+ /** The end index of the change before the edit. */
18
+ oldEndIndex;
19
+ /** The end index of the change after the edit. */
20
+ newEndIndex;
21
+ constructor({
22
+ startIndex,
23
+ oldEndIndex,
24
+ newEndIndex,
25
+ startPosition,
26
+ oldEndPosition,
27
+ newEndPosition
28
+ }) {
29
+ this.startIndex = startIndex >>> 0;
30
+ this.oldEndIndex = oldEndIndex >>> 0;
31
+ this.newEndIndex = newEndIndex >>> 0;
32
+ this.startPosition = startPosition;
33
+ this.oldEndPosition = oldEndPosition;
34
+ this.newEndPosition = newEndPosition;
35
+ }
36
+ /**
37
+ * Edit a point and index to keep it in-sync with source code that has been edited.
38
+ *
39
+ * This function updates a single point's byte offset and row/column position
40
+ * based on an edit operation. This is useful for editing points without
41
+ * requiring a tree or node instance.
42
+ */
43
+ editPoint(point, index) {
44
+ let newIndex = index;
45
+ const newPoint = { ...point };
46
+ if (index >= this.oldEndIndex) {
47
+ newIndex = this.newEndIndex + (index - this.oldEndIndex);
48
+ const originalRow = point.row;
49
+ newPoint.row = this.newEndPosition.row + (point.row - this.oldEndPosition.row);
50
+ newPoint.column = originalRow === this.oldEndPosition.row ? this.newEndPosition.column + (point.column - this.oldEndPosition.column) : point.column;
51
+ } else if (index > this.startIndex) {
52
+ newIndex = this.newEndIndex;
53
+ newPoint.row = this.newEndPosition.row;
54
+ newPoint.column = this.newEndPosition.column;
55
+ }
56
+ return { point: newPoint, index: newIndex };
57
+ }
58
+ /**
59
+ * Edit a range to keep it in-sync with source code that has been edited.
60
+ *
61
+ * This function updates a range's start and end positions based on an edit
62
+ * operation. This is useful for editing ranges without requiring a tree
63
+ * or node instance.
64
+ */
65
+ editRange(range) {
66
+ const newRange = {
67
+ startIndex: range.startIndex,
68
+ startPosition: { ...range.startPosition },
69
+ endIndex: range.endIndex,
70
+ endPosition: { ...range.endPosition }
71
+ };
72
+ if (range.endIndex >= this.oldEndIndex) {
73
+ if (range.endIndex !== Number.MAX_SAFE_INTEGER) {
74
+ newRange.endIndex = this.newEndIndex + (range.endIndex - this.oldEndIndex);
75
+ newRange.endPosition = {
76
+ row: this.newEndPosition.row + (range.endPosition.row - this.oldEndPosition.row),
77
+ column: range.endPosition.row === this.oldEndPosition.row ? this.newEndPosition.column + (range.endPosition.column - this.oldEndPosition.column) : range.endPosition.column
78
+ };
79
+ if (newRange.endIndex < this.newEndIndex) {
80
+ newRange.endIndex = Number.MAX_SAFE_INTEGER;
81
+ newRange.endPosition = { row: Number.MAX_SAFE_INTEGER, column: Number.MAX_SAFE_INTEGER };
82
+ }
83
+ }
84
+ } else if (range.endIndex > this.startIndex) {
85
+ newRange.endIndex = this.startIndex;
86
+ newRange.endPosition = { ...this.startPosition };
87
+ }
88
+ if (range.startIndex >= this.oldEndIndex) {
89
+ newRange.startIndex = this.newEndIndex + (range.startIndex - this.oldEndIndex);
90
+ newRange.startPosition = {
91
+ row: this.newEndPosition.row + (range.startPosition.row - this.oldEndPosition.row),
92
+ column: range.startPosition.row === this.oldEndPosition.row ? this.newEndPosition.column + (range.startPosition.column - this.oldEndPosition.column) : range.startPosition.column
93
+ };
94
+ if (newRange.startIndex < this.newEndIndex) {
95
+ newRange.startIndex = Number.MAX_SAFE_INTEGER;
96
+ newRange.startPosition = { row: Number.MAX_SAFE_INTEGER, column: Number.MAX_SAFE_INTEGER };
97
+ }
98
+ } else if (range.startIndex > this.startIndex) {
99
+ newRange.startIndex = this.startIndex;
100
+ newRange.startPosition = { ...this.startPosition };
101
+ }
102
+ return newRange;
103
+ }
104
+ };
105
+
106
+ // src/constants.ts
107
+ var SIZE_OF_SHORT = 2;
108
+ var SIZE_OF_INT = 4;
109
+ var SIZE_OF_CURSOR = 4 * SIZE_OF_INT;
110
+ var SIZE_OF_NODE = 5 * SIZE_OF_INT;
111
+ var SIZE_OF_POINT = 2 * SIZE_OF_INT;
112
+ var SIZE_OF_RANGE = 2 * SIZE_OF_INT + 2 * SIZE_OF_POINT;
113
+ var ZERO_POINT = { row: 0, column: 0 };
114
+ var INTERNAL = /* @__PURE__ */ Symbol("INTERNAL");
115
+ function assertInternal(x) {
116
+ if (x !== INTERNAL) throw new Error("Illegal constructor");
117
+ }
118
+ __name(assertInternal, "assertInternal");
119
+ function isPoint(point) {
120
+ return !!point && typeof point.row === "number" && typeof point.column === "number";
121
+ }
122
+ __name(isPoint, "isPoint");
123
+ function setModule(module) {
124
+ C = module;
125
+ }
126
+ __name(setModule, "setModule");
127
+ var C;
128
+
129
+ // src/finalization_registry.ts
130
+ function newFinalizer(handler) {
131
+ try {
132
+ return new FinalizationRegistry(handler);
133
+ } catch (e) {
134
+ console.error("Unsupported FinalizationRegistry:", e);
135
+ return;
136
+ }
137
+ }
138
+ __name(newFinalizer, "newFinalizer");
139
+
140
+ // src/lookahead_iterator.ts
141
+ var finalizer = newFinalizer((address) => {
142
+ C._ts_lookahead_iterator_delete(address);
143
+ });
144
+ var LookaheadIterator = class {
145
+ static {
146
+ __name(this, "LookaheadIterator");
147
+ }
148
+ /** @internal */
149
+ [0] = 0;
150
+ // Internal handle for Wasm
151
+ /** @internal */
152
+ language;
153
+ /** @internal */
154
+ positioned = false;
155
+ /** @internal */
156
+ constructor(internal, address, language) {
157
+ assertInternal(internal);
158
+ this[0] = address;
159
+ this.language = language;
160
+ finalizer?.register(this, address, this);
161
+ }
162
+ /**
163
+ * Get the current symbol of the lookahead iterator.
164
+ *
165
+ * Returns `null` if the iterator is not positioned on a symbol:
166
+ *
167
+ * - Before the first iteration step
168
+ * - After the iterator is exhausted
169
+ * - After a {@link reset} or {@link resetState} call
170
+ */
171
+ get currentTypeId() {
172
+ return this.positioned ? C._ts_lookahead_iterator_current_symbol(this[0]) : null;
173
+ }
174
+ /**
175
+ * Get the current symbol name of the lookahead iterator.
176
+ *
177
+ * Returns `null` if the iterator is not positioned on a symbol.
178
+ */
179
+ get currentType() {
180
+ const id = this.currentTypeId;
181
+ if (id === null) return null;
182
+ return this.language.types[id] ?? C.UTF8ToString(C._ts_language_symbol_name(this.language[0], id));
183
+ }
184
+ /** Delete the lookahead iterator, freeing its resources. */
185
+ delete() {
186
+ finalizer?.unregister(this);
187
+ C._ts_lookahead_iterator_delete(this[0]);
188
+ this[0] = 0;
189
+ }
190
+ /**
191
+ * Reset the lookahead iterator.
192
+ *
193
+ * This returns `true` if the language was set successfully and `false`
194
+ * otherwise.
195
+ */
196
+ reset(language, stateId) {
197
+ if (C._ts_lookahead_iterator_reset(this[0], language[0], stateId)) {
198
+ this.language = language;
199
+ this.positioned = false;
200
+ return true;
201
+ }
202
+ return false;
203
+ }
204
+ /**
205
+ * Reset the lookahead iterator to another state.
206
+ *
207
+ * This returns `true` if the iterator was reset to the given state and
208
+ * `false` otherwise.
209
+ */
210
+ resetState(stateId) {
211
+ if (!C._ts_lookahead_iterator_reset_state(this[0], stateId)) return false;
212
+ this.positioned = false;
213
+ return true;
214
+ }
215
+ /**
216
+ * Returns an iterator that iterates over the symbols of the lookahead iterator.
217
+ *
218
+ * The iterator will yield the current symbol name as a string for each step
219
+ * until there are no more symbols to iterate over.
220
+ */
221
+ [Symbol.iterator]() {
222
+ return {
223
+ next: /* @__PURE__ */ __name(() => {
224
+ this.positioned = Boolean(C._ts_lookahead_iterator_next(this[0]));
225
+ const value = this.currentType;
226
+ return value === null ? { done: true, value: "" } : { done: false, value };
227
+ }, "next")
228
+ };
229
+ }
230
+ };
231
+
232
+ // src/tree.ts
233
+ function getText(tree, startIndex, endIndex, startPosition) {
234
+ const length = endIndex - startIndex;
235
+ let result = tree.textCallback(startIndex, startPosition);
236
+ if (result) {
237
+ startIndex += result.length;
238
+ while (startIndex < endIndex) {
239
+ const string = tree.textCallback(startIndex, startPosition);
240
+ if (string && string.length > 0) {
241
+ startIndex += string.length;
242
+ result += string;
243
+ } else {
244
+ break;
245
+ }
246
+ }
247
+ if (startIndex > endIndex) {
248
+ result = result.slice(0, length);
249
+ }
250
+ }
251
+ return result ?? "";
252
+ }
253
+ __name(getText, "getText");
254
+ var finalizer2 = newFinalizer((address) => {
255
+ C._ts_tree_delete(address);
256
+ });
257
+ var Tree = class _Tree {
258
+ static {
259
+ __name(this, "Tree");
260
+ }
261
+ /** @internal */
262
+ [0] = 0;
263
+ // Internal handle for Wasm
264
+ /** @internal */
265
+ textCallback;
266
+ /** The language that was used to parse the syntax tree. */
267
+ language;
268
+ /** @internal */
269
+ constructor(internal, address, language, textCallback) {
270
+ assertInternal(internal);
271
+ this[0] = address;
272
+ this.language = language;
273
+ this.textCallback = textCallback;
274
+ finalizer2?.register(this, address, this);
275
+ }
276
+ /** Create a shallow copy of the syntax tree. This is very fast. */
277
+ copy() {
278
+ const address = C._ts_tree_copy(this[0]);
279
+ return new _Tree(INTERNAL, address, this.language, this.textCallback);
280
+ }
281
+ /** Delete the syntax tree, freeing its resources. */
282
+ delete() {
283
+ finalizer2?.unregister(this);
284
+ C._ts_tree_delete(this[0]);
285
+ this[0] = 0;
286
+ }
287
+ /** Get the root node of the syntax tree. */
288
+ get rootNode() {
289
+ C._ts_tree_root_node_wasm(this[0]);
290
+ return unmarshalNode(this);
291
+ }
292
+ /**
293
+ * Get the root node of the syntax tree, but with its position shifted
294
+ * forward by the given offset.
295
+ */
296
+ rootNodeWithOffset(offsetBytes, offsetExtent) {
297
+ const address = TRANSFER_BUFFER + SIZE_OF_NODE;
298
+ C.setValue(address, offsetBytes, "i32");
299
+ marshalPoint(address + SIZE_OF_INT, offsetExtent);
300
+ C._ts_tree_root_node_with_offset_wasm(this[0]);
301
+ return unmarshalNode(this);
302
+ }
303
+ /**
304
+ * Edit the syntax tree to keep it in sync with source code that has been
305
+ * edited.
306
+ *
307
+ * You must describe the edit both in terms of byte offsets and in terms of
308
+ * row/column coordinates.
309
+ */
310
+ edit(edit) {
311
+ marshalEdit(edit);
312
+ C._ts_tree_edit_wasm(this[0]);
313
+ }
314
+ /** Create a new {@link TreeCursor} starting from the root of the tree. */
315
+ walk() {
316
+ return this.rootNode.walk();
317
+ }
318
+ /**
319
+ * Compare this old edited syntax tree to a new syntax tree representing
320
+ * the same document, returning a sequence of ranges whose syntactic
321
+ * structure has changed.
322
+ *
323
+ * For this to work correctly, this syntax tree must have been edited such
324
+ * that its ranges match up to the new tree. Generally, you'll want to
325
+ * call this method right after calling one of the [`Parser::parse`]
326
+ * functions. Call it on the old tree that was passed to parse, and
327
+ * pass the new tree that was returned from `parse`.
328
+ */
329
+ getChangedRanges(other) {
330
+ if (!(other instanceof _Tree)) {
331
+ throw new TypeError("Argument must be a Tree");
332
+ }
333
+ C._ts_tree_get_changed_ranges_wasm(this[0], other[0]);
334
+ const count = C.getValue(TRANSFER_BUFFER, "i32");
335
+ const buffer = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
336
+ const result = new Array(count);
337
+ if (count > 0) {
338
+ let address = buffer;
339
+ for (let i = 0; i < count; i++) {
340
+ result[i] = unmarshalRange(address);
341
+ address += SIZE_OF_RANGE;
342
+ }
343
+ C._free(buffer);
344
+ }
345
+ return result;
346
+ }
347
+ /** Get the included ranges that were used to parse the syntax tree. */
348
+ getIncludedRanges() {
349
+ C._ts_tree_included_ranges_wasm(this[0]);
350
+ const count = C.getValue(TRANSFER_BUFFER, "i32");
351
+ const buffer = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
352
+ const result = new Array(count);
353
+ if (count > 0) {
354
+ let address = buffer;
355
+ for (let i = 0; i < count; i++) {
356
+ result[i] = unmarshalRange(address);
357
+ address += SIZE_OF_RANGE;
358
+ }
359
+ C._free(buffer);
360
+ }
361
+ return result;
362
+ }
363
+ };
364
+
365
+ // src/tree_cursor.ts
366
+ var finalizer3 = newFinalizer((address) => {
367
+ C._ts_tree_cursor_delete_wasm(address);
368
+ });
369
+ var TreeCursor = class _TreeCursor {
370
+ static {
371
+ __name(this, "TreeCursor");
372
+ }
373
+ /** @internal */
374
+ // @ts-expect-error: never read
375
+ [0] = 0;
376
+ // Internal handle for Wasm
377
+ /** @internal */
378
+ // @ts-expect-error: never read
379
+ [1] = 0;
380
+ // Internal handle for Wasm
381
+ /** @internal */
382
+ // @ts-expect-error: never read
383
+ [2] = 0;
384
+ // Internal handle for Wasm
385
+ /** @internal */
386
+ // @ts-expect-error: never read
387
+ [3] = 0;
388
+ // Internal handle for Wasm
389
+ /** @internal */
390
+ tree;
391
+ /** @internal */
392
+ constructor(internal, tree) {
393
+ assertInternal(internal);
394
+ this.tree = tree;
395
+ unmarshalTreeCursor(this);
396
+ finalizer3?.register(this, this.tree[0], this);
397
+ }
398
+ /** Creates a deep copy of the tree cursor. This allocates new memory. */
399
+ copy() {
400
+ const copy = new _TreeCursor(INTERNAL, this.tree);
401
+ C._ts_tree_cursor_copy_wasm(this.tree[0]);
402
+ unmarshalTreeCursor(copy);
403
+ return copy;
404
+ }
405
+ /** Delete the tree cursor, freeing its resources. */
406
+ delete() {
407
+ finalizer3?.unregister(this);
408
+ marshalTreeCursor(this);
409
+ C._ts_tree_cursor_delete_wasm(this.tree[0]);
410
+ this[0] = this[1] = this[2] = 0;
411
+ }
412
+ /** Get the tree cursor's current {@link Node}. */
413
+ get currentNode() {
414
+ marshalTreeCursor(this);
415
+ C._ts_tree_cursor_current_node_wasm(this.tree[0]);
416
+ return unmarshalNode(this.tree);
417
+ }
418
+ /**
419
+ * Get the numerical field id of this tree cursor's current node.
420
+ *
421
+ * See also {@link TreeCursor#currentFieldName}.
422
+ */
423
+ get currentFieldId() {
424
+ marshalTreeCursor(this);
425
+ return C._ts_tree_cursor_current_field_id_wasm(this.tree[0]);
426
+ }
427
+ /** Get the field name of this tree cursor's current node. */
428
+ get currentFieldName() {
429
+ return this.tree.language.fields[this.currentFieldId];
430
+ }
431
+ /**
432
+ * Get the depth of the cursor's current node relative to the original
433
+ * node that the cursor was constructed with.
434
+ */
435
+ get currentDepth() {
436
+ marshalTreeCursor(this);
437
+ return C._ts_tree_cursor_current_depth_wasm(this.tree[0]);
438
+ }
439
+ /**
440
+ * Get the index of the cursor's current node out of all of the
441
+ * descendants of the original node that the cursor was constructed with.
442
+ */
443
+ get currentDescendantIndex() {
444
+ marshalTreeCursor(this);
445
+ return C._ts_tree_cursor_current_descendant_index_wasm(this.tree[0]);
446
+ }
447
+ /** Get the type of the cursor's current node. */
448
+ get nodeType() {
449
+ return this.tree.language.types[this.nodeTypeId] || "ERROR";
450
+ }
451
+ /** Get the type id of the cursor's current node. */
452
+ get nodeTypeId() {
453
+ marshalTreeCursor(this);
454
+ return C._ts_tree_cursor_current_node_type_id_wasm(this.tree[0]);
455
+ }
456
+ /** Get the state id of the cursor's current node. */
457
+ get nodeStateId() {
458
+ marshalTreeCursor(this);
459
+ return C._ts_tree_cursor_current_node_state_id_wasm(this.tree[0]);
460
+ }
461
+ /** Get the id of the cursor's current node. */
462
+ get nodeId() {
463
+ marshalTreeCursor(this);
464
+ return C._ts_tree_cursor_current_node_id_wasm(this.tree[0]);
465
+ }
466
+ /**
467
+ * Check if the cursor's current node is *named*.
468
+ *
469
+ * Named nodes correspond to named rules in the grammar, whereas
470
+ * *anonymous* nodes correspond to string literals in the grammar.
471
+ */
472
+ get nodeIsNamed() {
473
+ marshalTreeCursor(this);
474
+ return C._ts_tree_cursor_current_node_is_named_wasm(this.tree[0]) === 1;
475
+ }
476
+ /**
477
+ * Check if the cursor's current node is *missing*.
478
+ *
479
+ * Missing nodes are inserted by the parser in order to recover from
480
+ * certain kinds of syntax errors.
481
+ */
482
+ get nodeIsMissing() {
483
+ marshalTreeCursor(this);
484
+ return C._ts_tree_cursor_current_node_is_missing_wasm(this.tree[0]) === 1;
485
+ }
486
+ /** Get the string content of the cursor's current node. */
487
+ get nodeText() {
488
+ marshalTreeCursor(this);
489
+ const startIndex = C._ts_tree_cursor_start_index_wasm(this.tree[0]);
490
+ const endIndex = C._ts_tree_cursor_end_index_wasm(this.tree[0]);
491
+ C._ts_tree_cursor_start_position_wasm(this.tree[0]);
492
+ const startPosition = unmarshalPoint(TRANSFER_BUFFER);
493
+ return getText(this.tree, startIndex, endIndex, startPosition);
494
+ }
495
+ /** Get the start position of the cursor's current node. */
496
+ get startPosition() {
497
+ marshalTreeCursor(this);
498
+ C._ts_tree_cursor_start_position_wasm(this.tree[0]);
499
+ return unmarshalPoint(TRANSFER_BUFFER);
500
+ }
501
+ /** Get the end position of the cursor's current node. */
502
+ get endPosition() {
503
+ marshalTreeCursor(this);
504
+ C._ts_tree_cursor_end_position_wasm(this.tree[0]);
505
+ return unmarshalPoint(TRANSFER_BUFFER);
506
+ }
507
+ /** Get the start index of the cursor's current node. */
508
+ get startIndex() {
509
+ marshalTreeCursor(this);
510
+ return C._ts_tree_cursor_start_index_wasm(this.tree[0]);
511
+ }
512
+ /** Get the end index of the cursor's current node. */
513
+ get endIndex() {
514
+ marshalTreeCursor(this);
515
+ return C._ts_tree_cursor_end_index_wasm(this.tree[0]);
516
+ }
517
+ /**
518
+ * Move this cursor to the first child of its current node.
519
+ *
520
+ * This returns `true` if the cursor successfully moved, and returns
521
+ * `false` if there were no children.
522
+ */
523
+ gotoFirstChild() {
524
+ marshalTreeCursor(this);
525
+ const result = C._ts_tree_cursor_goto_first_child_wasm(this.tree[0]);
526
+ unmarshalTreeCursor(this);
527
+ return result === 1;
528
+ }
529
+ /**
530
+ * Move this cursor to the last child of its current node.
531
+ *
532
+ * This returns `true` if the cursor successfully moved, and returns
533
+ * `false` if there were no children.
534
+ *
535
+ * Note that this function may be slower than
536
+ * {@link TreeCursor#gotoFirstChild} because it needs to
537
+ * iterate through all the children to compute the child's position.
538
+ */
539
+ gotoLastChild() {
540
+ marshalTreeCursor(this);
541
+ const result = C._ts_tree_cursor_goto_last_child_wasm(this.tree[0]);
542
+ unmarshalTreeCursor(this);
543
+ return result === 1;
544
+ }
545
+ /**
546
+ * Move this cursor to the parent of its current node.
547
+ *
548
+ * This returns `true` if the cursor successfully moved, and returns
549
+ * `false` if there was no parent node (the cursor was already on the
550
+ * root node).
551
+ *
552
+ * Note that the node the cursor was constructed with is considered the root
553
+ * of the cursor, and the cursor cannot walk outside this node.
554
+ */
555
+ gotoParent() {
556
+ marshalTreeCursor(this);
557
+ const result = C._ts_tree_cursor_goto_parent_wasm(this.tree[0]);
558
+ unmarshalTreeCursor(this);
559
+ return result === 1;
560
+ }
561
+ /**
562
+ * Move this cursor to the next sibling of its current node.
563
+ *
564
+ * This returns `true` if the cursor successfully moved, and returns
565
+ * `false` if there was no next sibling node.
566
+ *
567
+ * Note that the node the cursor was constructed with is considered the root
568
+ * of the cursor, and the cursor cannot walk outside this node.
569
+ */
570
+ gotoNextSibling() {
571
+ marshalTreeCursor(this);
572
+ const result = C._ts_tree_cursor_goto_next_sibling_wasm(this.tree[0]);
573
+ unmarshalTreeCursor(this);
574
+ return result === 1;
575
+ }
576
+ /**
577
+ * Move this cursor to the previous sibling of its current node.
578
+ *
579
+ * This returns `true` if the cursor successfully moved, and returns
580
+ * `false` if there was no previous sibling node.
581
+ *
582
+ * Note that this function may be slower than
583
+ * {@link TreeCursor#gotoNextSibling} due to how node
584
+ * positions are stored. In the worst case, this will need to iterate
585
+ * through all the children up to the previous sibling node to recalculate
586
+ * its position. Also note that the node the cursor was constructed with is
587
+ * considered the root of the cursor, and the cursor cannot walk outside this node.
588
+ */
589
+ gotoPreviousSibling() {
590
+ marshalTreeCursor(this);
591
+ const result = C._ts_tree_cursor_goto_previous_sibling_wasm(this.tree[0]);
592
+ unmarshalTreeCursor(this);
593
+ return result === 1;
594
+ }
595
+ /**
596
+ * Move the cursor to the node that is the nth descendant of
597
+ * the original node that the cursor was constructed with, where
598
+ * zero represents the original node itself.
599
+ */
600
+ gotoDescendant(goalDescendantIndex) {
601
+ marshalTreeCursor(this);
602
+ C._ts_tree_cursor_goto_descendant_wasm(this.tree[0], goalDescendantIndex);
603
+ unmarshalTreeCursor(this);
604
+ }
605
+ /**
606
+ * Move this cursor to the first child of its current node that contains or
607
+ * starts after the given byte offset.
608
+ *
609
+ * This returns `true` if the cursor successfully moved to a child node, and returns
610
+ * `false` if no such child was found.
611
+ */
612
+ gotoFirstChildForIndex(goalIndex) {
613
+ marshalTreeCursor(this);
614
+ C.setValue(TRANSFER_BUFFER + SIZE_OF_CURSOR, goalIndex, "i32");
615
+ const result = C._ts_tree_cursor_goto_first_child_for_index_wasm(this.tree[0]);
616
+ unmarshalTreeCursor(this);
617
+ return result === 1;
618
+ }
619
+ /**
620
+ * Move this cursor to the first child of its current node that contains or
621
+ * starts after the given byte offset.
622
+ *
623
+ * This returns the index of the child node if one was found, and returns
624
+ * `null` if no such child was found.
625
+ */
626
+ gotoFirstChildForPosition(goalPosition) {
627
+ marshalTreeCursor(this);
628
+ marshalPoint(TRANSFER_BUFFER + SIZE_OF_CURSOR, goalPosition);
629
+ const result = C._ts_tree_cursor_goto_first_child_for_position_wasm(this.tree[0]);
630
+ unmarshalTreeCursor(this);
631
+ return result === 1;
632
+ }
633
+ /**
634
+ * Re-initialize this tree cursor to start at the original node that the
635
+ * cursor was constructed with.
636
+ */
637
+ reset(node) {
638
+ marshalNode(node);
639
+ marshalTreeCursor(this, TRANSFER_BUFFER + SIZE_OF_NODE);
640
+ C._ts_tree_cursor_reset_wasm(this.tree[0]);
641
+ unmarshalTreeCursor(this);
642
+ }
643
+ /**
644
+ * Re-initialize a tree cursor to the same position as another cursor.
645
+ *
646
+ * Unlike {@link TreeCursor#reset}, this will not lose parent
647
+ * information and allows reusing already created cursors.
648
+ */
649
+ resetTo(cursor) {
650
+ marshalTreeCursor(this, TRANSFER_BUFFER);
651
+ marshalTreeCursor(cursor, TRANSFER_BUFFER + SIZE_OF_CURSOR);
652
+ C._ts_tree_cursor_reset_to_wasm(this.tree[0], cursor.tree[0]);
653
+ unmarshalTreeCursor(this);
654
+ }
655
+ };
656
+
657
+ // src/node.ts
658
+ var Node = class {
659
+ static {
660
+ __name(this, "Node");
661
+ }
662
+ /** @internal */
663
+ // @ts-expect-error: never read
664
+ [0] = 0;
665
+ // Internal handle for Wasm
666
+ /** @internal */
667
+ _children;
668
+ /** @internal */
669
+ _namedChildren;
670
+ /** @internal */
671
+ constructor(internal, {
672
+ id,
673
+ tree,
674
+ startIndex,
675
+ startPosition,
676
+ other
677
+ }) {
678
+ assertInternal(internal);
679
+ this[0] = other;
680
+ this.id = id;
681
+ this.tree = tree;
682
+ this.startIndex = startIndex;
683
+ this.startPosition = startPosition;
684
+ }
685
+ /**
686
+ * The numeric id for this node that is unique.
687
+ *
688
+ * Within a given syntax tree, no two nodes have the same id. However:
689
+ *
690
+ * * If a new tree is created based on an older tree, and a node from the old tree is reused in
691
+ * the process, then that node will have the same id in both trees.
692
+ *
693
+ * * A node not marked as having changes does not guarantee it was reused.
694
+ *
695
+ * * If a node is marked as having changed in the old tree, it will not be reused.
696
+ */
697
+ id;
698
+ /** The byte index where this node starts. */
699
+ startIndex;
700
+ /** The position where this node starts. */
701
+ startPosition;
702
+ /** The tree that this node belongs to. */
703
+ tree;
704
+ /** Get this node's type as a numerical id. */
705
+ get typeId() {
706
+ marshalNode(this);
707
+ return C._ts_node_symbol_wasm(this.tree[0]);
708
+ }
709
+ /**
710
+ * Get the node's type as a numerical id as it appears in the grammar,
711
+ * ignoring aliases.
712
+ */
713
+ get grammarId() {
714
+ marshalNode(this);
715
+ return C._ts_node_grammar_symbol_wasm(this.tree[0]);
716
+ }
717
+ /** Get this node's type as a string. */
718
+ get type() {
719
+ return this.tree.language.types[this.typeId] || "ERROR";
720
+ }
721
+ /**
722
+ * Get this node's symbol name as it appears in the grammar, ignoring
723
+ * aliases as a string.
724
+ */
725
+ get grammarType() {
726
+ return this.tree.language.types[this.grammarId] || "ERROR";
727
+ }
728
+ /**
729
+ * Check if this node is *named*.
730
+ *
731
+ * Named nodes correspond to named rules in the grammar, whereas
732
+ * *anonymous* nodes correspond to string literals in the grammar.
733
+ */
734
+ get isNamed() {
735
+ marshalNode(this);
736
+ return C._ts_node_is_named_wasm(this.tree[0]) === 1;
737
+ }
738
+ /**
739
+ * Check if this node is *extra*.
740
+ *
741
+ * Extra nodes represent things like comments, which are not required
742
+ * by the grammar, but can appear anywhere.
743
+ */
744
+ get isExtra() {
745
+ marshalNode(this);
746
+ return C._ts_node_is_extra_wasm(this.tree[0]) === 1;
747
+ }
748
+ /**
749
+ * Check if this node represents a syntax error.
750
+ *
751
+ * Syntax errors represent parts of the code that could not be incorporated
752
+ * into a valid syntax tree.
753
+ */
754
+ get isError() {
755
+ marshalNode(this);
756
+ return C._ts_node_is_error_wasm(this.tree[0]) === 1;
757
+ }
758
+ /**
759
+ * Check if this node is *missing*.
760
+ *
761
+ * Missing nodes are inserted by the parser in order to recover from
762
+ * certain kinds of syntax errors.
763
+ */
764
+ get isMissing() {
765
+ marshalNode(this);
766
+ return C._ts_node_is_missing_wasm(this.tree[0]) === 1;
767
+ }
768
+ /** Check if this node has been edited. */
769
+ get hasChanges() {
770
+ marshalNode(this);
771
+ return C._ts_node_has_changes_wasm(this.tree[0]) === 1;
772
+ }
773
+ /**
774
+ * Check if this node represents a syntax error or contains any syntax
775
+ * errors anywhere within it.
776
+ */
777
+ get hasError() {
778
+ marshalNode(this);
779
+ return C._ts_node_has_error_wasm(this.tree[0]) === 1;
780
+ }
781
+ /** Get the byte index where this node ends. */
782
+ get endIndex() {
783
+ marshalNode(this);
784
+ return C._ts_node_end_index_wasm(this.tree[0]);
785
+ }
786
+ /** Get the position where this node ends. */
787
+ get endPosition() {
788
+ marshalNode(this);
789
+ C._ts_node_end_point_wasm(this.tree[0]);
790
+ return unmarshalPoint(TRANSFER_BUFFER);
791
+ }
792
+ /** Get the string content of this node. */
793
+ get text() {
794
+ return getText(this.tree, this.startIndex, this.endIndex, this.startPosition);
795
+ }
796
+ /** Get this node's parse state. */
797
+ get parseState() {
798
+ marshalNode(this);
799
+ return C._ts_node_parse_state_wasm(this.tree[0]);
800
+ }
801
+ /** Get the parse state after this node. */
802
+ get nextParseState() {
803
+ marshalNode(this);
804
+ return C._ts_node_next_parse_state_wasm(this.tree[0]);
805
+ }
806
+ /** Check if this node is equal to another node. */
807
+ equals(other) {
808
+ return this.tree === other.tree && this.id === other.id;
809
+ }
810
+ /**
811
+ * Get the node's child at the given index, where zero represents the first child.
812
+ *
813
+ * This method is fairly fast, but its cost is technically log(n), so if
814
+ * you might be iterating over a long list of children, you should use
815
+ * {@link Node#children} instead.
816
+ */
817
+ child(index) {
818
+ marshalNode(this);
819
+ C._ts_node_child_wasm(this.tree[0], index);
820
+ return unmarshalNode(this.tree);
821
+ }
822
+ /**
823
+ * Get this node's *named* child at the given index.
824
+ *
825
+ * See also {@link Node#isNamed}.
826
+ * This method is fairly fast, but its cost is technically log(n), so if
827
+ * you might be iterating over a long list of children, you should use
828
+ * {@link Node#namedChildren} instead.
829
+ */
830
+ namedChild(index) {
831
+ marshalNode(this);
832
+ C._ts_node_named_child_wasm(this.tree[0], index);
833
+ return unmarshalNode(this.tree);
834
+ }
835
+ /**
836
+ * Get this node's child with the given numerical field id.
837
+ *
838
+ * See also {@link Node#childForFieldName}. You can
839
+ * convert a field name to an id using {@link Language#fieldIdForName}.
840
+ */
841
+ childForFieldId(fieldId) {
842
+ marshalNode(this);
843
+ C._ts_node_child_by_field_id_wasm(this.tree[0], fieldId);
844
+ return unmarshalNode(this.tree);
845
+ }
846
+ /**
847
+ * Get the first child with the given field name.
848
+ *
849
+ * If multiple children may have the same field name, access them using
850
+ * {@link Node#childrenForFieldName}.
851
+ */
852
+ childForFieldName(fieldName) {
853
+ const fieldId = this.tree.language.fields.indexOf(fieldName);
854
+ if (fieldId !== -1) return this.childForFieldId(fieldId);
855
+ return null;
856
+ }
857
+ /** Get the field name of this node's child at the given index. */
858
+ fieldNameForChild(index) {
859
+ marshalNode(this);
860
+ const address = C._ts_node_field_name_for_child_wasm(this.tree[0], index);
861
+ if (!address) return null;
862
+ return C.AsciiToString(address);
863
+ }
864
+ /** Get the field name of this node's named child at the given index. */
865
+ fieldNameForNamedChild(index) {
866
+ marshalNode(this);
867
+ const address = C._ts_node_field_name_for_named_child_wasm(this.tree[0], index);
868
+ if (!address) return null;
869
+ return C.AsciiToString(address);
870
+ }
871
+ /**
872
+ * Get an array of this node's children with a given field name.
873
+ *
874
+ * See also {@link Node#children}.
875
+ */
876
+ childrenForFieldName(fieldName) {
877
+ const fieldId = this.tree.language.fields.indexOf(fieldName);
878
+ if (fieldId !== -1 && fieldId !== 0) return this.childrenForFieldId(fieldId);
879
+ return [];
880
+ }
881
+ /**
882
+ * Get an array of this node's children with a given field id.
883
+ *
884
+ * See also {@link Node#childrenForFieldName}.
885
+ */
886
+ childrenForFieldId(fieldId) {
887
+ marshalNode(this);
888
+ C._ts_node_children_by_field_id_wasm(this.tree[0], fieldId);
889
+ const count = C.getValue(TRANSFER_BUFFER, "i32");
890
+ const buffer = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
891
+ const result = new Array(count);
892
+ if (count > 0) {
893
+ let address = buffer;
894
+ for (let i = 0; i < count; i++) {
895
+ result[i] = unmarshalNode(this.tree, address);
896
+ address += SIZE_OF_NODE;
897
+ }
898
+ C._free(buffer);
899
+ }
900
+ return result;
901
+ }
902
+ /** Get the node's first child that contains or starts after the given byte offset. */
903
+ firstChildForIndex(index) {
904
+ marshalNode(this);
905
+ const address = TRANSFER_BUFFER + SIZE_OF_NODE;
906
+ C.setValue(address, index, "i32");
907
+ C._ts_node_first_child_for_byte_wasm(this.tree[0]);
908
+ return unmarshalNode(this.tree);
909
+ }
910
+ /** Get the node's first named child that contains or starts after the given byte offset. */
911
+ firstNamedChildForIndex(index) {
912
+ marshalNode(this);
913
+ const address = TRANSFER_BUFFER + SIZE_OF_NODE;
914
+ C.setValue(address, index, "i32");
915
+ C._ts_node_first_named_child_for_byte_wasm(this.tree[0]);
916
+ return unmarshalNode(this.tree);
917
+ }
918
+ /** Get this node's number of children. */
919
+ get childCount() {
920
+ marshalNode(this);
921
+ return C._ts_node_child_count_wasm(this.tree[0]);
922
+ }
923
+ /**
924
+ * Get this node's number of *named* children.
925
+ *
926
+ * See also {@link Node#isNamed}.
927
+ */
928
+ get namedChildCount() {
929
+ marshalNode(this);
930
+ return C._ts_node_named_child_count_wasm(this.tree[0]);
931
+ }
932
+ /** Get this node's first child. */
933
+ get firstChild() {
934
+ return this.child(0);
935
+ }
936
+ /**
937
+ * Get this node's first named child.
938
+ *
939
+ * See also {@link Node#isNamed}.
940
+ */
941
+ get firstNamedChild() {
942
+ return this.namedChild(0);
943
+ }
944
+ /** Get this node's last child. */
945
+ get lastChild() {
946
+ return this.child(this.childCount - 1);
947
+ }
948
+ /**
949
+ * Get this node's last named child.
950
+ *
951
+ * See also {@link Node#isNamed}.
952
+ */
953
+ get lastNamedChild() {
954
+ return this.namedChild(this.namedChildCount - 1);
955
+ }
956
+ /**
957
+ * Iterate over this node's children.
958
+ *
959
+ * If you're walking the tree recursively, you may want to use the
960
+ * {@link TreeCursor} APIs directly instead.
961
+ */
962
+ get children() {
963
+ if (!this._children) {
964
+ marshalNode(this);
965
+ C._ts_node_children_wasm(this.tree[0]);
966
+ const count = C.getValue(TRANSFER_BUFFER, "i32");
967
+ const buffer = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
968
+ this._children = new Array(count);
969
+ if (count > 0) {
970
+ let address = buffer;
971
+ for (let i = 0; i < count; i++) {
972
+ this._children[i] = unmarshalNode(this.tree, address);
973
+ address += SIZE_OF_NODE;
974
+ }
975
+ C._free(buffer);
976
+ }
977
+ }
978
+ return this._children;
979
+ }
980
+ /**
981
+ * Iterate over this node's named children.
982
+ *
983
+ * See also {@link Node#children}.
984
+ */
985
+ get namedChildren() {
986
+ if (!this._namedChildren) {
987
+ marshalNode(this);
988
+ C._ts_node_named_children_wasm(this.tree[0]);
989
+ const count = C.getValue(TRANSFER_BUFFER, "i32");
990
+ const buffer = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
991
+ this._namedChildren = new Array(count);
992
+ if (count > 0) {
993
+ let address = buffer;
994
+ for (let i = 0; i < count; i++) {
995
+ this._namedChildren[i] = unmarshalNode(this.tree, address);
996
+ address += SIZE_OF_NODE;
997
+ }
998
+ C._free(buffer);
999
+ }
1000
+ }
1001
+ return this._namedChildren;
1002
+ }
1003
+ /**
1004
+ * Get the descendants of this node that are the given type, or in the given types array.
1005
+ *
1006
+ * The types array should contain node type strings, which can be retrieved from {@link Language#types}.
1007
+ *
1008
+ * Additionally, a `startPosition` and `endPosition` can be passed in to restrict the search to a byte range.
1009
+ */
1010
+ descendantsOfType(types, startPosition = ZERO_POINT, endPosition = ZERO_POINT) {
1011
+ if (!Array.isArray(types)) types = [types];
1012
+ const symbols = [];
1013
+ const typesBySymbol = this.tree.language.types;
1014
+ for (const node_type of types) {
1015
+ if (node_type == "ERROR") {
1016
+ symbols.push(65535);
1017
+ }
1018
+ }
1019
+ for (let i = 0, n = typesBySymbol.length; i < n; i++) {
1020
+ if (types.includes(typesBySymbol[i])) {
1021
+ symbols.push(i);
1022
+ }
1023
+ }
1024
+ const symbolsAddress = C._malloc(SIZE_OF_INT * symbols.length);
1025
+ for (let i = 0, n = symbols.length; i < n; i++) {
1026
+ C.setValue(symbolsAddress + i * SIZE_OF_INT, symbols[i], "i32");
1027
+ }
1028
+ marshalNode(this);
1029
+ C._ts_node_descendants_of_type_wasm(
1030
+ this.tree[0],
1031
+ symbolsAddress,
1032
+ symbols.length,
1033
+ startPosition.row,
1034
+ startPosition.column,
1035
+ endPosition.row,
1036
+ endPosition.column
1037
+ );
1038
+ const descendantCount = C.getValue(TRANSFER_BUFFER, "i32");
1039
+ const descendantAddress = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
1040
+ const result = new Array(descendantCount);
1041
+ if (descendantCount > 0) {
1042
+ let address = descendantAddress;
1043
+ for (let i = 0; i < descendantCount; i++) {
1044
+ result[i] = unmarshalNode(this.tree, address);
1045
+ address += SIZE_OF_NODE;
1046
+ }
1047
+ }
1048
+ C._free(descendantAddress);
1049
+ C._free(symbolsAddress);
1050
+ return result;
1051
+ }
1052
+ /** Get this node's next sibling. */
1053
+ get nextSibling() {
1054
+ marshalNode(this);
1055
+ C._ts_node_next_sibling_wasm(this.tree[0]);
1056
+ return unmarshalNode(this.tree);
1057
+ }
1058
+ /** Get this node's previous sibling. */
1059
+ get previousSibling() {
1060
+ marshalNode(this);
1061
+ C._ts_node_prev_sibling_wasm(this.tree[0]);
1062
+ return unmarshalNode(this.tree);
1063
+ }
1064
+ /**
1065
+ * Get this node's next *named* sibling.
1066
+ *
1067
+ * See also {@link Node#isNamed}.
1068
+ */
1069
+ get nextNamedSibling() {
1070
+ marshalNode(this);
1071
+ C._ts_node_next_named_sibling_wasm(this.tree[0]);
1072
+ return unmarshalNode(this.tree);
1073
+ }
1074
+ /**
1075
+ * Get this node's previous *named* sibling.
1076
+ *
1077
+ * See also {@link Node#isNamed}.
1078
+ */
1079
+ get previousNamedSibling() {
1080
+ marshalNode(this);
1081
+ C._ts_node_prev_named_sibling_wasm(this.tree[0]);
1082
+ return unmarshalNode(this.tree);
1083
+ }
1084
+ /** Get the node's number of descendants, including one for the node itself. */
1085
+ get descendantCount() {
1086
+ marshalNode(this);
1087
+ return C._ts_node_descendant_count_wasm(this.tree[0]);
1088
+ }
1089
+ /**
1090
+ * Get this node's immediate parent.
1091
+ * Prefer {@link Node#childWithDescendant} for iterating over this node's ancestors.
1092
+ */
1093
+ get parent() {
1094
+ marshalNode(this);
1095
+ C._ts_node_parent_wasm(this.tree[0]);
1096
+ return unmarshalNode(this.tree);
1097
+ }
1098
+ /**
1099
+ * Get the node that contains `descendant`.
1100
+ *
1101
+ * Note that this can return `descendant` itself.
1102
+ */
1103
+ childWithDescendant(descendant) {
1104
+ marshalNode(this);
1105
+ marshalNode(descendant, 1);
1106
+ C._ts_node_child_with_descendant_wasm(this.tree[0]);
1107
+ return unmarshalNode(this.tree);
1108
+ }
1109
+ /** Get the smallest node within this node that spans the given byte range. */
1110
+ descendantForIndex(start, end = start) {
1111
+ if (typeof start !== "number" || typeof end !== "number") {
1112
+ throw new Error("Arguments must be numbers");
1113
+ }
1114
+ marshalNode(this);
1115
+ const address = TRANSFER_BUFFER + SIZE_OF_NODE;
1116
+ C.setValue(address, start, "i32");
1117
+ C.setValue(address + SIZE_OF_INT, end, "i32");
1118
+ C._ts_node_descendant_for_index_wasm(this.tree[0]);
1119
+ return unmarshalNode(this.tree);
1120
+ }
1121
+ /** Get the smallest named node within this node that spans the given byte range. */
1122
+ namedDescendantForIndex(start, end = start) {
1123
+ if (typeof start !== "number" || typeof end !== "number") {
1124
+ throw new Error("Arguments must be numbers");
1125
+ }
1126
+ marshalNode(this);
1127
+ const address = TRANSFER_BUFFER + SIZE_OF_NODE;
1128
+ C.setValue(address, start, "i32");
1129
+ C.setValue(address + SIZE_OF_INT, end, "i32");
1130
+ C._ts_node_named_descendant_for_index_wasm(this.tree[0]);
1131
+ return unmarshalNode(this.tree);
1132
+ }
1133
+ /** Get the smallest node within this node that spans the given point range. */
1134
+ descendantForPosition(start, end = start) {
1135
+ if (!isPoint(start) || !isPoint(end)) {
1136
+ throw new Error("Arguments must be {row, column} objects");
1137
+ }
1138
+ marshalNode(this);
1139
+ const address = TRANSFER_BUFFER + SIZE_OF_NODE;
1140
+ marshalPoint(address, start);
1141
+ marshalPoint(address + SIZE_OF_POINT, end);
1142
+ C._ts_node_descendant_for_position_wasm(this.tree[0]);
1143
+ return unmarshalNode(this.tree);
1144
+ }
1145
+ /** Get the smallest named node within this node that spans the given point range. */
1146
+ namedDescendantForPosition(start, end = start) {
1147
+ if (!isPoint(start) || !isPoint(end)) {
1148
+ throw new Error("Arguments must be {row, column} objects");
1149
+ }
1150
+ marshalNode(this);
1151
+ const address = TRANSFER_BUFFER + SIZE_OF_NODE;
1152
+ marshalPoint(address, start);
1153
+ marshalPoint(address + SIZE_OF_POINT, end);
1154
+ C._ts_node_named_descendant_for_position_wasm(this.tree[0]);
1155
+ return unmarshalNode(this.tree);
1156
+ }
1157
+ /**
1158
+ * Create a new {@link TreeCursor} starting from this node.
1159
+ *
1160
+ * Note that the given node is considered the root of the cursor,
1161
+ * and the cursor cannot walk outside this node.
1162
+ */
1163
+ walk() {
1164
+ marshalNode(this);
1165
+ C._ts_tree_cursor_new_wasm(this.tree[0]);
1166
+ return new TreeCursor(INTERNAL, this.tree);
1167
+ }
1168
+ /**
1169
+ * Edit this node to keep it in-sync with source code that has been edited.
1170
+ *
1171
+ * This function is only rarely needed. When you edit a syntax tree with
1172
+ * the {@link Tree#edit} method, all of the nodes that you retrieve from
1173
+ * the tree afterward will already reflect the edit. You only need to
1174
+ * use {@link Node#edit} when you have a specific {@link Node} instance that
1175
+ * you want to keep and continue to use after an edit.
1176
+ */
1177
+ edit(edit) {
1178
+ if (this.startIndex >= edit.oldEndIndex) {
1179
+ this.startIndex = edit.newEndIndex + (this.startIndex - edit.oldEndIndex);
1180
+ let subbedPointRow;
1181
+ let subbedPointColumn;
1182
+ if (this.startPosition.row > edit.oldEndPosition.row) {
1183
+ subbedPointRow = this.startPosition.row - edit.oldEndPosition.row;
1184
+ subbedPointColumn = this.startPosition.column;
1185
+ } else {
1186
+ subbedPointRow = 0;
1187
+ subbedPointColumn = this.startPosition.column;
1188
+ if (this.startPosition.column >= edit.oldEndPosition.column) {
1189
+ subbedPointColumn = this.startPosition.column - edit.oldEndPosition.column;
1190
+ }
1191
+ }
1192
+ if (subbedPointRow > 0) {
1193
+ this.startPosition.row += subbedPointRow;
1194
+ this.startPosition.column = subbedPointColumn;
1195
+ } else {
1196
+ this.startPosition.column += subbedPointColumn;
1197
+ }
1198
+ } else if (this.startIndex > edit.startIndex) {
1199
+ this.startIndex = edit.newEndIndex;
1200
+ this.startPosition.row = edit.newEndPosition.row;
1201
+ this.startPosition.column = edit.newEndPosition.column;
1202
+ }
1203
+ }
1204
+ /** Get the S-expression representation of this node. */
1205
+ toString() {
1206
+ marshalNode(this);
1207
+ const address = C._ts_node_to_string_wasm(this.tree[0]);
1208
+ const result = C.AsciiToString(address);
1209
+ C._free(address);
1210
+ return result;
1211
+ }
1212
+ };
1213
+
1214
+ // src/marshal.ts
1215
+ function unmarshalCaptures(query, tree, address, patternIndex, result) {
1216
+ for (let i = 0, n = result.length; i < n; i++) {
1217
+ const captureIndex = C.getValue(address, "i32");
1218
+ address += SIZE_OF_INT;
1219
+ const node = unmarshalNode(tree, address);
1220
+ address += SIZE_OF_NODE;
1221
+ result[i] = { patternIndex, name: query.captureNames[captureIndex], node };
1222
+ }
1223
+ return address;
1224
+ }
1225
+ __name(unmarshalCaptures, "unmarshalCaptures");
1226
+ function marshalNode(node, index = 0) {
1227
+ let address = TRANSFER_BUFFER + index * SIZE_OF_NODE;
1228
+ C.setValue(address, node.id, "i32");
1229
+ address += SIZE_OF_INT;
1230
+ C.setValue(address, node.startIndex, "i32");
1231
+ address += SIZE_OF_INT;
1232
+ C.setValue(address, node.startPosition.row, "i32");
1233
+ address += SIZE_OF_INT;
1234
+ C.setValue(address, node.startPosition.column, "i32");
1235
+ address += SIZE_OF_INT;
1236
+ C.setValue(address, node[0], "i32");
1237
+ }
1238
+ __name(marshalNode, "marshalNode");
1239
+ function unmarshalNode(tree, address = TRANSFER_BUFFER) {
1240
+ const id = C.getValue(address, "i32");
1241
+ address += SIZE_OF_INT;
1242
+ if (id === 0) return null;
1243
+ const index = C.getValue(address, "i32");
1244
+ address += SIZE_OF_INT;
1245
+ const row = C.getValue(address, "i32");
1246
+ address += SIZE_OF_INT;
1247
+ const column = C.getValue(address, "i32");
1248
+ address += SIZE_OF_INT;
1249
+ const other = C.getValue(address, "i32");
1250
+ const result = new Node(INTERNAL, {
1251
+ id,
1252
+ tree,
1253
+ startIndex: index,
1254
+ startPosition: { row, column },
1255
+ other
1256
+ });
1257
+ return result;
1258
+ }
1259
+ __name(unmarshalNode, "unmarshalNode");
1260
+ function marshalTreeCursor(cursor, address = TRANSFER_BUFFER) {
1261
+ C.setValue(address + 0 * SIZE_OF_INT, cursor[0], "i32");
1262
+ C.setValue(address + 1 * SIZE_OF_INT, cursor[1], "i32");
1263
+ C.setValue(address + 2 * SIZE_OF_INT, cursor[2], "i32");
1264
+ C.setValue(address + 3 * SIZE_OF_INT, cursor[3], "i32");
1265
+ }
1266
+ __name(marshalTreeCursor, "marshalTreeCursor");
1267
+ function unmarshalTreeCursor(cursor) {
1268
+ cursor[0] = C.getValue(TRANSFER_BUFFER + 0 * SIZE_OF_INT, "i32");
1269
+ cursor[1] = C.getValue(TRANSFER_BUFFER + 1 * SIZE_OF_INT, "i32");
1270
+ cursor[2] = C.getValue(TRANSFER_BUFFER + 2 * SIZE_OF_INT, "i32");
1271
+ cursor[3] = C.getValue(TRANSFER_BUFFER + 3 * SIZE_OF_INT, "i32");
1272
+ }
1273
+ __name(unmarshalTreeCursor, "unmarshalTreeCursor");
1274
+ function marshalPoint(address, point) {
1275
+ C.setValue(address, point.row, "i32");
1276
+ C.setValue(address + SIZE_OF_INT, point.column, "i32");
1277
+ }
1278
+ __name(marshalPoint, "marshalPoint");
1279
+ function unmarshalPoint(address) {
1280
+ const result = {
1281
+ row: C.getValue(address, "i32") >>> 0,
1282
+ column: C.getValue(address + SIZE_OF_INT, "i32") >>> 0
1283
+ };
1284
+ return result;
1285
+ }
1286
+ __name(unmarshalPoint, "unmarshalPoint");
1287
+ function marshalRange(address, range) {
1288
+ marshalPoint(address, range.startPosition);
1289
+ address += SIZE_OF_POINT;
1290
+ marshalPoint(address, range.endPosition);
1291
+ address += SIZE_OF_POINT;
1292
+ C.setValue(address, range.startIndex, "i32");
1293
+ address += SIZE_OF_INT;
1294
+ C.setValue(address, range.endIndex, "i32");
1295
+ address += SIZE_OF_INT;
1296
+ }
1297
+ __name(marshalRange, "marshalRange");
1298
+ function unmarshalRange(address) {
1299
+ const result = {};
1300
+ result.startPosition = unmarshalPoint(address);
1301
+ address += SIZE_OF_POINT;
1302
+ result.endPosition = unmarshalPoint(address);
1303
+ address += SIZE_OF_POINT;
1304
+ result.startIndex = C.getValue(address, "i32") >>> 0;
1305
+ address += SIZE_OF_INT;
1306
+ result.endIndex = C.getValue(address, "i32") >>> 0;
1307
+ return result;
1308
+ }
1309
+ __name(unmarshalRange, "unmarshalRange");
1310
+ function marshalEdit(edit, address = TRANSFER_BUFFER) {
1311
+ marshalPoint(address, edit.startPosition);
1312
+ address += SIZE_OF_POINT;
1313
+ marshalPoint(address, edit.oldEndPosition);
1314
+ address += SIZE_OF_POINT;
1315
+ marshalPoint(address, edit.newEndPosition);
1316
+ address += SIZE_OF_POINT;
1317
+ C.setValue(address, edit.startIndex, "i32");
1318
+ address += SIZE_OF_INT;
1319
+ C.setValue(address, edit.oldEndIndex, "i32");
1320
+ address += SIZE_OF_INT;
1321
+ C.setValue(address, edit.newEndIndex, "i32");
1322
+ address += SIZE_OF_INT;
1323
+ }
1324
+ __name(marshalEdit, "marshalEdit");
1325
+ function unmarshalLanguageMetadata(address) {
1326
+ const major_version = C.getValue(address, "i32");
1327
+ const minor_version = C.getValue(address += SIZE_OF_INT, "i32");
1328
+ const patch_version = C.getValue(address += SIZE_OF_INT, "i32");
1329
+ return { major_version, minor_version, patch_version };
1330
+ }
1331
+ __name(unmarshalLanguageMetadata, "unmarshalLanguageMetadata");
1332
+
1333
+ // src/language.ts
1334
+ var LANGUAGE_FUNCTION_REGEX = /^tree_sitter_\w+$/;
1335
+ var Language = class _Language {
1336
+ static {
1337
+ __name(this, "Language");
1338
+ }
1339
+ /** @internal */
1340
+ [0] = 0;
1341
+ // Internal handle for Wasm
1342
+ /**
1343
+ * A list of all node types in the language. The index of each type in this
1344
+ * array is its node type id.
1345
+ */
1346
+ types;
1347
+ /**
1348
+ * A list of all field names in the language. The index of each field name in
1349
+ * this array is its field id.
1350
+ */
1351
+ fields;
1352
+ /** @internal */
1353
+ constructor(internal, address) {
1354
+ assertInternal(internal);
1355
+ this[0] = address;
1356
+ this.types = new Array(C._ts_language_symbol_count(this[0]));
1357
+ for (let i = 0, n = this.types.length; i < n; i++) {
1358
+ if (C._ts_language_symbol_type(this[0], i) < 2) {
1359
+ this.types[i] = C.UTF8ToString(C._ts_language_symbol_name(this[0], i));
1360
+ }
1361
+ }
1362
+ this.fields = new Array(C._ts_language_field_count(this[0]) + 1);
1363
+ for (let i = 0, n = this.fields.length; i < n; i++) {
1364
+ const fieldName = C._ts_language_field_name_for_id(this[0], i);
1365
+ if (fieldName !== 0) {
1366
+ this.fields[i] = C.UTF8ToString(fieldName);
1367
+ } else {
1368
+ this.fields[i] = null;
1369
+ }
1370
+ }
1371
+ }
1372
+ /**
1373
+ * Gets the name of the language.
1374
+ */
1375
+ get name() {
1376
+ const ptr = C._ts_language_name(this[0]);
1377
+ if (ptr === 0) return null;
1378
+ return C.UTF8ToString(ptr);
1379
+ }
1380
+ /**
1381
+ * Gets the ABI version of the language.
1382
+ */
1383
+ get abiVersion() {
1384
+ return C._ts_language_abi_version(this[0]);
1385
+ }
1386
+ /**
1387
+ * Get the metadata for this language. This information is generated by the
1388
+ * CLI, and relies on the language author providing the correct metadata in
1389
+ * the language's `tree-sitter.json` file.
1390
+ */
1391
+ get metadata() {
1392
+ C._ts_language_metadata_wasm(this[0]);
1393
+ const length = C.getValue(TRANSFER_BUFFER, "i32");
1394
+ if (length === 0) return null;
1395
+ return unmarshalLanguageMetadata(TRANSFER_BUFFER + SIZE_OF_INT);
1396
+ }
1397
+ /**
1398
+ * Gets the number of fields in the language.
1399
+ */
1400
+ get fieldCount() {
1401
+ return this.fields.length - 1;
1402
+ }
1403
+ /**
1404
+ * Gets the number of states in the language.
1405
+ */
1406
+ get stateCount() {
1407
+ return C._ts_language_state_count(this[0]);
1408
+ }
1409
+ /**
1410
+ * Get the field id for a field name.
1411
+ */
1412
+ fieldIdForName(fieldName) {
1413
+ const result = this.fields.indexOf(fieldName);
1414
+ return result !== -1 ? result : null;
1415
+ }
1416
+ /**
1417
+ * Get the field name for a field id.
1418
+ */
1419
+ fieldNameForId(fieldId) {
1420
+ return this.fields[fieldId] ?? null;
1421
+ }
1422
+ /**
1423
+ * Get the node type id for a node type name.
1424
+ */
1425
+ idForNodeType(type, named) {
1426
+ const typeLength = C.lengthBytesUTF8(type);
1427
+ const typeAddress = C._malloc(typeLength + 1);
1428
+ C.stringToUTF8(type, typeAddress, typeLength + 1);
1429
+ const result = C._ts_language_symbol_for_name(this[0], typeAddress, typeLength, named ? 1 : 0);
1430
+ C._free(typeAddress);
1431
+ return result || null;
1432
+ }
1433
+ /**
1434
+ * Gets the number of node types in the language.
1435
+ */
1436
+ get nodeTypeCount() {
1437
+ return C._ts_language_symbol_count(this[0]);
1438
+ }
1439
+ /**
1440
+ * Get the node type name for a node type id.
1441
+ */
1442
+ nodeTypeForId(typeId) {
1443
+ const name = C._ts_language_symbol_name(this[0], typeId);
1444
+ return name ? C.UTF8ToString(name) : null;
1445
+ }
1446
+ /**
1447
+ * Check if a node type is named.
1448
+ *
1449
+ * @see {@link https://tree-sitter.github.io/tree-sitter/using-parsers/2-basic-parsing.html#named-vs-anonymous-nodes}
1450
+ */
1451
+ nodeTypeIsNamed(typeId) {
1452
+ return C._ts_language_type_is_named_wasm(this[0], typeId) ? true : false;
1453
+ }
1454
+ /**
1455
+ * Check if a node type is visible.
1456
+ */
1457
+ nodeTypeIsVisible(typeId) {
1458
+ return C._ts_language_type_is_visible_wasm(this[0], typeId) ? true : false;
1459
+ }
1460
+ /**
1461
+ * Get the supertypes ids of this language.
1462
+ *
1463
+ * @see {@link https://tree-sitter.github.io/tree-sitter/using-parsers/6-static-node-types.html?highlight=supertype#supertype-nodes}
1464
+ */
1465
+ get supertypes() {
1466
+ C._ts_language_supertypes_wasm(this[0]);
1467
+ const count = C.getValue(TRANSFER_BUFFER, "i32");
1468
+ const buffer = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
1469
+ const result = new Array(count);
1470
+ if (count > 0) {
1471
+ let address = buffer;
1472
+ for (let i = 0; i < count; i++) {
1473
+ result[i] = C.getValue(address, "i16");
1474
+ address += SIZE_OF_SHORT;
1475
+ }
1476
+ }
1477
+ return result;
1478
+ }
1479
+ /**
1480
+ * Get the subtype ids for a given supertype node id.
1481
+ */
1482
+ subtypes(supertype) {
1483
+ C._ts_language_subtypes_wasm(this[0], supertype);
1484
+ const count = C.getValue(TRANSFER_BUFFER, "i32");
1485
+ const buffer = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
1486
+ const result = new Array(count);
1487
+ if (count > 0) {
1488
+ let address = buffer;
1489
+ for (let i = 0; i < count; i++) {
1490
+ result[i] = C.getValue(address, "i16");
1491
+ address += SIZE_OF_SHORT;
1492
+ }
1493
+ }
1494
+ return result;
1495
+ }
1496
+ /**
1497
+ * Get the next state id for a given state id and node type id.
1498
+ */
1499
+ nextState(stateId, typeId) {
1500
+ return C._ts_language_next_state(this[0], stateId, typeId);
1501
+ }
1502
+ /**
1503
+ * Create a new lookahead iterator for this language and parse state.
1504
+ *
1505
+ * This returns `null` if state is invalid for this language.
1506
+ *
1507
+ * Iterating {@link LookaheadIterator} will yield valid symbols in the given
1508
+ * parse state. A newly created iterator is not positioned on a symbol, so
1509
+ * {@link LookaheadIterator#currentType} returns `null` until the first
1510
+ * iteration step.
1511
+ *
1512
+ * Lookahead iterators can be useful for generating suggestions and improving
1513
+ * syntax error diagnostics. To get symbols valid in an `ERROR` node, use the
1514
+ * lookahead iterator on its first leaf node state. For `MISSING` nodes, a
1515
+ * lookahead iterator created on the previous non-extra leaf node may be
1516
+ * appropriate.
1517
+ */
1518
+ lookaheadIterator(stateId) {
1519
+ const address = C._ts_lookahead_iterator_new(this[0], stateId);
1520
+ if (address) return new LookaheadIterator(INTERNAL, address, this);
1521
+ return null;
1522
+ }
1523
+ /**
1524
+ * Load a language from a WebAssembly module.
1525
+ * The module can be provided as a path to a file, a `URL` to a file, or as a
1526
+ * buffer.
1527
+ */
1528
+ static async load(input) {
1529
+ let binary;
1530
+ if (input instanceof Uint8Array) {
1531
+ binary = input;
1532
+ } else if (globalThis.process?.versions.node) {
1533
+ const fs = await import("fs/promises");
1534
+ binary = await fs.readFile(input);
1535
+ } else {
1536
+ const response = await fetch(input);
1537
+ if (!response.ok) {
1538
+ const body = await response.text();
1539
+ throw new Error(`Language.load failed with status ${response.status}.
1540
+
1541
+ ${body}`);
1542
+ }
1543
+ const retryResp = response.clone();
1544
+ try {
1545
+ binary = await WebAssembly.compileStreaming(response);
1546
+ } catch (reason) {
1547
+ console.error("wasm streaming compile failed:", reason);
1548
+ console.error("falling back to ArrayBuffer instantiation");
1549
+ binary = new Uint8Array(await retryResp.arrayBuffer());
1550
+ }
1551
+ }
1552
+ const mod = await C.loadWebAssemblyModule(binary, { loadAsync: true });
1553
+ return _Language.loadFromWasmExports(mod, { sync: false });
1554
+ }
1555
+ static loadFromWasmExports(mod, { sync }) {
1556
+ const symbolNames = Object.keys(mod);
1557
+ const functionName = symbolNames.find((key) => LANGUAGE_FUNCTION_REGEX.test(key) && !key.includes("external_scanner_"));
1558
+ if (!functionName) {
1559
+ console.log(`Couldn't find language function in Wasm file. Symbols:
1560
+ ${JSON.stringify(symbolNames, null, 2)}`);
1561
+ throw new Error(`Language.${sync ? "loadSync" : "load"} failed: no language function found in Wasm file`);
1562
+ }
1563
+ const languageAddress = mod[functionName]();
1564
+ return new _Language(INTERNAL, languageAddress);
1565
+ }
1566
+ /**
1567
+ * Load a language synchronously from a pre-compiled WebAssembly module.
1568
+ * Use this when the host environment provides a `WebAssembly.Module` directly.
1569
+ */
1570
+ static loadSync(wasmModule) {
1571
+ const mod = C.loadWebAssemblyModule(wasmModule, { loadAsync: false });
1572
+ return _Language.loadFromWasmExports(mod, { sync: true });
1573
+ }
1574
+ };
1575
+
1576
+ // src/wasi-module.ts
1577
+ var ERRNO_BADF = 8;
1578
+ var ERRNO_NOSYS = 52;
1579
+ function wasiImports(module) {
1580
+ const wasi = {};
1581
+ for (const { module: from, name } of WebAssembly.Module.imports(module)) {
1582
+ if (from !== "wasi_snapshot_preview1") continue;
1583
+ if (name === "proc_exit") {
1584
+ wasi[name] = () => {
1585
+ throw new Error("tree-sitter runtime exited");
1586
+ };
1587
+ } else {
1588
+ wasi[name] = name.startsWith("fd_") ? () => ERRNO_BADF : () => ERRNO_NOSYS;
1589
+ }
1590
+ }
1591
+ return wasi;
1592
+ }
1593
+ __name(wasiImports, "wasiImports");
1594
+ var utf8Decoder = new TextDecoder();
1595
+ var utf8Encoder = new TextEncoder();
1596
+ var INPUT_BUFFER_SIZE = 10 * 1024;
1597
+ function readLeb(bytes, cursor) {
1598
+ let result = 0;
1599
+ let shift = 0;
1600
+ let byte;
1601
+ do {
1602
+ byte = bytes[cursor.at++];
1603
+ result |= (byte & 127) << shift;
1604
+ shift += 7;
1605
+ } while (byte & 128);
1606
+ return result >>> 0;
1607
+ }
1608
+ __name(readLeb, "readLeb");
1609
+ function dylinkInfo(module) {
1610
+ const info = { memorySize: 0, memoryAlign: 0, tableSize: 0, tableAlign: 0 };
1611
+ const sections = WebAssembly.Module.customSections(module, "dylink.0");
1612
+ if (sections.length === 0) throw new Error("Language module has no dylink.0 section");
1613
+ const bytes = new Uint8Array(sections[0]);
1614
+ const cursor = { at: 0 };
1615
+ while (cursor.at < bytes.length) {
1616
+ const type = bytes[cursor.at++];
1617
+ const size = readLeb(bytes, cursor);
1618
+ const end = cursor.at + size;
1619
+ if (type === 1) {
1620
+ info.memorySize = readLeb(bytes, cursor);
1621
+ info.memoryAlign = readLeb(bytes, cursor);
1622
+ info.tableSize = readLeb(bytes, cursor);
1623
+ info.tableAlign = readLeb(bytes, cursor);
1624
+ }
1625
+ cursor.at = end;
1626
+ }
1627
+ return info;
1628
+ }
1629
+ __name(dylinkInfo, "dylinkInfo");
1630
+ async function runtimeBytes(options) {
1631
+ if (options.wasmBinary) return options.wasmBinary;
1632
+ const base = new URL(".", import.meta.url).href;
1633
+ const location = options.locateFile?.("web-tree-sitter.wasm", base) ?? new URL("web-tree-sitter.wasm", import.meta.url).href;
1634
+ const isPath = /^[a-z]:/i.test(location) || !/^[a-z][a-z\d+.-]*:/i.test(location);
1635
+ if (typeof process !== "undefined" && process.versions.node && isPath) {
1636
+ const { readFile } = await import("fs/promises");
1637
+ return readFile(location);
1638
+ }
1639
+ const url = new URL(location, base);
1640
+ if (url.protocol === "file:") {
1641
+ const { readFile } = await import("fs/promises");
1642
+ return readFile(url).catch((error) => {
1643
+ if (options.locateFile) throw error;
1644
+ return readFile(new URL("../lib/web-tree-sitter.wasm", import.meta.url));
1645
+ });
1646
+ }
1647
+ const response = await fetch(url);
1648
+ if (!response.ok) throw new Error(`Failed to load ${url.href}: ${response.status}`);
1649
+ return response.arrayBuffer();
1650
+ }
1651
+ __name(runtimeBytes, "runtimeBytes");
1652
+ async function createModule(options = {}) {
1653
+ const module = {
1654
+ currentParseCallback: null,
1655
+ currentLogCallback: null,
1656
+ currentProgressCallback: null,
1657
+ currentQueryProgressCallback: null
1658
+ };
1659
+ const runtime = { exports: void 0 };
1660
+ let heapBuffer = null;
1661
+ let heap2 = new DataView(new ArrayBuffer(0));
1662
+ let heap8 = new Int8Array(0);
1663
+ let heapU8 = new Uint8Array(0);
1664
+ let heap16 = new Int16Array(0);
1665
+ let heap32 = new Int32Array(0);
1666
+ const refresh = /* @__PURE__ */ __name(() => {
1667
+ const buffer = runtime.exports.memory.buffer;
1668
+ if (buffer === heapBuffer) return;
1669
+ heapBuffer = buffer;
1670
+ heap2 = new DataView(buffer);
1671
+ heap8 = new Int8Array(buffer);
1672
+ heapU8 = new Uint8Array(buffer);
1673
+ heap16 = new Int16Array(buffer);
1674
+ heap32 = new Int32Array(buffer);
1675
+ }, "refresh");
1676
+ const bytes = /* @__PURE__ */ __name(() => {
1677
+ refresh();
1678
+ return heapU8;
1679
+ }, "bytes");
1680
+ const getValue = /* @__PURE__ */ __name((ptr, type = "i8") => {
1681
+ refresh();
1682
+ switch (type) {
1683
+ case "i32":
1684
+ case "*":
1685
+ return heap32[ptr >> 2];
1686
+ case "i16":
1687
+ return heap16[ptr >> 1];
1688
+ case "i1":
1689
+ case "i8":
1690
+ return heap8[ptr];
1691
+ case "i64":
1692
+ return Number(heap2.getBigInt64(ptr, true));
1693
+ case "float":
1694
+ return heap2.getFloat32(ptr, true);
1695
+ case "double":
1696
+ return heap2.getFloat64(ptr, true);
1697
+ default:
1698
+ throw new Error(`getValue: invalid type ${type}`);
1699
+ }
1700
+ }, "getValue");
1701
+ const setValue = /* @__PURE__ */ __name((ptr, value, type = "i8") => {
1702
+ refresh();
1703
+ switch (type) {
1704
+ case "i32":
1705
+ case "*":
1706
+ heap32[ptr >> 2] = value;
1707
+ return;
1708
+ case "i16":
1709
+ heap16[ptr >> 1] = value;
1710
+ return;
1711
+ case "i1":
1712
+ case "i8":
1713
+ heap8[ptr] = value;
1714
+ return;
1715
+ case "i64":
1716
+ heap2.setBigInt64(ptr, BigInt(value), true);
1717
+ return;
1718
+ case "float":
1719
+ heap2.setFloat32(ptr, value, true);
1720
+ return;
1721
+ case "double":
1722
+ heap2.setFloat64(ptr, value, true);
1723
+ return;
1724
+ default:
1725
+ throw new Error(`setValue: invalid type ${type}`);
1726
+ }
1727
+ }, "setValue");
1728
+ const UTF8ToString = /* @__PURE__ */ __name((ptr, maxBytesToRead, ignoreNul) => {
1729
+ if (!ptr) return "";
1730
+ const heapU82 = bytes();
1731
+ const limit = maxBytesToRead === void 0 ? heapU82.length : Math.min(heapU82.length, ptr + maxBytesToRead);
1732
+ let end = ptr;
1733
+ if (ignoreNul) end = limit;
1734
+ else while (end < limit && heapU82[end]) end++;
1735
+ return utf8Decoder.decode(heapU82.subarray(ptr, end));
1736
+ }, "UTF8ToString");
1737
+ const AsciiToString = /* @__PURE__ */ __name((ptr) => {
1738
+ const heapU82 = bytes();
1739
+ let result = "";
1740
+ for (let at = ptr; heapU82[at]; at++) result += String.fromCharCode(heapU82[at]);
1741
+ return result;
1742
+ }, "AsciiToString");
1743
+ const lengthBytesUTF8 = /* @__PURE__ */ __name((str) => utf8Encoder.encode(str).length, "lengthBytesUTF8");
1744
+ const stringToUTF8 = /* @__PURE__ */ __name((str, outPtr, maxBytesToWrite) => {
1745
+ if (maxBytesToWrite <= 0) return 0;
1746
+ const target = bytes().subarray(outPtr, outPtr + maxBytesToWrite - 1);
1747
+ const { written } = utf8Encoder.encodeInto(str, target);
1748
+ bytes()[outPtr + written] = 0;
1749
+ return written;
1750
+ }, "stringToUTF8");
1751
+ const stringToUTF16 = /* @__PURE__ */ __name((str, outPtr, maxBytesToWrite = 2147483647) => {
1752
+ if (maxBytesToWrite < 2) return 0;
1753
+ const length = Math.min(str.length, maxBytesToWrite - 2 >> 1);
1754
+ const units = new Uint16Array(bytes().buffer, outPtr, length + 1);
1755
+ for (let i = 0; i < length; i++) units[i] = str.charCodeAt(i);
1756
+ units[length] = 0;
1757
+ return 2 * length;
1758
+ }, "stringToUTF16");
1759
+ const imports = {
1760
+ env: {
1761
+ tree_sitter_parse_callback(inputBufferAddress, index, row, column, lengthAddress) {
1762
+ const text = module.currentParseCallback?.(index, { row, column });
1763
+ if (typeof text === "string") {
1764
+ setValue(lengthAddress, text.length, "i32");
1765
+ stringToUTF16(text, inputBufferAddress, INPUT_BUFFER_SIZE);
1766
+ } else {
1767
+ setValue(lengthAddress, 0, "i32");
1768
+ }
1769
+ },
1770
+ tree_sitter_log_callback(isLexMessage, messageAddress) {
1771
+ module.currentLogCallback?.(UTF8ToString(messageAddress), isLexMessage !== 0);
1772
+ },
1773
+ // A progress callback returns true to cancel, although MainModule types it as void.
1774
+ tree_sitter_progress_callback(currentOffset, hasError) {
1775
+ const cancel = module.currentProgressCallback?.({ currentOffset, hasError: hasError !== 0 });
1776
+ return Number(!!cancel);
1777
+ },
1778
+ tree_sitter_query_progress_callback(currentOffset) {
1779
+ const cancel = module.currentQueryProgressCallback?.({ currentOffset });
1780
+ return Number(!!cancel);
1781
+ }
1782
+ }
1783
+ };
1784
+ const source = await runtimeBytes(options);
1785
+ const compiled = source instanceof WebAssembly.Module ? source : await WebAssembly.compile(source);
1786
+ const instance = await WebAssembly.instantiate(compiled, { ...imports, wasi_snapshot_preview1: wasiImports(compiled) });
1787
+ runtime.exports = instance.exports;
1788
+ const exports = runtime.exports;
1789
+ exports._initialize();
1790
+ function link(wasmModule) {
1791
+ const info = dylinkInfo(wasmModule);
1792
+ const align = Math.max(2 ** info.memoryAlign, 16);
1793
+ const memoryBase = info.memorySize ? Math.ceil(exports.malloc(info.memorySize + align) / align) * align : 0;
1794
+ if (info.memorySize) bytes().fill(0, memoryBase, memoryBase + info.memorySize);
1795
+ const table = exports.__indirect_function_table;
1796
+ const tableBase = table.grow(info.tableSize);
1797
+ const env = {
1798
+ memory: exports.memory,
1799
+ __indirect_function_table: table,
1800
+ __stack_pointer: exports.__stack_pointer,
1801
+ __memory_base: new WebAssembly.Global({ value: "i32", mutable: false }, memoryBase),
1802
+ __table_base: new WebAssembly.Global({ value: "i32", mutable: false }, tableBase)
1803
+ };
1804
+ const memoryGot = /* @__PURE__ */ new Map();
1805
+ const functionGot = /* @__PURE__ */ new Map();
1806
+ const got = { "GOT.mem": {}, "GOT.func": {} };
1807
+ for (const { module: from, name, kind } of WebAssembly.Module.imports(wasmModule)) {
1808
+ if (from === "env") {
1809
+ if (name in env) continue;
1810
+ if (kind !== "function" || typeof exports[name] !== "function") {
1811
+ throw new Error(`Language module imports ${name}, which the runtime does not provide`);
1812
+ }
1813
+ env[name] = exports[name];
1814
+ } else if (from === "GOT.mem" || from === "GOT.func") {
1815
+ const slot = new WebAssembly.Global({ value: "i32", mutable: true }, 0);
1816
+ got[from][name] = slot;
1817
+ (from === "GOT.mem" ? memoryGot : functionGot).set(name, slot);
1818
+ } else {
1819
+ throw new Error(`Language module imports ${from}.${name}, which the runtime does not provide`);
1820
+ }
1821
+ }
1822
+ const side = new WebAssembly.Instance(wasmModule, { env, ...got }).exports;
1823
+ for (const [name, slot] of memoryGot) {
1824
+ const symbol = side[name];
1825
+ if (!(symbol instanceof WebAssembly.Global)) throw new Error(`Language module has no data symbol ${name}`);
1826
+ slot.value = memoryBase + symbol.value;
1827
+ }
1828
+ for (const [name, slot] of functionGot) {
1829
+ const fn = side[name] ?? exports[name];
1830
+ if (typeof fn !== "function") throw new Error(`Language module has no function ${name}`);
1831
+ const index = table.grow(1);
1832
+ table.set(index, fn);
1833
+ slot.value = index;
1834
+ }
1835
+ side.__wasm_apply_data_relocs?.();
1836
+ side.__wasm_call_ctors?.();
1837
+ return side;
1838
+ }
1839
+ __name(link, "link");
1840
+ function loadWebAssemblyModule(binary, flags) {
1841
+ if (!flags.loadAsync) {
1842
+ return link(binary instanceof WebAssembly.Module ? binary : new WebAssembly.Module(binary));
1843
+ }
1844
+ const compiled2 = binary instanceof WebAssembly.Module ? Promise.resolve(binary) : WebAssembly.compile(binary);
1845
+ return compiled2.then(link);
1846
+ }
1847
+ __name(loadWebAssemblyModule, "loadWebAssemblyModule");
1848
+ Object.assign(module, {
1849
+ getValue,
1850
+ setValue,
1851
+ UTF8ToString,
1852
+ AsciiToString,
1853
+ lengthBytesUTF8,
1854
+ stringToUTF8,
1855
+ stringToUTF16,
1856
+ loadWebAssemblyModule
1857
+ });
1858
+ Object.defineProperty(module, "HEAPU8", { get: bytes });
1859
+ for (const [name, value] of Object.entries(exports)) {
1860
+ if (typeof value === "function") module[`_${name}`] = value;
1861
+ }
1862
+ return module;
1863
+ }
1864
+ __name(createModule, "createModule");
1865
+
1866
+ // src/bindings.ts
1867
+ var Module = null;
1868
+ var initialization = null;
1869
+ async function initializeBinding(moduleOptions) {
1870
+ if (Module) return Module;
1871
+ initialization ??= createModule(moduleOptions).then((module) => {
1872
+ Module = module;
1873
+ return module;
1874
+ }).catch((error) => {
1875
+ initialization = null;
1876
+ throw error;
1877
+ });
1878
+ return initialization;
1879
+ }
1880
+ __name(initializeBinding, "initializeBinding");
1881
+ function checkModule() {
1882
+ return !!Module;
1883
+ }
1884
+ __name(checkModule, "checkModule");
1885
+
1886
+ // src/text_buffer.ts
1887
+ var finalizer4 = newFinalizer((address) => {
1888
+ C._free(address);
1889
+ });
1890
+ var DECODE_CHUNK = 4096;
1891
+ var TextBuffer = class {
1892
+ static {
1893
+ __name(this, "TextBuffer");
1894
+ }
1895
+ /** @internal */
1896
+ [0] = 0;
1897
+ // Address of the text
1898
+ /** @internal */
1899
+ capacity = 0;
1900
+ /** The length of the text, in UTF-16 code units. */
1901
+ length = 0;
1902
+ constructor(text = "") {
1903
+ this.set(text);
1904
+ }
1905
+ /** Replace the whole text. */
1906
+ set(text) {
1907
+ this.reserve(text.length);
1908
+ this.length = text.length;
1909
+ this.write(0, text);
1910
+ }
1911
+ /** Replace the code units in `[startIndex, oldEndIndex)` with `text`. */
1912
+ edit(startIndex, oldEndIndex, text) {
1913
+ if (startIndex < 0 || oldEndIndex < startIndex || oldEndIndex > this.length) {
1914
+ throw new RangeError(`Invalid edit [${startIndex}, ${oldEndIndex}) of a buffer of length ${this.length}`);
1915
+ }
1916
+ const length = this.length + text.length - (oldEndIndex - startIndex);
1917
+ this.reserve(length);
1918
+ const units = this.units(Math.max(length, this.length));
1919
+ units.copyWithin(startIndex + text.length, oldEndIndex, this.length);
1920
+ this.length = length;
1921
+ this.write(startIndex, text);
1922
+ }
1923
+ /** The text in `[startIndex, endIndex)`. */
1924
+ slice(startIndex = 0, endIndex = this.length) {
1925
+ const end = Math.min(endIndex, this.length);
1926
+ const units = this.units(this.length);
1927
+ let result = "";
1928
+ for (let at = startIndex; at < end; at += DECODE_CHUNK) {
1929
+ result += String.fromCharCode(...units.subarray(at, Math.min(end, at + DECODE_CHUNK)));
1930
+ }
1931
+ return result;
1932
+ }
1933
+ // The last chunk read decoded: node text for query predicates asks for many small
1934
+ // ranges near each other, and decoding a chunk per request dominated query time.
1935
+ chunkStart = -1;
1936
+ chunk = "";
1937
+ /** The text from `index` on, in chunks, for {@link Tree#textCallback}. */
1938
+ read = /* @__PURE__ */ __name((index) => {
1939
+ const start = index - index % DECODE_CHUNK;
1940
+ if (start !== this.chunkStart) {
1941
+ this.chunk = this.slice(start, Math.min(this.length, start + DECODE_CHUNK));
1942
+ this.chunkStart = start;
1943
+ }
1944
+ return this.chunk.slice(index - start);
1945
+ }, "read");
1946
+ /** Free the buffer's memory. */
1947
+ delete() {
1948
+ finalizer4?.unregister(this);
1949
+ C._free(this[0]);
1950
+ this[0] = 0;
1951
+ this.capacity = 0;
1952
+ this.length = 0;
1953
+ }
1954
+ units(length) {
1955
+ return new Uint16Array(C.HEAPU8.buffer, this[0], length);
1956
+ }
1957
+ write(at, text) {
1958
+ this.chunkStart = -1;
1959
+ const units = this.units(at + text.length);
1960
+ for (let i = 0; i < text.length; i++) units[at + i] = text.charCodeAt(i);
1961
+ }
1962
+ reserve(length) {
1963
+ if (length <= this.capacity && this[0]) return;
1964
+ const capacity = Math.max(length, this.capacity * 2, 64);
1965
+ const address = C._realloc(this[0], capacity * 2);
1966
+ if (!address) throw new Error(`Failed to allocate a text buffer of ${capacity} code units`);
1967
+ finalizer4?.unregister(this);
1968
+ this[0] = address;
1969
+ this.capacity = capacity;
1970
+ finalizer4?.register(this, address, this);
1971
+ }
1972
+ };
1973
+
1974
+ // src/parser.ts
1975
+ var TRANSFER_BUFFER;
1976
+ var LANGUAGE_VERSION;
1977
+ var MIN_COMPATIBLE_VERSION;
1978
+ var finalizer5 = newFinalizer((addresses) => {
1979
+ C._ts_parser_delete(addresses[0]);
1980
+ C._free(addresses[1]);
1981
+ });
1982
+ var Parser = class {
1983
+ static {
1984
+ __name(this, "Parser");
1985
+ }
1986
+ /** @internal */
1987
+ [0] = 0;
1988
+ // Internal handle for Wasm
1989
+ /** @internal */
1990
+ [1] = 0;
1991
+ // Internal handle for Wasm
1992
+ /** @internal */
1993
+ logCallback = null;
1994
+ /** The parser's current language. */
1995
+ language = null;
1996
+ /**
1997
+ * This must always be called before creating a Parser.
1998
+ *
1999
+ * You can optionally pass in options to configure the Wasm module, the most common
2000
+ * one being `locateFile` to help the module find the `.wasm` file.
2001
+ */
2002
+ static async init(moduleOptions) {
2003
+ setModule(await initializeBinding(moduleOptions));
2004
+ TRANSFER_BUFFER = C._ts_init();
2005
+ LANGUAGE_VERSION = C.getValue(TRANSFER_BUFFER, "i32");
2006
+ MIN_COMPATIBLE_VERSION = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
2007
+ }
2008
+ /**
2009
+ * Create a new parser.
2010
+ */
2011
+ constructor() {
2012
+ this.initialize();
2013
+ finalizer5?.register(this, [this[0], this[1]], this);
2014
+ }
2015
+ /** @internal */
2016
+ initialize() {
2017
+ if (!checkModule()) {
2018
+ throw new Error("cannot construct a Parser before calling `init()`");
2019
+ }
2020
+ C._ts_parser_new_wasm();
2021
+ this[0] = C.getValue(TRANSFER_BUFFER, "i32");
2022
+ this[1] = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
2023
+ }
2024
+ /** Delete the parser, freeing its resources. */
2025
+ delete() {
2026
+ finalizer5?.unregister(this);
2027
+ C._ts_parser_delete(this[0]);
2028
+ C._free(this[1]);
2029
+ this[0] = 0;
2030
+ this[1] = 0;
2031
+ }
2032
+ /**
2033
+ * Set the language that the parser should use for parsing.
2034
+ *
2035
+ * If the language was not successfully assigned, an error will be thrown.
2036
+ * This happens if the language was generated with an incompatible
2037
+ * version of the Tree-sitter CLI. Check the language's version using
2038
+ * {@link Language#version} and compare it to this library's
2039
+ * {@link LANGUAGE_VERSION} and {@link MIN_COMPATIBLE_VERSION} constants.
2040
+ */
2041
+ setLanguage(language) {
2042
+ let address;
2043
+ if (!language) {
2044
+ address = 0;
2045
+ this.language = null;
2046
+ } else if (language.constructor === Language) {
2047
+ address = language[0];
2048
+ const version = C._ts_language_abi_version(address);
2049
+ if (version < MIN_COMPATIBLE_VERSION || LANGUAGE_VERSION < version) {
2050
+ throw new Error(
2051
+ `Incompatible language version ${version}. Compatibility range ${MIN_COMPATIBLE_VERSION} through ${LANGUAGE_VERSION}.`
2052
+ );
2053
+ }
2054
+ this.language = language;
2055
+ } else {
2056
+ throw new Error("Argument must be a Language");
2057
+ }
2058
+ C._ts_parser_set_language(this[0], address);
2059
+ return this;
2060
+ }
2061
+ /**
2062
+ * Parse a slice of UTF8 text.
2063
+ *
2064
+ * @param {string | ParseCallback | TextBuffer} callback - The text to parse, a callback function, or a
2065
+ * {@link TextBuffer}, which is read in place.
2066
+ *
2067
+ * @param {Tree | null} [oldTree] - A previous syntax tree parsed from the same document. If the text of the
2068
+ * document has changed since `oldTree` was created, then you must edit `oldTree` to match
2069
+ * the new text using {@link Tree#edit}.
2070
+ *
2071
+ * @param {ParseOptions} [options] - Options for parsing the text.
2072
+ * This can be used to set the included ranges, or a progress callback.
2073
+ *
2074
+ * @returns {Tree | null} A {@link Tree} if parsing succeeded, or `null` if:
2075
+ * - The parser has not yet had a language assigned with {@link Parser#setLanguage}.
2076
+ * - The progress callback returned true.
2077
+ */
2078
+ parse(callback, oldTree, options) {
2079
+ if (callback instanceof TextBuffer) {
2080
+ C.currentParseCallback = callback.read;
2081
+ } else if (typeof callback === "string") {
2082
+ C.currentParseCallback = (index) => callback.slice(index);
2083
+ } else if (typeof callback === "function") {
2084
+ C.currentParseCallback = callback;
2085
+ } else {
2086
+ throw new Error("Argument must be a string or a function");
2087
+ }
2088
+ if (options?.progressCallback) {
2089
+ C.currentProgressCallback = options.progressCallback;
2090
+ } else {
2091
+ C.currentProgressCallback = null;
2092
+ }
2093
+ if (this.logCallback) {
2094
+ C.currentLogCallback = this.logCallback;
2095
+ C._ts_parser_enable_logger_wasm(this[0], 1);
2096
+ } else {
2097
+ C.currentLogCallback = null;
2098
+ C._ts_parser_enable_logger_wasm(this[0], 0);
2099
+ }
2100
+ let rangeCount = 0;
2101
+ let rangeAddress = 0;
2102
+ if (options?.includedRanges) {
2103
+ rangeCount = options.includedRanges.length;
2104
+ rangeAddress = C._calloc(rangeCount, SIZE_OF_RANGE);
2105
+ let address = rangeAddress;
2106
+ for (let i = 0; i < rangeCount; i++) {
2107
+ marshalRange(address, options.includedRanges[i]);
2108
+ address += SIZE_OF_RANGE;
2109
+ }
2110
+ }
2111
+ const treeAddress = callback instanceof TextBuffer ? C._ts_parser_parse_utf16_wasm(
2112
+ this[0],
2113
+ callback[0],
2114
+ callback.length * 2,
2115
+ oldTree ? oldTree[0] : 0,
2116
+ rangeAddress,
2117
+ rangeCount
2118
+ ) : C._ts_parser_parse_wasm(
2119
+ this[0],
2120
+ this[1],
2121
+ oldTree ? oldTree[0] : 0,
2122
+ rangeAddress,
2123
+ rangeCount
2124
+ );
2125
+ if (!treeAddress) {
2126
+ C.currentParseCallback = null;
2127
+ C.currentLogCallback = null;
2128
+ C.currentProgressCallback = null;
2129
+ return null;
2130
+ }
2131
+ if (!this.language) {
2132
+ throw new Error("Parser must have a language to parse");
2133
+ }
2134
+ const result = new Tree(INTERNAL, treeAddress, this.language, C.currentParseCallback);
2135
+ C.currentParseCallback = null;
2136
+ C.currentLogCallback = null;
2137
+ C.currentProgressCallback = null;
2138
+ return result;
2139
+ }
2140
+ /**
2141
+ * Instruct the parser to start the next parse from the beginning.
2142
+ *
2143
+ * If the parser previously failed because of a callback,
2144
+ * then by default, it will resume where it left off on the
2145
+ * next call to {@link Parser#parse} or other parsing functions.
2146
+ * If you don't want to resume, and instead intend to use this parser to
2147
+ * parse some other document, you must call `reset` first.
2148
+ */
2149
+ reset() {
2150
+ C._ts_parser_reset(this[0]);
2151
+ }
2152
+ /** Get the ranges of text that the parser will include when parsing. */
2153
+ getIncludedRanges() {
2154
+ C._ts_parser_included_ranges_wasm(this[0]);
2155
+ const count = C.getValue(TRANSFER_BUFFER, "i32");
2156
+ const buffer = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
2157
+ const result = new Array(count);
2158
+ if (count > 0) {
2159
+ let address = buffer;
2160
+ for (let i = 0; i < count; i++) {
2161
+ result[i] = unmarshalRange(address);
2162
+ address += SIZE_OF_RANGE;
2163
+ }
2164
+ C._free(buffer);
2165
+ }
2166
+ return result;
2167
+ }
2168
+ /** Set the logging callback that a parser should use during parsing. */
2169
+ setLogger(callback) {
2170
+ if (!callback) {
2171
+ this.logCallback = null;
2172
+ } else if (typeof callback !== "function") {
2173
+ throw new Error("Logger callback must be a function");
2174
+ } else {
2175
+ this.logCallback = callback;
2176
+ }
2177
+ return this;
2178
+ }
2179
+ /** Get the parser's current logger. */
2180
+ getLogger() {
2181
+ return this.logCallback;
2182
+ }
2183
+ };
2184
+
2185
+ // src/extension.ts
2186
+ async function loadExtension(binary) {
2187
+ return C.loadWebAssemblyModule(binary, { loadAsync: true });
2188
+ }
2189
+ __name(loadExtension, "loadExtension");
2190
+ function heap() {
2191
+ return C.HEAPU8;
2192
+ }
2193
+ __name(heap, "heap");
2194
+
2195
+ // src/query.ts
2196
+ var PREDICATE_STEP_TYPE_CAPTURE = 1;
2197
+ var PREDICATE_STEP_TYPE_STRING = 2;
2198
+ var QUERY_WORD_REGEX = /[\w-]+/g;
2199
+ var CaptureQuantifier = {
2200
+ Zero: 0,
2201
+ ZeroOrOne: 1,
2202
+ ZeroOrMore: 2,
2203
+ One: 3,
2204
+ OneOrMore: 4
2205
+ };
2206
+ var isCaptureStep = /* @__PURE__ */ __name((step) => step.type === "capture", "isCaptureStep");
2207
+ var isStringStep = /* @__PURE__ */ __name((step) => step.type === "string", "isStringStep");
2208
+ var QueryErrorKind = {
2209
+ Syntax: 1,
2210
+ NodeName: 2,
2211
+ FieldName: 3,
2212
+ CaptureName: 4,
2213
+ PatternStructure: 5
2214
+ };
2215
+ var QueryError = class _QueryError extends Error {
2216
+ constructor(kind, info, index, length) {
2217
+ super(_QueryError.formatMessage(kind, info));
2218
+ this.kind = kind;
2219
+ this.info = info;
2220
+ this.index = index;
2221
+ this.length = length;
2222
+ this.name = "QueryError";
2223
+ }
2224
+ kind;
2225
+ info;
2226
+ index;
2227
+ length;
2228
+ static {
2229
+ __name(this, "QueryError");
2230
+ }
2231
+ /** Formats an error message based on the error kind and info */
2232
+ static formatMessage(kind, info) {
2233
+ switch (kind) {
2234
+ case QueryErrorKind.NodeName:
2235
+ return `Bad node name '${info.word}'`;
2236
+ case QueryErrorKind.FieldName:
2237
+ return `Bad field name '${info.word}'`;
2238
+ case QueryErrorKind.CaptureName:
2239
+ return `Bad capture name @${info.word}`;
2240
+ case QueryErrorKind.PatternStructure:
2241
+ return `Bad pattern structure at offset ${info.suffix}`;
2242
+ case QueryErrorKind.Syntax:
2243
+ return `Bad syntax at offset ${info.suffix}`;
2244
+ }
2245
+ }
2246
+ };
2247
+ function parseAnyPredicate(steps, index, operator, textPredicates) {
2248
+ if (steps.length !== 3) {
2249
+ throw new Error(
2250
+ `Wrong number of arguments to \`#${operator}\` predicate. Expected 2, got ${steps.length - 1}`
2251
+ );
2252
+ }
2253
+ if (!isCaptureStep(steps[1])) {
2254
+ throw new Error(
2255
+ `First argument of \`#${operator}\` predicate must be a capture. Got "${steps[1].value}"`
2256
+ );
2257
+ }
2258
+ const isPositive = operator === "eq?" || operator === "any-eq?";
2259
+ const matchAll = !operator.startsWith("any-");
2260
+ if (isCaptureStep(steps[2])) {
2261
+ const captureName1 = steps[1].name;
2262
+ const captureName2 = steps[2].name;
2263
+ textPredicates[index].push((captures) => {
2264
+ const nodes1 = [];
2265
+ const nodes2 = [];
2266
+ for (const c of captures) {
2267
+ if (c.name === captureName1) nodes1.push(c.node);
2268
+ if (c.name === captureName2) nodes2.push(c.node);
2269
+ }
2270
+ const compare = /* @__PURE__ */ __name((n1, n2, positive) => {
2271
+ return positive ? n1.text === n2.text : n1.text !== n2.text;
2272
+ }, "compare");
2273
+ return matchAll ? nodes1.every((n1) => nodes2.some((n2) => compare(n1, n2, isPositive))) : nodes1.some((n1) => nodes2.some((n2) => compare(n1, n2, isPositive)));
2274
+ });
2275
+ } else {
2276
+ const captureName = steps[1].name;
2277
+ const stringValue = steps[2].value;
2278
+ const matches = /* @__PURE__ */ __name((n) => n.text === stringValue, "matches");
2279
+ const doesNotMatch = /* @__PURE__ */ __name((n) => n.text !== stringValue, "doesNotMatch");
2280
+ textPredicates[index].push((captures) => {
2281
+ const nodes = [];
2282
+ for (const c of captures) {
2283
+ if (c.name === captureName) nodes.push(c.node);
2284
+ }
2285
+ const test = isPositive ? matches : doesNotMatch;
2286
+ return matchAll ? nodes.every(test) : nodes.some(test);
2287
+ });
2288
+ }
2289
+ }
2290
+ __name(parseAnyPredicate, "parseAnyPredicate");
2291
+ function parseMatchPredicate(steps, index, operator, textPredicates) {
2292
+ if (steps.length !== 3) {
2293
+ throw new Error(
2294
+ `Wrong number of arguments to \`#${operator}\` predicate. Expected 2, got ${steps.length - 1}.`
2295
+ );
2296
+ }
2297
+ if (steps[1].type !== "capture") {
2298
+ throw new Error(
2299
+ `First argument of \`#${operator}\` predicate must be a capture. Got "${steps[1].value}".`
2300
+ );
2301
+ }
2302
+ if (steps[2].type !== "string") {
2303
+ throw new Error(
2304
+ `Second argument of \`#${operator}\` predicate must be a string. Got @${steps[2].name}.`
2305
+ );
2306
+ }
2307
+ const isPositive = operator === "match?" || operator === "any-match?";
2308
+ const matchAll = !operator.startsWith("any-");
2309
+ const captureName = steps[1].name;
2310
+ const regex = new RegExp(steps[2].value);
2311
+ textPredicates[index].push((captures) => {
2312
+ const nodes = [];
2313
+ for (const c of captures) {
2314
+ if (c.name === captureName) nodes.push(c.node.text);
2315
+ }
2316
+ const test = /* @__PURE__ */ __name((text, positive) => {
2317
+ return positive ? regex.test(text) : !regex.test(text);
2318
+ }, "test");
2319
+ if (nodes.length === 0) return !isPositive;
2320
+ return matchAll ? nodes.every((text) => test(text, isPositive)) : nodes.some((text) => test(text, isPositive));
2321
+ });
2322
+ }
2323
+ __name(parseMatchPredicate, "parseMatchPredicate");
2324
+ function parseAnyOfPredicate(steps, index, operator, textPredicates) {
2325
+ if (steps.length < 2) {
2326
+ throw new Error(
2327
+ `Wrong number of arguments to \`#${operator}\` predicate. Expected at least 1. Got ${steps.length - 1}.`
2328
+ );
2329
+ }
2330
+ if (steps[1].type !== "capture") {
2331
+ throw new Error(
2332
+ `First argument of \`#${operator}\` predicate must be a capture. Got "${steps[1].value}".`
2333
+ );
2334
+ }
2335
+ const isPositive = operator === "any-of?";
2336
+ const captureName = steps[1].name;
2337
+ const stringSteps = steps.slice(2);
2338
+ if (!stringSteps.every(isStringStep)) {
2339
+ throw new Error(
2340
+ `Arguments to \`#${operator}\` predicate must be strings.".`
2341
+ );
2342
+ }
2343
+ const values = stringSteps.map((s) => s.value);
2344
+ textPredicates[index].push((captures) => {
2345
+ const nodes = [];
2346
+ for (const c of captures) {
2347
+ if (c.name === captureName) nodes.push(c.node.text);
2348
+ }
2349
+ if (nodes.length === 0) return !isPositive;
2350
+ return nodes.every((text) => values.includes(text)) === isPositive;
2351
+ });
2352
+ }
2353
+ __name(parseAnyOfPredicate, "parseAnyOfPredicate");
2354
+ function parseIsPredicate(steps, index, operator, assertedProperties, refutedProperties) {
2355
+ if (steps.length < 2 || steps.length > 3) {
2356
+ throw new Error(
2357
+ `Wrong number of arguments to \`#${operator}\` predicate. Expected 1 or 2. Got ${steps.length - 1}.`
2358
+ );
2359
+ }
2360
+ if (!steps.every(isStringStep)) {
2361
+ throw new Error(
2362
+ `Arguments to \`#${operator}\` predicate must be strings.".`
2363
+ );
2364
+ }
2365
+ const properties = operator === "is?" ? assertedProperties : refutedProperties;
2366
+ if (!properties[index]) properties[index] = {};
2367
+ properties[index][steps[1].value] = steps[2]?.value ?? null;
2368
+ }
2369
+ __name(parseIsPredicate, "parseIsPredicate");
2370
+ function parseSetDirective(steps, index, setProperties) {
2371
+ if (steps.length < 2 || steps.length > 3) {
2372
+ throw new Error(`Wrong number of arguments to \`#set!\` predicate. Expected 1 or 2. Got ${steps.length - 1}.`);
2373
+ }
2374
+ if (!steps.every(isStringStep)) {
2375
+ throw new Error(`Arguments to \`#set!\` predicate must be strings.".`);
2376
+ }
2377
+ if (!setProperties[index]) setProperties[index] = {};
2378
+ setProperties[index][steps[1].value] = steps[2]?.value ?? null;
2379
+ }
2380
+ __name(parseSetDirective, "parseSetDirective");
2381
+ function parsePattern(index, stepType, stepValueId, captureNames, stringValues, steps, textPredicates, predicates, setProperties, assertedProperties, refutedProperties) {
2382
+ if (stepType === PREDICATE_STEP_TYPE_CAPTURE) {
2383
+ const name = captureNames[stepValueId];
2384
+ steps.push({ type: "capture", name });
2385
+ } else if (stepType === PREDICATE_STEP_TYPE_STRING) {
2386
+ steps.push({ type: "string", value: stringValues[stepValueId] });
2387
+ } else if (steps.length > 0) {
2388
+ if (steps[0].type !== "string") {
2389
+ throw new Error("Predicates must begin with a literal value");
2390
+ }
2391
+ const operator = steps[0].value;
2392
+ switch (operator) {
2393
+ case "any-not-eq?":
2394
+ case "not-eq?":
2395
+ case "any-eq?":
2396
+ case "eq?":
2397
+ parseAnyPredicate(steps, index, operator, textPredicates);
2398
+ break;
2399
+ case "any-not-match?":
2400
+ case "not-match?":
2401
+ case "any-match?":
2402
+ case "match?":
2403
+ parseMatchPredicate(steps, index, operator, textPredicates);
2404
+ break;
2405
+ case "not-any-of?":
2406
+ case "any-of?":
2407
+ parseAnyOfPredicate(steps, index, operator, textPredicates);
2408
+ break;
2409
+ case "is?":
2410
+ case "is-not?":
2411
+ parseIsPredicate(steps, index, operator, assertedProperties, refutedProperties);
2412
+ break;
2413
+ case "set!":
2414
+ parseSetDirective(steps, index, setProperties);
2415
+ break;
2416
+ default:
2417
+ predicates[index].push({ operator, operands: steps.slice(1) });
2418
+ }
2419
+ steps.length = 0;
2420
+ }
2421
+ }
2422
+ __name(parsePattern, "parsePattern");
2423
+ var finalizer6 = newFinalizer((address) => {
2424
+ C._ts_query_delete(address);
2425
+ });
2426
+ var Query = class {
2427
+ static {
2428
+ __name(this, "Query");
2429
+ }
2430
+ /** @internal */
2431
+ [0] = 0;
2432
+ // Internal handle for Wasm
2433
+ /** @internal */
2434
+ exceededMatchLimit;
2435
+ /** @internal */
2436
+ textPredicates;
2437
+ /** The names of the captures used in the query. */
2438
+ captureNames;
2439
+ /** The quantifiers of the captures used in the query. */
2440
+ captureQuantifiers;
2441
+ /**
2442
+ * The other user-defined predicates associated with the given index.
2443
+ *
2444
+ * This includes predicates with operators other than:
2445
+ * - `match?`
2446
+ * - `eq?` and `not-eq?`
2447
+ * - `any-of?` and `not-any-of?`
2448
+ * - `is?` and `is-not?`
2449
+ * - `set!`
2450
+ */
2451
+ predicates;
2452
+ /** The properties for predicates with the operator `set!`. */
2453
+ setProperties;
2454
+ /** The properties for predicates with the operator `is?`. */
2455
+ assertedProperties;
2456
+ /** The properties for predicates with the operator `is-not?`. */
2457
+ refutedProperties;
2458
+ /** The maximum number of in-progress matches for this cursor. */
2459
+ matchLimit;
2460
+ /**
2461
+ * Create a new query from a string containing one or more S-expression
2462
+ * patterns.
2463
+ *
2464
+ * The query is associated with a particular language, and can only be run
2465
+ * on syntax nodes parsed with that language. References to Queries can be
2466
+ * shared between multiple threads.
2467
+ *
2468
+ * @link {@see https://tree-sitter.github.io/tree-sitter/using-parsers/queries}
2469
+ */
2470
+ constructor(language, source) {
2471
+ const sourceLength = C.lengthBytesUTF8(source);
2472
+ const sourceAddress = C._malloc(sourceLength + 1);
2473
+ C.stringToUTF8(source, sourceAddress, sourceLength + 1);
2474
+ const address = C._ts_query_new(
2475
+ language[0],
2476
+ sourceAddress,
2477
+ sourceLength,
2478
+ TRANSFER_BUFFER,
2479
+ TRANSFER_BUFFER + SIZE_OF_INT
2480
+ );
2481
+ if (!address) {
2482
+ const errorId = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
2483
+ const errorByte = C.getValue(TRANSFER_BUFFER, "i32");
2484
+ const errorIndex = C.UTF8ToString(sourceAddress, errorByte).length;
2485
+ const suffix = source.slice(errorIndex, errorIndex + 100).split("\n")[0];
2486
+ const word = suffix.match(QUERY_WORD_REGEX)?.[0] ?? "";
2487
+ C._free(sourceAddress);
2488
+ switch (errorId) {
2489
+ case QueryErrorKind.Syntax:
2490
+ throw new QueryError(QueryErrorKind.Syntax, { suffix: `${errorIndex}: '${suffix}'...` }, errorIndex, 0);
2491
+ case QueryErrorKind.NodeName:
2492
+ throw new QueryError(errorId, { word }, errorIndex, word.length);
2493
+ case QueryErrorKind.FieldName:
2494
+ throw new QueryError(errorId, { word }, errorIndex, word.length);
2495
+ case QueryErrorKind.CaptureName:
2496
+ throw new QueryError(errorId, { word }, errorIndex, word.length);
2497
+ case QueryErrorKind.PatternStructure:
2498
+ throw new QueryError(errorId, { suffix: `${errorIndex}: '${suffix}'...` }, errorIndex, 0);
2499
+ }
2500
+ }
2501
+ const stringCount = C._ts_query_string_count(address);
2502
+ const captureCount = C._ts_query_capture_count(address);
2503
+ const patternCount = C._ts_query_pattern_count(address);
2504
+ const captureNames = new Array(captureCount);
2505
+ const captureQuantifiers = new Array(patternCount);
2506
+ const stringValues = new Array(stringCount);
2507
+ for (let i = 0; i < captureCount; i++) {
2508
+ const nameAddress = C._ts_query_capture_name_for_id(
2509
+ address,
2510
+ i,
2511
+ TRANSFER_BUFFER
2512
+ );
2513
+ const nameLength = C.getValue(TRANSFER_BUFFER, "i32");
2514
+ captureNames[i] = C.UTF8ToString(nameAddress, nameLength);
2515
+ }
2516
+ for (let i = 0; i < patternCount; i++) {
2517
+ const captureQuantifiersArray = new Array(captureCount);
2518
+ for (let j = 0; j < captureCount; j++) {
2519
+ const quantifier = C._ts_query_capture_quantifier_for_id(address, i, j);
2520
+ captureQuantifiersArray[j] = quantifier;
2521
+ }
2522
+ captureQuantifiers[i] = captureQuantifiersArray;
2523
+ }
2524
+ for (let i = 0; i < stringCount; i++) {
2525
+ const valueAddress = C._ts_query_string_value_for_id(
2526
+ address,
2527
+ i,
2528
+ TRANSFER_BUFFER
2529
+ );
2530
+ const nameLength = C.getValue(TRANSFER_BUFFER, "i32");
2531
+ stringValues[i] = C.UTF8ToString(valueAddress, nameLength);
2532
+ }
2533
+ const setProperties = new Array(patternCount);
2534
+ const assertedProperties = new Array(patternCount);
2535
+ const refutedProperties = new Array(patternCount);
2536
+ const predicates = new Array(patternCount);
2537
+ const textPredicates = new Array(patternCount);
2538
+ for (let i = 0; i < patternCount; i++) {
2539
+ const predicatesAddress = C._ts_query_predicates_for_pattern(address, i, TRANSFER_BUFFER);
2540
+ const stepCount = C.getValue(TRANSFER_BUFFER, "i32");
2541
+ predicates[i] = [];
2542
+ textPredicates[i] = [];
2543
+ const steps = new Array();
2544
+ let stepAddress = predicatesAddress;
2545
+ for (let j = 0; j < stepCount; j++) {
2546
+ const stepType = C.getValue(stepAddress, "i32");
2547
+ stepAddress += SIZE_OF_INT;
2548
+ const stepValueId = C.getValue(stepAddress, "i32");
2549
+ stepAddress += SIZE_OF_INT;
2550
+ parsePattern(
2551
+ i,
2552
+ stepType,
2553
+ stepValueId,
2554
+ captureNames,
2555
+ stringValues,
2556
+ steps,
2557
+ textPredicates,
2558
+ predicates,
2559
+ setProperties,
2560
+ assertedProperties,
2561
+ refutedProperties
2562
+ );
2563
+ }
2564
+ Object.freeze(textPredicates[i]);
2565
+ Object.freeze(predicates[i]);
2566
+ Object.freeze(setProperties[i]);
2567
+ Object.freeze(assertedProperties[i]);
2568
+ Object.freeze(refutedProperties[i]);
2569
+ }
2570
+ C._free(sourceAddress);
2571
+ this[0] = address;
2572
+ this.captureNames = captureNames;
2573
+ this.captureQuantifiers = captureQuantifiers;
2574
+ this.textPredicates = textPredicates;
2575
+ this.predicates = predicates;
2576
+ this.setProperties = setProperties;
2577
+ this.assertedProperties = assertedProperties;
2578
+ this.refutedProperties = refutedProperties;
2579
+ this.exceededMatchLimit = false;
2580
+ finalizer6?.register(this, address, this);
2581
+ }
2582
+ /** Delete the query, freeing its resources. */
2583
+ delete() {
2584
+ finalizer6?.unregister(this);
2585
+ C._ts_query_delete(this[0]);
2586
+ this[0] = 0;
2587
+ }
2588
+ /**
2589
+ * Iterate over all of the matches in the order that they were found.
2590
+ *
2591
+ * Each match contains the index of the pattern that matched, and a list of
2592
+ * captures. Because multiple patterns can match the same set of nodes,
2593
+ * one match may contain captures that appear *before* some of the
2594
+ * captures from a previous match.
2595
+ *
2596
+ * @param {Node} node - The node to execute the query on.
2597
+ *
2598
+ * @param {QueryOptions} options - Options for query execution.
2599
+ */
2600
+ matches(node, options = {}) {
2601
+ const startPosition = options.startPosition ?? ZERO_POINT;
2602
+ const endPosition = options.endPosition ?? ZERO_POINT;
2603
+ const startIndex = options.startIndex ?? 0;
2604
+ const endIndex = options.endIndex ?? 0;
2605
+ const startContainingPosition = options.startContainingPosition ?? ZERO_POINT;
2606
+ const endContainingPosition = options.endContainingPosition ?? ZERO_POINT;
2607
+ const startContainingIndex = options.startContainingIndex ?? 0;
2608
+ const endContainingIndex = options.endContainingIndex ?? 0;
2609
+ const matchLimit = options.matchLimit ?? 4294967295;
2610
+ const maxStartDepth = options.maxStartDepth ?? 4294967295;
2611
+ const progressCallback = options.progressCallback;
2612
+ if (typeof matchLimit !== "number") {
2613
+ throw new Error("Arguments must be numbers");
2614
+ }
2615
+ this.matchLimit = matchLimit;
2616
+ if (endIndex !== 0 && startIndex > endIndex) {
2617
+ throw new Error("`startIndex` cannot be greater than `endIndex`");
2618
+ }
2619
+ if (endPosition !== ZERO_POINT && (startPosition.row > endPosition.row || startPosition.row === endPosition.row && startPosition.column > endPosition.column)) {
2620
+ throw new Error("`startPosition` cannot be greater than `endPosition`");
2621
+ }
2622
+ if (endContainingIndex !== 0 && startContainingIndex > endContainingIndex) {
2623
+ throw new Error("`startContainingIndex` cannot be greater than `endContainingIndex`");
2624
+ }
2625
+ if (endContainingPosition !== ZERO_POINT && (startContainingPosition.row > endContainingPosition.row || startContainingPosition.row === endContainingPosition.row && startContainingPosition.column > endContainingPosition.column)) {
2626
+ throw new Error("`startContainingPosition` cannot be greater than `endContainingPosition`");
2627
+ }
2628
+ if (progressCallback) {
2629
+ C.currentQueryProgressCallback = progressCallback;
2630
+ }
2631
+ marshalNode(node);
2632
+ C._ts_query_matches_wasm(
2633
+ this[0],
2634
+ node.tree[0],
2635
+ startPosition.row,
2636
+ startPosition.column,
2637
+ endPosition.row,
2638
+ endPosition.column,
2639
+ startIndex,
2640
+ endIndex,
2641
+ startContainingPosition.row,
2642
+ startContainingPosition.column,
2643
+ endContainingPosition.row,
2644
+ endContainingPosition.column,
2645
+ startContainingIndex,
2646
+ endContainingIndex,
2647
+ matchLimit,
2648
+ maxStartDepth
2649
+ );
2650
+ const rawCount = C.getValue(TRANSFER_BUFFER, "i32");
2651
+ const startAddress = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
2652
+ const didExceedMatchLimit = C.getValue(TRANSFER_BUFFER + 2 * SIZE_OF_INT, "i32");
2653
+ const result = new Array(rawCount);
2654
+ this.exceededMatchLimit = Boolean(didExceedMatchLimit);
2655
+ let filteredCount = 0;
2656
+ let address = startAddress;
2657
+ for (let i = 0; i < rawCount; i++) {
2658
+ const patternIndex = C.getValue(address, "i32");
2659
+ address += SIZE_OF_INT;
2660
+ const captureCount = C.getValue(address, "i32");
2661
+ address += SIZE_OF_INT;
2662
+ const captures = new Array(captureCount);
2663
+ address = unmarshalCaptures(this, node.tree, address, patternIndex, captures);
2664
+ if (this.textPredicates[patternIndex].every((p) => p(captures))) {
2665
+ result[filteredCount] = { patternIndex, captures };
2666
+ const setProperties = this.setProperties[patternIndex];
2667
+ result[filteredCount].setProperties = setProperties;
2668
+ const assertedProperties = this.assertedProperties[patternIndex];
2669
+ result[filteredCount].assertedProperties = assertedProperties;
2670
+ const refutedProperties = this.refutedProperties[patternIndex];
2671
+ result[filteredCount].refutedProperties = refutedProperties;
2672
+ filteredCount++;
2673
+ }
2674
+ }
2675
+ result.length = filteredCount;
2676
+ C._free(startAddress);
2677
+ C.currentQueryProgressCallback = null;
2678
+ return result;
2679
+ }
2680
+ /**
2681
+ * Iterate over all of the individual captures in the order that they
2682
+ * appear.
2683
+ *
2684
+ * This is useful if you don't care about which pattern matched, and just
2685
+ * want a single, ordered sequence of captures.
2686
+ *
2687
+ * @param {Node} node - The node to execute the query on.
2688
+ *
2689
+ * @param {QueryOptions} options - Options for query execution.
2690
+ */
2691
+ captures(node, options = {}) {
2692
+ const startPosition = options.startPosition ?? ZERO_POINT;
2693
+ const endPosition = options.endPosition ?? ZERO_POINT;
2694
+ const startIndex = options.startIndex ?? 0;
2695
+ const endIndex = options.endIndex ?? 0;
2696
+ const startContainingPosition = options.startContainingPosition ?? ZERO_POINT;
2697
+ const endContainingPosition = options.endContainingPosition ?? ZERO_POINT;
2698
+ const startContainingIndex = options.startContainingIndex ?? 0;
2699
+ const endContainingIndex = options.endContainingIndex ?? 0;
2700
+ const matchLimit = options.matchLimit ?? 4294967295;
2701
+ const maxStartDepth = options.maxStartDepth ?? 4294967295;
2702
+ const progressCallback = options.progressCallback;
2703
+ if (typeof matchLimit !== "number") {
2704
+ throw new Error("Arguments must be numbers");
2705
+ }
2706
+ this.matchLimit = matchLimit;
2707
+ if (endIndex !== 0 && startIndex > endIndex) {
2708
+ throw new Error("`startIndex` cannot be greater than `endIndex`");
2709
+ }
2710
+ if (endPosition !== ZERO_POINT && (startPosition.row > endPosition.row || startPosition.row === endPosition.row && startPosition.column > endPosition.column)) {
2711
+ throw new Error("`startPosition` cannot be greater than `endPosition`");
2712
+ }
2713
+ if (endContainingIndex !== 0 && startContainingIndex > endContainingIndex) {
2714
+ throw new Error("`startContainingIndex` cannot be greater than `endContainingIndex`");
2715
+ }
2716
+ if (endContainingPosition !== ZERO_POINT && (startContainingPosition.row > endContainingPosition.row || startContainingPosition.row === endContainingPosition.row && startContainingPosition.column > endContainingPosition.column)) {
2717
+ throw new Error("`startContainingPosition` cannot be greater than `endContainingPosition`");
2718
+ }
2719
+ if (progressCallback) {
2720
+ C.currentQueryProgressCallback = progressCallback;
2721
+ }
2722
+ marshalNode(node);
2723
+ C._ts_query_captures_wasm(
2724
+ this[0],
2725
+ node.tree[0],
2726
+ startPosition.row,
2727
+ startPosition.column,
2728
+ endPosition.row,
2729
+ endPosition.column,
2730
+ startIndex,
2731
+ endIndex,
2732
+ startContainingPosition.row,
2733
+ startContainingPosition.column,
2734
+ endContainingPosition.row,
2735
+ endContainingPosition.column,
2736
+ startContainingIndex,
2737
+ endContainingIndex,
2738
+ matchLimit,
2739
+ maxStartDepth
2740
+ );
2741
+ const count = C.getValue(TRANSFER_BUFFER, "i32");
2742
+ const startAddress = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
2743
+ const didExceedMatchLimit = C.getValue(TRANSFER_BUFFER + 2 * SIZE_OF_INT, "i32");
2744
+ const result = new Array();
2745
+ this.exceededMatchLimit = Boolean(didExceedMatchLimit);
2746
+ const captures = new Array();
2747
+ let address = startAddress;
2748
+ for (let i = 0; i < count; i++) {
2749
+ const patternIndex = C.getValue(address, "i32");
2750
+ address += SIZE_OF_INT;
2751
+ const captureCount = C.getValue(address, "i32");
2752
+ address += SIZE_OF_INT;
2753
+ const captureIndex = C.getValue(address, "i32");
2754
+ address += SIZE_OF_INT;
2755
+ captures.length = captureCount;
2756
+ address = unmarshalCaptures(this, node.tree, address, patternIndex, captures);
2757
+ if (this.textPredicates[patternIndex].every((p) => p(captures))) {
2758
+ const capture = captures[captureIndex];
2759
+ const setProperties = this.setProperties[patternIndex];
2760
+ capture.setProperties = setProperties;
2761
+ const assertedProperties = this.assertedProperties[patternIndex];
2762
+ capture.assertedProperties = assertedProperties;
2763
+ const refutedProperties = this.refutedProperties[patternIndex];
2764
+ capture.refutedProperties = refutedProperties;
2765
+ result.push(capture);
2766
+ }
2767
+ }
2768
+ C._free(startAddress);
2769
+ C.currentQueryProgressCallback = null;
2770
+ return result;
2771
+ }
2772
+ /** Get the predicates for a given pattern. */
2773
+ predicatesForPattern(patternIndex) {
2774
+ return this.predicates[patternIndex];
2775
+ }
2776
+ /**
2777
+ * Disable a certain capture within a query.
2778
+ *
2779
+ * This prevents the capture from being returned in matches, and also
2780
+ * avoids any resource usage associated with recording the capture.
2781
+ */
2782
+ disableCapture(captureName) {
2783
+ const captureNameLength = C.lengthBytesUTF8(captureName);
2784
+ const captureNameAddress = C._malloc(captureNameLength + 1);
2785
+ C.stringToUTF8(captureName, captureNameAddress, captureNameLength + 1);
2786
+ C._ts_query_disable_capture(this[0], captureNameAddress, captureNameLength);
2787
+ C._free(captureNameAddress);
2788
+ }
2789
+ /**
2790
+ * Disable a certain pattern within a query.
2791
+ *
2792
+ * This prevents the pattern from matching, and also avoids any resource
2793
+ * usage associated with the pattern. This throws an error if the pattern
2794
+ * index is out of bounds.
2795
+ */
2796
+ disablePattern(patternIndex) {
2797
+ if (patternIndex >= this.predicates.length) {
2798
+ throw new Error(
2799
+ `Pattern index is ${patternIndex} but the pattern count is ${this.predicates.length}`
2800
+ );
2801
+ }
2802
+ C._ts_query_disable_pattern(this[0], patternIndex);
2803
+ }
2804
+ /**
2805
+ * Check if, on its last execution, this cursor exceeded its maximum number
2806
+ * of in-progress matches.
2807
+ */
2808
+ didExceedMatchLimit() {
2809
+ return this.exceededMatchLimit;
2810
+ }
2811
+ /** Get the byte offset where the given pattern starts in the query's source. */
2812
+ startIndexForPattern(patternIndex) {
2813
+ if (patternIndex >= this.predicates.length) {
2814
+ throw new Error(
2815
+ `Pattern index is ${patternIndex} but the pattern count is ${this.predicates.length}`
2816
+ );
2817
+ }
2818
+ return C._ts_query_start_byte_for_pattern(this[0], patternIndex);
2819
+ }
2820
+ /** Get the byte offset where the given pattern ends in the query's source. */
2821
+ endIndexForPattern(patternIndex) {
2822
+ if (patternIndex >= this.predicates.length) {
2823
+ throw new Error(
2824
+ `Pattern index is ${patternIndex} but the pattern count is ${this.predicates.length}`
2825
+ );
2826
+ }
2827
+ return C._ts_query_end_byte_for_pattern(this[0], patternIndex);
2828
+ }
2829
+ /** Get the number of patterns in the query. */
2830
+ patternCount() {
2831
+ return C._ts_query_pattern_count(this[0]);
2832
+ }
2833
+ /** Get the index for a given capture name. */
2834
+ captureIndexForName(captureName) {
2835
+ return this.captureNames.indexOf(captureName);
2836
+ }
2837
+ /** Check if a given pattern within a query has a single root node. */
2838
+ isPatternRooted(patternIndex) {
2839
+ return C._ts_query_is_pattern_rooted(this[0], patternIndex) === 1;
2840
+ }
2841
+ /** Check if a given pattern within a query has a single root node. */
2842
+ isPatternNonLocal(patternIndex) {
2843
+ return C._ts_query_is_pattern_non_local(this[0], patternIndex) === 1;
2844
+ }
2845
+ /**
2846
+ * Check if a given step in a query is 'definite'.
2847
+ *
2848
+ * A query step is 'definite' if its parent pattern will be guaranteed to
2849
+ * match successfully once it reaches the step.
2850
+ */
2851
+ isPatternGuaranteedAtStep(byteIndex) {
2852
+ return C._ts_query_is_pattern_guaranteed_at_step(this[0], byteIndex) === 1;
2853
+ }
2854
+ };
2855
+ export {
2856
+ CaptureQuantifier,
2857
+ Edit,
2858
+ LANGUAGE_VERSION,
2859
+ Language,
2860
+ LookaheadIterator,
2861
+ MIN_COMPATIBLE_VERSION,
2862
+ Node,
2863
+ Parser,
2864
+ Query,
2865
+ TextBuffer,
2866
+ Tree,
2867
+ TreeCursor,
2868
+ heap,
2869
+ loadExtension
2870
+ };
2871
+ //# sourceMappingURL=web-tree-sitter.js.map