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

+55
View File
@@ -0,0 +1,55 @@
# VoidLanguageServer Neovim client
Thin Neovim LSP and replay-DAP integration for the installed `vls` and
`vls-dap`. All language, build and debugger semantics stay in the C++ server;
this plugin only starts processes, forwards user actions and renders bounded
replies.
## Setup
Add this directory to `runtimepath` (for example with your plugin manager), or
copy `plugin/` and `lua/` into a Neovim config directory. Neovim 0.12.6 or newer
is tested. `nvim-dap` is optional and only needed for replay.
```lua
require("vls").setup({
server = "/absolute/path/to/vls", -- default: vls on PATH
dap_adapter = "/absolute/path/to/vls-dap", -- default: vls-dap on PATH
gcc_profile = nil, -- absolute prepared GCC profile
provider = nil, -- auto, vbs, compdb or none
})
```
## Commands
| Command | Action |
| --- | --- |
| `:VlsStart` | Start the server for the current buffer and workspace root. |
| `:VlsStatus` | Request `voidLanguageServer/providerStatus`. |
| `:VlsAnalysisStatus` | Request `voidLanguageServer/analysisStatus`. |
| `:VlsReplay {trace}` | Launch `vls-dap --replay` on an absolute recording. |
| `:VlsSession` | Subscribe to the active replay session and generation. |
| `:VlsTimeline [start] [count]` | Render a bounded timeline page. |
| `:VlsFrames [start] [count]` | Render a bounded frame page. |
| `:VlsSource` | Render the captured source of the active replay. |
| `:VlsStop` | Terminate the replay. |
| `:VlsRename {name}` | Request a guarded rename and apply it transactionally. |
Replies from a generation older than the subscribed one are rejected instead
of being rendered. Rename edits are validated for every buffer before any is
touched; if a buffer write fails, all already-changed buffers are restored
exactly and the transaction reports the failure.
## Acceptance
```sh
VLS_SERVER="$PWD/build/native/profiles/debug/out/bin/vls" \
VLS_DAP="$PWD/build/native/profiles/debug/out/bin/vls-dap" \
VLS_TRACE="$PWD/tests/debug/fixtures/integral-17.vls" \
VLS_NVIM_DAP="$PWD/build/dap-evidence/nvim-dap" \
nvim --headless -u NONE -i NONE -l tests/native/NeovimClient.lua
```
The test uses a temporary workspace, does not read or write user
configuration, and checks LSP status, a real replay session, timeline paging,
captured source, stale-generation rejection and shutdown.
+367
View File
@@ -0,0 +1,367 @@
local M = {}
local defaults = {
server = nil,
dap_adapter = nil,
gcc_profile = nil,
provider = nil,
}
local state = { config = {}, replay = nil }
function M.setup(options)
state.config = vim.tbl_extend("force", defaults, options or {})
end
local function config()
return state.config
end
local function absolute(path)
return type(path) == "string" and vim.startswith(path, "/")
end
local function executable(name, explicit)
local path = explicit or vim.fn.exepath(name)
if path == nil or path == "" then
return nil, name .. " is not on PATH"
end
if not absolute(path) then
return nil, name .. " did not resolve to an absolute path"
end
return path
end
local function workspace_root(bufnr)
local name = vim.api.nvim_buf_get_name(bufnr)
if name == "" then
return vim.fn.getcwd()
end
local markers = { ".git", "vbs.lock", "compile_commands.json", "build.cpp" }
return vim.fs.root(name, markers) or vim.fn.fnamemodify(name, ":p:h")
end
local function client_for(bufnr)
for _, client in ipairs(vim.lsp.get_clients({ bufnr = bufnr })) do
if client.name == "VoidLanguageServer" then
return client
end
end
return nil
end
function M.start(bufnr)
bufnr = bufnr or vim.api.nvim_get_current_buf()
local server, err = executable("vls", config().server)
if not server then
return nil, err
end
local root = workspace_root(bufnr)
local cmd = { server, "--stdio", "--workspace-root", root }
if config().provider then
vim.list_extend(cmd, { "--provider", config().provider })
end
if config().gcc_profile then
if not absolute(config().gcc_profile) then
return nil, "gcc_profile must be an absolute path"
end
vim.list_extend(cmd, { "--gcc-profile", config().gcc_profile })
end
local id = vim.lsp.start({ name = "VoidLanguageServer", cmd = cmd, root_dir = root },
{ bufnr = bufnr })
if not id then
return nil, "could not start VoidLanguageServer"
end
return vim.lsp.get_client_by_id(id)
end
local function request_sync(bufnr, method, params)
bufnr = bufnr or vim.api.nvim_get_current_buf()
local client = client_for(bufnr)
if not client then
return nil, "no VoidLanguageServer attached to this buffer"
end
local reply = client:request_sync(method, params, 5000, bufnr)
if not reply then
return nil, method .. " timed out"
end
if reply.err then
return nil, vim.inspect(reply.err)
end
return reply.result
end
function M.status(bufnr)
bufnr = bufnr or vim.api.nvim_get_current_buf()
local client = client_for(bufnr)
if not client then
return nil, "no VoidLanguageServer attached to this buffer"
end
return request_sync(bufnr, "voidLanguageServer/providerStatus", {
textDocument = { uri = vim.uri_from_bufnr(bufnr) },
workspaceUri = vim.uri_from_fname(client.config.root_dir),
})
end
function M.analysis_status(bufnr)
bufnr = bufnr or vim.api.nvim_get_current_buf()
return request_sync(bufnr, "voidLanguageServer/analysisStatus", {
textDocument = { uri = vim.uri_from_bufnr(bufnr) },
})
end
local function dap()
local ok, module = pcall(require, "dap")
if ok then
return module
end
return nil
end
function M.replay(trace)
if not absolute(trace) then
return nil, "an absolute trace path is required"
end
if vim.fn.filereadable(trace) ~= 1 then
return nil, "trace is not readable: " .. trace
end
local adapter, err = executable("vls-dap", config().dap_adapter)
if not adapter then
return nil, err
end
local dap_module = dap()
if not dap_module then
return nil, "nvim-dap is not installed"
end
local name = "vls-replay"
dap_module.adapters[name] = { type = "executable", command = adapter,
args = { "--replay", trace } }
dap_module.configurations.cpp = dap_module.configurations.cpp or {}
for index = #dap_module.configurations.cpp, 1, -1 do
if dap_module.configurations.cpp[index].type == name then
table.remove(dap_module.configurations.cpp, index)
end
end
local configuration = { type = name, request = "launch",
name = "VLS replay " .. vim.fn.fnamemodify(trace, ":t") }
table.insert(dap_module.configurations.cpp, configuration)
state.replay = { trace = trace }
dap_module.run(configuration)
return state.replay
end
local function session()
local dap_module = dap()
if not dap_module then
return nil
end
return dap_module.session()
end
local function request(method, arguments)
local active = session()
if not active then
return nil, "no active replay session"
end
local done, failure, body = false, nil, nil
active:request(method, arguments, function(err, result)
failure, body, done = err, result, true
end)
if not vim.wait(5000, function() return done end, 10) then
return nil, method .. " timed out"
end
if failure then
return nil, vim.inspect(failure)
end
return body
end
function M.session()
local reply, err = request("vls/session")
if not reply then
return nil, err
end
state.replay = state.replay or {}
state.replay.schemaVersion = reply.schemaVersion
state.replay.sessionId = reply.sessionId
state.replay.generation = reply.generation
return reply
end
local function current()
local active = state.replay
if not active or not active.generation then
return nil, "subscribe with :VlsSession first"
end
return active
end
function M.timeline(start, count)
local active, err = current()
if not active then
return nil, err
end
local page, failure = request("vls/timeline", {
schemaVersion = active.schemaVersion,
sessionId = active.sessionId,
generation = active.generation,
start = start or 0,
count = count or 20,
})
if not page then
return nil, failure
end
if page.sessionId ~= active.sessionId or page.generation ~= active.generation then
return nil, "stale replay generation"
end
return page
end
function M.frames(start, count)
local active, err = current()
if not active then
return nil, err
end
local page, failure = request("vls/frames", {
schemaVersion = active.schemaVersion,
sessionId = active.sessionId,
generation = active.generation,
start = start or 0,
count = count or 20,
})
if not page then
return nil, failure
end
if page.sessionId ~= active.sessionId or page.generation ~= active.generation then
return nil, "stale replay generation"
end
return page
end
function M.source()
local active, err = current()
if not active then
return nil, err
end
local reply, failure = request("source", { sourceReference = 1 })
if not reply then
return nil, failure
end
return reply.content
end
function M.stop()
local dap_module = dap()
if dap_module and dap_module.session() then
dap_module.terminate()
end
state.replay = nil
end
function M.render(title, lines)
local buffer = vim.api.nvim_create_buf(false, true)
vim.api.nvim_buf_set_lines(buffer, 0, -1, false, lines)
vim.bo[buffer].bufhidden = "wipe"
vim.bo[buffer].filetype = "vls-inspection"
vim.api.nvim_buf_set_name(buffer, title .. " " .. os.date("%H:%M:%S"))
vim.cmd.split()
vim.api.nvim_win_set_buf(0, buffer)
return buffer
end
local function before(left, right)
if left.line ~= right.line then
return left.line > right.line
end
return left.character > right.character
end
-- Applies an LSP `changes` map transactionally. Every range is validated
-- before any buffer is touched; an application failure restores the exact
-- pre-edit lines and modified state of every buffer already changed.
function M.apply_workspace_edit(changes)
if type(changes) ~= "table" then
return nil, "no workspace edit changes"
end
local plan = {}
for uri, edits in pairs(changes) do
if type(edits) ~= "table" or #edits == 0 then
return nil, "empty edit list for " .. uri
end
local bufnr = vim.uri_to_bufnr(uri)
if not vim.api.nvim_buf_is_loaded(bufnr) then
vim.fn.bufload(bufnr)
end
local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)
local sorted = vim.deepcopy(edits)
table.sort(sorted, function(left, right)
return before(left.range.start, right.range.start)
end)
for _, edit in ipairs(sorted) do
local first, last = edit.range.start, edit.range["end"]
if first.line < 0 or first.line >= #lines or last.line < first.line or
last.line >= #lines or first.character < 0 or last.character < 0 or
first.character > #lines[first.line + 1] or
(last.line == first.line and last.character < first.character) then
return nil, "edit range is outside the buffer: " .. uri
end
if type(edit.newText) ~= "string" then
return nil, "edit text is not a string: " .. uri
end
end
plan[#plan + 1] = { bufnr = bufnr, uri = uri, lines = lines,
modified = vim.bo[bufnr].modified, edits = sorted }
end
table.sort(plan, function(left, right) return left.uri < right.uri end)
for _, item in ipairs(plan) do
if not vim.bo[item.bufnr].modifiable then
return nil, "buffer is not modifiable: " .. item.uri
end
end
local applied = {}
local ok, failure = pcall(function()
for _, item in ipairs(plan) do
applied[#applied + 1] = item
for _, edit in ipairs(item.edits) do
vim.api.nvim_buf_set_text(item.bufnr, edit.range.start.line,
edit.range.start.character, edit.range["end"].line,
edit.range["end"].character, { edit.newText })
end
end
end)
if ok then
return true
end
for _, item in ipairs(applied) do
vim.api.nvim_buf_set_lines(item.bufnr, 0, -1, false, item.lines)
vim.bo[item.bufnr].modified = item.modified
end
return nil, tostring(failure)
end
-- Requests a guarded rename from the server and applies it transactionally.
function M.rename(new_name, bufnr)
bufnr = bufnr or vim.api.nvim_get_current_buf()
local client = client_for(bufnr)
if not client then
return nil, "no VoidLanguageServer attached to this buffer"
end
local cursor = vim.api.nvim_win_get_cursor(0)
local reply = client:request_sync("textDocument/rename", {
textDocument = { uri = vim.uri_from_bufnr(bufnr) },
position = { line = cursor[1] - 1, character = cursor[2] },
newName = new_name,
}, 5000, bufnr)
if not reply then
return nil, "textDocument/rename timed out"
end
if reply.err then
return nil, (reply.err.message or vim.inspect(reply.err))
end
if not reply.result or not reply.result.changes then
return nil, "the server returned no rename changes"
end
return M.apply_workspace_edit(reply.result.changes)
end
return M
+92
View File
@@ -0,0 +1,92 @@
if vim.g.loaded_vls then
return
end
vim.g.loaded_vls = 1
local function report(subject, result, err)
if err then
vim.notify("VLS: " .. err, vim.log.levels.ERROR)
return
end
vim.notify(subject .. "\n" .. vim.inspect(result), vim.log.levels.INFO)
end
vim.api.nvim_create_user_command("VlsStart", function()
local client, err = require("vls").start()
report("VoidLanguageServer started",
client and { id = client.id, root = client.config.root_dir } or nil, err)
end, { desc = "Start VoidLanguageServer for the current buffer" })
vim.api.nvim_create_user_command("VlsStatus", function()
report("VoidLanguageServer provider status", require("vls").status())
end, { desc = "Request provider status for the current document" })
vim.api.nvim_create_user_command("VlsAnalysisStatus", function()
report("VoidLanguageServer analysis status", require("vls").analysis_status())
end, { desc = "Request semantic analysis status for the current document" })
vim.api.nvim_create_user_command("VlsReplay", function(options)
local trace = vim.fn.fnamemodify(options.args, ":p")
report("VoidLanguageServer replay", require("vls").replay(trace))
end, { nargs = 1, complete = "file", desc = "Replay an absolute VLS recording" })
vim.api.nvim_create_user_command("VlsSession", function()
report("VoidLanguageServer replay session", require("vls").session())
end, { desc = "Subscribe to the active replay session and generation" })
vim.api.nvim_create_user_command("VlsTimeline", function(options)
local fields = vim.split(options.args, "%s+", { trimempty = true })
local page, err = require("vls").timeline(tonumber(fields[1]), tonumber(fields[2]))
if err then
report("VoidLanguageServer timeline", nil, err)
return
end
local lines = { string.format("session %s generation %d total %d",
page.sessionId, page.generation, page.total) }
for _, event in ipairs(page.events) do
table.insert(lines, string.format("%d %s%s", event.sequence, event.kind,
event.acknowledgedAction and
string.format(" stop=%d action=%s", event.acknowledgedStop,
event.acknowledgedAction) or ""))
end
require("vls").render("VLS timeline", lines)
end, { nargs = "*", desc = "Show a bounded timeline page: :VlsTimeline [start] [count]" })
vim.api.nvim_create_user_command("VlsFrames", function(options)
local fields = vim.split(options.args, "%s+", { trimempty = true })
local page, err = require("vls").frames(tonumber(fields[1]), tonumber(fields[2]))
if err then
report("VoidLanguageServer frames", nil, err)
return
end
local lines = { string.format("session %s generation %d total %d",
page.sessionId, page.generation, page.total) }
for _, frame in ipairs(page.frames) do
table.insert(lines, string.format("%s %s", tostring(frame.id),
tostring(frame.name)))
end
require("vls").render("VLS frames", lines)
end, { nargs = "*", desc = "Show a bounded frame page: :VlsFrames [start] [count]" })
vim.api.nvim_create_user_command("VlsSource", function()
local content, err = require("vls").source()
if err then
report("VoidLanguageServer source", nil, err)
return
end
require("vls").render("VLS captured source", vim.split(content, "\n", { plain = true }))
end, { desc = "Show the captured source of the active replay" })
vim.api.nvim_create_user_command("VlsStop", function()
require("vls").stop()
vim.notify("VLS: replay stopped", vim.log.levels.INFO)
end, { desc = "Stop the active replay session" })
vim.api.nvim_create_user_command("VlsRename", function(options)
local ok, err = require("vls").rename(options.args)
if not ok then
vim.notify("VLS: " .. err, vim.log.levels.ERROR)
else
vim.notify("VLS: rename applied", vim.log.levels.INFO)
end
end, { nargs = 1, desc = "Rename the symbol at the cursor through the server" })
+51
View File
@@ -0,0 +1,51 @@
# VoidLanguageServer VS Code client
Thin VS Code extension for the installed `vls` language server and the
`vls-dap` replay adapter. All language, build and debugger semantics stay in
the C++ server.
## Build
Node and npm are development prerequisites. Dependencies are fetched only by
this explicit step, never by the acceptance test:
```sh
cd clients/vscode
npm install
npm run compile
```
## Use
| Setting | Meaning |
| --- | --- |
| `vls.serverPath` | Absolute path to `vls` (default: `vls` on `PATH`). |
| `vls.dapPath` | Absolute path to `vls-dap` (default: `vls-dap` on `PATH`). |
| `vls.gccProfile` | Absolute prepared stock GCC profile for editor diagnostics. |
| `vls.provider` | Build-context preference: `auto`, `vbs`, `compdb` or `none`. |
Commands: `VLS: Start Language Server`, `VLS: Provider Status`,
`VLS: Analysis Status`, `VLS: Replay Recording`, `VLS: Stop Language Server`.
The C++ rename provider forwards `prepareRename`/`rename` to the server; the
exported `applyRename` applies an LSP `changes` map through one WorkspaceEdit
after checking the document versions captured at preparation, so a stale plan
is refused without partial edits.
The `VLS replay` debug configuration launches an absolute recording; the
extension renders only bounded server replies and rejects a stale
session/generation.
## Acceptance
The test runs a disposable extension host with temporary user-data and
extensions directories; it does not touch the user's profile.
```sh
python3 -B tests/native/VscodeClient.py \
--server "$PWD/build/native/profiles/debug/out/bin/vls" \
--adapter "$PWD/build/native/profiles/debug/out/bin/vls-dap" \
--trace "$PWD/tests/debug/fixtures/integral-17.vls"
```
On Nix, the `code` launcher detaches from the terminal, so the test invokes the
application binary (`lib/vscode/code`) directly to keep the extension host's
exit status and output.
+162
View File
@@ -0,0 +1,162 @@
{
"name": "vls-vscode",
"version": "0.0.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "vls-vscode",
"version": "0.0.1",
"dependencies": {
"vscode-languageclient": "^12.0.0"
},
"devDependencies": {
"@types/node": "^24.0.0",
"@types/vscode": "^1.146.0",
"typescript": "^5.7.0"
},
"engines": {
"vscode": "^1.91.0"
}
},
"node_modules/@isaacs/nonrecursive-glob-match": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz",
"integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==",
"license": "BlueOak-1.0.0"
},
"node_modules/@types/node": {
"version": "24.19.4",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.4.tgz",
"integrity": "sha512-s04odlR3ksJrLu7QLi+pddkWLD0RmSbcP9KuWn2/ozQKAp/YgwBC/6x9kJj8yAzZnGPfxePm7zm7nysVPCRagw==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": ">=7.24.0 <7.24.7"
}
},
"node_modules/@types/vscode": {
"version": "1.146.0",
"resolved": "https://registry.npmjs.org/@types/vscode/-/vscode-1.146.0.tgz",
"integrity": "sha512-OtU25faeM997QQsW+D07FN9cX06j+EEI4aQaPw/UO3HWlCM39N1W7fG8ewhdZKluut31KffyMsmDzJzgMu6t8Q==",
"dev": true,
"license": "MIT"
},
"node_modules/balanced-match": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
"integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",
"license": "MIT",
"engines": {
"node": "18 || 20 || >=22"
}
},
"node_modules/brace-expansion": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.1.2.tgz",
"integrity": "sha512-ELhY3JEerIBbhgW+rh0/8glkZAaMqn1x3BAvp3yTULSEGozMK/5PT6WTdBgsdvJqwwmv7MAQNOydfYbvK1Vgfw==",
"license": "MIT",
"dependencies": {
"balanced-match": "^4.0.2"
},
"engines": {
"node": "20 || >=22"
}
},
"node_modules/minimatch": {
"version": "11.0.10",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.10.tgz",
"integrity": "sha512-L3/cjhQ5E6lft0VCp/2mO3Ic74RnutKy3rz7iGwp/6w1hKcO262g2rbfacFyw6eBig5OdI0nu5PpuA0/WQs9Tw==",
"license": "BlueOak-1.0.0",
"dependencies": {
"@isaacs/nonrecursive-glob-match": "^1.1.0",
"brace-expansion": "^5.0.12"
},
"engines": {
"node": "20 || >=22"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/semver": {
"version": "7.8.6",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz",
"integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==",
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/undici-types": {
"version": "7.24.6",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz",
"integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==",
"dev": true,
"license": "MIT"
},
"node_modules/vscode-jsonrpc": {
"version": "10.0.2",
"resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-10.0.2.tgz",
"integrity": "sha512-U6K7wa1t8jTZf7eoHJLKSNdHE0oi9r/+/4TSXWPSLQ2FSQVMYLR5TvzQHrYjwW/lLjq0eTm+pi8vWz4jSV7o4w==",
"license": "MIT",
"engines": {
"node": ">=14.17.0"
}
},
"node_modules/vscode-languageclient": {
"version": "12.0.0",
"resolved": "https://registry.npmjs.org/vscode-languageclient/-/vscode-languageclient-12.0.0.tgz",
"integrity": "sha512-lDxVFl/sr++Mf/v9oY9Kh9Ihh+241zkVijtjJ1Q9w4QSeOkjojKO3Teg5bNPWHZU1zXbaI9/OTcajYjDZUWPEA==",
"license": "MIT",
"dependencies": {
"minimatch": "^11.0.9",
"semver": "^7.8.1",
"vscode-languageserver-protocol": "3.18.7",
"vscode-languageserver-textdocument": "1.0.16"
},
"engines": {
"vscode": "^1.91.0"
}
},
"node_modules/vscode-languageserver-protocol": {
"version": "3.18.7",
"resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.18.7.tgz",
"integrity": "sha512-5oItSZDTTehe0zXzwJCFUMso6RfUb2FWVTFfQxAesV3nTbkY1hjW3O6q8872M9TACEXFcALaU5xU37sGudYI8g==",
"license": "MIT",
"dependencies": {
"vscode-jsonrpc": "10.0.2",
"vscode-languageserver-types": "3.18.6"
}
},
"node_modules/vscode-languageserver-textdocument": {
"version": "1.0.16",
"resolved": "https://registry.npmjs.org/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.16.tgz",
"integrity": "sha512-qeNEuOi9a3qkqRf7Gfez2WL2VwlBTLCNekHBGO9kxPVUp9XuY15yfTJ9jwvOwKI0I2MhUUfZq95NSp+LK1CLQg==",
"license": "MIT"
},
"node_modules/vscode-languageserver-types": {
"version": "3.18.6",
"resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.18.6.tgz",
"integrity": "sha512-DEDtik4YupS+nOg4JxqJ2H5ec/m4tTD9a5mGcBVGYkQKZQo1AIF3ZToiP8+A0kUzyhyqX5dMnPDEnhtmzts7GA==",
"license": "MIT"
}
}
}
+130
View File
@@ -0,0 +1,130 @@
{
"name": "vls-vscode",
"displayName": "VoidLanguageServer",
"description": "Thin VS Code client for the VoidLanguageServer LSP and replay DAP.",
"publisher": "vls-local",
"version": "0.0.1",
"private": true,
"engines": {
"vscode": "^1.91.0"
},
"categories": [
"Programming Languages",
"Debuggers"
],
"activationEvents": [
"onLanguage:cpp",
"onCommand:vls.start"
],
"main": "./out/extension.js",
"contributes": {
"commands": [
{
"command": "vls.start",
"title": "VLS: Start Language Server"
},
{
"command": "vls.providerStatus",
"title": "VLS: Provider Status"
},
{
"command": "vls.analysisStatus",
"title": "VLS: Analysis Status"
},
{
"command": "vls.replay",
"title": "VLS: Replay Recording"
},
{
"command": "vls.stop",
"title": "VLS: Stop Language Server"
}
],
"configuration": {
"title": "VoidLanguageServer",
"properties": {
"vls.serverPath": {
"type": "string",
"default": "",
"description": "Absolute path to the vls executable (default: vls on PATH)."
},
"vls.dapPath": {
"type": "string",
"default": "",
"description": "Absolute path to the vls-dap executable (default: vls-dap on PATH)."
},
"vls.gccProfile": {
"type": "string",
"default": "",
"description": "Absolute prepared stock GCC profile for editor diagnostics."
},
"vls.provider": {
"type": "string",
"enum": [
"",
"auto",
"vbs",
"compdb",
"none"
],
"default": "",
"description": "Build-context provider preference."
}
}
},
"debuggers": [
{
"type": "vls-replay",
"label": "VLS replay",
"languages": [
"cpp"
],
"configurationAttributes": {
"launch": {
"properties": {
"trace": {
"type": "string",
"description": "Absolute path to a VLS recording.",
"default": ""
}
},
"required": [
"trace"
]
}
},
"initialConfigurations": [
{
"type": "vls-replay",
"request": "launch",
"name": "VLS replay",
"trace": ""
}
],
"configurationSnippets": [
{
"label": "VLS: replay a recording",
"body": {
"type": "vls-replay",
"request": "launch",
"name": "VLS replay ${1:name}",
"trace": "^\"\\${2:/absolute/path/to/recording.vls}\""
}
}
]
}
]
},
"scripts": {
"compile": "tsc -p .",
"test": "node ./out/test/run.js"
},
"dependencies": {
"vscode-languageclient": "^12.0.0"
},
"devDependencies": {
"@types/node": "^24.0.0",
"@types/vscode": "^1.146.0",
"typescript": "^5.7.0"
}
}
+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');
}
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "node16",
"moduleResolution": "node16",
"lib": [
"ES2022"
],
"outDir": "out",
"rootDir": "src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"sourceMap": true
},
"include": [
"src"
]
}