-
Notifications
You must be signed in to change notification settings - Fork 582
/
Copy pathutilities.go
2547 lines (2308 loc) · 93 KB
/
utilities.go
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
package checker
import (
"cmp"
"slices"
"strings"
"github.com/microsoft/typescript-go/internal/ast"
"github.com/microsoft/typescript-go/internal/binder"
"github.com/microsoft/typescript-go/internal/compiler/diagnostics"
"github.com/microsoft/typescript-go/internal/core"
"github.com/microsoft/typescript-go/internal/jsnum"
"github.com/microsoft/typescript-go/internal/scanner"
"github.com/microsoft/typescript-go/internal/tspath"
)
// Links store
type LinkStore[K comparable, V any] struct {
entries map[K]*V
pool core.Pool[V]
}
func (s *LinkStore[K, V]) get(key K) *V {
value := s.entries[key]
if value != nil {
return value
}
if s.entries == nil {
s.entries = make(map[K]*V)
}
value = s.pool.New()
s.entries[key] = value
return value
}
func (s *LinkStore[K, V]) has(key K) bool {
_, ok := s.entries[key]
return ok
}
func NewDiagnosticForNode(node *ast.Node, message *diagnostics.Message, args ...any) *ast.Diagnostic {
var file *ast.SourceFile
var loc core.TextRange
if node != nil {
file = ast.GetSourceFileOfNode(node)
loc = binder.GetErrorRangeForNode(file, node)
}
return ast.NewDiagnostic(file, loc, message, args...)
}
func NewDiagnosticChainForNode(chain *ast.Diagnostic, node *ast.Node, message *diagnostics.Message, args ...any) *ast.Diagnostic {
if chain != nil {
return ast.NewDiagnosticChain(chain, message, args...)
}
return NewDiagnosticForNode(node, message, args...)
}
func isIntrinsicJsxName(name string) bool {
if len(name) == 0 {
return false
}
ch := name[0]
return (ch >= 'a' && ch <= 'z') || strings.ContainsRune(name, '-')
}
func findInMap[K comparable, V any](m map[K]V, predicate func(V) bool) V {
for _, value := range m {
if predicate(value) {
return value
}
}
return *new(V)
}
func boolToTristate(b bool) core.Tristate {
if b {
return core.TSTrue
}
return core.TSFalse
}
func isCompoundAssignment(token ast.Kind) bool {
return token >= ast.KindFirstCompoundAssignment && token <= ast.KindLastCompoundAssignment
}
func tokenIsIdentifierOrKeyword(token ast.Kind) bool {
return token >= ast.KindIdentifier
}
func tokenIsIdentifierOrKeywordOrGreaterThan(token ast.Kind) bool {
return token == ast.KindGreaterThanToken || tokenIsIdentifierOrKeyword(token)
}
func isCommonJSContainingModuleKind(kind core.ModuleKind) bool {
return kind == core.ModuleKindCommonJS || kind == core.ModuleKindNode16 || kind == core.ModuleKindNodeNext
}
/** @internal */
func isEffectiveExternalModule(node *ast.SourceFile, compilerOptions *core.CompilerOptions) bool {
return ast.IsExternalModule(node) || (isCommonJSContainingModuleKind(compilerOptions.GetEmitModuleKind()) && node.CommonJsModuleIndicator != nil)
}
func hasOverrideModifier(node *ast.Node) bool {
return ast.HasSyntacticModifier(node, ast.ModifierFlagsOverride)
}
func hasAbstractModifier(node *ast.Node) bool {
return ast.HasSyntacticModifier(node, ast.ModifierFlagsAbstract)
}
func hasAmbientModifier(node *ast.Node) bool {
return ast.HasSyntacticModifier(node, ast.ModifierFlagsAmbient)
}
func hasAsyncModifier(node *ast.Node) bool {
return ast.HasSyntacticModifier(node, ast.ModifierFlagsAsync)
}
func hasDecorators(node *ast.Node) bool {
return ast.HasSyntacticModifier(node, ast.ModifierFlagsDecorator)
}
func getEffectiveModifierFlags(node *ast.Node) ast.ModifierFlags {
return node.ModifierFlags() // !!! Handle JSDoc
}
func getSelectedEffectiveModifierFlags(node *ast.Node, flags ast.ModifierFlags) ast.ModifierFlags {
return getEffectiveModifierFlags(node) & flags
}
func hasEffectiveModifier(node *ast.Node, flags ast.ModifierFlags) bool {
return getEffectiveModifierFlags(node)&flags != 0
}
func hasEffectiveReadonlyModifier(node *ast.Node) bool {
return hasEffectiveModifier(node, ast.ModifierFlagsReadonly)
}
func isBindingElementOfBareOrAccessedRequire(node *ast.Node) bool {
return ast.IsBindingElement(node) && isVariableDeclarationInitializedToBareOrAccessedRequire(node.Parent.Parent)
}
/**
* Like {@link isVariableDeclarationInitializedToRequire} but allows things like `require("...").foo.bar` or `require("...")["baz"]`.
*/
func isVariableDeclarationInitializedToBareOrAccessedRequire(node *ast.Node) bool {
return isVariableDeclarationInitializedWithRequireHelper(node, true /*allowAccessedRequire*/)
}
func isVariableDeclarationInitializedWithRequireHelper(node *ast.Node, allowAccessedRequire bool) bool {
if node.Kind == ast.KindVariableDeclaration && node.AsVariableDeclaration().Initializer != nil {
initializer := node.AsVariableDeclaration().Initializer
if allowAccessedRequire {
initializer = getLeftmostAccessExpression(initializer)
}
return ast.IsRequireCall(initializer, true /*requireStringLiteralLikeArgument*/)
}
return false
}
func getLeftmostAccessExpression(expr *ast.Node) *ast.Node {
for ast.IsAccessExpression(expr) {
expr = expr.Expression()
}
return expr
}
func isStaticPrivateIdentifierProperty(s *ast.Symbol) bool {
return s.ValueDeclaration != nil && ast.IsPrivateIdentifierClassElementDeclaration(s.ValueDeclaration) && ast.IsStatic(s.ValueDeclaration)
}
func isEmptyObjectLiteral(expression *ast.Node) bool {
return expression.Kind == ast.KindObjectLiteralExpression && len(expression.AsObjectLiteralExpression().Properties.Nodes) == 0
}
type AssignmentKind int32
const (
AssignmentKindNone AssignmentKind = iota
AssignmentKindDefinite
AssignmentKindCompound
)
type AssignmentTarget = ast.Node // BinaryExpression | PrefixUnaryExpression | PostfixUnaryExpression | ForInOrOfStatement
func getAssignmentTargetKind(node *ast.Node) AssignmentKind {
target := ast.GetAssignmentTarget(node)
if target == nil {
return AssignmentKindNone
}
switch target.Kind {
case ast.KindBinaryExpression:
binaryOperator := target.AsBinaryExpression().OperatorToken.Kind
if binaryOperator == ast.KindEqualsToken || ast.IsLogicalOrCoalescingAssignmentOperator(binaryOperator) {
return AssignmentKindDefinite
}
return AssignmentKindCompound
case ast.KindPrefixUnaryExpression, ast.KindPostfixUnaryExpression:
return AssignmentKindCompound
case ast.KindForInStatement, ast.KindForOfStatement:
return AssignmentKindDefinite
}
panic("Unhandled case in getAssignmentTargetKind")
}
func isDeleteTarget(node *ast.Node) bool {
if !ast.IsAccessExpression(node) {
return false
}
node = ast.WalkUpParenthesizedExpressions(node.Parent)
return node != nil && node.Kind == ast.KindDeleteExpression
}
func isInCompoundLikeAssignment(node *ast.Node) bool {
target := ast.GetAssignmentTarget(node)
return target != nil && ast.IsAssignmentExpression(target /*excludeCompoundAssignment*/, true) && isCompoundLikeAssignment(target)
}
func isCompoundLikeAssignment(assignment *ast.Node) bool {
right := ast.SkipParentheses(assignment.AsBinaryExpression().Right)
return right.Kind == ast.KindBinaryExpression && isShiftOperatorOrHigher(right.AsBinaryExpression().OperatorToken.Kind)
}
func getAssertedTypeNode(node *ast.Node) *ast.Node {
switch node.Kind {
case ast.KindAsExpression:
return node.AsAsExpression().Type
case ast.KindSatisfiesExpression:
return node.AsSatisfiesExpression().Type
case ast.KindTypeAssertionExpression:
return node.AsTypeAssertion().Type
}
panic("Unhandled case in getAssertedTypeNode")
}
func isConstAssertion(node *ast.Node) bool {
switch node.Kind {
case ast.KindAsExpression, ast.KindTypeAssertionExpression:
return isConstTypeReference(getAssertedTypeNode(node))
}
return false
}
func isConstTypeReference(node *ast.Node) bool {
return ast.IsTypeReferenceNode(node) && len(node.TypeArguments()) == 0 && ast.IsIdentifier(node.AsTypeReferenceNode().TypeName) && node.AsTypeReferenceNode().TypeName.Text() == "const"
}
func isModuleOrEnumDeclaration(node *ast.Node) bool {
return node.Kind == ast.KindModuleDeclaration || node.Kind == ast.KindEnumDeclaration
}
func isGlobalSourceFile(node *ast.Node) bool {
return node.Kind == ast.KindSourceFile && !ast.IsExternalOrCommonJsModule(node.AsSourceFile())
}
func isParameterLikeOrReturnTag(node *ast.Node) bool {
switch node.Kind {
case ast.KindParameter, ast.KindTypeParameter, ast.KindJSDocParameterTag, ast.KindJSDocReturnTag:
return true
}
return false
}
func getEmitStandardClassFields(options *core.CompilerOptions) bool {
return options.UseDefineForClassFields != core.TSFalse && options.GetEmitScriptTarget() >= core.ScriptTargetES2022
}
func getLocalSymbolForExportDefault(symbol *ast.Symbol) *ast.Symbol {
if !isExportDefaultSymbol(symbol) || len(symbol.Declarations) == 0 {
return nil
}
for _, decl := range symbol.Declarations {
localSymbol := decl.LocalSymbol()
if localSymbol != nil {
return localSymbol
}
}
return nil
}
func isExportDefaultSymbol(symbol *ast.Symbol) bool {
return symbol != nil && len(symbol.Declarations) > 0 && ast.HasSyntacticModifier(symbol.Declarations[0], ast.ModifierFlagsDefault)
}
func getDeclarationOfKind(symbol *ast.Symbol, kind ast.Kind) *ast.Node {
for _, declaration := range symbol.Declarations {
if declaration.Kind == kind {
return declaration
}
}
return nil
}
func getIsolatedModules(options *core.CompilerOptions) bool {
return options.IsolatedModules == core.TSTrue || options.VerbatimModuleSyntax == core.TSTrue
}
func findConstructorDeclaration(node *ast.Node) *ast.Node {
for _, member := range node.ClassLikeData().Members.Nodes {
if ast.IsConstructorDeclaration(member) && ast.NodeIsPresent(member.AsConstructorDeclaration().Body) {
return member
}
}
return nil
}
func getSingleVariableOfVariableStatement(node *ast.Node) *ast.Node {
if !ast.IsVariableStatement(node) {
return nil
}
return core.FirstOrNil(node.AsVariableStatement().DeclarationList.AsVariableDeclarationList().Declarations.Nodes)
}
type NameResolver struct {
compilerOptions *core.CompilerOptions
getSymbolOfDeclaration func(node *ast.Node) *ast.Symbol
error func(location *ast.Node, message *diagnostics.Message, args ...any) *ast.Diagnostic
globals ast.SymbolTable
argumentsSymbol *ast.Symbol
requireSymbol *ast.Symbol
lookup func(symbols ast.SymbolTable, name string, meaning ast.SymbolFlags) *ast.Symbol
symbolReferenced func(symbol *ast.Symbol, meaning ast.SymbolFlags)
setRequiresScopeChangeCache func(node *ast.Node, value core.Tristate)
getRequiresScopeChangeCache func(node *ast.Node) core.Tristate
onPropertyWithInvalidInitializer func(location *ast.Node, name string, declaration *ast.Node, result *ast.Symbol) bool
onFailedToResolveSymbol func(location *ast.Node, name string, meaning ast.SymbolFlags, nameNotFoundMessage *diagnostics.Message)
onSuccessfullyResolvedSymbol func(location *ast.Node, result *ast.Symbol, meaning ast.SymbolFlags, lastLocation *ast.Node, associatedDeclarationForContainingInitializerOrBindingName *ast.Node, withinDeferredContext bool)
}
func (r *NameResolver) resolve(location *ast.Node, name string, meaning ast.SymbolFlags, nameNotFoundMessage *diagnostics.Message, isUse bool, excludeGlobals bool) *ast.Symbol {
var result *ast.Symbol
var lastLocation *ast.Node
var lastSelfReferenceLocation *ast.Node
var propertyWithInvalidInitializer *ast.Node
var associatedDeclarationForContainingInitializerOrBindingName *ast.Node
var withinDeferredContext bool
var grandparent *ast.Node
originalLocation := location // needed for did-you-mean error reporting, which gathers candidates starting from the original location
nameIsConst := name == "const"
loop:
for location != nil {
if nameIsConst && isConstAssertion(location) {
// `const` in an `as const` has no symbol, but issues no error because there is no *actual* lookup of the type
// (it refers to the constant type of the expression instead)
return nil
}
if isModuleOrEnumDeclaration(location) && lastLocation != nil && location.Name() == lastLocation {
// If lastLocation is the name of a namespace or enum, skip the parent since it will have is own locals that could
// conflict.
lastLocation = location
location = location.Parent
}
locals := location.Locals()
// Locals of a source file are not in scope (because they get merged into the global symbol table)
if locals != nil && !isGlobalSourceFile(location) {
result = r.lookup(locals, name, meaning)
if result != nil {
useResult := true
if ast.IsFunctionLike(location) && lastLocation != nil && lastLocation != location.Body() {
// symbol lookup restrictions for function-like declarations
// - Type parameters of a function are in scope in the entire function declaration, including the parameter
// list and return type. However, local types are only in scope in the function body.
// - parameters are only in the scope of function body
// This restriction does not apply to JSDoc comment types because they are parented
// at a higher level than type parameters would normally be
if meaning&result.Flags&ast.SymbolFlagsType != 0 && lastLocation.Kind != ast.KindJSDoc {
useResult = result.Flags&ast.SymbolFlagsTypeParameter != 0 && (lastLocation.Flags&ast.NodeFlagsSynthesized != 0 ||
lastLocation == location.Type() ||
isParameterLikeOrReturnTag(lastLocation))
}
if meaning&result.Flags&ast.SymbolFlagsVariable != 0 {
// expression inside parameter will lookup as normal variable scope when targeting es2015+
if r.useOuterVariableScopeInParameter(result, location, lastLocation) {
useResult = false
} else if result.Flags&ast.SymbolFlagsFunctionScopedVariable != 0 {
// parameters are visible only inside function body, parameter list and return type
// technically for parameter list case here we might mix parameters and variables declared in function,
// however it is detected separately when checking initializers of parameters
// to make sure that they reference no variables declared after them.
useResult = lastLocation.Kind == ast.KindParameter ||
lastLocation.Flags&ast.NodeFlagsSynthesized != 0 ||
lastLocation == location.Type() && ast.FindAncestor(result.ValueDeclaration, ast.IsParameter) != nil
}
}
} else if location.Kind == ast.KindConditionalType {
// A type parameter declared using 'infer T' in a conditional type is visible only in
// the true branch of the conditional type.
useResult = lastLocation == location.AsConditionalTypeNode().TrueType
}
if useResult {
break loop
}
result = nil
}
}
withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation)
switch location.Kind {
case ast.KindSourceFile:
if !ast.IsExternalOrCommonJsModule(location.AsSourceFile()) {
break
}
fallthrough
case ast.KindModuleDeclaration:
moduleExports := r.getSymbolOfDeclaration(location).Exports
if ast.IsSourceFile(location) || (ast.IsModuleDeclaration(location) && location.Flags&ast.NodeFlagsAmbient != 0 && !ast.IsGlobalScopeAugmentation(location)) {
// It's an external module. First see if the module has an export default and if the local
// name of that export default matches.
result = moduleExports[ast.InternalSymbolNameDefault]
if result != nil {
localSymbol := getLocalSymbolForExportDefault(result)
if localSymbol != nil && result.Flags&meaning != 0 && localSymbol.Name == name {
break loop
}
result = nil
}
// Because of module/namespace merging, a module's exports are in scope,
// yet we never want to treat an export specifier as putting a member in scope.
// Therefore, if the name we find is purely an export specifier, it is not actually considered in scope.
// Two things to note about this:
// 1. We have to check this without calling getSymbol. The problem with calling getSymbol
// on an export specifier is that it might find the export specifier itself, and try to
// resolve it as an alias. This will cause the checker to consider the export specifier
// a circular alias reference when it might not be.
// 2. We check === SymbolFlags.Alias in order to check that the symbol is *purely*
// an alias. If we used &, we'd be throwing out symbols that have non alias aspects,
// which is not the desired behavior.
moduleExport := moduleExports[name]
if moduleExport != nil && moduleExport.Flags == ast.SymbolFlagsAlias && (getDeclarationOfKind(moduleExport, ast.KindExportSpecifier) != nil || getDeclarationOfKind(moduleExport, ast.KindNamespaceExport) != nil) {
break
}
}
if name != ast.InternalSymbolNameDefault {
result = r.lookup(moduleExports, name, meaning&ast.SymbolFlagsModuleMember)
if result != nil {
break loop
}
}
case ast.KindEnumDeclaration:
result = r.lookup(r.getSymbolOfDeclaration(location).Exports, name, meaning&ast.SymbolFlagsEnumMember)
if result != nil {
if nameNotFoundMessage != nil && getIsolatedModules(r.compilerOptions) && location.Flags&ast.NodeFlagsAmbient == 0 && ast.GetSourceFileOfNode(location) != ast.GetSourceFileOfNode(result.ValueDeclaration) {
isolatedModulesLikeFlagName := core.IfElse(r.compilerOptions.VerbatimModuleSyntax == core.TSTrue, "verbatimModuleSyntax", "isolatedModules")
r.error(originalLocation, diagnostics.Cannot_access_0_from_another_file_without_qualification_when_1_is_enabled_Use_2_instead,
name, isolatedModulesLikeFlagName, r.getSymbolOfDeclaration(location).Name+"."+name)
}
break loop
}
case ast.KindPropertyDeclaration:
if !ast.IsStatic(location) {
ctor := findConstructorDeclaration(location.Parent)
if ctor != nil && ctor.Locals() != nil {
if r.lookup(ctor.Locals(), name, meaning&ast.SymbolFlagsValue) != nil {
// Remember the property node, it will be used later to report appropriate error
propertyWithInvalidInitializer = location
}
}
}
case ast.KindClassDeclaration, ast.KindClassExpression, ast.KindInterfaceDeclaration:
result = r.lookup(r.getSymbolOfDeclaration(location).Members, name, meaning&ast.SymbolFlagsType)
if result != nil {
if !isTypeParameterSymbolDeclaredInContainer(result, location) {
// ignore type parameters not declared in this container
result = nil
break
}
if lastLocation != nil && ast.IsStatic(lastLocation) {
// TypeScript 1.0 spec (April 2014): 3.4.1
// The scope of a type parameter extends over the entire declaration with which the type
// parameter list is associated, with the exception of static member declarations in classes.
if nameNotFoundMessage != nil {
r.error(originalLocation, diagnostics.Static_members_cannot_reference_class_type_parameters)
}
return nil
}
break loop
}
if ast.IsClassExpression(location) && meaning&ast.SymbolFlagsClass != 0 {
className := location.Name()
if className != nil && name == className.Text() {
result = location.Symbol()
break loop
}
}
case ast.KindExpressionWithTypeArguments:
if lastLocation == location.AsExpressionWithTypeArguments().Expression && ast.IsHeritageClause(location.Parent) && location.Parent.AsHeritageClause().Token == ast.KindExtendsKeyword {
container := location.Parent.Parent
if ast.IsClassLike(container) {
result = r.lookup(r.getSymbolOfDeclaration(container).Members, name, meaning&ast.SymbolFlagsType)
if result != nil {
if nameNotFoundMessage != nil {
r.error(originalLocation, diagnostics.Base_class_expressions_cannot_reference_class_type_parameters)
}
return nil
}
}
}
// It is not legal to reference a class's own type parameters from a computed property name that
// belongs to the class. For example:
//
// function foo<T>() { return '' }
// class C<T> { // <-- Class's own type parameter T
// [foo<T>()]() { } // <-- Reference to T from class's own computed property
// }
case ast.KindComputedPropertyName:
grandparent = location.Parent.Parent
if ast.IsClassLike(grandparent) || ast.IsInterfaceDeclaration(grandparent) {
// A reference to this grandparent's type parameters would be an error
result = r.lookup(r.getSymbolOfDeclaration(grandparent).Members, name, meaning&ast.SymbolFlagsType)
if result != nil {
if nameNotFoundMessage != nil {
r.error(originalLocation, diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type)
}
return nil
}
}
case ast.KindArrowFunction:
// when targeting ES6 or higher there is no 'arguments' in an arrow function
// for lower compile targets the resolved symbol is used to emit an error
if r.compilerOptions.GetEmitScriptTarget() >= core.ScriptTargetES2015 {
break
}
fallthrough
case ast.KindMethodDeclaration, ast.KindConstructor, ast.KindGetAccessor, ast.KindSetAccessor, ast.KindFunctionDeclaration:
if meaning&ast.SymbolFlagsVariable != 0 && name == "arguments" {
result = r.argumentsSymbol
break loop
}
case ast.KindFunctionExpression:
if meaning&ast.SymbolFlagsVariable != 0 && name == "arguments" {
result = r.argumentsSymbol
break loop
}
if meaning&ast.SymbolFlagsFunction != 0 {
functionName := location.AsFunctionExpression().Name()
if functionName != nil && name == functionName.AsIdentifier().Text {
result = location.AsFunctionExpression().Symbol
break loop
}
}
case ast.KindDecorator:
// Decorators are resolved at the class declaration. Resolving at the parameter
// or member would result in looking up locals in the method.
//
// function y() {}
// class C {
// method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter.
// }
//
if location.Parent != nil && location.Parent.Kind == ast.KindParameter {
location = location.Parent
}
// function y() {}
// class C {
// @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method.
// }
//
// class Decorators are resolved outside of the class to avoid referencing type parameters of that class.
//
// type T = number;
// declare function y(x: T): any;
// @param(1 as T) // <-- T should resolve to the type alias outside of class C
// class C<T> {}
if location.Parent != nil && (ast.IsClassElement(location.Parent) || location.Parent.Kind == ast.KindClassDeclaration) {
location = location.Parent
}
case ast.KindParameter:
parameterDeclaration := location.AsParameterDeclaration()
if lastLocation != nil && (lastLocation == parameterDeclaration.Initializer ||
lastLocation == parameterDeclaration.Name() && ast.IsBindingPattern(lastLocation)) {
if associatedDeclarationForContainingInitializerOrBindingName == nil {
associatedDeclarationForContainingInitializerOrBindingName = location
}
}
case ast.KindBindingElement:
bindingElement := location.AsBindingElement()
if lastLocation != nil && (lastLocation == bindingElement.Initializer ||
lastLocation == bindingElement.Name() && ast.IsBindingPattern(lastLocation)) {
if ast.IsPartOfParameterDeclaration(location) && associatedDeclarationForContainingInitializerOrBindingName == nil {
associatedDeclarationForContainingInitializerOrBindingName = location
}
}
case ast.KindInferType:
if meaning&ast.SymbolFlagsTypeParameter != 0 {
parameterName := location.AsInferTypeNode().TypeParameter.AsTypeParameter().Name()
if parameterName != nil && name == parameterName.AsIdentifier().Text {
result = location.AsInferTypeNode().TypeParameter.AsTypeParameter().Symbol
break loop
}
}
case ast.KindExportSpecifier:
exportSpecifier := location.AsExportSpecifier()
if lastLocation != nil && lastLocation == exportSpecifier.PropertyName && location.Parent.Parent.AsExportDeclaration().ModuleSpecifier != nil {
location = location.Parent.Parent.Parent
}
}
if isSelfReferenceLocation(location, lastLocation) {
lastSelfReferenceLocation = location
}
lastLocation = location
switch {
// case isJSDocTemplateTag(location):
// location = getEffectiveContainerForJSDocTemplateTag(location.(*JSDocTemplateTag))
// if location == nil {
// location = location.parent
// }
// case isJSDocParameterTag(location) || isJSDocReturnTag(location):
// location = getHostSignatureFromJSDoc(location)
// if location == nil {
// location = location.parent
// }
default:
location = location.Parent
}
}
// We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`.
// If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself.
// That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used.
if isUse && result != nil && (lastSelfReferenceLocation == nil || result != lastSelfReferenceLocation.Symbol()) {
r.symbolReferenced(result, meaning)
}
if result == nil {
if !excludeGlobals {
result = r.lookup(r.globals, name, meaning)
}
}
if nameNotFoundMessage != nil {
if propertyWithInvalidInitializer != nil && r.onPropertyWithInvalidInitializer(originalLocation, name, propertyWithInvalidInitializer, result) {
return nil
}
if result == nil {
r.onFailedToResolveSymbol(originalLocation, name, meaning, nameNotFoundMessage)
} else {
r.onSuccessfullyResolvedSymbol(originalLocation, result, meaning, lastLocation, associatedDeclarationForContainingInitializerOrBindingName, withinDeferredContext)
}
}
return result
}
func (r *NameResolver) useOuterVariableScopeInParameter(result *ast.Symbol, location *ast.Node, lastLocation *ast.Node) bool {
if ast.IsParameter(lastLocation) {
body := location.Body()
if body != nil && result.ValueDeclaration != nil && result.ValueDeclaration.Pos() >= body.Pos() && result.ValueDeclaration.End() <= body.End() {
// check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body
// - static field in a class expression
// - optional chaining pre-es2020
// - nullish coalesce pre-es2020
// - spread assignment in binding pattern pre-es2017
target := r.compilerOptions.GetEmitScriptTarget()
if target >= core.ScriptTargetES2015 {
functionLocation := location
declarationRequiresScopeChange := r.getRequiresScopeChangeCache(functionLocation)
if declarationRequiresScopeChange == core.TSUnknown {
declarationRequiresScopeChange = boolToTristate(core.Some(functionLocation.Parameters(), r.requiresScopeChange))
r.setRequiresScopeChangeCache(functionLocation, declarationRequiresScopeChange)
}
return declarationRequiresScopeChange == core.TSTrue
}
}
}
return false
}
func (r *NameResolver) requiresScopeChange(node *ast.Node) bool {
d := node.AsParameterDeclaration()
return r.requiresScopeChangeWorker(d.Name()) || d.Initializer != nil && r.requiresScopeChangeWorker(d.Initializer)
}
func (r *NameResolver) requiresScopeChangeWorker(node *ast.Node) bool {
switch node.Kind {
case ast.KindArrowFunction, ast.KindFunctionExpression, ast.KindFunctionDeclaration, ast.KindConstructor:
return false
case ast.KindMethodDeclaration, ast.KindGetAccessor, ast.KindSetAccessor, ast.KindPropertyAssignment:
return r.requiresScopeChangeWorker(node.Name())
case ast.KindPropertyDeclaration:
if ast.HasStaticModifier(node) {
return !getEmitStandardClassFields(r.compilerOptions)
}
return r.requiresScopeChangeWorker(node.AsPropertyDeclaration().Name())
default:
if ast.IsNullishCoalesce(node) || ast.IsOptionalChain(node) {
return r.compilerOptions.GetEmitScriptTarget() < core.ScriptTargetES2020
}
if ast.IsBindingElement(node) && node.AsBindingElement().DotDotDotToken != nil && ast.IsObjectBindingPattern(node.Parent) {
return r.compilerOptions.GetEmitScriptTarget() < core.ScriptTargetES2017
}
if ast.IsTypeNode(node) {
return false
}
return node.ForEachChild(r.requiresScopeChangeWorker)
}
}
func getIsDeferredContext(location *ast.Node, lastLocation *ast.Node) bool {
if location.Kind != ast.KindArrowFunction && location.Kind != ast.KindFunctionExpression {
// initializers in instance property declaration of class like entities are executed in constructor and thus deferred
// A name is evaluated within the enclosing scope - so it shouldn't count as deferred
return ast.IsTypeQueryNode(location) ||
(ast.IsFunctionLikeDeclaration(location) || location.Kind == ast.KindPropertyDeclaration && !ast.IsStatic(location)) &&
(lastLocation == nil || lastLocation != location.Name())
}
if lastLocation != nil && lastLocation == location.Name() {
return false
}
// generator functions and async functions are not inlined in control flow when immediately invoked
if location.BodyData().AsteriskToken != nil || ast.HasSyntacticModifier(location, ast.ModifierFlagsAsync) {
return true
}
return ast.GetImmediatelyInvokedFunctionExpression(location) == nil
}
func isTypeParameterSymbolDeclaredInContainer(symbol *ast.Symbol, container *ast.Node) bool {
for _, decl := range symbol.Declarations {
if decl.Kind == ast.KindTypeParameter {
parent := decl.Parent
if parent == container {
return true
}
}
}
return false
}
func isSelfReferenceLocation(node *ast.Node, lastLocation *ast.Node) bool {
switch node.Kind {
case ast.KindParameter:
return lastLocation != nil && lastLocation == node.AsParameterDeclaration().Name()
case ast.KindFunctionDeclaration, ast.KindClassDeclaration, ast.KindInterfaceDeclaration, ast.KindEnumDeclaration,
ast.KindTypeAliasDeclaration, ast.KindModuleDeclaration: // For `namespace N { N; }`
return true
}
return false
}
func isTypeReferenceIdentifier(node *ast.Node) bool {
for node.Parent.Kind == ast.KindQualifiedName {
node = node.Parent
}
return ast.IsTypeReferenceNode(node.Parent)
}
func isInTypeQuery(node *ast.Node) bool {
// TypeScript 1.0 spec (April 2014): 3.6.3
// A type query consists of the keyword typeof followed by an expression.
// The expression is restricted to a single identifier or a sequence of identifiers separated by periods
return ast.FindAncestorOrQuit(node, func(n *ast.Node) ast.FindAncestorResult {
switch n.Kind {
case ast.KindTypeQuery:
return ast.FindAncestorTrue
case ast.KindIdentifier, ast.KindQualifiedName:
return ast.FindAncestorFalse
}
return ast.FindAncestorQuit
}) != nil
}
func isTypeOnlyImportDeclaration(node *ast.Node) bool {
switch node.Kind {
case ast.KindImportSpecifier:
return node.AsImportSpecifier().IsTypeOnly || node.Parent.Parent.AsImportClause().IsTypeOnly
case ast.KindNamespaceImport:
return node.Parent.AsImportClause().IsTypeOnly
case ast.KindImportClause:
return node.AsImportClause().IsTypeOnly
case ast.KindImportEqualsDeclaration:
return node.AsImportEqualsDeclaration().IsTypeOnly
}
return false
}
func isTypeOnlyExportDeclaration(node *ast.Node) bool {
switch node.Kind {
case ast.KindExportSpecifier:
return node.AsExportSpecifier().IsTypeOnly || node.Parent.Parent.AsExportDeclaration().IsTypeOnly
case ast.KindExportDeclaration:
d := node.AsExportDeclaration()
return d.IsTypeOnly && d.ModuleSpecifier != nil && d.ExportClause == nil
case ast.KindNamespaceExport:
return node.Parent.AsExportDeclaration().IsTypeOnly
}
return false
}
func isTypeOnlyImportOrExportDeclaration(node *ast.Node) bool {
return isTypeOnlyImportDeclaration(node) || isTypeOnlyExportDeclaration(node)
}
func getNameFromImportDeclaration(node *ast.Node) *ast.Node {
switch node.Kind {
case ast.KindImportSpecifier:
return node.AsImportSpecifier().Name()
case ast.KindNamespaceImport:
return node.AsNamespaceImport().Name()
case ast.KindImportClause:
return node.AsImportClause().Name()
case ast.KindImportEqualsDeclaration:
return node.AsImportEqualsDeclaration().Name()
}
return nil
}
func isValidTypeOnlyAliasUseSite(useSite *ast.Node) bool {
return useSite.Flags&ast.NodeFlagsAmbient != 0 ||
ast.IsPartOfTypeQuery(useSite) ||
isIdentifierInNonEmittingHeritageClause(useSite) ||
isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(useSite) ||
!(ast.IsExpressionNode(useSite) || isShorthandPropertyNameUseSite(useSite))
}
func isIdentifierInNonEmittingHeritageClause(node *ast.Node) bool {
if !ast.IsIdentifier(node) {
return false
}
parent := node.Parent
for ast.IsPropertyAccessExpression(parent) || ast.IsExpressionWithTypeArguments(parent) {
parent = parent.Parent
}
return ast.IsHeritageClause(parent) && (parent.AsHeritageClause().Token == ast.KindImplementsKeyword || ast.IsInterfaceDeclaration(parent.Parent))
}
func isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node *ast.Node) bool {
for ast.NodeKindIs(node, ast.KindIdentifier, ast.KindPropertyAccessExpression) {
node = node.Parent
}
if node.Kind != ast.KindComputedPropertyName {
return false
}
if ast.HasSyntacticModifier(node.Parent, ast.ModifierFlagsAbstract) {
return true
}
return ast.NodeKindIs(node.Parent.Parent, ast.KindInterfaceDeclaration, ast.KindTypeLiteral)
}
func nodeCanBeDecorated(useLegacyDecorators bool, node *ast.Node, parent *ast.Node, grandparent *ast.Node) bool {
// private names cannot be used with decorators yet
if useLegacyDecorators && node.Name() != nil && ast.IsPrivateIdentifier(node.Name()) {
return false
}
switch node.Kind {
case ast.KindClassDeclaration:
// class declarations are valid targets
return true
case ast.KindClassExpression:
// class expressions are valid targets for native decorators
return !useLegacyDecorators
case ast.KindPropertyDeclaration:
// property declarations are valid if their parent is a class declaration.
return parent != nil && (ast.IsClassDeclaration(parent) || !useLegacyDecorators && ast.IsClassExpression(parent) && !hasAbstractModifier(node) && !hasAmbientModifier(node))
case ast.KindGetAccessor,
ast.KindSetAccessor,
ast.KindMethodDeclaration:
// if this method has a body and its parent is a class declaration, this is a valid target.
return node.BodyData() != nil && parent != nil && (ast.IsClassDeclaration(parent) || !useLegacyDecorators && ast.IsClassExpression(parent))
case ast.KindParameter:
// TODO(rbuckton): Parameter decorator support for ES decorators must wait until it is standardized
if !useLegacyDecorators {
return false
}
// if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target.
return parent != nil && parent.BodyData() != nil && (parent.BodyData()).Body != nil && (parent.Kind == ast.KindConstructor || parent.Kind == ast.KindMethodDeclaration || parent.Kind == ast.KindSetAccessor) && getThisParameter(parent) != node && grandparent != nil && grandparent.Kind == ast.KindClassDeclaration
}
return false
}
func isShorthandPropertyNameUseSite(useSite *ast.Node) bool {
return ast.IsIdentifier(useSite) && ast.IsShorthandPropertyAssignment(useSite.Parent) && useSite.Parent.AsShorthandPropertyAssignment().Name() == useSite
}
func isTypeDeclaration(node *ast.Node) bool {
switch node.Kind {
case ast.KindTypeParameter, ast.KindClassDeclaration, ast.KindInterfaceDeclaration, ast.KindTypeAliasDeclaration, ast.KindEnumDeclaration:
return true
case ast.KindImportClause:
return node.AsImportClause().IsTypeOnly
case ast.KindImportSpecifier:
return node.Parent.Parent.AsImportClause().IsTypeOnly
case ast.KindExportSpecifier:
return node.Parent.Parent.AsExportDeclaration().IsTypeOnly
default:
return false
}
}
func canHaveSymbol(node *ast.Node) bool {
switch node.Kind {
case ast.KindArrowFunction, ast.KindBinaryExpression, ast.KindBindingElement, ast.KindCallExpression, ast.KindCallSignature,
ast.KindClassDeclaration, ast.KindClassExpression, ast.KindClassStaticBlockDeclaration, ast.KindConstructor, ast.KindConstructorType,
ast.KindConstructSignature, ast.KindElementAccessExpression, ast.KindEnumDeclaration, ast.KindEnumMember, ast.KindExportAssignment,
ast.KindExportDeclaration, ast.KindExportSpecifier, ast.KindFunctionDeclaration, ast.KindFunctionExpression, ast.KindFunctionType,
ast.KindGetAccessor, ast.KindIdentifier, ast.KindImportClause, ast.KindImportEqualsDeclaration, ast.KindImportSpecifier,
ast.KindIndexSignature, ast.KindInterfaceDeclaration, ast.KindJSDocCallbackTag,
ast.KindJSDocParameterTag, ast.KindJSDocPropertyTag, ast.KindJSDocSignature, ast.KindJSDocTypedefTag, ast.KindJSDocTypeLiteral,
ast.KindJsxAttribute, ast.KindJsxAttributes, ast.KindJsxSpreadAttribute, ast.KindMappedType, ast.KindMethodDeclaration,
ast.KindMethodSignature, ast.KindModuleDeclaration, ast.KindNamedTupleMember, ast.KindNamespaceExport, ast.KindNamespaceExportDeclaration,
ast.KindNamespaceImport, ast.KindNewExpression, ast.KindNoSubstitutionTemplateLiteral, ast.KindNumericLiteral, ast.KindObjectLiteralExpression,
ast.KindParameter, ast.KindPropertyAccessExpression, ast.KindPropertyAssignment, ast.KindPropertyDeclaration, ast.KindPropertySignature,
ast.KindSetAccessor, ast.KindShorthandPropertyAssignment, ast.KindSourceFile, ast.KindSpreadAssignment, ast.KindStringLiteral,
ast.KindTypeAliasDeclaration, ast.KindTypeLiteral, ast.KindTypeParameter, ast.KindVariableDeclaration:
return true
}
return false
}
func canHaveLocals(node *ast.Node) bool {
switch node.Kind {
case ast.KindArrowFunction, ast.KindBlock, ast.KindCallSignature, ast.KindCaseBlock, ast.KindCatchClause,
ast.KindClassStaticBlockDeclaration, ast.KindConditionalType, ast.KindConstructor, ast.KindConstructorType,
ast.KindConstructSignature, ast.KindForStatement, ast.KindForInStatement, ast.KindForOfStatement, ast.KindFunctionDeclaration,
ast.KindFunctionExpression, ast.KindFunctionType, ast.KindGetAccessor, ast.KindIndexSignature, ast.KindJSDocCallbackTag,
ast.KindJSDocSignature, ast.KindJSDocTypedefTag, ast.KindMappedType,
ast.KindMethodDeclaration, ast.KindMethodSignature, ast.KindModuleDeclaration, ast.KindSetAccessor, ast.KindSourceFile,
ast.KindTypeAliasDeclaration:
return true
}
return false
}
func isShorthandAmbientModuleSymbol(moduleSymbol *ast.Symbol) bool {
return isShorthandAmbientModule(moduleSymbol.ValueDeclaration)
}
func isShorthandAmbientModule(node *ast.Node) bool {
// The only kind of module that can be missing a body is a shorthand ambient module.
return node != nil && node.Kind == ast.KindModuleDeclaration && node.AsModuleDeclaration().Body == nil
}
func getFirstIdentifier(node *ast.Node) *ast.Node {
switch node.Kind {
case ast.KindIdentifier:
return node
case ast.KindQualifiedName:
return getFirstIdentifier(node.AsQualifiedName().Left)
case ast.KindPropertyAccessExpression:
return getFirstIdentifier(node.AsPropertyAccessExpression().Expression)
}
panic("Unhandled case in getFirstIdentifier")
}
func getAliasDeclarationFromName(node *ast.Node) *ast.Node {
switch node.Kind {
case ast.KindImportClause, ast.KindImportSpecifier, ast.KindNamespaceImport, ast.KindExportSpecifier, ast.KindExportAssignment,
ast.KindImportEqualsDeclaration, ast.KindNamespaceExport:
return node.Parent
case ast.KindQualifiedName:
return getAliasDeclarationFromName(node.Parent)
}
return nil
}
func entityNameToString(name *ast.Node) string {
switch name.Kind {
case ast.KindThisKeyword:
return "this"
case ast.KindIdentifier, ast.KindPrivateIdentifier:
return scanner.GetTextOfNode(name)
case ast.KindQualifiedName:
return entityNameToString(name.AsQualifiedName().Left) + "." + entityNameToString(name.AsQualifiedName().Right)
case ast.KindPropertyAccessExpression:
return entityNameToString(name.AsPropertyAccessExpression().Expression) + "." + entityNameToString(name.AsPropertyAccessExpression().Name())
case ast.KindJsxNamespacedName:
return entityNameToString(name.AsJsxNamespacedName().Namespace) + ":" + entityNameToString(name.AsJsxNamespacedName().Name())
}
panic("Unhandled case in entityNameToString")
}
func getContainingQualifiedNameNode(node *ast.Node) *ast.Node {
for ast.IsQualifiedName(node.Parent) {
node = node.Parent
}
return node
}
func isSideEffectImport(node *ast.Node) bool {
ancestor := ast.FindAncestor(node, ast.IsImportDeclaration)
return ancestor != nil && ancestor.AsImportDeclaration().ImportClause == nil
}
func getExternalModuleRequireArgument(node *ast.Node) *ast.Node {
if isVariableDeclarationInitializedToBareOrAccessedRequire(node) {
return getLeftmostAccessExpression(node.AsVariableDeclaration().Initializer).AsCallExpression().Arguments.Nodes[0]
}
return nil
}
func getExternalModuleImportEqualsDeclarationExpression(node *ast.Node) *ast.Node {
// Debug.assert(isExternalModuleImportEqualsDeclaration(node))
return node.AsImportEqualsDeclaration().ModuleReference.AsExternalModuleReference().Expression
}
func isRightSideOfQualifiedNameOrPropertyAccess(node *ast.Node) bool {
parent := node.Parent
switch parent.Kind {
case ast.KindQualifiedName:
return parent.AsQualifiedName().Right == node
case ast.KindPropertyAccessExpression:
return parent.AsPropertyAccessExpression().Name() == node
case ast.KindMetaProperty: