-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathweb-tree-sitter.js
4001 lines (3989 loc) · 162 KB
/
web-tree-sitter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
if (typeof require !== "undefined") return require.apply(this, arguments);
throw Error('Dynamic require of "' + x + '" is not supported');
});
// src/constants.ts
var SIZE_OF_SHORT = 2;
var SIZE_OF_INT = 4;
var SIZE_OF_CURSOR = 4 * SIZE_OF_INT;
var SIZE_OF_NODE = 5 * SIZE_OF_INT;
var SIZE_OF_POINT = 2 * SIZE_OF_INT;
var SIZE_OF_RANGE = 2 * SIZE_OF_INT + 2 * SIZE_OF_POINT;
var ZERO_POINT = { row: 0, column: 0 };
var INTERNAL = Symbol("INTERNAL");
function assertInternal(x) {
if (x !== INTERNAL) throw new Error("Illegal constructor");
}
__name(assertInternal, "assertInternal");
function isPoint(point) {
return !!point && typeof point.row === "number" && typeof point.column === "number";
}
__name(isPoint, "isPoint");
function setModule(module2) {
C = module2;
}
__name(setModule, "setModule");
var C;
// src/lookahead_iterator.ts
var LookaheadIterator = class {
static {
__name(this, "LookaheadIterator");
}
/** @internal */
[0] = 0;
// Internal handle for WASM
/** @internal */
language;
/** @internal */
constructor(internal, address, language) {
assertInternal(internal);
this[0] = address;
this.language = language;
}
/** Get the current symbol of the lookahead iterator. */
get currentTypeId() {
return C._ts_lookahead_iterator_current_symbol(this[0]);
}
/** Get the current symbol name of the lookahead iterator. */
get currentType() {
return this.language.types[this.currentTypeId] || "ERROR";
}
/** Delete the lookahead iterator, freeing its resources. */
delete() {
C._ts_lookahead_iterator_delete(this[0]);
this[0] = 0;
}
/**
* Reset the lookahead iterator.
*
* This returns `true` if the language was set successfully and `false`
* otherwise.
*/
reset(language, stateId) {
if (C._ts_lookahead_iterator_reset(this[0], language[0], stateId)) {
this.language = language;
return true;
}
return false;
}
/**
* Reset the lookahead iterator to another state.
*
* This returns `true` if the iterator was reset to the given state and
* `false` otherwise.
*/
resetState(stateId) {
return Boolean(C._ts_lookahead_iterator_reset_state(this[0], stateId));
}
/**
* Returns an iterator that iterates over the symbols of the lookahead iterator.
*
* The iterator will yield the current symbol name as a string for each step
* until there are no more symbols to iterate over.
*/
[Symbol.iterator]() {
return {
next: /* @__PURE__ */ __name(() => {
if (C._ts_lookahead_iterator_next(this[0])) {
return { done: false, value: this.currentType };
}
return { done: true, value: "" };
}, "next")
};
}
};
// src/query.ts
var CaptureQuantifier = {
Zero: 0,
ZeroOrOne: 1,
ZeroOrMore: 2,
One: 3,
OneOrMore: 4
};
var Query = class {
static {
__name(this, "Query");
}
/** @internal */
[0] = 0;
// Internal handle for WASM
/** @internal */
exceededMatchLimit;
/** @internal */
textPredicates;
/** The names of the captures used in the query. */
captureNames;
/** The quantifiers of the captures used in the query. */
captureQuantifiers;
/**
* The other user-defined predicates associated with the given index.
*
* This includes predicates with operators other than:
* - `match?`
* - `eq?` and `not-eq?`
* - `any-of?` and `not-any-of?`
* - `is?` and `is-not?`
* - `set!`
*/
predicates;
/** The properties for predicates with the operator `set!`. */
setProperties;
/** The properties for predicates with the operator `is?`. */
assertedProperties;
/** The properties for predicates with the operator `is-not?`. */
refutedProperties;
/** The maximum number of in-progress matches for this cursor. */
matchLimit;
/** @internal */
constructor(internal, address, captureNames, captureQuantifiers, textPredicates, predicates, setProperties, assertedProperties, refutedProperties) {
assertInternal(internal);
this[0] = address;
this.captureNames = captureNames;
this.captureQuantifiers = captureQuantifiers;
this.textPredicates = textPredicates;
this.predicates = predicates;
this.setProperties = setProperties;
this.assertedProperties = assertedProperties;
this.refutedProperties = refutedProperties;
this.exceededMatchLimit = false;
}
/** Delete the query, freeing its resources. */
delete() {
C._ts_query_delete(this[0]);
this[0] = 0;
}
/**
* Iterate over all of the matches in the order that they were found.
*
* Each match contains the index of the pattern that matched, and a list of
* captures. Because multiple patterns can match the same set of nodes,
* one match may contain captures that appear *before* some of the
* captures from a previous match.
*
* @param {Node} node - The node to execute the query on.
*
* @param {QueryOptions} options - Options for query execution.
*/
matches(node, options = {}) {
const startPosition = options.startPosition ?? ZERO_POINT;
const endPosition = options.endPosition ?? ZERO_POINT;
const startIndex = options.startIndex ?? 0;
const endIndex = options.endIndex ?? 0;
const matchLimit = options.matchLimit ?? 4294967295;
const maxStartDepth = options.maxStartDepth ?? 4294967295;
const timeoutMicros = options.timeoutMicros ?? 0;
const progressCallback = options.progressCallback;
if (typeof matchLimit !== "number") {
throw new Error("Arguments must be numbers");
}
this.matchLimit = matchLimit;
if (endIndex !== 0 && startIndex > endIndex) {
throw new Error("`startIndex` cannot be greater than `endIndex`");
}
if (endPosition !== ZERO_POINT && (startPosition.row > endPosition.row || startPosition.row === endPosition.row && startPosition.column > endPosition.column)) {
throw new Error("`startPosition` cannot be greater than `endPosition`");
}
if (progressCallback) {
C.currentQueryProgressCallback = progressCallback;
}
marshalNode(node);
C._ts_query_matches_wasm(
this[0],
node.tree[0],
startPosition.row,
startPosition.column,
endPosition.row,
endPosition.column,
startIndex,
endIndex,
matchLimit,
maxStartDepth,
timeoutMicros
);
const rawCount = C.getValue(TRANSFER_BUFFER, "i32");
const startAddress = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
const didExceedMatchLimit = C.getValue(TRANSFER_BUFFER + 2 * SIZE_OF_INT, "i32");
const result = new Array(rawCount);
this.exceededMatchLimit = Boolean(didExceedMatchLimit);
let filteredCount = 0;
let address = startAddress;
for (let i2 = 0; i2 < rawCount; i2++) {
const pattern = C.getValue(address, "i32");
address += SIZE_OF_INT;
const captureCount = C.getValue(address, "i32");
address += SIZE_OF_INT;
const captures = new Array(captureCount);
address = unmarshalCaptures(this, node.tree, address, captures);
if (this.textPredicates[pattern].every((p) => p(captures))) {
result[filteredCount] = { pattern, captures };
const setProperties = this.setProperties[pattern];
result[filteredCount].setProperties = setProperties;
const assertedProperties = this.assertedProperties[pattern];
result[filteredCount].assertedProperties = assertedProperties;
const refutedProperties = this.refutedProperties[pattern];
result[filteredCount].refutedProperties = refutedProperties;
filteredCount++;
}
}
result.length = filteredCount;
C._free(startAddress);
C.currentQueryProgressCallback = null;
return result;
}
/**
* Iterate over all of the individual captures in the order that they
* appear.
*
* This is useful if you don't care about which pattern matched, and just
* want a single, ordered sequence of captures.
*
* @param {Node} node - The node to execute the query on.
*
* @param {QueryOptions} options - Options for query execution.
*/
captures(node, options = {}) {
const startPosition = options.startPosition ?? ZERO_POINT;
const endPosition = options.endPosition ?? ZERO_POINT;
const startIndex = options.startIndex ?? 0;
const endIndex = options.endIndex ?? 0;
const matchLimit = options.matchLimit ?? 4294967295;
const maxStartDepth = options.maxStartDepth ?? 4294967295;
const timeoutMicros = options.timeoutMicros ?? 0;
const progressCallback = options.progressCallback;
if (typeof matchLimit !== "number") {
throw new Error("Arguments must be numbers");
}
this.matchLimit = matchLimit;
if (endIndex !== 0 && startIndex > endIndex) {
throw new Error("`startIndex` cannot be greater than `endIndex`");
}
if (endPosition !== ZERO_POINT && (startPosition.row > endPosition.row || startPosition.row === endPosition.row && startPosition.column > endPosition.column)) {
throw new Error("`startPosition` cannot be greater than `endPosition`");
}
if (progressCallback) {
C.currentQueryProgressCallback = progressCallback;
}
marshalNode(node);
C._ts_query_captures_wasm(
this[0],
node.tree[0],
startPosition.row,
startPosition.column,
endPosition.row,
endPosition.column,
startIndex,
endIndex,
matchLimit,
maxStartDepth,
timeoutMicros
);
const count = C.getValue(TRANSFER_BUFFER, "i32");
const startAddress = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
const didExceedMatchLimit = C.getValue(TRANSFER_BUFFER + 2 * SIZE_OF_INT, "i32");
const result = new Array();
this.exceededMatchLimit = Boolean(didExceedMatchLimit);
const captures = new Array();
let address = startAddress;
for (let i2 = 0; i2 < count; i2++) {
const pattern = C.getValue(address, "i32");
address += SIZE_OF_INT;
const captureCount = C.getValue(address, "i32");
address += SIZE_OF_INT;
const captureIndex = C.getValue(address, "i32");
address += SIZE_OF_INT;
captures.length = captureCount;
address = unmarshalCaptures(this, node.tree, address, captures);
if (this.textPredicates[pattern].every((p) => p(captures))) {
const capture = captures[captureIndex];
const setProperties = this.setProperties[pattern];
capture.setProperties = setProperties;
const assertedProperties = this.assertedProperties[pattern];
capture.assertedProperties = assertedProperties;
const refutedProperties = this.refutedProperties[pattern];
capture.refutedProperties = refutedProperties;
result.push(capture);
}
}
C._free(startAddress);
C.currentQueryProgressCallback = null;
return result;
}
/** Get the predicates for a given pattern. */
predicatesForPattern(patternIndex) {
return this.predicates[patternIndex];
}
/**
* Disable a certain capture within a query.
*
* This prevents the capture from being returned in matches, and also
* avoids any resource usage associated with recording the capture.
*/
disableCapture(captureName) {
const captureNameLength = C.lengthBytesUTF8(captureName);
const captureNameAddress = C._malloc(captureNameLength + 1);
C.stringToUTF8(captureName, captureNameAddress, captureNameLength + 1);
C._ts_query_disable_capture(this[0], captureNameAddress, captureNameLength);
C._free(captureNameAddress);
}
/**
* Disable a certain pattern within a query.
*
* This prevents the pattern from matching, and also avoids any resource
* usage associated with the pattern. This throws an error if the pattern
* index is out of bounds.
*/
disablePattern(patternIndex) {
if (patternIndex >= this.predicates.length) {
throw new Error(
`Pattern index is ${patternIndex} but the pattern count is ${this.predicates.length}`
);
}
C._ts_query_disable_pattern(this[0], patternIndex);
}
/**
* Check if, on its last execution, this cursor exceeded its maximum number
* of in-progress matches.
*/
didExceedMatchLimit() {
return this.exceededMatchLimit;
}
/** Get the byte offset where the given pattern starts in the query's source. */
startIndexForPattern(patternIndex) {
if (patternIndex >= this.predicates.length) {
throw new Error(
`Pattern index is ${patternIndex} but the pattern count is ${this.predicates.length}`
);
}
return C._ts_query_start_byte_for_pattern(this[0], patternIndex);
}
/** Get the byte offset where the given pattern ends in the query's source. */
endIndexForPattern(patternIndex) {
if (patternIndex >= this.predicates.length) {
throw new Error(
`Pattern index is ${patternIndex} but the pattern count is ${this.predicates.length}`
);
}
return C._ts_query_end_byte_for_pattern(this[0], patternIndex);
}
/** Get the number of patterns in the query. */
patternCount() {
return C._ts_query_pattern_count(this[0]);
}
/** Get the index for a given capture name. */
captureIndexForName(captureName) {
return this.captureNames.indexOf(captureName);
}
/** Check if a given pattern within a query has a single root node. */
isPatternRooted(patternIndex) {
return C._ts_query_is_pattern_rooted(this[0], patternIndex) === 1;
}
/** Check if a given pattern within a query has a single root node. */
isPatternNonLocal(patternIndex) {
return C._ts_query_is_pattern_non_local(this[0], patternIndex) === 1;
}
/**
* Check if a given step in a query is 'definite'.
*
* A query step is 'definite' if its parent pattern will be guaranteed to
* match successfully once it reaches the step.
*/
isPatternGuaranteedAtStep(byteIndex) {
return C._ts_query_is_pattern_guaranteed_at_step(this[0], byteIndex) === 1;
}
};
// src/language.ts
var PREDICATE_STEP_TYPE_CAPTURE = 1;
var PREDICATE_STEP_TYPE_STRING = 2;
var QUERY_WORD_REGEX = /[\w-]+/g;
var LANGUAGE_FUNCTION_REGEX = /^tree_sitter_\w+$/;
var Language = class _Language {
static {
__name(this, "Language");
}
/** @internal */
[0] = 0;
// Internal handle for WASM
/**
* A list of all node types in the language. The index of each type in this
* array is its node type id.
*/
types;
/**
* A list of all field names in the language. The index of each field name in
* this array is its field id.
*/
fields;
/** @internal */
constructor(internal, address) {
assertInternal(internal);
this[0] = address;
this.types = new Array(C._ts_language_symbol_count(this[0]));
for (let i2 = 0, n = this.types.length; i2 < n; i2++) {
if (C._ts_language_symbol_type(this[0], i2) < 2) {
this.types[i2] = C.UTF8ToString(C._ts_language_symbol_name(this[0], i2));
}
}
this.fields = new Array(C._ts_language_field_count(this[0]) + 1);
for (let i2 = 0, n = this.fields.length; i2 < n; i2++) {
const fieldName = C._ts_language_field_name_for_id(this[0], i2);
if (fieldName !== 0) {
this.fields[i2] = C.UTF8ToString(fieldName);
} else {
this.fields[i2] = null;
}
}
}
/**
* Gets the name of the language.
*/
get name() {
const ptr = C._ts_language_name(this[0]);
if (ptr === 0) return null;
return C.UTF8ToString(ptr);
}
/**
* Gets the version of the language.
*/
get version() {
return C._ts_language_version(this[0]);
}
/**
* Gets the number of fields in the language.
*/
get fieldCount() {
return this.fields.length - 1;
}
/**
* Gets the number of states in the language.
*/
get stateCount() {
return C._ts_language_state_count(this[0]);
}
/**
* Get the field id for a field name.
*/
fieldIdForName(fieldName) {
const result = this.fields.indexOf(fieldName);
return result !== -1 ? result : null;
}
/**
* Get the field name for a field id.
*/
fieldNameForId(fieldId) {
return this.fields[fieldId] ?? null;
}
/**
* Get the node type id for a node type name.
*/
idForNodeType(type, named) {
const typeLength = C.lengthBytesUTF8(type);
const typeAddress = C._malloc(typeLength + 1);
C.stringToUTF8(type, typeAddress, typeLength + 1);
const result = C._ts_language_symbol_for_name(this[0], typeAddress, typeLength, named ? 1 : 0);
C._free(typeAddress);
return result || null;
}
/**
* Gets the number of node types in the language.
*/
get nodeTypeCount() {
return C._ts_language_symbol_count(this[0]);
}
/**
* Get the node type name for a node type id.
*/
nodeTypeForId(typeId) {
const name2 = C._ts_language_symbol_name(this[0], typeId);
return name2 ? C.UTF8ToString(name2) : null;
}
/**
* Check if a node type is named.
*
* @see {@link https://tree-sitter.github.io/tree-sitter/using-parsers/2-basic-parsing.html#named-vs-anonymous-nodes}
*/
nodeTypeIsNamed(typeId) {
return C._ts_language_type_is_named_wasm(this[0], typeId) ? true : false;
}
/**
* Check if a node type is visible.
*/
nodeTypeIsVisible(typeId) {
return C._ts_language_type_is_visible_wasm(this[0], typeId) ? true : false;
}
/**
* Get the supertypes ids of this language.
*
* @see {@link https://tree-sitter.github.io/tree-sitter/using-parsers/6-static-node-types.html?highlight=supertype#supertype-nodes}
*/
get supertypes() {
C._ts_language_supertypes_wasm(this[0]);
const count = C.getValue(TRANSFER_BUFFER, "i32");
const buffer = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
const result = new Array(count);
if (count > 0) {
let address = buffer;
for (let i2 = 0; i2 < count; i2++) {
result[i2] = C.getValue(address, "i16");
address += SIZE_OF_SHORT;
}
}
return result;
}
/**
* Get the subtype ids for a given supertype node id.
*/
subtypes(supertype) {
C._ts_language_subtypes_wasm(this[0], supertype);
const count = C.getValue(TRANSFER_BUFFER, "i32");
const buffer = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
const result = new Array(count);
if (count > 0) {
let address = buffer;
for (let i2 = 0; i2 < count; i2++) {
result[i2] = C.getValue(address, "i16");
address += SIZE_OF_SHORT;
}
}
return result;
}
/**
* Get the next state id for a given state id and node type id.
*/
nextState(stateId, typeId) {
return C._ts_language_next_state(this[0], stateId, typeId);
}
/**
* Create a new lookahead iterator for this language and parse state.
*
* This returns `null` if state is invalid for this language.
*
* Iterating {@link LookaheadIterator} will yield valid symbols in the given
* parse state. Newly created lookahead iterators will return the `ERROR`
* symbol from {@link LookaheadIterator#currentType}.
*
* Lookahead iterators can be useful for generating suggestions and improving
* syntax error diagnostics. To get symbols valid in an `ERROR` node, use the
* lookahead iterator on its first leaf node state. For `MISSING` nodes, a
* lookahead iterator created on the previous non-extra leaf node may be
* appropriate.
*/
lookaheadIterator(stateId) {
const address = C._ts_lookahead_iterator_new(this[0], stateId);
if (address) return new LookaheadIterator(INTERNAL, address, this);
return null;
}
/**
* Create a new query from a string containing one or more S-expression
* patterns.
*
* The query is associated with a particular language, and can only be run
* on syntax nodes parsed with that language. References to Queries can be
* shared between multiple threads.
*
* @link {@see https://tree-sitter.github.io/tree-sitter/using-parsers/queries}
*/
query(source) {
const sourceLength = C.lengthBytesUTF8(source);
const sourceAddress = C._malloc(sourceLength + 1);
C.stringToUTF8(source, sourceAddress, sourceLength + 1);
const address = C._ts_query_new(
this[0],
sourceAddress,
sourceLength,
TRANSFER_BUFFER,
TRANSFER_BUFFER + SIZE_OF_INT
);
if (!address) {
const errorId = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
const errorByte = C.getValue(TRANSFER_BUFFER, "i32");
const errorIndex = C.UTF8ToString(sourceAddress, errorByte).length;
const suffix = source.slice(errorIndex, errorIndex + 100).split("\n")[0];
let word = suffix.match(QUERY_WORD_REGEX)?.[0] ?? "";
let error;
switch (errorId) {
case 2:
error = new RangeError(`Bad node name '${word}'`);
break;
case 3:
error = new RangeError(`Bad field name '${word}'`);
break;
case 4:
error = new RangeError(`Bad capture name @${word}`);
break;
case 5:
error = new TypeError(`Bad pattern structure at offset ${errorIndex}: '${suffix}'...`);
word = "";
break;
default:
error = new SyntaxError(`Bad syntax at offset ${errorIndex}: '${suffix}'...`);
word = "";
break;
}
error.index = errorIndex;
error.length = word.length;
C._free(sourceAddress);
throw error;
}
const stringCount = C._ts_query_string_count(address);
const captureCount = C._ts_query_capture_count(address);
const patternCount = C._ts_query_pattern_count(address);
const captureNames = new Array(captureCount);
const captureQuantifiers = new Array(patternCount);
const stringValues = new Array(stringCount);
for (let i2 = 0; i2 < captureCount; i2++) {
const nameAddress = C._ts_query_capture_name_for_id(
address,
i2,
TRANSFER_BUFFER
);
const nameLength = C.getValue(TRANSFER_BUFFER, "i32");
captureNames[i2] = C.UTF8ToString(nameAddress, nameLength);
}
for (let i2 = 0; i2 < patternCount; i2++) {
const captureQuantifiersArray = new Array(captureCount);
for (let j = 0; j < captureCount; j++) {
const quantifier = C._ts_query_capture_quantifier_for_id(address, i2, j);
captureQuantifiersArray[j] = quantifier;
}
captureQuantifiers[i2] = captureQuantifiersArray;
}
for (let i2 = 0; i2 < stringCount; i2++) {
const valueAddress = C._ts_query_string_value_for_id(
address,
i2,
TRANSFER_BUFFER
);
const nameLength = C.getValue(TRANSFER_BUFFER, "i32");
stringValues[i2] = C.UTF8ToString(valueAddress, nameLength);
}
const setProperties = new Array(patternCount);
const assertedProperties = new Array(patternCount);
const refutedProperties = new Array(patternCount);
const predicates = new Array(patternCount);
const textPredicates = new Array(patternCount);
for (let i2 = 0; i2 < patternCount; i2++) {
const predicatesAddress = C._ts_query_predicates_for_pattern(
address,
i2,
TRANSFER_BUFFER
);
const stepCount = C.getValue(TRANSFER_BUFFER, "i32");
predicates[i2] = [];
textPredicates[i2] = [];
const steps = new Array();
const isStringStep = /* @__PURE__ */ __name((step) => {
return step.type === "string";
}, "isStringStep");
let stepAddress = predicatesAddress;
for (let j = 0; j < stepCount; j++) {
const stepType = C.getValue(stepAddress, "i32");
stepAddress += SIZE_OF_INT;
const stepValueId = C.getValue(stepAddress, "i32");
stepAddress += SIZE_OF_INT;
if (stepType === PREDICATE_STEP_TYPE_CAPTURE) {
const name2 = captureNames[stepValueId];
steps.push({ type: "capture", name: name2 });
} else if (stepType === PREDICATE_STEP_TYPE_STRING) {
steps.push({ type: "string", value: stringValues[stepValueId] });
} else if (steps.length > 0) {
if (steps[0].type !== "string") {
throw new Error("Predicates must begin with a literal value");
}
const operator = steps[0].value;
let isPositive = true;
let matchAll = true;
let captureName;
switch (operator) {
case "any-not-eq?":
case "not-eq?":
isPositive = false;
case "any-eq?":
case "eq?": {
if (steps.length !== 3) {
throw new Error(
`Wrong number of arguments to \`#${operator}\` predicate. Expected 2, got ${steps.length - 1}`
);
}
if (steps[1].type !== "capture") {
throw new Error(
`First argument of \`#${operator}\` predicate must be a capture. Got "${steps[1].value}"`
);
}
matchAll = !operator.startsWith("any-");
if (steps[2].type === "capture") {
const captureName1 = steps[1].name;
const captureName2 = steps[2].name;
textPredicates[i2].push((captures) => {
const nodes1 = [];
const nodes2 = [];
for (const c of captures) {
if (c.name === captureName1) nodes1.push(c.node);
if (c.name === captureName2) nodes2.push(c.node);
}
const compare = /* @__PURE__ */ __name((n1, n2, positive) => {
return positive ? n1.text === n2.text : n1.text !== n2.text;
}, "compare");
return matchAll ? nodes1.every((n1) => nodes2.some((n2) => compare(n1, n2, isPositive))) : nodes1.some((n1) => nodes2.some((n2) => compare(n1, n2, isPositive)));
});
} else {
captureName = steps[1].name;
const stringValue = steps[2].value;
const matches = /* @__PURE__ */ __name((n) => n.text === stringValue, "matches");
const doesNotMatch = /* @__PURE__ */ __name((n) => n.text !== stringValue, "doesNotMatch");
textPredicates[i2].push((captures) => {
const nodes = [];
for (const c of captures) {
if (c.name === captureName) nodes.push(c.node);
}
const test = isPositive ? matches : doesNotMatch;
return matchAll ? nodes.every(test) : nodes.some(test);
});
}
break;
}
case "any-not-match?":
case "not-match?":
isPositive = false;
case "any-match?":
case "match?": {
if (steps.length !== 3) {
throw new Error(
`Wrong number of arguments to \`#${operator}\` predicate. Expected 2, got ${steps.length - 1}.`
);
}
if (steps[1].type !== "capture") {
throw new Error(
`First argument of \`#${operator}\` predicate must be a capture. Got "${steps[1].value}".`
);
}
if (steps[2].type !== "string") {
throw new Error(
`Second argument of \`#${operator}\` predicate must be a string. Got @${steps[2].name}.`
);
}
captureName = steps[1].name;
const regex = new RegExp(steps[2].value);
matchAll = !operator.startsWith("any-");
textPredicates[i2].push((captures) => {
const nodes = [];
for (const c of captures) {
if (c.name === captureName) nodes.push(c.node.text);
}
const test = /* @__PURE__ */ __name((text, positive) => {
return positive ? regex.test(text) : !regex.test(text);
}, "test");
if (nodes.length === 0) return !isPositive;
return matchAll ? nodes.every((text) => test(text, isPositive)) : nodes.some((text) => test(text, isPositive));
});
break;
}
case "set!": {
if (steps.length < 2 || steps.length > 3) {
throw new Error(
`Wrong number of arguments to \`#set!\` predicate. Expected 1 or 2. Got ${steps.length - 1}.`
);
}
if (!steps.every(isStringStep)) {
throw new Error(
`Arguments to \`#set!\` predicate must be strings.".`
);
}
if (!setProperties[i2]) setProperties[i2] = {};
setProperties[i2][steps[1].value] = steps[2]?.value ?? null;
break;
}
case "is?":
case "is-not?": {
if (steps.length < 2 || steps.length > 3) {
throw new Error(
`Wrong number of arguments to \`#${operator}\` predicate. Expected 1 or 2. Got ${steps.length - 1}.`
);
}
if (!steps.every(isStringStep)) {
throw new Error(
`Arguments to \`#${operator}\` predicate must be strings.".`
);
}
const properties = operator === "is?" ? assertedProperties : refutedProperties;
if (!properties[i2]) properties[i2] = {};
properties[i2][steps[1].value] = steps[2]?.value ?? null;
break;
}
case "not-any-of?":
isPositive = false;
case "any-of?": {
if (steps.length < 2) {
throw new Error(
`Wrong number of arguments to \`#${operator}\` predicate. Expected at least 1. Got ${steps.length - 1}.`
);
}
if (steps[1].type !== "capture") {
throw new Error(
`First argument of \`#${operator}\` predicate must be a capture. Got "${steps[1].value}".`
);
}
captureName = steps[1].name;
const stringSteps = steps.slice(2);
if (!stringSteps.every(isStringStep)) {
throw new Error(
`Arguments to \`#${operator}\` predicate must be strings.".`
);
}
const values = stringSteps.map((s) => s.value);
textPredicates[i2].push((captures) => {
const nodes = [];
for (const c of captures) {
if (c.name === captureName) nodes.push(c.node.text);
}
if (nodes.length === 0) return !isPositive;
return nodes.every((text) => values.includes(text)) === isPositive;
});
break;
}
default:
predicates[i2].push({ operator, operands: steps.slice(1) });
}
steps.length = 0;
}
}
Object.freeze(setProperties[i2]);
Object.freeze(assertedProperties[i2]);
Object.freeze(refutedProperties[i2]);
}
C._free(sourceAddress);
return new Query(
INTERNAL,
address,
captureNames,
captureQuantifiers,
textPredicates,
predicates,
setProperties,
assertedProperties,
refutedProperties
);
}
/**
* Load a language from a WebAssembly module.
* The module can be provided as a path to a file or as a buffer.
*/
static async load(input) {
let bytes;
if (input instanceof Uint8Array) {
bytes = Promise.resolve(input);
} else {
if (globalThis.process?.versions.node) {
const fs2 = __require("fs/promises");
bytes = fs2.readFile(input);
} else {
bytes = fetch(input).then((response) => response.arrayBuffer().then((buffer) => {
if (response.ok) {
return new Uint8Array(buffer);
} else {
const body2 = new TextDecoder("utf-8").decode(buffer);
throw new Error(`Language.load failed with status ${response.status}.
${body2}`);
}
}));
}
}
const mod = await C.loadWebAssemblyModule(await bytes, { loadAsync: true });
const symbolNames = Object.keys(mod);
const functionName = symbolNames.find((key) => LANGUAGE_FUNCTION_REGEX.test(key) && !key.includes("external_scanner_"));
if (!functionName) {
console.log(`Couldn't find language function in WASM file. Symbols:
${JSON.stringify(symbolNames, null, 2)}`);
throw new Error("Language.load failed: no language function found in WASM file");
}
const languageAddress = mod[functionName]();
return new _Language(INTERNAL, languageAddress);
}
};
// lib/tree-sitter.mjs
var Module2 = (() => {
var _scriptName = import.meta.url;
return async function(moduleArg = {}) {
var moduleRtn;
var Module = moduleArg;
var readyPromiseResolve, readyPromiseReject;
var readyPromise = new Promise((resolve, reject) => {
readyPromiseResolve = resolve;
readyPromiseReject = reject;
});
var ENVIRONMENT_IS_WEB = typeof window == "object";
var ENVIRONMENT_IS_WORKER = typeof WorkerGlobalScope != "undefined";
var ENVIRONMENT_IS_NODE = typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string" && process.type != "renderer";
var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
if (ENVIRONMENT_IS_NODE) {
const { createRequire } = await import("module");
let dirname = import.meta.url;
if (dirname.startsWith("data:")) {
dirname = "/";
}
var require = createRequire(dirname);
}
Module.currentQueryProgressCallback = null;
Module.currentProgressCallback = null;
Module.currentLogCallback = null;
Module.currentParseCallback = null;
var moduleOverrides = Object.assign({}, Module);
var arguments_ = [];
var thisProgram = "./this.program";
var quit_ = /* @__PURE__ */ __name((status, toThrow) => {
throw toThrow;
}, "quit_");
var scriptDirectory = "";
function locateFile(path) {
if (Module["locateFile"]) {
return Module["locateFile"](path, scriptDirectory);
}
return scriptDirectory + path;
}
__name(locateFile, "locateFile");
var readAsync, readBinary;
if (ENVIRONMENT_IS_NODE) {
var fs = require("fs");
var nodePath = require("path");
if (!import.meta.url.startsWith("data:")) {
scriptDirectory = nodePath.dirname(require("url").fileURLToPath(import.meta.url)) + "/";
}
readBinary = /* @__PURE__ */ __name((filename) => {
filename = isFileURI(filename) ? new URL(filename) : nodePath.normalize(filename);
var ret = fs.readFileSync(filename);
return ret;
}, "readBinary");
readAsync = /* @__PURE__ */ __name((filename, binary2 = true) => {
filename = isFileURI(filename) ? new URL(filename) : nodePath.normalize(filename);
return new Promise((resolve, reject) => {
fs.readFile(filename, binary2 ? void 0 : "utf8", (err2, data) => {
if (err2) reject(err2);
else resolve(binary2 ? data.buffer : data);
});
});
}, "readAsync");
if (!Module["thisProgram"] && process.argv.length > 1) {
thisProgram = process.argv[1].replace(/\\/g, "/");
}
arguments_ = process.argv.slice(2);
quit_ = /* @__PURE__ */ __name((status, toThrow) => {
process.exitCode = status;
throw toThrow;
}, "quit_");
} else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
if (ENVIRONMENT_IS_WORKER) {
scriptDirectory = self.location.href;
} else if (typeof document != "undefined" && document.currentScript) {
scriptDirectory = document.currentScript.src;
}
if (_scriptName) {
scriptDirectory = _scriptName;
}
if (scriptDirectory.startsWith("blob:")) {
scriptDirectory = "";
} else {
scriptDirectory = scriptDirectory.substr(0, scriptDirectory.replace(/[?#].*/, "").lastIndexOf("/") + 1);
}
{
if (ENVIRONMENT_IS_WORKER) {
readBinary = /* @__PURE__ */ __name((url) => {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);