Repository navigation
Expand file tree
/
Copy pathjavascriptSemanticProjection.ts
More file actions
874 lines (835 loc) · 28.3 KB
/
Copy pathjavascriptSemanticProjection.ts
File metadata and controls
874 lines (835 loc) · 28.3 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
import * as t from "@babel/types";
import type {
JavaScriptSemanticBinding,
JavaScriptSemanticModuleLink,
JavaScriptSemanticReference,
JavaScriptSemanticScope,
} from "./javascriptSemanticIr.js";
import {
resolveSemanticBindingState,
semanticResolutionBlocked,
type JavaScriptSemanticAnalysisState,
type JavaScriptSemanticScopeState,
} from "./javascriptSemanticState.js";
import { semanticRequireOrigin } from "./javascriptSemanticRequireOrigin.js";
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
import {
completeSemanticSteps,
traverseJavaScriptAstSteps,
} from "./javascriptSemanticTraversal.js";
import {
evaluateSemanticBinding,
evaluateSemanticProvenance,
} from "./javascriptSemanticValues.js";
import { range } from "./javascriptStaticAnalysisHelpers.js";
import {
propertyName,
semanticFinalObjectProperty,
semanticStaticPropertyKey,
semanticWrappedWriteSite,
semanticWriteSiteReadsFirst,
semanticWriteSiteTarget,
unwrapJavaScriptExpression,
} from "./javascriptAstValues.js";
import {
isTypeOnlyExportDeclaration,
isTypeOnlyExportSpecifier,
isTypeOnlyImportDeclaration,
isTypeOnlyImportSpecifier,
semanticImportEqualsSpecifier,
} from "./javascriptModuleDeclaration.js";
import {
commonJsDefinedExport,
commonJsExportName,
type CommonJsExportReceiverEffect,
type CommonJsExportSite,
} from "./javascriptCommonJsExportReceivers.js";
interface CollectCallableInput {
readonly node: t.Node;
readonly parent: t.Node | null;
readonly containerScope: JavaScriptSemanticScopeState;
readonly bodyScope: JavaScriptSemanticScopeState | undefined;
readonly state: JavaScriptSemanticAnalysisState;
}
/** Retain callable identity without polluting lexical bindings. */
export const collectSemanticCallable = (input: CollectCallableInput): void => {
const { node, parent, containerScope, bodyScope, state } = input;
const kind = callableKind(node);
if (kind === undefined) return;
const callableId =
semanticCallableIdForNode(node) ?? "callable:unknown:-1:-1";
state.callables.push({
callableId,
kind,
name: callableName(node, parent),
containerScopeId: containerScope.scopeId,
bodyScopeId:
bodyScope === undefined || !bodyScope.bindingsComplete
? null
: bodyScope.scopeId,
location: range(node),
returnSites: [],
returnCoverage: {
status: "partial",
retainedCount: 0,
omittedCount: null,
},
});
state.callableNodesById.set(callableId, node);
};
/** Collect one static import/export relationship for later composition. */
export const collectSemanticModuleLink = (
node: t.Node,
state: JavaScriptSemanticAnalysisState,
commonJsReceivers: ReadonlyMap<
CommonJsExportSite,
CommonJsExportReceiverEffect
>,
): void => {
if (t.isTSImportEqualsDeclaration(node)) collectImportEquals(node, state);
else if (t.isImportDeclaration(node)) collectImports(node, state);
else if (collectSemanticEsmExport(node, state)) return;
else if (t.isVariableDeclarator(node)) collectRequireLink(node, state);
else if (t.isAssignmentExpression(node))
collectCommonJsExport(node, state, commonJsReceivers.get(node));
else if (t.isCallExpression(node)) {
collectDefinedCommonJsExport(node, state, commonJsReceivers.get(node));
collectUnboundRequireLink(node, state);
}
};
const collectedEsmExports = new WeakMap<
JavaScriptSemanticAnalysisState,
WeakSet<t.Node>
>();
/** static consumers can request export facts without evaluating the complete IR. */
export const collectSemanticEsmExport = (
node: t.Node,
state: JavaScriptSemanticAnalysisState,
): boolean => {
if (
!t.isExportAllDeclaration(node) &&
!t.isExportNamedDeclaration(node) &&
!t.isExportDefaultDeclaration(node)
)
return false;
let collected = collectedEsmExports.get(state);
if (collected === undefined) {
collected = new WeakSet();
collectedEsmExports.set(state, collected);
}
if (collected.has(node)) return true;
collected.add(node);
if (t.isExportAllDeclaration(node))
addModuleLink(
state,
{
kind: isTypeOnlyExportDeclaration(node) ? "type-import" : "re-export",
specifier: node.source.value,
importedName: "*",
localName: null,
exportedName: "*",
location: range(node),
},
node,
);
else if (t.isExportNamedDeclaration(node)) collectNamedExports(node, state);
else if (t.isExportDefaultDeclaration(node))
addModuleLink(
state,
{
kind: "export",
specifier: null,
importedName: null,
localName: defaultExportLocalName(node.declaration),
exportedName: "default",
callableId: semanticCallableIdForNode(node.declaration),
location: range(node),
},
node,
);
return true;
};
const collectImportEquals = (
node: t.TSImportEqualsDeclaration,
state: JavaScriptSemanticAnalysisState,
): void => {
const moduleReference = node.moduleReference;
const specifier =
semanticImportEqualsSpecifier(node) ??
(node.importKind === "type" &&
t.isTSExternalModuleReference(moduleReference) &&
t.isStringLiteral(moduleReference.expression)
? moduleReference.expression.value
: null);
if (specifier === null) return;
addModuleLink(
state,
{
kind: node.importKind === "type" ? "type-import" : "require",
specifier,
importedName: null,
localName: node.id.name,
exportedName: null,
location: range(node),
},
node,
);
};
/** Collect lexical references after definitions exist, optionally for one name. */
export const collectSemanticReferences = (
program: t.Program,
state: JavaScriptSemanticAnalysisState,
name?: string,
): JavaScriptSemanticReference[] =>
completeSemanticSteps(collectSemanticReferencesSteps(program, state, name));
/** Collect lexical references in steps while preserving resolution and visit order. */
export function* collectSemanticReferencesSteps(
program: t.Program,
state: JavaScriptSemanticAnalysisState,
name?: string,
): Generator<void, JavaScriptSemanticReference[]> {
const output: JavaScriptSemanticReference[] = [];
const seen = new Set<string>();
const patterns: t.Node[] = [];
yield* traverseJavaScriptAstSteps(program, {
enter: (node, parent, readAncestors) => {
if (isPatternNode(node)) patterns.push(node);
if (
!t.isIdentifier(node) ||
parent === null ||
(name !== undefined && node.name !== name) ||
(isNonReferenceKey(node, parent) &&
!patterns.some((pattern) => bindsIdentifier(pattern, parent, node)))
)
return;
const ancestors = readAncestors();
const role = semanticIdentifierRole(node, parent, ancestors);
if (role === null) return;
// A compound assignment or update reads before it writes; emit both so
// reference consumers see the read they actually execute.
const roles =
role === "write" &&
semanticReadsBeforeWrite(
node,
semanticWrappedWriteSite(node, parent, ancestors) ?? parent,
)
? (["read", "write"] as const)
: ([role] as const);
for (const resolvedRole of roles) {
const key = `${String(node.start)}:${resolvedRole}:${node.name}`;
if (seen.has(key)) continue;
seen.add(key);
const binding = resolveSemanticBindingState(state, node, node.name);
const blocked =
binding === undefined &&
semanticResolutionBlocked(state, node, node.name);
output.push({
name: node.name,
role: resolvedRole,
location: range(node),
bindingId: binding?.bindingId ?? null,
resolution:
binding !== undefined
? "resolved"
: blocked
? "unknown"
: "unbound",
});
}
},
exit: (node) => {
if (isPatternNode(node)) patterns.pop();
},
});
return output;
}
/** Freeze collected scopes into deterministic IR order. */
export const immutableSemanticScopes = (
state: JavaScriptSemanticAnalysisState,
): JavaScriptSemanticScope[] =>
state.scopes.map((scope) => ({
scopeId: scope.scopeId,
parentScopeId: scope.parentScopeId,
kind: scope.kind,
location: scope.location,
bindingsComplete: scope.bindingsComplete,
bindingIds: [...scope.bindings.values()]
.map(({ bindingId }) => bindingId)
.sort(compareUnicodeCodePoints),
}));
/** Evaluate and freeze bindings into deterministic IR order. */
export const immutableSemanticBindings = (
state: JavaScriptSemanticAnalysisState,
): JavaScriptSemanticBinding[] =>
[...state.bindingsById.values()]
.map((binding) => ({
bindingId: binding.bindingId,
scopeId: binding.scopeId,
name: binding.name,
kind: binding.kind,
mutable: binding.mutable,
definitions: binding.definitions,
value: evaluateSemanticBinding(binding, state),
provenance: evaluateSemanticProvenance(binding, state),
}))
.sort((left, right) =>
compareUnicodeCodePoints(left.bindingId, right.bindingId),
);
const callableKind = (
node: t.Node,
): "function" | "class" | "method" | undefined => {
if (
t.isClassMethod(node) ||
t.isClassPrivateMethod(node) ||
t.isObjectMethod(node)
)
return "method";
if (t.isFunction(node)) return "function";
if (t.isClass(node)) return "class";
return undefined;
};
const callableName = (node: t.Node, parent: t.Node | null): string | null => {
if (
(t.isFunctionDeclaration(node) ||
t.isFunctionExpression(node) ||
t.isClassDeclaration(node) ||
t.isClassExpression(node)) &&
t.isIdentifier(node.id)
)
return node.id.name;
if (
t.isClassMethod(node) ||
t.isClassPrivateMethod(node) ||
t.isObjectMethod(node)
) {
if (t.isPrivateName(node.key)) return `#${node.key.id.name}`;
// `{[key]() {}}` names nothing statically; reading `key` off the key node
// would report the variable name as the method name. `{[""]() {}}` names
// the exact empty key, which is retained rather than replaced.
return (
semanticStaticPropertyKey(node.key, node.computed) ??
`[computed@${String(node.start ?? -1)}]`
);
}
if (
parent !== null &&
t.isVariableDeclarator(parent) &&
t.isIdentifier(parent.id)
)
return parent.id.name;
return null;
};
const collectImports = (
node: t.ImportDeclaration,
state: JavaScriptSemanticAnalysisState,
): void => {
if (node.specifiers.length === 0)
addModuleLink(
state,
{
kind: isTypeOnlyImportDeclaration(node) ? "type-import" : "import",
specifier: node.source.value,
importedName: null,
localName: null,
exportedName: null,
location: range(node),
},
node,
);
for (const specifier of node.specifiers)
addModuleLink(
state,
{
kind:
isTypeOnlyImportDeclaration(node) ||
(t.isImportSpecifier(specifier) &&
isTypeOnlyImportSpecifier(specifier))
? "type-import"
: "import",
specifier: node.source.value,
importedName: t.isImportDefaultSpecifier(specifier)
? "default"
: t.isImportNamespaceSpecifier(specifier)
? "*"
: propertyName(specifier.imported),
localName: specifier.local.name,
exportedName: null,
location: range(specifier),
},
node,
);
};
const collectNamedExports = (
node: t.ExportNamedDeclaration,
state: JavaScriptSemanticAnalysisState,
): void => {
const declarationTypeOnly = isTypeOnlyExportDeclaration(node);
if (node.declaration !== null && node.declaration !== undefined)
for (const localName of declarationNames(node.declaration))
addModuleLink(
state,
{
kind: declarationTypeOnly ? "type-import" : "export",
specifier: null,
importedName: null,
localName,
exportedName: localName,
callableId: declarationCallableId(node.declaration, localName),
location: range(node.declaration),
},
node,
);
for (const specifier of node.specifiers)
if (
t.isExportSpecifier(specifier) ||
(t.isExportNamespaceSpecifier(specifier) && node.exportKind !== "type")
)
addModuleLink(
state,
{
kind:
declarationTypeOnly ||
(t.isExportSpecifier(specifier) &&
isTypeOnlyExportSpecifier(specifier))
? "type-import"
: node.source == null
? "export"
: "re-export",
specifier: node.source?.value ?? null,
importedName: t.isExportNamespaceSpecifier(specifier)
? "*"
: propertyName(specifier.local),
localName:
node.source == null && t.isExportSpecifier(specifier)
? propertyName(specifier.local)
: null,
exportedName: propertyName(specifier.exported),
location: range(specifier),
},
node,
);
};
const collectRequireLink = (
node: t.VariableDeclarator,
state: JavaScriptSemanticAnalysisState,
): void => {
const required = semanticRequireOrigin(node.init, state);
if (required === undefined) return;
const { origin, call } = required;
const bindings = requirePatternBindings(node.id, origin.importedPath);
for (const binding of bindings)
addModuleLink(
state,
{
kind: "require",
specifier: origin.specifier,
importedName: binding.importedName,
localName: binding.localName,
exportedName: null,
location: range(node),
},
node,
);
if (bindings.length > 0) state.linkedRequireCalls.add(call);
};
const collectUnboundRequireLink = (
node: t.CallExpression,
state: JavaScriptSemanticAnalysisState,
): void => {
if (state.linkedRequireCalls.has(node)) return;
const required = semanticRequireOrigin(node, state);
if (required === undefined) return;
addModuleLink(
state,
{
kind: "require",
specifier: required.origin.specifier,
importedName: null,
localName: null,
exportedName: null,
location: range(node),
},
node,
);
state.linkedRequireCalls.add(node);
};
const requirePatternBindings = (
pattern: t.Node,
path: readonly string[],
): { readonly importedName: string; readonly localName: string }[] => {
if (t.isTSParameterProperty(pattern))
return requirePatternBindings(pattern.parameter, path);
if (t.isIdentifier(pattern))
return [{ importedName: path.at(-1) ?? "*", localName: pattern.name }];
if (t.isAssignmentPattern(pattern))
return requirePatternBindings(pattern.left, path);
if (t.isObjectPattern(pattern))
return pattern.properties.flatMap((property) => {
if (t.isRestElement(property)) return [];
const name = semanticStaticPropertyKey(property.key, property.computed);
return name === null
? []
: requirePatternBindings(property.value, [...path, name]);
});
if (t.isArrayPattern(pattern))
return pattern.elements.flatMap((element, index) =>
element === null
? []
: requirePatternBindings(element, [...path, String(index)]),
);
return [];
};
const collectCommonJsExport = (
node: t.AssignmentExpression,
state: JavaScriptSemanticAnalysisState,
receiverEffect: CommonJsExportReceiverEffect | undefined,
): void => {
const exportedName = commonJsExportName(node.left, state);
if (exportedName === undefined) return;
if (receiverEffect === "detached") return;
// Compound and logical writes also depend on the previous value, so remain
// unknown.
const value =
node.operator === "=" && receiverEffect !== "uncertain" ? node.right : null;
addCommonJsExport(node, state, exportedName, value);
};
const collectDefinedCommonJsExport = (
node: t.CallExpression,
state: JavaScriptSemanticAnalysisState,
receiverEffect: CommonJsExportReceiverEffect | undefined,
): void => {
const defined = commonJsDefinedExport(node, state);
if (defined === undefined || receiverEffect === "detached") return;
// A data descriptor exports its value; an accessor's result stays unknown.
const descriptor = unwrapJavaScriptExpression(defined.descriptor).node;
const value =
receiverEffect !== "uncertain" && t.isObjectExpression(descriptor)
? (semanticFinalObjectProperty(descriptor, "value") ?? null)
: null;
addCommonJsExport(node, state, defined.exportedName, value);
};
const addCommonJsExport = (
node: CommonJsExportSite,
state: JavaScriptSemanticAnalysisState,
exportedName: string,
exported: t.Node | null,
): void => {
// Simple assignment chains yield their rightmost assigned value.
let value = exported;
while (t.isAssignmentExpression(value, { operator: "=" }))
value = value.right;
const required =
value === null ? undefined : semanticRequireOrigin(value, state);
const origin = required?.origin;
addModuleLink(
state,
{
kind: "commonjs-export",
specifier: origin?.specifier ?? null,
importedName: origin?.importedPath.at(-1) ?? null,
localName: value !== null && t.isIdentifier(value) ? value.name : null,
exportedName,
callableId: value === null ? null : semanticCallableIdForNode(value),
location: range(node),
},
node,
);
if (required !== undefined) state.linkedRequireCalls.add(required.call);
};
const addModuleLink = (
state: JavaScriptSemanticAnalysisState,
link: Omit<JavaScriptSemanticModuleLink, "callableId"> & {
readonly callableId?: string | null;
},
referenceNode: t.Node,
): void => {
const resolutionMode =
link.resolutionMode ??
(link.kind === "import" ||
link.kind === "re-export" ||
link.kind === "type-import"
? state.staticImportResolutionMode
: link.kind === "require"
? "require"
: undefined);
const collected = {
...link,
...(resolutionMode === undefined ? {} : { resolutionMode }),
callableId: link.callableId ?? null,
};
state.moduleLinks.push(collected);
if (
t.isExportDefaultDeclaration(referenceNode) &&
t.isExpression(referenceNode.declaration)
)
state.defaultExportExpressions.set(collected, referenceNode.declaration);
if (link.localName !== null) {
const binding = resolveSemanticBindingState(
state,
referenceNode,
link.localName,
);
if (binding !== undefined) state.moduleLinkBindings.set(collected, binding);
}
};
/** Deterministic callable identity shared by collection and return recovery. */
export const semanticCallableIdForNode = (node: t.Node): string | null => {
const kind = callableKind(node);
return kind === undefined
? null
: `callable:${kind}:${String(node.start ?? -1)}:${String(node.end ?? -1)}`;
};
const declarationCallableId = (
declaration: t.Declaration,
localName: string,
): string | null => {
if (
(t.isFunctionDeclaration(declaration) ||
t.isClassDeclaration(declaration)) &&
declaration.id?.name === localName
)
return semanticCallableIdForNode(declaration);
if (!t.isVariableDeclaration(declaration)) return null;
const declarator = declaration.declarations.find(({ id }) =>
t.isIdentifier(id, { name: localName }),
);
return declarator?.init === null || declarator?.init === undefined
? null
: semanticCallableIdForNode(declarator.init);
};
/**
* True when writing `node` also reads it first: a compound assignment
* (`+=`, `||=`, …) or an update (`++`/`--`). A plain `=` writes only.
*
* One predicate serves both member operations and identifier references so the
* two can never disagree about what counts as a read-modify-write.
*/
export const semanticReadsBeforeWrite = (
node: t.Node,
site: t.Node,
): boolean => {
const target = semanticWriteSiteTarget(site);
return (
target !== null &&
unwrapJavaScriptExpression(target).node === node &&
semanticWriteSiteReadsFirst(site)
);
};
/**
* Role of one identifier occurrence, given the node's ancestry.
*
* A binding inside a destructuring pattern has an ObjectProperty/ArrayPattern
* as its direct parent, so the immediate parent cannot tell a declaration
* (`const {a} = o`, `catch ({message})`) from an assignment target
* (`({a} = o)`, `for (a of list)`). Walking the ancestry to the nearest
* pattern-owning construct is what makes the distinction possible.
*/
export const semanticIdentifierRole = (
node: t.Identifier,
parent: t.Node,
ancestors: readonly t.Node[],
): JavaScriptSemanticReference["role"] | null => {
const patternAncestor = enclosingPatternAncestor(node, parent, ancestors);
if (patternAncestor !== null) {
if (isPatternOwnerDeclaration(patternAncestor)) return null;
return "write";
}
const site = semanticWrappedWriteSite(node, parent, ancestors);
if (site !== null && site !== parent && !isDeleteSite(site)) return "write";
return semanticReferenceRole(node, parent);
};
/**
* The nearest ancestor that owns this identifier as a *bound* pattern slot, or
* null when the identifier is not being bound. A binding inside a pattern has
* an ObjectProperty/ArrayPattern parent, so the immediate parent cannot say
* whether the identifier declares a binding or is assigned to.
*
* Only the bound side counts: `{a = compute()}` binds `a` but merely *reads*
* `compute`, so the default-value side must not be mistaken for a binding.
*/
const enclosingPatternAncestor = (
node: t.Identifier,
parent: t.Node,
ancestors: readonly t.Node[],
): t.Node | null => {
const chain = [...ancestors, parent];
for (let index = chain.length - 1; index >= 0; index -= 1) {
const ancestor = chain[index];
if (ancestor === undefined || !isPatternNode(ancestor)) continue;
if (!bindsIdentifier(ancestor, parent, node)) continue;
// Found the binding slot; now find what owns the pattern.
for (let owner = index - 1; owner >= 0; owner -= 1) {
const candidate = chain[owner];
if (candidate === undefined) continue;
if (
t.isAssignmentExpression(candidate) ||
t.isForInStatement(candidate) ||
t.isForOfStatement(candidate)
)
return candidate;
if (isPatternOwnerDeclaration(candidate)) return candidate;
}
return null;
}
return null;
};
/** True when `parent` places `node` in the bound slot of `pattern`. */
const bindsIdentifier = (
pattern: t.Node,
parent: t.Node,
node: t.Identifier,
): boolean => {
// The identifier sits directly in the pattern: `[b]`, `({b})`, `{b = 1}`.
if (parent === pattern) return patternContains(pattern, node);
if (t.isObjectPattern(pattern))
return (
t.isObjectProperty(parent) &&
(parent.value === node || (parent.shorthand && parent.key === node))
);
if (t.isArrayPattern(pattern))
return pattern.elements.some((element) => element === parent);
if (t.isAssignmentPattern(pattern)) return pattern.left === parent;
return t.isRestElement(pattern) && pattern.argument === parent;
};
const isPatternNode = (node: t.Node): boolean =>
t.isObjectPattern(node) ||
t.isArrayPattern(node) ||
t.isAssignmentPattern(node) ||
t.isRestElement(node);
const isDeleteSite = (site: t.Node): boolean =>
t.isUnaryExpression(site, { operator: "delete" });
const isPatternOwnerDeclaration = (node: t.Node): boolean =>
t.isTSParameterProperty(node) ||
(t.isVariableDeclarator(node) && t.isPattern(node.id)) ||
(t.isFunction(node) &&
node.params.some((value): value is t.Pattern => t.isPattern(value))) ||
(t.isCatchClause(node) && node.param !== null && t.isPattern(node.param));
/** Classify one identifier occurrence consistently with semantic references. */
export const semanticReferenceRole = (
node: t.Identifier,
parent: t.Node,
): JavaScriptSemanticReference["role"] | null => {
if (isDeclarationIdentifier(node, parent) || isNonReferenceKey(node, parent))
return null;
if (
(t.isAssignmentExpression(parent) && parent.left === node) ||
t.isUpdateExpression(parent) ||
((t.isForInStatement(parent) || t.isForOfStatement(parent)) &&
parent.left === node)
)
return "write";
if (t.isExportSpecifier(parent) && parent.local === node) return "export";
return "read";
};
const isDeclarationIdentifier = (
node: t.Identifier,
parent: t.Node,
): boolean => {
if (t.isTSImportEqualsDeclaration(parent)) return parent.id === node;
return (
(t.isTSParameterProperty(parent) &&
patternContains(parent.parameter, node)) ||
(t.isVariableDeclarator(parent) && patternContains(parent.id, node)) ||
((t.isFunctionDeclaration(parent) || t.isFunctionExpression(parent)) &&
parent.id === node) ||
(t.isFunction(parent) &&
parent.params.some((value) => patternContains(value, node))) ||
((t.isClassDeclaration(parent) || t.isClassExpression(parent)) &&
parent.id === node) ||
(t.isImportSpecifier(parent) &&
(parent.local === node || parent.imported === node)) ||
(t.isImportDefaultSpecifier(parent) && parent.local === node) ||
(t.isImportNamespaceSpecifier(parent) && parent.local === node) ||
(t.isCatchClause(parent) && parent.param === node)
);
};
const isNonReferenceKey = (node: t.Identifier, parent: t.Node): boolean =>
((t.isMemberExpression(parent) || t.isOptionalMemberExpression(parent)) &&
parent.property === node &&
!parent.computed) ||
((t.isObjectProperty(parent) || t.isObjectMethod(parent)) &&
parent.key === node &&
!parent.computed &&
!(t.isObjectProperty(parent) && parent.shorthand)) ||
isNoncomputedClassMemberKey(node, parent) ||
t.isPrivateName(parent) ||
(t.isExportSpecifier(parent) && parent.exported === node) ||
t.isLabeledStatement(parent) ||
t.isBreakStatement(parent) ||
t.isContinueStatement(parent);
/** A noncomputed class member name is a property key, never a lexical read. */
const isNoncomputedClassMemberKey = (
node: t.Identifier,
parent: t.Node,
): boolean =>
(t.isClassMethod(parent) ||
t.isClassProperty(parent) ||
t.isTSDeclareMethod(parent)) &&
parent.key === node &&
!parent.computed;
const patternNames = (pattern: t.Node): string[] => {
if (t.isTSParameterProperty(pattern)) return patternNames(pattern.parameter);
if (t.isIdentifier(pattern)) return [pattern.name];
if (t.isAssignmentPattern(pattern)) return patternNames(pattern.left);
if (t.isRestElement(pattern)) return patternNames(pattern.argument);
if (t.isObjectPattern(pattern))
return pattern.properties.flatMap((property) =>
t.isRestElement(property)
? patternNames(property.argument)
: patternNames(property.value),
);
if (t.isArrayPattern(pattern))
return pattern.elements.flatMap((element) =>
element === null ? [] : patternNames(element),
);
return [];
};
const patternContains = (pattern: t.Node, target: t.Identifier): boolean =>
pattern === target ||
(t.isTSParameterProperty(pattern) &&
patternContains(pattern.parameter, target)) ||
(t.isAssignmentPattern(pattern) && patternContains(pattern.left, target)) ||
(t.isRestElement(pattern) && patternContains(pattern.argument, target)) ||
(t.isObjectPattern(pattern) &&
pattern.properties.some((property) =>
t.isRestElement(property)
? patternContains(property.argument, target)
: patternContains(property.value, target),
)) ||
(t.isArrayPattern(pattern) &&
pattern.elements.some(
(element) => element !== null && patternContains(element, target),
));
const declarationNames = (declaration: t.Declaration): string[] => {
if (t.isVariableDeclaration(declaration))
return declaration.declarations.flatMap(({ id }) => patternNames(id));
if (
(t.isFunctionDeclaration(declaration) ||
t.isClassDeclaration(declaration)) &&
t.isIdentifier(declaration.id)
)
return [declaration.id.name];
if (
(t.isTSInterfaceDeclaration(declaration) ||
t.isTSTypeAliasDeclaration(declaration) ||
t.isTSDeclareFunction(declaration)) &&
t.isIdentifier(declaration.id)
)
return [declaration.id.name];
if (
t.isTSImportEqualsDeclaration(declaration) &&
semanticImportEqualsSpecifier(declaration) !== null
)
return [declaration.id.name];
return [];
};
const defaultExportLocalName = (
declaration: t.ExportDefaultDeclaration["declaration"],
): string | null => {
const value = unwrapJavaScriptExpression(declaration).node;
if (t.isIdentifier(value)) return value.name;
return (t.isFunctionDeclaration(value) || t.isClassDeclaration(value)) &&
t.isIdentifier(value.id)
? value.id.name
: null;
};