-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathserver.ts
1366 lines (1254 loc) · 45.4 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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import process from "process";
import * as p from "vscode-languageserver-protocol";
import * as v from "vscode-languageserver";
import * as rpc from "vscode-jsonrpc/node";
import * as path from "path";
import fs from "fs";
// TODO: check DidChangeWatchedFilesNotification.
import {
DidOpenTextDocumentNotification,
DidChangeTextDocumentNotification,
DidCloseTextDocumentNotification,
DidChangeConfigurationNotification,
InitializeParams,
InlayHintParams,
CodeLensParams,
SignatureHelpParams,
} from "vscode-languageserver-protocol";
import * as lookup from "./lookup";
import * as utils from "./utils";
import * as codeActions from "./codeActions";
import * as c from "./constants";
import * as chokidar from "chokidar";
import { assert } from "console";
import { fileURLToPath } from "url";
import { WorkspaceEdit } from "vscode-languageserver";
import { onErrorReported } from "./errorReporter";
import * as ic from "./incrementalCompilation";
import config, { extensionConfiguration } from "./config";
import { projectsFiles } from "./projectFiles";
// This holds client capabilities specific to our extension, and not necessarily
// related to the LS protocol. It's for enabling/disabling features that might
// work in one client, like VSCode, but perhaps not in others, like vim.
export interface extensionClientCapabilities {
supportsMarkdownLinks?: boolean | null;
supportsSnippetSyntax?: boolean | null;
}
let extensionClientCapabilities: extensionClientCapabilities = {};
// Below here is some state that's not important exactly how long it lives.
let hasPromptedAboutBuiltInFormatter = false;
let pullConfigurationPeriodically: NodeJS.Timeout | null = null;
// https://microsoft.github.io/language-server-protocol/specification#initialize
// According to the spec, there could be requests before the 'initialize' request. Link in comment tells how to handle them.
let initialized = false;
let serverSentRequestIdCounter = 0;
// https://microsoft.github.io/language-server-protocol/specification#exit
let shutdownRequestAlreadyReceived = false;
let stupidFileContentCache: Map<string, string> = new Map();
// ^ caching AND states AND distributed system. Why does LSP has to be stupid like this
// This keeps track of code actions extracted from diagnostics.
let codeActionsFromDiagnostics: codeActions.filesCodeActions = {};
// will be properly defined later depending on the mode (stdio/node-rpc)
let send: (msg: p.Message) => void = (_) => {};
let findRescriptBinary = (projectRootPath: p.DocumentUri | null) =>
config.extensionConfiguration.binaryPath == null
? lookup.findFilePathFromProjectRoot(
projectRootPath,
path.join(c.nodeModulesBinDir, c.rescriptBinName)
)
: utils.findBinary(
config.extensionConfiguration.binaryPath,
c.rescriptBinName
);
let createInterfaceRequest = new v.RequestType<
p.TextDocumentIdentifier,
p.TextDocumentIdentifier,
void
>("textDocument/createInterface");
let openCompiledFileRequest = new v.RequestType<
p.TextDocumentIdentifier,
p.TextDocumentIdentifier,
void
>("textDocument/openCompiled");
let getCurrentCompilerDiagnosticsForFile = (
fileUri: string
): p.Diagnostic[] => {
let diagnostics: p.Diagnostic[] | null = null;
projectsFiles.forEach((projectFile, _projectRootPath) => {
if (diagnostics == null && projectFile.filesDiagnostics[fileUri] != null) {
diagnostics = projectFile.filesDiagnostics[fileUri].slice();
}
});
return diagnostics ?? [];
};
let sendUpdatedDiagnostics = () => {
projectsFiles.forEach((projectFile, projectRootPath) => {
let { filesWithDiagnostics } = projectFile;
let compilerLogPath = path.join(projectRootPath, c.compilerLogPartialPath);
let content = fs.readFileSync(compilerLogPath, { encoding: "utf-8" });
let {
done,
result: filesAndErrors,
codeActions,
linesWithParseErrors,
} = utils.parseCompilerLogOutput(content);
if (linesWithParseErrors.length > 0) {
let params: p.ShowMessageParams = {
type: p.MessageType.Warning,
message: `There are more compiler warning/errors that we could not parse. You can help us fix this by opening an [issue on the repository](https://github.com/rescript-lang/rescript-vscode/issues/new?title=Compiler%20log%20parse%20error), pasting the contents of the file [lib/bs/.compiler.log](file://${compilerLogPath}).`,
};
let message: p.NotificationMessage = {
jsonrpc: c.jsonrpcVersion,
method: "window/showMessage",
params: params,
};
send(message);
}
projectFile.filesDiagnostics = filesAndErrors;
codeActionsFromDiagnostics = codeActions;
// diff
Object.keys(filesAndErrors).forEach((file) => {
let params: p.PublishDiagnosticsParams = {
uri: file,
diagnostics: filesAndErrors[file],
};
let notification: p.NotificationMessage = {
jsonrpc: c.jsonrpcVersion,
method: "textDocument/publishDiagnostics",
params: params,
};
send(notification);
filesWithDiagnostics.add(file);
});
if (done) {
// clear old files
filesWithDiagnostics.forEach((file) => {
if (filesAndErrors[file] == null) {
// Doesn't exist in the new diagnostics. Clear this diagnostic
let params: p.PublishDiagnosticsParams = {
uri: file,
diagnostics: [],
};
let notification: p.NotificationMessage = {
jsonrpc: c.jsonrpcVersion,
method: "textDocument/publishDiagnostics",
params: params,
};
send(notification);
filesWithDiagnostics.delete(file);
}
});
}
});
};
let deleteProjectDiagnostics = (projectRootPath: string) => {
let root = projectsFiles.get(projectRootPath);
if (root != null) {
root.filesWithDiagnostics.forEach((file) => {
let params: p.PublishDiagnosticsParams = {
uri: file,
diagnostics: [],
};
let notification: p.NotificationMessage = {
jsonrpc: c.jsonrpcVersion,
method: "textDocument/publishDiagnostics",
params: params,
};
send(notification);
});
projectsFiles.delete(projectRootPath);
if (config.extensionConfiguration.incrementalTypechecking?.enable) {
ic.removeIncrementalFileFolder(projectRootPath);
}
}
};
let sendCompilationFinishedMessage = () => {
let notification: p.NotificationMessage = {
jsonrpc: c.jsonrpcVersion,
method: "rescript/compilationFinished",
};
send(notification);
};
let debug = false;
let syncProjectConfigCache = (rootPath: string) => {
try {
if (debug) console.log("syncing project config cache for " + rootPath);
utils.runAnalysisAfterSanityCheck(rootPath, ["cache-project", rootPath]);
if (debug) console.log("OK - synced project config cache for " + rootPath);
} catch (e) {
if (debug) console.error(e);
}
};
let deleteProjectConfigCache = (rootPath: string) => {
try {
if (debug) console.log("deleting project config cache for " + rootPath);
utils.runAnalysisAfterSanityCheck(rootPath, ["cache-delete", rootPath]);
if (debug) console.log("OK - deleted project config cache for " + rootPath);
} catch (e) {
if (debug) console.error(e);
}
};
let compilerLogsWatcher = chokidar
.watch([], {
awaitWriteFinish: {
stabilityThreshold: 1,
},
})
.on("all", (_e, changedPath) => {
if (changedPath.includes("build.ninja")) {
if (config.extensionConfiguration.cache?.projectConfig?.enable === true) {
let projectRoot = utils.findProjectRootOfFile(changedPath);
if (projectRoot != null) {
syncProjectConfigCache(projectRoot);
}
}
} else {
try {
sendUpdatedDiagnostics();
sendCompilationFinishedMessage();
if (config.extensionConfiguration.inlayHints?.enable === true) {
sendInlayHintsRefresh();
}
if (config.extensionConfiguration.codeLens === true) {
sendCodeLensRefresh();
}
} catch {
console.log("Error while sending updated diagnostics");
}
}
});
let stopWatchingCompilerLog = () => {
// TODO: cleanup of compilerLogs?
compilerLogsWatcher.close();
};
type clientSentBuildAction = {
title: string;
projectRootPath: string;
};
let openedFile = (fileUri: string, fileContent: string) => {
let filePath = fileURLToPath(fileUri);
stupidFileContentCache.set(filePath, fileContent);
let projectRootPath = utils.findProjectRootOfFile(filePath);
if (projectRootPath != null) {
let projectRootState = projectsFiles.get(projectRootPath);
if (projectRootState == null) {
if (config.extensionConfiguration.incrementalTypechecking?.enable) {
ic.recreateIncrementalFileFolder(projectRootPath);
}
const namespaceName =
utils.getNamespaceNameFromConfigFile(projectRootPath);
projectRootState = {
openFiles: new Set(),
filesWithDiagnostics: new Set(),
filesDiagnostics: {},
namespaceName:
namespaceName.kind === "success" ? namespaceName.result : null,
rescriptVersion: utils.findReScriptVersion(projectRootPath),
bsbWatcherByEditor: null,
bscBinaryLocation: utils.findBscExeBinary(projectRootPath),
editorAnalysisLocation: utils.findEditorAnalysisBinary(projectRootPath),
hasPromptedToStartBuild: /(\/|\\)node_modules(\/|\\)/.test(
projectRootPath
)
? "never"
: false,
};
projectsFiles.set(projectRootPath, projectRootState);
compilerLogsWatcher.add(
path.join(projectRootPath, c.compilerLogPartialPath)
);
if (config.extensionConfiguration.cache?.projectConfig?.enable === true) {
compilerLogsWatcher.add(
path.join(projectRootPath, c.buildNinjaPartialPath)
);
syncProjectConfigCache(projectRootPath);
}
}
let root = projectsFiles.get(projectRootPath)!;
root.openFiles.add(filePath);
// check if .bsb.lock is still there. If not, start a bsb -w ourselves
// because otherwise the diagnostics info we'll display might be stale
let bsbLockPath = path.join(projectRootPath, c.bsbLock);
if (
projectRootState.hasPromptedToStartBuild === false &&
config.extensionConfiguration.askToStartBuild === true &&
!fs.existsSync(bsbLockPath)
) {
// TODO: sometime stale .bsb.lock dangling. bsb -w knows .bsb.lock is
// stale. Use that logic
// TODO: close watcher when lang-server shuts down
if (findRescriptBinary(projectRootPath) != null) {
let payload: clientSentBuildAction = {
title: c.startBuildAction,
projectRootPath: projectRootPath,
};
let params = {
type: p.MessageType.Info,
message: `Start a build for this project to get the freshest data?`,
actions: [payload],
};
let request: p.RequestMessage = {
jsonrpc: c.jsonrpcVersion,
id: serverSentRequestIdCounter++,
method: "window/showMessageRequest",
params: params,
};
send(request);
projectRootState.hasPromptedToStartBuild = true;
// the client might send us back the "start build" action, which we'll
// handle in the isResponseMessage check in the message handling way
// below
} else {
let request: p.NotificationMessage = {
jsonrpc: c.jsonrpcVersion,
method: "window/showMessage",
params: {
type: p.MessageType.Error,
message:
config.extensionConfiguration.binaryPath == null
? `Can't find ReScript binary in ${path.join(
projectRootPath,
c.nodeModulesBinDir
)} or parent directories. Did you install it? It's required to use "rescript" > 9.1`
: `Can't find ReScript binary in the directory ${config.extensionConfiguration.binaryPath}`,
},
};
send(request);
}
}
// no need to call sendUpdatedDiagnostics() here; the watcher add will
// call the listener which calls it
}
};
let closedFile = (fileUri: string) => {
let filePath = fileURLToPath(fileUri);
if (config.extensionConfiguration.incrementalTypechecking?.enable) {
ic.handleClosedFile(filePath);
}
stupidFileContentCache.delete(filePath);
let projectRootPath = utils.findProjectRootOfFile(filePath);
if (projectRootPath != null) {
let root = projectsFiles.get(projectRootPath);
if (root != null) {
root.openFiles.delete(filePath);
// clear diagnostics too if no open files open in said project
if (root.openFiles.size === 0) {
compilerLogsWatcher.unwatch(
path.join(projectRootPath, c.compilerLogPartialPath)
);
compilerLogsWatcher.unwatch(
path.join(projectRootPath, c.buildNinjaPartialPath)
);
deleteProjectConfigCache(projectRootPath);
deleteProjectDiagnostics(projectRootPath);
if (root.bsbWatcherByEditor !== null) {
root.bsbWatcherByEditor.kill();
root.bsbWatcherByEditor = null;
}
}
}
}
};
let updateOpenedFile = (fileUri: string, fileContent: string) => {
let filePath = fileURLToPath(fileUri);
assert(stupidFileContentCache.has(filePath));
stupidFileContentCache.set(filePath, fileContent);
if (config.extensionConfiguration.incrementalTypechecking?.enable) {
ic.handleUpdateOpenedFile(filePath, fileContent, send, () => {
if (config.extensionConfiguration.codeLens) {
sendCodeLensRefresh();
}
if (config.extensionConfiguration.inlayHints) {
sendInlayHintsRefresh();
}
});
}
};
let getOpenedFileContent = (fileUri: string) => {
let filePath = fileURLToPath(fileUri);
let content = stupidFileContentCache.get(filePath)!;
assert(content != null);
return content;
};
export default function listen(useStdio = false) {
// Start listening now!
// We support two modes: the regular node RPC mode for VSCode, and the --stdio
// mode for other editors The latter is _technically unsupported_. It's an
// implementation detail that might change at any time
if (useStdio) {
let writer = new rpc.StreamMessageWriter(process.stdout);
let reader = new rpc.StreamMessageReader(process.stdin);
// proper `this` scope for writer
send = (msg: p.Message) => writer.write(msg);
reader.listen(onMessage);
} else {
// proper `this` scope for process
send = (msg: p.Message) => process.send!(msg);
process.on("message", onMessage);
}
}
function hover(msg: p.RequestMessage) {
let params = msg.params as p.HoverParams;
let filePath = fileURLToPath(params.textDocument.uri);
let code = getOpenedFileContent(params.textDocument.uri);
let tmpname = utils.createFileInTempDir();
fs.writeFileSync(tmpname, code, { encoding: "utf-8" });
let response = utils.runAnalysisCommand(
filePath,
[
"hover",
filePath,
params.position.line,
params.position.character,
tmpname,
Boolean(extensionClientCapabilities.supportsMarkdownLinks),
],
msg
);
fs.unlink(tmpname, () => null);
return response;
}
function inlayHint(msg: p.RequestMessage) {
const params = msg.params as p.InlayHintParams;
const filePath = fileURLToPath(params.textDocument.uri);
const response = utils.runAnalysisCommand(
filePath,
[
"inlayHint",
filePath,
params.range.start.line,
params.range.end.line,
config.extensionConfiguration.inlayHints?.maxLength,
],
msg
);
return response;
}
function sendInlayHintsRefresh() {
let request: p.RequestMessage = {
jsonrpc: c.jsonrpcVersion,
method: p.InlayHintRefreshRequest.method,
id: serverSentRequestIdCounter++,
};
send(request);
}
function codeLens(msg: p.RequestMessage) {
const params = msg.params as p.CodeLensParams;
const filePath = fileURLToPath(params.textDocument.uri);
const response = utils.runAnalysisCommand(
filePath,
["codeLens", filePath],
msg
);
return response;
}
function sendCodeLensRefresh() {
let request: p.RequestMessage = {
jsonrpc: c.jsonrpcVersion,
method: p.CodeLensRefreshRequest.method,
id: serverSentRequestIdCounter++,
};
send(request);
}
function signatureHelp(msg: p.RequestMessage) {
let params = msg.params as p.SignatureHelpParams;
let filePath = fileURLToPath(params.textDocument.uri);
let code = getOpenedFileContent(params.textDocument.uri);
let tmpname = utils.createFileInTempDir();
fs.writeFileSync(tmpname, code, { encoding: "utf-8" });
let response = utils.runAnalysisCommand(
filePath,
[
"signatureHelp",
filePath,
params.position.line,
params.position.character,
tmpname,
config.extensionConfiguration.signatureHelp?.forConstructorPayloads
? "true"
: "false",
],
msg
);
fs.unlink(tmpname, () => null);
return response;
}
function definition(msg: p.RequestMessage) {
// https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_definition
let params = msg.params as p.DefinitionParams;
let filePath = fileURLToPath(params.textDocument.uri);
let response = utils.runAnalysisCommand(
filePath,
["definition", filePath, params.position.line, params.position.character],
msg
);
return response;
}
function typeDefinition(msg: p.RequestMessage) {
// https://microsoft.github.io/language-server-protocol/specification/specification-current/#textDocument_typeDefinition
let params = msg.params as p.TypeDefinitionParams;
let filePath = fileURLToPath(params.textDocument.uri);
let response = utils.runAnalysisCommand(
filePath,
[
"typeDefinition",
filePath,
params.position.line,
params.position.character,
],
msg
);
return response;
}
function references(msg: p.RequestMessage) {
// https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_references
let params = msg.params as p.ReferenceParams;
let filePath = fileURLToPath(params.textDocument.uri);
let result: typeof p.ReferencesRequest.type = utils.getReferencesForPosition(
filePath,
params.position
);
let response: p.ResponseMessage = {
jsonrpc: c.jsonrpcVersion,
id: msg.id,
result,
// error: code and message set in case an exception happens during the definition request.
};
return response;
}
function prepareRename(msg: p.RequestMessage): p.ResponseMessage {
// https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_prepareRename
let params = msg.params as p.PrepareRenameParams;
let filePath = fileURLToPath(params.textDocument.uri);
let locations: null | p.Location[] = utils.getReferencesForPosition(
filePath,
params.position
);
let result: p.Range | null = null;
if (locations !== null) {
locations.forEach((loc) => {
if (
path.normalize(fileURLToPath(loc.uri)) ===
path.normalize(fileURLToPath(params.textDocument.uri))
) {
let { start, end } = loc.range;
let pos = params.position;
if (
start.character <= pos.character &&
start.line <= pos.line &&
end.character >= pos.character &&
end.line >= pos.line
) {
result = loc.range;
}
}
});
}
return {
jsonrpc: c.jsonrpcVersion,
id: msg.id,
result,
};
}
function rename(msg: p.RequestMessage) {
// https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_rename
let params = msg.params as p.RenameParams;
let filePath = fileURLToPath(params.textDocument.uri);
let documentChanges: (p.RenameFile | p.TextDocumentEdit)[] | null =
utils.runAnalysisAfterSanityCheck(filePath, [
"rename",
filePath,
params.position.line,
params.position.character,
params.newName,
]);
let result: WorkspaceEdit | null = null;
if (documentChanges !== null) {
result = { documentChanges };
}
let response: p.ResponseMessage = {
jsonrpc: c.jsonrpcVersion,
id: msg.id,
result,
};
return response;
}
function documentSymbol(msg: p.RequestMessage) {
// https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_documentSymbol
let params = msg.params as p.DocumentSymbolParams;
let filePath = fileURLToPath(params.textDocument.uri);
let extension = path.extname(params.textDocument.uri);
let code = getOpenedFileContent(params.textDocument.uri);
let tmpname = utils.createFileInTempDir(extension);
fs.writeFileSync(tmpname, code, { encoding: "utf-8" });
let response = utils.runAnalysisCommand(
filePath,
["documentSymbol", tmpname],
msg,
/* projectRequired */ false
);
fs.unlink(tmpname, () => null);
return response;
}
function askForAllCurrentConfiguration() {
// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#workspace_configuration
let params: p.ConfigurationParams = {
items: [
{
section: "rescript.settings",
},
],
};
let req: p.RequestMessage = {
jsonrpc: c.jsonrpcVersion,
id: c.configurationRequestId,
method: p.ConfigurationRequest.type.method,
params,
};
send(req);
}
function semanticTokens(msg: p.RequestMessage) {
// https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_semanticTokens
let params = msg.params as p.SemanticTokensParams;
let filePath = fileURLToPath(params.textDocument.uri);
let extension = path.extname(params.textDocument.uri);
let code = getOpenedFileContent(params.textDocument.uri);
let tmpname = utils.createFileInTempDir(extension);
fs.writeFileSync(tmpname, code, { encoding: "utf-8" });
let response = utils.runAnalysisCommand(
filePath,
["semanticTokens", tmpname],
msg,
/* projectRequired */ false
);
fs.unlink(tmpname, () => null);
return response;
}
function completion(msg: p.RequestMessage) {
// https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion
let params = msg.params as p.ReferenceParams;
let filePath = fileURLToPath(params.textDocument.uri);
let code = getOpenedFileContent(params.textDocument.uri);
let tmpname = utils.createFileInTempDir();
fs.writeFileSync(tmpname, code, { encoding: "utf-8" });
let response = utils.runAnalysisCommand(
filePath,
[
"completion",
filePath,
params.position.line,
params.position.character,
tmpname,
],
msg
);
fs.unlink(tmpname, () => null);
return response;
}
function completionResolve(msg: p.RequestMessage) {
const item = msg.params as p.CompletionItem;
let response: p.ResponseMessage = {
jsonrpc: c.jsonrpcVersion,
id: msg.id,
result: item,
};
if (item.documentation == null && item.data != null) {
const data = item.data as { filePath: string; modulePath: string };
let result = utils.runAnalysisAfterSanityCheck(
data.filePath,
["completionResolve", data.filePath, data.modulePath],
true
);
item.documentation = { kind: "markdown", value: result };
}
return response;
}
function codeAction(msg: p.RequestMessage): p.ResponseMessage {
let params = msg.params as p.CodeActionParams;
let filePath = fileURLToPath(params.textDocument.uri);
let code = getOpenedFileContent(params.textDocument.uri);
let extension = path.extname(params.textDocument.uri);
let tmpname = utils.createFileInTempDir(extension);
// Check local code actions coming from the diagnostics, or from incremental compilation.
let localResults: v.CodeAction[] = [];
const fromDiagnostics =
codeActionsFromDiagnostics[params.textDocument.uri] ?? [];
const fromIncrementalCompilation =
ic.getCodeActionsFromIncrementalCompilation(filePath) ?? [];
[...fromDiagnostics, ...fromIncrementalCompilation].forEach(
({ range, codeAction }) => {
if (utils.rangeContainsRange(range, params.range)) {
localResults.push(codeAction);
}
}
);
fs.writeFileSync(tmpname, code, { encoding: "utf-8" });
let response = utils.runAnalysisCommand(
filePath,
[
"codeAction",
filePath,
params.range.start.line,
params.range.start.character,
params.range.end.line,
params.range.end.character,
tmpname,
],
msg
);
fs.unlink(tmpname, () => null);
let { result } = response;
// We must send `null` when there are no results, empty array isn't enough.
let codeActions =
result != null && Array.isArray(result)
? [...localResults, ...result]
: localResults;
let res: v.ResponseMessage = {
jsonrpc: c.jsonrpcVersion,
id: msg.id,
result: codeActions.length > 0 ? codeActions : null,
};
return res;
}
function format(msg: p.RequestMessage): Array<p.Message> {
// technically, a formatting failure should reply with the error. Sadly
// the LSP alert box for these error replies sucks (e.g. doesn't actually
// display the message). In order to signal the client to display a proper
// alert box (sometime with actionable buttons), we need to first send
// back a fake success message (because each request mandates a
// response), then right away send a server notification to display a
// nicer alert. Ugh.
let fakeSuccessResponse: p.ResponseMessage = {
jsonrpc: c.jsonrpcVersion,
id: msg.id,
result: [],
};
let params = msg.params as p.DocumentFormattingParams;
let filePath = fileURLToPath(params.textDocument.uri);
let extension = path.extname(params.textDocument.uri);
if (extension !== c.resExt && extension !== c.resiExt) {
let params: p.ShowMessageParams = {
type: p.MessageType.Error,
message: `Not a ${c.resExt} or ${c.resiExt} file. Cannot format it.`,
};
let response: p.NotificationMessage = {
jsonrpc: c.jsonrpcVersion,
method: "window/showMessage",
params: params,
};
return [fakeSuccessResponse, response];
} else {
// code will always be defined here, even though technically it can be undefined
let code = getOpenedFileContent(params.textDocument.uri);
let projectRootPath = utils.findProjectRootOfFile(filePath);
let project =
projectRootPath != null ? projectsFiles.get(projectRootPath) : null;
let bscExeBinaryPath = project?.bscBinaryLocation ?? null;
let formattedResult = utils.formatCode(
bscExeBinaryPath,
filePath,
code,
Boolean(config.extensionConfiguration.allowBuiltInFormatter)
);
if (formattedResult.kind === "success") {
let max = code.length;
let result: p.TextEdit[] = [
{
range: {
start: { line: 0, character: 0 },
end: { line: max, character: max },
},
newText: formattedResult.result,
},
];
let response: p.ResponseMessage = {
jsonrpc: c.jsonrpcVersion,
id: msg.id,
result: result,
};
return [response];
} else if (formattedResult.kind === "blocked-using-built-in-formatter") {
// Let's only prompt the user once about this, or things might become annoying.
if (hasPromptedAboutBuiltInFormatter) {
return [fakeSuccessResponse];
}
hasPromptedAboutBuiltInFormatter = true;
let params: p.ShowMessageParams = {
type: p.MessageType.Warning,
message: `Formatting not applied! Could not find the ReScript compiler in the current project, and you haven't configured the extension to allow formatting using the built in formatter. To allow formatting files not strictly part of a ReScript project using the built in formatter, [please configure the extension to allow that.](command:workbench.action.openSettings?${encodeURIComponent(
JSON.stringify(["rescript.settings.allowBuiltInFormatter"])
)})`,
};
let response: p.NotificationMessage = {
jsonrpc: c.jsonrpcVersion,
method: "window/showMessage",
params: params,
};
return [fakeSuccessResponse, response];
} else {
// let the diagnostics logic display the updated syntax errors,
// from the build.
// Again, not sending the actual errors. See fakeSuccessResponse
// above for explanation
return [fakeSuccessResponse];
}
}
}
let updateDiagnosticSyntax = (fileUri: string, fileContent: string) => {
if (config.extensionConfiguration.incrementalTypechecking?.enable) {
// The incremental typechecking already sends syntax diagnostics.
return;
}
let filePath = fileURLToPath(fileUri);
let extension = path.extname(filePath);
let tmpname = utils.createFileInTempDir(extension);
fs.writeFileSync(tmpname, fileContent, { encoding: "utf-8" });
// We need to account for any existing diagnostics from the compiler for this
// file. If we don't we might accidentally clear the current file's compiler
// diagnostics if there's no syntax diagostics to send. This is because
// publishing an empty diagnostics array is equivalent to saying "clear all
// errors".
let compilerDiagnosticsForFile =
getCurrentCompilerDiagnosticsForFile(fileUri);
let syntaxDiagnosticsForFile: p.Diagnostic[] =
utils.runAnalysisAfterSanityCheck(filePath, ["diagnosticSyntax", tmpname]);
let notification: p.NotificationMessage = {
jsonrpc: c.jsonrpcVersion,
method: "textDocument/publishDiagnostics",
params: {
uri: fileUri,
diagnostics: [...syntaxDiagnosticsForFile, ...compilerDiagnosticsForFile],
},
};
fs.unlink(tmpname, () => null);
send(notification);
};
function createInterface(msg: p.RequestMessage): p.Message {
let params = msg.params as p.TextDocumentIdentifier;
let extension = path.extname(params.uri);
let filePath = fileURLToPath(params.uri);
let projDir = utils.findProjectRootOfFile(filePath);
if (projDir === null) {
let params: p.ShowMessageParams = {
type: p.MessageType.Error,
message: `Cannot locate project directory to generate the interface file.`,
};
let response: p.NotificationMessage = {
jsonrpc: c.jsonrpcVersion,
method: "window/showMessage",
params: params,
};
return response;
}
if (extension !== c.resExt) {
let params: p.ShowMessageParams = {
type: p.MessageType.Error,
message: `Not a ${c.resExt} file. Cannot create an interface for it.`,
};
let response: p.NotificationMessage = {
jsonrpc: c.jsonrpcVersion,
method: "window/showMessage",
params: params,
};
return response;
}
let resPartialPath = filePath.split(projDir)[1];
// The .cmi filename may have a namespace suffix appended.
let namespaceResult = utils.getNamespaceNameFromConfigFile(projDir);
if (namespaceResult.kind === "error") {
let params: p.ShowMessageParams = {
type: p.MessageType.Error,
message: `Error reading ReScript config file.`,
};
let response: p.NotificationMessage = {
jsonrpc: c.jsonrpcVersion,
method: "window/showMessage",
params,
};
return response;
}
let namespace = namespaceResult.result;
let suffixToAppend = namespace.length > 0 ? "-" + namespace : "";
let cmiPartialPath = path.join(
path.dirname(resPartialPath),
path.basename(resPartialPath, c.resExt) + suffixToAppend + c.cmiExt
);
let cmiPath = path.join(projDir, c.compilerDirPartialPath, cmiPartialPath);
let cmiAvailable = fs.existsSync(cmiPath);
if (!cmiAvailable) {
let params: p.ShowMessageParams = {
type: p.MessageType.Error,
message: `No compiled interface file found. Please compile your project first.`,
};
let response: p.NotificationMessage = {
jsonrpc: c.jsonrpcVersion,
method: "window/showMessage",
params,
};
return response;
}
let response = utils.runAnalysisCommand(
filePath,
["createInterface", filePath, cmiPath],
msg
);
let result = typeof response.result === "string" ? response.result : "";
try {
let resiPath = lookup.replaceFileExtension(filePath, c.resiExt);
fs.writeFileSync(resiPath, result, { encoding: "utf-8" });
let response: p.ResponseMessage = {
jsonrpc: c.jsonrpcVersion,
id: msg.id,
result: {
uri: utils.pathToURI(resiPath),
},
};
return response;
} catch (e) {
let response: p.ResponseMessage = {
jsonrpc: c.jsonrpcVersion,
id: msg.id,
error: {
code: p.ErrorCodes.InternalError,