-
Notifications
You must be signed in to change notification settings - Fork 12.7k
/
Copy pathfindAllReferences.ts
1744 lines (1529 loc) · 85.8 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
/// <reference path="./importTracker.ts" />
/* @internal */
namespace ts.FindAllReferences {
export interface SymbolAndEntries {
definition: Definition | undefined;
references: Entry[];
}
export type Definition =
| { type: "symbol"; symbol: Symbol; node: Node }
| { type: "label"; node: Identifier }
| { type: "keyword"; node: ts.Node }
| { type: "this"; node: ts.Node }
| { type: "string"; node: ts.StringLiteral };
export type Entry = NodeEntry | SpanEntry;
export interface NodeEntry {
type: "node";
node: Node;
isInString?: true;
}
export interface SpanEntry {
type: "span";
fileName: string;
textSpan: TextSpan;
}
export function nodeEntry(node: ts.Node, isInString?: true): NodeEntry {
return { type: "node", node, isInString };
}
export interface Options {
readonly findInStrings?: boolean;
readonly findInComments?: boolean;
/**
* True if we are renaming the symbol.
* If so, we will find fewer references -- if it is referenced by several different names, we sill only find references for the original name.
*/
readonly isForRename?: boolean;
/** True if we are searching for implementations. We will have a different method of adding references if so. */
readonly implementations?: boolean;
}
export function findReferencedSymbols(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray<SourceFile>, sourceFile: SourceFile, position: number): ReferencedSymbol[] | undefined {
const referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position);
if (!referencedSymbols || !referencedSymbols.length) {
return undefined;
}
const out: ReferencedSymbol[] = [];
const checker = program.getTypeChecker();
for (const { definition, references } of referencedSymbols) {
// Only include referenced symbols that have a valid definition.
if (definition) {
out.push({ definition: definitionToReferencedSymbolDefinitionInfo(definition, checker), references: references.map(toReferenceEntry) });
}
}
return out;
}
export function getImplementationsAtPosition(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray<SourceFile>, sourceFile: SourceFile, position: number): ImplementationLocation[] {
// A node in a JSDoc comment can't have an implementation anyway.
const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false);
const referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node);
const checker = program.getTypeChecker();
return map(referenceEntries, entry => toImplementationLocation(entry, checker));
}
function getImplementationReferenceEntries(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray<SourceFile>, node: Node): 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(node, program, sourceFiles, cancellationToken, { implementations: true });
}
}
export function findReferencedEntries(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray<SourceFile>, sourceFile: SourceFile, position: number, options?: Options): ReferenceEntry[] | undefined {
const x = flattenEntries(findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options));
return map(x, toReferenceEntry);
}
export function getReferenceEntriesForNode(node: Node, program: Program, sourceFiles: ReadonlyArray<SourceFile>, cancellationToken: CancellationToken, options: Options = {}): Entry[] | undefined {
return flattenEntries(Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options));
}
function findAllReferencedSymbols(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray<SourceFile>, sourceFile: SourceFile, position: number, options?: Options): SymbolAndEntries[] | undefined {
const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
return Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options);
}
function flattenEntries(referenceSymbols: SymbolAndEntries[]): Entry[] {
return referenceSymbols && flatMap(referenceSymbols, r => r.references);
}
function definitionToReferencedSymbolDefinitionInfo(def: Definition, checker: TypeChecker): ReferencedSymbolDefinitionInfo | undefined {
const info = (() => {
switch (def.type) {
case "symbol": {
const { symbol, node } = def;
const { displayParts, kind } = getDefinitionKindAndDisplayParts(symbol, node, checker);
const name = displayParts.map(p => p.text).join("");
return { node, name, kind, displayParts };
}
case "label": {
const { node } = def;
return { node, name: node.text, kind: ScriptElementKind.label, displayParts: [displayPart(node.text, SymbolDisplayPartKind.text)] };
}
case "keyword": {
const { node } = def;
const name = tokenToString(node.kind);
return { node, name, kind: ScriptElementKind.keyword, displayParts: [{ text: name, kind: ScriptElementKind.keyword }] };
}
case "this": {
const { node } = def;
const symbol = checker.getSymbolAtLocation(node);
const displayParts = symbol && SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(
checker, symbol, node.getSourceFile(), getContainerNode(node), node).displayParts;
return { node, name: "this", kind: ScriptElementKind.variableElement, displayParts };
}
case "string": {
const { node } = def;
return { node, name: node.text, kind: ScriptElementKind.variableElement, displayParts: [displayPart(getTextOfNode(node), SymbolDisplayPartKind.stringLiteral)] };
}
}
})();
if (!info) {
return undefined;
}
const { node, name, kind, displayParts } = info;
const sourceFile = node.getSourceFile();
return {
containerKind: ScriptElementKind.unknown,
containerName: "",
fileName: sourceFile.fileName,
kind,
name,
textSpan: createTextSpanFromNode(node, sourceFile),
displayParts
};
}
function getDefinitionKindAndDisplayParts(symbol: Symbol, node: Node, checker: TypeChecker): { displayParts: SymbolDisplayPart[], kind: ScriptElementKind } {
const { displayParts, symbolKind } =
SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node.getSourceFile(), getContainerNode(node), node);
return { displayParts, kind: symbolKind };
}
function toReferenceEntry(entry: Entry): ReferenceEntry {
if (entry.type === "span") {
return { textSpan: entry.textSpan, fileName: entry.fileName, isWriteAccess: false, isDefinition: false };
}
const { node, isInString } = entry;
return {
fileName: node.getSourceFile().fileName,
textSpan: getTextSpan(node),
isWriteAccess: isWriteAccessForReference(node),
isDefinition: node.kind === SyntaxKind.DefaultKeyword
|| isAnyDeclarationName(node)
|| isLiteralComputedPropertyDeclarationName(node),
isInString
};
}
function toImplementationLocation(entry: Entry, checker: ts.TypeChecker): ImplementationLocation {
if (entry.type === "node") {
const { node } = entry;
return { textSpan: getTextSpan(node), fileName: node.getSourceFile().fileName, ...implementationKindDisplayParts(node, checker) };
}
else {
const { textSpan, fileName } = entry;
return { textSpan, fileName, kind: ScriptElementKind.unknown, displayParts: [] };
}
}
function implementationKindDisplayParts(node: ts.Node, checker: ts.TypeChecker): { kind: ScriptElementKind, displayParts: SymbolDisplayPart[] } {
const symbol = checker.getSymbolAtLocation(isDeclaration(node) && node.name ? node.name : node);
if (symbol) {
return getDefinitionKindAndDisplayParts(symbol, node, checker);
}
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: [] };
}
}
export function toHighlightSpan(entry: FindAllReferences.Entry): { fileName: string, span: HighlightSpan } {
if (entry.type === "span") {
const { fileName, textSpan } = entry;
return { fileName, span: { textSpan, kind: HighlightSpanKind.reference } };
}
const { node, isInString } = entry;
const fileName = entry.node.getSourceFile().fileName;
const writeAccess = isWriteAccessForReference(node);
const span: HighlightSpan = {
textSpan: getTextSpan(node),
kind: writeAccess ? HighlightSpanKind.writtenReference : HighlightSpanKind.reference,
isInString
};
return { fileName, span };
}
function getTextSpan(node: Node): TextSpan {
let start = node.getStart();
let end = node.getEnd();
if (node.kind === SyntaxKind.StringLiteral) {
start += 1;
end -= 1;
}
return createTextSpanFromBounds(start, end);
}
/** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */
function isWriteAccessForReference(node: Node): boolean {
return node.kind === SyntaxKind.DefaultKeyword || isAnyDeclarationName(node) || isWriteAccess(node);
}
}
/** Encapsulates the core find-all-references algorithm. */
/* @internal */
namespace ts.FindAllReferences.Core {
/** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */
export function getReferencedSymbolsForNode(node: Node, program: Program, sourceFiles: ReadonlyArray<SourceFile>, cancellationToken: CancellationToken, options: Options = {}): SymbolAndEntries[] | undefined {
if (node.kind === ts.SyntaxKind.SourceFile) {
return undefined;
}
if (!options.implementations) {
const special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken);
if (special) {
return special;
}
}
const checker = program.getTypeChecker();
const symbol = checker.getSymbolAtLocation(node);
// Could not find a symbol e.g. unknown identifier
if (!symbol) {
// String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial.
if (!options.implementations && node.kind === SyntaxKind.StringLiteral) {
return getReferencesForStringLiteral(<StringLiteral>node, sourceFiles, cancellationToken);
}
// Can't have references to something that we have no symbol for.
return undefined;
}
if (symbol.flags & SymbolFlags.Module && isModuleReferenceLocation(node)) {
return getReferencedSymbolsForModule(program, symbol, sourceFiles);
}
return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options);
}
function isModuleReferenceLocation(node: ts.Node): boolean {
if (node.kind !== SyntaxKind.StringLiteral) {
return false;
}
switch (node.parent.kind) {
case SyntaxKind.ModuleDeclaration:
case SyntaxKind.ExternalModuleReference:
case SyntaxKind.ImportDeclaration:
case SyntaxKind.ExportDeclaration:
return true;
case SyntaxKind.CallExpression:
return isRequireCall(node.parent as CallExpression, /*checkArgumentIsStringLiteral*/ false) || isImportCall(node.parent as CallExpression);
default:
return false;
}
}
function getReferencedSymbolsForModule(program: Program, symbol: Symbol, sourceFiles: ReadonlyArray<SourceFile>): SymbolAndEntries[] {
Debug.assert(!!symbol.valueDeclaration);
const references = findModuleReferences(program, sourceFiles, symbol).map<Entry>(reference => {
if (reference.kind === "import") {
return { type: "node", node: reference.literal };
}
else {
return {
type: "span",
fileName: reference.referencingFile.fileName,
textSpan: createTextSpanFromRange(reference.ref),
};
}
});
for (const decl of symbol.declarations) {
switch (decl.kind) {
case ts.SyntaxKind.SourceFile:
// Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.)
break;
case ts.SyntaxKind.ModuleDeclaration:
references.push({ type: "node", node: (decl as ts.ModuleDeclaration).name });
break;
default:
Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration.");
}
}
return [{
definition: { type: "symbol", symbol, node: symbol.valueDeclaration },
references
}];
}
/** getReferencedSymbols for special node kinds. */
function getReferencedSymbolsSpecial(node: Node, sourceFiles: ReadonlyArray<SourceFile>, cancellationToken: CancellationToken): SymbolAndEntries[] | undefined {
if (isTypeKeyword(node.kind)) {
return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken);
}
// Labels
if (isLabelName(node)) {
if (isJumpStatementTarget(node)) {
const labelDefinition = getTargetLabel((<BreakOrContinueStatement>node.parent), (<Identifier>node).text);
// if we have a label definition, look within its statement for references, if not, then
// the label is undefined and we have no results..
return labelDefinition && getLabelReferencesInNode(labelDefinition.parent, labelDefinition);
}
else {
// it is a label definition and not a target, search within the parent labeledStatement
return getLabelReferencesInNode(node.parent, <Identifier>node);
}
}
if (isThis(node)) {
return getReferencesForThisKeyword(node, sourceFiles, cancellationToken);
}
if (node.kind === SyntaxKind.SuperKeyword) {
return getReferencesForSuperKeyword(node);
}
return undefined;
}
/** Core find-all-references algorithm for a normal symbol. */
function getReferencedSymbolsForSymbol(symbol: Symbol, node: Node, sourceFiles: ReadonlyArray<SourceFile>, checker: TypeChecker, cancellationToken: CancellationToken, options: Options): SymbolAndEntries[] {
symbol = skipPastExportOrImportSpecifier(symbol, node, checker);
// Compute the meaning from the location and the symbol it references
const searchMeaning = getIntersectingMeaningFromDeclarations(getMeaningFromLocation(node), symbol.declarations);
const result: SymbolAndEntries[] = [];
const state = new State(sourceFiles, /*isForConstructor*/ node.kind === SyntaxKind.ConstructorKeyword, checker, cancellationToken, searchMeaning, options, result);
const search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) });
// Try to get the smallest valid scope that we can limit our search to;
// otherwise we'll need to search globally (i.e. include each file).
const scope = getSymbolScope(symbol);
if (scope) {
getReferencesInContainer(scope, scope.getSourceFile(), search, state);
}
else {
// Global search
for (const sourceFile of state.sourceFiles) {
state.cancellationToken.throwIfCancellationRequested();
searchForName(sourceFile, search, state);
}
}
return result;
}
/** Handle a few special cases relating to export/import specifiers. */
function skipPastExportOrImportSpecifier(symbol: Symbol, node: Node, checker: TypeChecker): Symbol {
const { parent } = node;
if (isExportSpecifier(parent)) {
return getLocalSymbolForExportSpecifier(node as Identifier, symbol, parent, checker);
}
if (isImportSpecifier(parent) && parent.propertyName === node) {
// We're at `foo` in `import { foo as bar }`. Probably intended to find all refs on the original, not just on the import.
return checker.getImmediateAliasedSymbol(symbol);
}
return symbol;
}
/**
* Symbol that is currently being searched for.
* This will be replaced if we find an alias for the symbol.
*/
interface Search {
/** If coming from an export, we will not recursively search for the imported symbol (since that's where we came from). */
readonly comingFrom?: ImportExport;
readonly location: Node;
readonly symbol: Symbol;
readonly text: string;
readonly escapedText: __String;
/** Only set if `options.implementations` is true. These are the symbols checked to get the implementations of a property access. */
readonly parents: Symbol[] | undefined;
/**
* Whether a symbol is in the search set.
* Do not compare directly to `symbol` because there may be related symbols to search for. See `populateSearchSymbolSet`.
*/
includes(symbol: Symbol): boolean;
}
/**
* Holds all state needed for the finding references.
* Unlike `Search`, there is only one `State`.
*/
class State {
/** Cache for `explicitlyinheritsFrom`. */
readonly inheritsFromCache = createMap<boolean>();
/**
* Type nodes can contain multiple references to the same type. For example:
* let x: Foo & (Foo & Bar) = ...
* Because we are returning the implementation locations and not the identifier locations,
* duplicate entries would be returned here as each of the type references is part of
* the same implementation. For that reason, check before we add a new entry.
*/
readonly markSeenContainingTypeReference = nodeSeenTracker();
/**
* It's possible that we will encounter the right side of `export { foo as bar } from "x";` more than once.
* For example:
* // b.ts
* export { foo as bar } from "./a";
* import { bar } from "./b";
*
* Normally at `foo as bar` we directly add `foo` and do not locally search for it (since it doesn't declare a local).
* But another reference to it may appear in the same source file.
* See `tests/cases/fourslash/transitiveExportImports3.ts`.
*/
readonly markSeenReExportRHS = nodeSeenTracker();
constructor(
readonly sourceFiles: ReadonlyArray<SourceFile>,
/** True if we're searching for constructor references. */
readonly isForConstructor: boolean,
readonly checker: TypeChecker,
readonly cancellationToken: CancellationToken,
readonly searchMeaning: SemanticMeaning,
readonly options: Options,
private readonly result: Push<SymbolAndEntries>) {}
private importTracker: ImportTracker | undefined;
/** Gets every place to look for references of an exported symbols. See `ImportsResult` in `importTracker.ts` for more documentation. */
getImportSearches(exportSymbol: Symbol, exportInfo: ExportInfo): ImportsResult {
if (!this.importTracker) this.importTracker = createImportTracker(this.sourceFiles, this.checker, this.cancellationToken);
return this.importTracker(exportSymbol, exportInfo, this.options.isForRename);
}
/** @param allSearchSymbols set of additinal symbols for use by `includes`. */
createSearch(location: Node, symbol: Symbol, comingFrom: ImportExport | undefined, searchOptions: { text?: string, allSearchSymbols?: Symbol[] } = {}): Search {
// Note: if this is an external module symbol, the name doesn't include quotes.
const {
text = stripQuotes(unescapeLeadingUnderscores((getLocalSymbolForExportDefault(symbol) || symbol).escapedName)),
allSearchSymbols = undefined,
} = searchOptions;
const escapedText = escapeLeadingUnderscores(text);
const parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker);
return {
location, symbol, comingFrom, text, escapedText, parents,
includes: referenceSymbol => allSearchSymbols ? contains(allSearchSymbols, referenceSymbol) : referenceSymbol === symbol,
};
}
private readonly symbolIdToReferences: Entry[][] = [];
/**
* Callback to add references for a particular searched symbol.
* This initializes a reference group, so only call this if you will add at least one reference.
*/
referenceAdder(searchSymbol: Symbol, searchLocation: Node): (node: Node) => void {
const symbolId = getSymbolId(searchSymbol);
let references = this.symbolIdToReferences[symbolId];
if (!references) {
references = this.symbolIdToReferences[symbolId] = [];
this.result.push({ definition: { type: "symbol", symbol: searchSymbol, node: searchLocation }, references });
}
return node => references.push(nodeEntry(node));
}
/** Add a reference with no associated definition. */
addStringOrCommentReference(fileName: string, textSpan: TextSpan): void {
this.result.push({
definition: undefined,
references: [{ type: "span", fileName, textSpan }]
});
}
// Source file ID → symbol ID → Whether the symbol has been searched for in the source file.
private readonly sourceFileToSeenSymbols: Array<Array<true>> = [];
/** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */
markSearchedSymbol(sourceFile: SourceFile, symbol: Symbol): boolean {
const sourceId = getNodeId(sourceFile);
const symbolId = getSymbolId(symbol);
const seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = []);
return !seenSymbols[symbolId] && (seenSymbols[symbolId] = true);
}
}
/** Search for all imports of a given exported symbol using `State.getImportSearches`. */
function searchForImportsOfExport(exportLocation: Node, exportSymbol: Symbol, exportInfo: ExportInfo, state: State): void {
const { importSearches, singleReferences, indirectUsers } = state.getImportSearches(exportSymbol, exportInfo);
// For `import { foo as bar }` just add the reference to `foo`, and don't otherwise search in the file.
if (singleReferences.length) {
const addRef = state.referenceAdder(exportSymbol, exportLocation);
for (const singleRef of singleReferences) {
addRef(singleRef);
}
}
// For each import, find all references to that import in its source file.
for (const [importLocation, importSymbol] of importSearches) {
getReferencesInSourceFile(importLocation.getSourceFile(), state.createSearch(importLocation, importSymbol, ImportExport.Export), state);
}
if (indirectUsers.length) {
let indirectSearch: Search | undefined;
switch (exportInfo.exportKind) {
case ExportKind.Named:
indirectSearch = state.createSearch(exportLocation, exportSymbol, ImportExport.Export);
break;
case ExportKind.Default:
// Search for a property access to '.default'. This can't be renamed.
indirectSearch = state.options.isForRename ? undefined : state.createSearch(exportLocation, exportSymbol, ImportExport.Export, { text: "default" });
break;
case ExportKind.ExportEquals:
break;
}
if (indirectSearch) {
for (const indirectUser of indirectUsers) {
searchForName(indirectUser, indirectSearch, state);
}
}
}
}
// Go to the symbol we imported from and find references for it.
function searchForImportedSymbol(symbol: Symbol, state: State): void {
for (const declaration of symbol.declarations) {
getReferencesInSourceFile(declaration.getSourceFile(), state.createSearch(declaration, symbol, ImportExport.Import), state);
}
}
/** Search for all occurences of an identifier in a source file (and filter out the ones that match). */
function searchForName(sourceFile: SourceFile, search: Search, state: State): void {
if (getNameTable(sourceFile).get(search.escapedText) !== undefined) {
getReferencesInSourceFile(sourceFile, search, state);
}
}
function getPropertySymbolOfDestructuringAssignment(location: Node, checker: TypeChecker): Symbol | undefined {
return isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) &&
checker.getPropertySymbolOfDestructuringAssignment(<Identifier>location);
}
function getObjectBindingElementWithoutPropertyName(symbol: Symbol): BindingElement | undefined {
const bindingElement = getDeclarationOfKind<BindingElement>(symbol, SyntaxKind.BindingElement);
if (bindingElement &&
bindingElement.parent.kind === SyntaxKind.ObjectBindingPattern &&
!bindingElement.propertyName) {
return bindingElement;
}
}
function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol: Symbol, checker: TypeChecker): Symbol | undefined {
const bindingElement = getObjectBindingElementWithoutPropertyName(symbol);
if (!bindingElement) return undefined;
const typeOfPattern = checker.getTypeAtLocation(bindingElement.parent);
const propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, (<Identifier>bindingElement.name).text);
if (propSymbol && propSymbol.flags & SymbolFlags.Accessor) {
// See GH#16922
Debug.assert(!!(propSymbol.flags & SymbolFlags.Transient));
return (propSymbol as TransientSymbol).target;
}
return propSymbol;
}
/**
* Determines the smallest scope in which a symbol may have named references.
* Note that not every construct has been accounted for. This function can
* probably be improved.
*
* @returns undefined if the scope cannot be determined, implying that
* a reference to a symbol can occur anywhere.
*/
function getSymbolScope(symbol: Symbol): Node | undefined {
// If this is the symbol of a named function expression or named class expression,
// then named references are limited to its own scope.
const { declarations, flags, parent, valueDeclaration } = symbol;
if (valueDeclaration && (valueDeclaration.kind === SyntaxKind.FunctionExpression || valueDeclaration.kind === SyntaxKind.ClassExpression)) {
return valueDeclaration;
}
if (!declarations) {
return undefined;
}
// If this is private property or method, the scope is the containing class
if (flags & (SymbolFlags.Property | SymbolFlags.Method)) {
const privateDeclaration = find(declarations, d => hasModifier(d, ModifierFlags.Private));
if (privateDeclaration) {
return getAncestor(privateDeclaration, SyntaxKind.ClassDeclaration);
}
// Else this is a public property and could be accessed from anywhere.
return undefined;
}
// If symbol is of object binding pattern element without property name we would want to
// look for property too and that could be anywhere
if (getObjectBindingElementWithoutPropertyName(symbol)) {
return undefined;
}
/*
If the symbol has a parent, it's globally visible unless:
- It's a private property (handled above).
- It's a type parameter.
- The parent is an external module: then we should only search in the module (and recurse on the export later).
- But if the parent has `export as namespace`, the symbol is globally visible through that namespace.
*/
const exposedByParent = parent && !(symbol.flags & SymbolFlags.TypeParameter);
if (exposedByParent && !((parent.flags & SymbolFlags.Module) && isExternalModuleSymbol(parent) && !parent.globalExports)) {
return undefined;
}
let scope: Node | undefined;
for (const declaration of declarations) {
const container = getContainerNode(declaration);
if (scope && scope !== container) {
// Different declarations have different containers, bail out
return undefined;
}
if (!container || container.kind === SyntaxKind.SourceFile && !isExternalOrCommonJsModule(<SourceFile>container)) {
// This is a global variable and not an external module, any declaration defined
// within this scope is visible outside the file
return undefined;
}
// The search scope is the container node
scope = container;
}
// If symbol.parent, this means we are in an export of an external module. (Otherwise we would have returned `undefined` above.)
// For an export of a module, we may be in a declaration file, and it may be accessed elsewhere. E.g.:
// declare module "a" { export type T = number; }
// declare module "b" { import { T } from "a"; export const x: T; }
// So we must search the whole source file. (Because we will mark the source file as seen, we we won't return to it when searching for imports.)
return exposedByParent ? scope.getSourceFile() : scope;
}
function getPossibleSymbolReferencePositions(sourceFile: SourceFile, symbolName: string, container: Node = sourceFile): number[] {
const positions: number[] = [];
/// TODO: Cache symbol existence for files to save text search
// Also, need to make this work for unicode escapes.
// Be resilient in the face of a symbol with no name or zero length name
if (!symbolName || !symbolName.length) {
return positions;
}
const text = sourceFile.text;
const sourceLength = text.length;
const symbolNameLength = symbolName.length;
let position = text.indexOf(symbolName, container.pos);
while (position >= 0) {
// If we are past the end, stop looking
if (position > container.end) break;
// We found a match. Make sure it's not part of a larger word (i.e. the char
// before and after it have to be a non-identifier char).
const endPosition = position + symbolNameLength;
if ((position === 0 || !isIdentifierPart(text.charCodeAt(position - 1), ScriptTarget.Latest)) &&
(endPosition === sourceLength || !isIdentifierPart(text.charCodeAt(endPosition), ScriptTarget.Latest))) {
// Found a real match. Keep searching.
positions.push(position);
}
position = text.indexOf(symbolName, position + symbolNameLength + 1);
}
return positions;
}
function getLabelReferencesInNode(container: Node, targetLabel: Identifier): SymbolAndEntries[] {
const references: Entry[] = [];
const sourceFile = container.getSourceFile();
const labelName = targetLabel.text;
const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container);
for (const position of possiblePositions) {
const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false);
// Only pick labels that are either the target label, or have a target that is the target label
if (node && (node === targetLabel || (isJumpStatementTarget(node) && getTargetLabel(node, labelName) === targetLabel))) {
references.push(nodeEntry(node));
}
}
return [{ definition: { type: "label", node: targetLabel }, references }];
}
function isValidReferencePosition(node: Node, searchSymbolName: string): boolean {
// Compare the length so we filter out strict superstrings of the symbol we are looking for
switch (node.kind) {
case SyntaxKind.Identifier:
return (node as Identifier).text.length === searchSymbolName.length;
case SyntaxKind.StringLiteral:
return (isLiteralNameOfPropertyDeclarationOrIndexAccess(node as StringLiteral) || isNameOfExternalModuleImportOrDeclaration(node)) &&
(node as StringLiteral).text.length === searchSymbolName.length;
case SyntaxKind.NumericLiteral:
return isLiteralNameOfPropertyDeclarationOrIndexAccess(node as NumericLiteral) && (node as NumericLiteral).text.length === searchSymbolName.length;
case SyntaxKind.DefaultKeyword:
return "default".length === searchSymbolName.length;
default:
return false;
}
}
function getAllReferencesForKeyword(sourceFiles: ReadonlyArray<SourceFile>, keywordKind: ts.SyntaxKind, cancellationToken: CancellationToken): SymbolAndEntries[] {
const references: NodeEntry[] = [];
for (const sourceFile of sourceFiles) {
cancellationToken.throwIfCancellationRequested();
addReferencesForKeywordInFile(sourceFile, keywordKind, tokenToString(keywordKind), references);
}
return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references }] : undefined;
}
function addReferencesForKeywordInFile(sourceFile: SourceFile, kind: SyntaxKind, searchText: string, references: Push<NodeEntry>): void {
const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile);
for (const position of possiblePositions) {
const referenceLocation = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
if (referenceLocation.kind === kind) {
references.push(nodeEntry(referenceLocation));
}
}
}
function getReferencesInSourceFile(sourceFile: ts.SourceFile, search: Search, state: State): void {
state.cancellationToken.throwIfCancellationRequested();
return getReferencesInContainer(sourceFile, sourceFile, search, state);
}
/**
* Search within node "container" for references for a search value, where the search value is defined as a
* tuple of(searchSymbol, searchText, searchLocation, and searchMeaning).
* searchLocation: a node where the search value
*/
function getReferencesInContainer(container: Node, sourceFile: ts.SourceFile, search: Search, state: State): void {
if (!state.markSearchedSymbol(sourceFile, search.symbol)) {
return;
}
for (const position of getPossibleSymbolReferencePositions(sourceFile, search.text, container)) {
getReferencesAtLocation(sourceFile, position, search, state);
}
}
function getReferencesAtLocation(sourceFile: SourceFile, position: number, search: Search, state: State): void {
const referenceLocation = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
if (!isValidReferencePosition(referenceLocation, search.text)) {
// This wasn't the start of a token. Check to see if it might be a
// match in a comment or string if that's what the caller is asking
// for.
if (!state.options.implementations && (state.options.findInStrings && isInString(sourceFile, position) || state.options.findInComments && isInNonReferenceComment(sourceFile, position))) {
// In the case where we're looking inside comments/strings, we don't have
// an actual definition. So just use 'undefined' here. Features like
// 'Rename' won't care (as they ignore the definitions), and features like
// 'FindReferences' will just filter out these results.
state.addStringOrCommentReference(sourceFile.fileName, createTextSpan(position, search.text.length));
}
return;
}
if (!(getMeaningFromLocation(referenceLocation) & state.searchMeaning)) {
return;
}
const referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation);
if (!referenceSymbol) {
return;
}
const { parent } = referenceLocation;
if (isImportSpecifier(parent) && parent.propertyName === referenceLocation) {
// This is added through `singleReferences` in ImportsResult. If we happen to see it again, don't add it again.
return;
}
if (isExportSpecifier(parent)) {
Debug.assert(referenceLocation.kind === SyntaxKind.Identifier);
getReferencesAtExportSpecifier(referenceLocation as Identifier, referenceSymbol, parent, search, state);
return;
}
const relatedSymbol = getRelatedSymbol(search, referenceSymbol, referenceLocation, state);
if (!relatedSymbol) {
getReferenceForShorthandProperty(referenceSymbol, search, state);
return;
}
if (state.isForConstructor) {
findConstructorReferences(referenceLocation, sourceFile, search, state);
}
else {
addReference(referenceLocation, relatedSymbol, search.location, state);
}
getImportOrExportReferences(referenceLocation, referenceSymbol, search, state);
}
function getReferencesAtExportSpecifier(referenceLocation: Identifier, referenceSymbol: Symbol, exportSpecifier: ExportSpecifier, search: Search, state: State): void {
const { parent, propertyName, name } = exportSpecifier;
const exportDeclaration = parent.parent;
const localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker);
if (!search.includes(localSymbol)) {
return;
}
if (!propertyName) {
addRef();
}
else if (referenceLocation === propertyName) {
// For `export { foo as bar } from "baz"`, "`foo`" will be added from the singleReferences for import searches of the original export.
// For `export { foo as bar };`, where `foo` is a local, so add it now.
if (!exportDeclaration.moduleSpecifier) {
addRef();
}
if (!state.options.isForRename && state.markSeenReExportRHS(name)) {
addReference(name, referenceSymbol, name, state);
}
}
else {
if (state.markSeenReExportRHS(referenceLocation)) {
addRef();
}
}
// For `export { foo as bar }`, rename `foo`, but not `bar`.
if (!(referenceLocation === propertyName && state.options.isForRename)) {
const exportKind = (referenceLocation as Identifier).originalKeywordKind === ts.SyntaxKind.DefaultKeyword ? ExportKind.Default : ExportKind.Named;
const exportInfo = getExportInfo(referenceSymbol, exportKind, state.checker);
Debug.assert(!!exportInfo);
searchForImportsOfExport(referenceLocation, referenceSymbol, exportInfo, state);
}
// At `export { x } from "foo"`, also search for the imported symbol `"foo".x`.
if (search.comingFrom !== ImportExport.Export && exportDeclaration.moduleSpecifier && !propertyName) {
searchForImportedSymbol(state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier), state);
}
function addRef() {
addReference(referenceLocation, localSymbol, search.location, state);
}
}
function getLocalSymbolForExportSpecifier(referenceLocation: Identifier, referenceSymbol: Symbol, exportSpecifier: ExportSpecifier, checker: TypeChecker): Symbol {
return isExportSpecifierAlias(referenceLocation, exportSpecifier) ? checker.getExportSpecifierLocalTargetSymbol(exportSpecifier) : referenceSymbol;
}
function isExportSpecifierAlias(referenceLocation: Identifier, exportSpecifier: ExportSpecifier): boolean {
const { parent, propertyName, name } = exportSpecifier;
Debug.assert(propertyName === referenceLocation || name === referenceLocation);
if (propertyName) {
// Given `export { foo as bar } [from "someModule"]`: It's an alias at `foo`, but at `bar` it's a new symbol.
return propertyName === referenceLocation;
}
else {
// `export { foo } from "foo"` is a re-export.
// `export { foo };` is not a re-export, it creates an alias for the local variable `foo`.
return !parent.parent.moduleSpecifier;
}
}
function getImportOrExportReferences(referenceLocation: Node, referenceSymbol: Symbol, search: Search, state: State): void {
const importOrExport = getImportOrExportSymbol(referenceLocation, referenceSymbol, state.checker, search.comingFrom === ImportExport.Export);
if (!importOrExport) return;
const { symbol } = importOrExport;
if (importOrExport.kind === ImportExport.Import) {
if (!state.options.isForRename || importOrExport.isNamedImport) {
searchForImportedSymbol(symbol, state);
}
}
else {
// We don't check for `state.isForRename`, even for default exports, because importers that previously matched the export name should be updated to continue matching.
searchForImportsOfExport(referenceLocation, symbol, importOrExport.exportInfo, state);
}
}
function getReferenceForShorthandProperty({ flags, valueDeclaration }: Symbol, search: Search, state: State): void {
const shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration);
/*
* Because in short-hand property assignment, an identifier which stored as name of the short-hand property assignment
* has two meanings: property name and property value. Therefore when we do findAllReference at the position where
* an identifier is declared, the language service should return the position of the variable declaration as well as
* the position in short-hand property assignment excluding property accessing. However, if we do findAllReference at the
* position of property accessing, the referenceEntry of such position will be handled in the first case.
*/
if (!(flags & SymbolFlags.Transient) && search.includes(shorthandValueSymbol)) {
addReference(getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state);
}
}
function addReference(referenceLocation: Node, relatedSymbol: Symbol, searchLocation: Node, state: State): void {
const addRef = state.referenceAdder(relatedSymbol, searchLocation);
if (state.options.implementations) {
addImplementationReferences(referenceLocation, addRef, state);
}
else {
addRef(referenceLocation);
}
}
/** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */
function findConstructorReferences(referenceLocation: Node, sourceFile: SourceFile, search: Search, state: State): void {
if (isNewExpressionTarget(referenceLocation)) {
addReference(referenceLocation, search.symbol, search.location, state);
}
const pusher = state.referenceAdder(search.symbol, search.location);
if (isClassLike(referenceLocation.parent)) {
Debug.assert(referenceLocation.parent.name === referenceLocation);
// This is the class declaration containing the constructor.
findOwnConstructorReferences(search.symbol, sourceFile, pusher);
}
else {
// If this class appears in `extends C`, then the extending class' "super" calls are references.
const classExtending = tryGetClassByExtendingIdentifier(referenceLocation);
if (classExtending && isClassLike(classExtending)) {
findSuperConstructorAccesses(classExtending, pusher);
}
}
}
function getPropertyAccessExpressionFromRightHandSide(node: Node): PropertyAccessExpression {
return isRightSideOfPropertyAccess(node) && <PropertyAccessExpression>node.parent;
}
/**
* `classSymbol` is the class where the constructor was defined.
* Reference the constructor and all calls to `new this()`.
*/
function findOwnConstructorReferences(classSymbol: Symbol, sourceFile: SourceFile, addNode: (node: Node) => void): void {
for (const decl of classSymbol.members.get(InternalSymbolName.Constructor).declarations) {
const ctrKeyword = ts.findChildOfKind(decl, ts.SyntaxKind.ConstructorKeyword, sourceFile)!;
Debug.assert(decl.kind === SyntaxKind.Constructor && !!ctrKeyword);
addNode(ctrKeyword);
}
classSymbol.exports.forEach(member => {
const decl = member.valueDeclaration;
if (decl && decl.kind === SyntaxKind.MethodDeclaration) {
const body = (<MethodDeclaration>decl).body;
if (body) {
forEachDescendantOfKind(body, SyntaxKind.ThisKeyword, thisKeyword => {
if (isNewExpressionTarget(thisKeyword)) {
addNode(thisKeyword);