This repository was archived by the owner on Nov 25, 2025. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathzls.ts
More file actions
582 lines (517 loc) · 22.5 KB
/
zls.ts
File metadata and controls
582 lines (517 loc) · 22.5 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
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
import vscode from "vscode";
import {
ConfigurationParams,
LSPAny,
LanguageClient,
LanguageClientOptions,
ResponseError,
ServerOptions,
} from "vscode-languageclient/node";
import { camelCase, snakeCase } from "lodash-es";
import semver from "semver";
import * as minisign from "./minisign";
import * as versionManager from "./versionManager";
import * as zigUtil from "./zigUtil";
import { zigProvider } from "./zigSetup";
const ZIG_MODE = [
{ language: "zig", scheme: "file" },
{ language: "zig", scheme: "untitled" },
];
let versionManagerConfig: versionManager.Config;
let statusItem: vscode.LanguageStatusItem;
let outputChannel: vscode.LogOutputChannel;
export let client: LanguageClient | null = null;
export async function restartClient(context: vscode.ExtensionContext): Promise<void> {
const result = await getZLSPath(context);
if (!result) {
await stopClient();
updateStatusItem(null);
return;
}
try {
const newClient = await startClient(result.exe, result.version);
void stopClient();
client = newClient;
updateStatusItem(result.version);
} catch (reason) {
if (reason instanceof Error) {
void vscode.window.showWarningMessage(`Failed to run ZLS language server: ${reason.message}`);
} else {
void vscode.window.showWarningMessage("Failed to run ZLS language server");
}
updateStatusItem(null);
}
}
async function startClient(zlsPath: string, zlsVersion: semver.SemVer): Promise<LanguageClient> {
const configuration = vscode.workspace.getConfiguration("zig.zls");
const debugLog = configuration.get<boolean>("debugLog", false);
const args: string[] = [];
if (debugLog) {
/** `--enable-debug-log` has been deprecated in favor of `--log-level`. https://github.com/zigtools/zls/pull/1957 */
const zlsCLIRevampVersion = new semver.SemVer("0.14.0-50+3354fdc");
if (semver.lt(zlsVersion, zlsCLIRevampVersion)) {
args.push("--enable-debug-log");
} else {
args.push("--log-level", "debug");
}
}
const serverOptions: ServerOptions = {
command: zlsPath,
args: args,
};
const clientOptions: LanguageClientOptions = {
documentSelector: ZIG_MODE,
outputChannel,
middleware: {
workspace: {
configuration: configurationMiddleware,
},
},
};
const languageClient = new LanguageClient("zig.zls", "ZLS language server", serverOptions, clientOptions);
await languageClient.start();
// Formatting is handled by `zigFormat.ts`
languageClient.getFeature("textDocument/formatting").clear();
return languageClient;
}
async function stopClient(): Promise<void> {
if (!client) return;
const oldClient = client;
client = null;
// The `stop` call will send the "shutdown" notification to the LSP
await oldClient.stop();
// The `dipose` call will send the "exit" request to the LSP which actually tells the child process to exit
await oldClient.dispose();
}
/** returns the file system path to the zls executable */
async function getZLSPath(context: vscode.ExtensionContext): Promise<{ exe: string; version: semver.SemVer } | null> {
const configuration = vscode.workspace.getConfiguration("zig.zls");
let zlsExePath = configuration.get<string>("path");
let zlsVersion: semver.SemVer | null = null;
if (!!zlsExePath) {
// This will fail on older ZLS version that do not support `zls --version`.
// It should be more likely that the given executable is invalid than someone using ZLS 0.9.0 or older.
const result = zigUtil.resolveExePathAndVersion(zlsExePath, "--version");
if ("message" in result) {
vscode.window
.showErrorMessage(`Unexpected 'zig.zls.path': ${result.message}`, "install ZLS", "open settings")
.then(async (response) => {
switch (response) {
case "install ZLS":
const zlsConfig = vscode.workspace.getConfiguration("zig.zls");
await zigUtil.workspaceConfigUpdateNoThrow(zlsConfig, "enabled", "on", true);
await zigUtil.workspaceConfigUpdateNoThrow(zlsConfig, "path", undefined);
break;
case "open settings":
await vscode.commands.executeCommand("workbench.action.openSettings", "zig.zls.path");
break;
case undefined:
break;
}
});
return null;
}
return result;
}
if (configuration.get<"ask" | "off" | "on">("enabled", "ask") !== "on") return null;
const zigVersion = zigProvider.getZigVersion();
if (!zigVersion) return null;
const result = await fetchVersion(context, zigVersion, true);
if (!result) return null;
try {
zlsExePath = await versionManager.install(versionManagerConfig, result.version);
zlsVersion = result.version;
} catch (err) {
if (err instanceof Error) {
void vscode.window.showErrorMessage(`Failed to install ZLS ${result.version.toString()}: ${err.message}`);
} else {
void vscode.window.showErrorMessage(`Failed to install ZLS ${result.version.toString()}!`);
}
return null;
}
return {
exe: zlsExePath,
version: zlsVersion,
};
}
function configurationMiddleware(params: ConfigurationParams): LSPAny[] | ResponseError {
void validateAdditionalOptions();
return params.items.map((param) => {
if (!param.section) return null;
const scopeUri = param.scopeUri ? client?.protocol2CodeConverter.asUri(param.scopeUri) : undefined;
const configuration = vscode.workspace.getConfiguration("zig", scopeUri);
const workspaceFolder = scopeUri ? vscode.workspace.getWorkspaceFolder(scopeUri) : undefined;
const updateConfigOption = (section: string, value: unknown) => {
if (section === "zls.zigExePath") {
return zigProvider.getZigPath();
}
if (typeof value === "string") {
// Make sure that `""` gets converted to `undefined` and resolve predefined values
value = value ? zigUtil.handleConfigOption(value, workspaceFolder ?? "guess") : undefined;
} else if (typeof value === "object" && value !== null && !Array.isArray(value)) {
// Recursively update the config options
const newValue: Record<string, unknown> = {};
for (const [fieldName, fieldValue] of Object.entries(value)) {
newValue[snakeCase(fieldName)] = updateConfigOption(section + "." + fieldName, fieldValue);
}
return newValue;
}
const inspect = configuration.inspect(section);
const isDefaultValue =
value === inspect?.defaultValue &&
inspect?.globalValue === undefined &&
inspect?.workspaceValue === undefined &&
inspect?.workspaceFolderValue === undefined;
if (isDefaultValue) {
if (section === "zls.semanticTokens") {
// The extension has a different default value for this config
// option compared to ZLS
return value;
} else {
return undefined;
}
}
return value;
};
let additionalOptions = configuration.get<Record<string, unknown>>("zls.additionalOptions", {});
// Remove the `zig.zls.` prefix from the entries in `zig.zls.additionalOptions`
additionalOptions = Object.fromEntries(
Object.entries(additionalOptions)
.filter(([key]) => key.startsWith("zig.zls."))
.map(([key, value]) => [key.slice("zig.zls.".length), value]),
);
switch (configuration.get<"off" | "auto" | "extension" | "zls">("buildOnSaveProvider", "auto")) {
case "auto":
break;
case "zls":
additionalOptions["enableBuildOnSave"] = true;
break;
case "off":
case "extension":
additionalOptions["enableBuildOnSave"] = false;
break;
}
if (param.section === "zls") {
// ZLS has requested all config options.
const options = { ...configuration.get<Record<string, unknown>>(param.section, {}) };
// Some config options are specific to the VS Code
// extension. ZLS should ignore unknown values but
// we remove them here anyway.
delete options["debugLog"]; // zig.zls.debugLog
delete options["trace"]; // zig.zls.trace.server
delete options["enabled"]; // zig.zls.enabled
delete options["path"]; // zig.zls.path
delete options["additionalOptions"]; // zig.zls.additionalOptions
return updateConfigOption(param.section, {
...additionalOptions,
...options,
// eslint-disable-next-line @typescript-eslint/naming-convention
zig_exe_path: zigProvider.getZigPath(),
});
} else if (param.section.startsWith("zls.")) {
// ZLS has requested a specific config option.
// ZLS names it's config options in snake_case but the VS Code extension uses camelCase
const camelCaseSection = param.section
.split(".")
.map((str) => camelCase(str))
.join(".");
return updateConfigOption(
camelCaseSection,
configuration.get(camelCaseSection, additionalOptions[camelCaseSection.slice("zls.".length)]),
);
} else {
// Do not allow ZLS to request other editor config options.
return null;
}
});
}
async function validateAdditionalOptions(): Promise<void> {
const configuration = vscode.workspace.getConfiguration("zig.zls", null);
const additionalOptions = configuration.get<Record<string, unknown>>("additionalOptions", {});
for (const optionName in additionalOptions) {
if (!optionName.startsWith("zig.zls.")) continue;
const section = optionName.slice("zig.zls.".length);
const inspect = configuration.inspect(section);
const doesOptionExist = inspect?.defaultValue !== undefined;
if (!doesOptionExist) continue;
// The extension has defined a config option with the given name but the user still used `additionalOptions`.
const response = await vscode.window.showWarningMessage(
`The config option 'zig.zls.additionalOptions' contains the already existing option '${optionName}'`,
`Use ${optionName} instead`,
"Show zig.zls.additionalOptions",
);
switch (response) {
case `Use ${optionName} instead`:
const { [optionName]: newValue, ...updatedAdditionalOptions } = additionalOptions;
await zigUtil.workspaceConfigUpdateNoThrow(
configuration,
"additionalOptions",
Object.keys(updatedAdditionalOptions).length ? updatedAdditionalOptions : undefined,
true,
);
await zigUtil.workspaceConfigUpdateNoThrow(configuration, section, newValue, true);
break;
case "Show zig.zls.additionalOptions":
await vscode.commands.executeCommand("workbench.action.openSettingsJson", {
revealSetting: { key: "zig.zls.additionalOptions" },
});
break;
case undefined:
return;
}
}
}
/**
* Similar to https://builds.zigtools.org/index.json
*/
interface SelectVersionResponse {
/** The ZLS version */
version: string;
/** `YYYY-MM-DD` */
date: string;
[artifact: string]: ArtifactEntry | string | undefined;
}
interface SelectVersionFailureResponse {
/**
* The `code` **may** be one of `SelectVersionFailureCode`. Be aware that new
* codes can be added over time.
*/
code: number;
/** A simplified explanation of why no ZLS build could be selected */
message: string;
}
interface ArtifactEntry {
/** A download URL */
tarball: string;
/** A SHA256 hash of the tarball */
shasum: string;
/** Size of the tarball in bytes */
size: string;
}
async function fetchVersion(
context: vscode.ExtensionContext,
zigVersion: semver.SemVer,
useCache: boolean,
): Promise<{ version: semver.SemVer; artifact: ArtifactEntry } | null> {
// Should the cache be periodically cleared?
const cacheKey = `zls-select-version-${zigVersion.raw}`;
let response: SelectVersionResponse | SelectVersionFailureResponse | null = null;
try {
const url = new URL("https://releases.zigtools.org/v1/zls/select-version");
url.searchParams.append("zig_version", zigVersion.raw);
url.searchParams.append("compatibility", "only-runtime");
const fetchResponse = await fetch(url);
response = (await fetchResponse.json()) as SelectVersionResponse | SelectVersionFailureResponse;
// Cache the response
if (useCache) {
await context.globalState.update(cacheKey, response);
}
} catch (err) {
// Try to read the result from cache
if (useCache) {
response = context.globalState.get<SelectVersionResponse | SelectVersionFailureResponse>(cacheKey) ?? null;
}
if (!response) {
if (err instanceof Error) {
void vscode.window.showErrorMessage(`Failed to query ZLS version: ${err.message}`);
} else {
throw err;
}
return null;
}
}
if ("message" in response) {
void vscode.window.showErrorMessage(`Unable to fetch ZLS: ${response.message as string}`);
return null;
}
const version = new semver.SemVer(response.version);
const armName = semver.gte(version, "0.15.0") ? "arm" : "armv7a";
const targetName = `${zigUtil.getZigArchName(armName)}-${zigUtil.getZigOSName()}`;
if (!(targetName in response)) {
void vscode.window.showErrorMessage(
`A prebuilt ZLS ${response.version} binary is not available for your system. You can build it yourself with https://github.com/zigtools/zls#from-source`,
);
return null;
}
return {
version: version,
artifact: response[targetName] as ArtifactEntry,
};
}
async function isEnabled(): Promise<boolean> {
const zlsConfig = vscode.workspace.getConfiguration("zig.zls");
if (!!zlsConfig.get<string>("path")) return true;
switch (zlsConfig.get<"ask" | "off" | "on">("enabled", "ask")) {
case "on":
return true;
case "off":
return false;
case "ask": {
const response = await vscode.window.showInformationMessage(
"We recommend enabling the ZLS language server for a better editing experience. Would you like to install it?",
{ modal: true },
"Yes",
"No",
);
switch (response) {
case "Yes":
await zigUtil.workspaceConfigUpdateNoThrow(zlsConfig, "enabled", "on", true);
return true;
case "No":
await zigUtil.workspaceConfigUpdateNoThrow(zlsConfig, "enabled", "off", true);
return false;
case undefined:
return false;
}
}
}
}
function updateStatusItem(version: semver.SemVer | null) {
if (version) {
statusItem.text = `ZLS ${version.toString()}`;
statusItem.detail = "ZLS Version";
statusItem.severity = vscode.LanguageStatusSeverity.Information;
statusItem.command = {
title: "View Output",
command: "zig.zls.openOutput",
};
} else {
statusItem.text = "ZLS not enabled";
statusItem.detail = undefined;
statusItem.severity = vscode.LanguageStatusSeverity.Error;
const zigPath = zigProvider.getZigPath();
const zigVersion = zigProvider.getZigVersion();
if (zigPath !== null && zigVersion !== null) {
statusItem.command = {
title: "Enable",
command: "zig.zls.enable",
};
} else {
statusItem.command = undefined;
}
}
}
export async function activate(context: vscode.ExtensionContext) {
{
// This check can be removed once enough time has passed so that most users switched to the new value
// remove the `zls_install` directory from the global storage
try {
await vscode.workspace.fs.delete(vscode.Uri.joinPath(context.globalStorageUri, "zls_install"), {
recursive: true,
useTrash: false,
});
} catch {}
// convert a `zig.zls.path` that points to the global storage to `zig.zls.enabled == "on"`
const zlsConfig = vscode.workspace.getConfiguration("zig.zls");
const zlsPath = zlsConfig.get<string>("path", "");
if (zlsPath.startsWith(context.globalStorageUri.fsPath)) {
await zigUtil.workspaceConfigUpdateNoThrow(zlsConfig, "enabled", "on", true);
await zigUtil.workspaceConfigUpdateNoThrow(zlsConfig, "path", undefined, true);
}
// convert `zig.zls.enableBuildOnSave` to `zig.buildOnSaveProvider`
{
const inspect = zlsConfig.inspect("enableBuildOnSave");
if (inspect?.globalValue !== undefined) {
await zigUtil.workspaceConfigUpdateNoThrow(
vscode.workspace.getConfiguration("zig"),
"buildOnSaveProvider",
inspect.globalValue ? "zls" : "off",
true,
);
await zigUtil.workspaceConfigUpdateNoThrow(zlsConfig, "enableBuildOnSave", undefined, true);
}
if (inspect?.workspaceValue !== undefined) {
await zigUtil.workspaceConfigUpdateNoThrow(
vscode.workspace.getConfiguration("zig"),
"buildOnSaveProvider",
inspect.workspaceValue ? "zls" : "off",
false,
);
await zigUtil.workspaceConfigUpdateNoThrow(zlsConfig, "enableBuildOnSave", undefined, false);
}
}
// convert `zig.zls.buildOnSaveArgs` to `zig.buildOnSaveArgs`
{
const inspect = zlsConfig.inspect("buildOnSaveArgs");
const zigConfig = vscode.workspace.getConfiguration("zig");
if (inspect?.globalValue) {
await zigUtil.workspaceConfigUpdateNoThrow(zigConfig, "buildOnSaveArgs", inspect.globalValue, true);
await zigUtil.workspaceConfigUpdateNoThrow(zlsConfig, "buildOnSaveArgs", undefined, true);
}
if (inspect?.workspaceValue) {
await zigUtil.workspaceConfigUpdateNoThrow(zigConfig, "buildOnSaveArgs", inspect.workspaceValue, false);
await zigUtil.workspaceConfigUpdateNoThrow(zlsConfig, "buildOnSaveArgs", undefined, false);
}
}
}
versionManagerConfig = {
context: context,
title: "ZLS",
exeName: "zls",
extraTarArgs: [],
/** https://github.com/zigtools/release-worker */
minisignKey: minisign.parseKey("RWR+9B91GBZ0zOjh6Lr17+zKf5BoSuFvrx2xSeDE57uIYvnKBGmMjOex"),
versionArg: "--version",
getMirrorUrls() {
return Promise.resolve([]);
},
canonicalUrl: {
release: vscode.Uri.parse("https://builds.zigtools.org"),
nightly: vscode.Uri.parse("https://builds.zigtools.org"),
},
getArtifactName(version) {
const fileExtension = process.platform === "win32" ? "zip" : "tar.xz";
const targetName = semver.gte(version, "0.15.0")
? `${zigUtil.getZigArchName("arm")}-${zigUtil.getZigOSName()}`
: `${zigUtil.getZigOSName()}-${zigUtil.getZigArchName("armv7a")}`;
return `zls-${targetName}-${version.raw}.${fileExtension}`;
},
};
// Remove after some time has passed from the prefix change.
await versionManager.convertOldInstallPrefixes(versionManagerConfig);
outputChannel = vscode.window.createOutputChannel("ZLS language server", { log: true });
statusItem = vscode.languages.createLanguageStatusItem("zig.zls.status", ZIG_MODE);
statusItem.name = "ZLS";
updateStatusItem(null);
context.subscriptions.push(
outputChannel,
statusItem,
vscode.commands.registerCommand("zig.zls.enable", async () => {
const zlsConfig = vscode.workspace.getConfiguration("zig.zls");
await zigUtil.workspaceConfigUpdateNoThrow(zlsConfig, "enabled", "on", true);
}),
vscode.commands.registerCommand("zig.zls.stop", async () => {
await stopClient();
}),
vscode.commands.registerCommand("zig.zls.startRestart", async () => {
const zlsConfig = vscode.workspace.getConfiguration("zig.zls");
await zigUtil.workspaceConfigUpdateNoThrow(zlsConfig, "enabled", "on", true);
await restartClient(context);
}),
vscode.commands.registerCommand("zig.zls.openOutput", () => {
outputChannel.show();
}),
);
if (await isEnabled()) {
await restartClient(context);
}
// These checks are added later to avoid ZLS be started twice because `isEnabled` sets `zig.zls.enabled`.
context.subscriptions.push(
vscode.workspace.onDidChangeConfiguration(async (change) => {
// The `zig.path` config option is handled by `zigProvider.onChange`.
if (
change.affectsConfiguration("zig.zls.enabled", undefined) ||
change.affectsConfiguration("zig.zls.path", undefined) ||
change.affectsConfiguration("zig.zls.debugLog", undefined)
) {
await restartClient(context);
}
}),
zigProvider.onChange.event(async () => {
await restartClient(context);
}),
);
}
export async function deactivate(): Promise<void> {
await stopClient();
}