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

+238
View File
@@ -0,0 +1,238 @@
"""Exercise stock GCC diagnostics over the installed server's normal LSP transport."""
import argparse
import json
import os
from pathlib import Path
import queue
import subprocess
import tempfile
import threading
import time
class Editor:
def __init__(self, binary, profile, root, provider, versions=True):
self.errors = tempfile.TemporaryFile()
self.process = subprocess.Popen(
[binary, "--stdio", "--workspace-root", root, "--provider", provider,
"--gcc-profile", profile], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=self.errors, cwd=root, env={"LC_ALL": "C", "PATH": ""})
self.messages = queue.Queue()
self.pending = []
self.sequence = 0
self.reader = threading.Thread(target=self.read, daemon=True)
self.reader.start()
try:
result = self.request("initialize", {
"capabilities": {"textDocument": {"publishDiagnostics": {"versionSupport": versions}}},
"workspaceFolders": [{"uri": root.as_uri(), "name": root.name}]})
assert result["capabilities"]["textDocumentSync"]["openClose"]
self.send("initialized", {})
except BaseException:
self.dispose()
raise
def read(self):
try:
stream = self.process.stdout
while line := stream.readline(8192):
assert line.startswith(b"Content-Length: ") and line.endswith(b"\r\n")
size = int(line[16:])
assert 0 < size <= 16 * 1024 * 1024 and stream.readline(8192) == b"\r\n"
self.messages.put(json.loads(stream.read(size)))
except Exception as exc:
self.messages.put(exc)
finally:
self.messages.put(EOFError("server stdout closed"))
def send(self, method, params, **fields):
body = json.dumps({"jsonrpc": "2.0", "method": method, "params": params, **fields}).encode()
self.process.stdin.write(f"Content-Length: {len(body)}\r\n\r\n".encode() + body)
self.process.stdin.flush()
def wait(self, predicate, timeout=30):
end = time.monotonic() + timeout
while True:
for index, item in enumerate(self.pending):
if predicate(item):
return self.pending.pop(index)
try:
item = self.messages.get(timeout=max(0, end - time.monotonic()))
except queue.Empty:
raise AssertionError(f"timed out waiting for LSP output; pending={self.pending!r}") from None
if isinstance(item, Exception):
raise item
self.pending.append(item)
def request(self, method, params):
self.sequence += 1
self.send(method, params, id=self.sequence)
response = self.wait(lambda item: item.get("id") == self.sequence)
assert "error" not in response, response
return response["result"]
def open(self, file, text, version=1):
self.send("textDocument/didOpen", {"textDocument": {
"uri": file.as_uri(), "languageId": "cpp", "version": version, "text": text}})
def change(self, file, version, text):
self.send("textDocument/didChange", {"textDocument": {"uri": file.as_uri(), "version": version},
"contentChanges": [{"text": text}]})
def close(self, file):
self.send("textDocument/didClose", {"textDocument": {"uri": file.as_uri()}})
def status(self, file):
return self.request("voidLanguageServer/analysisStatus", {"textDocument": {"uri": file.as_uri()}})
def state(self, file, names, timeout=30):
end = time.monotonic() + timeout
while time.monotonic() < end:
status = self.status(file)
if status["state"] in names:
return status
time.sleep(.02)
raise AssertionError(f"missing analysis state {names}: {status}")
def diagnostics(self, file, version, word=None, timeout=30):
def match(message):
if message.get("method") != "textDocument/publishDiagnostics":
return False
p = message["params"]
if p["uri"] != file.as_uri() or p.get("version") != version:
return False
return (not p["diagnostics"] if word is None else
any(word in d["message"] for d in p["diagnostics"]))
try:
return self.wait(match, timeout)["params"]["diagnostics"]
except AssertionError as err:
raise AssertionError(f"{err}; status={self.status(file)}") from err
def finish(self):
assert self.request("shutdown", None) is None
self.send("exit", None)
self.process.stdin.close()
assert self.process.wait(timeout=10) == 0
self.errors.seek(0)
assert self.errors.read() == b""
def __enter__(self):
return self
def dispose(self):
if self.process.poll() is None:
self.process.kill()
self.process.wait()
if not self.process.stdin.closed:
self.process.stdin.close()
self.reader.join(timeout=5)
self.process.stdout.close()
self.errors.close()
def __exit__(self, exc_type, *_):
try:
if exc_type is None:
self.finish()
finally:
self.dispose()
def simple(binary, profile, root):
driver = json.loads(profile.read_text())["driver"]["path"]
tu, header, optional = (root / s for s in ("main.cpp", "value.hpp", "optional.hpp"))
good = ('#include "value.hpp"\n#if __has_include("optional.hpp")\n'
'int guard = optional_error;\n#endif\nint answer(){return value();}\n')
tu.write_text(good)
header.write_text('static_assert(!__builtin_strcmp(__TIMESTAMP__, "Sat Jan 1 00:00:00 2000"));\n'
'inline int value(){return 7;}\n')
os.utime(header, (946684800, 946684800))
(root / "compile_commands.json").write_text(json.dumps([{
"directory": str(root), "file": str(tu), "arguments": [driver, "-std=c++26", "-c", str(tu)]}]))
with Editor(binary, profile, root, "compdb") as e:
e.open(tu, good)
e.diagnostics(tu, 1)
bad = good.replace("return value()", "return wrong()")
e.change(tu, 2, bad)
diag = e.diagnostics(tu, 2, "wrong")[0]
assert diag["range"] == {"start": {"line": 4, "character": 20},
"end": {"line": 4, "character": 25}}, diag
assert diag["severity"] == 1 and diag["source"] == "gcc"
e.change(tu, 3, good)
e.diagnostics(tu, 3)
e.open(header, "inline int renamed(){return 7;}\n")
e.diagnostics(tu, 3, "value")
e.close(header)
e.diagnostics(tu, 3)
# No incoming protocol message triggers either of the next two disk changes.
optional.write_text("// appeared after the last successful analysis\n")
e.diagnostics(tu, 3, "optional_error")
optional.unlink()
e.diagnostics(tu, 3)
e.state(tu, {"ready"})
e.change(tu, 4, bad)
e.change(tu, 5, good)
e.diagnostics(tu, 5)
assert all(m.get("params", {}).get("version") != 4 for m in e.pending)
# A same-spelling #line origin in a header cannot point at inactive code in main.
(root / "line.hpp").write_text(f'#line 2 "{tu}"\nint x = impostor;\n')
e.change(tu, 6, '#if 0\nint x = impostor;\n#endif\n#include "line.hpp"\n')
report = e.state(tu, {"partial"})
assert report["unlocatedCount"] and any("impostor" in m for m in report["messages"]), report
e.close(tu)
e.open(tu, good)
e.diagnostics(tu, 1)
e.close(tu)
e.diagnostics(tu, 1)
with Editor(binary, profile, root, "compdb", versions=False) as e:
e.open(tu, bad)
e.diagnostics(tu, None, "wrong")
db = root / "compile_commands.json"
saved_db = db.read_bytes()
db.unlink()
with Editor(binary, profile, root, "compdb") as e:
e.open(tu, bad)
e.state(tu, {"unavailable"})
db.write_bytes(saved_db)
e.diagnostics(tu, 1, "wrong")
db.unlink()
e.diagnostics(tu, 1)
assert e.state(tu, {"unavailable"})["compilerRuns"] == 0
print("compdb: exact range, unsaved header, disk timestamp, idle header and database changes, supersession, remap, reopen and version negotiation passed", flush=True)
def actual(binary, profile, root):
tu = root / "src/Documents/DocumentSnapshot.cpp"
saved = tu.read_text()
assert saved.count("Void::Hash::fnv1a64(text)") == 1
edited = saved.replace("Void::Hash::fnv1a64(text)", "Void::Hash::missing(text)")
with Editor(binary, profile, root, "vbs") as e:
e.open(tu, edited)
diag = e.diagnostics(tu, 1, "missing", 90)[0]
assert diag["range"] == {"start": {"line": 18, "character": 33},
"end": {"line": 18, "character": 40}}, diag
status = e.status(tu)
assert status["state"] == "ready" and status["provider"] == "vbs", status
cold = status["compilerRuns"]
e.change(tu, 2, saved)
e.diagnostics(tu, 2, timeout=90)
warm = e.status(tu)["compilerRuns"]
# Cancel a running compiler job, then observe only the newer editor version.
e.change(tu, 3, edited)
e.state(tu, {"running"})
e.change(tu, 4, saved)
e.diagnostics(tu, 4, timeout=90)
assert all(m.get("params", {}).get("version") != 3 for m in e.pending)
print(f"native VBS: edited DocumentSnapshot.cpp line 19, recovery and in-flight cancellation passed; GCC runs cold={cold} warm={warm}", flush=True)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--server", required=True, type=Path)
parser.add_argument("--gcc-profile", required=True, type=Path)
parser.add_argument("--vbs-workspace", type=Path)
args = parser.parse_args()
binary, profile = args.server.resolve(), args.gcc_profile.resolve()
with tempfile.TemporaryDirectory(prefix="vls-stock-editor-") as tmp:
simple(binary, profile, Path(tmp).resolve())
if args.vbs_workspace:
actual(binary, profile, args.vbs_workspace.resolve())