-
Notifications
You must be signed in to change notification settings - Fork 582
/
Copy pathutilities.go
2545 lines (2272 loc) · 78.2 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 ast
import (
"slices"
"strings"
"sync"
"sync/atomic"
"github.com/microsoft/typescript-go/internal/core"
"github.com/microsoft/typescript-go/internal/tspath"
)
// Atomic ids
var (
nextNodeId atomic.Uint64
nextSymbolId atomic.Uint64
)
func GetNodeId(node *Node) NodeId {
id := node.id.Load()
if id == 0 {
// Worst case, we burn a few ids if we have to CAS.
id = nextNodeId.Add(1)
if !node.id.CompareAndSwap(0, id) {
id = node.id.Load()
}
}
return NodeId(id)
}
func GetSymbolId(symbol *Symbol) SymbolId {
id := symbol.id.Load()
if id == 0 {
// Worst case, we burn a few ids if we have to CAS.
id = nextSymbolId.Add(1)
if !symbol.id.CompareAndSwap(0, id) {
id = symbol.id.Load()
}
}
return SymbolId(id)
}
func GetSymbolTable(data *SymbolTable) SymbolTable {
if *data == nil {
*data = make(SymbolTable)
}
return *data
}
func GetMembers(symbol *Symbol) SymbolTable {
return GetSymbolTable(&symbol.Members)
}
func GetExports(symbol *Symbol) SymbolTable {
return GetSymbolTable(&symbol.Exports)
}
func GetLocals(container *Node) SymbolTable {
return GetSymbolTable(&container.LocalsContainerData().Locals)
}
// Determines if a node is missing (either `nil` or empty)
func NodeIsMissing(node *Node) bool {
return node == nil || node.Loc.Pos() == node.Loc.End() && node.Loc.Pos() >= 0 && node.Kind != KindEndOfFile
}
// Determines if a node is present
func NodeIsPresent(node *Node) bool {
return !NodeIsMissing(node)
}
// Determines if a node contains synthetic positions
func NodeIsSynthesized(node *Node) bool {
return PositionIsSynthesized(node.Loc.Pos()) || PositionIsSynthesized(node.Loc.End())
}
// Determines whether a position is synthetic
func PositionIsSynthesized(pos int) bool {
return pos < 0
}
func NodeKindIs(node *Node, kinds ...Kind) bool {
return slices.Contains(kinds, node.Kind)
}
func IsModifierKind(token Kind) bool {
switch token {
case KindAbstractKeyword,
KindAccessorKeyword,
KindAsyncKeyword,
KindConstKeyword,
KindDeclareKeyword,
KindDefaultKeyword,
KindExportKeyword,
KindInKeyword,
KindPublicKeyword,
KindPrivateKeyword,
KindProtectedKeyword,
KindReadonlyKeyword,
KindStaticKeyword,
KindOutKeyword,
KindOverrideKeyword:
return true
}
return false
}
func IsModifier(node *Node) bool {
return IsModifierKind(node.Kind)
}
func IsKeywordKind(token Kind) bool {
return KindFirstKeyword <= token && token <= KindLastKeyword
}
func IsPunctuationKind(token Kind) bool {
return KindFirstPunctuation <= token && token <= KindLastPunctuation
}
func IsAssignmentOperator(token Kind) bool {
return token >= KindFirstAssignment && token <= KindLastAssignment
}
func IsAssignmentExpression(node *Node, excludeCompoundAssignment bool) bool {
if node.Kind == KindBinaryExpression {
expr := node.AsBinaryExpression()
return (expr.OperatorToken.Kind == KindEqualsToken || !excludeCompoundAssignment && IsAssignmentOperator(expr.OperatorToken.Kind)) &&
IsLeftHandSideExpression(expr.Left)
}
return false
}
func GetRightMostAssignedExpression(node *Node) *Node {
for IsAssignmentExpression(node, true /*excludeCompoundAssignment*/) {
node = node.AsBinaryExpression().Right
}
return node
}
func IsDestructuringAssignment(node *Node) bool {
if IsAssignmentExpression(node, true /*excludeCompoundAssignment*/) {
kind := node.AsBinaryExpression().Left.Kind
return kind == KindObjectLiteralExpression || kind == KindArrayLiteralExpression
}
return false
}
// A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property
// assignment in an object literal that is an assignment target, or if it is parented by an array literal that is
// an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ a }] = xxx'.
// (Note that `p` is not a target in the above examples, only `a`.)
func IsAssignmentTarget(node *Node) bool {
return GetAssignmentTarget(node) != nil
}
// Returns the BinaryExpression, PrefixUnaryExpression, PostfixUnaryExpression, or ForInOrOfStatement that references
// the given node as an assignment target
func GetAssignmentTarget(node *Node) *Node {
for {
parent := node.Parent
switch parent.Kind {
case KindBinaryExpression:
if IsAssignmentOperator(parent.AsBinaryExpression().OperatorToken.Kind) && parent.AsBinaryExpression().Left == node {
return parent
}
return nil
case KindPrefixUnaryExpression:
if parent.AsPrefixUnaryExpression().Operator == KindPlusPlusToken || parent.AsPrefixUnaryExpression().Operator == KindMinusMinusToken {
return parent
}
return nil
case KindPostfixUnaryExpression:
if parent.AsPostfixUnaryExpression().Operator == KindPlusPlusToken || parent.AsPostfixUnaryExpression().Operator == KindMinusMinusToken {
return parent
}
return nil
case KindForInStatement, KindForOfStatement:
if parent.AsForInOrOfStatement().Initializer == node {
return parent
}
return nil
case KindParenthesizedExpression, KindArrayLiteralExpression, KindSpreadElement, KindNonNullExpression:
node = parent
case KindSpreadAssignment:
node = parent.Parent
case KindShorthandPropertyAssignment:
if parent.AsShorthandPropertyAssignment().Name() != node {
return nil
}
node = parent.Parent
case KindPropertyAssignment:
if parent.AsPropertyAssignment().Name() == node {
return nil
}
node = parent.Parent
default:
return nil
}
}
}
func IsLogicalBinaryOperator(token Kind) bool {
return token == KindBarBarToken || token == KindAmpersandAmpersandToken
}
func IsLogicalOrCoalescingBinaryOperator(token Kind) bool {
return IsLogicalBinaryOperator(token) || token == KindQuestionQuestionToken
}
func IsLogicalOrCoalescingBinaryExpression(expr *Node) bool {
return IsBinaryExpression(expr) && IsLogicalOrCoalescingBinaryOperator(expr.AsBinaryExpression().OperatorToken.Kind)
}
func IsLogicalOrCoalescingAssignmentOperator(token Kind) bool {
return token == KindBarBarEqualsToken || token == KindAmpersandAmpersandEqualsToken || token == KindQuestionQuestionEqualsToken
}
func IsLogicalOrCoalescingAssignmentExpression(expr *Node) bool {
return IsBinaryExpression(expr) && IsLogicalOrCoalescingAssignmentOperator(expr.AsBinaryExpression().OperatorToken.Kind)
}
func IsLogicalExpression(node *Node) bool {
for {
if node.Kind == KindParenthesizedExpression {
node = node.AsParenthesizedExpression().Expression
} else if node.Kind == KindPrefixUnaryExpression && node.AsPrefixUnaryExpression().Operator == KindExclamationToken {
node = node.AsPrefixUnaryExpression().Operand
} else {
return IsLogicalOrCoalescingBinaryExpression(node)
}
}
}
func IsTokenKind(token Kind) bool {
return KindFirstToken <= token && token <= KindLastToken
}
func IsAccessor(node *Node) bool {
return node.Kind == KindGetAccessor || node.Kind == KindSetAccessor
}
func IsPropertyNameLiteral(node *Node) bool {
switch node.Kind {
case KindIdentifier,
KindStringLiteral,
KindNoSubstitutionTemplateLiteral,
KindNumericLiteral:
return true
}
return false
}
func IsMemberName(node *Node) bool {
return node.Kind == KindIdentifier || node.Kind == KindPrivateIdentifier
}
func IsEntityName(node *Node) bool {
return node.Kind == KindIdentifier || node.Kind == KindQualifiedName
}
func IsPropertyName(node *Node) bool {
switch node.Kind {
case KindIdentifier,
KindPrivateIdentifier,
KindStringLiteral,
KindNumericLiteral,
KindComputedPropertyName:
return true
}
return false
}
// Return true if the given identifier is classified as an IdentifierName by inspecting the parent of the node
func IsIdentifierName(node *Node) bool {
parent := node.Parent
switch parent.Kind {
case KindPropertyDeclaration, KindPropertySignature, KindMethodDeclaration, KindMethodSignature, KindGetAccessor,
KindSetAccessor, KindEnumMember, KindPropertyAssignment, KindPropertyAccessExpression:
return parent.Name() == node
case KindQualifiedName:
return parent.AsQualifiedName().Right == node
case KindBindingElement:
return parent.AsBindingElement().PropertyName == node
case KindImportSpecifier:
return parent.AsImportSpecifier().PropertyName == node
case KindExportSpecifier, KindJsxAttribute, KindJsxSelfClosingElement, KindJsxOpeningElement, KindJsxClosingElement:
return true
}
return false
}
func IsPushOrUnshiftIdentifier(node *Node) bool {
text := node.Text()
return text == "push" || text == "unshift"
}
func IsBooleanLiteral(node *Node) bool {
return node.Kind == KindTrueKeyword || node.Kind == KindFalseKeyword
}
func IsLiteralKind(kind Kind) bool {
return KindFirstLiteralToken <= kind && kind <= KindLastLiteralToken
}
func IsLiteralExpression(node *Node) bool {
return IsLiteralKind(node.Kind)
}
func IsStringLiteralLike(node *Node) bool {
switch node.Kind {
case KindStringLiteral, KindNoSubstitutionTemplateLiteral:
return true
}
return false
}
func IsStringOrNumericLiteralLike(node *Node) bool {
return IsStringLiteralLike(node) || IsNumericLiteral(node)
}
func IsSignedNumericLiteral(node *Node) bool {
if node.Kind == KindPrefixUnaryExpression {
node := node.AsPrefixUnaryExpression()
return (node.Operator == KindPlusToken || node.Operator == KindMinusToken) && IsNumericLiteral(node.Operand)
}
return false
}
// Determines if a node is part of an OptionalChain
func IsOptionalChain(node *Node) bool {
if node.Flags&NodeFlagsOptionalChain != 0 {
switch node.Kind {
case KindPropertyAccessExpression,
KindElementAccessExpression,
KindCallExpression,
KindNonNullExpression:
return true
}
}
return false
}
func getQuestionDotToken(node *Expression) *TokenNode {
switch node.Kind {
case KindPropertyAccessExpression:
return node.AsPropertyAccessExpression().QuestionDotToken
case KindElementAccessExpression:
return node.AsElementAccessExpression().QuestionDotToken
case KindCallExpression:
return node.AsCallExpression().QuestionDotToken
}
panic("Unhandled case in getQuestionDotToken")
}
// Determines if node is the root expression of an OptionalChain
func IsOptionalChainRoot(node *Expression) bool {
return IsOptionalChain(node) && !IsNonNullExpression(node) && getQuestionDotToken(node) != nil
}
// Determines whether a node is the outermost `OptionalChain` in an ECMAScript `OptionalExpression`:
//
// 1. For `a?.b.c`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.`)
// 2. For `a?.b!`, the outermost chain is `a?.b` (`b` is the end of the chain starting at `a?.`)
// 3. For `(a?.b.c).d`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.` since parens end the chain)
// 4. For `a?.b.c?.d`, both `a?.b.c` and `a?.b.c?.d` are outermost (`c` is the end of the chain starting at `a?.`, and `d` is
// the end of the chain starting at `c?.`)
// 5. For `a?.(b?.c).d`, both `b?.c` and `a?.(b?.c)d` are outermost (`c` is the end of the chain starting at `b`, and `d` is
// the end of the chain starting at `a?.`)
func IsOutermostOptionalChain(node *Expression) bool {
parent := node.Parent
return !IsOptionalChain(parent) || // cases 1, 2, and 3
IsOptionalChainRoot(parent) || // case 4
node != parent.Expression() // case 5
}
// Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`).
func IsExpressionOfOptionalChainRoot(node *Node) bool {
return IsOptionalChainRoot(node.Parent) && node.Parent.Expression() == node
}
func IsNullishCoalesce(node *Node) bool {
return node.Kind == KindBinaryExpression && node.AsBinaryExpression().OperatorToken.Kind == KindQuestionQuestionToken
}
func IsAssertionExpression(node *Node) bool {
kind := node.Kind
return kind == KindTypeAssertionExpression || kind == KindAsExpression
}
func isLeftHandSideExpressionKind(kind Kind) bool {
switch kind {
case KindPropertyAccessExpression, KindElementAccessExpression, KindNewExpression, KindCallExpression,
KindJsxElement, KindJsxSelfClosingElement, KindJsxFragment, KindTaggedTemplateExpression, KindArrayLiteralExpression,
KindParenthesizedExpression, KindObjectLiteralExpression, KindClassExpression, KindFunctionExpression, KindIdentifier,
KindPrivateIdentifier, KindRegularExpressionLiteral, KindNumericLiteral, KindBigIntLiteral, KindStringLiteral,
KindNoSubstitutionTemplateLiteral, KindTemplateExpression, KindFalseKeyword, KindNullKeyword, KindThisKeyword,
KindTrueKeyword, KindSuperKeyword, KindNonNullExpression, KindExpressionWithTypeArguments, KindMetaProperty,
KindImportKeyword, KindMissingDeclaration:
return true
}
return false
}
// Determines whether a node is a LeftHandSideExpression based only on its kind.
func IsLeftHandSideExpression(node *Node) bool {
return isLeftHandSideExpressionKind(node.Kind)
}
func isUnaryExpressionKind(kind Kind) bool {
switch kind {
case KindPrefixUnaryExpression,
KindPostfixUnaryExpression,
KindDeleteExpression,
KindTypeOfExpression,
KindVoidExpression,
KindAwaitExpression,
KindTypeAssertionExpression:
return true
}
return isLeftHandSideExpressionKind(kind)
}
// Determines whether a node is a UnaryExpression based only on its kind.
func IsUnaryExpression(node *Node) bool {
return isUnaryExpressionKind(node.Kind)
}
func isExpressionKind(kind Kind) bool {
switch kind {
case KindConditionalExpression,
KindYieldExpression,
KindArrowFunction,
KindBinaryExpression,
KindSpreadElement,
KindAsExpression,
KindOmittedExpression,
KindCommaListExpression,
KindPartiallyEmittedExpression,
KindSatisfiesExpression:
return true
}
return isUnaryExpressionKind(kind)
}
// Determines whether a node is an expression based only on its kind.
func IsExpression(node *Node) bool {
return isExpressionKind(node.Kind)
}
func IsCommaExpression(node *Node) bool {
return node.Kind == KindBinaryExpression && node.AsBinaryExpression().OperatorToken.Kind == KindCommaToken
}
func IsCommaSequence(node *Node) bool {
// !!!
// New compiler just has binary expressinons.
// Maybe this should consider KindCommaListExpression even though we don't generate them.
return IsCommaExpression(node)
}
func IsIterationStatement(node *Node, lookInLabeledStatements bool) bool {
switch node.Kind {
case KindForStatement,
KindForInStatement,
KindForOfStatement,
KindDoStatement,
KindWhileStatement:
return true
case KindLabeledStatement:
return lookInLabeledStatements && IsIterationStatement((node.AsLabeledStatement()).Statement, lookInLabeledStatements)
}
return false
}
// Determines if a node is a property or element access expression
func IsAccessExpression(node *Node) bool {
return node.Kind == KindPropertyAccessExpression || node.Kind == KindElementAccessExpression
}
func isFunctionLikeDeclarationKind(kind Kind) bool {
switch kind {
case KindFunctionDeclaration,
KindMethodDeclaration,
KindConstructor,
KindGetAccessor,
KindSetAccessor,
KindFunctionExpression,
KindArrowFunction:
return true
}
return false
}
// Determines if a node is function-like (but is not a signature declaration)
// ensure node != nil before calling this
func IsFunctionLikeDeclaration(node *Node) bool {
return isFunctionLikeDeclarationKind(node.Kind)
}
func isFunctionLikeKind(kind Kind) bool {
switch kind {
case KindMethodSignature,
KindCallSignature,
KindJSDocSignature,
KindConstructSignature,
KindIndexSignature,
KindFunctionType,
KindConstructorType:
return true
}
return isFunctionLikeDeclarationKind(kind)
}
// Determines if a node is function- or signature-like.
// Ensure node != nil before calling this
func IsFunctionLike(node *Node) bool {
return isFunctionLikeKind(node.Kind)
}
func IsFunctionLikeOrClassStaticBlockDeclaration(node *Node) bool {
return node != nil && (IsFunctionLike(node) || IsClassStaticBlockDeclaration(node))
}
func IsFunctionOrSourceFile(node *Node) bool {
return IsFunctionLike(node) || IsSourceFile(node)
}
func IsClassLike(node *Node) bool {
return node.Kind == KindClassDeclaration || node.Kind == KindClassExpression
}
func IsClassElement(node *Node) bool {
switch node.Kind {
case KindConstructor,
KindPropertyDeclaration,
KindMethodDeclaration,
KindGetAccessor,
KindSetAccessor,
KindIndexSignature,
KindClassStaticBlockDeclaration,
KindSemicolonClassElement:
return true
}
return false
}
func isMethodOrAccessor(node *Node) bool {
switch node.Kind {
case KindMethodDeclaration, KindGetAccessor, KindSetAccessor:
return true
}
return false
}
func IsPrivateIdentifierClassElementDeclaration(node *Node) bool {
return (IsPropertyDeclaration(node) || isMethodOrAccessor(node)) && IsPrivateIdentifier(node.Name())
}
func IsObjectLiteralOrClassExpressionMethodOrAccessor(node *Node) bool {
kind := node.Kind
return (kind == KindMethodDeclaration || kind == KindGetAccessor || kind == KindSetAccessor) &&
(node.Parent.Kind == KindObjectLiteralExpression || node.Parent.Kind == KindClassExpression)
}
func IsTypeElement(node *Node) bool {
switch node.Kind {
case KindConstructSignature,
KindCallSignature,
KindPropertySignature,
KindMethodSignature,
KindIndexSignature,
KindGetAccessor,
KindSetAccessor:
// !!! KindNotEmittedTypeElement
return true
}
return false
}
func IsObjectLiteralElement(node *Node) bool {
switch node.Kind {
case KindPropertyAssignment,
KindShorthandPropertyAssignment,
KindSpreadAssignment,
KindMethodDeclaration,
KindGetAccessor,
KindSetAccessor:
return true
}
return false
}
func IsObjectLiteralMethod(node *Node) bool {
return node != nil && node.Kind == KindMethodDeclaration && node.Parent.Kind == KindObjectLiteralExpression
}
func IsAutoAccessorPropertyDeclaration(node *Node) bool {
return IsPropertyDeclaration(node) && HasAccessorModifier(node)
}
func IsParameterPropertyDeclaration(node *Node, parent *Node) bool {
return IsParameter(node) && HasSyntacticModifier(node, ModifierFlagsParameterPropertyModifier) && parent.Kind == KindConstructor
}
func IsJsxChild(node *Node) bool {
switch node.Kind {
case KindJsxElement,
KindJsxExpression,
KindJsxSelfClosingElement,
KindJsxText,
KindJsxFragment:
return true
}
return false
}
func isDeclarationStatementKind(kind Kind) bool {
switch kind {
case KindFunctionDeclaration,
KindMissingDeclaration,
KindClassDeclaration,
KindInterfaceDeclaration,
KindTypeAliasDeclaration,
KindEnumDeclaration,
KindModuleDeclaration,
KindImportDeclaration,
KindImportEqualsDeclaration,
KindExportDeclaration,
KindExportAssignment,
KindNamespaceExportDeclaration:
return true
}
return false
}
// Determines whether a node is a DeclarationStatement. Ideally this does not use Parent pointers, but it may use them
// to rule out a Block node that is part of `try` or `catch` or is the Block-like body of a function.
//
// NOTE: ECMA262 would just call this a Declaration
func IsDeclarationStatement(node *Node) bool {
return isDeclarationStatementKind(node.Kind)
}
func isStatementKindButNotDeclarationKind(kind Kind) bool {
switch kind {
case KindBreakStatement,
KindContinueStatement,
KindDebuggerStatement,
KindDoStatement,
KindExpressionStatement,
KindEmptyStatement,
KindForInStatement,
KindForOfStatement,
KindForStatement,
KindIfStatement,
KindLabeledStatement,
KindReturnStatement,
KindSwitchStatement,
KindThrowStatement,
KindTryStatement,
KindVariableStatement,
KindWhileStatement,
KindWithStatement,
KindNotEmittedStatement:
return true
}
return false
}
// Determines whether a node is a Statement that is not also a Declaration. Ideally this does not use Parent pointers,
// but it may use them to rule out a Block node that is part of `try` or `catch` or is the Block-like body of a function.
//
// NOTE: ECMA262 would just call this a Statement
func IsStatementButNotDeclaration(node *Node) bool {
return isStatementKindButNotDeclarationKind(node.Kind)
}
// Determines whether a node is a Statement. Ideally this does not use Parent pointers, but it may use
// them to rule out a Block node that is part of `try` or `catch` or is the Block-like body of a function.
//
// NOTE: ECMA262 would call this either a StatementListItem or ModuleListItem
func IsStatement(node *Node) bool {
kind := node.Kind
return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) || isBlockStatement(node)
}
// Determines whether a node is a BlockStatement. If parents are available, this ensures the Block is
// not part of a `try` statement, `catch` clause, or the Block-like body of a function
func isBlockStatement(node *Node) bool {
if node.Kind != KindBlock {
return false
}
if node.Parent != nil && (node.Parent.Kind == KindTryStatement || node.Parent.Kind == KindCatchClause) {
return false
}
return !IsFunctionBlock(node)
}
// Determines whether a node is the Block-like body of a function by walking the parent of the node
func IsFunctionBlock(node *Node) bool {
return node != nil && node.Kind == KindBlock && node.Parent != nil && IsFunctionLike(node.Parent)
}
func GetStatementsOfBlock(block *Node) *StatementList {
switch block.Kind {
case KindBlock:
return block.AsBlock().Statements
case KindModuleBlock:
return block.AsModuleBlock().Statements
case KindSourceFile:
return block.AsSourceFile().Statements
}
panic("Unhandled case in getStatementsOfBlock")
}
func IsBlockOrCatchScoped(declaration *Node) bool {
return GetCombinedNodeFlags(declaration)&NodeFlagsBlockScoped != 0 || IsCatchClauseVariableDeclarationOrBindingElement(declaration)
}
func IsCatchClauseVariableDeclarationOrBindingElement(declaration *Node) bool {
node := GetRootDeclaration(declaration)
return node.Kind == KindVariableDeclaration && node.Parent.Kind == KindCatchClause
}
func IsTypeNodeKind(kind Kind) bool {
switch kind {
case KindAnyKeyword,
KindUnknownKeyword,
KindNumberKeyword,
KindBigIntKeyword,
KindObjectKeyword,
KindBooleanKeyword,
KindStringKeyword,
KindSymbolKeyword,
KindVoidKeyword,
KindUndefinedKeyword,
KindNeverKeyword,
KindIntrinsicKeyword,
KindExpressionWithTypeArguments,
KindJSDocAllType,
KindJSDocNullableType,
KindJSDocNonNullableType,
KindJSDocOptionalType,
KindJSDocVariadicType:
return true
}
return kind >= KindFirstTypeNode && kind <= KindLastTypeNode
}
func IsTypeNode(node *Node) bool {
return IsTypeNodeKind(node.Kind)
}
func IsJSDocKind(kind Kind) bool {
return KindFirstJSDocNode <= kind && kind <= KindLastJSDocNode
}
func isJSDocTypeAssertion(_ *Node) bool {
return false // !!!
}
func IsPrologueDirective(node *Node) bool {
return node.Kind == KindExpressionStatement &&
node.AsExpressionStatement().Expression.Kind == KindStringLiteral
}
type OuterExpressionKinds int16
const (
OEKParentheses OuterExpressionKinds = 1 << 0
OEKTypeAssertions OuterExpressionKinds = 1 << 1
OEKNonNullAssertions OuterExpressionKinds = 1 << 2
OEKPartiallyEmittedExpressions OuterExpressionKinds = 1 << 3
OEKExpressionsWithTypeArguments OuterExpressionKinds = 1 << 4
OEKExcludeJSDocTypeAssertion = 1 << 5
OEKAssertions = OEKTypeAssertions | OEKNonNullAssertions
OEKAll = OEKParentheses | OEKAssertions | OEKPartiallyEmittedExpressions | OEKExpressionsWithTypeArguments
)
// Determines whether node is an "outer expression" of the provided kinds
func IsOuterExpression(node *Expression, kinds OuterExpressionKinds) bool {
switch node.Kind {
case KindParenthesizedExpression:
return kinds&OEKParentheses != 0 && !(kinds&OEKExcludeJSDocTypeAssertion != 0 && isJSDocTypeAssertion(node))
case KindTypeAssertionExpression, KindAsExpression, KindSatisfiesExpression:
return kinds&OEKTypeAssertions != 0
case KindExpressionWithTypeArguments:
return kinds&OEKExpressionsWithTypeArguments != 0
case KindNonNullExpression:
return kinds&OEKNonNullAssertions != 0
case KindPartiallyEmittedExpression:
return kinds&OEKPartiallyEmittedExpressions != 0
}
return false
}
// Descends into an expression, skipping past "outer expressions" of the provided kinds
func SkipOuterExpressions(node *Expression, kinds OuterExpressionKinds) *Expression {
for IsOuterExpression(node, kinds) {
node = node.Expression()
}
return node
}
// Skips past the parentheses of an expression
func SkipParentheses(node *Expression) *Expression {
return SkipOuterExpressions(node, OEKParentheses)
}
func SkipTypeParentheses(node *Node) *Node {
for IsParenthesizedTypeNode(node) {
node = node.AsParenthesizedTypeNode().Type
}
return node
}
func SkipPartiallyEmittedExpressions(node *Expression) *Expression {
return SkipOuterExpressions(node, OEKPartiallyEmittedExpressions)
}
// Walks up the parents of a parenthesized expression to find the containing node
func WalkUpParenthesizedExpressions(node *Expression) *Node {
for node != nil && node.Kind == KindParenthesizedExpression {
node = node.Parent
}
return node
}
// Walks up the parents of a parenthesized type to find the containing node
func WalkUpParenthesizedTypes(node *TypeNode) *Node {
for node != nil && node.Kind == KindParenthesizedType {
node = node.Parent
}
return node
}
// Walks up the parents of a node to find the containing SourceFile
func GetSourceFileOfNode(node *Node) *SourceFile {
for node != nil {
if node.Kind == KindSourceFile {
return node.AsSourceFile()
}
node = node.Parent
}
return nil
}
var setParentInChildrenPool = sync.Pool{
New: func() any {
return newParentInChildrenSetter()
},
}
func newParentInChildrenSetter() func(node *Node) bool {
// Consolidate state into one allocation.
// Similar to https://go.dev/cl/552375.
var state struct {
parent *Node
visit func(*Node) bool
}
state.visit = func(node *Node) bool {
if state.parent != nil {
node.Parent = state.parent
}
saveParent := state.parent
state.parent = node
node.ForEachChild(state.visit)
state.parent = saveParent
return false
}
return state.visit
}
func SetParentInChildren(node *Node) {
fn := setParentInChildrenPool.Get().(func(node *Node) bool)
defer setParentInChildrenPool.Put(fn)
fn(node)
}
// Walks up the parents of a node to find the ancestor that matches the callback
func FindAncestor(node *Node, callback func(*Node) bool) *Node {
for node != nil {
if callback(node) {
return node
}
node = node.Parent
}
return nil
}
type FindAncestorResult int32
const (
FindAncestorFalse FindAncestorResult = iota
FindAncestorTrue
FindAncestorQuit
)
// Walks up the parents of a node to find the ancestor that matches the callback
func FindAncestorOrQuit(node *Node, callback func(*Node) FindAncestorResult) *Node {
for node != nil {
switch callback(node) {
case FindAncestorQuit:
return nil
case FindAncestorTrue:
return node
}
node = node.Parent
}
return nil
}
func IsNodeDescendantOf(node *Node, ancestor *Node) bool {
for node != nil {
if node == ancestor {
return true
}
node = node.Parent
}
return false
}
func ModifierToFlag(token Kind) ModifierFlags {
switch token {
case KindStaticKeyword:
return ModifierFlagsStatic
case KindPublicKeyword:
return ModifierFlagsPublic
case KindProtectedKeyword:
return ModifierFlagsProtected
case KindPrivateKeyword:
return ModifierFlagsPrivate
case KindAbstractKeyword:
return ModifierFlagsAbstract
case KindAccessorKeyword:
return ModifierFlagsAccessor
case KindExportKeyword:
return ModifierFlagsExport
case KindDeclareKeyword:
return ModifierFlagsAmbient
case KindConstKeyword:
return ModifierFlagsConst
case KindDefaultKeyword:
return ModifierFlagsDefault
case KindAsyncKeyword:
return ModifierFlagsAsync
case KindReadonlyKeyword:
return ModifierFlagsReadonly
case KindOverrideKeyword:
return ModifierFlagsOverride
case KindInKeyword:
return ModifierFlagsIn
case KindOutKeyword:
return ModifierFlagsOut
case KindImmediateKeyword:
return ModifierFlagsImmediate
case KindDecorator:
return ModifierFlagsDecorator
}
return ModifierFlagsNone
}
func ModifiersToFlags(modifiers []*Node) ModifierFlags {
var flags ModifierFlags
for _, modifier := range modifiers {
flags |= ModifierToFlag(modifier.Kind)
}
return flags
}
func HasSyntacticModifier(node *Node, flags ModifierFlags) bool {
return node.ModifierFlags()&flags != 0
}
func HasAccessorModifier(node *Node) bool {
return HasSyntacticModifier(node, ModifierFlagsAccessor)
}
func HasStaticModifier(node *Node) bool {
return HasSyntacticModifier(node, ModifierFlagsStatic)
}
func IsStatic(node *Node) bool {
// https://tc39.es/ecma262/#sec-static-semantics-isstatic
return IsClassElement(node) && HasStaticModifier(node) || IsClassStaticBlockDeclaration(node)
}
func CanHaveIllegalDecorators(node *Node) bool {
switch node.Kind {
case KindPropertyAssignment, KindShorthandPropertyAssignment,
KindFunctionDeclaration, KindConstructor,
KindIndexSignature, KindClassStaticBlockDeclaration,
KindMissingDeclaration, KindVariableStatement,
KindInterfaceDeclaration, KindTypeAliasDeclaration,
KindEnumDeclaration, KindModuleDeclaration,
KindImportEqualsDeclaration, KindImportDeclaration,