forked from sveltejs/language-tools
/
FindReferencesProvider.ts
59 lines (51 loc) · 2.29 KB
/
FindReferencesProvider.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
import ts from 'typescript';
import { Location, Position, ReferenceContext } from 'vscode-languageserver';
import { Document } from '../../../lib/documents';
import { flatten, pathToUrl } from '../../../utils';
import { FindReferencesProvider } from '../../interfaces';
import { LSAndTSDocResolver } from '../LSAndTSDocResolver';
import { convertToLocationRange, hasNonZeroRange } from '../utils';
import { isNoTextSpanInGeneratedCode, SnapshotFragmentMap } from './utils';
export class FindReferencesProviderImpl implements FindReferencesProvider {
constructor(private readonly lsAndTsDocResolver: LSAndTSDocResolver) {}
async findReferences(
document: Document,
position: Position,
context: ReferenceContext
): Promise<Location[] | null> {
const { lang, tsDoc } = await this.getLSAndTSDoc(document);
const fragment = tsDoc.getFragment();
const references = lang.findReferences(
tsDoc.filePath,
fragment.offsetAt(fragment.getGeneratedPosition(position))
);
if (!references) {
return null;
}
const docs = new SnapshotFragmentMap(this.lsAndTsDocResolver);
docs.set(tsDoc.filePath, { fragment, snapshot: tsDoc });
const locations = await Promise.all(
flatten(references.map((ref) => ref.references))
.filter((ref) => context.includeDeclaration || !ref.isDefinition)
.filter(notInGeneratedCode(tsDoc.getFullText()))
.map(async (ref) => {
const defDoc = await docs.retrieveFragment(ref.fileName);
return Location.create(
pathToUrl(ref.fileName),
convertToLocationRange(defDoc, ref.textSpan)
);
})
);
// Some references are in generated code but not wrapped with explicit ignore comments.
// These show up as zero-length ranges, so filter them out.
return locations.filter(hasNonZeroRange);
}
private async getLSAndTSDoc(document: Document) {
return this.lsAndTsDocResolver.getLSAndTSDoc(document);
}
}
function notInGeneratedCode(text: string) {
return (ref: ts.ReferenceEntry) => {
return isNoTextSpanInGeneratedCode(text, ref.textSpan);
};
}