-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
288 lines (253 loc) · 8.81 KB
/
Copy pathserver.js
File metadata and controls
288 lines (253 loc) · 8.81 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
#!/usr/bin/env node
// azazel-lsp: a Language Server Protocol server for authoring project.cue.
//
// Speaks LSP over stdio with zero npm dependencies (raw JSON-RPC framing). It
// serves:
// - diagnostics from `cue export -e build`, on open/change/save
// - the two graph cross-checks cue cannot do (a dep naming no module, a module
// missing from export.cue's _modules)
// - completion for #Module fields and their enum values
// - hover for fields and enum values
// - go-to-definition from a deps entry to the module it names
//
// The schema model, symbol index, and feature logic are shared with the VS Code
// extension via ../vscode/*.js so the two never drift. Full design in
// ../DESIGN.md.
//
// Try it without an editor:
// node server/test-client.js
// Wire it into an editor by pointing an LSP client at:
// node /abs/path/to/ide/server/server.js (transport: stdio)
'use strict';
const path = require('path');
const fs = require('fs');
const { findPackageDir, runCue, parseCueErrors } = require('../vscode/cueDiagnostics');
const { loadForPackage } = require('../vscode/schemaModel');
const { buildIndex } = require('../vscode/symbolIndex');
const features = require('../vscode/features');
let cuePath = 'cue';
const docs = new Map(); // fsPath -> current text (open buffers)
// ---- JSON-RPC framing over stdio -----------------------------------------
let buffer = Buffer.alloc(0);
process.stdin.on('data', (chunk) => {
buffer = Buffer.concat([buffer, chunk]);
drain();
});
function drain() {
for (;;) {
const headerEnd = buffer.indexOf('\r\n\r\n');
if (headerEnd === -1) return;
const header = buffer.slice(0, headerEnd).toString('ascii');
const m = header.match(/Content-Length:\s*(\d+)/i);
if (!m) {
buffer = Buffer.alloc(0);
return;
}
const len = Number(m[1]);
const start = headerEnd + 4;
if (buffer.length < start + len) return;
const body = buffer.slice(start, start + len).toString('utf8');
buffer = buffer.slice(start + len);
let msg;
try {
msg = JSON.parse(body);
} catch (_e) {
continue;
}
handle(msg);
}
}
function send(msg) {
const payload = Buffer.from(JSON.stringify(msg), 'utf8');
process.stdout.write(`Content-Length: ${payload.length}\r\n\r\n`);
process.stdout.write(payload);
}
function reply(id, result) {
send({ jsonrpc: '2.0', id, result });
}
function notify(method, params) {
send({ jsonrpc: '2.0', method, params });
}
// ---- URI helpers ----------------------------------------------------------
function uriToPath(uri) {
if (!uri.startsWith('file://')) return uri;
let p = decodeURIComponent(uri.slice('file://'.length));
if (p.startsWith('/') === false) p = '/' + p;
return p;
}
function pathToUri(p) {
const abs = path.resolve(p);
return 'file://' + abs.split(path.sep).map(encodeURIComponent).join('/').replace('file%3A', 'file:');
}
// Text for a path: the open buffer if we have it, else disk.
function textFor(fsPath) {
if (docs.has(fsPath)) return docs.get(fsPath);
try {
return fs.readFileSync(fsPath, 'utf8');
} catch (_e) {
return '';
}
}
// A symbol index for the package, with every open buffer overriding disk.
function indexFor(pkgDir) {
const overrides = {};
for (const [p, t] of docs) overrides[p] = t;
return buildIndex(pkgDir, overrides);
}
// ---- diagnostics ----------------------------------------------------------
async function publishDiagnostics(uri) {
const fsPath = uriToPath(uri);
const pkgDir = findPackageDir(path.dirname(fsPath));
if (!pkgDir) {
notify('textDocument/publishDiagnostics', { uri, diagnostics: [] });
return;
}
const perFile = new Map();
perFile.set(fsPath, []);
const projectPath = path.join(pkgDir, 'project.cue');
perFile.set(projectPath, []); // always refresh cross-checks on project.cue
// cue diagnostics.
const result = await runCue(cuePath, pkgDir);
if (result.spawnError) {
process.stderr.write(`[azazel-lsp] ${result.spawnError}\n`);
} else if (result.code !== 0) {
for (const p of parseCueErrors(result.output, pkgDir)) {
let targetPath = p.absPath;
let line = p.line;
let col = p.col;
if (path.basename(targetPath) === 'schema.cue') {
targetPath = fsPath;
line = 1;
col = 1;
}
const d = {
range: {
start: { line: Math.max(0, line - 1), character: Math.max(0, col - 1) },
end: { line: Math.max(0, line - 1), character: Math.max(0, col) },
},
severity: 1,
source: 'azazel (cue)',
message: p.message,
};
if (!perFile.has(targetPath)) perFile.set(targetPath, []);
perFile.get(targetPath).push(d);
}
}
// The two graph cross-checks, from the symbol index.
for (const c of features.crossCheckDiagnostics(indexFor(pkgDir))) {
perFile.get(projectPath).push({
range: {
start: { line: c.line, character: c.character },
end: { line: c.line, character: c.endCharacter },
},
severity: c.severity === 'warning' ? 2 : 1,
source: 'azazel',
message: c.message,
});
}
for (const [fp, diags] of perFile) {
notify('textDocument/publishDiagnostics', { uri: pathToUri(fp), diagnostics: diags });
}
}
// ---- request routing ------------------------------------------------------
function handle(msg) {
const { id, method, params } = msg;
switch (method) {
case 'initialize':
cuePath =
(params && params.initializationOptions && params.initializationOptions.cuePath) || 'cue';
reply(id, {
capabilities: {
textDocumentSync: 1,
completionProvider: { triggerCharacters: ['"', ':', ' '] },
hoverProvider: true,
definitionProvider: true,
},
serverInfo: { name: 'azazel-lsp', version: '0.2.0' },
});
break;
case 'initialized':
break;
case 'textDocument/didOpen':
if (params && params.textDocument) {
docs.set(uriToPath(params.textDocument.uri), params.textDocument.text || '');
publishDiagnostics(params.textDocument.uri);
}
break;
case 'textDocument/didChange':
if (params && params.textDocument) {
const fsPath = uriToPath(params.textDocument.uri);
const changes = params.contentChanges || [];
if (changes.length) docs.set(fsPath, changes[changes.length - 1].text);
publishDiagnostics(params.textDocument.uri);
}
break;
case 'textDocument/didSave':
if (params && params.textDocument) publishDiagnostics(params.textDocument.uri);
break;
case 'textDocument/didClose':
if (params && params.textDocument) {
docs.delete(uriToPath(params.textDocument.uri));
notify('textDocument/publishDiagnostics', {
uri: params.textDocument.uri,
diagnostics: [],
});
}
break;
case 'textDocument/completion': {
const fsPath = uriToPath(params.textDocument.uri);
const pkgDir = findPackageDir(path.dirname(fsPath));
const schema = pkgDir ? loadForPackage(pkgDir) : null;
const items = features
.completionAt(schema, textFor(fsPath), params.position.line, params.position.character)
.map((c) => ({
label: c.label,
kind: c.kind === 'field' ? 5 : 20, // Field / EnumMember
detail: c.detail,
documentation: c.doc ? { kind: 'markdown', value: c.doc } : undefined,
}));
reply(id, { isIncomplete: false, items });
break;
}
case 'textDocument/hover': {
const fsPath = uriToPath(params.textDocument.uri);
const pkgDir = findPackageDir(path.dirname(fsPath));
const schema = pkgDir ? loadForPackage(pkgDir) : null;
const h = features.hoverAt(schema, textFor(fsPath), params.position.line, params.position.character);
reply(id, h ? { contents: { kind: 'markdown', value: h.markdown } } : null);
break;
}
case 'textDocument/definition': {
const fsPath = uriToPath(params.textDocument.uri);
const pkgDir = findPackageDir(path.dirname(fsPath));
if (!pkgDir) {
reply(id, null);
break;
}
const def = features.definitionAt(indexFor(pkgDir), params.position.line, params.position.character);
if (!def) {
reply(id, null);
break;
}
reply(id, {
uri: pathToUri(path.join(pkgDir, 'project.cue')),
range: {
start: { line: def.line, character: def.character },
end: { line: def.line, character: def.character },
},
});
break;
}
case 'shutdown':
reply(id, null);
break;
case 'exit':
process.exit(0);
break;
default:
if (id !== undefined) {
send({ jsonrpc: '2.0', id, error: { code: -32601, message: `method not found: ${method}` } });
}
}
}
process.stderr.write('[azazel-lsp] started, waiting on stdio\n');