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

Introduce DocumentUpdateHandler service #1286

Merged
merged 4 commits into from
Dec 11, 2023
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
11 changes: 2 additions & 9 deletions examples/arithmetics/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
******************************************************************************/

import type { LanguageClientOptions, ServerOptions } from 'vscode-languageclient/node.js';
import * as vscode from 'vscode';
import type * as vscode from 'vscode';
import * as path from 'node:path';
import { LanguageClient, TransportKind } from 'vscode-languageclient/node.js';

Expand Down Expand Up @@ -37,16 +37,9 @@ function startLanguageClient(context: vscode.ExtensionContext): LanguageClient {
debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions }
};

const fileSystemWatcher = vscode.workspace.createFileSystemWatcher('**/*.calc');
context.subscriptions.push(fileSystemWatcher);

// Options to control the language client
const clientOptions: LanguageClientOptions = {
documentSelector: [{ scheme: 'file', language: 'arithmetics' }],
synchronize: {
// Notify the server about file changes to files contained in the workspace
fileEvents: fileSystemWatcher
}
documentSelector: [{ scheme: 'file', language: 'arithmetics' }]
};

// Create the language client and start the client.
Expand Down
11 changes: 2 additions & 9 deletions examples/domainmodel/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
******************************************************************************/

import type { LanguageClientOptions, ServerOptions } from 'vscode-languageclient/node.js';
import * as vscode from 'vscode';
import type * as vscode from 'vscode';
import * as path from 'node:path';
import { LanguageClient, TransportKind } from 'vscode-languageclient/node.js';

Expand Down Expand Up @@ -37,16 +37,9 @@ function startLanguageClient(context: vscode.ExtensionContext): LanguageClient {
debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions }
};

const fileSystemWatcher = vscode.workspace.createFileSystemWatcher('**/*.dmodel');
context.subscriptions.push(fileSystemWatcher);

// Options to control the language client
const clientOptions: LanguageClientOptions = {
documentSelector: [{ scheme: 'file', language: 'domain-model' }],
synchronize: {
// Notify the server about file changes to files contained in the workspace
fileEvents: fileSystemWatcher
}
documentSelector: [{ scheme: 'file', language: 'domain-model' }]
};

// Create the language client and start the client.
Expand Down
11 changes: 2 additions & 9 deletions examples/requirements/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

import type { LanguageClientOptions, ServerOptions } from 'vscode-languageclient/node.js';
import { LanguageClient, TransportKind } from 'vscode-languageclient/node.js';
import * as vscode from 'vscode';
import type * as vscode from 'vscode';
import * as path from 'node:path';

let client: LanguageClient;
Expand Down Expand Up @@ -38,18 +38,11 @@ function startLanguageClient(context: vscode.ExtensionContext): LanguageClient {
debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions }
};

const fileSystemWatcher = vscode.workspace.createFileSystemWatcher('**/*.(req|tst)');
context.subscriptions.push(fileSystemWatcher);

// Options to control the language client
const clientOptions: LanguageClientOptions = {
documentSelector: [
{ scheme: 'file', language: 'tests-lang' },
{ scheme: 'file', language: 'requirements-lang' }],
synchronize: {
// Notify the server about file changes to files contained in the workspace
fileEvents: fileSystemWatcher
}
{ scheme: 'file', language: 'requirements-lang' }]
};

// Create the language client and start the client.
Expand Down
11 changes: 2 additions & 9 deletions examples/statemachine/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
******************************************************************************/

import type { LanguageClientOptions, ServerOptions } from 'vscode-languageclient/node.js';
import * as vscode from 'vscode';
import type * as vscode from 'vscode';
import * as path from 'node:path';
import { LanguageClient, TransportKind } from 'vscode-languageclient/node.js';

Expand Down Expand Up @@ -37,16 +37,9 @@ function startLanguageClient(context: vscode.ExtensionContext): LanguageClient {
debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions }
};

const fileSystemWatcher = vscode.workspace.createFileSystemWatcher('**/*.statemachine');
context.subscriptions.push(fileSystemWatcher);

// Options to control the language client
const clientOptions: LanguageClientOptions = {
documentSelector: [{ scheme: 'file', language: 'statemachine' }],
synchronize: {
// Notify the server about file changes to files contained in the workspace
fileEvents: fileSystemWatcher
}
documentSelector: [{ scheme: 'file', language: 'statemachine' }]
};

// Create the language client and start the client.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { LanguageClientOptions, ServerOptions} from 'vscode-languageclient/node.js';
import * as vscode from 'vscode';
import type * as vscode from 'vscode';
import * as path from 'node:path';
import { LanguageClient, TransportKind } from 'vscode-languageclient/node.js';

Expand Down Expand Up @@ -32,16 +32,9 @@ function startLanguageClient(context: vscode.ExtensionContext): LanguageClient {
debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions }
};

const fileSystemWatcher = vscode.workspace.createFileSystemWatcher('**/*.<%= file-glob-extension %>');
context.subscriptions.push(fileSystemWatcher);

// Options to control the language client
const clientOptions: LanguageClientOptions = {
documentSelector: [{ scheme: 'file', language: '<%= language-id %>' }],
synchronize: {
// Notify the server about file changes to files contained in the workspace
fileEvents: fileSystemWatcher
}
documentSelector: [{ scheme: 'file', language: '<%= language-id %>' }]
};

// Create the language client and start the client.
Expand Down
9 changes: 1 addition & 8 deletions packages/langium-vscode/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,17 +45,10 @@ async function startLanguageClient(context: vscode.ExtensionContext): Promise<La
}
};

const fileSystemWatcher = vscode.workspace.createFileSystemWatcher('**/*.langium');
context.subscriptions.push(fileSystemWatcher);

// Options to control the language client
const clientOptions: LanguageClientOptions = {
// Register the server for langium documents
documentSelector: [{ scheme: 'file', language: 'langium' }],
synchronize: {
// Notify the server about file changes to langium files contained in the workspace
fileEvents: fileSystemWatcher
}
documentSelector: [{ scheme: 'file', language: 'langium' }]
};

// Create the language client and start the client.
Expand Down
2 changes: 2 additions & 0 deletions packages/langium/src/default-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { createCompletionParser } from './parser/completion-parser-builder.js';
import { DefaultCompletionProvider } from './lsp/completion/completion-provider.js';
import { DefaultDocumentHighlightProvider } from './lsp/document-highlight-provider.js';
import { DefaultDocumentSymbolProvider } from './lsp/document-symbol-provider.js';
import { DefaultDocumentUpdateHandler } from './lsp/document-update-handler.js';
import { DefaultFoldingRangeProvider } from './lsp/folding-range-provider.js';
import { DefaultFuzzyMatcher } from './lsp/fuzzy-matcher.js';
import { DefaultDefinitionProvider } from './lsp/definition-provider.js';
Expand Down Expand Up @@ -136,6 +137,7 @@ export function createDefaultSharedModule(context: DefaultSharedModuleContext):
lsp: {
Connection: () => context.connection,
LanguageServer: (services) => new DefaultLanguageServer(services),
DocumentUpdateHandler: (services) => new DefaultDocumentUpdateHandler(services),
WorkspaceSymbolProvider: (services) => new DefaultWorkspaceSymbolProvider(services),
NodeKindProvider: () => new DefaultNodeKindProvider(),
FuzzyMatcher: () => new DefaultFuzzyMatcher()
Expand Down
95 changes: 95 additions & 0 deletions packages/langium/src/lsp/document-update-handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/******************************************************************************
* Copyright 2023 TypeFox GmbH
* This program and the accompanying materials are made available under the
* terms of the MIT License, which is available in the project root.
******************************************************************************/

import type { DidChangeWatchedFilesParams, DidChangeWatchedFilesRegistrationOptions, TextDocumentChangeEvent } from 'vscode-languageserver';
import type { TextDocument } from 'vscode-languageserver-textdocument';
import type { LangiumSharedServices } from '../services.js';
import type { MutexLock } from '../utils/promise-util.js';
import type { DocumentBuilder } from '../workspace/document-builder.js';
import { DidChangeWatchedFilesNotification, FileChangeType } from 'vscode-languageserver';
import { URI } from 'vscode-uri';
import { stream } from '../utils/stream.js';

/**
* Shared service for handling text document changes and watching relevant files.
*/
export interface DocumentUpdateHandler {

/**
* A content change event was triggered by the `TextDocuments` service.
*/
didChangeContent(change: TextDocumentChangeEvent<TextDocument>): void;

/**
* The client detected changes to files and folders watched by the language client.
*/
didChangeWatchedFiles(params: DidChangeWatchedFilesParams): void;

}

export class DefaultDocumentUpdateHandler implements DocumentUpdateHandler {

protected readonly documentBuilder: DocumentBuilder;
protected readonly mutexLock: MutexLock;

constructor(services: LangiumSharedServices) {
this.documentBuilder = services.workspace.DocumentBuilder;
this.mutexLock = services.workspace.MutexLock;

let canRegisterFileWatcher = false;
services.lsp.LanguageServer.onInitialize(params => {
canRegisterFileWatcher = Boolean(params.capabilities.workspace?.didChangeWatchedFiles?.dynamicRegistration);
});

services.lsp.LanguageServer.onInitialized(_params => {
if (canRegisterFileWatcher) {
this.registerFileWatcher(services);
}
});
}

protected registerFileWatcher(services: LangiumSharedServices): void {
const fileExtensions = stream(services.ServiceRegistry.all)
.flatMap(language => language.LanguageMetaData.fileExtensions)
.map(ext => ext.startsWith('.') ? ext.substring(1) : ext)
.distinct()
.toArray();
if (fileExtensions.length > 0) {
const connection = services.lsp.Connection;
const options: DidChangeWatchedFilesRegistrationOptions = {
watchers: [{
globPattern: fileExtensions.length === 1
? `**/*.${fileExtensions[0]}`
: `**/*.{${fileExtensions.join(',')}}`
}]
};
connection?.client.register(DidChangeWatchedFilesNotification.type, options);
}
}

protected fireDocumentUpdate(changed: URI[], deleted: URI[]): void {
this.mutexLock.lock(token => this.documentBuilder.update(changed, deleted, token));
}

didChangeContent(change: TextDocumentChangeEvent<TextDocument>): void {
this.fireDocumentUpdate([URI.parse(change.document.uri)], []);
}

didChangeWatchedFiles(params: DidChangeWatchedFilesParams): void {
const changedUris = stream(params.changes)
.filter(c => c.type !== FileChangeType.Deleted)
.distinct(c => c.uri)
.map(c => URI.parse(c.uri))
.toArray();
const deletedUris = stream(params.changes)
.filter(c => c.type === FileChangeType.Deleted)
.distinct(c => c.uri)
.map(c => URI.parse(c.uri))
.toArray();
this.fireDocumentUpdate(changedUris, deletedUris);
}

}
63 changes: 63 additions & 0 deletions packages/langium/src/lsp/file-operation-handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/******************************************************************************
* Copyright 2023 TypeFox GmbH
* This program and the accompanying materials are made available under the
* terms of the MIT License, which is available in the project root.
******************************************************************************/

import type { CreateFilesParams, DeleteFilesParams, FileOperationOptions, RenameFilesParams, WorkspaceEdit } from 'vscode-languageserver';
import type { MaybePromise } from '../utils/promise-util.js';

/**
* Shared service for handling file changes such as file creation, deletion and renaming.
* The interface methods are optional, so they are only registered if they are implemented.
*/
export interface FileOperationHandler {

/**
* These options are reported to the client as part of the ServerCapabilities.
*/
readonly fileOperationOptions: FileOperationOptions;

/**
* Files were created from within the client.
* This notification must be registered with the {@link fileOperationOptions}.
*/
didCreateFiles?(params: CreateFilesParams): void;

/**
* Files were renamed from within the client.
* This notification must be registered with the {@link fileOperationOptions}.
*/
didRenameFiles?(params: RenameFilesParams): void;

/**
* Files were deleted from within the client.
* This notification must be registered with the {@link fileOperationOptions}.
*/
didDeleteFiles?(params: DeleteFilesParams): void;

/**
* Called before files are actually created as long as the creation is triggered from within
* the client either by a user action or by applying a workspace edit.
* This request must be registered with the {@link fileOperationOptions}.
* @returns a WorkspaceEdit which will be applied to workspace before the files are created.
*/
willCreateFiles?(params: CreateFilesParams): MaybePromise<WorkspaceEdit | null>;

/**
* Called before files are actually renamed as long as the rename is triggered from within
* the client either by a user action or by applying a workspace edit.
* This request must be registered with the {@link fileOperationOptions}.
* @returns a WorkspaceEdit which will be applied to workspace before the files are renamed.
*/
willRenameFiles?(params: RenameFilesParams): MaybePromise<WorkspaceEdit | null>;

/**
* Called before files are actually deleted as long as the deletion is triggered from within
* the client either by a user action or by applying a workspace edit.
* This request must be registered with the {@link fileOperationOptions}.
* @returns a WorkspaceEdit which will be applied to workspace before the files are deleted.
*/
willDeleteFiles?(params: DeleteFilesParams): MaybePromise<WorkspaceEdit | null>;

}
Loading