Implement the VLS roadmap on the native VBS build

Native VBS and CMake builds of the server and every registered suite:
protocol and document sync, VBS/compdb providers, stock GCC diagnostics
(including in-process default profile preparation), the stock occurrence
observer and hover/definition, the bounded Scheduler, C++ module graph,
scan and artifact cache with real CMI production, the context-aware
symbol index with schema-2 snapshot migration, navigation and guarded
rename, reflection provenance with splice-origin extraction, index-backed
completion and signature help, live GCC worker control with a registered
DAP suite, and the Neovim and VS Code clients.

VoidLibrary follows main. The private GCC 16.2.0 frontend is reproduced
from the versioned patches and verified stepping reflection/template code
with projected values 17/34 and 41/82.
This commit is contained in:
faumaray committed 2026-12-05 14:06:50 +03:00
1 parent ca04975d54
commit da8003f6d4
310 files changed
+47552 -480

No files matched your search

+269
View File
@@ -0,0 +1,269 @@
import * as path from 'path';
import * as vscode from 'vscode';
import { LanguageClient, LanguageClientOptions, ServerOptions } from 'vscode-languageclient/node';
let client: LanguageClient | undefined;
let output: vscode.LogOutputChannel;
function settings(): vscode.WorkspaceConfiguration {
return vscode.workspace.getConfiguration('vls');
}
function rootFor(document?: vscode.TextDocument): string | undefined {
const uri = document?.uri ?? vscode.window.activeTextEditor?.document.uri;
if (uri) {
const folder = vscode.workspace.getWorkspaceFolder(uri);
if (folder) {
return folder.uri.fsPath;
}
if (uri.scheme === 'file') {
return path.dirname(uri.fsPath);
}
}
return vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
}
async function start(): Promise<void> {
await stop();
const server = settings().get<string>('serverPath') || 'vls';
const root = rootFor();
if (!root) {
throw new Error('open a C++ document or a workspace folder first');
}
const args = ['--stdio', '--workspace-root', root];
const provider = settings().get<string>('provider');
if (provider) {
args.push('--provider', provider);
}
const profile = settings().get<string>('gccProfile');
if (profile) {
if (!path.isAbsolute(profile)) {
throw new Error('vls.gccProfile must be an absolute path');
}
args.push('--gcc-profile', profile);
}
const serverOptions: ServerOptions = { command: server, args, options: { cwd: root } };
const clientOptions: LanguageClientOptions = {
documentSelector: [
{ scheme: 'file', language: 'cpp' },
{ scheme: 'file', language: 'c' },
],
outputChannel: output,
};
client = new LanguageClient('vls', 'VoidLanguageServer', serverOptions, clientOptions);
await client.start();
}
async function stop(): Promise<void> {
if (client) {
await client.stop();
client = undefined;
}
}
async function requestStatus(method: string): Promise<unknown> {
if (!client || !client.isRunning()) {
throw new Error('VoidLanguageServer is not running');
}
const document = vscode.window.activeTextEditor?.document;
if (!document) {
throw new Error('no active document');
}
const params: Record<string, unknown> = { textDocument: { uri: document.uri.toString() } };
if (method === 'voidLanguageServer/providerStatus') {
const root = rootFor(document);
if (!root) {
throw new Error('no workspace root for the active document');
}
params.workspaceUri = vscode.Uri.file(root).toString();
}
const reply = await client.sendRequest(method, params);
output.appendLine(`${method}: ${JSON.stringify(reply, null, 2)}`);
output.show(true);
return reply;
}
async function replay(trace?: string): Promise<void> {
let selected = trace;
if (!selected) {
const choice = await vscode.window.showOpenDialog({
canSelectFiles: true,
canSelectMany: false,
openLabel: 'Replay recording',
});
selected = choice?.[0]?.fsPath;
}
if (!selected) {
return;
}
if (!path.isAbsolute(selected)) {
throw new Error('the trace path must be absolute');
}
const started = await vscode.debug.startDebugging(vscode.workspace.workspaceFolders?.[0], {
type: 'vls-replay',
request: 'launch',
name: `VLS replay ${path.basename(selected)}`,
trace: selected,
});
if (!started) {
throw new Error('could not start the VLS replay session');
}
}
export interface RenameChange {
range: { start: { line: number; character: number }; end: { line: number; character: number } };
newText: string;
}
export type RenameChanges = Record<string, RenameChange[]>;
export interface RenamePlanInput {
changes: RenameChanges;
// Document versions observed when the rename was requested. A mismatch
// means the plan is stale and must not be applied.
versions?: Record<string, number>;
}
// Applies an LSP `changes` map through one WorkspaceEdit. Ranges are validated
// and every document version is rechecked immediately before application; an
// injected failure leaves no partial edits because VS Code applies the edit
// transactionally.
export async function applyRename(input: RenamePlanInput):
Promise<{ applied: boolean; reason?: string }> {
const edit = new vscode.WorkspaceEdit();
const prepared = new Map<string, { version: number; text: string }>();
for (const [uri, edits] of Object.entries(input.changes)) {
if (!edits.length) {
return { applied: false, reason: `empty edit list for ${uri}` };
}
const document = await vscode.workspace.openTextDocument(vscode.Uri.parse(uri));
const expected = input.versions?.[uri];
if (expected !== undefined && expected !== document.version) {
return { applied: false, reason: `document changed after preparation: ${uri}` };
}
prepared.set(uri, { version: document.version, text: document.getText() });
for (const change of edits) {
const start = new vscode.Position(change.range.start.line, change.range.start.character);
const end = new vscode.Position(change.range.end.line, change.range.end.character);
const range = new vscode.Range(start, end);
if (change.range.start.line >= document.lineCount ||
change.range.end.line >= document.lineCount ||
document.validateRange(range).end.isBefore(end) ||
end.isBefore(start) || typeof change.newText !== "string") {
return { applied: false, reason: `edit range is outside the document: ${uri}` };
}
edit.replace(document.uri, range, change.newText);
}
}
for (const [uri, expected] of prepared) {
const document = await vscode.workspace.openTextDocument(vscode.Uri.parse(uri));
if (document.version !== expected.version || document.getText() !== expected.text) {
return { applied: false, reason: `document changed after preparation: ${uri}` };
}
}
return await vscode.workspace.applyEdit(edit)
? { applied: true }
: { applied: false, reason: "the workspace edit was rejected" };
}
function registerRename(context: vscode.ExtensionContext): void {
context.subscriptions.push(vscode.languages.registerRenameProvider(
{ scheme: "file", language: "cpp" },
{
async prepareRename(document, position) {
if (!client || !client.isRunning()) {
throw new Error("VoidLanguageServer is not running");
}
const reply = await client.sendRequest<any>("textDocument/prepareRename", {
textDocument: { uri: document.uri.toString() },
position: { line: position.line, character: position.character },
});
if (!reply || !reply.range) {
throw new Error("no symbol at the requested position");
}
return new vscode.Range(reply.range.start.line, reply.range.start.character,
reply.range.end.line, reply.range.end.character);
},
async provideRenameEdits(document, position, newName) {
if (!client || !client.isRunning()) {
throw new Error("VoidLanguageServer is not running");
}
const reply = await client.sendRequest<any>("textDocument/rename", {
textDocument: { uri: document.uri.toString() },
position: { line: position.line, character: position.character },
newName,
});
const edit = new vscode.WorkspaceEdit();
for (const [uri, edits] of Object.entries(reply?.changes ?? {})) {
for (const change of edits as RenameChange[]) {
edit.replace(vscode.Uri.parse(uri),
new vscode.Range(change.range.start.line,
change.range.start.character,
change.range.end.line,
change.range.end.character),
change.newText);
}
}
return edit;
},
}));
}
function registerDebug(context: vscode.ExtensionContext): void {
context.subscriptions.push(vscode.debug.registerDebugConfigurationProvider('vls-replay', {
resolveDebugConfiguration(_folder, configuration) {
if (!configuration.type && !configuration.request) {
return undefined;
}
if (typeof configuration.trace !== 'string' || !path.isAbsolute(configuration.trace)) {
void vscode.window.showErrorMessage('VLS replay requires an absolute trace path.');
return undefined;
}
return configuration;
},
}));
context.subscriptions.push(vscode.debug.registerDebugAdapterDescriptorFactory('vls-replay', {
createDebugAdapterDescriptor(session) {
const trace: unknown = session.configuration.trace;
if (typeof trace !== 'string' || !path.isAbsolute(trace)) {
throw new Error('VLS replay requires an absolute trace path.');
}
const adapter = settings().get<string>('dapPath') || 'vls-dap';
return new vscode.DebugAdapterExecutable(adapter, ['--replay', trace]);
},
}));
}
export interface VlsApi {
client(): LanguageClient | undefined;
providerStatus(): Promise<unknown>;
analysisStatus(): Promise<unknown>;
replay(trace: string): Promise<void>;
applyRename(input: RenamePlanInput): Promise<{ applied: boolean; reason?: string }>;
output(): vscode.OutputChannel;
}
export function activate(context: vscode.ExtensionContext): VlsApi {
output = vscode.window.createOutputChannel('VoidLanguageServer', { log: true });
context.subscriptions.push(output);
context.subscriptions.push(vscode.commands.registerCommand('vls.start', start));
context.subscriptions.push(vscode.commands.registerCommand('vls.providerStatus', () =>
requestStatus('voidLanguageServer/providerStatus')));
context.subscriptions.push(vscode.commands.registerCommand('vls.analysisStatus', () =>
requestStatus('voidLanguageServer/analysisStatus')));
context.subscriptions.push(vscode.commands.registerCommand('vls.replay', replay));
context.subscriptions.push(vscode.commands.registerCommand('vls.stop', stop));
registerDebug(context);
registerRename(context);
return {
client: () => client,
providerStatus: () => requestStatus('voidLanguageServer/providerStatus'),
analysisStatus: () => requestStatus('voidLanguageServer/analysisStatus'),
replay,
applyRename,
output: () => output,
};
}
export async function deactivate(): Promise<void> {
await stop();
}
+185
View File
@@ -0,0 +1,185 @@
import assert from 'assert';
import * as crypto from 'crypto';
import * as fs from 'fs';
import * as path from 'path';
import * as vscode from 'vscode';
import { VlsApi } from '../extension';
const EXTENSION = 'vls-local.vls-vscode';
async function waitFor<T>(label: string, probe: () => T | undefined | false,
timeout = 20000): Promise<T> {
const deadline = Date.now() + timeout;
while (Date.now() < deadline) {
const value = probe();
if (value) {
return value;
}
await new Promise(resolve => setTimeout(resolve, 50));
}
throw new Error(`timed out waiting for ${label}`);
}
async function waitForAsync<T>(label: string, probe: () => Promise<T | undefined | false>,
timeout = 20000): Promise<T> {
const deadline = Date.now() + timeout;
while (Date.now() < deadline) {
try {
const value = await probe();
if (value) {
return value;
}
} catch {
// The adapter is not ready yet.
}
await new Promise(resolve => setTimeout(resolve, 100));
}
throw new Error(`timed out waiting for ${label}`);
}
async function request<T>(session: vscode.DebugSession, command: string,
args?: unknown): Promise<T> {
return await session.customRequest(command, args) as T;
}
async function readResult(session: vscode.DebugSession): Promise<string | undefined> {
const stack = await request<{ stackFrames: Array<{ id: number }> }>(session, 'stackTrace',
{ threadId: 1 });
const frame = stack.stackFrames[0];
if (!frame) {
return undefined;
}
const scopes = await request<{ scopes: Array<{ variablesReference: number }> }>(
session, 'scopes', { frameId: frame.id });
const scope = scopes.scopes[0];
if (!scope) {
return undefined;
}
const variables = await request<{ variables: Array<{ name: string; value: string }> }>(
session, 'variables', { variablesReference: scope.variablesReference });
return variables.variables.find(variable => variable.name === 'Result')?.value;
}
export async function run(): Promise<void> {
const server = process.env.VLS_SERVER;
const adapter = process.env.VLS_DAP;
const trace = process.env.VLS_TRACE;
assert(server && adapter && trace, 'VLS_SERVER, VLS_DAP and VLS_TRACE are required');
const settings = vscode.workspace.getConfiguration('vls');
await settings.update('serverPath', server, vscode.ConfigurationTarget.Global);
await settings.update('dapPath', adapter, vscode.ConfigurationTarget.Global);
const extension = vscode.extensions.getExtension(EXTENSION);
assert(extension, 'VLS extension not found');
const api = await extension.activate() as VlsApi;
const folder = vscode.workspace.workspaceFolders?.[0];
assert(folder, 'the test host requires a workspace folder');
const document = await vscode.workspace.openTextDocument(
path.join(folder.uri.fsPath, 'unit.cpp'));
await vscode.window.showTextDocument(document);
await vscode.commands.executeCommand('vls.start');
await waitFor('language client', () => api.client()?.isRunning());
const provider = await api.providerStatus() as { state?: unknown };
assert(typeof provider.state === 'string', JSON.stringify(provider));
const analysis = await api.analysisStatus() as { state?: unknown };
assert(typeof analysis.state === 'string', JSON.stringify(analysis));
await vscode.commands.executeCommand('vls.replay', trace);
const session = await waitFor('debug session', () => vscode.debug.activeDebugSession);
const first = await waitForAsync('replay session', async () =>
await request<{ sessionId?: unknown; generation?: unknown; schemaVersion?: unknown;
sourceSha256?: unknown }>(session, 'vls/session'));
assert(typeof first.sessionId === 'string' && typeof first.generation === 'number',
JSON.stringify(first));
const firstValue = await waitForAsync('first recorded value', async () =>
await readResult(session));
assert.strictEqual(firstValue, '17');
const timeline = await request<{ events: unknown[]; generation: number; sessionId: string }>(
session, 'vls/timeline', { schemaVersion: first.schemaVersion, sessionId: first.sessionId,
generation: first.generation, start: 0, count: 4 });
assert(Array.isArray(timeline.events) && timeline.events.length > 0, JSON.stringify(timeline));
const source = await request<{ content: string }>(session, 'source', { sourceReference: 1 });
assert.strictEqual(crypto.createHash('sha256').update(source.content).digest('hex'),
first.sourceSha256);
await request(session, 'continue', { threadId: 1 });
const secondValue = await waitForAsync('second recorded value', async () =>
await readResult(session));
assert.strictEqual(secondValue, '34');
let staleRejected = false;
try {
await request(session, 'vls/timeline', { schemaVersion: first.schemaVersion,
sessionId: first.sessionId,
generation: first.generation,
start: 0, count: 2 });
} catch {
staleRejected = true;
}
assert(staleRejected, 'a stale generation was accepted');
const second = await request<{ sessionId: string; generation: number;
schemaVersion: number }>(session, 'vls/session');
assert(second.generation > (first.generation as number));
const page = await request<{ generation: number }>(session, 'vls/timeline', {
schemaVersion: second.schemaVersion, sessionId: second.sessionId,
generation: second.generation, start: 0, count: 2 });
assert.strictEqual(page.generation, second.generation);
await vscode.debug.stopDebugging(session);
await vscode.commands.executeCommand('vls.stop');
await waitFor('client stop', () => !api.client() || !api.client()?.isRunning());
// Transactional rename application.
const firstPath = path.join(folder.uri.fsPath, "rename-a.cpp");
const secondPath = path.join(folder.uri.fsPath, "rename-b.cpp");
fs.writeFileSync(firstPath, "int value = 1;\n");
fs.writeFileSync(secondPath, "int value = 2;\n");
const renameFirst = await vscode.workspace.openTextDocument(firstPath);
const renameSecond = await vscode.workspace.openTextDocument(secondPath);
const changes = {
[renameFirst.uri.toString()]: [{ range: { start: { line: 0, character: 4 },
end: { line: 0, character: 9 } }, newText: "count" }],
[renameSecond.uri.toString()]: [{ range: { start: { line: 0, character: 4 },
end: { line: 0, character: 9 } }, newText: "count" }],
};
const applied = await api.applyRename({ changes });
assert.strictEqual(applied.applied, true, JSON.stringify(applied));
assert.strictEqual((await vscode.workspace.openTextDocument(firstPath)).getText(),
"int count = 1;\n");
assert.strictEqual((await vscode.workspace.openTextDocument(secondPath)).getText(),
"int count = 2;\n");
const thirdPath = path.join(folder.uri.fsPath, "rename-c.cpp");
const fourthPath = path.join(folder.uri.fsPath, "rename-d.cpp");
fs.writeFileSync(thirdPath, "int value = 3;\n");
fs.writeFileSync(fourthPath, "int value = 4;\n");
const third = await vscode.workspace.openTextDocument(thirdPath);
const fourth = await vscode.workspace.openTextDocument(fourthPath);
const stale = {
[third.uri.toString()]: [{ range: { start: { line: 0, character: 4 },
end: { line: 0, character: 9 } }, newText: "count" }],
[fourth.uri.toString()]: [{ range: { start: { line: 0, character: 4 },
end: { line: 0, character: 9 } }, newText: "count" }],
};
const versions = { [third.uri.toString()]: third.version,
[fourth.uri.toString()]: fourth.version };
const editor = await vscode.window.showTextDocument(third);
await editor.edit(builder => builder.insert(new vscode.Position(0, 0), "// changed\n"));
const rejected = await api.applyRename({ changes: stale, versions });
assert.strictEqual(rejected.applied, false, JSON.stringify(rejected));
assert.strictEqual((await vscode.workspace.openTextDocument(fourthPath)).getText(),
"int value = 4;\n");
const invalid = {
[fourth.uri.toString()]: [{ range: { start: { line: 99, character: 0 },
end: { line: 99, character: 1 } }, newText: "x" }],
};
assert.strictEqual((await api.applyRename({ changes: invalid })).applied, false);
assert.strictEqual((await vscode.workspace.openTextDocument(fourthPath)).getText(),
"int value = 4;\n");
console.log('VSCODE_CLIENT_PASS');
}