-
Notifications
You must be signed in to change notification settings - Fork 12.5k
/
binder.ts
3975 lines (3685 loc) · 193 KB
/
binder.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
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 {
__String,
AccessExpression,
addRelatedInfo,
append,
appendIfUnique,
ArrayBindingElement,
ArrayLiteralExpression,
ArrowFunction,
AssignmentDeclarationKind,
BinaryExpression,
BinaryOperatorToken,
BindableAccessExpression,
BindableObjectDefinePropertyCall,
BindablePropertyAssignmentExpression,
BindableStaticAccessExpression,
BindableStaticNameExpression,
BindableStaticPropertyAssignmentExpression,
BindingElement,
Block,
BreakOrContinueStatement,
CallChain,
CallExpression,
canHaveLocals,
canHaveSymbol,
CaseBlock,
CaseClause,
cast,
CatchClause,
ClassLikeDeclaration,
ClassStaticBlockDeclaration,
CompilerOptions,
concatenate,
ConditionalExpression,
ConditionalTypeNode,
contains,
createBinaryExpressionTrampoline,
createDiagnosticForNodeInSourceFile,
createFileDiagnostic,
createQueue,
createSymbolTable,
Debug,
Declaration,
declarationNameToString,
DeleteExpression,
DestructuringAssignment,
DiagnosticArguments,
DiagnosticCategory,
DiagnosticMessage,
DiagnosticRelatedInformation,
Diagnostics,
DiagnosticWithLocation,
DoStatement,
DynamicNamedDeclaration,
ElementAccessChain,
ElementAccessExpression,
EntityNameExpression,
EnumDeclaration,
escapeLeadingUnderscores,
every,
ExportAssignment,
exportAssignmentIsAlias,
ExportDeclaration,
ExportSpecifier,
Expression,
ExpressionStatement,
findAncestor,
FlowArrayMutation,
FlowAssignment,
FlowCall,
FlowCondition,
FlowFlags,
FlowLabel,
FlowNode,
FlowReduceLabel,
FlowSwitchClause,
forEach,
forEachChild,
ForInOrOfStatement,
ForStatement,
FunctionDeclaration,
FunctionExpression,
FunctionLikeDeclaration,
GetAccessorDeclaration,
getAssignedExpandoInitializer,
getAssignmentDeclarationKind,
getAssignmentDeclarationPropertyAccessKind,
getCombinedModifierFlags,
getCombinedNodeFlags,
getContainingClass,
getEffectiveContainerForJSDocTemplateTag,
getElementOrPropertyAccessName,
getEmitScriptTarget,
getEnclosingBlockScopeContainer,
getEnclosingContainer,
getErrorSpanForNode,
getEscapedTextOfIdentifierOrLiteral,
getEscapedTextOfJsxNamespacedName,
getExpandoInitializer,
getHostSignatureFromJSDoc,
getImmediatelyInvokedFunctionExpression,
getJSDocHost,
getJSDocTypeTag,
getLeftmostAccessExpression,
getNameOfDeclaration,
getNameOrArgument,
getNodeId,
getRangesWhere,
getRightMostAssignedExpression,
getSourceFileOfNode,
getSourceTextOfNodeFromSourceFile,
getSpanOfTokenAtPosition,
getStrictOptionValue,
getSymbolNameForPrivateIdentifier,
getTextOfIdentifierOrLiteral,
getThisContainer,
getTokenPosOfNode,
HasContainerFlags,
hasDynamicName,
HasFlowNode,
hasJSDocNodes,
HasLocals,
hasSyntacticModifier,
Identifier,
identifierToKeywordKind,
idText,
IfStatement,
ImportClause,
InternalSymbolName,
isAliasableExpression,
isAmbientModule,
isAssignmentExpression,
isAssignmentOperator,
isAssignmentTarget,
isAsyncFunction,
isAutoAccessorPropertyDeclaration,
isBinaryExpression,
isBindableObjectDefinePropertyCall,
isBindableStaticAccessExpression,
isBindableStaticNameExpression,
isBindingPattern,
isBlock,
isBlockOrCatchScoped,
IsBlockScopedContainer,
isBooleanLiteral,
isCallExpression,
isClassStaticBlockDeclaration,
isConditionalTypeNode,
IsContainer,
isDeclaration,
isDeclarationStatement,
isDestructuringAssignment,
isDottedName,
isEmptyObjectLiteral,
isEntityNameExpression,
isEnumConst,
isEnumDeclaration,
isExportAssignment,
isExportDeclaration,
isExportsIdentifier,
isExportSpecifier,
isExpression,
isExpressionOfOptionalChainRoot,
isExternalModule,
isExternalOrCommonJsModule,
isForInOrOfStatement,
isFunctionDeclaration,
isFunctionLike,
isFunctionLikeDeclaration,
isFunctionLikeOrClassStaticBlockDeclaration,
isFunctionSymbol,
isGlobalScopeAugmentation,
isIdentifier,
isIdentifierName,
isInJSFile,
isInTopLevelContext,
isJSDocConstructSignature,
isJSDocEnumTag,
isJSDocTemplateTag,
isJSDocTypeAlias,
isJSDocTypeAssertion,
isJsonSourceFile,
isJsxNamespacedName,
isLeftHandSideExpression,
isLogicalOrCoalescingAssignmentExpression,
isLogicalOrCoalescingAssignmentOperator,
isLogicalOrCoalescingBinaryExpression,
isLogicalOrCoalescingBinaryOperator,
isModuleAugmentationExternal,
isModuleBlock,
isModuleDeclaration,
isModuleExportsAccessExpression,
isNamedDeclaration,
isNamespaceExport,
isNullishCoalesce,
isObjectLiteralExpression,
isObjectLiteralMethod,
isObjectLiteralOrClassExpressionMethodOrAccessor,
isOmittedExpression,
isOptionalChain,
isOptionalChainRoot,
isOutermostOptionalChain,
isParameterPropertyDeclaration,
isParenthesizedExpression,
isPartOfParameterDeclaration,
isPartOfTypeQuery,
isPrefixUnaryExpression,
isPrivateIdentifier,
isPrologueDirective,
isPropertyAccessEntityNameExpression,
isPropertyAccessExpression,
isPropertyNameLiteral,
isPrototypeAccess,
isPushOrUnshiftIdentifier,
isRequireCall,
isShorthandPropertyAssignment,
isSignedNumericLiteral,
isSourceFile,
isSpecialPropertyDeclaration,
isStatement,
isStatementButNotDeclaration,
isStatic,
isString,
isStringLiteralLike,
isStringOrNumericLiteralLike,
isThisInitializedDeclaration,
isTypeAliasDeclaration,
isTypeOfExpression,
isVariableDeclaration,
isVariableDeclarationInitializedToBareOrAccessedRequire,
isVariableStatement,
JSDocCallbackTag,
JSDocClassTag,
JSDocEnumTag,
JSDocFunctionType,
JSDocImportTag,
JSDocOverloadTag,
JSDocParameterTag,
JSDocPropertyLikeTag,
JSDocSignature,
JSDocTypedefTag,
JSDocTypeLiteral,
JsxAttribute,
JsxAttributes,
LabeledStatement,
length,
LiteralLikeElementAccessExpression,
MappedTypeNode,
MetaProperty,
MethodDeclaration,
ModifierFlags,
ModuleBlock,
ModuleDeclaration,
moduleExportNameIsDefault,
Mutable,
NamespaceExportDeclaration,
Node,
NodeArray,
NodeFlags,
nodeHasName,
nodeIsMissing,
nodeIsPresent,
NonNullChain,
NonNullExpression,
objectAllocator,
ObjectLiteralExpression,
OptionalChain,
ParameterDeclaration,
ParenthesizedExpression,
Pattern,
PatternAmbientModule,
perfLogger,
PostfixUnaryExpression,
PrefixUnaryExpression,
PrivateIdentifier,
PropertyAccessChain,
PropertyAccessEntityNameExpression,
PropertyAccessExpression,
PropertyDeclaration,
PropertySignature,
QualifiedName,
removeFileExtension,
ReturnStatement,
ScriptTarget,
SetAccessorDeclaration,
setParent,
setParentRecursive,
setValueDeclaration,
ShorthandPropertyAssignment,
shouldPreserveConstEnums,
SignatureDeclaration,
skipParentheses,
sliceAfter,
some,
SourceFile,
SpreadElement,
Statement,
StringLiteral,
SuperExpression,
SwitchStatement,
Symbol,
SymbolFlags,
symbolName,
SymbolTable,
SyntaxKind,
TextRange,
ThisExpression,
ThrowStatement,
tokenToString,
tracing,
TracingNode,
tryCast,
tryParsePattern,
TryStatement,
TypeLiteralNode,
TypeOfExpression,
TypeParameterDeclaration,
unescapeLeadingUnderscores,
unreachableCodeIsError,
unusedLabelIsError,
VariableDeclaration,
WhileStatement,
WithStatement,
} from "./_namespaces/ts.js";
import * as performance from "./_namespaces/ts.performance.js";
/** @internal */
export const enum ModuleInstanceState {
NonInstantiated = 0,
Instantiated = 1,
ConstEnumOnly = 2,
}
interface ActiveLabel {
next: ActiveLabel | undefined;
name: __String;
breakTarget: FlowLabel;
continueTarget: FlowLabel | undefined;
referenced: boolean;
}
/** @internal */
export function getModuleInstanceState(node: ModuleDeclaration, visited?: Map<number, ModuleInstanceState | undefined>): ModuleInstanceState {
if (node.body && !node.body.parent) {
// getModuleInstanceStateForAliasTarget needs to walk up the parent chain, so parent pointers must be set on this tree already
setParent(node.body, node);
setParentRecursive(node.body, /*incremental*/ false);
}
return node.body ? getModuleInstanceStateCached(node.body, visited) : ModuleInstanceState.Instantiated;
}
function getModuleInstanceStateCached(node: Node, visited = new Map<number, ModuleInstanceState | undefined>()) {
const nodeId = getNodeId(node);
if (visited.has(nodeId)) {
return visited.get(nodeId) || ModuleInstanceState.NonInstantiated;
}
visited.set(nodeId, undefined);
const result = getModuleInstanceStateWorker(node, visited);
visited.set(nodeId, result);
return result;
}
function getModuleInstanceStateWorker(node: Node, visited: Map<number, ModuleInstanceState | undefined>): ModuleInstanceState {
// A module is uninstantiated if it contains only
switch (node.kind) {
// 1. interface declarations, type alias declarations
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.TypeAliasDeclaration:
return ModuleInstanceState.NonInstantiated;
// 2. const enum declarations
case SyntaxKind.EnumDeclaration:
if (isEnumConst(node as EnumDeclaration)) {
return ModuleInstanceState.ConstEnumOnly;
}
break;
// 3. non-exported import declarations
case SyntaxKind.ImportDeclaration:
case SyntaxKind.ImportEqualsDeclaration:
if (!(hasSyntacticModifier(node, ModifierFlags.Export))) {
return ModuleInstanceState.NonInstantiated;
}
break;
// 4. Export alias declarations pointing at only uninstantiated modules or things uninstantiated modules contain
case SyntaxKind.ExportDeclaration:
const exportDeclaration = node as ExportDeclaration;
if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === SyntaxKind.NamedExports) {
let state = ModuleInstanceState.NonInstantiated;
for (const specifier of exportDeclaration.exportClause.elements) {
const specifierState = getModuleInstanceStateForAliasTarget(specifier, visited);
if (specifierState > state) {
state = specifierState;
}
if (state === ModuleInstanceState.Instantiated) {
return state;
}
}
return state;
}
break;
// 5. other uninstantiated module declarations.
case SyntaxKind.ModuleBlock: {
let state = ModuleInstanceState.NonInstantiated;
forEachChild(node, n => {
const childState = getModuleInstanceStateCached(n, visited);
switch (childState) {
case ModuleInstanceState.NonInstantiated:
// child is non-instantiated - continue searching
return;
case ModuleInstanceState.ConstEnumOnly:
// child is const enum only - record state and continue searching
state = ModuleInstanceState.ConstEnumOnly;
return;
case ModuleInstanceState.Instantiated:
// child is instantiated - record state and stop
state = ModuleInstanceState.Instantiated;
return true;
default:
Debug.assertNever(childState);
}
});
return state;
}
case SyntaxKind.ModuleDeclaration:
return getModuleInstanceState(node as ModuleDeclaration, visited);
case SyntaxKind.Identifier:
// Only jsdoc typedef definition can exist in jsdoc namespace, and it should
// be considered the same as type alias
if (node.flags & NodeFlags.IdentifierIsInJSDocNamespace) {
return ModuleInstanceState.NonInstantiated;
}
}
return ModuleInstanceState.Instantiated;
}
function getModuleInstanceStateForAliasTarget(specifier: ExportSpecifier, visited: Map<number, ModuleInstanceState | undefined>) {
const name = specifier.propertyName || specifier.name;
if (name.kind !== SyntaxKind.Identifier) {
return ModuleInstanceState.Instantiated; // Skip for invalid syntax like this: export { "x" }
}
let p: Node | undefined = specifier.parent;
while (p) {
if (isBlock(p) || isModuleBlock(p) || isSourceFile(p)) {
const statements = p.statements;
let found: ModuleInstanceState | undefined;
for (const statement of statements) {
if (nodeHasName(statement, name)) {
if (!statement.parent) {
setParent(statement, p);
setParentRecursive(statement, /*incremental*/ false);
}
const state = getModuleInstanceStateCached(statement, visited);
if (found === undefined || state > found) {
found = state;
}
if (found === ModuleInstanceState.Instantiated) {
return found;
}
if (statement.kind === SyntaxKind.ImportEqualsDeclaration) {
// Treat re-exports of import aliases as instantiated,
// since they're ambiguous. This is consistent with
// `export import x = mod.x` being treated as instantiated:
// import x = mod.x;
// export { x };
found = ModuleInstanceState.Instantiated;
}
}
}
if (found !== undefined) {
return found;
}
}
p = p.parent;
}
return ModuleInstanceState.Instantiated; // Couldn't locate, assume could refer to a value
}
/** @internal */
export const enum ContainerFlags {
// The current node is not a container, and no container manipulation should happen before
// recursing into it.
None = 0,
// The current node is a container. It should be set as the current container (and block-
// container) before recursing into it. The current node does not have locals. Examples:
//
// Classes, ObjectLiterals, TypeLiterals, Interfaces...
IsContainer = 1 << 0,
// The current node is a block-scoped-container. It should be set as the current block-
// container before recursing into it. Examples:
//
// Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements...
IsBlockScopedContainer = 1 << 1,
// The current node is the container of a control flow path. The current control flow should
// be saved and restored, and a new control flow initialized within the container.
IsControlFlowContainer = 1 << 2,
IsFunctionLike = 1 << 3,
IsFunctionExpression = 1 << 4,
HasLocals = 1 << 5,
IsInterface = 1 << 6,
IsObjectLiteralOrClassExpressionMethodOrAccessor = 1 << 7,
}
/** @internal */
export function createFlowNode(flags: FlowFlags, node: unknown, antecedent: FlowNode | FlowNode[] | undefined): FlowNode {
return Debug.attachFlowNodeDebugInfo({ flags, id: 0, node, antecedent } as FlowNode);
}
const binder = /* @__PURE__ */ createBinder();
/** @internal */
export function bindSourceFile(file: SourceFile, options: CompilerOptions) {
performance.mark("beforeBind");
perfLogger?.logStartBindFile("" + file.fileName);
binder(file, options);
perfLogger?.logStopBindFile();
performance.mark("afterBind");
performance.measure("Bind", "beforeBind", "afterBind");
}
function createBinder(): (file: SourceFile, options: CompilerOptions) => void {
// Why var? It avoids TDZ checks in the runtime which can be costly.
// See: https://github.com/microsoft/TypeScript/issues/52924
/* eslint-disable no-var */
var file: SourceFile;
var options: CompilerOptions;
var languageVersion: ScriptTarget;
var parent: Node;
var container: IsContainer | EntityNameExpression;
var thisParentContainer: IsContainer | EntityNameExpression; // Container one level up
var blockScopeContainer: IsBlockScopedContainer;
var lastContainer: HasLocals;
var delayedTypeAliases: (JSDocTypedefTag | JSDocCallbackTag | JSDocEnumTag)[];
var seenThisKeyword: boolean;
var jsDocImports: JSDocImportTag[];
// state used by control flow analysis
var currentFlow: FlowNode;
var currentBreakTarget: FlowLabel | undefined;
var currentContinueTarget: FlowLabel | undefined;
var currentReturnTarget: FlowLabel | undefined;
var currentTrueTarget: FlowLabel | undefined;
var currentFalseTarget: FlowLabel | undefined;
var currentExceptionTarget: FlowLabel | undefined;
var preSwitchCaseFlow: FlowNode | undefined;
var activeLabelList: ActiveLabel | undefined;
var hasExplicitReturn: boolean;
var hasFlowEffects: boolean;
// state used for emit helpers
var emitFlags: NodeFlags;
// If this file is an external module, then it is automatically in strict-mode according to
// ES6. If it is not an external module, then we'll determine if it is in strict mode or
// not depending on if we see "use strict" in certain places or if we hit a class/namespace
// or if compiler options contain alwaysStrict.
var inStrictMode: boolean;
// If we are binding an assignment pattern, we will bind certain expressions differently.
var inAssignmentPattern = false;
var symbolCount = 0;
var Symbol: new (flags: SymbolFlags, name: __String) => Symbol;
var classifiableNames: Set<__String>;
var unreachableFlow = createFlowNode(FlowFlags.Unreachable, /*node*/ undefined, /*antecedent*/ undefined);
var reportedUnreachableFlow = createFlowNode(FlowFlags.Unreachable, /*node*/ undefined, /*antecedent*/ undefined);
var bindBinaryExpressionFlow = createBindBinaryExpressionFlow();
/* eslint-enable no-var */
return bindSourceFile;
/**
* Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file)
* If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node)
* This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations.
*/
function createDiagnosticForNode(node: Node, message: DiagnosticMessage, ...args: DiagnosticArguments): DiagnosticWithLocation {
return createDiagnosticForNodeInSourceFile(getSourceFileOfNode(node) || file, node, message, ...args);
}
function bindSourceFile(f: SourceFile, opts: CompilerOptions) {
file = f;
options = opts;
languageVersion = getEmitScriptTarget(options);
inStrictMode = bindInStrictMode(file, opts);
classifiableNames = new Set();
symbolCount = 0;
Symbol = objectAllocator.getSymbolConstructor();
// Attach debugging information if necessary
Debug.attachFlowNodeDebugInfo(unreachableFlow);
Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow);
if (!file.locals) {
tracing?.push(tracing.Phase.Bind, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true);
bind(file);
tracing?.pop();
file.symbolCount = symbolCount;
file.classifiableNames = classifiableNames;
delayedBindJSDocTypedefTag();
bindJSDocImports();
}
file = undefined!;
options = undefined!;
languageVersion = undefined!;
parent = undefined!;
container = undefined!;
thisParentContainer = undefined!;
blockScopeContainer = undefined!;
lastContainer = undefined!;
delayedTypeAliases = undefined!;
jsDocImports = undefined!;
seenThisKeyword = false;
currentFlow = undefined!;
currentBreakTarget = undefined;
currentContinueTarget = undefined;
currentReturnTarget = undefined;
currentTrueTarget = undefined;
currentFalseTarget = undefined;
currentExceptionTarget = undefined;
activeLabelList = undefined;
hasExplicitReturn = false;
hasFlowEffects = false;
inAssignmentPattern = false;
emitFlags = NodeFlags.None;
}
function bindInStrictMode(file: SourceFile, opts: CompilerOptions): boolean {
if (getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) {
// bind in strict mode source files with alwaysStrict option
return true;
}
else {
return !!file.externalModuleIndicator;
}
}
function createSymbol(flags: SymbolFlags, name: __String): Symbol {
symbolCount++;
return new Symbol(flags, name);
}
function addDeclarationToSymbol(symbol: Symbol, node: Declaration, symbolFlags: SymbolFlags) {
symbol.flags |= symbolFlags;
node.symbol = symbol;
symbol.declarations = appendIfUnique(symbol.declarations, node);
if (symbolFlags & (SymbolFlags.Class | SymbolFlags.Enum | SymbolFlags.Module | SymbolFlags.Variable) && !symbol.exports) {
symbol.exports = createSymbolTable();
}
if (symbolFlags & (SymbolFlags.Class | SymbolFlags.Interface | SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral) && !symbol.members) {
symbol.members = createSymbolTable();
}
// On merge of const enum module with class or function, reset const enum only flag (namespaces will already recalculate)
if (symbol.constEnumOnlyModule && (symbol.flags & (SymbolFlags.Function | SymbolFlags.Class | SymbolFlags.RegularEnum))) {
symbol.constEnumOnlyModule = false;
}
if (symbolFlags & SymbolFlags.Value) {
setValueDeclaration(symbol, node);
}
}
// Should not be called on a declaration with a computed property name,
// unless it is a well known Symbol.
function getDeclarationName(node: Declaration): __String | undefined {
if (node.kind === SyntaxKind.ExportAssignment) {
return (node as ExportAssignment).isExportEquals ? InternalSymbolName.ExportEquals : InternalSymbolName.Default;
}
const name = getNameOfDeclaration(node);
if (name) {
if (isAmbientModule(node)) {
const moduleName = getTextOfIdentifierOrLiteral(name as Identifier | StringLiteral);
return (isGlobalScopeAugmentation(node as ModuleDeclaration) ? "__global" : `"${moduleName}"`) as __String;
}
if (name.kind === SyntaxKind.ComputedPropertyName) {
const nameExpression = name.expression;
// treat computed property names where expression is string/numeric literal as just string/numeric literal
if (isStringOrNumericLiteralLike(nameExpression)) {
return escapeLeadingUnderscores(nameExpression.text);
}
if (isSignedNumericLiteral(nameExpression)) {
return tokenToString(nameExpression.operator) + nameExpression.operand.text as __String;
}
else {
Debug.fail("Only computed properties with literal names have declaration names");
}
}
if (isPrivateIdentifier(name)) {
// containingClass exists because private names only allowed inside classes
const containingClass = getContainingClass(node);
if (!containingClass) {
// we can get here in cases where there is already a parse error.
return undefined;
}
const containingClassSymbol = containingClass.symbol;
return getSymbolNameForPrivateIdentifier(containingClassSymbol, name.escapedText);
}
if (isJsxNamespacedName(name)) {
return getEscapedTextOfJsxNamespacedName(name);
}
return isPropertyNameLiteral(name) ? getEscapedTextOfIdentifierOrLiteral(name) : undefined;
}
switch (node.kind) {
case SyntaxKind.Constructor:
return InternalSymbolName.Constructor;
case SyntaxKind.FunctionType:
case SyntaxKind.CallSignature:
case SyntaxKind.JSDocSignature:
return InternalSymbolName.Call;
case SyntaxKind.ConstructorType:
case SyntaxKind.ConstructSignature:
return InternalSymbolName.New;
case SyntaxKind.IndexSignature:
return InternalSymbolName.Index;
case SyntaxKind.ExportDeclaration:
return InternalSymbolName.ExportStar;
case SyntaxKind.SourceFile:
// json file should behave as
// module.exports = ...
return InternalSymbolName.ExportEquals;
case SyntaxKind.BinaryExpression:
if (getAssignmentDeclarationKind(node as BinaryExpression) === AssignmentDeclarationKind.ModuleExports) {
// module.exports = ...
return InternalSymbolName.ExportEquals;
}
Debug.fail("Unknown binary declaration kind");
break;
case SyntaxKind.JSDocFunctionType:
return (isJSDocConstructSignature(node) ? InternalSymbolName.New : InternalSymbolName.Call);
case SyntaxKind.Parameter:
// Parameters with names are handled at the top of this function. Parameters
// without names can only come from JSDocFunctionTypes.
Debug.assert(node.parent.kind === SyntaxKind.JSDocFunctionType, "Impossible parameter parent kind", () => `parent is: ${Debug.formatSyntaxKind(node.parent.kind)}, expected JSDocFunctionType`);
const functionType = node.parent as JSDocFunctionType;
const index = functionType.parameters.indexOf(node as ParameterDeclaration);
return "arg" + index as __String;
}
}
function getDisplayName(node: Declaration): string {
return isNamedDeclaration(node) ? declarationNameToString(node.name) : unescapeLeadingUnderscores(Debug.checkDefined(getDeclarationName(node)));
}
/**
* Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names.
* @param symbolTable - The symbol table which node will be added to.
* @param parent - node's parent declaration.
* @param node - The declaration to be added to the symbol table
* @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.)
* @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
*/
function declareSymbol(symbolTable: SymbolTable, parent: Symbol | undefined, node: Declaration, includes: SymbolFlags, excludes: SymbolFlags, isReplaceableByMethod?: boolean, isComputedName?: boolean): Symbol {
Debug.assert(isComputedName || !hasDynamicName(node));
const isDefaultExport = hasSyntacticModifier(node, ModifierFlags.Default) || isExportSpecifier(node) && moduleExportNameIsDefault(node.name);
// The exported symbol for an export default function/class node is always named "default"
const name = isComputedName ? InternalSymbolName.Computed
: isDefaultExport && parent ? InternalSymbolName.Default
: getDeclarationName(node);
let symbol: Symbol | undefined;
if (name === undefined) {
symbol = createSymbol(SymbolFlags.None, InternalSymbolName.Missing);
}
else {
// Check and see if the symbol table already has a symbol with this name. If not,
// create a new symbol with this name and add it to the table. Note that we don't
// give the new symbol any flags *yet*. This ensures that it will not conflict
// with the 'excludes' flags we pass in.
//
// If we do get an existing symbol, see if it conflicts with the new symbol we're
// creating. For example, a 'var' symbol and a 'class' symbol will conflict within
// the same symbol table. If we have a conflict, report the issue on each
// declaration we have for this symbol, and then create a new symbol for this
// declaration.
//
// Note that when properties declared in Javascript constructors
// (marked by isReplaceableByMethod) conflict with another symbol, the property loses.
// Always. This allows the common Javascript pattern of overwriting a prototype method
// with an bound instance method of the same type: `this.method = this.method.bind(this)`
//
// If we created a new symbol, either because we didn't have a symbol with this name
// in the symbol table, or we conflicted with an existing symbol, then just add this
// node as the sole declaration of the new symbol.
//
// Otherwise, we'll be merging into a compatible existing symbol (for example when
// you have multiple 'vars' with the same name in the same container). In this case
// just add this node into the declarations list of the symbol.
symbol = symbolTable.get(name);
if (includes & SymbolFlags.Classifiable) {
classifiableNames.add(name);
}
if (!symbol) {
symbolTable.set(name, symbol = createSymbol(SymbolFlags.None, name));
if (isReplaceableByMethod) symbol.isReplaceableByMethod = true;
}
else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) {
// A symbol already exists, so don't add this as a declaration.
return symbol;
}
else if (symbol.flags & excludes) {
if (symbol.isReplaceableByMethod) {
// Javascript constructor-declared symbols can be discarded in favor of
// prototype symbols like methods.
symbolTable.set(name, symbol = createSymbol(SymbolFlags.None, name));
}
else if (!(includes & SymbolFlags.Variable && symbol.flags & SymbolFlags.Assignment)) {
// Assignment declarations are allowed to merge with variables, no matter what other flags they have.
if (isNamedDeclaration(node)) {
setParent(node.name, node);
}
// Report errors every position with duplicate declaration
// Report errors on previous encountered declarations
let message = symbol.flags & SymbolFlags.BlockScopedVariable
? Diagnostics.Cannot_redeclare_block_scoped_variable_0
: Diagnostics.Duplicate_identifier_0;
let messageNeedsName = true;
if (symbol.flags & SymbolFlags.Enum || includes & SymbolFlags.Enum) {
message = Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations;
messageNeedsName = false;
}
let multipleDefaultExports = false;
if (length(symbol.declarations)) {
// If the current node is a default export of some sort, then check if
// there are any other default exports that we need to error on.
// We'll know whether we have other default exports depending on if `symbol` already has a declaration list set.
if (isDefaultExport) {
message = Diagnostics.A_module_cannot_have_multiple_default_exports;
messageNeedsName = false;
multipleDefaultExports = true;
}
else {
// This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration.
// Error on multiple export default in the following case:
// 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default
// 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers)
if (
symbol.declarations && symbol.declarations.length &&
(node.kind === SyntaxKind.ExportAssignment && !(node as ExportAssignment).isExportEquals)
) {
message = Diagnostics.A_module_cannot_have_multiple_default_exports;
messageNeedsName = false;
multipleDefaultExports = true;
}
}
}
const relatedInformation: DiagnosticRelatedInformation[] = [];
if (isTypeAliasDeclaration(node) && nodeIsMissing(node.type) && hasSyntacticModifier(node, ModifierFlags.Export) && symbol.flags & (SymbolFlags.Alias | SymbolFlags.Type | SymbolFlags.Namespace)) {
// export type T; - may have meant export type { T }?
relatedInformation.push(createDiagnosticForNode(node, Diagnostics.Did_you_mean_0, `export type { ${unescapeLeadingUnderscores(node.name.escapedText)} }`));
}
const declarationName = getNameOfDeclaration(node) || node;
forEach(symbol.declarations, (declaration, index) => {
const decl = getNameOfDeclaration(declaration) || declaration;
const diag = messageNeedsName ? createDiagnosticForNode(decl, message, getDisplayName(declaration)) : createDiagnosticForNode(decl, message);
file.bindDiagnostics.push(
multipleDefaultExports ? addRelatedInfo(diag, createDiagnosticForNode(declarationName, index === 0 ? Diagnostics.Another_export_default_is_here : Diagnostics.and_here)) : diag,
);
if (multipleDefaultExports) {
relatedInformation.push(createDiagnosticForNode(decl, Diagnostics.The_first_export_default_is_here));
}
});
const diag = messageNeedsName ? createDiagnosticForNode(declarationName, message, getDisplayName(node)) : createDiagnosticForNode(declarationName, message);
file.bindDiagnostics.push(addRelatedInfo(diag, ...relatedInformation));
symbol = createSymbol(SymbolFlags.None, name);
}
}
}
addDeclarationToSymbol(symbol, node, includes);
if (symbol.parent) {
Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one");
}
else {
symbol.parent = parent;
}
return symbol;
}
function declareModuleMember(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags): Symbol {
const hasExportModifier = !!(getCombinedModifierFlags(node) & ModifierFlags.Export) || jsdocTreatAsExported(node);
if (symbolFlags & SymbolFlags.Alias) {
if (node.kind === SyntaxKind.ExportSpecifier || (node.kind === SyntaxKind.ImportEqualsDeclaration && hasExportModifier)) {
return declareSymbol(container.symbol.exports!, container.symbol, node, symbolFlags, symbolExcludes);
}
else {
Debug.assertNode(container, canHaveLocals);
return declareSymbol(container.locals!, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
}
else {
// Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag,
// and an associated export symbol with all the correct flags set on it. There are 2 main reasons:
//
// 1. We treat locals and exports of the same name as mutually exclusive within a container.
// That means the binder will issue a Duplicate Identifier error if you mix locals and exports
// with the same name in the same container.
// TODO: Make this a more specific error and decouple it from the exclusion logic.
// 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol,
// but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way
// when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope.
// NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge
// during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
// and this case is specially handled. Module augmentations should only be merged with original module definition
// and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
if (isJSDocTypeAlias(node)) Debug.assert(isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
if (!isAmbientModule(node) && (hasExportModifier || container.flags & NodeFlags.ExportContext)) {
if (!canHaveLocals(container) || !container.locals || (hasSyntacticModifier(node, ModifierFlags.Default) && !getDeclarationName(node))) {
return declareSymbol(container.symbol.exports!, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default!
}
const exportKind = symbolFlags & SymbolFlags.Value ? SymbolFlags.ExportValue : 0;
const local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes);
local.exportSymbol = declareSymbol(container.symbol.exports!, container.symbol, node, symbolFlags, symbolExcludes);
node.localSymbol = local;
return local;
}
else {
Debug.assertNode(container, canHaveLocals);
return declareSymbol(container.locals!, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
}
}
function jsdocTreatAsExported(node: Node) {
if (node.parent && isModuleDeclaration(node)) {
node = node.parent;
}
if (!isJSDocTypeAlias(node)) return false;
// jsdoc typedef handling is a bit of a doozy, but to summarize, treat the typedef as exported if:
// 1. It has an explicit name (since by default typedefs are always directly exported, either at the top level or in a container), or
if (!isJSDocEnumTag(node) && !!node.fullName) return true;
// 2. The thing a nameless typedef pulls its name from is implicitly a direct export (either by assignment or actual export flag).
const declName = getNameOfDeclaration(node);
if (!declName) return false;
if (isPropertyAccessEntityNameExpression(declName.parent) && isTopLevelNamespaceAssignment(declName.parent)) return true;
if (isDeclaration(declName.parent) && getCombinedModifierFlags(declName.parent) & ModifierFlags.Export) return true;
// This could potentially be simplified by having `delayedBindJSDocTypedefTag` pass in an override for `hasExportModifier`, since it should
// already have calculated and branched on most of this.
return false;
}
// All container nodes are kept on a linked list in declaration order. This list is used by
// the getLocalNameOfContainer function in the type checker to validate that the local name
// used for a container is unique.
function bindContainer(node: Mutable<HasContainerFlags>, containerFlags: ContainerFlags) {
// Before we recurse into a node's children, we first save the existing parent, container
// and block-container. Then after we pop out of processing the children, we restore
// these saved values.
const saveContainer = container;
const saveThisParentContainer = thisParentContainer;
const savedBlockScopeContainer = blockScopeContainer;
// Depending on what kind of node this is, we may have to adjust the current container
// and block-container. If the current node is a container, then it is automatically
// considered the current block-container as well. Also, for containers that we know
// may contain locals, we eagerly initialize the .locals field. We do this because
// it's highly likely that the .locals will be needed to place some child in (for example,
// a parameter, or variable declaration).
//
// However, we do not proactively create the .locals for block-containers because it's
// totally normal and common for block-containers to never actually have a block-scoped
// variable in them. We don't want to end up allocating an object for every 'block' we
// run into when most of them won't be necessary.
//
// Finally, if this is a block-container, then we clear out any existing .locals object
// it may contain within it. This happens in incremental scenarios. Because we can be
// reusing a node from a previous compilation, that node may have had 'locals' created
// for it. We must clear this so we don't accidentally move any stale data forward from
// a previous compilation.
if (containerFlags & ContainerFlags.IsContainer) {
if (node.kind !== SyntaxKind.ArrowFunction) {
thisParentContainer = container;
}
container = blockScopeContainer = node as IsContainer;
if (containerFlags & ContainerFlags.HasLocals) {
(container as HasLocals).locals = createSymbolTable();
addToContainerChain(container as HasLocals);
}