-
Notifications
You must be signed in to change notification settings - Fork 582
/
Copy pathutilities.go
2163 lines (1950 loc) · 72.5 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"
"sync"
"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"
)
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 {
return len(name) != 0 && (name[0] >= 'a' && name[0] <= '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 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 getSelectedModifierFlags(node *ast.Node, flags ast.ModifierFlags) ast.ModifierFlags {
return node.ModifierFlags() & flags
}
func hasModifier(node *ast.Node, flags ast.ModifierFlags) bool {
return node.ModifierFlags()&flags != 0
}
func hasReadonlyModifier(node *ast.Node) bool {
return hasModifier(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 isRequireCall(initializer, true /*requireStringLiteralLikeArgument*/)
}
return false
}
func getLeftmostAccessExpression(expr *ast.Node) *ast.Node {
for ast.IsAccessExpression(expr) {
expr = expr.Expression()
}
return expr
}
func isRequireCall(node *ast.Node, requireStringLiteralLikeArgument bool) bool {
if ast.IsCallExpression(node) {
callExpression := node.AsCallExpression()
if len(callExpression.Arguments.Nodes) == 1 {
if ast.IsIdentifier(callExpression.Expression) && callExpression.Expression.AsIdentifier().Text == "require" {
return !requireStringLiteralLikeArgument || ast.IsStringLiteralLike(callExpression.Arguments.Nodes[0])
}
}
}
return false
}
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 getSingleVariableOfVariableStatement(node *ast.Node) *ast.Node {
if !ast.IsVariableStatement(node) {
return nil
}
return core.FirstOrNil(node.AsVariableStatement().DeclarationList.AsVariableDeclarationList().Declarations.Nodes)
}
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.KindJSTypeAliasDeclaration, 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.KindJSDocSignature, 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.KindJSTypeAliasDeclaration, 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.KindJSDocSignature, ast.KindMappedType,
ast.KindMethodDeclaration, ast.KindMethodSignature, ast.KindModuleDeclaration, ast.KindSetAccessor, ast.KindSourceFile,
ast.KindTypeAliasDeclaration, ast.KindJSTypeAliasDeclaration:
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 getAliasDeclarationFromName(node *ast.Node) *ast.Node {
switch node.Parent.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:
if ast.NodeIsSynthesized(name) {
return name.Text()
}
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:
return parent.AsMetaProperty().Name() == node
}
return false
}
func getSourceFileOfModule(module *ast.Symbol) *ast.SourceFile {
declaration := module.ValueDeclaration
if declaration == nil {
declaration = getNonAugmentationDeclaration(module)
}
return ast.GetSourceFileOfNode(declaration)
}
func getNonAugmentationDeclaration(symbol *ast.Symbol) *ast.Node {
return core.Find(symbol.Declarations, func(d *ast.Node) bool {
return !isExternalModuleAugmentation(d) && !ast.IsGlobalScopeAugmentation(d)
})
}
func isExternalModuleAugmentation(node *ast.Node) bool {
return ast.IsAmbientModule(node) && ast.IsModuleAugmentationExternal(node)
}
func isTopLevelInExternalModuleAugmentation(node *ast.Node) bool {
return node != nil && node.Parent != nil && ast.IsModuleBlock(node.Parent) && isExternalModuleAugmentation(node.Parent.Parent)
}
func isSyntacticDefault(node *ast.Node) bool {
return (ast.IsExportAssignment(node) && !node.AsExportAssignment().IsExportEquals) ||
ast.HasSyntacticModifier(node, ast.ModifierFlagsDefault) ||
ast.IsExportSpecifier(node) ||
ast.IsNamespaceExport(node)
}
func hasExportAssignmentSymbol(moduleSymbol *ast.Symbol) bool {
return moduleSymbol.Exports[ast.InternalSymbolNameExportEquals] != nil
}
func isTypeAlias(node *ast.Node) bool {
return ast.IsTypeOrJSTypeAliasDeclaration(node)
}
func hasOnlyExpressionInitializer(node *ast.Node) bool {
switch node.Kind {
case ast.KindVariableDeclaration, ast.KindParameter, ast.KindBindingElement, ast.KindPropertyDeclaration, ast.KindPropertyAssignment, ast.KindEnumMember:
return true
}
return false
}
func hasDotDotDotToken(node *ast.Node) bool {
switch node.Kind {
case ast.KindParameter:
return node.AsParameterDeclaration().DotDotDotToken != nil
case ast.KindBindingElement:
return node.AsBindingElement().DotDotDotToken != nil
case ast.KindNamedTupleMember:
return node.AsNamedTupleMember().DotDotDotToken != nil
case ast.KindJsxExpression:
return node.AsJsxExpression().DotDotDotToken != nil
}
return false
}
func IsTypeAny(t *Type) bool {
return t != nil && t.flags&TypeFlagsAny != 0
}
func isJSDocOptionalParameter(node *ast.ParameterDeclaration) bool {
return false // !!!
}
func isExclamationToken(node *ast.Node) bool {
return node != nil && node.Kind == ast.KindExclamationToken
}
func isOptionalDeclaration(declaration *ast.Node) bool {
switch declaration.Kind {
case ast.KindParameter:
return declaration.AsParameterDeclaration().QuestionToken != nil
case ast.KindPropertyDeclaration:
return ast.IsQuestionToken(declaration.AsPropertyDeclaration().PostfixToken)
case ast.KindPropertySignature:
return ast.IsQuestionToken(declaration.AsPropertySignatureDeclaration().PostfixToken)
case ast.KindMethodDeclaration:
return ast.IsQuestionToken(declaration.AsMethodDeclaration().PostfixToken)
case ast.KindMethodSignature:
return ast.IsQuestionToken(declaration.AsMethodSignatureDeclaration().PostfixToken)
case ast.KindPropertyAssignment:
return ast.IsQuestionToken(declaration.AsPropertyAssignment().PostfixToken)
case ast.KindShorthandPropertyAssignment:
return ast.IsQuestionToken(declaration.AsShorthandPropertyAssignment().PostfixToken)
}
return false
}
func isEmptyArrayLiteral(expression *ast.Node) bool {
return ast.IsArrayLiteralExpression(expression) && len(expression.AsArrayLiteralExpression().Elements.Nodes) == 0
}
func declarationBelongsToPrivateAmbientMember(declaration *ast.Node) bool {
root := ast.GetRootDeclaration(declaration)
memberDeclaration := root
if root.Kind == ast.KindParameter {
memberDeclaration = root.Parent
}
return isPrivateWithinAmbient(memberDeclaration)
}
func isPrivateWithinAmbient(node *ast.Node) bool {
return (hasModifier(node, ast.ModifierFlagsPrivate) || ast.IsPrivateIdentifierClassElementDeclaration(node)) && node.Flags&ast.NodeFlagsAmbient != 0
}
func isTypeAssertion(node *ast.Node) bool {
return ast.IsAssertionExpression(ast.SkipParentheses(node))
}
func createSymbolTable(symbols []*ast.Symbol) ast.SymbolTable {
if len(symbols) == 0 {
return nil
}
result := make(ast.SymbolTable)
for _, symbol := range symbols {
result[symbol.Name] = symbol
}
return result
}
func (c *Checker) sortSymbols(symbols []*ast.Symbol) {
slices.SortFunc(symbols, c.compareSymbols)
}
func (c *Checker) compareSymbolsWorker(s1, s2 *ast.Symbol) int {
if s1 == s2 {
return 0
}
if s1 == nil {
return 1
}
if s2 == nil {
return -1
}
if len(s1.Declarations) != 0 && len(s2.Declarations) != 0 {
if r := c.compareNodes(s1.Declarations[0], s2.Declarations[0]); r != 0 {
return r
}
} else if len(s1.Declarations) != 0 {
return -1
} else if len(s2.Declarations) != 0 {
return 1
}
if r := strings.Compare(s1.Name, s2.Name); r != 0 {
return r
}
// Fall back to symbol IDs. This is a last resort that should happen only when symbols have
// no declaration and duplicate names.
return int(ast.GetSymbolId(s1)) - int(ast.GetSymbolId(s2))
}
func (c *Checker) compareNodes(n1, n2 *ast.Node) int {
if n1 == n2 {
return 0
}
if n1 == nil {
return 1
}
if n2 == nil {
return -1
}
s1 := ast.GetSourceFileOfNode(n1)
s2 := ast.GetSourceFileOfNode(n2)
if s1 != s2 {
f1 := c.fileIndexMap[s1]
f2 := c.fileIndexMap[s2]
// Order by index of file in the containing program
return f1 - f2
}
// In the same file, order by source position
return n1.Pos() - n2.Pos()
}
func CompareTypes(t1, t2 *Type) int {
if t1 == t2 {
return 0
}
if t1 == nil {
return -1
}
if t2 == nil {
return 1
}
if t1.checker != t2.checker {
panic("Cannot compare types from different checkers")
}
// First sort in order of increasing type flags values.
if c := getSortOrderFlags(t1) - getSortOrderFlags(t2); c != 0 {
return c
}
// Order named types by name and, in the case of aliased types, by alias type arguments.
if c := compareTypeNames(t1, t2); c != 0 {
return c
}
// We have unnamed types or types with identical names. Now sort by data specific to the type.
switch {
case t1.flags&(TypeFlagsAny|TypeFlagsUnknown|TypeFlagsString|TypeFlagsNumber|TypeFlagsBoolean|TypeFlagsBigInt|TypeFlagsESSymbol|TypeFlagsVoid|TypeFlagsUndefined|TypeFlagsNull|TypeFlagsNever|TypeFlagsNonPrimitive) != 0:
// Only distinguished by type IDs, handled below.
case t1.flags&TypeFlagsObject != 0:
// Order unnamed or identically named object types by symbol.
if c := t1.checker.compareSymbols(t1.symbol, t2.symbol); c != 0 {
return c
}
// When object types have the same or no symbol, order by kind. We order type references before other kinds.
if t1.objectFlags&ObjectFlagsReference != 0 && t2.objectFlags&ObjectFlagsReference != 0 {
r1 := t1.AsTypeReference()
r2 := t2.AsTypeReference()
if r1.target.objectFlags&ObjectFlagsTuple != 0 && r2.target.objectFlags&ObjectFlagsTuple != 0 {
// Tuple types have no associated symbol, instead we order by tuple element information.
if c := compareTupleTypes(r1.target.AsTupleType(), r2.target.AsTupleType()); c != 0 {
return c
}
}
// Here we know we have references to instantiations of the same type because we have matching targets.
if r1.node == nil && r2.node == nil {
// Non-deferred type references with the same target are sorted by their type argument lists.
if c := compareTypeLists(t1.AsTypeReference().resolvedTypeArguments, t2.AsTypeReference().resolvedTypeArguments); c != 0 {
return c
}
} else {
// Deferred type references with the same target are ordered by the source location of the reference.
if c := t1.checker.compareNodes(r1.node, r2.node); c != 0 {
return c
}
// Instantiations of the same deferred type reference are ordered by their associated type mappers
// (which reflect the mapping of in-scope type parameters to type arguments).
if c := compareTypeMappers(t1.AsObjectType().mapper, t2.AsObjectType().mapper); c != 0 {
return c
}
}
} else if t1.objectFlags&ObjectFlagsReference != 0 {
return -1
} else if t2.objectFlags&ObjectFlagsReference != 0 {
return 1
} else {
// Order unnamed non-reference object types by kind associated type mappers. Reverse mapped types have
// neither symbols nor mappers so they're ultimately ordered by unstable type IDs, but given their rarity
// this should be fine.
if c := int(t1.objectFlags&ObjectFlagsObjectTypeKindMask) - int(t2.objectFlags&ObjectFlagsObjectTypeKindMask); c != 0 {
return c
}
if c := compareTypeMappers(t1.AsObjectType().mapper, t2.AsObjectType().mapper); c != 0 {
return c
}
}
case t1.flags&TypeFlagsUnion != 0:
// Unions are ordered by origin and then constituent type lists.
o1 := t1.AsUnionType().origin
o2 := t2.AsUnionType().origin
if o1 == nil && o2 == nil {
if c := compareTypeLists(t1.Types(), t2.Types()); c != 0 {
return c
}
} else if o1 == nil {
return 1
} else if o2 == nil {
return -1
} else {
if c := CompareTypes(o1, o2); c != 0 {
return c
}
}
case t1.flags&TypeFlagsIntersection != 0:
// Intersections are ordered by their constituent type lists.
if c := compareTypeLists(t1.Types(), t2.Types()); c != 0 {
return c
}
case t1.flags&(TypeFlagsEnum|TypeFlagsEnumLiteral|TypeFlagsUniqueESSymbol) != 0:
// Enum members are ordered by their symbol (and thus their declaration order).
if c := t1.checker.compareSymbols(t1.symbol, t2.symbol); c != 0 {
return c
}
case t1.flags&TypeFlagsStringLiteral != 0:
// String literal types are ordered by their values.
if c := strings.Compare(t1.AsLiteralType().value.(string), t2.AsLiteralType().value.(string)); c != 0 {
return c
}
case t1.flags&TypeFlagsNumberLiteral != 0:
// Numeric literal types are ordered by their values.
if c := cmp.Compare(t1.AsLiteralType().value.(jsnum.Number), t2.AsLiteralType().value.(jsnum.Number)); c != 0 {
return c
}
case t1.flags&TypeFlagsBooleanLiteral != 0:
b1 := t1.AsLiteralType().value.(bool)
b2 := t2.AsLiteralType().value.(bool)
if b1 != b2 {
if b1 {
return 1
}
return -1
}
case t1.flags&TypeFlagsTypeParameter != 0:
if c := t1.checker.compareSymbols(t1.symbol, t2.symbol); c != 0 {
return c
}
case t1.flags&TypeFlagsIndex != 0:
if c := CompareTypes(t1.AsIndexType().target, t2.AsIndexType().target); c != 0 {
return c
}
if c := int(t1.AsIndexType().flags) - int(t2.AsIndexType().flags); c != 0 {
return c
}
case t1.flags&TypeFlagsIndexedAccess != 0:
if c := CompareTypes(t1.AsIndexedAccessType().objectType, t2.AsIndexedAccessType().objectType); c != 0 {
return c
}
if c := CompareTypes(t1.AsIndexedAccessType().indexType, t2.AsIndexedAccessType().indexType); c != 0 {
return c
}
case t1.flags&TypeFlagsConditional != 0:
if c := t1.checker.compareNodes(t1.AsConditionalType().root.node.AsNode(), t2.AsConditionalType().root.node.AsNode()); c != 0 {
return c
}
if c := compareTypeMappers(t1.AsConditionalType().mapper, t2.AsConditionalType().mapper); c != 0 {
return c
}
case t1.flags&TypeFlagsSubstitution != 0:
if c := CompareTypes(t1.AsSubstitutionType().baseType, t2.AsSubstitutionType().baseType); c != 0 {
return c
}
if c := CompareTypes(t1.AsSubstitutionType().constraint, t2.AsSubstitutionType().constraint); c != 0 {
return c
}
case t1.flags&TypeFlagsTemplateLiteral != 0:
if c := slices.Compare(t1.AsTemplateLiteralType().texts, t2.AsTemplateLiteralType().texts); c != 0 {
return c
}
if c := compareTypeLists(t1.AsTemplateLiteralType().types, t2.AsTemplateLiteralType().types); c != 0 {
return c
}
case t1.flags&TypeFlagsStringMapping != 0:
if c := CompareTypes(t1.AsStringMappingType().target, t2.AsStringMappingType().target); c != 0 {
return c
}
}
// Fall back to type IDs. This results in type creation order for built-in types.
return int(t1.id) - int(t2.id)
}
func getSortOrderFlags(t *Type) int {
// Return TypeFlagsEnum for all enum-like unit types (they'll be sorted by their symbols)
if t.flags&(TypeFlagsEnumLiteral|TypeFlagsEnum) != 0 && t.flags&TypeFlagsUnion == 0 {
return int(TypeFlagsEnum)
}
return int(t.flags)
}
func compareTypeNames(t1, t2 *Type) int {
s1 := getTypeNameSymbol(t1)
s2 := getTypeNameSymbol(t2)
if s1 == s2 {
if t1.alias != nil {
return compareTypeLists(t1.alias.typeArguments, t2.alias.typeArguments)
}
return 0
}
if s1 == nil {
return 1
}
if s2 == nil {
return -1
}
return strings.Compare(s1.Name, s2.Name)
}
func getTypeNameSymbol(t *Type) *ast.Symbol {
if t.alias != nil {
return t.alias.symbol
}
if t.flags&(TypeFlagsTypeParameter|TypeFlagsStringMapping) != 0 || t.objectFlags&(ObjectFlagsClassOrInterface|ObjectFlagsReference) != 0 {
return t.symbol
}
return nil
}
func getObjectTypeName(t *Type) *ast.Symbol {
if t.objectFlags&(ObjectFlagsClassOrInterface|ObjectFlagsReference) != 0 {
return t.symbol
}
return nil
}
func compareTupleTypes(t1, t2 *TupleType) int {
if t1 == t2 {
return 0
}
if t1.readonly != t2.readonly {
return core.IfElse(t1.readonly, 1, -1)
}
if len(t1.elementInfos) != len(t2.elementInfos) {
return len(t1.elementInfos) - len(t2.elementInfos)
}
for i := range t1.elementInfos {
if c := int(t1.elementInfos[i].flags) - int(t2.elementInfos[i].flags); c != 0 {
return c
}
}
for i := range t1.elementInfos {
if c := compareElementLabels(t1.elementInfos[i].labeledDeclaration, t2.elementInfos[i].labeledDeclaration); c != 0 {
return c
}
}
return 0
}
func compareElementLabels(n1, n2 *ast.Node) int {
if n1 == n2 {
return 0
}
if n1 == nil {
return -1
}
if n2 == nil {
return 1
}
return strings.Compare(n1.Name().Text(), n2.Name().Text())
}
func compareTypeLists(s1, s2 []*Type) int {
if len(s1) != len(s2) {
return len(s1) - len(s2)
}
for i, t1 := range s1 {
if c := CompareTypes(t1, s2[i]); c != 0 {
return c
}
}
return 0
}
func compareTypeMappers(m1, m2 *TypeMapper) int {
if m1 == m2 {
return 0
}
if m1 == nil {
return 1
}
if m2 == nil {
return -1
}
kind1 := m1.Kind()
kind2 := m2.Kind()
if kind1 != kind2 {
return int(kind1) - int(kind2)
}
switch kind1 {
case TypeMapperKindSimple:
m1 := m1.data.(*SimpleTypeMapper)
m2 := m2.data.(*SimpleTypeMapper)
if c := CompareTypes(m1.source, m2.source); c != 0 {
return c
}
return CompareTypes(m1.target, m2.target)
case TypeMapperKindArray:
m1 := m1.data.(*ArrayTypeMapper)
m2 := m2.data.(*ArrayTypeMapper)
if c := compareTypeLists(m1.sources, m2.sources); c != 0 {
return c
}
return compareTypeLists(m1.targets, m2.targets)
case TypeMapperKindMerged:
m1 := m1.data.(*MergedTypeMapper)
m2 := m2.data.(*MergedTypeMapper)
if c := compareTypeMappers(m1.m1, m2.m1); c != 0 {
return c
}
return compareTypeMappers(m1.m2, m2.m2)
}
return 0
}
func getClassLikeDeclarationOfSymbol(symbol *ast.Symbol) *ast.Node {
return core.Find(symbol.Declarations, ast.IsClassLike)
}
func isThisInTypeQuery(node *ast.Node) bool {
if !ast.IsThisIdentifier(node) {
return false
}
for ast.IsQualifiedName(node.Parent) && node.Parent.AsQualifiedName().Left == node {
node = node.Parent
}
return node.Parent.Kind == ast.KindTypeQuery
}
func getDeclarationModifierFlagsFromSymbol(s *ast.Symbol) ast.ModifierFlags {
return getDeclarationModifierFlagsFromSymbolEx(s, false /*isWrite*/)
}
func getDeclarationModifierFlagsFromSymbolEx(s *ast.Symbol, isWrite bool) ast.ModifierFlags {
if s.ValueDeclaration != nil {
var declaration *ast.Node
if isWrite {
declaration = core.Find(s.Declarations, ast.IsSetAccessorDeclaration)
}
if declaration == nil && s.Flags&ast.SymbolFlagsGetAccessor != 0 {
declaration = core.Find(s.Declarations, ast.IsGetAccessorDeclaration)
}
if declaration == nil {
declaration = s.ValueDeclaration
}
flags := ast.GetCombinedModifierFlags(declaration)
if s.Parent != nil && s.Parent.Flags&ast.SymbolFlagsClass != 0 {
return flags
}
return flags & ^ast.ModifierFlagsAccessibilityModifier
}
if s.CheckFlags&ast.CheckFlagsSynthetic != 0 {
var accessModifier ast.ModifierFlags
switch {
case s.CheckFlags&ast.CheckFlagsContainsPrivate != 0:
accessModifier = ast.ModifierFlagsPrivate