-
Notifications
You must be signed in to change notification settings - Fork 28
/
server.ts
655 lines (558 loc) · 18.7 KB
/
server.ts
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
import {
CompletionItem,
CompletionItemKind,
Definition,
Diagnostic,
DiagnosticSeverity,
DidChangeConfigurationNotification,
HandlerResult,
HoverParams,
InitializeParams,
InitializeResult,
ProposedFeatures,
TextDocumentPositionParams,
TextDocumentSyncKind,
TextDocuments,
createConnection,
} from "vscode-languageserver/node";
import {
InlayHint,
InlayHintKind,
InlayHintLabelPart,
InlayHintParams,
Position,
} from "vscode-languageserver-protocol";
import { fileURLToPath } from "node:url";
import { TextEncoder } from "node:util";
import { TextDocument } from "vscode-languageserver-textdocument";
interface NuTextDocument extends TextDocument {
nuInlayHints?: InlayHint[];
}
import fs = require("fs");
import tmp = require("tmp");
import path = require("path");
import util = require("node:util");
// eslint-disable-next-line @typescript-eslint/no-var-requires
const exec = util.promisify(require("node:child_process").exec);
const tmpFile = tmp.fileSync({ prefix: "nushell", keep: false });
// 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;
function includeFlagForPath(file_path: string): string {
if (file_path.startsWith("file://")) {
file_path = decodeURI(file_path);
return "-I " + '"' + path.dirname(fileURLToPath(file_path));
}
return "-I " + '"' + file_path;
}
connection.onExit(() => {
tmpFile.removeCallback();
});
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,
// Tell the client that this server supports code completion.
completionProvider: {
resolveProvider: true,
},
inlayHintProvider: {
resolveProvider: false,
},
hoverProvider: true,
definitionProvider: true,
},
};
if (hasWorkspaceFolderCapability) {
result.capabilities.workspace = {
workspaceFolders: {
supported: true,
},
};
}
return result;
});
let labelid = 0;
function createLabel(name: string): string {
return `${name}#${labelid++}`;
}
async function durationLogWrapper<T>(
name: string,
fn: () => Promise<T>
): Promise<T> {
console.log("Triggered " + name + ": ...");
const label = createLabel(name);
console.time(label);
const result = await fn();
// This purposefully has the same prefix length as the "Triggered " log above,
// also does not add a newline at the end.
process.stdout.write("Finished ");
console.timeEnd(label);
return new Promise<T>((resolve) => resolve(result));
}
connection.onInitialized(() => {
if (hasConfigurationCapability) {
// Register for all configuration changes.
connection.client.register(
DidChangeConfigurationNotification.type,
undefined
);
}
if (hasWorkspaceFolderCapability) {
connection.workspace.onDidChangeWorkspaceFolders((_event) => {
connection.console.log("Workspace folder change event received.");
});
}
});
// The nushell settings
interface NushellIDESettings {
maxNumberOfProblems: number;
hints: {
showInferredTypes: boolean;
};
nushellExecutablePath: string;
maxNushellInvocationTime: number;
includeDirs: 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: NushellIDESettings = {
maxNumberOfProblems: 1000,
hints: { showInferredTypes: true },
nushellExecutablePath: "nu",
maxNushellInvocationTime: 10000000,
includeDirs: [],
};
let globalSettings: NushellIDESettings = defaultSettings;
// Cache the settings of all open documents
const documentSettings: Map<string, Thenable<NushellIDESettings>> = new Map();
connection.onDidChangeConfiguration((change) => {
if (hasConfigurationCapability) {
// Reset all cached document settings
documentSettings.clear();
} else {
globalSettings = <NushellIDESettings>(
(change.settings.nushellLanguageServer || defaultSettings)
);
}
// Revalidate all open text documents
documents.all().forEach(validateTextDocument);
});
function getDocumentSettings(resource: string): Thenable<NushellIDESettings> {
if (!hasConfigurationCapability) {
return Promise.resolve(globalSettings);
}
let result = documentSettings.get(resource);
if (!result) {
result = connection.workspace.getConfiguration({
scopeUri: resource,
section: "nushellLanguageServer",
});
documentSettings.set(resource, result);
}
return result;
}
// Only keep settings for open documents
documents.onDidClose((e) => {
documentSettings.delete(e.document.uri);
});
function debounce(func: any, wait: number, immediate: boolean) {
let timeout: any;
return function executedFunction(this: any, ...args: any[]) {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const context = this;
const later = function () {
timeout = null;
if (!immediate) func.apply(context, args);
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
documents.onDidChangeContent(
(() => {
const throttledValidateTextDocument = debounce(
validateTextDocument,
500,
false
);
return (change) => {
throttledValidateTextDocument(change.document);
};
})()
);
async function validateTextDocument(
textDocument: NuTextDocument
): Promise<void> {
return await durationLogWrapper(
`validateTextDocument ${textDocument.uri}`,
async () => {
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 lineBreaks = findLineBreaks(text);
const stdout = await runCompiler(
text,
"--ide-check",
settings,
textDocument.uri
);
textDocument.nuInlayHints = [];
const diagnostics: Diagnostic[] = [];
// FIXME: We use this to deduplicate type hints given by the compiler.
// It'd be nicer if it didn't give duplicate hints in the first place.
const seenTypeHintPositions = new Set();
const lines = stdout.split("\n").filter((l) => l.length > 0);
for (const line of lines) {
connection.console.log("line: " + line);
try {
const obj = JSON.parse(line);
if (obj.type == "diagnostic") {
let severity: DiagnosticSeverity = DiagnosticSeverity.Error;
switch (obj.severity) {
case "Information":
severity = DiagnosticSeverity.Information;
break;
case "Hint":
severity = DiagnosticSeverity.Hint;
break;
case "Warning":
severity = DiagnosticSeverity.Warning;
break;
case "Error":
severity = DiagnosticSeverity.Error;
break;
}
const position_start = convertSpan(obj.span.start, lineBreaks);
const position_end = convertSpan(obj.span.end, lineBreaks);
const diagnostic: Diagnostic = {
severity,
range: {
start: position_start,
end: position_end,
},
message: obj.message,
source: textDocument.uri,
};
// connection.console.log(diagnostic.message);
diagnostics.push(diagnostic);
} else if (obj.type == "hint" && settings.hints.showInferredTypes) {
if (!seenTypeHintPositions.has(obj.position)) {
seenTypeHintPositions.add(obj.position);
const position = convertSpan(obj.position.end, lineBreaks);
const hint_string = ": " + obj.typename;
const hint = InlayHint.create(
position,
[InlayHintLabelPart.create(hint_string)],
InlayHintKind.Type
);
textDocument.nuInlayHints.push(hint);
}
}
} catch (e) {
connection.console.error(`error: ${e}`);
}
}
// Send the computed diagnostics to VSCode.
connection.sendDiagnostics({ uri: textDocument.uri, diagnostics });
}
);
}
connection.onDidChangeWatchedFiles((_change) => {
// Monitored files have change in VSCode
connection.console.log("We received an file change event");
});
function lowerBoundBinarySearch(arr: number[], num: number): number {
let low = 0;
let mid = 0;
let high = arr.length - 1;
if (num >= arr[high]) return high;
while (low < high) {
// Bitshift to avoid floating point division
mid = (low + high) >> 1;
if (arr[mid] < num) {
low = mid + 1;
} else {
high = mid;
}
}
return low - 1;
}
function convertSpan(utf8_offset: number, lineBreaks: Array<number>): Position {
const lineBreakIndex = lowerBoundBinarySearch(lineBreaks, utf8_offset);
const start_of_line_offset =
lineBreakIndex == -1 ? 0 : lineBreaks[lineBreakIndex] + 1;
const character = Math.max(0, utf8_offset - start_of_line_offset);
return { line: lineBreakIndex + 1, character };
}
function convertPosition(position: Position, text: string): number {
let line = 0;
let character = 0;
const buffer = new TextEncoder().encode(text);
let i = 0;
while (i < buffer.length) {
if (line == position.line && character == position.character) {
return i;
}
if (buffer.at(i) == 0x0a) {
line++;
character = 0;
} else {
character++;
}
i++;
}
return i;
}
async function runCompiler(
text: string, // this is the script or the snippet of nushell code
flags: string,
settings: NushellIDESettings,
uri: string,
options: { allowErrors?: boolean } = {}
): Promise<string> {
const allowErrors =
options.allowErrors === undefined ? true : options.allowErrors;
try {
fs.writeFileSync(tmpFile.name, text);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
// connection.console.log(e);
}
let stdout = "";
try {
const script_path_flag =
includeFlagForPath(uri) +
"\x1e" + // \x1e is the record separator character (a character that is unlikely to appear in a path)
settings.includeDirs.join("\x1e") +
'"';
const max_errors = settings.maxNumberOfProblems;
if (flags.includes("ide-check")) {
flags = flags + " " + max_errors;
}
connection.console.log(
"running: " +
`${settings.nushellExecutablePath} ${flags} ${script_path_flag} ${tmpFile.name}`
);
const output = await exec(
`${settings.nushellExecutablePath} ${flags} ${script_path_flag} ${tmpFile.name}`,
{
timeout: settings.maxNushellInvocationTime,
}
);
stdout = output.stdout;
console.log("stdout: " + stdout);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
stdout = e.stdout;
if (!allowErrors) {
if (e.signal != null) {
connection.console.log("compile failed: ");
connection.console.log(e);
} else {
connection.console.log("Error:" + e);
}
throw e;
}
}
return stdout;
}
connection.onHover(async (request: HoverParams) => {
return await durationLogWrapper(`onHover`, async () => {
const document = documents.get(request.textDocument.uri);
const settings = await getDocumentSettings(request.textDocument.uri);
const text = document?.getText();
if (!(typeof text == "string")) return null;
// connection.console.log("request: ");
// connection.console.log(request.textDocument.uri);
// connection.console.log("index: " + convertPosition(request.position, text));
const stdout = await runCompiler(
text,
"--ide-hover " + convertPosition(request.position, text),
settings,
request.textDocument.uri
);
const lines = stdout.split("\n").filter((l) => l.length > 0);
for (const line of lines) {
const obj = JSON.parse(line);
// connection.console.log("hovering");
// connection.console.log(obj);
// FIXME: Figure out how to import `vscode` package in server.ts without
// getting runtime import errors to remove this deprecation warning.
const contents = {
value: obj.hover,
language: "nushell",
};
if (obj.hover != "") {
if (obj.span) {
const lineBreaks = findLineBreaks(
obj.file
? (await fs.promises.readFile(obj.file)).toString()
: document?.getText() ?? ""
);
return {
contents,
range: {
start: convertSpan(obj.span.start, lineBreaks),
end: convertSpan(obj.span.end, lineBreaks),
},
};
} else {
return { contents };
}
}
}
});
});
// This handler provides the initial list of the completion items.
connection.onCompletion(
async (request: TextDocumentPositionParams): Promise<CompletionItem[]> => {
return await durationLogWrapper(`onCompletion`, async () => {
// The pass parameter contains the position of the text document in
// which code complete got requested. For the example we ignore this
// info and always provide the same completion items.
const document = documents.get(request.textDocument.uri);
const settings = await getDocumentSettings(request.textDocument.uri);
const text = document?.getText();
if (typeof text == "string") {
// connection.console.log("completion request: ");
// connection.console.log(request.textDocument.uri);
const index = convertPosition(request.position, text);
// connection.console.log("index: " + index);
const stdout = await runCompiler(
text,
"--ide-complete " + index,
settings,
request.textDocument.uri
);
// connection.console.log("got: " + stdout);
const lines = stdout.split("\n").filter((l) => l.length > 0);
for (const line of lines) {
const obj = JSON.parse(line);
// connection.console.log("completions");
// connection.console.log(obj);
const output = [];
let index = 1;
for (const completion of obj.completions) {
output.push({
label: completion,
kind: completion.includes("(")
? CompletionItemKind.Function
: CompletionItemKind.Field,
data: index,
});
index++;
}
return output;
}
}
return [];
});
}
);
connection.onDefinition(async (request) => {
return await durationLogWrapper(`onDefinition`, async () => {
const document = documents.get(request.textDocument.uri);
if (!document) return;
const settings = await getDocumentSettings(request.textDocument.uri);
const text = document.getText();
// connection.console.log("request: ");
// connection.console.log(request.textDocument.uri);
// connection.console.log("index: " + convertPosition(request.position, text));
const stdout = await runCompiler(
text,
"--ide-goto-def " + convertPosition(request.position, text),
settings,
request.textDocument.uri
);
return goToDefinition(document, stdout);
});
});
// This handler resolves additional information for the item selected in
// the completion list.
connection.onCompletionResolve((item: CompletionItem): CompletionItem => {
return item;
});
async function goToDefinition(
document: TextDocument,
nushellOutput: string
): Promise<HandlerResult<Definition, void> | undefined> {
const lines = nushellOutput.split("\n").filter((l) => l.length > 0);
for (const line of lines) {
const obj = JSON.parse(line);
// connection.console.log("going to type definition");
// connection.console.log(obj);
if (obj.file === "" || obj.file === "__prelude__") return;
const lineBreaks = findLineBreaks(
obj.file
? (await fs.promises.readFile(obj.file)).toString()
: document.getText() ?? ""
);
let uri = "";
if (obj.file == tmpFile.name) {
uri = document.uri;
} else {
uri = obj.file ? "file://" + obj.file : document.uri;
}
// connection.console.log(uri);
return {
uri: uri,
range: {
start: convertSpan(obj.start, lineBreaks),
end: convertSpan(obj.end, lineBreaks),
},
};
}
}
connection.languages.inlayHint.on((params: InlayHintParams) => {
const document = documents.get(params.textDocument.uri) as NuTextDocument;
return document.nuInlayHints;
});
function findLineBreaks(utf16_text: string): Array<number> {
const utf8_text = new TextEncoder().encode(utf16_text);
const lineBreaks: Array<number> = [];
for (let i = 0; i < utf8_text.length; ++i) {
if (utf8_text[i] == 0x0a) {
lineBreaks.push(i);
}
}
return lineBreaks;
}
// 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();