Skip to content
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

feat: language service resolver cache #900

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
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
65 changes: 31 additions & 34 deletions src/lib/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,50 +10,47 @@ import {
import { TextDocument } from 'vscode-languageserver-textdocument';

import { initializeResult } from './capabilities';
import { VscodeStylableLanguageService } from './vscode-service';
import { VSCodeStylableLanguageService } from './vscode-service';
import { wrapFs } from './wrap-fs';

const connection = createConnection(new IPCMessageReader(process), new IPCMessageWriter(process));
let vscodeStylableLSP: VscodeStylableLanguageService;

connection.listen();
connection.onInitialize((params) => {
const docs = new TextDocuments(TextDocument);
const wrappedFs = wrapFs(fs, docs);

vscodeStylableLSP = new VscodeStylableLanguageService(
connection,
docs,
wrappedFs,
Stylable.create({
projectRoot: params.rootPath || '',
fileSystem: wrappedFs as MinimalFS,
requireModule: require,
cssParser: safeParse
})
);
const stylable = Stylable.create({
projectRoot: params.rootPath || '',
fileSystem: wrappedFs as MinimalFS,
requireModule: require,
cssParser: safeParse,
resolverCache: new Map(),
});
const lsp = new VSCodeStylableLanguageService(connection, docs, wrappedFs, stylable);

docs.listen(connection);
docs.onDidChangeContent(vscodeStylableLSP.diagnoseWithVsCodeConfig.bind(vscodeStylableLSP));
docs.onDidClose(vscodeStylableLSP.onDidClose.bind(vscodeStylableLSP));

connection.onCompletion(vscodeStylableLSP.onCompletion.bind(vscodeStylableLSP));
connection.onDefinition(vscodeStylableLSP.onDefinition.bind(vscodeStylableLSP));
connection.onHover(vscodeStylableLSP.onHover.bind(vscodeStylableLSP));
connection.onReferences(vscodeStylableLSP.onReferences.bind(vscodeStylableLSP));
connection.onDocumentColor(vscodeStylableLSP.onDocumentColor.bind(vscodeStylableLSP));
connection.onColorPresentation(vscodeStylableLSP.onColorPresentation.bind(vscodeStylableLSP));
connection.onRenameRequest(vscodeStylableLSP.onRenameRequest.bind(vscodeStylableLSP));
connection.onSignatureHelp(vscodeStylableLSP.onSignatureHelp.bind(vscodeStylableLSP));
connection.onDocumentFormatting(vscodeStylableLSP.onDocumentFormatting.bind(vscodeStylableLSP));
connection.onDocumentRangeFormatting(vscodeStylableLSP.onDocumentRangeFormatting.bind(vscodeStylableLSP));
docs.onDidChangeContent((event) => {
lsp.cleanStylableCacheForDocument(event.document);
lsp.emitDiagnosticsForOpenDocuments();
});
docs.onDidClose((event) => lsp.onDidClose(event));

connection.onCompletion(lsp.onCompletion.bind(lsp));
connection.onDefinition(lsp.onDefinition.bind(lsp));
connection.onHover(lsp.onHover.bind(lsp));
connection.onReferences(lsp.onReferences.bind(lsp));
connection.onDocumentColor(lsp.onDocumentColor.bind(lsp));
connection.onColorPresentation(lsp.onColorPresentation.bind(lsp));
connection.onRenameRequest(lsp.onRenameRequest.bind(lsp));
connection.onSignatureHelp(lsp.onSignatureHelp.bind(lsp));
connection.onDocumentFormatting(lsp.onDocumentFormatting.bind(lsp));
connection.onDocumentRangeFormatting(lsp.onDocumentRangeFormatting.bind(lsp));
// eslint-disable-next-line @typescript-eslint/no-misused-promises
connection.onDidChangeConfiguration(vscodeStylableLSP.onChangeConfig.bind(vscodeStylableLSP));

connection.onDidChangeConfiguration(lsp.onChangeConfig.bind(lsp));
connection.onInitialized(() => {
connection.client.register(DidChangeConfigurationNotification.type, undefined).catch(console.error);
lsp.loadClientConfiguration().then(console.log).catch(console.error);
});
return initializeResult;
});

connection.onInitialized(() => {
connection.client.register(DidChangeConfigurationNotification.type, undefined).catch(console.error);
vscodeStylableLSP.loadClientConfiguration().then(console.log).catch(console.error);
});
connection.listen();
82 changes: 48 additions & 34 deletions src/lib/vscode-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,18 @@ export interface ExtensionConfiguration {
formatting: CSSBeautifyOptions;
}

export class VscodeStylableLanguageService {
export class VSCodeStylableLanguageService {
public textDocuments: TextDocuments<TextDocument>;
public languageService: StylableLanguageService;
private connection: Connection;
private clientConfig: ExtensionConfiguration = { diagnostics: { ignore: [] }, formatting: {} };

constructor(connection: Connection, docs: TextDocuments<TextDocument>, fs: IFileSystem, stylable: Stylable) {
constructor(
connection: Connection,
docs: TextDocuments<TextDocument>,
fs: IFileSystem,
private stylable: Stylable
) {
this.languageService = new StylableLanguageService({
fs,
stylable,
Expand Down Expand Up @@ -127,48 +132,45 @@ export class VscodeStylableLanguageService {
return [];
}

public diagnoseWithVsCodeConfig(): Diagnostic[] {
const result: Diagnostic[] = [];
this.textDocuments.keys().forEach((key) => {
const doc = this.textDocuments.get(key);
if (doc) {
if (doc.languageId === 'stylable') {
const uri = URI.parse(doc.uri);
// on windows, uri.fsPath replaces separators with '\'
// this breaks posix paths in-memory when running on windows
// take raw posix path instead
const fsPath =
uri.scheme === 'file' &&
!uri.authority && // not UNC
uri.path.charCodeAt(2) !== 58 && // the colon in "c:"
path.isAbsolute(uri.path)
? uri.path
: uri.fsPath;
let diagnostics: Diagnostic[];
if (
this.clientConfig.diagnostics.ignore.some((p) => {
return fsPath.startsWith(p);
})
) {
diagnostics = [];
} else {
diagnostics = this.languageService.diagnose(fsPath);
result.push(...diagnostics);
public cleanStylableCacheForDocument(document: TextDocument) {
if (document.languageId === 'stylable') {
const fsPath = fsPathCompatibility(URI.parse(document.uri));
this.stylable.initCache({
filter(_, entity) {
if ('resolvedPath' in entity) {
return entity.resolvedPath !== fsPath;
}
this.connection.sendDiagnostics({ uri: doc.uri, diagnostics });
}
}
});
return false;
},
});
}
}

public emitDiagnosticsForOpenDocuments(): Diagnostic[] {
const result: Diagnostic[] = [];
for (const doc of this.textDocuments.all()) {
if (doc.languageId !== 'stylable') {
continue;
}
const fsPath = fsPathCompatibility(URI.parse(doc.uri));
const hasIgnoredDiagnostics = this.clientConfig.diagnostics.ignore.some((p) => {
return fsPath.startsWith(p);
});
const diagnostics: Diagnostic[] = hasIgnoredDiagnostics ? [] : this.languageService.diagnose(fsPath);
result.push(...diagnostics);
this.connection.sendDiagnostics({ uri: doc.uri, diagnostics });
}
return result;
}

public async onChangeConfig(): Promise<void> {
await this.loadClientConfiguration();
this.diagnoseWithVsCodeConfig();
this.stylable.initCache();
this.emitDiagnosticsForOpenDocuments();
}

public onDidClose(event: TextDocumentChangeEvent<TextDocument>): void {
this.cleanStylableCacheForDocument(event.document);
this.connection.sendDiagnostics({
diagnostics: [],
uri: event.document.uri,
Expand All @@ -194,3 +196,15 @@ export class VscodeStylableLanguageService {
return { fsPath, doc };
}
}

function fsPathCompatibility(uri: URI) {
// on windows, uri.fsPath replaces separators with '\'
// this breaks posix paths in-memory when running on windows
// take raw posix path instead
return uri.scheme === 'file' &&
!uri.authority && // not UNC
uri.path.charCodeAt(2) !== 58 && // the colon in "c:"
path.isAbsolute(uri.path)
? uri.path
: uri.fsPath;
}
7 changes: 3 additions & 4 deletions src/lib/wrap-fs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@ import { URI } from 'vscode-uri';
import type { TextDocument } from 'vscode-languageserver-textdocument';

export function wrapFs(fs: IFileSystem, docs: TextDocuments<TextDocument>): IFileSystem {
const readFileSync = ((path: string, ...args: [ReadFileOptions]) => {
const file = docs.get(URI.file(path).toString());
return file ? file.getText() : fs.readFileSync(path, ...args);
}) as IBaseFileSystemSyncActions['readFileSync'];
const readFileSync = ((path: string, ...args: [ReadFileOptions]) =>
docs.get(URI.file(path).toString())?.getText() ??
fs.readFileSync(path, ...args)) as IBaseFileSystemSyncActions['readFileSync'];
return { ...fs, readFileSync };
}
22 changes: 11 additions & 11 deletions test/unit/service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { URI } from 'vscode-uri';

import { TestConnection } from '../lsp-testkit/connection.spec';
import { expect, plan } from '../testkit/chai.spec';
import { VscodeStylableLanguageService } from '../../src/lib/vscode-service';
import { VSCodeStylableLanguageService } from '../../src/lib/vscode-service';
import { getRangeAndText } from '../testkit/text.spec';
import { TestDocuments } from '../lsp-testkit/test-documents';

Expand Down Expand Up @@ -67,7 +67,7 @@ describe('Service component test', () => {

const memFs = createMemoryFs({ [baseFileName]: rangeAndText.text });
const { requireModule } = createCjsModuleSystem({ fs: memFs });
const stylableLSP = new VscodeStylableLanguageService(
const stylableLSP = new VSCodeStylableLanguageService(
connection,
new TestDocuments({
[baseTextDocument.uri]: baseTextDocument,
Expand All @@ -76,7 +76,7 @@ describe('Service component test', () => {
new Stylable('/', memFs, requireModule)
);

const diagnostics = stylableLSP.diagnoseWithVsCodeConfig();
const diagnostics = stylableLSP.emitDiagnosticsForOpenDocuments();
expect(diagnostics).to.deep.equal(expectedDiagnostics);
})
);
Expand Down Expand Up @@ -121,7 +121,7 @@ describe('Service component test', () => {
const memFs = createMemoryFs({ [baseFileName]: baseFilecContent, [topFileName]: topFileContent });
const { requireModule } = createCjsModuleSystem({ fs: memFs });

const stylableLSP = new VscodeStylableLanguageService(
const stylableLSP = new VSCodeStylableLanguageService(
connection,
new TestDocuments({
[baseTextDocument.uri]: baseTextDocument,
Expand All @@ -131,7 +131,7 @@ describe('Service component test', () => {
new Stylable('/', memFs, requireModule)
);

const diagnostics = stylableLSP.diagnoseWithVsCodeConfig();
const diagnostics = stylableLSP.emitDiagnosticsForOpenDocuments();
expect(diagnostics).to.deep.equal(expectedDiagnostics);
})
);
Expand Down Expand Up @@ -181,7 +181,7 @@ describe('Service component test', () => {
const memFs = createMemoryFs({ [baseFileName]: baseFilecContent });
const { requireModule } = createCjsModuleSystem({ fs: memFs });

const stylableLSP = new VscodeStylableLanguageService(
const stylableLSP = new VSCodeStylableLanguageService(
connection,
new TestDocuments({
[baseTextDocument.uri]: baseTextDocument,
Expand All @@ -190,7 +190,7 @@ describe('Service component test', () => {
new Stylable('/', memFs, requireModule)
);

const diagnostics = stylableLSP.diagnoseWithVsCodeConfig();
const diagnostics = stylableLSP.emitDiagnosticsForOpenDocuments();
expect(diagnostics).to.deep.equal(expectedDiagnostics);
})
);
Expand All @@ -207,7 +207,7 @@ describe('Service component test', () => {

const memFs = createMemoryFs({ [baseFileName]: text });
const { requireModule } = createCjsModuleSystem({ fs: memFs });
const stylableLSP = new VscodeStylableLanguageService(
const stylableLSP = new VSCodeStylableLanguageService(
connection,
new TestDocuments({
[textDocument.uri]: textDocument,
Expand Down Expand Up @@ -240,7 +240,7 @@ describe('Service component test', () => {

const memFs = createMemoryFs({ [baseFileName]: text });
const { requireModule } = createCjsModuleSystem({ fs: memFs });
const stylableLSP = new VscodeStylableLanguageService(
const stylableLSP = new VSCodeStylableLanguageService(
connection,
new TestDocuments({
[textDocument.uri]: textDocument,
Expand Down Expand Up @@ -303,7 +303,7 @@ describe('Service component test', () => {
const memFs = createMemoryFs({ [baseFileName]: baseFilecContent, [importFileName]: importFileContent });
const { requireModule } = createCjsModuleSystem({ fs: memFs });

const stylableLSP = new VscodeStylableLanguageService(
const stylableLSP = new VSCodeStylableLanguageService(
connection,
new TestDocuments({
[baseTextDocument.uri]: baseTextDocument,
Expand Down Expand Up @@ -366,7 +366,7 @@ describe('Service component test', () => {
const memFs = createMemoryFs({ [filePath]: fileText });
const { requireModule } = createCjsModuleSystem({ fs: memFs });

const stylableLSP = new VscodeStylableLanguageService(
const stylableLSP = new VSCodeStylableLanguageService(
connection,
new TestDocuments({
[textDocument.uri]: textDocument,
Expand Down