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