vscode插件快餐教程(4) - 語言服務器協議lsp
語言服務器協議lsp是vscode爲了解決語言擴展中的痛點來實現的一套協議。如下圖所示:
總體說來,在有lsp之前,存在三個主要問題:
一是語言相關的擴展都是用該語言母語寫的,不容易集成到插件中去。畢竟現在大量的語言都帶有運行時。
二是語言掃描相關的工作都比較佔用CPU資源,運行在vscode內部不如放在獨立進程,甚至遠程服務器上更好。
三是如上圖左邊所示,缺少一套協議的話,每種語言服務需要適配多個編輯器。同樣,每種編輯器也需要各種語言服務。這造成了較大的資源浪費。
LSP協議概述
LSP是基於json rpc的協議。
我們先來看一個例子:
Content-Length: ...\r\n
\r\n
{
"jsonrpc": "2.0",
"id": 1,
"method": "textDocument/didOpen",
"params": {
...
}
}
jsonrpc是json rpc協議的頭,LSP主要是定義了method和params。
從服務端發給客戶端的,是Request,客戶端返回Response。客戶端主動發起的是Notification.
下面我們用一張圖來看看LSP目前都支持哪些功能:
最大的一塊是語言功能,這些也通可以通過本地的Provider等方法來實現。
生命週期管理
服務器的生命週期通過客戶端發送initialize請求開始,負載爲一個InitializeParameter對象:
interface InitializeParams {
/**
* The process Id of the parent process that started
* the server. Is null if the process has not been started by another process.
* If the parent process is not alive then the server should exit (see exit notification) its process.
*/
processId: number | null;
/**
* The rootPath of the workspace. Is null
* if no folder is open.
*
* @deprecated in favour of rootUri.
*/
rootPath?: string | null;
/**
* The rootUri of the workspace. Is null if no
* folder is open. If both `rootPath` and `rootUri` are set
* `rootUri` wins.
*/
rootUri: DocumentUri | null;
/**
* User provided initialization options.
*/
initializationOptions?: any;
/**
* The capabilities provided by the client (editor or tool)
*/
capabilities: ClientCapabilities;
/**
* The initial trace setting. If omitted trace is disabled ('off').
*/
trace?: 'off' | 'messages' | 'verbose';
/**
* The workspace folders configured in the client when the server starts.
* This property is only available if the client supports workspace folders.
* It can be `null` if the client supports workspace folders but none are
* configured.
*
* Since 3.6.0
*/
workspaceFolders?: WorkspaceFolder[] | null;
}
而服務端返回的,是服務器的能力:
interface InitializeResult {
/**
* The capabilities the language server provides.
*/
capabilities: ServerCapabilities;
}
ServerCapabilities的定義如下。主要對應了Workspace和TextDocument兩大類型的API:
interface ClientCapabilities {
/**
* Workspace specific client capabilities.
*/
workspace?: WorkspaceClientCapabilities;
/**
* Text document specific client capabilities.
*/
textDocument?: TextDocumentClientCapabilities;
/**
* Experimental client capabilities.
*/
experimental?: any;
}
客戶端收到initialize result之後,按照三次握手的原則,將返回一個initialized消息做確認。至此,一個服務端與客戶端通信的生命週期就算是成功建立。
LSP協議的實現
除了整個協議的詳細描述之外,微軟還爲我們準備了LSP的SDK,源碼在:https://github.com/microsoft/vscode-languageserver-node
我們首先從server側來講解LSP sdk的用法。
createConnection
服務端首先要獲取一個Connection對象,通過vscode-languageserver提供的createConnection函數來創建Connection.
let connection = createConnection(ProposedFeatures.all);
Connection中對於LSP的消息進行了封裝,比如:
onInitialize: (handler) => initializeHandler = handler,
onInitialized: (handler) => connection.onNotification(InitializedNotification.type, handler),
onShutdown: (handler) => shutdownHandler = handler,
onExit: (handler) => exitHandler = handler,
...
onDidChangeConfiguration: (handler) => connection.onNotification(DidChangeConfigurationNotification.type, handler),
onDidChangeWatchedFiles: (handler) => connection.onNotification(DidChangeWatchedFilesNotification.type, handler),
...
onDidOpenTextDocument: (handler) => connection.onNotification(DidOpenTextDocumentNotification.type, handler),
onDidChangeTextDocument: (handler) => connection.onNotification(DidChangeTextDocumentNotification.type, handler),
onDidCloseTextDocument: (handler) => connection.onNotification(DidCloseTextDocumentNotification.type, handler),
onWillSaveTextDocument: (handler) => connection.onNotification(WillSaveTextDocumentNotification.type, handler),
onWillSaveTextDocumentWaitUntil: (handler) => connection.onRequest(WillSaveTextDocumentWaitUntilRequest.type, handler),
onDidSaveTextDocument: (handler) => connection.onNotification(DidSaveTextDocumentNotification.type, handler),
sendDiagnostics: (params) => connection.sendNotification(PublishDiagnosticsNotification.type, params),
...
onHover: (handler) => connection.onRequest(HoverRequest.type, handler),
onCompletion: (handler) => connection.onRequest(CompletionRequest.type, handler),
onCompletionResolve: (handler) => connection.onRequest(CompletionResolveRequest.type, handler),
onSignatureHelp: (handler) => connection.onRequest(SignatureHelpRequest.type, handler),
onDeclaration: (handler) => connection.onRequest(DeclarationRequest.type, handler),
onDefinition: (handler) => connection.onRequest(DefinitionRequest.type, handler),
onTypeDefinition: (handler) => connection.onRequest(TypeDefinitionRequest.type, handler),
onImplementation: (handler) => connection.onRequest(ImplementationRequest.type, handler),
onReferences: (handler) => connection.onRequest(ReferencesRequest.type, handler),
onDocumentHighlight: (handler) => connection.onRequest(DocumentHighlightRequest.type, handler),
onDocumentSymbol: (handler) => connection.onRequest(DocumentSymbolRequest.type, handler),
onWorkspaceSymbol: (handler) => connection.onRequest(WorkspaceSymbolRequest.type, handler),
onCodeAction: (handler) => connection.onRequest(CodeActionRequest.type, handler),
onCodeLens: (handler) => connection.onRequest(CodeLensRequest.type, handler),
onCodeLensResolve: (handler) => connection.onRequest(CodeLensResolveRequest.type, handler),
onDocumentFormatting: (handler) => connection.onRequest(DocumentFormattingRequest.type, handler),
onDocumentRangeFormatting: (handler) => connection.onRequest(DocumentRangeFormattingRequest.type, handler),
onDocumentOnTypeFormatting: (handler) => connection.onRequest(DocumentOnTypeFormattingRequest.type, handler),
onRenameRequest: (handler) => connection.onRequest(RenameRequest.type, handler),
onPrepareRename: (handler) => connection.onRequest(PrepareRenameRequest.type, handler),
onDocumentLinks: (handler) => connection.onRequest(DocumentLinkRequest.type, handler),
onDocumentLinkResolve: (handler) => connection.onRequest(DocumentLinkResolveRequest.type, handler),
onDocumentColor: (handler) => connection.onRequest(DocumentColorRequest.type, handler),
onColorPresentation: (handler) => connection.onRequest(ColorPresentationRequest.type, handler),
onFoldingRanges: (handler) => connection.onRequest(FoldingRangeRequest.type, handler),
onExecuteCommand: (handler) => connection.onRequest(ExecuteCommandRequest.type, handler),
協議中的所有的消息都有封裝。
onInitialize
通過createConnection創建了Connection對象之後,我們就可以調用connection.listen()來實現對client的監聽了。
在監聽之前,我們需要把處理監聽事件的回調函數設好。
首先是處理initialize消息的onInitialize,之前我們講協議時介紹了,主要工作是告知client這個服務端的能力:
connection.onInitialize((params: InitializeParams) => {
let capabilities = params.capabilities;
return {
capabilities: {
textDocumentSync: documents.syncKind,
// Tell the client that the server supports code completion
completionProvider: {
resolveProvider: true
}
}
};
});
根據三次握手的原則,客戶端還會返回initialized notification進行通知,服務端可以借用處理這個notification的返回值進行一些初始化的工作。例:
connection.onInitialized(() => {
if (hasWorkspaceFolderCapability) {
connection.workspace.onDidChangeWorkspaceFolders(_event => {
connection.console.log('Workspace folder change event received.');
});
}
});