-
Notifications
You must be signed in to change notification settings - Fork 12.8k
/
Copy pathfindAllReferences.ts
2803 lines (2545 loc) · 135 KB
/
findAllReferences.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
createImportTracker,
ExportInfo,
ExportKind,
findModuleReferences,
getExportInfo,
getImportOrExportSymbol,
ImportExport,
ImportsResult,
ImportTracker,
ModuleReference,
} from "./_namespaces/ts.FindAllReferences.js";
import {
__String,
addToSeen,
append,
AssignmentDeclarationKind,
BinaryExpression,
BindingElement,
Block,
CallExpression,
CancellationToken,
canHaveSymbol,
cast,
CheckFlags,
ClassLikeDeclaration,
climbPastPropertyAccess,
compareValues,
ConstructorDeclaration,
contains,
createQueue,
createTextSpan,
createTextSpanFromBounds,
createTextSpanFromRange,
Debug,
Declaration,
displayPart,
DocumentSpan,
emptyArray,
emptyOptions,
escapeLeadingUnderscores,
ExportSpecifier,
Expression,
externalHelpersModuleNameText,
FileIncludeReason,
FileReference,
filter,
find,
findAncestor,
findChildOfKind,
findIndex,
first,
firstDefined,
firstOrUndefined,
flatMap,
forEach,
forEachChild,
forEachChildRecursively,
forEachReturnStatement,
ForInOrOfStatement,
FunctionDeclaration,
FunctionExpression,
FunctionLikeDeclaration,
GetAccessorDeclaration,
getAdjustedReferenceLocation,
getAdjustedRenameLocation,
getAllSuperTypeNodes,
getAncestor,
getAssignmentDeclarationKind,
getCheckFlags,
getContainerNode,
getContainingObjectLiteralElement,
getContextualTypeFromParentOrAncestorTypeNode,
getDeclarationFromName,
getDeclarationOfKind,
getEffectiveModifierFlags,
getLocalSymbolForExportDefault,
getMeaningFromDeclaration,
getMeaningFromLocation,
getNameOfDeclaration,
getNameTable,
getNextJSDocCommentLocation,
getNodeId,
getNodeKind,
getPropertySymbolFromBindingElement,
getPropertySymbolsFromContextualType,
getQuoteFromPreference,
getReferencedFileLocation,
getSuperContainer,
getSymbolId,
getSyntacticModifierFlags,
getTargetLabel,
getTextOfNode,
getThisContainer,
getTouchingPropertyName,
GoToDefinition,
hasEffectiveModifier,
hasInitializer,
hasSyntacticModifier,
hasType,
HighlightSpan,
HighlightSpanKind,
Identifier,
ImplementationLocation,
InterfaceDeclaration,
InternalSymbolName,
isAccessExpression,
isArrayLiteralOrObjectLiteralDestructuringPattern,
isAssertionExpression,
isBinaryExpression,
isBindableObjectDefinePropertyCall,
isBindingElement,
isBreakOrContinueStatement,
isCallExpression,
isCallExpressionTarget,
isCatchClause,
isClassLike,
isClassStaticBlockDeclaration,
isComputedPropertyName,
isConstructorDeclaration,
isDeclaration,
isDeclarationName,
isExportAssignment,
isExportSpecifier,
isExpressionOfExternalModuleImportEqualsDeclaration,
isExpressionStatement,
isExpressionWithTypeArguments,
isExternalModule,
isExternalModuleSymbol,
isExternalOrCommonJsModule,
isForInOrOfStatement,
isFunctionExpression,
isFunctionLike,
isFunctionLikeDeclaration,
isIdentifier,
isIdentifierPart,
isImportMeta,
isImportOrExportSpecifier,
isImportSpecifier,
isImportTypeNode,
isInJSFile,
isInNonReferenceComment,
isInString,
isInterfaceDeclaration,
isJSDocMemberName,
isJSDocPropertyLikeTag,
isJSDocTag,
isJSDocTypeLiteral,
isJsxClosingElement,
isJsxElement,
isJsxFragment,
isJsxOpeningElement,
isJsxSelfClosingElement,
isJumpStatementTarget,
isLabeledStatement,
isLabelOfLabeledStatement,
isLiteralComputedPropertyDeclarationName,
isLiteralNameOfPropertyDeclarationOrIndexAccess,
isLiteralTypeNode,
isMethodOrAccessor,
isModuleDeclaration,
isModuleExportsAccessExpression,
isModuleOrEnumDeclaration,
isModuleSpecifierLike,
isNameOfModuleDeclaration,
isNamespaceExportDeclaration,
isNewExpressionTarget,
isNoSubstitutionTemplateLiteral,
isNumericLiteral,
isObjectBindingElementWithoutPropertyName,
isObjectLiteralExpression,
isObjectLiteralMethod,
isParameter,
isParameterPropertyDeclaration,
isPrivateIdentifierClassElementDeclaration,
isPropertyAccessExpression,
isPropertySignature,
isQualifiedName,
isReferencedFile,
isReferenceFileLocation,
isRightSideOfPropertyAccess,
isSatisfiesExpression,
isShorthandPropertyAssignment,
isSourceFile,
isStatement,
isStatic,
isStaticModifier,
isStringLiteralLike,
isSuperProperty,
isThis,
isTypeAliasDeclaration,
isTypeElement,
isTypeKeyword,
isTypeLiteralNode,
isTypeNode,
isTypeOperatorNode,
isUnionTypeNode,
isVariableDeclarationInitializedToBareOrAccessedRequire,
isVariableDeclarationList,
isVariableLike,
isVariableStatement,
isVoidExpression,
isWriteAccess,
JSDocPropertyLikeTag,
length,
map,
mapDefined,
MethodDeclaration,
ModifierFlags,
ModuleDeclaration,
ModuleExportName,
moduleExportNameIsDefault,
MultiMap,
NamedDeclaration,
Node,
NodeFlags,
nodeSeenTracker,
NumericLiteral,
ObjectLiteralExpression,
or,
ParameterDeclaration,
ParenthesizedExpression,
Path,
PrivateIdentifier,
Program,
PropertyAccessExpression,
PropertyAssignment,
PropertyDeclaration,
punctuationPart,
QuotePreference,
rangeIsOnSingleLine,
ReferencedSymbol,
ReferencedSymbolDefinitionInfo,
ReferencedSymbolEntry,
ReferenceEntry,
RenameLocation,
ScriptElementKind,
ScriptTarget,
SemanticMeaning,
SetAccessorDeclaration,
SignatureDeclaration,
skipAlias,
some,
SourceFile,
StringLiteral,
StringLiteralLike,
stripQuotes,
SuperContainer,
SwitchStatement,
Symbol,
SymbolDisplay,
SymbolDisplayPart,
SymbolDisplayPartKind,
SymbolFlags,
symbolName,
SyntaxKind,
textPart,
TextSpan,
tokenToString,
TransformFlags,
tryAddToSet,
tryCast,
tryGetClassExtendingExpressionWithTypeArguments,
tryGetImportFromModuleSpecifier,
TypeChecker,
TypeLiteralNode,
VariableDeclaration,
} from "./_namespaces/ts.js";
/** @internal */
export interface SymbolAndEntries {
readonly definition: Definition | undefined;
readonly references: readonly Entry[];
}
/** @internal */
export const enum DefinitionKind {
Symbol,
Label,
Keyword,
This,
String,
TripleSlashReference,
}
/** @internal */
export type Definition =
| { readonly type: DefinitionKind.Symbol; readonly symbol: Symbol; }
| { readonly type: DefinitionKind.Label; readonly node: Identifier; }
| { readonly type: DefinitionKind.Keyword; readonly node: Node; }
| { readonly type: DefinitionKind.This; readonly node: Node; }
| { readonly type: DefinitionKind.String; readonly node: StringLiteralLike; }
| { readonly type: DefinitionKind.TripleSlashReference; readonly reference: FileReference; readonly file: SourceFile; };
/** @internal */
export const enum EntryKind {
Span,
Node,
StringLiteral,
SearchedLocalFoundProperty,
SearchedPropertyFoundLocal,
}
/** @internal */
export type NodeEntryKind = EntryKind.Node | EntryKind.StringLiteral | EntryKind.SearchedLocalFoundProperty | EntryKind.SearchedPropertyFoundLocal;
/** @internal */
export type Entry = NodeEntry | SpanEntry;
/** @internal */
export interface ContextWithStartAndEndNode {
start: Node;
end: Node;
}
/** @internal */
export type ContextNode = Node | ContextWithStartAndEndNode;
/** @internal */
export interface NodeEntry {
readonly kind: NodeEntryKind;
readonly node: Node;
readonly context?: ContextNode;
}
/** @internal */
export interface SpanEntry {
readonly kind: EntryKind.Span;
readonly fileName: string;
readonly textSpan: TextSpan;
}
function nodeEntry(node: Node, kind: NodeEntryKind = EntryKind.Node): NodeEntry {
return {
kind,
node: (node as NamedDeclaration).name || node,
context: getContextNodeForNodeEntry(node),
};
}
/** @internal */
export function isContextWithStartAndEndNode(node: ContextNode): node is ContextWithStartAndEndNode {
return node && (node as Node).kind === undefined;
}
function getContextNodeForNodeEntry(node: Node): ContextNode | undefined {
if (isDeclaration(node)) {
return getContextNode(node);
}
if (!node.parent) return undefined;
if (!isDeclaration(node.parent) && !isExportAssignment(node.parent)) {
// Special property assignment in javascript
if (isInJSFile(node)) {
const binaryExpression = isBinaryExpression(node.parent) ?
node.parent :
isAccessExpression(node.parent) &&
isBinaryExpression(node.parent.parent) &&
node.parent.parent.left === node.parent ?
node.parent.parent :
undefined;
if (binaryExpression && getAssignmentDeclarationKind(binaryExpression) !== AssignmentDeclarationKind.None) {
return getContextNode(binaryExpression);
}
}
// Jsx Tags
if (isJsxOpeningElement(node.parent) || isJsxClosingElement(node.parent)) {
return node.parent.parent;
}
else if (
isJsxSelfClosingElement(node.parent) ||
isLabeledStatement(node.parent) ||
isBreakOrContinueStatement(node.parent)
) {
return node.parent;
}
else if (isStringLiteralLike(node)) {
const validImport = tryGetImportFromModuleSpecifier(node);
if (validImport) {
const declOrStatement = findAncestor(validImport, node =>
isDeclaration(node) ||
isStatement(node) ||
isJSDocTag(node))!;
return isDeclaration(declOrStatement) ?
getContextNode(declOrStatement) :
declOrStatement;
}
}
// Handle computed property name
const propertyName = findAncestor(node, isComputedPropertyName);
return propertyName ?
getContextNode(propertyName.parent) :
undefined;
}
if (
node.parent.name === node || // node is name of declaration, use parent
isConstructorDeclaration(node.parent) ||
isExportAssignment(node.parent) ||
// Property name of the import export specifier or binding pattern, use parent
((isImportOrExportSpecifier(node.parent) || isBindingElement(node.parent))
&& node.parent.propertyName === node) ||
// Is default export
(node.kind === SyntaxKind.DefaultKeyword && hasSyntacticModifier(node.parent, ModifierFlags.ExportDefault))
) {
return getContextNode(node.parent);
}
return undefined;
}
/** @internal */
export function getContextNode(node: NamedDeclaration | BinaryExpression | ForInOrOfStatement | SwitchStatement | undefined): ContextNode | undefined {
if (!node) return undefined;
switch (node.kind) {
case SyntaxKind.VariableDeclaration:
return !isVariableDeclarationList(node.parent) || node.parent.declarations.length !== 1 ?
node :
isVariableStatement(node.parent.parent) ?
node.parent.parent :
isForInOrOfStatement(node.parent.parent) ?
getContextNode(node.parent.parent) :
node.parent;
case SyntaxKind.BindingElement:
return getContextNode(node.parent.parent as NamedDeclaration);
case SyntaxKind.ImportSpecifier:
return node.parent.parent.parent;
case SyntaxKind.ExportSpecifier:
case SyntaxKind.NamespaceImport:
return node.parent.parent;
case SyntaxKind.ImportClause:
case SyntaxKind.NamespaceExport:
return node.parent;
case SyntaxKind.BinaryExpression:
return isExpressionStatement(node.parent) ?
node.parent :
node;
case SyntaxKind.ForOfStatement:
case SyntaxKind.ForInStatement:
return {
start: (node as ForInOrOfStatement).initializer,
end: (node as ForInOrOfStatement).expression,
};
case SyntaxKind.PropertyAssignment:
case SyntaxKind.ShorthandPropertyAssignment:
return isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent) ?
getContextNode(
findAncestor(node.parent, node => isBinaryExpression(node) || isForInOrOfStatement(node)) as BinaryExpression | ForInOrOfStatement,
) :
node;
case SyntaxKind.SwitchStatement:
return {
start: find(node.getChildren(node.getSourceFile()), node => node.kind === SyntaxKind.SwitchKeyword)!,
end: (node as SwitchStatement).caseBlock,
};
default:
return node;
}
}
/** @internal */
export function toContextSpan(textSpan: TextSpan, sourceFile: SourceFile, context: ContextNode | undefined): { contextSpan: TextSpan; } | undefined {
if (!context) return undefined;
const contextSpan = isContextWithStartAndEndNode(context) ?
getTextSpan(context.start, sourceFile, context.end) :
getTextSpan(context, sourceFile);
return contextSpan.start !== textSpan.start || contextSpan.length !== textSpan.length ?
{ contextSpan } :
undefined;
}
/** @internal */
export const enum FindReferencesUse {
/**
* When searching for references to a symbol, the location will not be adjusted (this is the default behavior when not specified).
*/
Other,
/**
* When searching for references to a symbol, the location will be adjusted if the cursor was on a keyword.
*/
References,
/**
* When searching for references to a symbol, the location will be adjusted if the cursor was on a keyword.
* Unlike `References`, the location will only be adjusted keyword belonged to a declaration with a valid name.
* If set, we will find fewer references -- if it is referenced by several different names, we still only find references for the original name.
*/
Rename,
}
/** @internal */
export interface Options {
readonly findInStrings?: boolean;
readonly findInComments?: boolean;
readonly use?: FindReferencesUse;
/** True if we are searching for implementations. We will have a different method of adding references if so. */
readonly implementations?: boolean;
/**
* True to opt in for enhanced renaming of shorthand properties and import/export specifiers.
* The options controls the behavior for the whole rename operation; it cannot be changed on a per-file basis.
* Default is false for backwards compatibility.
*/
readonly providePrefixAndSuffixTextForRename?: boolean;
}
/** @internal */
export function findReferencedSymbols(program: Program, cancellationToken: CancellationToken, sourceFiles: readonly SourceFile[], sourceFile: SourceFile, position: number): ReferencedSymbol[] | undefined {
const node = getTouchingPropertyName(sourceFile, position);
const options = { use: FindReferencesUse.References };
const referencedSymbols = Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options);
const checker = program.getTypeChecker();
// Unless the starting node is a declaration (vs e.g. JSDoc), don't attempt to compute isDefinition
const adjustedNode = Core.getAdjustedNode(node, options);
const symbol = isDefinitionForReference(adjustedNode) ? checker.getSymbolAtLocation(adjustedNode) : undefined;
return !referencedSymbols || !referencedSymbols.length ? undefined : mapDefined<SymbolAndEntries, ReferencedSymbol>(referencedSymbols, ({ definition, references }) =>
// Only include referenced symbols that have a valid definition.
definition && {
definition: checker.runWithCancellationToken(cancellationToken, checker => definitionToReferencedSymbolDefinitionInfo(definition, checker, node)),
references: references.map(r => toReferencedSymbolEntry(r, symbol)),
});
}
function isDefinitionForReference(node: Node): boolean {
return node.kind === SyntaxKind.DefaultKeyword
|| !!getDeclarationFromName(node)
|| isLiteralComputedPropertyDeclarationName(node)
|| (node.kind === SyntaxKind.ConstructorKeyword && isConstructorDeclaration(node.parent));
}
/** @internal */
export function getImplementationsAtPosition(program: Program, cancellationToken: CancellationToken, sourceFiles: readonly SourceFile[], sourceFile: SourceFile, position: number): ImplementationLocation[] | undefined {
const node = getTouchingPropertyName(sourceFile, position);
let referenceEntries: Entry[] | undefined;
const entries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position);
if (
node.parent.kind === SyntaxKind.PropertyAccessExpression
|| node.parent.kind === SyntaxKind.BindingElement
|| node.parent.kind === SyntaxKind.ElementAccessExpression
|| node.kind === SyntaxKind.SuperKeyword
) {
referenceEntries = entries && [...entries];
}
else if (entries) {
const queue = createQueue(entries);
const seenNodes = new Set<number>();
while (!queue.isEmpty()) {
const entry = queue.dequeue() as NodeEntry;
if (!addToSeen(seenNodes, getNodeId(entry.node))) {
continue;
}
referenceEntries = append(referenceEntries, entry);
const entries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, entry.node, entry.node.pos);
if (entries) {
queue.enqueue(...entries);
}
}
}
const checker = program.getTypeChecker();
return map(referenceEntries, entry => toImplementationLocation(entry, checker));
}
function getImplementationReferenceEntries(program: Program, cancellationToken: CancellationToken, sourceFiles: readonly SourceFile[], node: Node, position: number): readonly Entry[] | undefined {
if (node.kind === SyntaxKind.SourceFile) {
return undefined;
}
const checker = program.getTypeChecker();
// If invoked directly on a shorthand property assignment, then return
// the declaration of the symbol being assigned (not the symbol being assigned to).
if (node.parent.kind === SyntaxKind.ShorthandPropertyAssignment) {
const result: NodeEntry[] = [];
Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, node => result.push(nodeEntry(node)));
return result;
}
else if (node.kind === SyntaxKind.SuperKeyword || isSuperProperty(node.parent)) {
// References to and accesses on the super keyword only have one possible implementation, so no
// need to "Find all References"
const symbol = checker.getSymbolAtLocation(node)!;
return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)];
}
else {
// Perform "Find all References" and retrieve only those that are implementations
return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true, use: FindReferencesUse.References });
}
}
/** @internal */
export function findReferenceOrRenameEntries<T>(
program: Program,
cancellationToken: CancellationToken,
sourceFiles: readonly SourceFile[],
node: Node,
position: number,
options: Options | undefined,
convertEntry: ToReferenceOrRenameEntry<T>,
): T[] | undefined {
return map(flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), entry => convertEntry(entry, node, program.getTypeChecker()));
}
/** @internal */
export type ToReferenceOrRenameEntry<T> = (entry: Entry, originalNode: Node, checker: TypeChecker) => T;
/** @internal */
export function getReferenceEntriesForNode(
position: number,
node: Node,
program: Program,
sourceFiles: readonly SourceFile[],
cancellationToken: CancellationToken,
options: Options = {},
sourceFilesSet: ReadonlySet<string> = new Set(sourceFiles.map(f => f.fileName)),
): readonly Entry[] | undefined {
return flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet));
}
function flattenEntries(referenceSymbols: readonly SymbolAndEntries[] | undefined): readonly Entry[] | undefined {
return referenceSymbols && flatMap(referenceSymbols, r => r.references);
}
function definitionToReferencedSymbolDefinitionInfo(def: Definition, checker: TypeChecker, originalNode: Node): ReferencedSymbolDefinitionInfo {
const info = ((): { sourceFile: SourceFile; textSpan: TextSpan; name: string; kind: ScriptElementKind; displayParts: SymbolDisplayPart[]; context?: Node | ContextWithStartAndEndNode; } => {
switch (def.type) {
case DefinitionKind.Symbol: {
const { symbol } = def;
const { displayParts, kind } = getDefinitionKindAndDisplayParts(symbol, checker, originalNode);
const name = displayParts.map(p => p.text).join("");
const declaration = symbol.declarations && firstOrUndefined(symbol.declarations);
const node = declaration ? (getNameOfDeclaration(declaration) || declaration) : originalNode;
return {
...getFileAndTextSpanFromNode(node),
name,
kind,
displayParts,
context: getContextNode(declaration),
};
}
case DefinitionKind.Label: {
const { node } = def;
return { ...getFileAndTextSpanFromNode(node), name: node.text, kind: ScriptElementKind.label, displayParts: [displayPart(node.text, SymbolDisplayPartKind.text)] };
}
case DefinitionKind.Keyword: {
const { node } = def;
const name = tokenToString(node.kind)!;
return { ...getFileAndTextSpanFromNode(node), name, kind: ScriptElementKind.keyword, displayParts: [{ text: name, kind: ScriptElementKind.keyword }] };
}
case DefinitionKind.This: {
const { node } = def;
const symbol = checker.getSymbolAtLocation(node);
const displayParts = symbol && SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(
checker,
symbol,
node.getSourceFile(),
getContainerNode(node),
node,
).displayParts || [textPart("this")];
return { ...getFileAndTextSpanFromNode(node), name: "this", kind: ScriptElementKind.variableElement, displayParts };
}
case DefinitionKind.String: {
const { node } = def;
return {
...getFileAndTextSpanFromNode(node),
name: node.text,
kind: ScriptElementKind.variableElement,
displayParts: [displayPart(getTextOfNode(node), SymbolDisplayPartKind.stringLiteral)],
};
}
case DefinitionKind.TripleSlashReference: {
return {
textSpan: createTextSpanFromRange(def.reference),
sourceFile: def.file,
name: def.reference.fileName,
kind: ScriptElementKind.string,
displayParts: [displayPart(`"${def.reference.fileName}"`, SymbolDisplayPartKind.stringLiteral)],
};
}
default:
return Debug.assertNever(def);
}
})();
const { sourceFile, textSpan, name, kind, displayParts, context } = info;
return {
containerKind: ScriptElementKind.unknown,
containerName: "",
fileName: sourceFile.fileName,
kind,
name,
textSpan,
displayParts,
...toContextSpan(textSpan, sourceFile, context),
};
}
function getFileAndTextSpanFromNode(node: Node) {
const sourceFile = node.getSourceFile();
return {
sourceFile,
textSpan: getTextSpan(isComputedPropertyName(node) ? node.expression : node, sourceFile),
};
}
function getDefinitionKindAndDisplayParts(symbol: Symbol, checker: TypeChecker, node: Node): { displayParts: SymbolDisplayPart[]; kind: ScriptElementKind; } {
const meaning = Core.getIntersectingMeaningFromDeclarations(node, symbol);
const enclosingDeclaration = symbol.declarations && firstOrUndefined(symbol.declarations) || node;
const { displayParts, symbolKind } = SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning);
return { displayParts, kind: symbolKind };
}
/** @internal */
export function toRenameLocation(entry: Entry, originalNode: Node, checker: TypeChecker, providePrefixAndSuffixText: boolean, quotePreference: QuotePreference): RenameLocation {
return { ...entryToDocumentSpan(entry), ...(providePrefixAndSuffixText && getPrefixAndSuffixText(entry, originalNode, checker, quotePreference)) };
}
function toReferencedSymbolEntry(entry: Entry, symbol: Symbol | undefined): ReferencedSymbolEntry {
const referenceEntry = toReferenceEntry(entry);
if (!symbol) return referenceEntry;
return {
...referenceEntry,
isDefinition: entry.kind !== EntryKind.Span && isDeclarationOfSymbol(entry.node, symbol),
};
}
/** @internal */
export function toReferenceEntry(entry: Entry): ReferenceEntry {
const documentSpan = entryToDocumentSpan(entry);
if (entry.kind === EntryKind.Span) {
return { ...documentSpan, isWriteAccess: false };
}
const { kind, node } = entry;
return {
...documentSpan,
isWriteAccess: isWriteAccessForReference(node),
isInString: kind === EntryKind.StringLiteral ? true : undefined,
};
}
function entryToDocumentSpan(entry: Entry): DocumentSpan {
if (entry.kind === EntryKind.Span) {
return { textSpan: entry.textSpan, fileName: entry.fileName };
}
else {
const sourceFile = entry.node.getSourceFile();
const textSpan = getTextSpan(entry.node, sourceFile);
return {
textSpan,
fileName: sourceFile.fileName,
...toContextSpan(textSpan, sourceFile, entry.context),
};
}
}
interface PrefixAndSuffix {
readonly prefixText?: string;
readonly suffixText?: string;
}
function getPrefixAndSuffixText(entry: Entry, originalNode: Node, checker: TypeChecker, quotePreference: QuotePreference): PrefixAndSuffix {
if (entry.kind !== EntryKind.Span && (isIdentifier(originalNode) || isStringLiteralLike(originalNode))) {
const { node, kind } = entry;
const parent = node.parent;
const name = originalNode.text;
const isShorthandAssignment = isShorthandPropertyAssignment(parent);
if (isShorthandAssignment || (isObjectBindingElementWithoutPropertyName(parent) && parent.name === node && parent.dotDotDotToken === undefined)) {
const prefixColon: PrefixAndSuffix = { prefixText: name + ": " };
const suffixColon: PrefixAndSuffix = { suffixText: ": " + name };
if (kind === EntryKind.SearchedLocalFoundProperty) {
return prefixColon;
}
if (kind === EntryKind.SearchedPropertyFoundLocal) {
return suffixColon;
}
// In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol.
// For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol.
if (isShorthandAssignment) {
const grandParent = parent.parent;
if (
isObjectLiteralExpression(grandParent) &&
isBinaryExpression(grandParent.parent) &&
isModuleExportsAccessExpression(grandParent.parent.left)
) {
return prefixColon;
}
return suffixColon;
}
else {
return prefixColon;
}
}
else if (isImportSpecifier(parent) && !parent.propertyName) {
// If the original symbol was using this alias, just rename the alias.
const originalSymbol = isExportSpecifier(originalNode.parent) ? checker.getExportSpecifierLocalTargetSymbol(originalNode.parent) : checker.getSymbolAtLocation(originalNode);
return contains(originalSymbol!.declarations, parent) ? { prefixText: name + " as " } : emptyOptions;
}
else if (isExportSpecifier(parent) && !parent.propertyName) {
// If the symbol for the node is same as declared node symbol use prefix text
return originalNode === entry.node || checker.getSymbolAtLocation(originalNode) === checker.getSymbolAtLocation(entry.node) ?
{ prefixText: name + " as " } :
{ suffixText: " as " + name };
}
}
// If the node is a numerical indexing literal, then add quotes around the property access.
if (entry.kind !== EntryKind.Span && isNumericLiteral(entry.node) && isAccessExpression(entry.node.parent)) {
const quote = getQuoteFromPreference(quotePreference);
return { prefixText: quote, suffixText: quote };
}
return emptyOptions;
}
function toImplementationLocation(entry: Entry, checker: TypeChecker): ImplementationLocation {
const documentSpan = entryToDocumentSpan(entry);
if (entry.kind !== EntryKind.Span) {
const { node } = entry;
return {
...documentSpan,
...implementationKindDisplayParts(node, checker),
};
}
else {
return { ...documentSpan, kind: ScriptElementKind.unknown, displayParts: [] };
}
}
function implementationKindDisplayParts(node: Node, checker: TypeChecker): { kind: ScriptElementKind; displayParts: SymbolDisplayPart[]; } {
const symbol = checker.getSymbolAtLocation(isDeclaration(node) && node.name ? node.name : node);
if (symbol) {
return getDefinitionKindAndDisplayParts(symbol, checker, node);
}
else if (node.kind === SyntaxKind.ObjectLiteralExpression) {
return {
kind: ScriptElementKind.interfaceElement,
displayParts: [punctuationPart(SyntaxKind.OpenParenToken), textPart("object literal"), punctuationPart(SyntaxKind.CloseParenToken)],
};
}
else if (node.kind === SyntaxKind.ClassExpression) {
return {
kind: ScriptElementKind.localClassElement,
displayParts: [punctuationPart(SyntaxKind.OpenParenToken), textPart("anonymous local class"), punctuationPart(SyntaxKind.CloseParenToken)],
};
}
else {
return { kind: getNodeKind(node), displayParts: [] };
}
}
/** @internal */
export function toHighlightSpan(entry: Entry): { fileName: string; span: HighlightSpan; } {
const documentSpan = entryToDocumentSpan(entry);
if (entry.kind === EntryKind.Span) {
return {
fileName: documentSpan.fileName,
span: {
textSpan: documentSpan.textSpan,
kind: HighlightSpanKind.reference,
},
};
}
const writeAccess = isWriteAccessForReference(entry.node);
const span: HighlightSpan = {
textSpan: documentSpan.textSpan,
kind: writeAccess ? HighlightSpanKind.writtenReference : HighlightSpanKind.reference,
isInString: entry.kind === EntryKind.StringLiteral ? true : undefined,
...documentSpan.contextSpan && { contextSpan: documentSpan.contextSpan },
};
return { fileName: documentSpan.fileName, span };
}
function getTextSpan(node: Node, sourceFile: SourceFile, endNode?: Node): TextSpan {
let start = node.getStart(sourceFile);
let end = (endNode || node).getEnd();
if (isStringLiteralLike(node) && (end - start) > 2) {
Debug.assert(endNode === undefined);
start += 1;
end -= 1;
}
if (endNode?.kind === SyntaxKind.CaseBlock) {
end = endNode.getFullStart();
}
return createTextSpanFromBounds(start, end);
}
function getTextSpanOfEntry(entry: Entry) {
return entry.kind === EntryKind.Span ? entry.textSpan :
getTextSpan(entry.node, entry.node.getSourceFile());
}
/**
* A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment.
*
* @internal
*/
export function isWriteAccessForReference(node: Node): boolean {
const decl = getDeclarationFromName(node);
return !!decl && declarationIsWriteAccess(decl) || node.kind === SyntaxKind.DefaultKeyword || isWriteAccess(node);
}
/**
* Whether a reference, `node`, is a definition of the `target` symbol
*
* @internal
*/
export function isDeclarationOfSymbol(node: Node, target: Symbol | undefined): boolean {
if (!target) return false;
const source = getDeclarationFromName(node) ||
(node.kind === SyntaxKind.DefaultKeyword ? node.parent
: isLiteralComputedPropertyDeclarationName(node) ? node.parent.parent
: node.kind === SyntaxKind.ConstructorKeyword && isConstructorDeclaration(node.parent) ? node.parent.parent
: undefined);
const commonjsSource = source && isBinaryExpression(source) ? source.left as unknown as Declaration : undefined;
return !!(source && target.declarations?.some(d => d === source || d === commonjsSource));
}
/**
* True if 'decl' provides a value, as in `function f() {}`;
* false if 'decl' is just a location for a future write, as in 'let x;'
*/
function declarationIsWriteAccess(decl: Declaration): boolean {
// Consider anything in an ambient declaration to be a write access since it may be coming from JS.
if (!!(decl.flags & NodeFlags.Ambient)) return true;
switch (decl.kind) {
case SyntaxKind.BinaryExpression:
case SyntaxKind.BindingElement:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ClassExpression:
case SyntaxKind.DefaultKeyword:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.EnumMember:
case SyntaxKind.ExportSpecifier:
case SyntaxKind.ImportClause: // default import
case SyntaxKind.ImportEqualsDeclaration:
case SyntaxKind.ImportSpecifier:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.JSDocCallbackTag:
case SyntaxKind.JSDocTypedefTag:
case SyntaxKind.JsxAttribute:
case SyntaxKind.ModuleDeclaration:
case SyntaxKind.NamespaceExportDeclaration:
case SyntaxKind.NamespaceImport:
case SyntaxKind.NamespaceExport:
case SyntaxKind.Parameter:
case SyntaxKind.ShorthandPropertyAssignment:
case SyntaxKind.TypeAliasDeclaration:
case SyntaxKind.TypeParameter:
return true;
case SyntaxKind.PropertyAssignment:
// In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.)
return !isArrayLiteralOrObjectLiteralDestructuringPattern((decl as PropertyAssignment).parent);
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
case SyntaxKind.Constructor:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return !!(decl as FunctionDeclaration | FunctionExpression | ConstructorDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration).body;
case SyntaxKind.VariableDeclaration:
case SyntaxKind.PropertyDeclaration:
return !!(decl as VariableDeclaration | PropertyDeclaration).initializer || isCatchClause(decl.parent);
case SyntaxKind.MethodSignature:
case SyntaxKind.PropertySignature:
case SyntaxKind.JSDocPropertyTag:
case SyntaxKind.JSDocParameterTag:
return false;
default:
return Debug.failBadSyntaxKind(decl);
}
}
/**
* Encapsulates the core find-all-references algorithm.
*
* @internal
*/
export namespace Core {
/** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */
export function getReferencedSymbolsForNode(position: number, node: Node, program: Program, sourceFiles: readonly SourceFile[], cancellationToken: CancellationToken, options: Options = {}, sourceFilesSet: ReadonlySet<string> = new Set(sourceFiles.map(f => f.fileName))): readonly SymbolAndEntries[] | undefined {
node = getAdjustedNode(node, options);
if (isSourceFile(node)) {
const resolvedRef = GoToDefinition.getReferenceAtPosition(node, position, program);
if (!resolvedRef?.file) {
return undefined;
}
const moduleSymbol = program.getTypeChecker().getMergedSymbol(resolvedRef.file.symbol);
if (moduleSymbol) {
return getReferencedSymbolsForModule(program, moduleSymbol, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet);
}
const fileIncludeReasons = program.getFileIncludeReasons();
if (!fileIncludeReasons) {
return undefined;
}
return [{