-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathserver.ts
More file actions
344 lines (310 loc) · 10.7 KB
/
server.ts
File metadata and controls
344 lines (310 loc) · 10.7 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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
import {
createConnection,
TextDocuments,
Diagnostic,
ProposedFeatures,
InitializeParams,
DidChangeConfigurationNotification,
TextDocumentSyncKind,
InitializeResult,
SymbolInformation,
SymbolKind,
} from 'vscode-languageserver/node';
import {
TextDocument
} from 'vscode-languageserver-textdocument';
import { Position } from 'vscode-languageserver-protocol';
// Create a connection for the server, using Node's IPC as a transport.
// Also include all preview / proposed LSP features.
const connection = createConnection(ProposedFeatures.all);
// Create a simple text document manager.
const documents: TextDocuments<TextDocument> = new TextDocuments(TextDocument);
let hasConfigurationCapability = false;
let hasWorkspaceFolderCapability = false;
let hasDiagnosticRelatedInformationCapability = false;
import fs = require('fs');
import tmp = require('tmp');
// import path = require('path');
import util = require('node:util');
import { TextEncoder } from 'node:util';
// import { Console } from 'console';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const exec = util.promisify(require('node:child_process').exec);
const tmpFile = tmp.fileSync();
connection.onInitialize((params: InitializeParams) => {
const capabilities = params.capabilities;
// Does the client support the `workspace/configuration` request?
// If not, we fall back using global settings.
hasConfigurationCapability = !!(
capabilities.workspace && !!capabilities.workspace.configuration
);
hasWorkspaceFolderCapability = !!(
capabilities.workspace && !!capabilities.workspace.workspaceFolders
);
hasDiagnosticRelatedInformationCapability = !!(
capabilities.textDocument &&
capabilities.textDocument.publishDiagnostics &&
capabilities.textDocument.publishDiagnostics.relatedInformation
);
const result: InitializeResult = {
capabilities: {
textDocumentSync: TextDocumentSyncKind.Incremental,
documentSymbolProvider: true,
definitionProvider: true,
}
};
if (hasWorkspaceFolderCapability) {
result.capabilities.workspace = {
workspaceFolders: {
supported: true
}
};
}
// console.log('LPython language server initialized');
return result;
});
connection.onInitialized(() => {
if (hasConfigurationCapability) {
// Register for all configuration changes.
connection.client.register(DidChangeConfigurationNotification.type, undefined);
}
if (hasWorkspaceFolderCapability) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
connection.workspace.onDidChangeWorkspaceFolders(_event => {
// connection.console.log('Workspace folder change event received.');
});
}
});
// Borrowed from Jakt: https://github.com/SerenityOS/jakt
function convertPosition(position: Position, text: string): number {
let line = 0;
let character = 0;
const buffer = new TextEncoder().encode(text);
let i = 0;
while (i < text.length) {
if (line == position.line && character == position.character) {
return i;
}
if (buffer.at(i) == 0x0A) {
line++;
character = 0;
} else {
character++;
}
i++;
}
return i;
}
connection.onDefinition(async (request) => {
console.time('onDefinition');
const document = documents.get(request.textDocument.uri);
const settings = await getDocumentSettings(request.textDocument.uri);
const text = document?.getText();
const symbols: SymbolInformation[] = [];
if (typeof text == "string") {
console.log("request: ");
console.log(request);
console.log("index: " + convertPosition(request.position, text));
const stdout = await runCompiler(text, "--goto-def " + convertPosition(request.position, text), settings);
console.log("got: ", stdout);
const obj = JSON.parse(stdout);
for (let i = 0; i < obj.length; i++) {
if (obj[i].location) {
return [{
targetUri: request.textDocument.uri,
targetRange: {
start: { line: obj[i].location.range.start.line, character: obj[i].location.range.start.character },
end: { line: obj[i].location.range.end.line, character: obj[i].location.range.end.character }
},
targetSelectionRange: {
start: { line: obj[i].location.range.start.line, character: obj[i].location.range.start.character },
end: { line: obj[i].location.range.end.line, character: obj[i].location.range.end.character }
},
originSelectionRange: {
start: { line: request.position.line, character: Math.max(0, request.position.character - 4) },
end: { line: request.position.line, character: request.position.character + 4 }
}
}];
}
}
// console.timeEnd('onDefinition');
return undefined;
}
});
// The example settings
interface ExampleSettings {
maxNumberOfProblems: number;
compiler: {
executablePath: string;
};
}
// The global settings, used when the `workspace/configuration` request is not supported by the client.
// Please note that this is not the case when using this server with the client provided in this example
// but could happen with other clients.
const defaultSettings: ExampleSettings = { maxNumberOfProblems: 1000, compiler: { executablePath: "lpython" } };
let globalSettings: ExampleSettings = defaultSettings;
// Cache the settings of all open documents
const documentSettings: Map<string, Thenable<ExampleSettings>> = new Map();
connection.onDocumentSymbol(async (request) => {
const document = documents.get(request.textDocument.uri);
const settings = await getDocumentSettings(request.textDocument.uri);
const text = document?.getText();
const symbols: SymbolInformation[] = [];
if (typeof text == "string") {
const stdout = await runCompiler(text, "--show-document-symbols ", settings);
const obj = JSON.parse(stdout);
for (let i=0; i<obj.length; i++) {
if (obj[i].location) {
const symbol: SymbolInformation = {
location: {
uri: request.textDocument.uri,
range: {
start: Position.create(obj[i].location.range.start.line, obj[i].location.range.start.character),
end: Position.create(obj[i].location.range.end.line, obj[i].location.range.end.character),
},
},
kind: SymbolKind.Function,
name: obj[i].name,
};
symbols.push(symbol);
}
}
}
console.log(symbols);
return symbols;
});
connection.onDidChangeConfiguration(change => {
// console.log("onDidChangeConfiguration, hasConfigurationCapability: " + hasConfigurationCapability);
// console.log("change is " + JSON.stringify(change));
if (hasConfigurationCapability) {
// Reset all cached document settings
documentSettings.clear();
} else {
globalSettings = <ExampleSettings>(
(change.settings.LPythonLanguageServer || defaultSettings)
);
}
// Revalidate all open text documents
documents.all().forEach(validateTextDocument);
});
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function getDocumentSettings(resource: string): Thenable<ExampleSettings> {
if (!hasConfigurationCapability) {
return Promise.resolve(globalSettings);
}
let result = documentSettings.get(resource);
if (!result) {
result = connection.workspace.getConfiguration({
scopeUri: resource,
section: 'LPythonLanguageServer'
});
documentSettings.set(resource, result);
}
return result;
}
// Only keep settings for open documents
documents.onDidClose(e => {
documentSettings.delete(e.document.uri);
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function throttle(fn: (...args: any) => void, delay: number) {
let shouldWait = false;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let waitingArgs: any | null;
const timeoutFunc = () => {
if (waitingArgs == null) {
shouldWait = false;
} else {
fn(...waitingArgs);
waitingArgs = null;
setTimeout(timeoutFunc, delay);
}
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (...args: any) => {
if (shouldWait) {
waitingArgs = args;
return;
}
fn(...args);
shouldWait = true;
setTimeout(timeoutFunc, delay);
};
}
// The content of a text document has changed. This event is emitted
// when the text document first opened or when its content has changed.
documents.onDidChangeContent((
() => {
const throttledValidateTextDocument = throttle(validateTextDocument, 500);
return (change) => {
throttledValidateTextDocument(change.document);
};
}
)());
async function runCompiler(text: string, flags: string, settings: ExampleSettings): Promise<string> {
try {
fs.writeFileSync(tmpFile.name, text);
} catch (error) {
console.log(error);
}
let stdout: string;
try {
const output = await exec(`${settings.compiler.executablePath} ${flags} ${tmpFile.name}`);
// console.log(output);
stdout = output.stdout;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
stdout = e.stdout;
if (e.signal != null) {
console.log("compile failed: ");
console.log(e);
} else {
console.log("Error:", e);
}
}
return stdout;
}
async function validateTextDocument(textDocument: TextDocument): Promise<void> {
console.time('validateTextDocument');
if (!hasDiagnosticRelatedInformationCapability) {
console.error('Trying to validate a document with no diagnostic capability');
return;
}
// // In this simple example we get the settings for every validate run.
const settings = await getDocumentSettings(textDocument.uri);
// The validator creates diagnostics for all uppercase words length 2 and more
const text = textDocument.getText();
const stdout = await runCompiler(text, "--show-errors ", settings);
const obj = JSON.parse(stdout);
const diagnostics: Diagnostic[] = [];
if (obj.diagnostics) {
const diagnostic: Diagnostic = {
severity: 2,
range: {
start: Position.create(obj.diagnostics[0].range.start.line, obj.diagnostics[0].range.start.character),
end: Position.create(obj.diagnostics[0].range.end.line, obj.diagnostics[0].range.end.character),
},
message: obj.diagnostics[0].message,
source: "lpyth"
};
diagnostics.push(diagnostic);
}
// console.log(diagnostics);
// Send the computed diagnostics to VSCode.
connection.sendDiagnostics({ uri: textDocument.uri, diagnostics });
console.timeEnd('validateTextDocument');
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
connection.onDidChangeWatchedFiles(_change => {
// Monitored files have change in VSCode
connection.console.log('We received an file change event');
});
// Make the text document manager listen on the connection
// for open, change and close text document events
documents.listen(connection);
// Listen on the connection
connection.listen();