Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
347 lines (298 loc) · 11.2 KB
/
Copy pathserver.js
File metadata and controls
347 lines (298 loc) · 11.2 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
345
346
347
#!/usr/bin/env node
'use strict';
// ErgoScript Language Server.
//
// Speaks LSP 3.17 over stdio with no third-party dependencies, so it runs from
// a bare Node install: node server.js --stdio
const { TextDocument } = require('./src/document');
const features = require('./src/features');
const { DEFAULT_SETTINGS } = require('./src/analyzer');
const PROTOCOL_ERROR = {
ParseError: -32700,
InvalidRequest: -32600,
MethodNotFound: -32601,
InvalidParams: -32602,
InternalError: -32603,
RequestCancelled: -32800,
};
class Connection {
constructor(input, output) {
this.input = input;
this.output = output;
this.buffer = Buffer.alloc(0);
this.handlers = new Map();
this.notificationHandlers = new Map();
this.shuttingDown = false;
this.nextId = 1;
this.pending = new Map();
}
onRequest(method, handler) { this.handlers.set(method, handler); }
onNotification(method, handler) { this.notificationHandlers.set(method, handler); }
listen() {
this.input.on('data', (chunk) => {
this.buffer = Buffer.concat([this.buffer, chunk]);
this.drain();
});
this.input.on('close', () => process.exit(this.shuttingDown ? 0 : 1));
}
drain() {
for (;;) {
const headerEnd = this.buffer.indexOf('\r\n\r\n');
if (headerEnd < 0) return;
const header = this.buffer.slice(0, headerEnd).toString('ascii');
const match = /Content-Length:\s*(\d+)/i.exec(header);
if (!match) {
// Unrecoverable framing error: drop the header and resynchronise.
this.buffer = this.buffer.slice(headerEnd + 4);
continue;
}
const length = parseInt(match[1], 10);
const bodyStart = headerEnd + 4;
if (this.buffer.length < bodyStart + length) return;
const body = this.buffer.slice(bodyStart, bodyStart + length).toString('utf8');
this.buffer = this.buffer.slice(bodyStart + length);
let message;
try {
message = JSON.parse(body);
} catch (e) {
this.sendError(null, PROTOCOL_ERROR.ParseError, `Invalid JSON: ${e.message}`);
continue;
}
this.dispatch(message);
}
}
dispatch(message) {
if (message.id !== undefined && message.method === undefined) {
const entry = this.pending.get(message.id);
if (entry) {
this.pending.delete(message.id);
if (message.error) entry.reject(message.error); else entry.resolve(message.result);
}
return;
}
if (message.id === undefined) {
const handler = this.notificationHandlers.get(message.method);
if (handler) {
try {
handler(message.params || {});
} catch (e) {
this.log(`Error handling ${message.method}: ${e.stack || e.message}`);
}
}
return;
}
const handler = this.handlers.get(message.method);
if (!handler) {
this.sendError(message.id, PROTOCOL_ERROR.MethodNotFound, `Unhandled method ${message.method}`);
return;
}
Promise.resolve()
.then(() => handler(message.params || {}))
.then((result) => this.send({ jsonrpc: '2.0', id: message.id, result: result === undefined ? null : result }))
.catch((e) => {
this.log(`Error handling ${message.method}: ${e.stack || e.message}`);
this.sendError(message.id, PROTOCOL_ERROR.InternalError, e.message || String(e));
});
}
send(message) {
const json = JSON.stringify(message);
const payload = Buffer.from(json, 'utf8');
this.output.write(`Content-Length: ${payload.length}\r\n\r\n`);
this.output.write(payload);
}
sendError(id, code, message) {
this.send({ jsonrpc: '2.0', id, error: { code, message } });
}
notify(method, params) {
this.send({ jsonrpc: '2.0', method, params });
}
request(method, params) {
const id = this.nextId++;
return new Promise((resolve, reject) => {
this.pending.set(id, { resolve, reject });
this.send({ jsonrpc: '2.0', id, method, params });
});
}
log(message) {
this.notify('window/logMessage', { type: 3, message: `[ergoscript-lsp] ${message}` });
}
}
// ---------------------------------------------------------------------------
const documents = new Map();
let settings = Object.assign({}, DEFAULT_SETTINGS);
let clientSupportsConfiguration = false;
const connection = new Connection(process.stdin, process.stdout);
function getDoc(params) {
const uri = params.textDocument.uri;
const doc = documents.get(uri);
if (!doc) throw new Error(`Document not open: ${uri}`);
return doc;
}
function analysisOf(doc) {
return doc.analysis(settings);
}
function publishDiagnostics(doc) {
try {
const analysis = analysisOf(doc);
connection.notify('textDocument/publishDiagnostics', {
uri: doc.uri,
version: doc.version,
diagnostics: features.diagnostics(doc, analysis),
});
} catch (e) {
connection.log(`Analysis failed for ${doc.uri}: ${e.stack || e.message}`);
connection.notify('textDocument/publishDiagnostics', { uri: doc.uri, diagnostics: [] });
}
}
function revalidateAll() {
for (const doc of documents.values()) publishDiagnostics(doc);
}
connection.onRequest('initialize', (params) => {
const caps = (params.capabilities || {}).workspace || {};
clientSupportsConfiguration = !!caps.configuration;
applySettings((params.initializationOptions || {}).settings);
return {
capabilities: {
textDocumentSync: { openClose: true, change: 1, save: { includeText: false } },
// `(`, `,` and `{` are here only so that a suggestion shaped like the
// expected parameter can appear without pressing Ctrl+Space. Triggered by
// one of those, completion returns *only* those shape suggestions, so the
// popup opens where there is something worth showing and stays shut
// otherwise — a brace anywhere else in a contract yields nothing.
completionProvider: {
triggerCharacters: ['.', '[', '(', ',', '{'],
resolveProvider: false,
},
hoverProvider: true,
signatureHelpProvider: { triggerCharacters: ['(', ','], retriggerCharacters: [','] },
definitionProvider: true,
referencesProvider: true,
documentHighlightProvider: true,
documentSymbolProvider: true,
renameProvider: true,
foldingRangeProvider: true,
inlayHintProvider: true,
codeActionProvider: { codeActionKinds: ['quickfix'] },
semanticTokensProvider: {
legend: {
tokenTypes: features.SEMANTIC_TOKEN_TYPES,
tokenModifiers: features.SEMANTIC_TOKEN_MODIFIERS,
},
full: true,
range: false,
},
},
serverInfo: { name: 'ErgoScript Language Server', version: '1.0.0' },
};
});
connection.onNotification('initialized', async () => {
if (clientSupportsConfiguration) {
try {
const result = await connection.request('workspace/configuration', {
items: [{ section: 'ergoscript' }],
});
if (result && result[0]) { applySettings(result[0]); revalidateAll(); }
} catch (e) {
// The client may not answer; the defaults are fine.
}
}
});
function applySettings(incoming) {
if (!incoming || typeof incoming !== 'object') return;
const next = Object.assign({}, DEFAULT_SETTINGS);
for (const key of Object.keys(DEFAULT_SETTINGS)) {
if (incoming[key] !== undefined && incoming[key] !== null) next[key] = incoming[key];
}
settings = next;
}
connection.onNotification('workspace/didChangeConfiguration', (params) => {
const incoming = (params.settings || {}).ergoscript || params.settings;
applySettings(incoming);
revalidateAll();
});
connection.onRequest('shutdown', () => {
connection.shuttingDown = true;
return null;
});
connection.onNotification('exit', () => process.exit(connection.shuttingDown ? 0 : 1));
// -- Document lifecycle -----------------------------------------------------
connection.onNotification('textDocument/didOpen', (params) => {
const { uri, languageId, version, text } = params.textDocument;
documents.set(uri, new TextDocument(uri, languageId, version, text));
publishDiagnostics(documents.get(uri));
});
connection.onNotification('textDocument/didChange', (params) => {
const doc = documents.get(params.textDocument.uri);
if (!doc) return;
// Full sync: the last content change carries the whole document.
const changes = params.contentChanges || [];
if (changes.length) doc.setText(changes[changes.length - 1].text);
doc.version = params.textDocument.version;
publishDiagnostics(doc);
});
connection.onNotification('textDocument/didSave', (params) => {
const doc = documents.get(params.textDocument.uri);
if (doc) publishDiagnostics(doc);
});
connection.onNotification('textDocument/didClose', (params) => {
documents.delete(params.textDocument.uri);
connection.notify('textDocument/publishDiagnostics', { uri: params.textDocument.uri, diagnostics: [] });
});
// -- Language features ------------------------------------------------------
connection.onRequest('textDocument/completion', (params) => {
const doc = getDoc(params);
return features.completion(doc, analysisOf(doc), params.position, params.context);
});
connection.onRequest('textDocument/hover', (params) => {
const doc = getDoc(params);
return features.hover(doc, analysisOf(doc), params.position);
});
connection.onRequest('textDocument/signatureHelp', (params) => {
const doc = getDoc(params);
return features.signatureHelp(doc, analysisOf(doc), params.position);
});
connection.onRequest('textDocument/definition', (params) => {
const doc = getDoc(params);
return features.definition(doc, analysisOf(doc), params.position);
});
connection.onRequest('textDocument/references', (params) => {
const doc = getDoc(params);
const include = params.context ? params.context.includeDeclaration : true;
return features.references(doc, analysisOf(doc), params.position, include);
});
connection.onRequest('textDocument/documentHighlight', (params) => {
const doc = getDoc(params);
return features.documentHighlight(doc, analysisOf(doc), params.position);
});
connection.onRequest('textDocument/documentSymbol', (params) => {
const doc = getDoc(params);
return features.documentSymbols(doc, analysisOf(doc));
});
connection.onRequest('textDocument/rename', (params) => {
const doc = getDoc(params);
return features.rename(doc, analysisOf(doc), params.position, params.newName);
});
connection.onRequest('textDocument/foldingRange', (params) => {
const doc = getDoc(params);
return features.foldingRanges(doc);
});
connection.onRequest('textDocument/inlayHint', (params) => {
const doc = getDoc(params);
return features.inlayHints(doc, analysisOf(doc), params.range);
});
connection.onRequest('textDocument/semanticTokens/full', (params) => {
const doc = getDoc(params);
return features.semanticTokens(doc, analysisOf(doc));
});
connection.onRequest('textDocument/codeAction', (params) => {
const doc = getDoc(params);
return features.codeActions(doc, analysisOf(doc), params);
});
// ---------------------------------------------------------------------------
process.on('uncaughtException', (e) => {
try { connection.log(`Uncaught exception: ${e.stack || e.message}`); } catch (_) { /* stdout gone */ }
});
process.on('unhandledRejection', (e) => {
try { connection.log(`Unhandled rejection: ${(e && e.stack) || e}`); } catch (_) { /* stdout gone */ }
});
connection.listen();