forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathutilities.ts
3341 lines (2924 loc) · 156 KB
/
utilities.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* @internal */ // Don't expose that we use this
// Based on lib.es6.d.ts
interface PromiseConstructor {
new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;
reject(reason: any): Promise<never>;
all<T>(values: (T | PromiseLike<T>)[]): Promise<T[]>;
}
/* @internal */
declare var Promise: PromiseConstructor; // eslint-disable-line no-var
/* @internal */
namespace ts {
// These utilities are common to multiple language service features.
//#region
export const scanner: Scanner = createScanner(ScriptTarget.Latest, /*skipTrivia*/ true);
export const enum SemanticMeaning {
None = 0x0,
Value = 0x1,
Type = 0x2,
Namespace = 0x4,
All = Value | Type | Namespace
}
export function getMeaningFromDeclaration(node: Node): SemanticMeaning {
switch (node.kind) {
case SyntaxKind.VariableDeclaration:
return isInJSFile(node) && getJSDocEnumTag(node) ? SemanticMeaning.All : SemanticMeaning.Value;
case SyntaxKind.Parameter:
case SyntaxKind.BindingElement:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.PropertySignature:
case SyntaxKind.PropertyAssignment:
case SyntaxKind.ShorthandPropertyAssignment:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
case SyntaxKind.Constructor:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
case SyntaxKind.CatchClause:
case SyntaxKind.JsxAttribute:
return SemanticMeaning.Value;
case SyntaxKind.TypeParameter:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.TypeAliasDeclaration:
case SyntaxKind.TypeLiteral:
return SemanticMeaning.Type;
case SyntaxKind.JSDocTypedefTag:
// If it has no name node, it shares the name with the value declaration below it.
return (node as JSDocTypedefTag).name === undefined ? SemanticMeaning.Value | SemanticMeaning.Type : SemanticMeaning.Type;
case SyntaxKind.EnumMember:
case SyntaxKind.ClassDeclaration:
return SemanticMeaning.Value | SemanticMeaning.Type;
case SyntaxKind.ModuleDeclaration:
if (isAmbientModule(node as ModuleDeclaration)) {
return SemanticMeaning.Namespace | SemanticMeaning.Value;
}
else if (getModuleInstanceState(node as ModuleDeclaration) === ModuleInstanceState.Instantiated) {
return SemanticMeaning.Namespace | SemanticMeaning.Value;
}
else {
return SemanticMeaning.Namespace;
}
case SyntaxKind.EnumDeclaration:
case SyntaxKind.NamedImports:
case SyntaxKind.ImportSpecifier:
case SyntaxKind.ImportEqualsDeclaration:
case SyntaxKind.ImportDeclaration:
case SyntaxKind.ExportAssignment:
case SyntaxKind.ExportDeclaration:
return SemanticMeaning.All;
// An external module can be a Value
case SyntaxKind.SourceFile:
return SemanticMeaning.Namespace | SemanticMeaning.Value;
}
return SemanticMeaning.All;
}
export function getMeaningFromLocation(node: Node): SemanticMeaning {
node = getAdjustedReferenceLocation(node);
const parent = node.parent;
if (node.kind === SyntaxKind.SourceFile) {
return SemanticMeaning.Value;
}
else if (isExportAssignment(parent)
|| isExportSpecifier(parent)
|| isExternalModuleReference(parent)
|| isImportSpecifier(parent)
|| isImportClause(parent)
|| isImportEqualsDeclaration(parent) && node === parent.name) {
return SemanticMeaning.All;
}
else if (isInRightSideOfInternalImportEqualsDeclaration(node)) {
return getMeaningFromRightHandSideOfImportEquals(node as Identifier);
}
else if (isDeclarationName(node)) {
return getMeaningFromDeclaration(parent);
}
else if (isEntityName(node) && findAncestor(node, or(isJSDocNameReference, isJSDocLinkLike, isJSDocMemberName))) {
return SemanticMeaning.All;
}
else if (isTypeReference(node)) {
return SemanticMeaning.Type;
}
else if (isNamespaceReference(node)) {
return SemanticMeaning.Namespace;
}
else if (isTypeParameterDeclaration(parent)) {
Debug.assert(isJSDocTemplateTag(parent.parent)); // Else would be handled by isDeclarationName
return SemanticMeaning.Type;
}
else if (isLiteralTypeNode(parent)) {
// This might be T["name"], which is actually referencing a property and not a type. So allow both meanings.
return SemanticMeaning.Type | SemanticMeaning.Value;
}
else {
return SemanticMeaning.Value;
}
}
function getMeaningFromRightHandSideOfImportEquals(node: Node): SemanticMeaning {
// import a = |b|; // Namespace
// import a = |b.c|; // Value, type, namespace
// import a = |b.c|.d; // Namespace
const name = node.kind === SyntaxKind.QualifiedName ? node : isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined;
return name && name.parent.kind === SyntaxKind.ImportEqualsDeclaration ? SemanticMeaning.All : SemanticMeaning.Namespace;
}
export function isInRightSideOfInternalImportEqualsDeclaration(node: Node) {
while (node.parent.kind === SyntaxKind.QualifiedName) {
node = node.parent;
}
return isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node;
}
function isNamespaceReference(node: Node): boolean {
return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node);
}
function isQualifiedNameNamespaceReference(node: Node): boolean {
let root = node;
let isLastClause = true;
if (root.parent.kind === SyntaxKind.QualifiedName) {
while (root.parent && root.parent.kind === SyntaxKind.QualifiedName) {
root = root.parent;
}
isLastClause = (root as QualifiedName).right === node;
}
return root.parent.kind === SyntaxKind.TypeReference && !isLastClause;
}
function isPropertyAccessNamespaceReference(node: Node): boolean {
let root = node;
let isLastClause = true;
if (root.parent.kind === SyntaxKind.PropertyAccessExpression) {
while (root.parent && root.parent.kind === SyntaxKind.PropertyAccessExpression) {
root = root.parent;
}
isLastClause = (root as PropertyAccessExpression).name === node;
}
if (!isLastClause && root.parent.kind === SyntaxKind.ExpressionWithTypeArguments && root.parent.parent.kind === SyntaxKind.HeritageClause) {
const decl = root.parent.parent.parent;
return (decl.kind === SyntaxKind.ClassDeclaration && (root.parent.parent as HeritageClause).token === SyntaxKind.ImplementsKeyword) ||
(decl.kind === SyntaxKind.InterfaceDeclaration && (root.parent.parent as HeritageClause).token === SyntaxKind.ExtendsKeyword);
}
return false;
}
function isTypeReference(node: Node): boolean {
if (isRightSideOfQualifiedNameOrPropertyAccess(node)) {
node = node.parent;
}
switch (node.kind) {
case SyntaxKind.ThisKeyword:
return !isExpressionNode(node);
case SyntaxKind.ThisType:
return true;
}
switch (node.parent.kind) {
case SyntaxKind.TypeReference:
return true;
case SyntaxKind.ImportType:
return !(node.parent as ImportTypeNode).isTypeOf;
case SyntaxKind.ExpressionWithTypeArguments:
return !isExpressionWithTypeArgumentsInClassExtendsClause(node.parent as ExpressionWithTypeArguments);
}
return false;
}
export function isCallExpressionTarget(node: Node, includeElementAccess = false, skipPastOuterExpressions = false): boolean {
return isCalleeWorker(node, isCallExpression, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions);
}
export function isNewExpressionTarget(node: Node, includeElementAccess = false, skipPastOuterExpressions = false): boolean {
return isCalleeWorker(node, isNewExpression, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions);
}
export function isCallOrNewExpressionTarget(node: Node, includeElementAccess = false, skipPastOuterExpressions = false): boolean {
return isCalleeWorker(node, isCallOrNewExpression, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions);
}
export function isTaggedTemplateTag(node: Node, includeElementAccess = false, skipPastOuterExpressions = false): boolean {
return isCalleeWorker(node, isTaggedTemplateExpression, selectTagOfTaggedTemplateExpression, includeElementAccess, skipPastOuterExpressions);
}
export function isDecoratorTarget(node: Node, includeElementAccess = false, skipPastOuterExpressions = false): boolean {
return isCalleeWorker(node, isDecorator, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions);
}
export function isJsxOpeningLikeElementTagName(node: Node, includeElementAccess = false, skipPastOuterExpressions = false): boolean {
return isCalleeWorker(node, isJsxOpeningLikeElement, selectTagNameOfJsxOpeningLikeElement, includeElementAccess, skipPastOuterExpressions);
}
function selectExpressionOfCallOrNewExpressionOrDecorator(node: CallExpression | NewExpression | Decorator) {
return node.expression;
}
function selectTagOfTaggedTemplateExpression(node: TaggedTemplateExpression) {
return node.tag;
}
function selectTagNameOfJsxOpeningLikeElement(node: JsxOpeningLikeElement) {
return node.tagName;
}
function isCalleeWorker<T extends CallExpression | NewExpression | TaggedTemplateExpression | Decorator | JsxOpeningLikeElement>(node: Node, pred: (node: Node) => node is T, calleeSelector: (node: T) => Expression, includeElementAccess: boolean, skipPastOuterExpressions: boolean) {
let target = includeElementAccess ? climbPastPropertyOrElementAccess(node) : climbPastPropertyAccess(node);
if (skipPastOuterExpressions) {
target = skipOuterExpressions(target);
}
return !!target && !!target.parent && pred(target.parent) && calleeSelector(target.parent) === target;
}
export function climbPastPropertyAccess(node: Node) {
return isRightSideOfPropertyAccess(node) ? node.parent : node;
}
export function climbPastPropertyOrElementAccess(node: Node) {
return isRightSideOfPropertyAccess(node) || isArgumentExpressionOfElementAccess(node) ? node.parent : node;
}
export function getTargetLabel(referenceNode: Node, labelName: string): Identifier | undefined {
while (referenceNode) {
if (referenceNode.kind === SyntaxKind.LabeledStatement && (referenceNode as LabeledStatement).label.escapedText === labelName) {
return (referenceNode as LabeledStatement).label;
}
referenceNode = referenceNode.parent;
}
return undefined;
}
export function hasPropertyAccessExpressionWithName(node: CallExpression, funcName: string): boolean {
if (!isPropertyAccessExpression(node.expression)) {
return false;
}
return node.expression.name.text === funcName;
}
export function isJumpStatementTarget(node: Node): node is Identifier & { parent: BreakOrContinueStatement } {
return isIdentifier(node) && tryCast(node.parent, isBreakOrContinueStatement)?.label === node;
}
export function isLabelOfLabeledStatement(node: Node): node is Identifier {
return isIdentifier(node) && tryCast(node.parent, isLabeledStatement)?.label === node;
}
export function isLabelName(node: Node): boolean {
return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node);
}
export function isTagName(node: Node): boolean {
return tryCast(node.parent, isJSDocTag)?.tagName === node;
}
export function isRightSideOfQualifiedName(node: Node) {
return tryCast(node.parent, isQualifiedName)?.right === node;
}
export function isRightSideOfPropertyAccess(node: Node) {
return tryCast(node.parent, isPropertyAccessExpression)?.name === node;
}
export function isArgumentExpressionOfElementAccess(node: Node) {
return tryCast(node.parent, isElementAccessExpression)?.argumentExpression === node;
}
export function isNameOfModuleDeclaration(node: Node) {
return tryCast(node.parent, isModuleDeclaration)?.name === node;
}
export function isNameOfFunctionDeclaration(node: Node): boolean {
return isIdentifier(node) && tryCast(node.parent, isFunctionLike)?.name === node;
}
export function isLiteralNameOfPropertyDeclarationOrIndexAccess(node: StringLiteral | NumericLiteral | NoSubstitutionTemplateLiteral): boolean {
switch (node.parent.kind) {
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.PropertySignature:
case SyntaxKind.PropertyAssignment:
case SyntaxKind.EnumMember:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.ModuleDeclaration:
return getNameOfDeclaration(node.parent as Declaration) === node;
case SyntaxKind.ElementAccessExpression:
return (node.parent as ElementAccessExpression).argumentExpression === node;
case SyntaxKind.ComputedPropertyName:
return true;
case SyntaxKind.LiteralType:
return node.parent.parent.kind === SyntaxKind.IndexedAccessType;
default:
return false;
}
}
export function isExpressionOfExternalModuleImportEqualsDeclaration(node: Node) {
return isExternalModuleImportEqualsDeclaration(node.parent.parent) &&
getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node;
}
export function getContainerNode(node: Node): Declaration | undefined {
if (isJSDocTypeAlias(node)) {
// This doesn't just apply to the node immediately under the comment, but to everything in its parent's scope.
// node.parent = the JSDoc comment, node.parent.parent = the node having the comment.
// Then we get parent again in the loop.
node = node.parent.parent;
}
while (true) {
node = node.parent;
if (!node) {
return undefined;
}
switch (node.kind) {
case SyntaxKind.SourceFile:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.ModuleDeclaration:
return node as Declaration;
}
}
}
export function getNodeKind(node: Node): ScriptElementKind {
switch (node.kind) {
case SyntaxKind.SourceFile:
return isExternalModule(node as SourceFile) ? ScriptElementKind.moduleElement : ScriptElementKind.scriptElement;
case SyntaxKind.ModuleDeclaration:
return ScriptElementKind.moduleElement;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ClassExpression:
return ScriptElementKind.classElement;
case SyntaxKind.InterfaceDeclaration: return ScriptElementKind.interfaceElement;
case SyntaxKind.TypeAliasDeclaration:
case SyntaxKind.JSDocCallbackTag:
case SyntaxKind.JSDocTypedefTag:
return ScriptElementKind.typeElement;
case SyntaxKind.EnumDeclaration: return ScriptElementKind.enumElement;
case SyntaxKind.VariableDeclaration:
return getKindOfVariableDeclaration(node as VariableDeclaration);
case SyntaxKind.BindingElement:
return getKindOfVariableDeclaration(getRootDeclaration(node) as VariableDeclaration);
case SyntaxKind.ArrowFunction:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
return ScriptElementKind.functionElement;
case SyntaxKind.GetAccessor: return ScriptElementKind.memberGetAccessorElement;
case SyntaxKind.SetAccessor: return ScriptElementKind.memberSetAccessorElement;
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
return ScriptElementKind.memberFunctionElement;
case SyntaxKind.PropertyAssignment:
const { initializer } = node as PropertyAssignment;
return isFunctionLike(initializer) ? ScriptElementKind.memberFunctionElement : ScriptElementKind.memberVariableElement;
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.PropertySignature:
case SyntaxKind.ShorthandPropertyAssignment:
case SyntaxKind.SpreadAssignment:
return ScriptElementKind.memberVariableElement;
case SyntaxKind.IndexSignature: return ScriptElementKind.indexSignatureElement;
case SyntaxKind.ConstructSignature: return ScriptElementKind.constructSignatureElement;
case SyntaxKind.CallSignature: return ScriptElementKind.callSignatureElement;
case SyntaxKind.Constructor:
case SyntaxKind.ClassStaticBlockDeclaration:
return ScriptElementKind.constructorImplementationElement;
case SyntaxKind.TypeParameter: return ScriptElementKind.typeParameterElement;
case SyntaxKind.EnumMember: return ScriptElementKind.enumMemberElement;
case SyntaxKind.Parameter: return hasSyntacticModifier(node, ModifierFlags.ParameterPropertyModifier) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement;
case SyntaxKind.ImportEqualsDeclaration:
case SyntaxKind.ImportSpecifier:
case SyntaxKind.ExportSpecifier:
case SyntaxKind.NamespaceImport:
case SyntaxKind.NamespaceExport:
return ScriptElementKind.alias;
case SyntaxKind.BinaryExpression:
const kind = getAssignmentDeclarationKind(node as BinaryExpression);
const { right } = node as BinaryExpression;
switch (kind) {
case AssignmentDeclarationKind.ObjectDefinePropertyValue:
case AssignmentDeclarationKind.ObjectDefinePropertyExports:
case AssignmentDeclarationKind.ObjectDefinePrototypeProperty:
case AssignmentDeclarationKind.None:
return ScriptElementKind.unknown;
case AssignmentDeclarationKind.ExportsProperty:
case AssignmentDeclarationKind.ModuleExports:
const rightKind = getNodeKind(right);
return rightKind === ScriptElementKind.unknown ? ScriptElementKind.constElement : rightKind;
case AssignmentDeclarationKind.PrototypeProperty:
return isFunctionExpression(right) ? ScriptElementKind.memberFunctionElement : ScriptElementKind.memberVariableElement;
case AssignmentDeclarationKind.ThisProperty:
return ScriptElementKind.memberVariableElement; // property
case AssignmentDeclarationKind.Property:
// static method / property
return isFunctionExpression(right) ? ScriptElementKind.memberFunctionElement : ScriptElementKind.memberVariableElement;
case AssignmentDeclarationKind.Prototype:
return ScriptElementKind.localClassElement;
default: {
assertType<never>(kind);
return ScriptElementKind.unknown;
}
}
case SyntaxKind.Identifier:
return isImportClause(node.parent) ? ScriptElementKind.alias : ScriptElementKind.unknown;
case SyntaxKind.ExportAssignment:
const scriptKind = getNodeKind((node as ExportAssignment).expression);
// If the expression didn't come back with something (like it does for an identifiers)
return scriptKind === ScriptElementKind.unknown ? ScriptElementKind.constElement : scriptKind;
default:
return ScriptElementKind.unknown;
}
function getKindOfVariableDeclaration(v: VariableDeclaration): ScriptElementKind {
return isVarConst(v)
? ScriptElementKind.constElement
: isLet(v)
? ScriptElementKind.letElement
: ScriptElementKind.variableElement;
}
}
export function isThis(node: Node): boolean {
switch (node.kind) {
case SyntaxKind.ThisKeyword:
// case SyntaxKind.ThisType: TODO: GH#9267
return true;
case SyntaxKind.Identifier:
// 'this' as a parameter
return identifierIsThisKeyword(node as Identifier) && node.parent.kind === SyntaxKind.Parameter;
default:
return false;
}
}
// Matches the beginning of a triple slash directive
const tripleSlashDirectivePrefixRegex = /^\/\/\/\s*</;
export interface ListItemInfo {
listItemIndex: number;
list: Node;
}
export function getLineStartPositionForPosition(position: number, sourceFile: SourceFileLike): number {
const lineStarts = getLineStarts(sourceFile);
const line = sourceFile.getLineAndCharacterOfPosition(position).line;
return lineStarts[line];
}
export function rangeContainsRange(r1: TextRange, r2: TextRange): boolean {
return startEndContainsRange(r1.pos, r1.end, r2);
}
export function rangeContainsRangeExclusive(r1: TextRange, r2: TextRange): boolean {
return rangeContainsPositionExclusive(r1, r2.pos) && rangeContainsPositionExclusive(r1, r2.end);
}
export function rangeContainsPosition(r: TextRange, pos: number): boolean {
return r.pos <= pos && pos <= r.end;
}
export function rangeContainsPositionExclusive(r: TextRange, pos: number) {
return r.pos < pos && pos < r.end;
}
export function startEndContainsRange(start: number, end: number, range: TextRange): boolean {
return start <= range.pos && end >= range.end;
}
export function rangeContainsStartEnd(range: TextRange, start: number, end: number): boolean {
return range.pos <= start && range.end >= end;
}
export function rangeOverlapsWithStartEnd(r1: TextRange, start: number, end: number) {
return startEndOverlapsWithStartEnd(r1.pos, r1.end, start, end);
}
export function nodeOverlapsWithStartEnd(node: Node, sourceFile: SourceFile, start: number, end: number) {
return startEndOverlapsWithStartEnd(node.getStart(sourceFile), node.end, start, end);
}
export function startEndOverlapsWithStartEnd(start1: number, end1: number, start2: number, end2: number) {
const start = Math.max(start1, start2);
const end = Math.min(end1, end2);
return start < end;
}
/**
* Assumes `candidate.start <= position` holds.
*/
export function positionBelongsToNode(candidate: Node, position: number, sourceFile: SourceFile): boolean {
Debug.assert(candidate.pos <= position);
return position < candidate.end || !isCompletedNode(candidate, sourceFile);
}
function isCompletedNode(n: Node | undefined, sourceFile: SourceFile): boolean {
if (n === undefined || nodeIsMissing(n)) {
return false;
}
switch (n.kind) {
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.ObjectLiteralExpression:
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.TypeLiteral:
case SyntaxKind.Block:
case SyntaxKind.ModuleBlock:
case SyntaxKind.CaseBlock:
case SyntaxKind.NamedImports:
case SyntaxKind.NamedExports:
return nodeEndsWith(n, SyntaxKind.CloseBraceToken, sourceFile);
case SyntaxKind.CatchClause:
return isCompletedNode((n as CatchClause).block, sourceFile);
case SyntaxKind.NewExpression:
if (!(n as NewExpression).arguments) {
return true;
}
// falls through
case SyntaxKind.CallExpression:
case SyntaxKind.ParenthesizedExpression:
case SyntaxKind.ParenthesizedType:
return nodeEndsWith(n, SyntaxKind.CloseParenToken, sourceFile);
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType:
return isCompletedNode((n as SignatureDeclaration).type, sourceFile);
case SyntaxKind.Constructor:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
case SyntaxKind.ConstructSignature:
case SyntaxKind.CallSignature:
case SyntaxKind.ArrowFunction:
if ((n as FunctionLikeDeclaration).body) {
return isCompletedNode((n as FunctionLikeDeclaration).body, sourceFile);
}
if ((n as FunctionLikeDeclaration).type) {
return isCompletedNode((n as FunctionLikeDeclaration).type, sourceFile);
}
// Even though type parameters can be unclosed, we can get away with
// having at least a closing paren.
return hasChildOfKind(n, SyntaxKind.CloseParenToken, sourceFile);
case SyntaxKind.ModuleDeclaration:
return !!(n as ModuleDeclaration).body && isCompletedNode((n as ModuleDeclaration).body, sourceFile);
case SyntaxKind.IfStatement:
if ((n as IfStatement).elseStatement) {
return isCompletedNode((n as IfStatement).elseStatement, sourceFile);
}
return isCompletedNode((n as IfStatement).thenStatement, sourceFile);
case SyntaxKind.ExpressionStatement:
return isCompletedNode((n as ExpressionStatement).expression, sourceFile) ||
hasChildOfKind(n, SyntaxKind.SemicolonToken, sourceFile);
case SyntaxKind.ArrayLiteralExpression:
case SyntaxKind.ArrayBindingPattern:
case SyntaxKind.ElementAccessExpression:
case SyntaxKind.ComputedPropertyName:
case SyntaxKind.TupleType:
return nodeEndsWith(n, SyntaxKind.CloseBracketToken, sourceFile);
case SyntaxKind.IndexSignature:
if ((n as IndexSignatureDeclaration).type) {
return isCompletedNode((n as IndexSignatureDeclaration).type, sourceFile);
}
return hasChildOfKind(n, SyntaxKind.CloseBracketToken, sourceFile);
case SyntaxKind.CaseClause:
case SyntaxKind.DefaultClause:
// there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed
return false;
case SyntaxKind.ForStatement:
case SyntaxKind.ForInStatement:
case SyntaxKind.ForOfStatement:
case SyntaxKind.WhileStatement:
return isCompletedNode((n as IterationStatement).statement, sourceFile);
case SyntaxKind.DoStatement:
// rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')';
return hasChildOfKind(n, SyntaxKind.WhileKeyword, sourceFile)
? nodeEndsWith(n, SyntaxKind.CloseParenToken, sourceFile)
: isCompletedNode((n as DoStatement).statement, sourceFile);
case SyntaxKind.TypeQuery:
return isCompletedNode((n as TypeQueryNode).exprName, sourceFile);
case SyntaxKind.TypeOfExpression:
case SyntaxKind.DeleteExpression:
case SyntaxKind.VoidExpression:
case SyntaxKind.YieldExpression:
case SyntaxKind.SpreadElement:
const unaryWordExpression = n as (TypeOfExpression | DeleteExpression | VoidExpression | YieldExpression | SpreadElement);
return isCompletedNode(unaryWordExpression.expression, sourceFile);
case SyntaxKind.TaggedTemplateExpression:
return isCompletedNode((n as TaggedTemplateExpression).template, sourceFile);
case SyntaxKind.TemplateExpression:
const lastSpan = lastOrUndefined((n as TemplateExpression).templateSpans);
return isCompletedNode(lastSpan, sourceFile);
case SyntaxKind.TemplateSpan:
return nodeIsPresent((n as TemplateSpan).literal);
case SyntaxKind.ExportDeclaration:
case SyntaxKind.ImportDeclaration:
return nodeIsPresent((n as ExportDeclaration | ImportDeclaration).moduleSpecifier);
case SyntaxKind.PrefixUnaryExpression:
return isCompletedNode((n as PrefixUnaryExpression).operand, sourceFile);
case SyntaxKind.BinaryExpression:
return isCompletedNode((n as BinaryExpression).right, sourceFile);
case SyntaxKind.ConditionalExpression:
return isCompletedNode((n as ConditionalExpression).whenFalse, sourceFile);
default:
return true;
}
}
/*
* Checks if node ends with 'expectedLastToken'.
* If child at position 'length - 1' is 'SemicolonToken' it is skipped and 'expectedLastToken' is compared with child at position 'length - 2'.
*/
function nodeEndsWith(n: Node, expectedLastToken: SyntaxKind, sourceFile: SourceFile): boolean {
const children = n.getChildren(sourceFile);
if (children.length) {
const lastChild = last(children);
if (lastChild.kind === expectedLastToken) {
return true;
}
else if (lastChild.kind === SyntaxKind.SemicolonToken && children.length !== 1) {
return children[children.length - 2].kind === expectedLastToken;
}
}
return false;
}
export function findListItemInfo(node: Node): ListItemInfo | undefined {
const list = findContainingList(node);
// It is possible at this point for syntaxList to be undefined, either if
// node.parent had no list child, or if none of its list children contained
// the span of node. If this happens, return undefined. The caller should
// handle this case.
if (!list) {
return undefined;
}
const children = list.getChildren();
const listItemIndex = indexOfNode(children, node);
return {
listItemIndex,
list
};
}
export function hasChildOfKind(n: Node, kind: SyntaxKind, sourceFile: SourceFile): boolean {
return !!findChildOfKind(n, kind, sourceFile);
}
export function findChildOfKind<T extends Node>(n: Node, kind: T["kind"], sourceFile: SourceFileLike): T | undefined {
return find(n.getChildren(sourceFile), (c): c is T => c.kind === kind);
}
export function findContainingList(node: Node): SyntaxList | undefined {
// The node might be a list element (nonsynthetic) or a comma (synthetic). Either way, it will
// be parented by the container of the SyntaxList, not the SyntaxList itself.
// In order to find the list item index, we first need to locate SyntaxList itself and then search
// for the position of the relevant node (or comma).
const syntaxList = find(node.parent.getChildren(), (c): c is SyntaxList => isSyntaxList(c) && rangeContainsRange(c, node));
// Either we didn't find an appropriate list, or the list must contain us.
Debug.assert(!syntaxList || contains(syntaxList.getChildren(), node));
return syntaxList;
}
function isDefaultModifier(node: Node) {
return node.kind === SyntaxKind.DefaultKeyword;
}
function isClassKeyword(node: Node) {
return node.kind === SyntaxKind.ClassKeyword;
}
function isFunctionKeyword(node: Node) {
return node.kind === SyntaxKind.FunctionKeyword;
}
function getAdjustedLocationForClass(node: ClassDeclaration | ClassExpression) {
if (isNamedDeclaration(node)) {
return node.name;
}
if (isClassDeclaration(node)) {
// for class and function declarations, use the `default` modifier
// when the declaration is unnamed.
const defaultModifier = node.modifiers && find(node.modifiers, isDefaultModifier);
if (defaultModifier) return defaultModifier;
}
if (isClassExpression(node)) {
// for class expressions, use the `class` keyword when the class is unnamed
const classKeyword = find(node.getChildren(), isClassKeyword);
if (classKeyword) return classKeyword;
}
}
function getAdjustedLocationForFunction(node: FunctionDeclaration | FunctionExpression) {
if (isNamedDeclaration(node)) {
return node.name;
}
if (isFunctionDeclaration(node)) {
// for class and function declarations, use the `default` modifier
// when the declaration is unnamed.
const defaultModifier = find(node.modifiers!, isDefaultModifier);
if (defaultModifier) return defaultModifier;
}
if (isFunctionExpression(node)) {
// for function expressions, use the `function` keyword when the function is unnamed
const functionKeyword = find(node.getChildren(), isFunctionKeyword);
if (functionKeyword) return functionKeyword;
}
}
function getAncestorTypeNode(node: Node) {
let lastTypeNode: TypeNode | undefined;
findAncestor(node, a => {
if (isTypeNode(a)) {
lastTypeNode = a;
}
return !isQualifiedName(a.parent) && !isTypeNode(a.parent) && !isTypeElement(a.parent);
});
return lastTypeNode;
}
export function getContextualTypeFromParentOrAncestorTypeNode(node: Expression, checker: TypeChecker): Type | undefined {
const contextualType = getContextualTypeFromParent(node, checker);
if (contextualType) return contextualType;
const ancestorTypeNode = getAncestorTypeNode(node);
return ancestorTypeNode && checker.getTypeAtLocation(ancestorTypeNode);
}
function getAdjustedLocationForDeclaration(node: Node, forRename: boolean) {
if (!forRename) {
switch (node.kind) {
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ClassExpression:
return getAdjustedLocationForClass(node as ClassDeclaration | ClassExpression);
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
return getAdjustedLocationForFunction(node as FunctionDeclaration | FunctionExpression);
}
}
if (isNamedDeclaration(node)) {
return node.name;
}
}
function getAdjustedLocationForImportDeclaration(node: ImportDeclaration, forRename: boolean) {
if (node.importClause) {
if (node.importClause.name && node.importClause.namedBindings) {
// do not adjust if we have both a name and named bindings
return;
}
// /**/import [|name|] from ...;
// import /**/type [|name|] from ...;
if (node.importClause.name) {
return node.importClause.name;
}
// /**/import { [|name|] } from ...;
// /**/import { propertyName as [|name|] } from ...;
// /**/import * as [|name|] from ...;
// import /**/type { [|name|] } from ...;
// import /**/type { propertyName as [|name|] } from ...;
// import /**/type * as [|name|] from ...;
if (node.importClause.namedBindings) {
if (isNamedImports(node.importClause.namedBindings)) {
// do nothing if there is more than one binding
const onlyBinding = singleOrUndefined(node.importClause.namedBindings.elements);
if (!onlyBinding) {
return;
}
return onlyBinding.name;
}
else if (isNamespaceImport(node.importClause.namedBindings)) {
return node.importClause.namedBindings.name;
}
}
}
if (!forRename) {
// /**/import "[|module|]";
// /**/import ... from "[|module|]";
// import /**/type ... from "[|module|]";
return node.moduleSpecifier;
}
}
function getAdjustedLocationForExportDeclaration(node: ExportDeclaration, forRename: boolean) {
if (node.exportClause) {
// /**/export { [|name|] } ...
// /**/export { propertyName as [|name|] } ...
// /**/export * as [|name|] ...
// export /**/type { [|name|] } from ...
// export /**/type { propertyName as [|name|] } from ...
// export /**/type * as [|name|] ...
if (isNamedExports(node.exportClause)) {
// do nothing if there is more than one binding
const onlyBinding = singleOrUndefined(node.exportClause.elements);
if (!onlyBinding) {
return;
}
return node.exportClause.elements[0].name;
}
else if (isNamespaceExport(node.exportClause)) {
return node.exportClause.name;
}
}
if (!forRename) {
// /**/export * from "[|module|]";
// export /**/type * from "[|module|]";
return node.moduleSpecifier;
}
}
function getAdjustedLocationForHeritageClause(node: HeritageClause) {
// /**/extends [|name|]
// /**/implements [|name|]
if (node.types.length === 1) {
return node.types[0].expression;
}
// /**/extends name1, name2 ...
// /**/implements name1, name2 ...
}
function getAdjustedLocation(node: Node, forRename: boolean): Node {
const { parent } = node;
// /**/<modifier> [|name|] ...
// /**/<modifier> <class|interface|type|enum|module|namespace|function|get|set> [|name|] ...
// /**/<class|interface|type|enum|module|namespace|function|get|set> [|name|] ...
// /**/import [|name|] = ...
//
// NOTE: If the node is a modifier, we don't adjust its location if it is the `default` modifier as that is handled
// specially by `getSymbolAtLocation`.
if (isModifier(node) && (forRename || node.kind !== SyntaxKind.DefaultKeyword) ? contains(parent.modifiers, node) :
node.kind === SyntaxKind.ClassKeyword ? isClassDeclaration(parent) || isClassExpression(node) :
node.kind === SyntaxKind.FunctionKeyword ? isFunctionDeclaration(parent) || isFunctionExpression(node) :
node.kind === SyntaxKind.InterfaceKeyword ? isInterfaceDeclaration(parent) :
node.kind === SyntaxKind.EnumKeyword ? isEnumDeclaration(parent) :
node.kind === SyntaxKind.TypeKeyword ? isTypeAliasDeclaration(parent) :
node.kind === SyntaxKind.NamespaceKeyword || node.kind === SyntaxKind.ModuleKeyword ? isModuleDeclaration(parent) :
node.kind === SyntaxKind.ImportKeyword ? isImportEqualsDeclaration(parent) :
node.kind === SyntaxKind.GetKeyword ? isGetAccessorDeclaration(parent) :
node.kind === SyntaxKind.SetKeyword && isSetAccessorDeclaration(parent)) {
const location = getAdjustedLocationForDeclaration(parent, forRename);
if (location) {
return location;
}
}
// /**/<var|let|const> [|name|] ...
if ((node.kind === SyntaxKind.VarKeyword || node.kind === SyntaxKind.ConstKeyword || node.kind === SyntaxKind.LetKeyword) &&
isVariableDeclarationList(parent) && parent.declarations.length === 1) {
const decl = parent.declarations[0];
if (isIdentifier(decl.name)) {
return decl.name;
}
}
if (node.kind === SyntaxKind.TypeKeyword) {
// import /**/type [|name|] from ...;
// import /**/type { [|name|] } from ...;
// import /**/type { propertyName as [|name|] } from ...;
// import /**/type ... from "[|module|]";
if (isImportClause(parent) && parent.isTypeOnly) {
const location = getAdjustedLocationForImportDeclaration(parent.parent, forRename);
if (location) {
return location;
}
}
// export /**/type { [|name|] } from ...;
// export /**/type { propertyName as [|name|] } from ...;
// export /**/type * from "[|module|]";
// export /**/type * as ... from "[|module|]";
if (isExportDeclaration(parent) && parent.isTypeOnly) {
const location = getAdjustedLocationForExportDeclaration(parent, forRename);
if (location) {
return location;
}
}
}
// import { propertyName /**/as [|name|] } ...
// import * /**/as [|name|] ...
// export { propertyName /**/as [|name|] } ...
// export * /**/as [|name|] ...
if (node.kind === SyntaxKind.AsKeyword) {
if (isImportSpecifier(parent) && parent.propertyName ||
isExportSpecifier(parent) && parent.propertyName ||
isNamespaceImport(parent) ||
isNamespaceExport(parent)) {
return parent.name;
}
if (isExportDeclaration(parent) && parent.exportClause && isNamespaceExport(parent.exportClause)) {
return parent.exportClause.name;
}
}
// /**/import [|name|] from ...;
// /**/import { [|name|] } from ...;
// /**/import { propertyName as [|name|] } from ...;
// /**/import ... from "[|module|]";
// /**/import "[|module|]";
if (node.kind === SyntaxKind.ImportKeyword && isImportDeclaration(parent)) {
const location = getAdjustedLocationForImportDeclaration(parent, forRename);
if (location) {
return location;
}
}
if (node.kind === SyntaxKind.ExportKeyword) {
// /**/export { [|name|] } ...;
// /**/export { propertyName as [|name|] } ...;
// /**/export * from "[|module|]";
// /**/export * as ... from "[|module|]";
if (isExportDeclaration(parent)) {
const location = getAdjustedLocationForExportDeclaration(parent, forRename);
if (location) {
return location;
}
}
// NOTE: We don't adjust the location of the `default` keyword as that is handled specially by `getSymbolAtLocation`.
// /**/export default [|name|];
// /**/export = [|name|];
if (isExportAssignment(parent)) {
return skipOuterExpressions(parent.expression);
}
}
// import name = /**/require("[|module|]");
if (node.kind === SyntaxKind.RequireKeyword && isExternalModuleReference(parent)) {
return parent.expression;
}
// import ... /**/from "[|module|]";
// export ... /**/from "[|module|]";
if (node.kind === SyntaxKind.FromKeyword && (isImportDeclaration(parent) || isExportDeclaration(parent)) && parent.moduleSpecifier) {
return parent.moduleSpecifier;