forked from firefox-devtools/debugger
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisitor.js
More file actions
1031 lines (948 loc) · 29.8 KB
/
Copy pathvisitor.js
File metadata and controls
1031 lines (948 loc) · 29.8 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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */
// @flow
import isEmpty from "lodash/isEmpty";
import type { SourceId, SourceLocation } from "../../../types";
import * as t from "@babel/types";
import type {
Node,
TraversalAncestors,
Location as BabelLocation
} from "@babel/types";
import getFunctionName from "../utils/getFunctionName";
import { getAst } from "../utils/ast";
/**
* "implicit"
* Variables added automaticly like "this" and "arguments"
*
* "var"
* Variables declared with "var" or non-block function declarations
*
* "let"
* Variables declared with "let".
*
* "const"
* Variables declared with "const", or added as const
* bindings like inner function expressions and inner class names.
*
* "import"
* Imported binding names exposed from other modules.
*
* "global"
* Variables that reference undeclared global values.
*/
export type BindingType =
| "implicit"
| "var"
| "const"
| "let"
| "import"
| "global";
export type BindingLocationType = "ref" | BindingDeclarationType;
export type BindingDeclarationType =
| "fn-expr"
| "fn-decl"
| "fn-param"
| "class-decl"
| "class-inner"
| "import-decl"
| "import-ns-decl"
| "ts-enum-decl"
| "ts-namespace-decl"
| "var"
| "let"
| "const"
| "catch";
export type BindingLocation = BindingDeclarationLocation | BindingRefLocation;
export type BindingRefLocation = {
type: "ref",
start: SourceLocation,
end: SourceLocation,
meta?: BindingMetaValue | null
};
export type BindingDeclarationLocation = {
type: BindingDeclarationType,
start: SourceLocation,
end: SourceLocation,
// The overall location of the declaration that this binding is part of.
declaration: {
start: SourceLocation,
end: SourceLocation
},
// If this declaration was an import, include the name of the imported
// binding that this binding references.
importName?: string
};
export type BindingData = {
type: BindingType,
refs: Array<BindingLocation>
};
// Location information about the expression immediartely surrounding a
// given binding reference.
export type BindingMetaValue =
| {
type: "inherit",
start: SourceLocation,
end: SourceLocation,
parent: BindingMetaValue | null
}
| {
type: "call",
start: SourceLocation,
end: SourceLocation,
parent: BindingMetaValue | null
}
| {
type: "member",
start: SourceLocation,
end: SourceLocation,
property: string,
parent: BindingMetaValue | null
};
export type ScopeBindingList = {
[name: string]: BindingData
};
export type SourceScope = {
type: "object" | "function" | "block",
displayName: string,
start: SourceLocation,
end: SourceLocation,
bindings: ScopeBindingList
};
export type ParsedScope = SourceScope & {
children: ?(ParsedScope[])
};
export type ParseJSScopeVisitor = {
traverseVisitor: any,
toParsedScopes: () => ParsedScope[]
};
type TempScope = {
type: "object" | "function" | "function-body" | "block" | "module",
displayName: string,
parent: TempScope | null,
children: Array<TempScope>,
loc: BabelLocation,
bindings: ScopeBindingList
};
type ScopeCollectionVisitorState = {
sourceId: SourceId,
inType: Node | null,
freeVariables: Map<string, Array<BindingLocation>>,
freeVariableStack: Array<Map<string, Array<BindingLocation>>>,
scope: TempScope,
scopeStack: Array<TempScope>,
declarationBindingIds: Set<Node>
};
function isGeneratedId(id: string) {
return !/\/originalSource/.test(id);
}
export function parseSourceScopes(sourceId: SourceId): ?Array<ParsedScope> {
const ast = getAst(sourceId);
if (isEmpty(ast)) {
return null;
}
return buildScopeList(ast, sourceId);
}
export function buildScopeList(ast: Node, sourceId: SourceId) {
const { global, lexical } = createGlobalScope(ast, sourceId);
const state = {
sourceId,
freeVariables: new Map(),
freeVariableStack: [],
inType: null,
scope: lexical,
scopeStack: [],
declarationBindingIds: new Set()
};
t.traverse(ast, scopeCollectionVisitor, state);
for (const [key, freeVariables] of state.freeVariables) {
let binding = global.bindings[key];
if (!binding) {
binding = {
type: "global",
refs: []
};
global.bindings[key] = binding;
}
binding.refs = freeVariables.concat(binding.refs);
}
// TODO: This should probably check for ".mjs" extension on the
// original file, and should also be skipped if the the generated
// code is an ES6 module rather than a script.
if (
isGeneratedId(sourceId) ||
((ast: any).program.sourceType === "script" && !looksLikeCommonJS(global))
) {
stripModuleScope(global);
}
return toParsedScopes([global], sourceId) || [];
}
function toParsedScopes(
children: TempScope[],
sourceId: SourceId
): ?(ParsedScope[]) {
if (!children || children.length === 0) {
return undefined;
}
return children.map(scope => {
// Removing unneed information from TempScope such as parent reference.
// We also need to convert BabelLocation to the Location type.
return {
start: scope.loc.start,
end: scope.loc.end,
type:
scope.type === "module" || scope.type === "function-body"
? "block"
: scope.type,
displayName: scope.displayName,
bindings: scope.bindings,
children: toParsedScopes(scope.children, sourceId)
};
});
}
function createTempScope(
type: "object" | "function" | "function-body" | "block" | "module",
displayName: string,
parent: TempScope | null,
loc: {
start: SourceLocation,
end: SourceLocation
}
): TempScope {
const result = {
type,
displayName,
parent,
children: [],
loc,
bindings: (Object.create(null): any)
};
if (parent) {
parent.children.push(result);
}
return result;
}
function pushTempScope(
state: ScopeCollectionVisitorState,
type: "object" | "function" | "function-body" | "block" | "module",
displayName: string,
loc: {
start: SourceLocation,
end: SourceLocation
}
): TempScope {
const scope = createTempScope(type, displayName, state.scope, loc);
state.scope = scope;
state.freeVariableStack.push(state.freeVariables);
state.freeVariables = new Map();
return scope;
}
function isNode(node?: Node, type: string): boolean {
return node ? node.type === type : false;
}
function getVarScope(scope: TempScope): TempScope {
let s = scope;
while (s.type !== "function" && s.type !== "module") {
if (!s.parent) {
return s;
}
s = s.parent;
}
return s;
}
function fromBabelLocation(
location: BabelLocation,
sourceId: SourceId
): SourceLocation {
return {
sourceId,
line: location.line,
column: location.column
};
}
function parseDeclarator(
declaratorId: Node,
targetScope: TempScope,
type: BindingType,
locationType: BindingDeclarationType,
declaration: Node,
state: ScopeCollectionVisitorState
) {
if (isNode(declaratorId, "Identifier")) {
let existing = targetScope.bindings[declaratorId.name];
if (!existing) {
existing = {
type,
refs: []
};
targetScope.bindings[declaratorId.name] = existing;
}
state.declarationBindingIds.add(declaratorId);
existing.refs.push({
type: locationType,
start: fromBabelLocation(declaratorId.loc.start, state.sourceId),
end: fromBabelLocation(declaratorId.loc.end, state.sourceId),
declaration: {
start: fromBabelLocation(declaration.loc.start, state.sourceId),
end: fromBabelLocation(declaration.loc.end, state.sourceId)
}
});
} else if (isNode(declaratorId, "ObjectPattern")) {
declaratorId.properties.forEach(prop => {
parseDeclarator(
prop.value,
targetScope,
type,
locationType,
declaration,
state
);
});
} else if (isNode(declaratorId, "ArrayPattern")) {
declaratorId.elements.forEach(item => {
parseDeclarator(
item,
targetScope,
type,
locationType,
declaration,
state
);
});
} else if (isNode(declaratorId, "AssignmentPattern")) {
parseDeclarator(
declaratorId.left,
targetScope,
type,
locationType,
declaration,
state
);
} else if (isNode(declaratorId, "RestElement")) {
parseDeclarator(
declaratorId.argument,
targetScope,
type,
locationType,
declaration,
state
);
} else if (t.isTSParameterProperty(declaratorId)) {
parseDeclarator(
declaratorId.parameter,
targetScope,
type,
locationType,
declaration,
state
);
}
}
function isLetOrConst(node) {
return node.kind === "let" || node.kind === "const";
}
function hasLexicalDeclaration(node, parent) {
const nodes = [];
if (t.isSwitchStatement(node)) {
for (const caseNode of node.cases) {
nodes.push(...caseNode.consequent);
}
} else {
nodes.push(...node.body);
}
const isFunctionBody = t.isFunction(parent, { body: node });
return nodes.some(
child =>
isLexicalVariable(child) ||
t.isClassDeclaration(child) ||
(!isFunctionBody && t.isFunctionDeclaration(child))
);
}
function isLexicalVariable(node) {
return isNode(node, "VariableDeclaration") && isLetOrConst(node);
}
function createGlobalScope(
ast: Node,
sourceId: SourceId
): { global: TempScope, lexical: TempScope } {
const global = createTempScope("object", "Global", null, {
start: fromBabelLocation(ast.loc.start, sourceId),
end: fromBabelLocation(ast.loc.end, sourceId)
});
const lexical = createTempScope("block", "Lexical Global", global, {
start: fromBabelLocation(ast.loc.start, sourceId),
end: fromBabelLocation(ast.loc.end, sourceId)
});
return {
global,
lexical
};
}
const scopeCollectionVisitor = {
// eslint-disable-next-line complexity
enter(
node: Node,
ancestors: TraversalAncestors,
state: ScopeCollectionVisitorState
) {
state.scopeStack.push(state.scope);
const parentNode =
ancestors.length === 0 ? null : ancestors[ancestors.length - 1].node;
if (state.inType) {
return;
}
if (t.isProgram(node)) {
const scope = pushTempScope(state, "module", "Module", {
start: fromBabelLocation(node.loc.start, state.sourceId),
end: fromBabelLocation(node.loc.end, state.sourceId)
});
scope.bindings.this = {
type: "implicit",
refs: []
};
} else if (t.isFunction(node)) {
let scope = state.scope;
if (t.isFunctionExpression(node) && isNode(node.id, "Identifier")) {
scope = pushTempScope(state, "block", "Function Expression", {
start: fromBabelLocation(node.loc.start, state.sourceId),
end: fromBabelLocation(node.loc.end, state.sourceId)
});
state.declarationBindingIds.add(node.id);
scope.bindings[node.id.name] = {
type: "const",
refs: [
{
type: "fn-expr",
start: fromBabelLocation(node.id.loc.start, state.sourceId),
end: fromBabelLocation(node.id.loc.end, state.sourceId),
declaration: {
start: fromBabelLocation(node.loc.start, state.sourceId),
end: fromBabelLocation(node.loc.end, state.sourceId)
}
}
]
};
}
if (t.isFunctionDeclaration(node) && isNode(node.id, "Identifier")) {
// This ignores Annex B function declaration hoisting, which
// is probably a fine assumption.
state.declarationBindingIds.add(node.id);
const refs = [
{
type: "fn-decl",
start: fromBabelLocation(node.id.loc.start, state.sourceId),
end: fromBabelLocation(node.id.loc.end, state.sourceId),
declaration: {
start: fromBabelLocation(node.loc.start, state.sourceId),
end: fromBabelLocation(node.loc.end, state.sourceId)
}
}
];
if (scope.type === "block") {
scope.bindings[node.id.name] = {
type: "let",
refs
};
} else {
getVarScope(scope).bindings[node.id.name] = {
type: "var",
refs
};
}
}
scope = pushTempScope(
state,
"function",
getFunctionName(node, parentNode),
{
// Being at the start of a function doesn't count as
// being inside of it.
start: fromBabelLocation(
node.params[0] ? node.params[0].loc.start : node.loc.start,
state.sourceId
),
end: fromBabelLocation(node.loc.end, state.sourceId)
}
);
node.params.forEach(param =>
parseDeclarator(param, scope, "var", "fn-param", node, state)
);
if (!t.isArrowFunctionExpression(node)) {
scope.bindings.this = {
type: "implicit",
refs: []
};
scope.bindings.arguments = {
type: "implicit",
refs: []
};
}
if (
t.isBlockStatement(node.body) &&
hasLexicalDeclaration(node.body, node)
) {
scope = pushTempScope(state, "function-body", "Function Body", {
start: fromBabelLocation(node.body.loc.start, state.sourceId),
end: fromBabelLocation(node.body.loc.end, state.sourceId)
});
}
} else if (t.isClass(node)) {
if (t.isIdentifier(node.id)) {
// For decorated classes, the AST considers the first the decorator
// to be the start of the class. For the purposes of mapping class
// declarations however, we really want to look for the "class Foo"
// piece. To achieve that, we estimate the location of the declaration
// instead.
let declStart = node.loc.start;
if (node.decorators && node.decorators.length > 0) {
// Estimate the location of the "class" keyword since it
// is unlikely to be a different line than the class name.
declStart = {
line: node.id.loc.start.line,
column: node.id.loc.start.column - "class ".length
};
}
const declaration = {
start: fromBabelLocation(declStart, state.sourceId),
end: fromBabelLocation(node.loc.end, state.sourceId)
};
if (t.isClassDeclaration(node)) {
state.declarationBindingIds.add(node.id);
state.scope.bindings[node.id.name] = {
type: "let",
refs: [
{
type: "class-decl",
start: fromBabelLocation(node.id.loc.start, state.sourceId),
end: fromBabelLocation(node.id.loc.end, state.sourceId),
declaration
}
]
};
}
const scope = pushTempScope(state, "block", "Class", {
start: fromBabelLocation(node.loc.start, state.sourceId),
end: fromBabelLocation(node.loc.end, state.sourceId)
});
state.declarationBindingIds.add(node.id);
scope.bindings[node.id.name] = {
type: "const",
refs: [
{
type: "class-inner",
start: fromBabelLocation(node.id.loc.start, state.sourceId),
end: fromBabelLocation(node.id.loc.end, state.sourceId),
declaration
}
]
};
}
} else if (t.isForXStatement(node) || t.isForStatement(node)) {
const init = node.init || node.left;
if (isNode(init, "VariableDeclaration") && isLetOrConst(init)) {
// Debugger will create new lexical environment for the for.
pushTempScope(state, "block", "For", {
// Being at the start of a for loop doesn't count as
// being inside it.
start: fromBabelLocation(init.loc.start, state.sourceId),
end: fromBabelLocation(node.loc.end, state.sourceId)
});
}
} else if (t.isCatchClause(node)) {
const scope = pushTempScope(state, "block", "Catch", {
start: fromBabelLocation(node.loc.start, state.sourceId),
end: fromBabelLocation(node.loc.end, state.sourceId)
});
parseDeclarator(node.param, scope, "var", "catch", node, state);
} else if (
t.isBlockStatement(node) &&
// Function body's are handled in the function logic above.
!t.isFunction(parentNode) &&
hasLexicalDeclaration(node, parentNode)
) {
// Debugger will create new lexical environment for the block.
pushTempScope(state, "block", "Block", {
start: fromBabelLocation(node.loc.start, state.sourceId),
end: fromBabelLocation(node.loc.end, state.sourceId)
});
} else if (
t.isVariableDeclaration(node) &&
(node.kind === "var" ||
// Lexical declarations in for statements are handled above.
!t.isForStatement(parentNode, { init: node }) ||
!t.isForXStatement(parentNode, { left: node }))
) {
// Finds right lexical environment
const hoistAt = !isLetOrConst(node)
? getVarScope(state.scope)
: state.scope;
node.declarations.forEach(declarator => {
parseDeclarator(
declarator.id,
hoistAt,
node.kind,
node.kind,
node,
state
);
});
} else if (
t.isImportDeclaration(node) &&
(!node.importKind || node.importKind === "value")
) {
node.specifiers.forEach(spec => {
if (spec.importKind && spec.importKind !== "value") {
return;
}
if (t.isImportNamespaceSpecifier(spec)) {
state.declarationBindingIds.add(spec.local);
state.scope.bindings[spec.local.name] = {
// Imported namespaces aren't live import bindings, they are
// just normal const bindings.
type: "const",
refs: [
{
type: "import-ns-decl",
start: fromBabelLocation(spec.local.loc.start, state.sourceId),
end: fromBabelLocation(spec.local.loc.end, state.sourceId),
declaration: {
start: fromBabelLocation(node.loc.start, state.sourceId),
end: fromBabelLocation(node.loc.end, state.sourceId)
}
}
]
};
} else {
state.declarationBindingIds.add(spec.local);
state.scope.bindings[spec.local.name] = {
type: "import",
refs: [
{
type: "import-decl",
start: fromBabelLocation(spec.local.loc.start, state.sourceId),
end: fromBabelLocation(spec.local.loc.end, state.sourceId),
importName: t.isImportDefaultSpecifier(spec)
? "default"
: spec.imported.name,
declaration: {
start: fromBabelLocation(node.loc.start, state.sourceId),
end: fromBabelLocation(node.loc.end, state.sourceId)
}
}
]
};
}
});
} else if (t.isTSEnumDeclaration(node)) {
state.declarationBindingIds.add(node.id);
state.scope.bindings[node.id.name] = {
type: "const",
refs: [
{
type: "ts-enum-decl",
start: fromBabelLocation(node.id.loc.start, state.sourceId),
end: fromBabelLocation(node.id.loc.end, state.sourceId),
declaration: {
start: fromBabelLocation(node.loc.start, state.sourceId),
end: fromBabelLocation(node.loc.end, state.sourceId)
}
}
]
};
} else if (t.isTSModuleDeclaration(node)) {
state.declarationBindingIds.add(node.id);
state.scope.bindings[node.id.name] = {
type: "const",
refs: [
{
type: "ts-namespace-decl",
start: fromBabelLocation(node.id.loc.start, state.sourceId),
end: fromBabelLocation(node.id.loc.end, state.sourceId),
declaration: {
start: fromBabelLocation(node.loc.start, state.sourceId),
end: fromBabelLocation(node.loc.end, state.sourceId)
}
}
]
};
} else if (t.isTSModuleBlock(node)) {
pushTempScope(state, "block", "TypeScript Namespace", {
start: fromBabelLocation(node.loc.start, state.sourceId),
end: fromBabelLocation(node.loc.end, state.sourceId)
});
} else if (
t.isIdentifier(node) &&
t.isReferenced(node, parentNode) &&
// Babel doesn't cover this in 'isReferenced' yet, but it should
// eventually.
!t.isTSEnumMember(parentNode, { id: node }) &&
!t.isTSModuleDeclaration(parentNode, { id: node }) &&
// isReferenced above fails to see `var { foo } = ...` as a non-reference
// because the direct parent is not enough to know that the pattern is
// used within a variable declaration.
!state.declarationBindingIds.has(node)
) {
let freeVariables = state.freeVariables.get(node.name);
if (!freeVariables) {
freeVariables = [];
state.freeVariables.set(node.name, freeVariables);
}
freeVariables.push({
type: "ref",
start: fromBabelLocation(node.loc.start, state.sourceId),
end: fromBabelLocation(node.loc.end, state.sourceId),
meta: buildMetaBindings(state.sourceId, node, ancestors)
});
} else if (isOpeningJSXIdentifier(node, ancestors)) {
let freeVariables = state.freeVariables.get(node.name);
if (!freeVariables) {
freeVariables = [];
state.freeVariables.set(node.name, freeVariables);
}
freeVariables.push({
type: "ref",
start: fromBabelLocation(node.loc.start, state.sourceId),
end: fromBabelLocation(node.loc.end, state.sourceId),
meta: buildMetaBindings(state.sourceId, node, ancestors)
});
} else if (t.isThisExpression(node)) {
let freeVariables = state.freeVariables.get("this");
if (!freeVariables) {
freeVariables = [];
state.freeVariables.set("this", freeVariables);
}
freeVariables.push({
type: "ref",
start: fromBabelLocation(node.loc.start, state.sourceId),
end: fromBabelLocation(node.loc.end, state.sourceId),
meta: buildMetaBindings(state.sourceId, node, ancestors)
});
} else if (t.isClassProperty(parentNode, { value: node })) {
const scope = pushTempScope(state, "function", "Class Field", {
start: fromBabelLocation(node.loc.start, state.sourceId),
end: fromBabelLocation(node.loc.end, state.sourceId)
});
scope.bindings.this = {
type: "implicit",
refs: []
};
scope.bindings.arguments = {
type: "implicit",
refs: []
};
} else if (
t.isSwitchStatement(node) &&
hasLexicalDeclaration(node, parentNode)
) {
pushTempScope(state, "block", "Switch", {
start: fromBabelLocation(node.loc.start, state.sourceId),
end: fromBabelLocation(node.loc.end, state.sourceId)
});
}
if (
// In general Flow expressions are deleted, so they can't contain
// runtime bindings, but typecasts are the one exception there.
(t.isFlow(node) && !t.isTypeCastExpression(node)) ||
// In general TS items are deleted, but TS has a few wrapper node
// types that can contain general JS expressions.
(node.type.startsWith("TS") &&
!t.isTSTypeAssertion(node) &&
!t.isTSAsExpression(node) &&
!t.isTSNonNullExpression(node) &&
!t.isTSModuleDeclaration(node) &&
!t.isTSModuleBlock(node) &&
!t.isTSParameterProperty(node) &&
!t.isTSExportAssignment(node))
) {
// Flag this node as a root "type" node. All items inside of this
// will be skipped entirely.
state.inType = node;
}
},
exit(
node: Node,
ancestors: TraversalAncestors,
state: ScopeCollectionVisitorState
) {
const currentScope = state.scope;
const parentScope = state.scopeStack.pop();
if (!parentScope) {
throw new Error("Assertion failure - unsynchronized pop");
}
state.scope = parentScope;
// It is possible, as in the case of function expressions, that a single
// node has added multiple scopes, so we need to traverse upward here
// rather than jumping stright to 'parentScope'.
for (
let scope = currentScope;
scope && scope !== parentScope;
scope = scope.parent
) {
const freeVariables = state.freeVariables;
state.freeVariables = state.freeVariableStack.pop();
const parentFreeVariables = state.freeVariables;
// Match up any free variables that match this scope's bindings and
// merge then into the refs.
for (const key of Object.keys(scope.bindings)) {
const binding = scope.bindings[key];
const freeVars = freeVariables.get(key);
if (freeVars) {
binding.refs.push(...freeVars);
freeVariables.delete(key);
}
}
// Move any undeclared references in this scope into the parent for
// processing in higher scopes.
for (const [key, value] of freeVariables) {
let refs = parentFreeVariables.get(key);
if (!refs) {
refs = [];
parentFreeVariables.set(key, refs);
}
refs.push(...value);
}
}
if (state.inType === node) {
state.inType = null;
}
}
};
function isOpeningJSXIdentifier(
node: Node,
ancestors: TraversalAncestors
): boolean {
if (!t.isJSXIdentifier(node)) {
return false;
}
for (let i = ancestors.length - 1; i >= 0; i--) {
const { node: parent, key } = ancestors[i];
if (t.isJSXOpeningElement(parent) && key === "name") {
return true;
} else if (!t.isJSXMemberExpression(parent) || key !== "object") {
break;
}
}
return false;
}
function buildMetaBindings(
sourceId: SourceId,
node: Node,
ancestors: TraversalAncestors,
parentIndex: number = ancestors.length - 1
): BindingMetaValue | null {
if (parentIndex <= 1) {
return null;
}
const parent = ancestors[parentIndex].node;
const grandparent = ancestors[parentIndex - 1].node;
// Consider "0, foo" to be equivalent to "foo".
if (
t.isSequenceExpression(parent) &&
parent.expressions.length === 2 &&
t.isNumericLiteral(parent.expressions[0]) &&
parent.expressions[1] === node
) {
let start = parent.loc.start;
let end = parent.loc.end;
if (t.isCallExpression(grandparent, { callee: parent })) {
// Attempt to expand the range around parentheses, e.g.
// (0, foo.bar)()
start = grandparent.loc.start;
end = Object.assign({}, end);
end.column += 1;
}
return {
type: "inherit",
start: fromBabelLocation(start, sourceId),
end: fromBabelLocation(end, sourceId),
parent: buildMetaBindings(sourceId, parent, ancestors, parentIndex - 1)
};
}
// Consider "Object(foo)", and "__webpack_require__.i(foo)" to be
// equivalent to "foo" since they are essentially identity functions.
if (
t.isCallExpression(parent) &&
(t.isIdentifier(parent.callee, { name: "Object" }) ||
(t.isMemberExpression(parent.callee, { computed: false }) &&
t.isIdentifier(parent.callee.object, { name: "__webpack_require__" }) &&
t.isIdentifier(parent.callee.property, { name: "i" }))) &&
parent.arguments.length === 1 &&
parent.arguments[0] === node
) {
return {
type: "inherit",
start: fromBabelLocation(parent.loc.start, sourceId),
end: fromBabelLocation(parent.loc.end, sourceId),
parent: buildMetaBindings(sourceId, parent, ancestors, parentIndex - 1)
};
}
if (t.isMemberExpression(parent, { object: node })) {
if (parent.computed) {
if (t.isStringLiteral(parent.property)) {
return {
type: "member",
start: fromBabelLocation(parent.loc.start, sourceId),
end: fromBabelLocation(parent.loc.end, sourceId),
property: parent.property.value,
parent: buildMetaBindings(
sourceId,
parent,
ancestors,
parentIndex - 1
)
};
}
} else {
return {
type: "member",
start: fromBabelLocation(parent.loc.start, sourceId),
end: fromBabelLocation(parent.loc.end, sourceId),
property: parent.property.name,
parent: buildMetaBindings(sourceId, parent, ancestors, parentIndex - 1)
};
}
}
if (
t.isCallExpression(parent, { callee: node }) &&
parent.arguments.length == 0
) {
return {
type: "call",
start: fromBabelLocation(parent.loc.start, sourceId),
end: fromBabelLocation(parent.loc.end, sourceId),
parent: buildMetaBindings(sourceId, parent, ancestors, parentIndex - 1)
};
}
return null;
}
function looksLikeCommonJS(rootScope: TempScope): boolean {
const hasRefs = name =>