forked from typescript-eslint/typescript-eslint
/
Referencer.ts
808 lines (695 loc) · 21.8 KB
/
Referencer.ts
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
import type { Lib, TSESTree } from '@typescript-eslint/types';
import { AST_NODE_TYPES } from '@typescript-eslint/types';
import { assert } from '../assert';
import {
CatchClauseDefinition,
FunctionNameDefinition,
ImportBindingDefinition,
ParameterDefinition,
TSEnumMemberDefinition,
TSEnumNameDefinition,
TSModuleNameDefinition,
VariableDefinition,
} from '../definition';
import { lib as TSLibraries } from '../lib';
import type { GlobalScope, Scope } from '../scope';
import type { ScopeManager } from '../ScopeManager';
import { ClassVisitor } from './ClassVisitor';
import { ExportVisitor } from './ExportVisitor';
import { ImportVisitor } from './ImportVisitor';
import { PatternVisitor } from './PatternVisitor';
import type { ReferenceImplicitGlobal } from './Reference';
import { ReferenceFlag } from './Reference';
import { TypeVisitor } from './TypeVisitor';
import type { VisitorOptions } from './Visitor';
import { Visitor } from './Visitor';
interface ReferencerOptions extends VisitorOptions {
jsxPragma: string | null;
jsxFragmentName: string | null;
lib: Lib[];
emitDecoratorMetadata: boolean;
}
// Referencing variables and creating bindings.
class Referencer extends Visitor {
#jsxPragma: string | null;
#jsxFragmentName: string | null;
#hasReferencedJsxFactory = false;
#hasReferencedJsxFragmentFactory = false;
#lib: Lib[];
readonly #emitDecoratorMetadata: boolean;
public readonly scopeManager: ScopeManager;
constructor(options: ReferencerOptions, scopeManager: ScopeManager) {
super(options);
this.scopeManager = scopeManager;
this.#jsxPragma = options.jsxPragma;
this.#jsxFragmentName = options.jsxFragmentName;
this.#lib = options.lib;
this.#emitDecoratorMetadata = options.emitDecoratorMetadata;
}
public currentScope(): Scope;
public currentScope(throwOnNull: true): Scope | null;
public currentScope(dontThrowOnNull?: true): Scope | null {
if (!dontThrowOnNull) {
assert(this.scopeManager.currentScope, 'aaa');
}
return this.scopeManager.currentScope;
}
public close(node: TSESTree.Node): void {
while (this.currentScope(true) && node === this.currentScope().block) {
this.scopeManager.currentScope = this.currentScope().close(
this.scopeManager,
);
}
}
public referencingDefaultValue(
pattern: TSESTree.Identifier,
assignments: (TSESTree.AssignmentExpression | TSESTree.AssignmentPattern)[],
maybeImplicitGlobal: ReferenceImplicitGlobal | null,
init: boolean,
): void {
assignments.forEach(assignment => {
this.currentScope().referenceValue(
pattern,
ReferenceFlag.Write,
assignment.right,
maybeImplicitGlobal,
init,
);
});
}
private populateGlobalsFromLib(globalScope: GlobalScope): void {
for (const lib of this.#lib) {
const variables = TSLibraries[lib];
/* istanbul ignore if */ if (!variables) {
throw new Error(`Invalid value for lib provided: ${lib}`);
}
for (const [name, variable] of Object.entries(variables)) {
globalScope.defineImplicitVariable(name, variable);
}
}
// for const assertions (`{} as const` / `<const>{}`)
globalScope.defineImplicitVariable('const', {
eslintImplicitGlobalSetting: 'readonly',
isTypeVariable: true,
isValueVariable: false,
});
}
/**
* Searches for a variable named "name" in the upper scopes and adds a pseudo-reference from itself to itself
*/
private referenceInSomeUpperScope(name: string): boolean {
let scope = this.scopeManager.currentScope;
while (scope) {
const variable = scope.set.get(name);
if (!variable) {
scope = scope.upper;
continue;
}
scope.referenceValue(variable.identifiers[0]);
return true;
}
return false;
}
private referenceJsxPragma(): void {
if (this.#jsxPragma === null || this.#hasReferencedJsxFactory) {
return;
}
this.#hasReferencedJsxFactory = this.referenceInSomeUpperScope(
this.#jsxPragma,
);
}
private referenceJsxFragment(): void {
if (
this.#jsxFragmentName === null ||
this.#hasReferencedJsxFragmentFactory
) {
return;
}
this.#hasReferencedJsxFragmentFactory = this.referenceInSomeUpperScope(
this.#jsxFragmentName,
);
}
///////////////////
// Visit helpers //
///////////////////
protected visitClass(
node: TSESTree.ClassDeclaration | TSESTree.ClassExpression,
): void {
ClassVisitor.visit(this, node, this.#emitDecoratorMetadata);
}
protected visitForIn(
node: TSESTree.ForInStatement | TSESTree.ForOfStatement,
): void {
if (
node.left.type === AST_NODE_TYPES.VariableDeclaration &&
node.left.kind !== 'var'
) {
this.scopeManager.nestForScope(node);
}
if (node.left.type === AST_NODE_TYPES.VariableDeclaration) {
this.visit(node.left);
this.visitPattern(node.left.declarations[0].id, pattern => {
this.currentScope().referenceValue(
pattern,
ReferenceFlag.Write,
node.right,
null,
true,
);
});
} else {
this.visitPattern(
node.left,
(pattern, info) => {
const maybeImplicitGlobal = !this.currentScope().isStrict
? {
pattern,
node,
}
: null;
this.referencingDefaultValue(
pattern,
info.assignments,
maybeImplicitGlobal,
false,
);
this.currentScope().referenceValue(
pattern,
ReferenceFlag.Write,
node.right,
maybeImplicitGlobal,
false,
);
},
{ processRightHandNodes: true },
);
}
this.visit(node.right);
this.visit(node.body);
this.close(node);
}
protected visitFunctionParameterTypeAnnotation(
node: TSESTree.Parameter,
): void {
if ('typeAnnotation' in node) {
this.visitType(node.typeAnnotation);
} else if (node.type === AST_NODE_TYPES.AssignmentPattern) {
this.visitType(node.left.typeAnnotation);
} else if (node.type === AST_NODE_TYPES.TSParameterProperty) {
this.visitFunctionParameterTypeAnnotation(node.parameter);
}
}
protected visitFunction(
node:
| TSESTree.ArrowFunctionExpression
| TSESTree.FunctionDeclaration
| TSESTree.FunctionExpression
| TSESTree.TSDeclareFunction
| TSESTree.TSEmptyBodyFunctionExpression,
): void {
// FunctionDeclaration name is defined in upper scope
// NOTE: Not referring variableScope. It is intended.
// Since
// in ES5, FunctionDeclaration should be in FunctionBody.
// in ES6, FunctionDeclaration should be block scoped.
if (node.type === AST_NODE_TYPES.FunctionExpression) {
if (node.id) {
// FunctionExpression with name creates its special scope;
// FunctionExpressionNameScope.
this.scopeManager.nestFunctionExpressionNameScope(node);
}
} else if (node.id) {
// id is defined in upper scope
this.currentScope().defineIdentifier(
node.id,
new FunctionNameDefinition(node.id, node),
);
}
// Consider this function is in the MethodDefinition.
this.scopeManager.nestFunctionScope(node, false);
// Process parameter declarations.
for (const param of node.params) {
this.visitPattern(
param,
(pattern, info) => {
this.currentScope().defineIdentifier(
pattern,
new ParameterDefinition(pattern, node, info.rest),
);
this.referencingDefaultValue(pattern, info.assignments, null, true);
},
{ processRightHandNodes: true },
);
this.visitFunctionParameterTypeAnnotation(param);
param.decorators?.forEach(d => this.visit(d));
}
this.visitType(node.returnType);
this.visitType(node.typeParameters);
// In TypeScript there are a number of function-like constructs which have no body,
// so check it exists before traversing
if (node.body) {
// Skip BlockStatement to prevent creating BlockStatement scope.
if (node.body.type === AST_NODE_TYPES.BlockStatement) {
this.visitChildren(node.body);
} else {
this.visit(node.body);
}
}
this.close(node);
}
protected visitProperty(node: TSESTree.Property): void {
if (node.computed) {
this.visit(node.key);
}
this.visit(node.value);
}
protected visitType(node: TSESTree.Node | null | undefined): void {
if (!node) {
return;
}
TypeVisitor.visit(this, node);
}
protected visitTypeAssertion(
node: TSESTree.TSAsExpression | TSESTree.TSTypeAssertion,
): void {
this.visit(node.expression);
this.visitType(node.typeAnnotation);
}
/////////////////////
// Visit selectors //
/////////////////////
protected ArrowFunctionExpression(
node: TSESTree.ArrowFunctionExpression,
): void {
this.visitFunction(node);
}
protected AssignmentExpression(node: TSESTree.AssignmentExpression): void {
let left = node.left;
switch (left.type) {
case AST_NODE_TYPES.TSAsExpression:
case AST_NODE_TYPES.TSTypeAssertion:
// explicitly visit the type annotation
this.visitType(left.typeAnnotation);
// intentional fallthrough
case AST_NODE_TYPES.TSNonNullExpression:
// unwrap the expression
left = left.expression;
}
if (PatternVisitor.isPattern(left)) {
if (node.operator === '=') {
this.visitPattern(
left,
(pattern, info) => {
const maybeImplicitGlobal = !this.currentScope().isStrict
? {
pattern,
node,
}
: null;
this.referencingDefaultValue(
pattern,
info.assignments,
maybeImplicitGlobal,
false,
);
this.currentScope().referenceValue(
pattern,
ReferenceFlag.Write,
node.right,
maybeImplicitGlobal,
false,
);
},
{ processRightHandNodes: true },
);
} else if (left.type === AST_NODE_TYPES.Identifier) {
this.currentScope().referenceValue(
left,
ReferenceFlag.ReadWrite,
node.right,
);
}
} else {
this.visit(left);
}
this.visit(node.right);
}
protected BlockStatement(node: TSESTree.BlockStatement): void {
if (this.scopeManager.isES6()) {
this.scopeManager.nestBlockScope(node);
}
this.visitChildren(node);
this.close(node);
}
protected BreakStatement(): void {
// don't reference the break statement's label
}
protected CallExpression(node: TSESTree.CallExpression): void {
this.visitChildren(node, ['typeParameters']);
this.visitType(node.typeParameters);
}
protected CatchClause(node: TSESTree.CatchClause): void {
this.scopeManager.nestCatchScope(node);
if (node.param) {
const param = node.param;
this.visitPattern(
param,
(pattern, info) => {
this.currentScope().defineIdentifier(
pattern,
new CatchClauseDefinition(param, node),
);
this.referencingDefaultValue(pattern, info.assignments, null, true);
},
{ processRightHandNodes: true },
);
}
this.visit(node.body);
this.close(node);
}
protected ClassExpression(node: TSESTree.ClassExpression): void {
this.visitClass(node);
}
protected ClassDeclaration(node: TSESTree.ClassDeclaration): void {
this.visitClass(node);
}
protected ContinueStatement(): void {
// don't reference the continue statement's label
}
protected ExportAllDeclaration(): void {
// this defines no local variables
}
protected ExportDefaultDeclaration(
node: TSESTree.ExportDefaultDeclaration,
): void {
if (node.declaration.type === AST_NODE_TYPES.Identifier) {
ExportVisitor.visit(this, node);
} else {
this.visit(node.declaration);
}
}
protected ExportNamedDeclaration(
node: TSESTree.ExportNamedDeclaration,
): void {
if (node.declaration) {
this.visit(node.declaration);
} else {
ExportVisitor.visit(this, node);
}
}
protected ForInStatement(node: TSESTree.ForInStatement): void {
this.visitForIn(node);
}
protected ForOfStatement(node: TSESTree.ForOfStatement): void {
this.visitForIn(node);
}
protected ForStatement(node: TSESTree.ForStatement): void {
// Create ForStatement declaration.
// NOTE: In ES6, ForStatement dynamically generates per iteration environment. However, this is
// a static analyzer, we only generate one scope for ForStatement.
if (
node.init &&
node.init.type === AST_NODE_TYPES.VariableDeclaration &&
node.init.kind !== 'var'
) {
this.scopeManager.nestForScope(node);
}
this.visitChildren(node);
this.close(node);
}
protected FunctionDeclaration(node: TSESTree.FunctionDeclaration): void {
this.visitFunction(node);
}
protected FunctionExpression(node: TSESTree.FunctionExpression): void {
this.visitFunction(node);
}
protected Identifier(node: TSESTree.Identifier): void {
this.currentScope().referenceValue(node);
this.visitType(node.typeAnnotation);
}
protected ImportDeclaration(node: TSESTree.ImportDeclaration): void {
assert(
this.scopeManager.isES6() && this.scopeManager.isModule(),
'ImportDeclaration should appear when the mode is ES6 and in the module context.',
);
ImportVisitor.visit(this, node);
}
protected JSXAttribute(node: TSESTree.JSXAttribute): void {
this.visit(node.value);
}
protected JSXClosingElement(): void {
// should not be counted as a reference
}
protected JSXFragment(node: TSESTree.JSXFragment): void {
this.referenceJsxPragma();
this.referenceJsxFragment();
this.visitChildren(node);
}
protected JSXIdentifier(node: TSESTree.JSXIdentifier): void {
this.currentScope().referenceValue(node);
}
protected JSXMemberExpression(node: TSESTree.JSXMemberExpression): void {
if (node.object.type !== AST_NODE_TYPES.JSXIdentifier) {
this.visit(node.object);
} else {
if (node.object.name !== 'this') {
this.visit(node.object);
}
}
// we don't ever reference the property as it's always going to be a property on the thing
}
protected JSXOpeningElement(node: TSESTree.JSXOpeningElement): void {
this.referenceJsxPragma();
if (node.name.type === AST_NODE_TYPES.JSXIdentifier) {
if (
node.name.name[0].toUpperCase() === node.name.name[0] ||
node.name.name === 'this'
) {
// lower cased component names are always treated as "intrinsic" names, and are converted to a string,
// not a variable by JSX transforms:
// <div /> => React.createElement("div", null)
// the only case we want to visit a lower-cased component has its name as "this",
this.visit(node.name);
}
} else {
this.visit(node.name);
}
this.visitType(node.typeParameters);
for (const attr of node.attributes) {
this.visit(attr);
}
}
protected LabeledStatement(node: TSESTree.LabeledStatement): void {
this.visit(node.body);
}
protected MemberExpression(node: TSESTree.MemberExpression): void {
this.visit(node.object);
if (node.computed) {
this.visit(node.property);
}
}
protected MetaProperty(): void {
// meta properties all builtin globals
}
protected NewExpression(node: TSESTree.NewExpression): void {
this.visitChildren(node, ['typeParameters']);
this.visitType(node.typeParameters);
}
protected PrivateIdentifier(): void {
// private identifiers are members on classes and thus have no variables to to reference
}
protected Program(node: TSESTree.Program): void {
const globalScope = this.scopeManager.nestGlobalScope(node);
this.populateGlobalsFromLib(globalScope);
if (this.scopeManager.isGlobalReturn()) {
// Force strictness of GlobalScope to false when using node.js scope.
this.currentScope().isStrict = false;
this.scopeManager.nestFunctionScope(node, false);
}
if (this.scopeManager.isES6() && this.scopeManager.isModule()) {
this.scopeManager.nestModuleScope(node);
}
if (
this.scopeManager.isStrictModeSupported() &&
this.scopeManager.isImpliedStrict()
) {
this.currentScope().isStrict = true;
}
this.visitChildren(node);
this.close(node);
}
protected Property(node: TSESTree.Property): void {
this.visitProperty(node);
}
protected SwitchStatement(node: TSESTree.SwitchStatement): void {
this.visit(node.discriminant);
if (this.scopeManager.isES6()) {
this.scopeManager.nestSwitchScope(node);
}
for (const switchCase of node.cases) {
this.visit(switchCase);
}
this.close(node);
}
protected TaggedTemplateExpression(
node: TSESTree.TaggedTemplateExpression,
): void {
this.visit(node.tag);
this.visit(node.quasi);
this.visitType(node.typeParameters);
}
protected TSAsExpression(node: TSESTree.TSAsExpression): void {
this.visitTypeAssertion(node);
}
protected TSDeclareFunction(node: TSESTree.TSDeclareFunction): void {
this.visitFunction(node);
}
protected TSImportEqualsDeclaration(
node: TSESTree.TSImportEqualsDeclaration,
): void {
this.currentScope().defineIdentifier(
node.id,
new ImportBindingDefinition(node.id, node, node),
);
if (node.moduleReference.type === AST_NODE_TYPES.TSQualifiedName) {
this.visit(node.moduleReference.left);
} else {
this.visit(node.moduleReference);
}
}
protected TSEmptyBodyFunctionExpression(
node: TSESTree.TSEmptyBodyFunctionExpression,
): void {
this.visitFunction(node);
}
protected TSEnumDeclaration(node: TSESTree.TSEnumDeclaration): void {
this.currentScope().defineIdentifier(
node.id,
new TSEnumNameDefinition(node.id, node),
);
// enum members can be referenced within the enum body
this.scopeManager.nestTSEnumScope(node);
// define the enum name again inside the new enum scope
// references to the enum should not resolve directly to the enum
this.currentScope().defineIdentifier(
node.id,
new TSEnumNameDefinition(node.id, node),
);
for (const member of node.members) {
// TS resolves literal named members to be actual names
// enum Foo {
// 'a' = 1,
// b = a, // this references the 'a' member
// }
if (
member.id.type === AST_NODE_TYPES.Literal &&
typeof member.id.value === 'string'
) {
const name = member.id;
this.currentScope().defineLiteralIdentifier(
name,
new TSEnumMemberDefinition(name, member),
);
} else if (
!member.computed &&
member.id.type === AST_NODE_TYPES.Identifier
) {
this.currentScope().defineIdentifier(
member.id,
new TSEnumMemberDefinition(member.id, member),
);
}
this.visit(member.initializer);
}
this.close(node);
}
protected TSInstantiationExpression(
node: TSESTree.TSInstantiationExpression,
): void {
this.visitChildren(node, ['typeParameters']);
this.visitType(node.typeParameters);
}
protected TSInterfaceDeclaration(
node: TSESTree.TSInterfaceDeclaration,
): void {
this.visitType(node);
}
protected TSModuleDeclaration(node: TSESTree.TSModuleDeclaration): void {
if (node.id.type === AST_NODE_TYPES.Identifier && !node.global) {
this.currentScope().defineIdentifier(
node.id,
new TSModuleNameDefinition(node.id, node),
);
}
this.scopeManager.nestTSModuleScope(node);
this.visit(node.body);
this.close(node);
}
protected TSTypeAliasDeclaration(
node: TSESTree.TSTypeAliasDeclaration,
): void {
this.visitType(node);
}
protected TSTypeAssertion(node: TSESTree.TSTypeAssertion): void {
this.visitTypeAssertion(node);
}
protected UpdateExpression(node: TSESTree.UpdateExpression): void {
if (PatternVisitor.isPattern(node.argument)) {
this.visitPattern(node.argument, pattern => {
this.currentScope().referenceValue(
pattern,
ReferenceFlag.ReadWrite,
null,
);
});
} else {
this.visitChildren(node);
}
}
protected VariableDeclaration(node: TSESTree.VariableDeclaration): void {
const variableTargetScope =
node.kind === 'var'
? this.currentScope().variableScope
: this.currentScope();
for (const decl of node.declarations) {
const init = decl.init;
this.visitPattern(
decl.id,
(pattern, info) => {
variableTargetScope.defineIdentifier(
pattern,
new VariableDefinition(pattern, decl, node),
);
this.referencingDefaultValue(pattern, info.assignments, null, true);
if (init) {
this.currentScope().referenceValue(
pattern,
ReferenceFlag.Write,
init,
null,
true,
);
}
},
{ processRightHandNodes: true },
);
if (decl.init) {
this.visit(decl.init);
}
if ('typeAnnotation' in decl.id) {
this.visitType(decl.id.typeAnnotation);
}
}
}
protected WithStatement(node: TSESTree.WithStatement): void {
this.visit(node.object);
// Then nest scope for WithStatement.
this.scopeManager.nestWithScope(node);
this.visit(node.body);
this.close(node);
}
protected ImportAttribute(): void {
// import assertions are module metadata and thus have no variables to reference
}
}
export { Referencer, ReferencerOptions };