-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.ts
More file actions
1255 lines (1180 loc) · 45.7 KB
/
Copy pathindex.ts
File metadata and controls
1255 lines (1180 loc) · 45.7 KB
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
import { FunctionCall, NodeType, parse, QNode } from "./parseQuery";
import { parse as parseJS } from "meriyah";
import {
isNodePath,
VISITOR_KEYS,
isAssignmentExpression,
isBinding,
isExportSpecifier,
isFunctionDeclaration,
isFunctionExpression,
isIdentifier,
isMemberExpression,
isNode,
isPrimitive,
isScopable,
isScope,
isUpdateExpression,
isVariableDeclaration,
isVariableDeclarator,
staticTemplateLiteralValue,
} from "./nodeutils";
import { ESTree } from "meriyah";
import { isDefined, toArray } from "./utils";
const debugLogEnabled = false;
const log = debugLogEnabled
? {
debug: (...args: unknown[]) => {
console.debug(...args);
},
}
: undefined;
export const functions = {
join: {
fn: (result: Result[][]): Result[] => {
if (result.length != 2) throw new Error("Invalid number of arugments for join");
const [values, separators] = result;
if (separators.length != 1) throw new Error("Invalid number of separators for join");
const separator = separators[0];
if (typeof separator != "string") throw new Error("Separator must be a string");
if (values.length == 0) return [];
return [values.join(separator as string)];
},
},
concat: {
fn: (result: Result[][]): Result[] => {
// Optimize: combine empty check with manual flattening
const flattened: Result[] = [];
for (let i = 0; i < result.length; i++) {
if (result[i].length === 0) return [];
for (let j = 0; j < result[i].length; j++) {
flattened.push(result[i][j]);
}
}
return [flattened.join("")];
},
},
first: {
fn: (result: Result[][]): Result[] => {
if (result.length != 1) throw new Error("Invalid number of arugments for first");
if (result[0].length == 0) return [];
return [result[0][0]];
},
},
nthchild: {
fn: (result: Result[][]): Result[] => {
if (result.length != 2) throw new Error("Invalid number of arguments for nthchild");
if (result[1].length != 1) throw new Error("Invalid number of arguments for nthchild");
const x = result[1][0];
const number = typeof x == "number" ? x : parseInt(x as string);
return [result[0][number]];
},
},
};
const functionNames = new Set(Object.keys(functions));
export type AvailableFunction = keyof typeof functions;
export function isAvailableFunction(name: string): name is AvailableFunction {
return functionNames.has(name);
}
export type PrimitiveValue = string | number | boolean;
type Result = ASTNode | PrimitiveValue;
type FNode = {
node: QNode;
result: Array<Result>;
// Insertion order among active descendant selectors. Assigned when a
// descendant FNode becomes active so that, when several descendant selectors
// match the same node, we can dispatch them in the exact depth-major order the
// old full-scan used (keeps result ordering stable).
seq?: number;
// Depth at which this descendant selector was activated (the depth of the
// ancestor node whose match triggered it). Combined with node.minDepth /
// node.maxDepth to bound //{min,max} selectors: a candidate at `depth`
// is `depth - baseDepth` steps away from the activating ancestor.
baseDepth?: number;
};
type State = {
depth: number;
child: FNode[][];
descendant: FNode[][];
// Lazily allocated per depth and keyed by the AST node, so looking up the
// filters for a (selector, node) pair is O(1) even when many siblings at the
// same depth carry filters. Most nodes carry no filter, so the Map itself is
// only allocated when one appears at that depth.
filtersMap: Array<Map<ASTNode, FilterResult[]> | undefined>;
matches: [FNode, NodePath][][];
functionCalls: FunctionCallResult[][];
// Index of the currently-active descendant ("//") selectors, kept in lockstep
// with `descendant`. Lets each visited node look up only the selectors that
// could match its type instead of scanning every active descendant selector.
// Arbitrary-depth matching is unchanged: selectors stay active for their whole
// subtree; only the lookup is faster.
descendantByType: Map<string, FNode[]>;
descendantOther: FNode[]; // wildcard (//*) and attribute selectors: checked at every node
descendantAttr: FNode[]; // attribute descendant selectors: used by the exit primitive pass
descendantActiveCount: number;
seqCounter: number;
};
type FilterCondition = {
type: typeof NodeType.AND | typeof NodeType.OR | typeof NodeType.EQUALS;
left: FilterNode;
right: FilterNode;
};
type FilterNode = FilterCondition | FNode;
type FilterResult = {
qNode: QNode;
filter: FilterNode;
node: ASTNode;
result: Array<Result>;
};
type FunctionCallResult = {
node: QNode;
functionCall: FunctionCall;
parameters: (FNode | FunctionCallResult)[];
result: Array<Result>;
};
function breadCrumb(path: NodePath) {
if (!debugLogEnabled) return "";
return {
//Using the toString trick here to avoid calculating the breadcrumb if debug logging is off
valueOf(): string {
if (path.parentPath == undefined) return "@" + path.node.type;
return (
breadCrumb(path.parentPath) +
"." +
(path.parentKey == path.key ? path.key : path.parentKey + "[" + path.key + "]") +
"@" +
path.node.type
);
},
};
}
function createQuerier() {
const traverser = createTraverser();
const { getChildren, getPrimitiveChildren, getPrimitiveChildrenOrNodePaths, getBinding, createNodePath, traverse } =
traverser;
function createFilter(filter: QNode, filterResult: Array<Result>): FilterNode {
if (filter.type == NodeType.AND || filter.type == NodeType.OR || filter.type == NodeType.EQUALS) {
return {
type: filter.type,
left: createFilter(filter.left, []),
right: createFilter(filter.right, []),
};
} else if (filter.type == NodeType.LITERAL) {
const r = [filter.value];
return {
node: filter,
result: r,
};
}
return createFNode(filter, filterResult);
}
function createFNode(token: QNode, result: Array<Result>): FNode {
return {
node: token,
result: result,
};
}
// Make a descendant FNode active: record it on the per-depth `descendant`
// stack (unchanged) and mirror it into the type index so future nodes can
// find it by their node type in O(1).
function activateDescendant(fnode: FNode, state: State) {
state.descendant[state.depth + 1].push(fnode);
fnode.seq = state.seqCounter++;
fnode.baseDepth = state.depth;
const value = fnode.node.value;
if (fnode.node.attribute) {
// Attribute selector (//:name): matches on key, so must be tried on every
// node; also drives the primitive-attribute pass on exit.
state.descendantOther.push(fnode);
state.descendantAttr.push(fnode);
} else if (value == "*") {
state.descendantOther.push(fnode);
} else if (value != undefined) {
let bucket = state.descendantByType.get(value);
if (!bucket) {
bucket = [];
state.descendantByType.set(value, bucket);
}
bucket.push(fnode);
}
state.descendantActiveCount++;
}
function removeFromBucket(arr: FNode[], fnode: FNode) {
// Deactivation is LIFO with activation, so the target is at (or near) the
// end; lastIndexOf keeps this close to O(1) for the tiny buckets involved.
const i = arr.lastIndexOf(fnode);
if (i >= 0) arr.splice(i, 1);
}
function deactivateDescendant(fnode: FNode, state: State) {
const value = fnode.node.value;
if (fnode.node.attribute) {
removeFromBucket(state.descendantOther, fnode);
removeFromBucket(state.descendantAttr, fnode);
} else if (value == "*") {
removeFromBucket(state.descendantOther, fnode);
} else if (value != undefined) {
const bucket = state.descendantByType.get(value);
if (bucket) removeFromBucket(bucket, fnode);
}
state.descendantActiveCount--;
}
function addFilterChildrenToState(filter: FilterNode, state: State) {
if (
"type" in filter &&
(filter.type == NodeType.AND || filter.type == NodeType.OR || filter.type == NodeType.EQUALS)
) {
addFilterChildrenToState(filter.left, state);
addFilterChildrenToState(filter.right, state);
} else if ("node" in filter) {
if (filter.node.type == NodeType.CHILD) {
log?.debug("ADDING FILTER CHILD", filter.node);
state.child[state.depth + 1].push(filter);
}
if (filter.node.type == NodeType.DESCENDANT) {
log?.debug("ADDING FILTER DESCENDANT", filter.node);
activateDescendant(filter, state);
}
}
}
function createFNodeAndAddToState(token: QNode, result: Array<Result>, state: State): FNode {
log?.debug("ADDING FNODE", token);
const fnode = createFNode(token, result);
if (token.type == NodeType.CHILD) {
state.child[state.depth + 1].push(fnode);
} else if (token.type == NodeType.DESCENDANT) {
activateDescendant(fnode, state);
}
return fnode;
}
// Bounds a //{min,max} descendant selector to the right number of steps
// below the ancestor that activated it. Plain "//" selectors carry no
// minDepth/maxDepth, so this is a no-op for them.
function descendantInDepthRange(fnode: FNode, depth: number): boolean {
const min = fnode.node.minDepth;
const max = fnode.node.maxDepth;
if (min == undefined && max == undefined) return true;
const steps = depth - fnode.baseDepth!;
if (min != undefined && steps < min) return false;
if (max != undefined && steps > max) return false;
return true;
}
// Matching needs only the node's type and its position keys, all available
// without materializing a NodePath. Loose equality on `key` is intentional:
// array indices are kept as numbers in the traversal frames while query
// values are strings.
function isMatch(
fnode: FNode,
node: ASTNode,
key: string | number | undefined,
parentKey: string | undefined,
): boolean {
if (fnode.node.attribute) {
return fnode.node.value == parentKey || fnode.node.value == key;
}
if (fnode.node.value == "*") {
return true;
}
return fnode.node.value == node.type;
}
// Records a match. The NodePath is only materialized by the caller when a
// match actually occurs, so most visited nodes never allocate one.
function addMatch(fnode: FNode, path: NodePath, state: State) {
state.matches[state.depth].push([fnode, path]);
if (fnode.node.filter) {
const filter = createFilter(fnode.node.filter, []);
const filteredResult: Array<Result> = [];
const f = { filter: filter, qNode: fnode.node, node: path.node, result: filteredResult };
let fmapContainer = state.filtersMap[state.depth];
if (!fmapContainer) {
fmapContainer = new Map();
state.filtersMap[state.depth] = fmapContainer;
}
let fmap = fmapContainer.get(path.node);
if (!fmap) {
fmap = [];
fmapContainer.set(path.node, fmap);
}
fmap.push(f);
addFilterChildrenToState(filter, state);
const child = fnode.node.child;
if (child) {
if (child.type == NodeType.FUNCTION) {
const fr = addFunction(fnode, child, path, state);
state.functionCalls[state.depth].push(fr);
} else {
createFNodeAndAddToState(child, filteredResult, state);
}
}
} else {
const child = fnode.node.child;
if (child?.type == NodeType.FUNCTION) {
const fr = addFunction(fnode, child, path, state);
state.functionCalls[state.depth].push(fr);
} else if (child && !fnode.node.binding && !fnode.node.resolve) {
createFNodeAndAddToState(child, fnode.result, state);
}
}
}
function addFunction(rootNode: FNode, functionCall: FunctionCall, path: NodePath, state: State): FunctionCallResult {
const functionNode: FunctionCallResult = {
node: rootNode.node,
functionCall: functionCall,
parameters: [],
result: [],
};
for (const param of functionCall.parameters) {
if (param.type == NodeType.LITERAL) {
functionNode.parameters.push({ node: param, result: [param.value] });
} else {
if (param.type == NodeType.FUNCTION) {
functionNode.parameters.push(addFunction(functionNode, param, path, state));
} else {
functionNode.parameters.push(createFNodeAndAddToState(param, [], state));
}
}
}
return functionNode;
}
function addPrimitiveAttributeIfMatch(fnode: FNode, node: ASTNode, depth: number) {
if (!fnode.node.attribute || fnode.node.value == undefined) return;
if (!descendantInDepthRange(fnode, depth)) return;
if (fnode.node.child || fnode.node.filter) return;
if (!Object.hasOwn(node, fnode.node.value)) return;
const nodes = getPrimitiveChildren(fnode.node.value, node);
if (nodes.length == 0) return;
log?.debug("PRIMITIVE", fnode.node.value, nodes);
fnode.result.push(...nodes);
}
function evaluateFilter(filter: FilterNode, path: NodePath): Result[] {
log?.debug("EVALUATING FILTER", filter, breadCrumb(path));
if ("type" in filter) {
if (filter.type == NodeType.AND) {
const left = evaluateFilter(filter.left, path);
if (left.length == 0) {
return [];
}
const r = evaluateFilter(filter.right, path);
return r;
}
if (filter.type == NodeType.OR) {
const left = evaluateFilter(filter.left, path);
if (left.length > 0) {
return left;
}
const r = evaluateFilter(filter.right, path);
return r;
}
if (filter.type == NodeType.EQUALS) {
const left = evaluateFilter(filter.left, path);
const right = evaluateFilter(filter.right, path);
// Optimize: use Set for O(1) lookups instead of O(n) includes
if (right.length > 3) {
const rightSet = new Set(right);
const r: Result[] = [];
for (let i = 0; i < left.length; i++) {
if (rightSet.has(left[i])) r.push(left[i]);
}
return r;
}
// For small arrays, includes is faster than Set creation
const r: Result[] = [];
for (let i = 0; i < left.length; i++) {
if (right.includes(left[i])) r.push(left[i]);
}
return r;
}
throw new Error("Unknown filter type: " + filter.type);
}
if (filter.node.type == NodeType.PARENT) {
const r = resolveFilterWithParent(filter.node, path);
return r;
}
// If result is empty and node is an attribute selector, try resolving directly
// (handles cases like /:value/:raw where value is a plain object, not an AST node)
if (filter.result.length === 0 && filter.node.attribute) {
return resolveDirectly(filter.node, path);
}
return filter.result;
}
function resolveBinding(path: NodePath): NodePath | undefined {
if (!isIdentifier(path.node)) return undefined;
log?.debug("RESOLVING BINDING FOR ", path.node);
const name = path.node.name;
if (name == undefined || typeof name != "string") return undefined;
//const binding = path.scope.getBinding(name);
const binding = getBinding(path.scopeId, name);
if (!binding) return undefined;
log?.debug("THIS IS THE BINDING", binding);
return binding.path;
}
function resolveFilterWithParent(node: QNode, path: NodePath): Result[] {
let startNode: QNode = node;
let startPath = path;
while (startNode.type == NodeType.PARENT) {
if (!startNode.child) throw new Error("Parent filter must have child");
if (!startPath.parentPath) return [];
log?.debug("STEP OUT", startNode, breadCrumb(startPath));
startNode = startNode.child;
startPath = startPath.parentPath;
}
return resolveDirectly(startNode, startPath);
}
let subQueryCounter = 0;
const memo = new Map<QNode, Map<NodePath | PrimitiveValue, Result[]>>();
function resolveDirectly(node: QNode, path: NodePath): Result[] {
let startNode: QNode = node;
const startPath = path;
let paths: Array<PrimitiveValue | NodePath> = [startPath];
while (startNode.attribute && startNode.type == NodeType.CHILD) {
const lookup = startNode.value;
if (!lookup) throw new Error("Selector must have a value");
//log?.debug("STEP IN ", lookup, paths.map(p => breadCrumb(p)));
// Optimize: avoid filter().map().flat() chain - use single loop
const nodes: Array<PrimitiveValue | NodePath> = [];
for (let i = 0; i < paths.length; i++) {
const p = paths[i];
if (!isNodePath(p)) continue;
const arr = getPrimitiveChildrenOrNodePaths(lookup, p);
for (let j = 0; j < arr.length; j++) {
nodes.push(arr[j]);
}
}
if (nodes.length == 0) return [];
paths = nodes;
if (startNode.resolve) {
const resolved: NodePath[] = [];
for (let i = 0; i < paths.length; i++) {
const p = paths[i];
if (!isNodePath(p)) continue;
const binding = resolveBinding(p);
if (!binding) continue;
const children = getChildren("init", binding);
for (let j = 0; j < children.length; j++) {
resolved.push(children[j]);
}
}
if (resolved.length > 0) paths = resolved;
} else if (startNode.binding) {
const bindings: NodePath[] = [];
for (let i = 0; i < paths.length; i++) {
const p = paths[i];
if (!isNodePath(p)) continue;
const binding = resolveBinding(p);
if (binding) bindings.push(binding);
}
paths = bindings;
}
const filter = startNode.filter;
if (filter) {
const filtered: NodePath[] = [];
for (let i = 0; i < paths.length; i++) {
const p = paths[i];
if (!isNodePath(p)) continue;
if (travHandle({ subquery: filter }, p).subquery.length > 0) {
filtered.push(p);
}
}
paths = filtered;
}
if (!startNode.child) {
const results = new Array(paths.length);
for (let i = 0; i < paths.length; i++) {
const p = paths[i];
results[i] = isPrimitive(p) ? p : p.node;
}
return results;
}
startNode = startNode.child;
}
//log?.debug("DIRECT TRAV RESOLVE", startNode, paths.map(p => breadCrumb(p)));
const result = [];
//console.log(paths.length, subQueryCounter);
for (const path of paths) {
if (isNodePath(path)) {
let nodeMemo = memo.get(startNode);
const cached = nodeMemo ? nodeMemo.get(path) : undefined;
if (cached) {
for (let i = 0; i < cached.length; i++) {
result.push(cached[i]);
}
} else {
const subQueryKey = "subquery-" + subQueryCounter++;
const subQueryResult = travHandle({ [subQueryKey]: startNode }, path)[subQueryKey];
if (!nodeMemo) {
nodeMemo = new Map();
memo.set(startNode, nodeMemo);
}
nodeMemo.set(path, subQueryResult);
for (let i = 0; i < subQueryResult.length; i++) {
result.push(subQueryResult[i]);
}
}
}
}
log?.debug("DIRECT TRAV RESOLVE RESULT", result);
return result;
}
function addResultIfTokenMatch(fnode: FNode, path: NodePath, state: State) {
// Lazily allocated: the vast majority of matches carry no filter, and this
// runs once per match.
let matchingFilters: FilterResult[] | undefined;
const fmapContainer = state.filtersMap[state.depth];
const nodeFilters = fmapContainer ? fmapContainer.get(path.node) : undefined;
if (nodeFilters) {
let filterCount = 0;
for (let i = 0; i < nodeFilters.length; i++) {
const f = nodeFilters[i];
if (f.qNode !== fnode.node) continue;
filterCount++;
if (evaluateFilter(f.filter, path).length > 0) {
(matchingFilters ??= []).push(f);
}
}
if (filterCount > 0 && matchingFilters == undefined) return;
}
if (fnode.node.resolve) {
const binding = resolveBinding(path);
const resolved = binding ? getChildren("init", binding)[0] : undefined;
if (fnode.node.child) {
const result = resolveDirectly(fnode.node.child, resolved ?? path);
for (let i = 0; i < result.length; i++) {
fnode.result.push(result[i]);
}
} else {
fnode.result.push(path.node);
}
} else if (fnode.node.binding) {
const binding = resolveBinding(path);
if (binding) {
if (fnode.node.child) {
const result = resolveDirectly(fnode.node.child, binding);
for (let i = 0; i < result.length; i++) {
fnode.result.push(result[i]);
}
} else {
fnode.result.push(binding.node);
}
}
} else if (!fnode.node.child) {
fnode.result.push(path.node);
} else if (fnode.node.child.type == NodeType.FUNCTION) {
const functionCallResult = state.functionCalls[state.depth].find((f) => f.node == fnode.node);
if (!functionCallResult) throw new Error("Did not find expected function call for " + fnode.node.child.function);
resolveFunctionCalls(fnode, functionCallResult, path, state);
} else if (matchingFilters != undefined) {
log?.debug("HAS MATCHING FILTER", fnode.result.length, matchingFilters.length, breadCrumb(path));
for (let i = 0; i < matchingFilters.length; i++) {
const filterResult = matchingFilters[i].result;
for (let j = 0; j < filterResult.length; j++) {
fnode.result.push(filterResult[j]);
}
}
} else if (fnode.node.child.attribute) {
// Handle attribute children that weren't resolved through normal traversal
// (e.g., when accessing nested properties of non-AST objects like TemplateElement.value.raw)
// Skip leaf attributes - they're handled by addPrimitiveAttributeIfMatch
// Only process if there's a child chain (like /:value/:raw)
if (fnode.node.child.child || fnode.node.child.filter) {
const attrName = fnode.node.child.value;
if (attrName) {
const attrValue = (path.node as unknown as Record<string, unknown>)[attrName];
// Check if the attribute value would NOT be traversed normally (i.e., not an AST node)
const isASTNode = (v: unknown): boolean => typeof v === "object" && v !== null && "type" in v;
const wouldBeTraversed =
isASTNode(attrValue) || (Array.isArray(attrValue) && attrValue.length > 0 && isASTNode(attrValue[0]));
if (!wouldBeTraversed) {
const result = resolveDirectly(fnode.node.child, path);
for (let i = 0; i < result.length; i++) {
fnode.result.push(result[i]);
}
}
}
}
}
}
function resolveFunctionCalls(fnode: FNode, functionCallResult: FunctionCallResult, path: NodePath, state: State) {
const parameterResults: Result[][] = [];
for (let i = 0; i < functionCallResult.parameters.length; i++) {
const p = functionCallResult.parameters[i];
if ("parameters" in p) {
resolveFunctionCalls(p, p, path, state);
parameterResults.push(p.result);
} else {
parameterResults.push(p.result);
}
}
const functionResult = functions[functionCallResult.functionCall.function].fn(parameterResults);
log?.debug("PARAMETER RESULTS", functionCallResult.functionCall.function, parameterResults, functionResult);
for (let i = 0; i < functionResult.length; i++) {
fnode.result.push(functionResult[i]);
}
}
function travHandle<T extends Record<string, QNode>>(queries: T, root: NodePath): Record<keyof T, Result[]> {
// Optimize: create results object directly instead of Object.fromEntries + map
const results = {} as Record<keyof T, Result[]>;
const queryKeys = Object.keys(queries);
for (let i = 0; i < queryKeys.length; i++) {
results[queryKeys[i] as keyof T] = [];
}
const state: State = {
depth: 0,
child: [[], []],
descendant: [[], []],
filtersMap: [undefined, undefined],
matches: [[]],
functionCalls: [[]],
descendantByType: new Map(),
descendantOther: [],
descendantAttr: [],
descendantActiveCount: 0,
seqCounter: 0,
};
for (const [name, node] of Object.entries(queries)) {
createFNodeAndAddToState(node, results[name], state);
}
// Optimize: replace forEach with for loop
const childAtDepth = state.child[state.depth + 1];
for (let i = 0; i < childAtDepth.length; i++) {
addPrimitiveAttributeIfMatch(childAtDepth[i], root.node, state.depth);
}
// Only attribute descendant selectors do anything in the primitive pass.
for (let i = 0; i < state.descendantAttr.length; i++) {
addPrimitiveAttributeIfMatch(state.descendantAttr[i], root.node, state.depth);
}
traverse(
root.node,
{
enter(node, key, parentKey, materialize, state) {
state.depth++;
state.child.push([]);
state.descendant.push([]);
state.filtersMap.push(undefined);
state.matches.push([]);
state.functionCalls.push([]);
const depth = state.depth;
// Materialized lazily on the first match at this node; most nodes
// match nothing and never pay for a NodePath.
let path: NodePath | undefined;
const childAtDepth = state.child[depth];
for (let i = 0; i < childAtDepth.length; i++) {
const fnode = childAtDepth[i];
if (isMatch(fnode, node, key, parentKey)) {
addMatch(fnode, path ?? (path = materialize(depth)), state);
}
}
// Descendant selectors active for this node: only those targeting this
// node's type (O(1) lookup) plus the always-checked wildcard/attribute
// selectors. Each bucket is already in activation (seq) order, so when a
// single source applies no sort is needed; only when both contribute do
// we merge by seq to reproduce the old depth-major ordering. Lengths are
// snapshotted so selectors this node activates for its children are not
// matched against the node itself.
const bucket = state.descendantByType.get(node.type);
const other = state.descendantOther;
const bucketLen = bucket ? bucket.length : 0;
const otherLen = other.length;
if (otherLen == 0) {
// Bucket entries are keyed on node type, so the match is guaranteed.
for (let i = 0; i < bucketLen; i++) {
const fnode = bucket![i];
if (descendantInDepthRange(fnode, depth)) {
addMatch(fnode, path ?? (path = materialize(depth)), state);
}
}
} else if (bucketLen == 0) {
for (let i = 0; i < otherLen; i++) {
const fnode = other[i];
if (isMatch(fnode, node, key, parentKey) && descendantInDepthRange(fnode, depth)) {
addMatch(fnode, path ?? (path = materialize(depth)), state);
}
}
} else {
const cands: FNode[] = [];
for (let i = 0; i < bucketLen; i++) cands.push(bucket![i]);
for (let i = 0; i < otherLen; i++) cands.push(other[i]);
cands.sort((a, b) => a.seq! - b.seq!);
for (let i = 0; i < cands.length; i++) {
const fnode = cands[i];
if (isMatch(fnode, node, key, parentKey) && descendantInDepthRange(fnode, depth)) {
addMatch(fnode, path ?? (path = materialize(depth)), state);
}
}
}
},
exit(node, state) {
// Check for attributes as not all attributes are visited
// Optimize: replace forEach with for loop
const childAtDepthPlusOne = state.child[state.depth + 1];
for (let i = 0; i < childAtDepthPlusOne.length; i++) {
addPrimitiveAttributeIfMatch(childAtDepthPlusOne[i], node, state.depth);
}
// Equivalent to scanning every active descendant selector, but only
// attribute selectors do any work here. descendantAttr is in activation
// (depth-major) order, matching the old scan order.
for (let i = 0; i < state.descendantAttr.length; i++) {
addPrimitiveAttributeIfMatch(state.descendantAttr[i], node, state.depth);
}
const matchesAtDepth = state.matches[state.depth];
for (let i = 0; i < matchesAtDepth.length; i++) {
addResultIfTokenMatch(matchesAtDepth[i][0], matchesAtDepth[i][1], state);
}
// Deactivate descendant selectors this node added for its subtree before
// unwinding the per-depth stack, keeping the type index in lockstep.
const leavingDescendants = state.descendant[state.descendant.length - 1];
for (let i = 0; i < leavingDescendants.length; i++) {
deactivateDescendant(leavingDescendants[i], state);
}
state.depth--;
state.child.pop();
state.descendant.pop();
state.filtersMap.pop();
state.matches.pop();
state.functionCalls.pop();
},
},
root.scopeId,
state,
root,
);
return results;
}
function beginHandle<T extends Record<string, QNode>>(queries: T, path: ASTNode): Record<keyof T, Result[]> {
const rootPath: NodePath = createNodePath(path, undefined, undefined, undefined, undefined);
const r = travHandle(queries, rootPath);
memo.clear();
return r;
}
return {
beginHandle,
};
}
const defaultKey = "__default__";
export function query(code: string | ASTNode, query: string, returnAST?: boolean): Result[] & { __AST?: ASTNode } {
const result = multiQuery(code, { [defaultKey]: query }, returnAST);
if (returnAST) {
const r = result[defaultKey] as Result[] & { __AST?: ASTNode };
r.__AST = result.__AST;
return r;
}
return result[defaultKey];
}
export function multiQuery<T extends Record<string, string>>(
code: string | ASTNode,
namedQueries: T,
returnAST?: boolean,
): Record<keyof T, Result[]> & { __AST?: ASTNode } {
const start = Date.now();
const ast = typeof code == "string" ? parseSource(code) : code;
if (ast == null) throw new Error("Could not pase code");
// Optimize: parse queries directly instead of Object.fromEntries + map
const queries = {} as Record<keyof T, QNode>;
const entries = Object.entries(namedQueries);
for (let i = 0; i < entries.length; i++) {
const [name, queryStr] = entries[i];
queries[name as keyof T] = parse(queryStr);
}
const querier = createQuerier();
const result = querier.beginHandle(queries, ast);
log?.debug("Query time: ", Date.now() - start);
if (returnAST) {
return { ...result, __AST: ast };
}
return result;
}
export function parseSource(source: string, optimize: boolean = true): ASTNode {
const parsingOptions = optimize ? { loc: false, ranges: false } : { loc: true, ranges: true };
const base = { next: true, validateRegex: false, ...parsingOptions };
try {
return parseJS(source, { ...base, sourceType: "module" });
} catch {
try {
return parseJS(source, { ...base, sourceType: "script", webcompat: true });
} catch {
try {
return parseJS(source, { ...base, sourceType: "module", jsx: true });
} catch {
return parseJS(source, { ...base, sourceType: "script", webcompat: true, jsx: true });
}
}
}
}
export type Binding = {
path: NodePath;
};
export type Scope = {
bindings: Record<string, Binding>;
parentScopeId?: number;
id: number;
};
export type ASTNode = ESTree.Node & {
// Internal: scope id assigned during binding registration. Stored as a flat
// property (not a nested object) to avoid allocating a wrapper per AST node.
scopeId?: number;
};
export type NodePath = {
node: ASTNode;
key?: string;
parentPath?: NodePath;
parentKey?: string;
scopeId: number;
functionScopeId: number;
};
// The visitor receives raw nodes plus their position keys; a NodePath is only
// created on demand via `materialize(depth)` (memoized per depth by the
// traversal), so nodes that match nothing never allocate one.
type Visitor<T> = {
enter: (
node: ASTNode,
key: string | number | undefined,
parentKey: string | undefined,
materialize: (depth: number) => NodePath,
state: T,
) => void;
exit: (node: ASTNode, state: T) => void;
};
export default function createTraverser() {
let scopeIdCounter = 0;
const scopes = new Map<number, Scope | number>();
let removedScopes = 0;
const nodePathsCreated: Record<string, number> = {};
function createScope(parentScopeId?: number): number {
const id = scopeIdCounter++;
if (parentScopeId != undefined) {
scopes.set(id, parentScopeId ?? -1);
}
return id;
}
function getBinding(scopeId: number, name: string): Binding | undefined {
let currentScope = scopes.get(scopeId);
while (currentScope !== undefined) {
if (typeof currentScope !== "number") {
// Full scope: Check for binding
if (currentScope.bindings[name]) {
return currentScope.bindings[name];
}
// Move to parent scope
if (currentScope.parentScopeId === -1) break; // No parent scope
currentScope = scopes.get(currentScope.parentScopeId!);
} else {
// Lightweight scope: Retrieve parent scope
if (currentScope === -1 || currentScope == undefined) break; // No parent scope
currentScope = scopes.get(currentScope);
}
}
return undefined; // Binding not found
}
function setBinding(scopeId: number, name: string, binding: Binding) {
let scope = scopes.get(scopeId);
if (typeof scope === "number" || scope === undefined) {
// Upgrade the lightweight scope to a full scope
scope = { bindings: {}, id: scopeId, parentScopeId: scope };
scopes.set(scopeId, scope);
}
if (scope && typeof scope !== "number") {
scope.bindings[name] = binding;
}
}
let pathsCreated = 0;
function getChildren(key: string, path: NodePath): NodePath[] {
if (key in path.node) {
const r = (path.node as unknown as Record<string, unknown>)[key];
if (Array.isArray(r)) {
const len = r.length;
const result = new Array(len);
for (let i = 0; i < len; i++) {
result[i] = createNodePath(r[i], i, key, path.scopeId, path.functionScopeId, path);
}
return result;
} else if (r != undefined) {
return [createNodePath(r as ASTNode, key, key, path.scopeId, path.functionScopeId, path)];
}
}
return [];
}
function getPrimitiveChildren(key: string, node: ASTNode): PrimitiveValue[] {
if (key in node) {
const r = (node as unknown as Record<string, unknown>)[key];
const arr = toArray(r);
// Optimize: single loop instead of chained filter()
const result: PrimitiveValue[] = [];
for (let i = 0; i < arr.length; i++) {
const item = arr[i];
if (isDefined(item) && isPrimitive(item)) {
result.push(item);
}
}
return result;
}
if (key === "value") {
const templateValue = staticTemplateLiteralValue(node);
if (templateValue != undefined) return [templateValue];
}
return [];
}
function getPrimitiveChildrenOrNodePaths(key: string, path: NodePath): Array<PrimitiveValue | NodePath> {
if (key in path.node) {
const r = (path.node as unknown as Record<string, unknown>)[key];
if (Array.isArray(r)) {
const len = r.length;
const result = new Array(len);
for (let i = 0; i < len; i++) {
const n = r[i];
result[i] = isPrimitive(n) ? n : createNodePath(n, i, key, path.scopeId, path.functionScopeId, path);
}
return result;
} else if (r != undefined) {
return [isPrimitive(r) ? r : createNodePath(r as ASTNode, key, key, path.scopeId, path.functionScopeId, path)];
}
}
if (key === "value") {
const templateValue = staticTemplateLiteralValue(path.node);
if (templateValue != undefined) return [templateValue];
}
return [];
}
const nodePathMap = new WeakMap<ASTNode, NodePath>();
function createNodePath(
node: ASTNode,
key: string | undefined | number,
parentKey: string | undefined,
scopeId: number | undefined,