Skip to content

(feat) find references #569

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 25, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/language-server/src/ls-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const defaultLSConfig: LSConfig = {
hover: { enable: true },
completions: { enable: true },
definitions: { enable: true },
findReferences: { enable: true },
documentSymbols: { enable: true },
codeActions: { enable: true },
rename: { enable: true },
Expand Down Expand Up @@ -67,6 +68,9 @@ export interface LSTypescriptConfig {
completions: {
enable: boolean;
};
findReferences: {
enable: boolean;
};
definitions: {
enable: boolean;
};
Expand Down
19 changes: 19 additions & 0 deletions packages/language-server/src/plugins/PluginHost.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import {
CompletionContext,
WorkspaceEdit,
FormattingOptions,
ReferenceContext,
Location,
} from 'vscode-languageserver';
import { LSConfig, LSConfigManager } from '../ls-config';
import { DocumentManager } from '../lib/documents';
Expand Down Expand Up @@ -315,6 +317,23 @@ export class PluginHost implements LSProvider, OnWatchFileChanges {
);
}

async findReferences(
textDocument: TextDocumentIdentifier,
position: Position,
context: ReferenceContext,
): Promise<Location[] | null> {
const document = this.getDocument(textDocument.uri);
if (!document) {
throw new Error('Cannot call methods on an unopened document');
}

return await this.execute<any>(
'findReferences',
[document, position, context],
ExecuteMode.FirstNonNull,
);
}

onWatchFileChanges(fileName: string, changeType: FileChangeType): void {
for (const support of this.plugins) {
support.onWatchFileChanges?.(fileName, changeType);
Expand Down
11 changes: 11 additions & 0 deletions packages/language-server/src/plugins/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@ import {
Diagnostic,
FormattingOptions,
Hover,
Location,
Position,
Range,
ReferenceContext,
SymbolInformation,
TextDocumentIdentifier,
TextEdit,
Expand Down Expand Up @@ -110,6 +112,14 @@ export interface RenameProvider {
prepareRename(document: Document, position: Position): Resolvable<Range | null>;
}

export interface FindReferencesProvider {
findReferences(
document: Document,
position: Position,
context: ReferenceContext,
): Promise<Location[] | null>;
}

export interface OnWatchFileChanges {
onWatchFileChanges(fileName: string, changeType: FileChangeType): void;
}
Expand All @@ -125,6 +135,7 @@ export type LSProvider = DiagnosticsProvider &
DefinitionsProvider &
UpdateImportsProvider &
CodeActionsProvider &
FindReferencesProvider &
RenameProvider;

export type Plugin = Partial<LSProvider & OnWatchFileChanges>;
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ import {
Diagnostic,
FileChangeType,
Hover,
Location,
LocationLink,
Position,
Range,
ReferenceContext,
SymbolInformation,
WorkspaceEdit,
CompletionList,
Expand All @@ -31,6 +33,7 @@ import {
DiagnosticsProvider,
DocumentSymbolsProvider,
FileRename,
FindReferencesProvider,
HoverProvider,
OnWatchFileChanges,
RenameProvider,
Expand All @@ -49,6 +52,7 @@ import { UpdateImportsProviderImpl } from './features/UpdateImportsProvider';
import { LSAndTSDocResolver } from './LSAndTSDocResolver';
import { convertToLocationRange, getScriptKindFromFileName, symbolKindFromString } from './utils';
import { getDirectiveCommentCompletions } from './features/getDirectiveCommentCompletions';
import { FindReferencesProviderImpl } from './features/FindReferencesProvider';

export class TypeScriptPlugin
implements
Expand All @@ -59,6 +63,7 @@ export class TypeScriptPlugin
CodeActionsProvider,
UpdateImportsProvider,
RenameProvider,
FindReferencesProvider,
OnWatchFileChanges,
CompletionsProvider<CompletionEntryWithIdentifer> {
private readonly configManager: LSConfigManager;
Expand All @@ -69,6 +74,7 @@ export class TypeScriptPlugin
private readonly diagnosticsProvider: DiagnosticsProviderImpl;
private readonly renameProvider: RenameProviderImpl;
private readonly hoverProvider: HoverProviderImpl;
private readonly findReferencesProvider: FindReferencesProviderImpl;

constructor(
docManager: DocumentManager,
Expand All @@ -86,6 +92,7 @@ export class TypeScriptPlugin
this.diagnosticsProvider = new DiagnosticsProviderImpl(this.lsAndTsDocResolver);
this.renameProvider = new RenameProviderImpl(this.lsAndTsDocResolver);
this.hoverProvider = new HoverProviderImpl(this.lsAndTsDocResolver);
this.findReferencesProvider = new FindReferencesProviderImpl(this.lsAndTsDocResolver);
}

async getDiagnostics(document: Document): Promise<Diagnostic[]> {
Expand Down Expand Up @@ -194,19 +201,19 @@ export class TypeScriptPlugin
const tsDirectiveCommentCompletions = getDirectiveCommentCompletions(
position,
document,
completionContext
completionContext,
);

const completions = await this.completionProvider.getCompletions(
document,
position,
completionContext
completionContext,
);

if (completions && tsDirectiveCommentCompletions) {
return CompletionList.create(
completions.items.concat(tsDirectiveCommentCompletions.items),
completions.isIncomplete
completions.isIncomplete,
);
}

Expand Down Expand Up @@ -309,6 +316,18 @@ export class TypeScriptPlugin
return this.updateImportsProvider.updateImports(fileRename);
}

async findReferences(
document: Document,
position: Position,
context: ReferenceContext,
): Promise<Location[] | null> {
if (!this.featureEnabled('findReferences')) {
return null;
}

return this.findReferencesProvider.findReferences(document, position, context);
}

onWatchFileChanges(fileName: string, changeType: FileChangeType) {
const scriptKind = getScriptKindFromFileName(fileName);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { Location, Position, ReferenceContext } from 'vscode-languageserver';
import { Document } from '../../../lib/documents';
import { pathToUrl } from '../../../utils';
import { FindReferencesProvider } from '../../interfaces';
import { SnapshotFragment } from '../DocumentSnapshot';
import { LSAndTSDocResolver } from '../LSAndTSDocResolver';
import { convertToLocationRange } 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 } = this.getLSAndTSDoc(document);
const fragment = await tsDoc.getFragment();

const references = lang.getReferencesAtPosition(
tsDoc.filePath,
fragment.offsetAt(fragment.getGeneratedPosition(position)),
);
if (!references) {
return null;
}

const docs = new Map<string, SnapshotFragment>([[tsDoc.filePath, fragment]]);

return await Promise.all(
references
.filter((ref) => context.includeDeclaration || !ref.isDefinition)
.map(async (ref) => {
let defDoc = docs.get(ref.fileName);
if (!defDoc) {
defDoc = await this.getSnapshot(ref.fileName).getFragment();
docs.set(ref.fileName, defDoc);
}

return Location.create(
pathToUrl(ref.fileName),
convertToLocationRange(defDoc, ref.textSpan),
);
}),
);
}

private getLSAndTSDoc(document: Document) {
return this.lsAndTsDocResolver.getLSAndTSDoc(document);
}

private getSnapshot(filePath: string, document?: Document) {
return this.lsAndTsDocResolver.getSnapshot(filePath, document);
}
}
4 changes: 4 additions & 0 deletions packages/language-server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ export function startServer(options?: LSOptions) {
renameProvider: evt.capabilities.textDocument?.rename?.prepareSupport
? { prepareProvider: true }
: true,
referencesProvider: true,
},
};
});
Expand Down Expand Up @@ -218,6 +219,9 @@ export function startServer(options?: LSOptions) {
);
connection.onDocumentSymbol((evt) => pluginHost.getDocumentSymbols(evt.textDocument));
connection.onDefinition((evt) => pluginHost.getDefinitions(evt.textDocument, evt.position));
connection.onReferences((evt) =>
pluginHost.findReferences(evt.textDocument, evt.position, evt.context),
);

connection.onCodeAction((evt) =>
pluginHost.getCodeActions(evt.textDocument, evt.range, evt.context),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import * as assert from 'assert';
import * as path from 'path';
import ts from 'typescript';
import { Location, Position, Range } from 'vscode-languageserver';
import { Document, DocumentManager } from '../../../../src/lib/documents';
import { FindReferencesProviderImpl } from '../../../../src/plugins/typescript/features/FindReferencesProvider';
import { LSAndTSDocResolver } from '../../../../src/plugins/typescript/LSAndTSDocResolver';
import { pathToUrl } from '../../../../src/utils';

const testDir = path.join(__dirname, '..');

describe('FindReferencesProvider', () => {
function getFullPath(filename: string) {
return path.join(testDir, 'testfiles', filename);
}
function getUri(filename: string) {
const filePath = path.join(testDir, 'testfiles', filename);
return pathToUrl(filePath);
}

function setup(filename: string) {
const docManager = new DocumentManager(
(textDocument) => new Document(textDocument.uri, textDocument.text),
);
const lsAndTsDocResolver = new LSAndTSDocResolver(docManager, [testDir]);
const provider = new FindReferencesProviderImpl(lsAndTsDocResolver);
const document = openDoc(filename);
return { provider, document };

function openDoc(filename: string) {
const filePath = getFullPath(filename);
const doc = docManager.openDocument(<any>{
uri: pathToUrl(filePath),
text: ts.sys.readFile(filePath) || '',
});
return doc;
}
}

async function test(position: Position, includeDeclaration: boolean) {
const { provider, document } = setup('find-references.svelte');

const results = await provider.findReferences(document, position, { includeDeclaration });

let expectedResults = [
Location.create(
getUri('find-references.svelte'),
Range.create(Position.create(2, 8), Position.create(2, 14)),
),
Location.create(
getUri('find-references.svelte'),
Range.create(Position.create(3, 8), Position.create(3, 14)),
),
];
if (includeDeclaration) {
expectedResults = [
Location.create(
getUri('find-references.svelte'),
Range.create(Position.create(1, 10), Position.create(1, 16)),
),
].concat(expectedResults);
}

assert.deepStrictEqual(results, expectedResults);
}

it('finds references', async () => {
await test(Position.create(1, 11), true);
});

it('finds references, exluding definition', async () => {
await test(Position.create(1, 11), false);
});

it('finds references (not searching from declaration)', async () => {
await test(Position.create(2, 8), true);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<script>
const findMe = true;
if (findMe) {
findMe;
}
</script>
4 changes: 4 additions & 0 deletions packages/svelte-vscode/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,10 @@ Enable document symbols for TypeScript. _Default_: `true`

Enable completions for TypeScript. _Default_: `true`

##### `svelte.plugin.typescript.findReferences`

Enable find-references for TypeScript. _Default_: `true`

##### `svelte.plugin.typescript.definitions`

Enable go to definition for TypeScript. _Default_: `true`
Expand Down
6 changes: 6 additions & 0 deletions packages/svelte-vscode/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,12 @@
"title": "TypeScript: Completions",
"description": "Enable completions for TypeScript"
},
"svelte.plugin.typescript.findReferences.enable": {
"type": "boolean",
"default": true,
"title": "TypeScript: Find References",
"description": "Enable find-references for TypeScript"
},
"svelte.plugin.typescript.definitions.enable": {
"type": "boolean",
"default": true,
Expand Down