-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.ts
More file actions
302 lines (271 loc) · 10.1 KB
/
server.ts
File metadata and controls
302 lines (271 loc) · 10.1 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
/*
* This file is part of OpenModelica.
*
* Copyright (c) 1998-2024, Open Source Modelica Consortium (OSMC),
* c/o Linköpings universitet, Department of Computer and Information Science,
* SE-58183 Linköping, Sweden.
*
* All rights reserved.
*
* THIS PROGRAM IS PROVIDED UNDER THE TERMS OF AGPL VERSION 3 LICENSE OR
* THIS OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.8.
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GNU AGPL
* VERSION 3, ACCORDING TO RECIPIENTS CHOICE.
*
* The OpenModelica software and the OSMC (Open Source Modelica Consortium)
* Public License (OSMC-PL) are obtained from OSMC, either from the above
* address, from the URLs:
* http://www.openmodelica.org or
* https://github.com/OpenModelica/ or
* http://www.ida.liu.se/projects/OpenModelica,
* and in the OpenModelica distribution.
*
* GNU AGPL version 3 is obtained from:
* https://www.gnu.org/licenses/licenses.html#GPL
*
* This program is distributed WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH
* IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL.
*
* See the full OSMC Public License conditions for more details.
*
*/
/* -----------------------------------------------------------------------------
* Taken from bash-language-server and adapted to Modelica language server
* https://github.com/bash-lsp/bash-language-server/blob/main/server/src/server.ts
* -----------------------------------------------------------------------------
*/
import * as LSP from 'vscode-languageserver/node';
import { TextDocument } from 'vscode-languageserver-textdocument';
import url from 'node:url';
import fs from 'node:fs/promises';
import path from 'node:path';
import { initializeParser } from './parser';
import Analyzer from './analyzer';
import { logger, setLoggerOptions } from './util/logger';
/**
* ModelicaServer collection all the important bits and bobs.
*/
export class ModelicaServer {
#analyzer: Analyzer;
#clientCapabilities: LSP.ClientCapabilities;
#connection: LSP.Connection;
#documents: LSP.TextDocuments<TextDocument> = new LSP.TextDocuments(TextDocument);
private constructor(
analyzer: Analyzer,
clientCapabilities: LSP.ClientCapabilities,
connection: LSP.Connection,
) {
this.#analyzer = analyzer;
this.#clientCapabilities = clientCapabilities;
this.#connection = connection;
}
public static async initialize(
connection: LSP.Connection,
{ capabilities, workspaceFolders, initializationOptions }: LSP.InitializeParams,
): Promise<ModelicaServer> {
// Initialize logger
setLoggerOptions({
connection,
logLevel: 'debug',
});
logger.debug('Initializing...');
const parser = await initializeParser();
const analyzer = new Analyzer(parser);
if (workspaceFolders != null) {
for (const workspace of workspaceFolders) {
await analyzer.loadLibrary(workspace.uri, true);
}
}
const configuredLibraries = [
...(Array.isArray(
(initializationOptions as { modelicaPath?: unknown } | undefined)?.modelicaPath,
)
? (initializationOptions as { modelicaPath: unknown[] }).modelicaPath.filter(
(value): value is string => typeof value === 'string' && value.length > 0,
)
: []),
...(Array.isArray((initializationOptions as { libraries?: unknown } | undefined)?.libraries)
? (initializationOptions as { libraries: unknown[] }).libraries.filter(
(value): value is string => typeof value === 'string' && value.length > 0,
)
: []),
];
for (const libraryPath of configuredLibraries) {
const libraryUri = url.pathToFileURL(path.resolve(libraryPath)).toString();
logger.debug(`Loading configured library '${libraryPath}'`);
await analyzer.loadLibrary(libraryUri, false);
}
logger.debug('Initialized');
return new ModelicaServer(analyzer, capabilities, connection);
}
/**
* Return what parts of the language server protocol are supported by ModelicaServer.
*/
public capabilities(): LSP.ServerCapabilities {
return {
completionProvider: undefined,
declarationProvider: true,
definitionProvider: true,
hoverProvider: false,
signatureHelpProvider: undefined,
documentSymbolProvider: true,
colorProvider: false,
semanticTokensProvider: undefined,
textDocumentSync: LSP.TextDocumentSyncKind.Incremental,
workspace: {
workspaceFolders: {
supported: true,
changeNotifications: true,
},
},
};
}
public register(connection: LSP.Connection): void {
// Make the text document manager listen on the connection
// for open, change and close text document events
this.#documents.listen(this.#connection);
connection.onInitialized(this.onInitialized.bind(this));
connection.onShutdown(this.onShutdown.bind(this));
connection.onDidChangeTextDocument(this.onDidChangeTextDocument.bind(this));
connection.onDidChangeWatchedFiles(this.onDidChangeWatchedFiles.bind(this));
connection.onDeclaration(this.onDeclaration.bind(this));
connection.onDefinition(this.onDefinition.bind(this));
connection.onDocumentSymbol(this.onDocumentSymbol.bind(this));
}
private async onInitialized(): Promise<void> {
logger.debug('onInitialized');
await connection.client.register(
new LSP.ProtocolNotificationType('workspace/didChangeWatchedFiles'),
{
watchers: [
{
globPattern: '**/*.{mo,mos}',
},
],
},
);
// If we opened a project, analyze it now that we're initialized
// and the linter is ready.
// TODO: analysis
}
private async onShutdown(): Promise<void> {
logger.debug('onShutdown');
}
private async onDidChangeTextDocument(params: LSP.DidChangeTextDocumentParams): Promise<void> {
logger.debug('onDidChangeTextDocument');
for (const change of params.contentChanges) {
const range = 'range' in change ? change.range : undefined;
await this.#analyzer.updateDocument(params.textDocument.uri, change.text, range);
}
}
private async onDidChangeWatchedFiles(params: LSP.DidChangeWatchedFilesParams): Promise<void> {
logger.debug('onDidChangeWatchedFiles: ' + JSON.stringify(params, undefined, 4));
for (const change of params.changes) {
switch (change.type) {
case LSP.FileChangeType.Created:
await this.#analyzer.addDocument(change.uri);
break;
case LSP.FileChangeType.Changed: {
// TODO: incremental?
const path = url.fileURLToPath(change.uri);
const content = await fs.readFile(path, 'utf-8');
await this.#analyzer.updateDocument(change.uri, content);
break;
}
case LSP.FileChangeType.Deleted: {
this.#analyzer.removeDocument(change.uri);
break;
}
}
}
}
// TODO: We currently treat goto declaration and goto definition the same,
// but there are probably some differences we need to handle.
//
// 1. inner/outer variables. Modelica allows the user to redeclare variables
// from enclosing classes to use them in inner classes. Goto Declaration
// should go to whichever declaration is in scope, while Goto Definition
// should go to the `outer` declaration. In the following example:
//
// model Outer
// model Inner
// inner Real shared;
// equation
// shared = ...; (A)
// end Inner;
// outer Real shared = 0;
// equation
// shared = ...; (B)
// end Outer;
//
// +-----+-------------+------------+
// | Ref | Declaration | Definition |
// +-----+-------------+------------+
// | A | inner | outer |
// | B | outer | outer |
// +-----+-------------+------------+
//
// 2. extends_clause is weird. This is a valid class:
//
// class extends Foo;
// end Foo;
//
// What does this even mean? Is this a definition of Foo or a redeclaration of Foo?
//
// 3. Import aliases. Should this be considered to be a declaration of `Frobnicator`?
//
// import Frobnicator = Foo.Bar.Baz;
//
private async onDeclaration(params: LSP.DeclarationParams): Promise<LSP.LocationLink[]> {
logger.debug('onDeclaration');
const locationLink = await this.#analyzer.findDeclaration(
params.textDocument.uri,
params.position,
);
if (locationLink == null) {
return [];
}
return [locationLink];
}
private async onDefinition(params: LSP.DefinitionParams): Promise<LSP.LocationLink[]> {
logger.debug('onDefinition');
const locationLink = await this.#analyzer.findDeclaration(
params.textDocument.uri,
params.position,
);
if (locationLink == null) {
return [];
}
return [locationLink];
}
/**
* Provide symbols defined in document.
*
* @param params Unused.
* @returns Symbol information.
*/
private async onDocumentSymbol(
params: LSP.DocumentSymbolParams,
): Promise<LSP.SymbolInformation[]> {
// TODO: ideally this should return LSP.DocumentSymbol[] instead of LSP.SymbolInformation[]
// which is a hierarchy of symbols.
// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_documentSymbol
logger.debug(`onDocumentSymbol`);
return this.#analyzer.getDeclarationsForUri(params.textDocument.uri);
}
}
// Create a connection for the server, using Node's IPC as a transport.
// Also include all preview / proposed LSP features.
const connection = LSP.createConnection(LSP.ProposedFeatures.all);
connection.onInitialize(async (params: LSP.InitializeParams): Promise<LSP.InitializeResult> => {
const server = await ModelicaServer.initialize(connection, params);
server.register(connection);
return {
capabilities: server.capabilities(),
};
});
// Listen on the connection
connection.listen();