-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathserver.ts
353 lines (338 loc) · 12.9 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
import process, { allowedNodeEnvironmentFlags } from "process";
import * as p from "vscode-languageserver-protocol";
import * as t from "vscode-languageserver-types";
import * as j from "vscode-jsonrpc";
import * as m from "vscode-jsonrpc/lib/messages";
import * as v from "vscode-languageserver";
import * as path from 'path';
import fs from 'fs';
// TODO: check DidChangeWatchedFilesNotification. Check DidChangeTextDocumentNotification. Do they fire on uninitialized files?
import { DidOpenTextDocumentNotification, DidChangeTextDocumentNotification, DidCloseTextDocumentNotification, DidChangeWatchedFilesNotification, CompletionResolveRequest } from 'vscode-languageserver-protocol';
import { uriToFsPath, URI } from 'vscode-uri';
import * as utils from './utils';
import * as c from './constants';
import * as chokidar from 'chokidar'
import { assert } from 'console';
// TODO: what's this?
import { fileURLToPath } from 'url';
// 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;
// https://microsoft.github.io/language-server-protocol/specification#exit
let shutdownRequestAlreadyReceived = false;
let stupidFileContentCache: Map<string, string> = new Map()
/*
Map {
'/foo/lib/bs/.compiler.log': Map {
'/foo/src/A.res': {
trackedContent: 'let a = 1',
hasDiagnostics: false
}
'/foo/src/B.res': {
trackedContent: null,
hasDiagnostics: true
}
},
}
*/
let projectsFiles: Map<
string,
{
openFiles: Set<string>,
filesWithDiagnostics: Set<string>,
}>
= new Map()
// ^ caching AND states AND distributed system. Why does LSP has to be stupid like this
let sendUpdatedDiagnostics = () => {
projectsFiles.forEach(({ filesWithDiagnostics }, compilerLogPath) => {
let content = fs.readFileSync(compilerLogPath, { encoding: 'utf-8' });
console.log("new log content: ", compilerLogPath, content)
let { done, result: filesAndErrors } = utils.parseCompilerLogOutput(content)
// diff
Object.keys(filesAndErrors).forEach(file => {
// send diagnostic
let params: p.PublishDiagnosticsParams = {
uri: file,
diagnostics: filesAndErrors[file],
}
let notification: m.NotificationMessage = {
jsonrpc: c.jsonrpcVersion,
method: 'textDocument/publishDiagnostics',
params: params,
};
process.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: m.NotificationMessage = {
jsonrpc: c.jsonrpcVersion,
method: 'textDocument/publishDiagnostics',
params: params,
};
process.send!(notification);
filesWithDiagnostics.delete(file)
}
})
}
});
}
let deleteProjectDiagnostics = (compilerLogPath: string) => {
let compilerLog = projectsFiles.get(compilerLogPath)
if (compilerLog != null) {
compilerLog.filesWithDiagnostics.forEach(file => {
let params: p.PublishDiagnosticsParams = {
uri: file,
diagnostics: [],
}
let notification: m.NotificationMessage = {
jsonrpc: c.jsonrpcVersion,
method: 'textDocument/publishDiagnostics',
params: params,
};
process.send!(notification);
})
projectsFiles.delete(compilerLogPath)
}
}
let compilerLogsWatcher = chokidar.watch([])
.on('all', (_e, changedPath) => {
console.log('new log change', changedPath, Math.random())
sendUpdatedDiagnostics()
})
let stopWatchingCompilerLog = () => {
// TODO: cleanup of compilerLogs?
compilerLogsWatcher.close()
}
let openedFile = (fileUri: string, fileContent: string) => {
let filePath = uriToFsPath(URI.parse(fileUri), true);
stupidFileContentCache.set(filePath, fileContent)
let compilerLogDir = utils.findDirOfFileNearFile(c.compilerLogPartialPath, filePath)
if (compilerLogDir != null) {
let compilerLogPath = path.join(compilerLogDir, c.compilerLogPartialPath);
if (!projectsFiles.has(compilerLogPath)) {
projectsFiles.set(compilerLogPath, { openFiles: new Set(), filesWithDiagnostics: new Set() })
compilerLogsWatcher.add(compilerLogPath)
}
let compilerLog = projectsFiles.get(compilerLogPath)!
compilerLog.openFiles.add(filePath)
// no need to call sendUpdatedDiagnostics() here; the watcher add will
// call the listener which calls it
}
}
let closedFile = (fileUri: string) => {
let filePath = uriToFsPath(URI.parse(fileUri), true);
stupidFileContentCache.delete(filePath)
let compilerLogDir = utils.findDirOfFileNearFile(c.compilerLogPartialPath, filePath)
if (compilerLogDir != null) {
let compilerLogPath = path.join(compilerLogDir, c.compilerLogPartialPath);
let compilerLog = projectsFiles.get(compilerLogPath)
if (compilerLog != null) {
compilerLog.openFiles.delete(filePath)
// clear diagnostics too if no open files open in said project
if (compilerLog.openFiles.size === 0) {
compilerLogsWatcher.unwatch(compilerLogPath)
deleteProjectDiagnostics(compilerLogPath)
}
}
}
}
let updateOpenedFile = (fileUri: string, fileContent: string) => {
let filePath = uriToFsPath(URI.parse(fileUri), true)
assert(stupidFileContentCache.has(filePath))
stupidFileContentCache.set(filePath, fileContent)
}
let getOpenedFileContent = (fileUri: string) => {
let filePath = uriToFsPath(URI.parse(fileUri), true)
let content = stupidFileContentCache.get(filePath)!
assert(content != null)
return content
}
process.on('message', (a: (m.RequestMessage | m.NotificationMessage)) => {
if ((a as m.RequestMessage).id == null) {
// this is a notification message, aka client sent and forgot
let aa = (a as m.NotificationMessage)
if (!initialized && aa.method !== 'exit') {
// From spec: "Notifications should be dropped, except for the exit notification. This will allow the exit of a server without an initialize request"
// For us: do nothing. We don't have anything we need to clean up right now
// TODO: think of fs watcher
} else if (aa.method === 'exit') {
// The server should exit with success code 0 if the shutdown request has been received before; otherwise with error code 1
if (shutdownRequestAlreadyReceived) {
process.exit(0)
} else {
process.exit(1)
}
} else if (aa.method === DidOpenTextDocumentNotification.method) {
let params = (aa.params as p.DidOpenTextDocumentParams);
let extName = path.extname(params.textDocument.uri)
if (extName === c.resExt || extName === c.resiExt) {
console.log("new file coming", params.textDocument.uri)
openedFile(params.textDocument.uri, params.textDocument.text)
}
} else if (aa.method === DidChangeTextDocumentNotification.method) {
let params = (aa.params as p.DidChangeTextDocumentParams);
let extName = path.extname(params.textDocument.uri)
if (extName === c.resExt || extName === c.resiExt) {
let changes = params.contentChanges
if (changes.length === 0) {
// no change?
} else {
// we currently only support full changes
updateOpenedFile(params.textDocument.uri, changes[changes.length - 1].text)
}
}
} else if (aa.method === DidCloseTextDocumentNotification.method) {
let params = (aa.params as p.DidCloseTextDocumentParams);
closedFile(params.textDocument.uri)
}
} else {
// this is a request message, aka client sent request, waits for our reply
let aa = (a as m.RequestMessage)
if (!initialized && aa.method !== 'initialize') {
let response: m.ResponseMessage = {
jsonrpc: c.jsonrpcVersion,
id: aa.id,
error: {
code: m.ErrorCodes.ServerNotInitialized,
message: "Server not initialized."
}
};
process.send!(response);
} else if (aa.method === 'initialize') {
// startWatchingCompilerLog(process)
// send the list of things we support
let result: p.InitializeResult = {
capabilities: {
// TODO: incremental sync?
textDocumentSync: v.TextDocumentSyncKind.Full,
documentFormattingProvider: true,
}
}
let response: m.ResponseMessage = {
jsonrpc: c.jsonrpcVersion,
id: aa.id,
result: result,
};
initialized = true;
process.send!(response);
} else if (aa.method === 'initialized') {
// sent from client after initialize. Nothing to do for now
let response: m.ResponseMessage = {
jsonrpc: c.jsonrpcVersion,
id: aa.id,
result: null,
};
process.send!(response);
} else if (aa.method === 'shutdown') {
// https://microsoft.github.io/language-server-protocol/specification#shutdown
if (shutdownRequestAlreadyReceived) {
let response: m.ResponseMessage = {
jsonrpc: c.jsonrpcVersion,
id: aa.id,
error: {
code: m.ErrorCodes.InvalidRequest,
message: `Language server already received the shutdown request`
}
};
process.send!(response);
} else {
shutdownRequestAlreadyReceived = true
// TODO: recheck logic around init/shutdown...
stopWatchingCompilerLog()
let response: m.ResponseMessage = {
jsonrpc: c.jsonrpcVersion,
id: aa.id,
result: null,
};
process.send!(response);
}
} else if (aa.method === p.DocumentFormattingRequest.method) {
let params = (aa.params as p.DocumentFormattingParams)
let filePath = uriToFsPath(URI.parse(params.textDocument.uri), true);
let extension = path.extname(params.textDocument.uri);
if (extension !== c.resExt && extension !== c.resiExt) {
let response: m.ResponseMessage = {
jsonrpc: c.jsonrpcVersion,
id: aa.id,
error: {
code: m.ErrorCodes.InvalidRequest,
message: `Not a ${c.resExt} or ${c.resiExt} file.`
}
};
process.send!(response);
} else {
let nodeModulesParentPath = utils.findDirOfFileNearFile(c.bscPartialPath, filePath)
if (nodeModulesParentPath == null) {
let response: m.ResponseMessage = {
jsonrpc: c.jsonrpcVersion,
id: aa.id,
error: {
code: m.ErrorCodes.InvalidRequest,
message: `Cannot find a nearby ${c.bscPartialPath}. It's needed for formatting.`,
}
};
process.send!(response);
} else {
// code will always be defined here, even though technically it can be undefined
let code = getOpenedFileContent(params.textDocument.uri)
let formattedResult = utils.formatUsingValidBscPath(
code,
path.join(nodeModulesParentPath, c.bscPartialPath),
extension === c.resiExt,
);
if (formattedResult.kind === 'success') {
let result: p.TextEdit[] = [{
range: {
start: { line: 0, character: 0 },
end: { line: Number.MAX_VALUE, character: Number.MAX_VALUE }
},
newText: formattedResult.result,
}]
let response: m.ResponseMessage = {
jsonrpc: c.jsonrpcVersion,
id: aa.id,
result: result,
};
process.send!(response);
} else {
let response: m.ResponseMessage = {
jsonrpc: c.jsonrpcVersion,
id: aa.id,
result: [],
// technically a formatting failure should return the error but
// since this is LSP... the idiom seems to be to silently return
// nothing (to avoid an alert window each time on bad formatting)
// while sending a diagnostic about the error afterward. We won't
// send an extra diagnostic because the .compiler.log watcher
// should have reported th won't send an extra diagnostic because
// theiler.log watcher should have reported them.
// error: {
// code: m.ErrorCodes.ParseError,
// message: formattedResult.error,
// }
};
process.send!(response);
}
}
}
} else {
let response: m.ResponseMessage = {
jsonrpc: c.jsonrpcVersion,
id: aa.id,
error: {
code: m.ErrorCodes.InvalidRequest,
message: "Unrecognized editor request."
}
};
process.send!(response);
}
}
})