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

+319
View File
@@ -0,0 +1,319 @@
"""Exercise a VLS debug adapter on recorded GCC events using the public stdio protocol."""
import argparse
import hashlib
import json
import queue
import shutil
import subprocess
import tempfile
import threading
from pathlib import Path
class Client:
def __init__(self, adapter, trace):
self.child = subprocess.Popen(
[adapter, "--replay", trace], cwd=trace.parent, env={"PATH": "", "LC_ALL": "C"},
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self.incoming = queue.Queue()
self.reader = threading.Thread(target=self._read, daemon=True)
self.reader.start()
self.outgoing_seq = 0
self.incoming_seq = 0
def _read(self):
try:
stream = self.child.stdout
while line := stream.readline(8192):
assert line.startswith(b"Content-Length: ") and line.endswith(b"\r\n"), line
length = int(line[16:])
assert 0 < length <= 16 * 1024 * 1024 and stream.readline(8192) == b"\r\n"
self.incoming.put(json.loads(stream.read(length)))
self.incoming.put(EOFError("adapter stdout closed"))
except Exception as error:
self.incoming.put(error)
def __enter__(self):
return self
def __exit__(self, *exc):
self.child.stdin.close()
if self.child.poll() is None:
self.child.kill()
self.child.wait(timeout=5)
self.reader.join(timeout=5)
self.child.stdout.close()
self.child.stderr.close()
def send(self, command, args=None):
self.outgoing_seq += 1
message = {"seq": self.outgoing_seq, "type": "request", "command": command,
"arguments": {} if args is None else args}
body = json.dumps(message).encode()
self.child.stdin.write(f"Content-Length: {len(body)}\r\n\r\n".encode() + body)
self.child.stdin.flush()
return self.outgoing_seq
def receive(self):
message = self.incoming.get(timeout=5)
if isinstance(message, Exception):
raise message
self.incoming_seq += 1
assert message["seq"] == self.incoming_seq, message
assert "jsonrpc" not in message, message
return message
def response(self, seq, command, success=True):
reply = self.receive()
assert (reply["type"], reply["request_seq"], reply["command"], reply["success"]) == (
"response", seq, command, success), reply
return reply.get("body", {})
def request(self, command, args=None, success=True):
return self.response(self.send(command, args), command, success)
def event(self, name):
event = self.receive()
assert event["type"] == "event" and event["event"] == name, event
return event.get("body", {})
def initialize(self, paging=True):
caps = self.request("initialize", {"adapterID": "vls", "supportsVariablePaging": paging})
assert caps["supportsConfigurationDoneRequest"] and caps["supportsLoadedSourcesRequest"]
assert not caps.get("supportsStepBack")
self.event("initialized")
def launch(self, paging=True):
self.initialize(paging)
launch = self.send("launch")
self.request("configurationDone")
self.response(launch, "launch")
self.stopped()
return self.request("vls/session")
def stopped(self):
stopped = self.event("stopped")
assert stopped["threadId"] == 1 and stopped["allThreadsStopped"]
def disconnect(self, terminated=False):
self.request("disconnect")
if not terminated:
self.event("terminated")
assert self.child.wait(timeout=5) == 0
assert self.child.stderr.read() == b""
assert isinstance(self.incoming.get(timeout=5), EOFError), "extra adapter output"
def identity(state):
return {key: state[key] for key in ("schemaVersion", "sessionId", "generation")}
def page(client, command, state, start=0, count=64):
reply = client.request(command, {**identity(state), "start": start, "count": count})
assert identity(reply) == identity(state)
return reply
def seek(client, state, **destination):
reply = client.request("vls/seek", {**identity(state), **destination})
client.stopped()
current = client.request("vls/session")
assert identity(current) == identity(reply)
assert current["generation"] > state["generation"]
return current
def inspect_value(client, expected):
stack = client.request("stackTrace", {"threadId": 1})
frames = stack["stackFrames"]
assert stack["totalFrames"] == len(frames) and len(frames) >= 1
assert all(f["line"] == 0 and f["column"] == 0 and "source" not in f for f in frames)
top = frames[0]["id"]
scopes = client.request("scopes", {"frameId": top})["scopes"]
ref = scopes[0]["variablesReference"]
assert ref > 0 and ref != top
variables = client.request("variables", {"variablesReference": ref})["variables"]
assert [v["value"] for v in variables if v["name"] == "Result"] == [str(expected)], variables
return top, ref
def replay(adapter, selected, replacement, work, expected):
private = work / "selected.vls"
shutil.copyfile(selected, private)
with Client(adapter, private) as client:
state = client.launch()
assert state["mode"] == "replay" and state["pauseKind"] == "recordedStop"
assert state["schemaVersion"] == 1 and state["eventSequence"] == 6
assert state["recording"]["outcome"] == "completed" and state["recording"]["exitCode"] == 0
assert not state["recording"]["partial"] and not state["recording"]["corrupt"]
session_id = state["sessionId"]
top, scope = inspect_value(client, expected)
source = client.request("loadedSources")["sources"]
assert len(source) == 1 and "path" not in source[0]
ref = source[0]["sourceReference"]
assert ref == state["sourceReference"] and ref > 0
source_args = {"sourceReference": ref, "source": {"path": str(replacement)}}
captured = client.request("source", source_args)["content"].encode()
assert f"Ready = {expected}".encode() in captured
assert len(captured) == state["sourceByteLength"]
assert hashlib.sha256(captured).hexdigest() == state["sourceSha256"]
client.request("source", {**source_args, "source": {"sourceReference": ref + 1}}, False)
client.request("source", {"sourceReference": 0, "source": {"path": str(replacement)}}, False)
# Later requests must use the bytes and index acquired on launch.
newer = work / "new.vls"
shutil.copyfile(replacement, newer)
newer.replace(private)
private.unlink()
assert client.request("source", source_args)["content"].encode() == captured
events = page(client, "vls/timeline", state)
assert events["total"] == len(events["events"]) == state["recording"]["eventCount"]
indexed = {event["sequence"]: event for event in events["events"]}
assert (indexed[7]["acknowledgedStop"], indexed[7]["acknowledgedAction"]) == (6, "step")
assert (indexed[11]["acknowledgedStop"], indexed[11]["acknowledgedAction"]) == (10, "continue")
assert page(client, "vls/timeline", state, events["total"], 0)["events"] == []
for bad_page in ({"count": 257}, {"count": -1}, {"start": events["total"] + 1},
{"start": 0.5}, {"sessionId": "other"}, {"schemaVersion": 2}):
args = {**identity(state), "start": 0, "count": 1, **bad_page}
client.request("vls/timeline", args, False)
view = page(client, "vls/frames", state)
assert [f["name"] for f in view["frames"]] == ["reflected_value", "twice"]
assert view["frames"][0]["sourceKind"] == "logicalDeclaration"
first = state
state = seek(client, state, eventSequence=5)
view = page(client, "vls/frames", state)
assert state["pauseKind"] == "value" and view["stop"] is None
assert view["frames"][0]["valueProvisional"] and view["lastLeave"] is None
state = seek(client, state, eventSequence=8)
view = page(client, "vls/frames", state)
assert [f["name"] for f in view["frames"]] == ["twice"]
assert view["lastLeave"]["outcome"] == "returned" and not view["lastLeave"]["valueProvisional"]
state = seek(client, state, direction="previousValue")
assert state["eventSequence"] == 6 and state["sessionId"] == session_id
assert inspect_value(client, expected)[0] != top
client.request("scopes", {"frameId": top}, False)
client.request("variables", {"variablesReference": scope}, False)
client.request("vls/frames", {**identity(first), "start": 0, "count": 1}, False)
client.request("vls/seek", {**identity(first), "eventSequence": 10}, False)
client.request("continue", {"threadId": 1, "vlsContext": identity(first)}, False)
client.request("next", {"threadId": 1}, False)
for value, sequence, kind in ((expected * 2, 10, "recordedStop"),
(expected + 5, 20, "value"), ((expected + 5) * 2, 22, "value")):
client.request("continue", {"threadId": 1, "vlsContext": identity(state)})
client.stopped()
state = client.request("vls/session")
assert (state["eventSequence"], state["pauseKind"]) == (sequence, kind)
inspect_value(client, value)
client.request("continue", {"threadId": 1})
client.event("terminated")
client.disconnect(terminated=True)
return session_id
def cancelled(adapter, fixture):
with Client(adapter, fixture) as client:
state = client.launch()
assert state["recording"]["outcome"] == "cancelled" and state["recording"]["exitCode"] == 125
assert state["recording"]["partial"] and not state["recording"]["corrupt"]
inspect_value(client, 41)
events = page(client, "vls/timeline", state)["events"]
assert events[-1]["sequence"] == 7 and events[-1]["kind"] == "terminal"
client.request("continue", {"threadId": 1})
client.event("terminated")
client.disconnect(terminated=True)
def failures(adapter, valid, work):
invalid = work / "invalid.vls"
invalid.write_bytes(b"invalid")
with Client(adapter, invalid) as client:
client.initialize()
client.request("launch", {"trace": str(valid)}, False)
client.request("launch", success=False)
client.disconnect()
with Client(adapter, valid) as client:
client.initialize()
for invalid_option in (True, "false", None):
client.request("launch", {"noDebug": invalid_option}, False)
client.request("configurationDone")
client.request("launch", {"noDebug": False})
client.stopped()
client.disconnect()
peer_reply = b'{"seq":3,"type":"response","request_seq":1,"command":"initialize","success":true}'
reply_frame = f"Content-Length: {len(peer_reply)}\r\n\r\n".encode() + peer_reply
for raw in (b"Content-Length: 20\r\n\r\n{}", b"Content-Length: 3\r\n\r\nabc",
b"Content-Length: 1\r\nContent-Length: 1\r\n\r\n0", b"Content-Len", reply_frame):
child = subprocess.run([adapter, "--replay", valid], input=raw, capture_output=True,
env={"PATH": ""}, timeout=5)
assert child.returncode != 0 and not child.stdout and child.stderr
with Client(adapter, valid) as client:
client.initialize()
pending = client.send("launch")
client.child.stdin.write(raw)
client.child.stdin.close()
client.response(pending, "launch", False)
assert client.child.wait(timeout=5) != 0
assert isinstance(client.incoming.get(timeout=5), EOFError)
def incomplete_and_paging(adapter, valid, work):
raw = valid.read_bytes()
assert hashlib.sha256(raw).hexdigest() == "4efd70044105ed7e2ae1104780e564d1b8e20bc7d9494f3e0ed82156cef95ea4"
# The original recording reaches the second function body at this record boundary.
prefix = work / "before-first-return.vls"
prefix.write_bytes(raw[:1995])
with Client(adapter, prefix) as client:
state = client.launch()
assert state["eventSequence"] == 4 and state["pauseKind"] == "event"
assert state["recording"]["partial"] and state["recording"]["eventCount"] == 5
state = seek(client, state, eventSequence=1)
assert [f["name"] for f in page(client, "vls/frames", state)["frames"]] == ["twice"]
client.disconnect()
for paged in (False, True):
with Client(adapter, valid) as client:
client.launch(paged)
_, ref = inspect_value(client, 17)
var_args = {"variablesReference": ref}
all_vars = client.request("variables", var_args)["variables"]
subset = client.request("variables", {**var_args, "start": 1, "count": 1})["variables"]
assert subset == (all_vars[1:2] if paged else all_vars)
assert client.request("stackTrace", {"threadId": 1, "startFrame": 2**32-1})["stackFrames"] == []
if paged:
assert client.request("variables", {**var_args, "start": 2**32-1})["variables"] == []
for breakpoint in ({}, {"line": "5"}, {"line": 3, "column": -1}):
client.request("setBreakpoints", {"source": {}, "breakpoints": [breakpoint]}, False)
client.disconnect()
with Client(adapter, valid) as client:
client.initialize()
seq = client.send("launch")
client.outgoing_seq -= 1 # A second packet reuses the outstanding launch correlation.
assert client.send("launch") == seq
client.response(seq, "launch", False)
assert client.child.wait(timeout=5) != 0
assert isinstance(client.incoming.get(timeout=5), EOFError), "duplicate launch response"
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--adapter", required=True, type=Path)
parser.add_argument("--fixtures", type=Path,
default=Path(__file__).resolve().parents[1] / "debug" / "fixtures")
args = parser.parse_args()
adapter = args.adapter.resolve(strict=True)
a, b, c = (args.fixtures.resolve() / name for name in
("integral-17.vls", "integral-41.vls", "cancelled-41.vls"))
with tempfile.TemporaryDirectory(prefix="vls-dap-") as directory:
work = Path(directory)
first = replay(adapter, a, b, work, 17)
second = replay(adapter, b, a, work, 41)
assert first != second
cancelled(adapter, c)
failures(adapter, a, work)
incomplete_and_paging(adapter, a, work)
print("DAP replay passed: 17/34/22/44, 41/82/46/92, cancelled prefix 41, expired "
"handles and pages, immutable source, ordered acknowledgements and malformed frames")
if __name__ == "__main__":
main()
+167
View File
@@ -0,0 +1,167 @@
#!/usr/bin/env python3
"""Exercise EditorDiagnostics module scan and artifact preparation with real GCC."""
import argparse
import json
import os
from pathlib import Path
import select
import subprocess
import tempfile
import time
def check(condition, detail):
if not condition:
raise ValueError(detail)
def frame(message):
payload = json.dumps({"jsonrpc": "2.0", **message}, ensure_ascii=False).encode()
return f"Content-Length: {len(payload)}\r\n\r\n".encode() + payload
class Session:
def __init__(self, argv, cwd, stderr):
self.process = subprocess.Popen(argv, cwd=cwd, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=stderr,
env={**os.environ, "LC_ALL": "C"})
self.sequence = 0
self.buffer = b""
def send(self, message):
self.process.stdin.write(frame(message))
self.process.stdin.flush()
def notify(self, method, params):
self.send({"method": method, "params": params})
def request(self, method, params, timeout=180):
self.sequence += 1
self.send({"id": self.sequence, "method": method, "params": params})
deadline = time.monotonic() + timeout
while True:
message = self.read(deadline - time.monotonic())
if message.get("id") == self.sequence:
return message
def read(self, timeout):
check(timeout > 0, "LSP response deadline expired")
while b"\r\n\r\n" not in self.buffer:
ready, _, _ = select.select([self.process.stdout], [], [], timeout)
check(ready, "LSP response deadline expired")
chunk = os.read(self.process.stdout.fileno(), 65536)
check(chunk, "the server closed stdout")
self.buffer += chunk
header, rest = self.buffer.split(b"\r\n\r\n", 1)
length = int(header.removeprefix(b"Content-Length: "))
while len(rest) < length:
chunk = os.read(self.process.stdout.fileno(), 65536)
check(chunk, "truncated LSP response")
rest += chunk
body, self.buffer = rest[:length], rest[length:]
return json.loads(body)
def close(self):
try:
self.request("shutdown", None, timeout=30)
self.notify("exit", None)
except (OSError, ValueError, TimeoutError):
pass
try:
self.process.stdin.close()
except OSError:
pass
try:
self.process.wait(timeout=10)
except subprocess.TimeoutExpired:
self.process.kill()
self.process.wait()
def await_field(session, uri, field, predicate, timeout=180):
deadline = time.monotonic() + timeout
last = None
result = None
while time.monotonic() < deadline:
reply = session.request("voidLanguageServer/analysisStatus",
{"textDocument": {"uri": uri}}, timeout=30)
result = reply.get("result") or {}
last = result.get(field)
if last and predicate(last):
return last
if last and last.get("state") in ("failed", "unavailable", "cancelled"):
raise ValueError(f"{field} did not complete: {last} status={result}")
time.sleep(0.2)
raise ValueError(f"{field} did not finish: {last} status={result}")
def run(server, profile, compiler, observer):
with tempfile.TemporaryDirectory(prefix="vls-editor-modules-") as temp:
root = Path(temp)
source = root / "editor.cmi.cpp"
source.write_text("export module editor.cmi;\n"
"export int twice(int value) { return value * 2; }\n",
encoding="utf-8")
object_path = root / "editor.cmi.o"
database = root / "compile_commands.json"
database.write_text(json.dumps([{
"directory": str(root), "file": str(source),
"arguments": [str(compiler), "-std=c++26", "-fmodules-ts", "-c", str(source), "-o",
str(object_path)]}]))
uri = source.as_uri()
text = source.read_text(encoding="utf-8")
with tempfile.TemporaryFile() as errors:
session = Session([str(server), "--stdio", "--workspace-root", str(root),
"--provider", "compdb", "--compdb", str(database),
"--gcc-profile", str(profile)], root, errors)
try:
initialized = session.request("initialize", {
"processId": None, "capabilities": {},
"workspaceFolders": [{"uri": root.as_uri(), "name": root.name}]})
check(initialized["result"]["capabilities"].get("hoverProvider"),
"observer capabilities are not advertised")
session.notify("initialized", {})
session.notify("textDocument/didOpen", {"textDocument": {
"uri": uri, "languageId": "cpp", "version": 1, "text": text}})
scan = await_field(session, uri, "moduleScan",
lambda value: value.get("state") in ("ready", "partial"))
check("editor.cmi" in scan.get("provides", []), f"wrong scan: {scan}")
artifact = await_field(session, uri, "moduleArtifact",
lambda value: value.get("state") == "ready")
check(len(artifact.get("generation", "")) == 64,
f"no published artifact generation: {artifact}")
finally:
session.close()
errors.seek(0)
diagnostics = errors.read()
check(b"fatal" not in diagnostics.lower(), diagnostics[-800:])
print(f"editor modules: scan provided editor.cmi, artifact generation "
f"{artifact['generation'][:16]}...")
def 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("--cxx", default="g++")
parser.add_argument("--observer", type=Path,
help="assert this observer is selected by the profile")
options = parser.parse_args()
compiler = Path(shutil_which(options.cxx))
run(options.server.resolve(strict=True), options.gcc_profile.resolve(strict=True),
compiler.resolve(strict=True), options.observer)
def shutil_which(name):
from shutil import which
selected = which(name)
check(selected, f"{name} was not found")
return selected
if __name__ == "__main__":
try:
main()
except (OSError, ValueError, subprocess.SubprocessError) as exc:
raise SystemExit(f"verify-editor-modules: {exc}")
+156
View File
@@ -0,0 +1,156 @@
"""Check the private Linux GCC launcher with a harmless ELF and the patched frontend."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import select
import shutil
import subprocess
import tempfile
NONCE = "146a66737eef9c04ea33c6e05589f701"
ROOT = Path(__file__).resolve().parents[2]
WITNESS = r"""
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <unistd.h>
int main(int argc, char **argv, char **env) {
const char *fixed[] = {"cc1plus", "-quiet", "-std=c++26", "-freflection", "-fsyntax-only",
"-nostdinc", "-o", "/dev/null", "-fvls-observe", "-fvls-step", "input.cpp"};
if (argc != 11) return 10;
for (int i = 0; i < argc; ++i)
if (strcmp(fixed[i], argv[i])) return 11;
const char *nonce = getenv("VLS_GCC_NONCE");
if (!nonce || !getenv("LC_ALL") || strcmp("C", getenv("LC_ALL")) ||
!getenv("PATH") || *getenv("PATH") || getenv("VLS_TEST_PARENT_ONLY")) return 12;
int count = 0;
while (env[count]) ++count;
if (count != 3) return 13;
struct stat raw_in, raw_out, err, control, events;
if (fstat(0, &raw_in) || fstat(1, &raw_out) || fstat(2, &err) ||
fstat(3, &control) || fstat(4, &events)) return 14;
if (!S_ISCHR(raw_in.st_mode) || raw_in.st_rdev != makedev(1,3) ||
raw_out.st_rdev != raw_in.st_rdev || !S_ISFIFO(err.st_mode) ||
!S_ISFIFO(control.st_mode) || !S_ISFIFO(events.st_mode) ||
control.st_ino == events.st_ino || err.st_ino == events.st_ino) return 15;
for (int fd = 5; fd < 32; ++fd)
if (fcntl(fd, F_GETFD) >= 0) return 16;
struct rlimit core, cpu, memory, files, descriptors;
if (getrlimit(RLIMIT_CORE, &core) || getrlimit(RLIMIT_CPU, &cpu) ||
getrlimit(RLIMIT_FSIZE, &files) || getrlimit(RLIMIT_AS, &memory) ||
getrlimit(RLIMIT_NOFILE, &descriptors)) return 17;
if (core.rlim_max || cpu.rlim_cur > 15 || cpu.rlim_max > 20 ||
memory.rlim_max > 768ULL * 1024 * 1024 || files.rlim_max > 1024 * 1024 ||
descriptors.rlim_max > 32) return 18;
int self = open("/proc/self/exe", O_RDONLY);
int seals = fcntl(self, F_GET_SEALS);
int required = F_SEAL_WRITE | F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_SEAL;
if (seals < 0 || (seals & required) != required) return 19;
close(self);
dprintf(1, "discarded raw output\n");
dprintf(2, "witness diagnostic\n");
dprintf(4, "%s\n", nonce);
char go;
if (read(3, &go, 1) != 1 || go != 'g') return 20;
dprintf(4, "same sealed executable\n");
return 0;
}
"""
def digest(path):
with path.open("rb") as file:
return hashlib.file_digest(file, "sha256").hexdigest()
def require(ok, message):
if not ok:
raise ValueError(message)
def args(probe, compiler, sha, nonce=NONCE, mode="step"):
return [str(probe), "--leaf", str(compiler), sha, nonce, mode]
def verify_leaf(probe, compiler, cc, work):
source = work / "witness.c"
source.write_text(WITNESS)
witness = work / "witness"
subprocess.run([cc, str(source), "-o", str(witness)], check=True, timeout=30)
sha = digest(witness)
saved = work / "original-witness"
env = {**os.environ, "VLS_TEST_PARENT_ONLY": "must not reach compiler"}
with subprocess.Popen(args(probe, witness, sha), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, cwd=work, env=env, bufsize=0) as child:
try:
require(select.select([child.stdout], [], [], 5)[0], "witness did not start")
require(child.stdout.readline() == NONCE.encode() + b"\n", "sealed ELF did not verify process state")
witness.rename(saved)
witness.write_bytes(b"this file cannot be a compiler")
out, err = child.communicate(b"g", timeout=5)
require((out, err, child.returncode) == (b"same sealed executable\n", b"witness diagnostic\n", 0),
f"unexpected witness output {out!r}, {err!r}, {child.returncode}")
finally:
if child.poll() is None:
child.kill()
child.wait(timeout=3)
print("Verified fixed argv, pipe identity, resource limits, environment and sealed execution after replacement")
script = work / "benign.sh"
script.write_text("#!/bin/sh\nexit 0\n")
script.chmod(0o700)
partial = work / "partial"
partial.write_bytes(saved.read_bytes()[:-24])
partial.chmod(0o700)
link = work / "alias"
link.symlink_to(saved)
for path, expected, nonce in ((witness, sha, NONCE), (saved, "0" * 64, NONCE),
(saved, sha, "x" * 32), (script, digest(script), NONCE),
(partial, digest(partial), NONCE), (link, sha, NONCE), (work, sha, NONCE)):
result = subprocess.run(args(probe, path, expected, nonce), input=b"", capture_output=True,
timeout=5, cwd=work)
require(result.returncode == 126 and not result.stdout, f"unexpected admission of {path}: {result}")
with open(os.devnull, "rb") as wrong_control:
result = subprocess.run(args(probe, saved, sha), stdin=wrong_control, capture_output=True,
timeout=5, cwd=work)
require(result.returncode == 126 and not result.stdout, "ordinary file accepted as control")
print("Eight invalid image, identity and descriptor configurations refused")
shutil.copyfile(ROOT / "tests/corpus/frontend/gcc-live.cpp", work / "input.cpp")
with subprocess.Popen(args(probe, compiler, digest(compiler), mode="observe"), stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=work) as child:
try:
out, err = child.communicate(timeout=45)
finally:
if child.poll() is None:
child.kill()
child.wait(timeout=3)
require(child.returncode == 0 and not err, f"real compiler exit {child.returncode}: {err!r}")
events = [json.loads(line) for line in out.splitlines()]
require(events and events[0]["kind"] == "hello" and events[0]["pid"] == child.pid
and events[0]["backend"] == "gcc-16.2.0/vls-eval-1", "compiler-origin handshake failed")
require(all(e["nonce"] == NONCE and e["seq"] == i for i, e in enumerate(events)), "invalid event stream")
values = [int(e["value"]["bitsHex"], 16) for e in events
if e["kind"] == "value" and e["value"]["kind"] == "integer"]
require(values == [17, 34, 22, 44] and events[-1]["kind"] == "frontendEnd", f"unexpected returns: {values}")
print("Real sealed cc1plus reported returns 17, 34, 22 and 44")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--probe", type=Path, required=True)
parser.add_argument("--cc1plus", type=Path, required=True)
parser.add_argument("--cc", default="cc")
cli = parser.parse_args()
with tempfile.TemporaryDirectory(prefix="vls-gcc-leaf-") as folder:
verify_leaf(cli.probe.resolve(strict=True), cli.cc1plus.resolve(strict=True), cli.cc, Path(folder))
+217
View File
@@ -0,0 +1,217 @@
"""Exercise the private compiler supervisor, live controls, cleanup and offline replay."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import select
import shutil
import subprocess
import tempfile
import time
ROOT = Path(__file__).resolve().parents[2]
WITNESS = r"""
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(void) {
char mode[32] = {0};
FILE *file = fopen("input.cpp", "r");
if (!file || fscanf(file, "%31s", mode) != 1) return 3;
fclose(file);
dprintf(4, "{\"v\":1,\"nonce\":\"%s\",\"seq\":0,\"kind\":\"hello\","
"\"backend\":\"gcc-16.2.0/vls-eval-1\",\"pid\":%ld,"
"\"capabilities\":[\"integralReturn\",\"cooperativeStep\"],"
"\"kinds\":[\"hello\",\"enter\",\"body\",\"value\",\"cached\",\"stopped\","
"\"resumed\",\"leave\",\"terminal\",\"frontendEnd\"]}\n",
getenv("VLS_GCC_NONCE"), (long)getpid());
if (!strcmp(mode, "partial")) { dprintf(4, "{\"v\":"); return 0; }
if (!strcmp(mode, "flood")) {
char block[4096]; memset(block, 'a', sizeof block);
for (int i=0; i<80; ++i) if (write(2, block, sizeof block) < 0) break;
return 0;
}
if (!strcmp(mode, "descendant")) {
pid_t sub = fork();
if (sub < 0) return 2;
if (sub == 0) { sleep(20); _exit(0); }
dprintf(2, "descendant=%ld\n", (long)sub);
return 0;
}
if (!strcmp(mode, "running")) { sleep(20); return 0; }
return 2;
}
"""
def check(value, message):
if not value:
raise RuntimeError(message)
def digest(path):
with path.open("rb") as source:
return hashlib.file_digest(source, "sha256").hexdigest()
class Client:
def __init__(self, probe, compiler, sha, source, trace, step):
args = [probe, "run", compiler, sha, source, trace, *(["--step"] if step else [])]
self.process = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, bufsize=0)
self.buffer = bytearray()
def __enter__(self):
return self
def __exit__(self, *unused):
if self.process.poll() is None:
self.process.terminate()
try:
self.process.wait(timeout=5)
except subprocess.TimeoutExpired:
self.process.kill()
self.process.wait(timeout=3)
for pipe in (self.process.stdin, self.process.stdout, self.process.stderr):
pipe.close()
def read(self, expected):
deadline = time.monotonic() + 18
while b"\n" not in self.buffer:
left = deadline - time.monotonic()
check(left > 0 and select.select([self.process.stdout], [], [], left)[0],
f"timed out waiting for {expected}")
chunk = os.read(self.process.stdout.fileno(), 8192)
check(chunk, f"probe closed stdout before {expected}")
self.buffer.extend(chunk)
check(len(self.buffer) <= 73728, "oversized probe notice")
line, _, self.buffer = self.buffer.partition(b"\n")
data = json.loads(line)
check(data["kind"] == expected, f"expected {expected}, got {data!r}")
return data
def send(self, control):
self.process.stdin.write((control + "\n").encode("ascii"))
def finish(self, expected, code):
message = self.read("finished")
actual = self.process.wait(timeout=5)
check(message["outcome"] == expected and actual == code, f"unexpected completion: {actual}, {message}")
check(not self.buffer and not self.process.stdout.read(1), "trailing process output")
check(not self.process.stderr.read(8192), "unexpected supervisor stderr")
def replay(probe, trace, seq=None):
cmd = [probe, "replay", trace, *([str(seq)] if seq is not None else [])]
result = subprocess.run(cmd, capture_output=True, timeout=8, check=True)
check(not result.stderr, f"unexpected replay stderr {result.stderr!r}")
return json.loads(result.stdout)
def integral(snapshot):
frame = snapshot["frames"][-1]
value = frame["value"]
check(value["kind"] == "integer" and value["signed"] and value["precision"] == 32,
f"unexpected scalar {value}")
return frame["name"], int(value["bitsHex"], 16)
def stepped(probe, compiler, sha, source, trace, inner, outer, cancel=False):
with Client(probe, compiler, sha, source, trace, True) as client:
start = client.read("started")
nonce, pid = start["nonce"], start["pid"]
stop = client.read("stopped")
seq = stop["stop"]
check(nonce == stop["nonce"] and client.process.poll() is None, "invalid initial stop")
os.kill(pid, 0)
client.send(f"{nonce} {seq} inspect")
live = client.read("inspection")["snapshot"]
check(integral(live) == ("reflected_value", inner), "wrong live inner value")
check(live["stop"] == seq and not live["frontendEnded"], "incorrect live generation")
client.send(f"{'0'*32} {seq} step")
client.read("rejected")
client.send(f"{nonce} {seq + 1} continue")
client.read("rejected")
check(not select.select([client.process.stdout], [], [], .035)[0], "compiler advanced on stale controls")
if cancel:
client.send(f"{nonce} {seq} cancel")
client.finish("cancelled", 125)
view = replay(probe, trace)
check(view["partial"] and view["terminal"] == "cancelled" and integral(view)[1] == inner,
"cancel lost its verified prefix")
return [seq]
client.send(f"{nonce} {seq} step")
stepped_stop = client.read("stopped")["stop"]
check(stepped_stop > seq, "stop generation did not advance")
client.send(f"{nonce} {seq} step")
client.read("rejected")
client.send(f"{nonce} {stepped_stop} inspect")
check(integral(client.read("inspection")["snapshot"]) == ("twice", outer), "wrong live outer value")
client.send(f"{nonce} {stepped_stop} continue")
client.finish("completed", 0)
return [seq, stepped_stop]
def verify(probe, compiler, cc, work):
fixture = work / "user.cpp"
original = (ROOT / "tests/corpus/frontend/gcc-live.cpp").read_text()
selected = work / "private-cc1plus"
shutil.copy2(compiler, selected)
sha = digest(selected)
old, new, cancelled = (work / name for name in ("old.trace", "edited.trace", "cancelled.trace"))
fixture.write_text(original)
stops = stepped(probe, selected, sha, fixture, old, 17, 34)
fixture.write_text(original.replace("Ready = 17", "Ready = 41"))
stepped(probe, selected, sha, fixture, new, 41, 82)
stepped(probe, selected, sha, fixture, cancelled, 41, 82, cancel=True)
selected.unlink()
fixture.unlink()
for seq, value in zip(stops, (17, 34)):
view = replay(probe, old, seq)
check(view["sequence"] == seq and view["stop"] == seq and integral(view)[1] == value,
"offline replay disagrees with the old live value")
check(view["source"] == original and view["compilerSha256"] == sha and view["outcome"] == "completed",
"offline identity or completion differs")
print("Live and offline GCC sessions agree on 17/34 and 41/82, stale controls and cancellation")
incomplete = work / "partial.trace"
incomplete.write_bytes(old.read_bytes()[:-5])
view = replay(probe, incomplete, stops[0])
check(view["partial"] and view["outcome"] is None and integral(view)[1] == 17, "incomplete tail promoted")
witness_c, witness = work / "witness.c", work / "witness"
witness_c.write_text(WITNESS)
subprocess.run([cc, witness_c, "-o", witness], check=True, timeout=30)
witness_sha = digest(witness)
for mode in ("partial", "flood", "descendant", "running"):
fixture.write_text(mode)
journal = work / f"{mode}.vls"
with Client(probe, witness, witness_sha, fixture, journal, mode == "running") as client:
started = client.read("started")
if mode == "running":
client.send(started["nonce"] + " cancel")
client.finish("cancelled", 125)
else:
client.finish("truncated", 126)
state = replay(probe, journal)
check(state["partial"], f"incomplete witness {mode} declared complete")
if mode == "descendant":
pid = int(re.search(r"descendant=(\d+)", state["diagnostics"]).group(1))
check(not Path(f"/proc/{pid}").exists(), "adopted descendant was not reaped")
if mode == "flood":
check(0 < len(state["diagnostics"]) <= 256*1024, "diagnostics escaped the capture limit")
print("Verified truncated input, bounded stderr, running cancellation and leader-first process cleanup")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--probe", type=Path, required=True)
parser.add_argument("--cc1plus", type=Path, required=True)
parser.add_argument("--cc", default="cc")
opts = parser.parse_args()
with tempfile.TemporaryDirectory(prefix="vls-gcc-supervisor-") as directory:
verify(opts.probe.resolve(strict=True), opts.cc1plus.resolve(strict=True), opts.cc, Path(directory))
+122
View File
@@ -0,0 +1,122 @@
"""Run a staged VLS from an empty directory without a tool search path."""
import argparse
import json
from pathlib import Path
import subprocess
import tempfile
def frame(message):
payload = json.dumps({"jsonrpc": "2.0", **message}, ensure_ascii=False).encode()
return f"Content-Length: {len(payload)}\r\n\r\n".encode() + payload
def replies(data):
result = []
while data:
header, data = data.split(b"\r\n\r\n", 1)
if not header.startswith(b"Content-Length: "):
raise ValueError(f"unexpected stdout header {header!r}")
length = int(header.removeprefix(b"Content-Length: "))
if not 0 < length <= len(data):
raise ValueError("truncated LSP response")
result.append(json.loads(data[:length]))
data = data[length:]
return result
def check_install(binary, work, encoding):
def start(args, data=b""):
return subprocess.run([binary, *args], cwd=work, input=data, capture_output=True,
check=True, timeout=10, env={"LC_ALL": "C", "PATH": ""})
version = start(["--version"])
if version.stdout != b"VoidLanguageServer 0.1.0\n" or version.stderr:
raise ValueError("unexpected version output")
document = {"uri": "untitled:installed-server"}
def edit(version, left, right, text):
return {"method": "textDocument/didChange", "params": {
"textDocument": {**document, "version": version}, "contentChanges": [{
"range": {"start": {"line": 0, "character": left},
"end": {"line": 0, "character": right}}, "text": text}]}}
messages = [
{"method": "initialize", "id": 1, "params": {"capabilities": {
"general": {"positionEncodings": [encoding]}}}},
{"method": "initialized", "params": {}},
{"method": "textDocument/didOpen", "params": {"textDocument": {
**document, "version": 1, "languageId": "cpp", "text": "a"}}},
edit(2, 0, 1, "😀"),
edit(3, 1, 1, "b"),
{"method": "textDocument/didClose", "params": {"textDocument": document}},
{"method": "shutdown", "id": 2},
{"method": "exit"},
]
process = start(["--stdio"], b"".join(map(frame, messages)))
responses = replies(process.stdout)
if [r["id"] for r in responses] != [1, 2] or responses[1]["result"] is not None:
raise ValueError(f"unexpected replies: {responses}")
capabilities = responses[0]["result"]["capabilities"]
if capabilities["positionEncoding"] != encoding or capabilities["textDocumentSync"]["change"] != 2:
raise ValueError(f"unexpected initialization: {capabilities}")
witness = "splits a Unicode scalar" if encoding == "utf-8" else "splits a surrogate pair"
if process.stderr.count(b"\n") != 1 or witness.encode() not in process.stderr:
raise ValueError(f"edit did not observe the preceding replacement: {process.stderr!r}")
print(f"{encoding}: installed binary negotiated sync, applied the edit and detected the split")
def check_provider(binary, work, root, database, provider, document):
rows = json.loads(database.read_bytes())
owners = sum((database.parent / row["directory"] / row["file"]).resolve() == document for row in rows)
if not owners:
raise ValueError(f"{database} has no command for {document}")
args = [str(binary), "--stdio"]
if provider == "compdb":
args += ["--workspace-root", str(root), "--provider", "compdb", "--compdb", str(database)]
messages = [
{"method": "initialize", "id": 1, "params": {"capabilities": {}, "workspaceFolders": [
{"uri": root.as_uri(), "name": root.name}]}},
{"method": "initialized", "params": {}},
{"method": "voidLanguageServer/providerStatus", "id": 2, "params": {
"workspaceUri": root.as_uri(), "textDocument": {"uri": document.as_uri()}}},
{"method": "shutdown", "id": 3},
{"method": "exit"},
]
process = subprocess.run(args, cwd=work, input=b"".join(map(frame, messages)),
capture_output=True, check=True, timeout=15, env={"LC_ALL": "C", "PATH": ""})
records = replies(process.stdout)
if process.stderr or [r["id"] for r in records] != [1, 2, 3]:
raise ValueError(f"unexpected provider transcript: {process.stderr!r}, {records!r}")
status = records[1]["result"]
if (status["provider"], status["state"], status["workspaceUri"]) != (provider, "ready", root.as_uri()):
raise ValueError(f"provider not ready: {status!r}")
if (status["contextCount"] != len(rows) or len(status["alternatives"]) != min(owners, 16) or
status.get("alternativesTruncated", False) != (owners > 16) or
status["selected"]["owningTu"] != document.as_uri()):
raise ValueError(f"provider disagrees with {database}: {status!r}")
if provider == "vbs" and status["nativeGeneration"] != database.parent.name:
raise ValueError(f"selected VBS generation changed: {status!r}")
print(f"{provider}: installed server reported {len(rows)} commands for {root.name}, {owners} for {document.name}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("executable", type=Path)
parser.add_argument("--workspace", type=Path, help="workspace used to build the installed server")
parser.add_argument("--vbs-database", type=Path, help="expected selected immutable VBS generation database")
parser.add_argument("--compdb", type=Path, help="comparison build's compilation database")
parser.add_argument("--document", type=Path, default=Path("src/main.cpp"), help="translation unit under the workspace")
args = parser.parse_args()
if any((args.workspace, args.vbs_database, args.compdb)) and not all((args.workspace, args.vbs_database, args.compdb)):
parser.error("--workspace, --vbs-database and --compdb must be supplied together")
binary = args.executable.resolve(strict=True)
with tempfile.TemporaryDirectory(prefix="vls-install-check-") as work:
for encoding in ("utf-8", "utf-16"):
check_install(binary, work, encoding)
if args.workspace:
root = args.workspace.resolve(strict=True)
document = (root / args.document).resolve(strict=True)
for provider, db in (("vbs", args.vbs_database), ("compdb", args.compdb)):
check_provider(binary, work, root, db.resolve(strict=True), provider, document)
+151
View File
@@ -0,0 +1,151 @@
#!/usr/bin/env python3
"""Drive vls-dap --live against the scripted worker: control, inspection, stale rejects."""
import argparse
import json
import os
from pathlib import Path
import select
import subprocess
import tempfile
import time
def check(condition, detail):
if not condition:
raise ValueError(detail)
class Adapter:
def __init__(self, argv):
self.process = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, env={**os.environ, "LC_ALL": "C"})
self.sequence = 0
self.buffer = b""
def send(self, message):
payload = json.dumps(message).encode()
self.process.stdin.write(f"Content-Length: {len(payload)}\r\n\r\n".encode() + payload)
self.process.stdin.flush()
def send_request(self, command, arguments=None):
self.sequence += 1
self.send({"seq": self.sequence, "type": "request", "command": command,
"arguments": arguments or {}})
return self.sequence
def request(self, command, arguments=None, timeout=15):
sequence = self.send_request(command, arguments)
while True:
message = self.read(timeout)
if message.get("type") == "response" and message.get("request_seq") == sequence:
return message
def event(self, name, timeout=15):
deadline = time.monotonic() + timeout
while True:
remaining = deadline - time.monotonic()
check(remaining > 0, f"timed out waiting for the {name} event")
message = self.read(remaining)
if message.get("type") == "event" and message.get("event") == name:
return message
def read(self, timeout):
while b"\r\n\r\n" not in self.buffer:
ready, _, _ = select.select([self.process.stdout], [], [], timeout)
check(ready, "DAP response deadline expired")
chunk = os.read(self.process.stdout.fileno(), 65536)
check(chunk, "the adapter closed stdout")
self.buffer += chunk
header, rest = self.buffer.split(b"\r\n\r\n", 1)
length = int(header.removeprefix(b"Content-Length: "))
while len(rest) < length:
chunk = os.read(self.process.stdout.fileno(), 65536)
check(chunk, "truncated DAP response")
rest += chunk
body, self.buffer = rest[:length], rest[length:]
return json.loads(body)
def close(self):
try:
self.request("disconnect")
except (OSError, ValueError, TimeoutError):
pass
try:
self.process.stdin.close()
except OSError:
pass
try:
self.process.wait(timeout=10)
except subprocess.TimeoutExpired:
self.process.kill()
self.process.wait()
def run(adapter, worker):
with tempfile.TemporaryDirectory(prefix="vls-live-dap-") as temp:
root = Path(temp)
source = root / "normal.cpp"
source.write_text("int value = 17;\n", encoding="utf-8")
trace = root / "session.vls"
client = Adapter([str(adapter), "--live", str(worker), "/private/cc1plus",
"a" * 64, str(source), str(trace)])
try:
initialized = client.request("initialize", {"adapterID": "vls"})
check(initialized["success"], initialized)
client.event("initialized")
client.send_request("launch", {})
client.request("configurationDone", {})
stopped = client.event("stopped")
check(stopped["body"]["threadId"] == 1, stopped)
threads = client.request("threads")
check(len(threads["body"]["threads"]) == 1, threads)
stack = client.request("stackTrace", {"threadId": 1})
check("body" in stack, stack)
frame = stack["body"]["stackFrames"][0]
check(frame["name"] == "fixture_frame" and frame["line"] == 1, frame)
scopes = client.request("scopes", {"frameId": frame["id"]})
reference = scopes["body"]["scopes"][0]["variablesReference"]
variables = client.request("variables", {"variablesReference": reference})
names = {variable["name"]: variable["value"] for variable in variables["body"]["variables"]}
check(names.get("source") == "input.cpp" and names.get("depth") == "0",
f"unexpected live variables: {names}")
check(names.get("Result") == "17", f"typed value was not projected: {names}")
breakpoints = client.request("setBreakpoints",
{"source": {"path": "input.cpp"}, "lines": [2, 99]})
check(breakpoints["success"] and
len(breakpoints["body"]["breakpoints"]) == 2, breakpoints)
moved = client.request("next")
check(moved["success"], moved)
stopped_event = client.event("stopped")
check(stopped_event["body"].get("hitBreakpointIds") == [2], stopped_event)
stale = client.request("scopes", {"frameId": frame["id"]})
check(stale["success"] is False and "stale" in stale["message"], stale)
stack = client.request("stackTrace", {"threadId": 1})
check(stack["body"]["stackFrames"][0]["line"] == 2, stack)
paused = client.request("pause")
check(paused["success"] is False, paused)
finished = client.request("continue")
check(finished["success"], finished)
client.event("terminated")
finally:
client.close()
print("live DAP passed: stopped/typed inspection/breakpoints/step/stale rejection/continue, pause refused")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--adapter", required=True, type=Path)
parser.add_argument("--worker", required=True, type=Path)
options = parser.parse_args()
run(options.adapter.resolve(strict=True), options.worker.resolve(strict=True))
if __name__ == "__main__":
try:
main()
except (OSError, ValueError, subprocess.SubprocessError) as exc:
raise SystemExit(f"verify-live-dap: {exc}")
+109
View File
@@ -0,0 +1,109 @@
-- Run with nvim --headless -u NONE -i NONE -l tests/native/NeovimClient.lua.
local server = assert(vim.env.VLS_SERVER, "set VLS_SERVER to the installed vls")
local adapter = assert(vim.env.VLS_DAP, "set VLS_DAP to the installed vls-dap")
local trace = assert(vim.env.VLS_TRACE, "set VLS_TRACE to integral-17.vls")
local plugin = assert(vim.env.VLS_NVIM_DAP, "set VLS_NVIM_DAP to the nvim-dap checkout")
local repository = vim.fn.fnamemodify(debug.getinfo(1, "S").source:sub(2), ":p:h:h:h")
vim.opt.runtimepath:prepend(plugin)
vim.opt.runtimepath:prepend(repository .. "/clients/neovim")
local vls = require("vls")
vls.setup({ server = server, dap_adapter = adapter })
dofile(repository .. "/clients/neovim/plugin/vls.lua")
local dap = require("dap")
local function wait_for(label, predicate, timeout)
assert(vim.wait(timeout or 10000, predicate, 25), "timed out waiting for " .. label)
end
local work = vim.fn.tempname()
assert(vim.fn.mkdir(work, "p") == 1)
local file = work .. "/unit.cpp"
assert(vim.fn.writefile({ "int value = 17;", "int read() { return value; }" }, file) == 0)
vim.cmd.edit(vim.fn.fnameescape(file))
local buffer = vim.api.nvim_get_current_buf()
vim.bo[buffer].filetype = "cpp"
local client, err = vls.start(buffer)
assert(client, err)
wait_for("LSP initialization", function() return client.initialized end)
local status, status_err = vls.status(buffer)
assert(not status_err and type(status.state) == "string", vim.inspect({ status, status_err }))
local analysis, analysis_err = vls.analysis_status(buffer)
assert(not analysis_err and type(analysis.state) == "string",
vim.inspect({ analysis, analysis_err }))
local messages = {}
local original_notify = vim.notify
vim.notify = function(message) table.insert(messages, message) end
vim.cmd("VlsStatus")
vim.notify = original_notify
wait_for("status notification", function() return #messages > 0 end)
assert(messages[1]:find("VoidLanguageServer provider status", 1, true), messages[1])
local stops = 0
dap.listeners.after.event_stopped.vls_client_test = function(_, event)
assert(event.threadId == 1)
stops = stops + 1
end
local replay, replay_err = vls.replay(trace)
assert(replay, replay_err)
wait_for("first replay stop", function() return stops == 1 and dap.session() ~= nil end)
local session = assert(dap.session())
local function request(method, arguments)
local done, failure, body = false, nil, nil
session:request(method, arguments, function(problem, result)
failure, body, done = problem, result, true
end)
wait_for(method, function() return done end)
assert(not failure, vim.inspect(failure))
return body
end
local function read_value()
local frame = assert(request("stackTrace", { threadId = 1 }).stackFrames[1])
local scope = request("scopes", { frameId = frame.id }).scopes[1]
local variables = request("variables", { variablesReference = scope.variablesReference })
for _, variable in ipairs(variables.variables) do
if variable.name == "Result" then
return variable.value, frame.name
end
end
error("recorded result is missing")
end
local value, name = read_value()
assert(value == "17" and name == "reflected_value", vim.inspect({ value, name }))
local first = assert(vls.session())
assert(type(first.sessionId) == "string" and type(first.generation) == "number")
local page = assert(vls.timeline(0, 4))
assert(page.sessionId == first.sessionId and #page.events > 0, vim.inspect(page))
local source = assert(vls.source())
assert(vim.fn.sha256(source) == first.sourceSha256)
dap.continue()
wait_for("second replay stop", function() return stops == 2 and session.stopped_thread_id == 1 end)
value, name = read_value()
assert(value == "34" and name == "twice", vim.inspect({ value, name }))
local stale, stale_err = vls.timeline()
assert(not stale and stale_err and stale_err:find("stale", 1, true),
vim.inspect({ stale, stale_err }))
local second = assert(vls.session())
assert(second.generation > first.generation)
local page2 = assert(vls.timeline(0, 2))
assert(page2.generation == second.generation)
vim.cmd("VlsTimeline 0 2")
local view = vim.api.nvim_get_current_buf()
local lines = vim.api.nvim_buf_get_lines(view, 0, -1, false)
assert(lines[1] and lines[1]:find("session", 1, true), vim.inspect(lines))
vim.cmd("close")
vls.stop()
wait_for("replay shutdown", function() return dap.session() == nil end)
client:stop()
wait_for("server shutdown", function()
return #vim.lsp.get_clients({ name = "VoidLanguageServer" }) == 0
end)
print("Neovim client passed: LSP status, replay session, timeline, source and stale rejection")
+56
View File
@@ -0,0 +1,56 @@
-- Exercise a real unsaved edit through the built-in Neovim LSP client.
local server = assert(vim.env.VLS_SERVER, "set VLS_SERVER to the installed vls")
local profile_path = assert(vim.env.VLS_GCC_PROFILE, "set VLS_GCC_PROFILE to the prepared stock GCC profile")
local profile = vim.json.decode(table.concat(vim.fn.readfile(profile_path), "\n"))
local root = vim.fn.tempname()
assert(vim.fn.mkdir(root) == 1)
local file = root .. "/unit.cpp"
local client
local function wait_for(label, predicate)
assert(vim.wait(15000, predicate, 25), "timed out waiting for " .. label)
end
local function run()
local original = "int read() { return value; }"
assert(vim.fn.writefile({ "int value = 17;", original }, file) == 0)
local row = { file = file, directory = root,
arguments = { profile.driver.path, "-std=c++26", "-freflection", "-c", file } }
assert(vim.fn.writefile({ vim.json.encode({ row }) }, root .. "/compile_commands.json") == 0)
vim.cmd.edit(vim.fn.fnameescape(file))
local buf = vim.api.nvim_get_current_buf()
vim.bo[buf].filetype = "cpp"
local id = assert(vim.lsp.start({
name = "VoidLanguageServer",
cmd = { server, "--stdio", "--workspace-root", root, "--provider", "compdb", "--gcc-profile", profile_path },
root_dir = root,
flags = { debounce_text_changes = 10 },
}, { bufnr = buf }))
client = assert(vim.lsp.get_client_by_id(id))
wait_for("initialization", function() return client.initialized end)
local params = { textDocument = { uri = vim.uri_from_bufnr(buf) }, workspaceUri = vim.uri_from_fname(root) }
local reply = assert(client:request_sync("voidLanguageServer/providerStatus", params, 5000, buf))
assert(not reply.err and reply.result.state == "ready" and reply.result.contextCount == 1,
vim.inspect(reply))
assert(reply.result.selected.owningTu == params.textDocument.uri)
local start = assert(original:find("value", 1, true)) - 1
vim.api.nvim_buf_set_text(buf, 1, start, 1, start + 5, { "missing" })
wait_for("stock compiler diagnosis", function()
for _, d in ipairs(vim.diagnostic.get(buf)) do
if d.source == "gcc" and d.message:find("missing", 1, true) and d.lnum == 1
and d.col == start and d.end_col == start + 7 then return true end
end
end)
vim.api.nvim_buf_set_text(buf, 1, start, 1, start + 7, { "value" })
wait_for("diagnostic clear", function() return #vim.diagnostic.get(buf) == 0 end)
assert(vim.fn.readfile(file)[2] == original)
end
local ok, err = xpcall(run, debug.traceback)
if client then
client:stop()
if not vim.wait(5000, function() return client:is_stopped() end) then client:stop(true) end
end
vim.fn.delete(root, "rf")
assert(ok, err)
print("Neovim LSP passed: selected compile command, seven-byte stock GCC diagnostic and clear")
+85
View File
@@ -0,0 +1,85 @@
-- Run with nvim --headless -u NONE -i NONE -l tests/native/NeovimRename.lua.
local repository = vim.fn.fnamemodify(debug.getinfo(1, "S").source:sub(2), ":p:h:h:h")
vim.opt.runtimepath:prepend(repository .. "/clients/neovim")
local vls = require("vls")
local root = vim.fn.tempname()
vim.fn.mkdir(root .. "/left", "p")
vim.fn.mkdir(root .. "/right", "p")
local left = root .. "/left/unit.cpp"
local right = root .. "/right/header.hpp"
vim.fn.writefile({ "int value = 17;", "int read() { return value; }" }, left)
vim.fn.writefile({ "int value = 3;" }, right)
local function load(path)
vim.cmd.edit(vim.fn.fnameescape(path))
return vim.api.nvim_get_current_buf()
end
local left_buffer = load(left)
local right_buffer = load(right)
local function snapshot(buffer)
return table.concat(vim.api.nvim_buf_get_lines(buffer, 0, -1, false), "\n")
end
local function edit(buffer, line, spelling, replacement)
local text = vim.api.nvim_buf_get_lines(buffer, line, line + 1, false)[1]
local start = assert(text:find(spelling, 1, true)) - 1
return { range = { start = { line = line, character = start },
["end"] = { line = line, character = start + #spelling } },
newText = replacement }
end
local function changes()
return {
[vim.uri_from_bufnr(left_buffer)] = {
edit(left_buffer, 0, "value", "count"),
edit(left_buffer, 1, "value", "count"),
},
[vim.uri_from_bufnr(right_buffer)] = {
edit(right_buffer, 0, "value", "count"),
},
}
end
local before_left, before_right = snapshot(left_buffer), snapshot(right_buffer)
assert(vls.apply_workspace_edit(changes()))
assert(snapshot(left_buffer):find("count", 1, true))
assert(snapshot(right_buffer):find("count", 1, true))
vim.api.nvim_buf_set_lines(left_buffer, 0, -1, false,
{ "int value = 17;", "int read() { return value; }" })
vim.api.nvim_buf_set_lines(right_buffer, 0, -1, false, { "int value = 3;" })
vim.bo[left_buffer].modified = false
vim.bo[right_buffer].modified = false
assert(snapshot(left_buffer) == before_left and snapshot(right_buffer) == before_right)
-- Inject a failure in the second buffer write and require a full rollback.
local original = vim.api.nvim_buf_set_text
local calls = 0
vim.api.nvim_buf_set_text = function(...)
calls = calls + 1
if calls == 2 then
error("injected buffer failure")
end
return original(...)
end
local ok, err = vls.apply_workspace_edit(changes())
vim.api.nvim_buf_set_text = original
assert(not ok and err:find("injected", 1, true), vim.inspect({ ok, err }))
assert(snapshot(left_buffer) == before_left and snapshot(right_buffer) == before_right)
assert(not vim.bo[left_buffer].modified and not vim.bo[right_buffer].modified)
-- An invalid range is rejected before any buffer is touched.
local invalid = changes()
invalid[vim.uri_from_bufnr(right_buffer)][1].range.start.line = 99
assert(not vls.apply_workspace_edit(invalid))
assert(snapshot(left_buffer) == before_left and snapshot(right_buffer) == before_right)
-- A read-only buffer refuses the whole transaction.
vim.bo[right_buffer].modifiable = false
assert(not vls.apply_workspace_edit(changes()))
vim.bo[right_buffer].modifiable = true
assert(snapshot(left_buffer) == before_left and snapshot(right_buffer) == before_right)
print("Neovim rename passed: atomic apply, injected-failure rollback, invalid range and read-only refusal")
+68
View File
@@ -0,0 +1,68 @@
-- Run with nvim --headless -u NONE -i NONE -l tests/native/NeovimReplay.lua.
local plugin = assert(vim.env.VLS_NVIM_DAP, "set VLS_NVIM_DAP to the nvim-dap checkout")
local adapter = assert(vim.env.VLS_DAP, "set VLS_DAP to the adapter executable")
local trace = assert(vim.env.VLS_TRACE, "set VLS_TRACE to integral-17.vls")
vim.opt.runtimepath:prepend(plugin)
local dap = require("dap")
dap.adapters.vls = { type = "executable", command = adapter, args = { "--replay", trace } }
local stops = 0
dap.listeners.after.event_stopped.vls_test = function(_, event)
assert(event.threadId == 1)
stops = stops + 1
end
local function wait_for(label, predicate)
assert(vim.wait(5000, predicate, 10), "timed out waiting for " .. label)
end
local function request(session, method, args)
local done, err, body = false, nil, nil
session:request(method, args, function(problem, result)
err, body, done = problem, result, true
end)
wait_for(method, function() return done end)
assert(not err, vim.inspect(err))
return body
end
local function read_value(session)
local stack = request(session, "stackTrace", { threadId = 1 })
local frame = assert(stack.stackFrames[1])
assert(not frame.source and frame.line == 0)
local scope = request(session, "scopes", { frameId = frame.id }).scopes[1]
local reply = request(session, "variables", { variablesReference = scope.variablesReference })
for _, var in ipairs(reply.variables) do
if var.name == "Result" then return var.value, frame.name end
end
error("recorded result is missing")
end
dap.run({ type = "vls", name = "C++ constant evaluation", request = "launch" })
wait_for("first stop", function()
return stops == 1 and dap.session() and dap.session().stopped_thread_id == 1
end)
local session = assert(dap.session())
local value, name = read_value(session)
assert(value == "17" and name == "reflected_value")
local first = request(session, "vls/session")
local query = { schemaVersion = first.schemaVersion, sessionId = first.sessionId,
generation = first.generation, start = 5, count = 4 }
local page = request(session, "vls/timeline", query)
assert(page.events[3].acknowledgedAction == "step" and page.events[3].acknowledgedStop == 6)
local source = request(session, "source", { sourceReference = first.sourceReference })
assert(vim.fn.sha256(source.content) == first.sourceSha256)
dap.continue()
wait_for("outer return", function() return stops == 2 and session.stopped_thread_id == 1 end)
value, name = read_value(session)
assert(value == "34" and name == "twice")
local second = request(session, "vls/session")
assert(second.sessionId == first.sessionId and second.eventSequence == 10)
assert(second.generation > first.generation)
local disconnected = false
session:disconnect({}, function(err)
assert(not err, vim.inspect(err))
disconnected = true
end)
wait_for("disconnect", function() return disconnected and dap.session() == nil end)
print("Neovim replay passed: reflected_value=17, twice=34, captured source and acknowledged timeline")
+273
View File
@@ -0,0 +1,273 @@
"""Exercise tools/prepare-voidlibrary with Git and source stores owned by the fixture."""
from concurrent.futures import ThreadPoolExecutor, wait
import hashlib
import json
import os
from pathlib import Path
import runpy
import shlex
import shutil
import signal
import stat
import subprocess
import tempfile
import time
import unittest
from unittest.mock import patch
TOOL = Path(__file__).resolve().parents[2] / "tools/prepare-voidlibrary"
HEADERS = """
Async/Task Configuration/Argparse Core/Hash Crypto/Crypto Data/StrictJson Functional/Result
Math/Numeric System/Process Testing/Test Testing/Detail/Registry Text/Url Time/Clock Unicode/Utf
Detail/Enum Log/Log Stacktrace/Color
""".split()
SOURCES = "Configuration/Argparse Crypto/Crypto LogState/State System/Process Testing/Main".split()
INCLUDED = ({f"include/Void/{name}.hpp" for name in HEADERS} |
{f"src/{name}.cpp" for name in SOURCES} | {"src/Crypto/BuiltinHash.hpp"})
EXCLUDED = {
".gitattributes", "src/Core/module.cmake", "include/Void/Core/.private.hpp",
"include/Void/Other/Header.hpp", "include/Void/System/AsyncProcess.hpp", "README.md",
}
JSON_HEADER = "include/Void/Data/StrictJson.hpp"
class PreparationTests(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.root = Path(temp.name)
self.tool = self.root / "project/tools/prepare-voidlibrary"
self.tool.parent.mkdir(parents=True)
shutil.copy2(TOOL, self.tool)
self.store = self.tool.parents[1] / "build/voidlibrary"
self.current = self.store / "current"
self.source = self.root / "checkout"
self.source.mkdir()
self.env = {k: v for k, v in os.environ.items()
if not k.startswith("GIT_") and k != "VLS_VOID_SOURCE_DIR"}
self.env.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull)
self.git("init", "--quiet", "--template=")
for name in INCLUDED | EXCLUDED:
self.write(name, f"// {name}\n")
self.write(".gitattributes", "*.hpp filter=fixture\n")
self.git("add", "--", *sorted(INCLUDED | EXCLUDED))
self.git("commit", "-qm", "synthetic recipe inputs")
self.revision = self.git("rev-parse", "HEAD").strip()
def git(self, *args):
return subprocess.check_output(
["git", "-c", "core.hooksPath=/dev/null", "-c", "user.name=Fixture",
"-c", "user.email=fixture@invalid", "-C", self.source, *args],
text=True, env=self.env,
)
def write(self, path, data):
dest = self.source / path
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_text(data, encoding="utf-8")
def cli(self, *args, env=None):
return subprocess.run([self.tool, *args], env=self.env | (env or {}), capture_output=True,
text=True, timeout=30)
def prepare(self, source=None):
result = self.cli("--source", source or self.source)
self.assertEqual(result.returncode, 0, result.stderr)
return Path(result.stdout.strip())
def failed_update(self, target):
result = self.cli("--source", self.source)
self.assertNotEqual(result.returncode, 0)
self.assertEqual(self.current.resolve(strict=True), target)
return result.stderr
def check_generation(self, target):
metadata = (target / "provenance.json").read_bytes()
self.assertEqual(target.name, hashlib.sha256(metadata).hexdigest())
self.assertEqual(target.parent, self.store / "sources")
self.assertLessEqual(len(metadata), 32768)
self.assertTrue((target / "src/Core").is_dir())
self.assertFalse(os.path.lexists(target / "build.cpp"))
return json.loads(metadata)
def test_allowlist_provenance_and_duplicate(self):
self.git("config", "filter.fixture.clean", "false")
self.git("config", "filter.fixture.smudge", "false")
self.git("config", "filter.fixture.required", "true")
self.write("src/System/Untracked.cpp", "untracked canary")
self.write("build.cpp", "untracked descriptor")
index = self.source / ".git/index"
before = (index.stat().st_mtime_ns, index.read_bytes())
target = self.prepare()
self.assertEqual(os.readlink(self.current), f"sources/{target.name}")
info = self.check_generation(target)
self.assertEqual(info["source_kind"], "local")
self.assertEqual(info["source_path"], str(self.source))
self.assertEqual(info["revision"], self.revision)
self.assertFalse(info["dirty"])
files = {p.relative_to(target).as_posix() for p in target.rglob("*") if p.is_file()}
self.assertEqual(files, INCLUDED | {"provenance.json"})
digest = hashlib.sha256()
for name in sorted(INCLUDED):
entry = target / name
self.assertEqual(stat.S_IMODE(entry.stat().st_mode), 0o444)
digest.update(name.encode() + b"\0" + hashlib.sha256(entry.read_bytes()).digest())
self.assertEqual(digest.hexdigest(), info["content_sha256"])
self.assertEqual(stat.S_IMODE(target.stat().st_mode), 0o555)
again = self.cli(env={"VLS_VOID_SOURCE_DIR": str(self.source)})
self.assertEqual(again.returncode, 0, again.stderr)
self.assertEqual(Path(again.stdout.strip()), target)
self.write(JSON_HEADER, "raw edited header with rejecting Git filters")
self.assertTrue(self.check_generation(self.prepare())["dirty"])
self.assertEqual((index.stat().st_mtime_ns, index.read_bytes()), before)
def test_dirty_sources_staged_additions_and_prior_build(self):
previous = self.prepare().resolve(strict=True)
old_data = (previous / JSON_HEADER).read_bytes()
self.write(JSON_HEADER, "// tracked local edit\n")
self.write("src/System/Platform/Extension.cpp", "// staged local source\n")
self.git("add", "--", "src/System/Platform/Extension.cpp")
target = self.prepare()
info = self.check_generation(target)
self.assertTrue(info["dirty"])
self.assertEqual(info["revision"], self.revision)
self.assertNotEqual(info["content_sha256"], self.check_generation(previous)["content_sha256"])
self.assertEqual((target / JSON_HEADER).read_text(), "// tracked local edit\n")
self.assertTrue((target / "src/System/Platform/Extension.cpp").is_file())
self.assertFalse((previous / "src/System/Platform/Extension.cpp").exists())
self.assertEqual((previous / JSON_HEADER).read_bytes(), old_data)
def test_unsupported_tracked_translation_unit_preserves_previous_generation(self):
previous = self.prepare()
name = "src/System/Window Helpers.cpp"
self.write(name, "// valid source with an unsupported spelling\n")
self.git("add", "--", name)
self.assertIn("unsupported tracked translation unit", self.failed_update(previous))
def test_descriptor_rejected_in_index_and_head(self):
previous = self.prepare()
self.write("build.cpp", "synthetic descriptor")
self.git("add", "--", "build.cpp")
self.assertIn("tracked root build.cpp", self.failed_update(previous))
self.git("commit", "-qm", "synthetic descriptor")
self.git("rm", "-q", "--", "build.cpp")
self.assertIn("tracked root build.cpp", self.failed_update(previous))
def test_rejects_links_missing_inputs_and_unstable_capture(self):
previous = self.prepare()
data = self.source / "include/Void/Data"
moved = self.root / "moved"
data.rename(moved)
data.symlink_to(moved, target_is_directory=True)
self.failed_update(previous)
data.unlink()
moved.rename(data)
leaf = self.source / JSON_HEADER
leaf.unlink()
self.failed_update(previous)
leaf.symlink_to(self.root / "absent")
self.failed_update(previous)
self.git("add", "--", JSON_HEADER)
self.assertIn("link", self.failed_update(previous))
leaf.unlink()
self.write(JSON_HEADER, "regular again")
self.git("update-index", "--cacheinfo", f"160000,{self.revision},{JSON_HEADER}")
self.assertIn("link", self.failed_update(previous))
oid = self.git("rev-parse", "HEAD:" + JSON_HEADER).strip()
self.git("update-index", "--cacheinfo", f"100644,{oid},{JSON_HEADER}")
mod = runpy.run_path(str(self.tool))
read_local = mod["local_file"]
def changing_file(root, path):
result = read_local(root, path)
if path == JSON_HEADER and result[0] == b"regular again":
self.write(path, "changed after the first read")
return result
with patch.dict(mod["prepare"].__globals__, local_file=changing_file):
with self.assertRaisesRegex(mod["PreparationError"], "changed during preparation"):
mod["prepare"](self.source)
self.assertEqual(self.current.resolve(strict=True), previous)
def test_concurrent_publications_and_failed_fetch(self):
first = self.prepare()
second_source = self.root / "second-checkout"
shutil.copytree(self.source, second_source)
(second_source / JSON_HEADER).write_text("second source")
with ThreadPoolExecutor(max_workers=4) as pool:
pending = [pool.submit(self.prepare, src) for src in [self.source, second_source] * 4]
while True:
self.check_generation(self.current.resolve(strict=True))
if not wait(pending, timeout=0.005).not_done:
break
targets = {future.result() for future in pending}
self.assertEqual(len(targets), 2)
self.assertEqual(set((self.store / "sources").iterdir()), targets)
self.assertIn(first, targets)
previous = self.current.resolve(strict=True)
trap = self.root / "offline"
trap.mkdir()
shim = trap / "git"
shim.write_text("#!/bin/sh\nfor arg do\n if [ \"$arg\" = fetch ]; then\n"
" echo synthetic-fetch-diagnostic >&2\n exit 76\n fi\ndone\n"
f"exec {shlex.quote(shutil.which('git'))} \"$@\"\n")
shim.chmod(0o755)
result = self.cli(env={"PATH": f"{trap}:{self.env['PATH']}"})
self.assertNotEqual(result.returncode, 0)
self.assertIn("git fetch failed (exit 76)", result.stderr)
self.assertNotIn("synthetic-fetch-diagnostic", result.stderr)
self.assertEqual(self.current.resolve(strict=True), previous)
self.check_generation(first)
def test_interrupted_capture_can_retry(self):
previous = self.prepare()
self.write(JSON_HEADER, "new generation")
trap = self.root / "interruption"
trap.mkdir()
first, ready = trap / "first", trap / "ready"
# Pause the second index read, after the new files are staged and before
# publication. Terminate the whole fixture process group at that point.
shim = trap / "git"
shim.write_text("#!/bin/sh\nfor arg do\n if [ \"$arg\" = ls-files ]; then\n"
f" if [ -f {shlex.quote(str(first))} ]; then\n"
f" touch {shlex.quote(str(ready))}\n exec sleep 20\n fi\n"
f" touch {shlex.quote(str(first))}\n fi\ndone\n"
f"exec {shlex.quote(shutil.which('git'))} \"$@\"\n")
shim.chmod(0o755)
with subprocess.Popen([self.tool, "--source", self.source], start_new_session=True,
env=self.env | {"PATH": f"{trap}:{self.env['PATH']}"}) as proc:
try:
timeout = time.monotonic() + 5
while not ready.exists() and proc.poll() is None and time.monotonic() < timeout:
time.sleep(0.005)
self.assertTrue(ready.exists())
finally:
if proc.poll() is None:
os.killpg(proc.pid, signal.SIGKILL)
self.assertEqual(proc.wait(timeout=5), -signal.SIGKILL)
self.assertEqual(self.current.resolve(strict=True), previous)
self.assertTrue(self.check_generation(self.prepare())["dirty"])
self.assertFalse(self.check_generation(previous)["dirty"])
def test_rejects_unowned_layout_or_damaged_generation(self):
previous = self.prepare()
# Simulate a damaged store in an isolated fixture.
previous.chmod(0o755)
(previous / "build.cpp").write_text("unexpected fixture entry")
previous.chmod(0o555)
self.assertIn("unexpected entries", self.failed_update(previous))
sources = self.store / "sources"
moved = self.root / "moved-sources"
sources.rename(moved)
sources.symlink_to(moved, target_is_directory=True)
result = self.cli("--source", self.source)
self.assertNotEqual(result.returncode, 0)
self.assertIn("owned directory", result.stderr)
if __name__ == "__main__":
unittest.main()
+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())
+274
View File
@@ -0,0 +1,274 @@
#!/usr/bin/env python3
"""Exercise stock-observer hover and definition through a real stdio LSP session."""
import argparse
import json
import os
from pathlib import Path
import select
import subprocess
import tempfile
import time
TU = Path("src/Documents/DocumentSnapshot.cpp")
def check(condition, detail):
if not condition:
raise ValueError(detail)
def utf16_position(text, offset):
line = text.count("\n", 0, offset)
start = text.rfind("\n", 0, offset) + 1
return line, len(text[start:offset].encode("utf-16-le")) // 2
def frame(message):
payload = json.dumps({"jsonrpc": "2.0", **message}, ensure_ascii=False).encode()
return f"Content-Length: {len(payload)}\r\n\r\n".encode() + payload
class Session:
def __init__(self, argv, cwd, stderr):
self.process = subprocess.Popen(argv, cwd=cwd, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=stderr,
env={**os.environ, "LC_ALL": "C"})
self.sequence = 0
self.buffer = b""
def send(self, message):
self.process.stdin.write(frame(message))
self.process.stdin.flush()
def notify(self, method, params):
self.send({"method": method, "params": params})
def request(self, method, params, timeout=90):
self.sequence += 1
self.send({"id": self.sequence, "method": method, "params": params})
deadline = time.monotonic() + timeout
while True:
message = self.read(deadline - time.monotonic())
if message.get("id") == self.sequence:
return message
def read(self, timeout):
if timeout <= 0:
raise TimeoutError("LSP response deadline expired")
while b"\r\n\r\n" not in self.buffer:
ready, _, _ = select.select([self.process.stdout], [], [], timeout)
if not ready:
raise TimeoutError("LSP response deadline expired")
chunk = os.read(self.process.stdout.fileno(), 65536)
check(chunk, "the server closed stdout")
self.buffer += chunk
header, rest = self.buffer.split(b"\r\n\r\n", 1)
length = int(header.removeprefix(b"Content-Length: "))
while len(rest) < length:
chunk = os.read(self.process.stdout.fileno(), 65536)
check(chunk, "truncated LSP response")
rest += chunk
body, self.buffer = rest[:length], rest[length:]
return json.loads(body)
def close(self):
try:
self.request("shutdown", None)
self.notify("exit", None)
except (OSError, TimeoutError, ValueError):
pass
try:
self.process.stdin.close()
except OSError:
pass
try:
self.process.wait(timeout=10)
except subprocess.TimeoutExpired:
self.process.kill()
self.process.wait()
def await_analysis(session, uri, expected_version=None, timeout=120):
deadline = time.monotonic() + timeout
last = None
while time.monotonic() < deadline:
reply = session.request("voidLanguageServer/analysisStatus",
{"textDocument": {"uri": uri}}, timeout=30)
result = reply.get("result") or {}
last = result
state = result.get("state")
version = result.get("version")
if state == "unavailable":
raise ValueError(f"analysis unavailable: {result.get('detail')}")
if state in ("ready", "partial") and (
expected_version is None or version == expected_version):
return result
time.sleep(0.2)
raise ValueError(f"analysis did not finish: {last}")
def await_module_scan(session, uri, timeout=180):
deadline = time.monotonic() + timeout
last = None
while time.monotonic() < deadline:
reply = session.request("voidLanguageServer/analysisStatus",
{"textDocument": {"uri": uri}}, timeout=30)
result = reply.get("result") or {}
last = result.get("moduleScan")
if last and last.get("state") in ("ready", "partial"):
return last
if last and last.get("state") in ("failed", "unavailable", "cancelled"):
raise ValueError(f"module scan did not complete: {last} status={result}")
time.sleep(0.2)
raise ValueError(f"module scan did not finish: {last}")
def overload_lines(header):
lines = header.read_text(encoding="utf-8").splitlines()
found = {}
for number, line in enumerate(lines, 1):
if "fnv1a64(std::string_view s)" in line:
found["string_view"] = number
if "fnv1a64(std::span<const std::byte> data)" in line:
found["byte_span"] = number
check(set(found) == {"string_view", "byte_span"}, f"missing overloads in {header}")
return found
def run(server, profile, workspace, header):
text = (workspace / TU).read_text(encoding="utf-8")
call = "Void::Hash::fnv1a64(text)"
check(text.count(call) == 1, "the real Void overload witness changed")
start = text.index(call)
name_start = start + len("Void::Hash::")
line, character = utf16_position(text, name_start)
argument = start + len("Void::Hash::fnv1a64(")
argument_line, argument_character = utf16_position(text, argument)
uri = (workspace / TU).as_uri()
lines = overload_lines(header)
with tempfile.TemporaryFile() as errors:
session = Session([str(server), "--stdio", "--workspace-root", str(workspace),
"--gcc-profile", str(profile)], workspace, errors)
try:
initialized = session.request("initialize", {
"processId": None, "capabilities": {},
"workspaceFolders": [{"uri": workspace.as_uri(), "name": workspace.name}]})
capabilities = initialized["result"]["capabilities"]
check(capabilities.get("hoverProvider") and capabilities.get("definitionProvider"),
f"observer capabilities are not advertised: {capabilities}")
session.notify("initialized", {})
session.notify("textDocument/didOpen", {"textDocument": {
"uri": uri, "languageId": "cpp", "version": 1, "text": text}})
status = await_analysis(session, uri, expected_version=1)
position = {"line": line, "character": character}
hover = session.request("textDocument/hover",
{"textDocument": {"uri": uri}, "position": position})
check(hover.get("result"), f"no hover fact: {hover} status={status}")
contents = hover["result"]["contents"]["value"]
check("fnv1a64" in contents and "string_view" in contents,
f"unexpected hover contents: {contents}")
definition = session.request("textDocument/definition",
{"textDocument": {"uri": uri}, "position": position})
location = definition.get("result")
check(location and location["uri"].endswith("Void/Core/Hash.hpp"),
f"wrong definition: {definition}")
check(location["range"]["start"]["line"] + 1 == lines["string_view"],
f"string_view overload not selected: {location} vs {lines}")
session.notify("textDocument/didChange", {
"textDocument": {"uri": uri, "version": 2},
"contentChanges": [{
"range": {"start": {"line": argument_line, "character": argument_character},
"end": {"line": argument_line,
"character": argument_character + len("text")}},
"text": "std::as_bytes(std::span{text})"}]})
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
running = session.request("voidLanguageServer/analysisStatus",
{"textDocument": {"uri": uri}}, timeout=30)
if (running.get("result") or {}).get("state") == "running":
break
time.sleep(0.02)
else:
raise ValueError("the second revision never started running")
edited = (text[:argument] + "std::as_bytes(std::span{text})" +
text[argument + len("text"):])
session.notify("textDocument/didChange", {
"textDocument": {"uri": uri, "version": 3},
"contentChanges": [{
"range": {"start": {"line": edited.count("\n"), "character": 0},
"end": {"line": edited.count("\n"), "character": 0}},
"text": "// scheduler coalescing\n"}]})
status = await_analysis(session, uri, expected_version=3)
check(status.get("scheduler", {}).get("cancelled", 0) >= 1,
f"the superseded revision was not cancelled: {status.get('scheduler')}")
definition = session.request("textDocument/definition",
{"textDocument": {"uri": uri}, "position": position})
location = definition.get("result")
check(location and location["range"]["start"]["line"] + 1 == lines["byte_span"],
f"byte_span overload not selected after the edit: {definition} vs {lines}")
scan = await_module_scan(session, uri)
check(isinstance(scan.get("provides"), list) and
isinstance(scan.get("imports"), list),
f"module scan has no verified rule: {scan}")
symbols = session.request("workspace/symbol", {"query": "fnv1a64"})
found = [symbol for symbol in (symbols.get("result") or [])
if symbol["location"]["uri"].endswith("Void/Core/Hash.hpp")]
check(found and any(symbol["name"] == "fnv1a64" for symbol in found),
f"workspace symbol did not reach the Hash.hpp definition: {symbols} status={status}")
empty = session.request("workspace/symbol", {"query": "no-such-symbol"})
check(empty.get("result") == [], f"unexpected workspace symbol result: {empty}")
references = session.request("textDocument/references",
{"textDocument": {"uri": uri}, "position": position})
check(references.get("error") and references["error"]["code"] == -32803 and
"incomplete" in references["error"]["message"],
f"references were presented as complete: {references}")
prepare = session.request("textDocument/prepareRename",
{"textDocument": {"uri": uri}, "position": position})
check(prepare.get("error") and prepare["error"]["code"] == -32803,
f"prepareRename did not refuse incomplete coverage: {prepare}")
rename = session.request("textDocument/rename",
{"textDocument": {"uri": uri}, "position": position,
"newName": "renamed_fnv"})
check(rename.get("error") and rename["error"]["code"] == -32803 and
"incomplete" in rename["error"]["message"],
f"rename was not guarded: {rename}")
missing = session.request("textDocument/definition", {
"textDocument": {"uri": uri},
"position": {"line": 0, "character": 0}})
check(missing.get("result") is None, f"definition for an unrelated position: {missing}")
finally:
session.close()
errors.seek(0)
diagnostics = errors.read()
check(b"fatal" not in diagnostics.lower(), f"server stderr: {diagnostics[-800:]!r}")
print(f"stock occurrences: hover and definition selected string_view at "
f"Hash.hpp:{lines['string_view']} then byte_span at {lines['byte_span']}; "
f"module scan {scan['state']}")
def 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("--workspace", type=Path, default=Path.cwd())
parser.add_argument("--header", type=Path,
default=Path("build/voidlibrary/current/include/Void/Core/Hash.hpp"))
options = parser.parse_args()
run(options.server.resolve(strict=True), options.gcc_profile.resolve(strict=True),
options.workspace.resolve(strict=True), options.header.resolve(strict=True))
if __name__ == "__main__":
try:
main()
except (OSError, ValueError, subprocess.SubprocessError) as exc:
raise SystemExit(f"verify-stock-occurrences: {exc}")
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env python3
"""Run the VS Code client acceptance in a disposable extension host."""
import argparse
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
ROOT = Path(__file__).resolve().parents[2]
CLIENT = ROOT / "clients/vscode"
def check(condition, detail):
if not condition:
raise ValueError(detail)
def application(code):
"""The Nix `code` wrapper starts a detached CLI; the app binary runs tests in-process."""
resolved = code.resolve(strict=True)
candidate = resolved.parent.parent / "lib/vscode/code"
return candidate if candidate.is_file() else resolved
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--code", default=shutil.which("code"),
help="VS Code launcher (default: code on PATH)")
parser.add_argument("--server", required=True, type=Path)
parser.add_argument("--adapter", required=True, type=Path)
parser.add_argument("--trace", required=True, type=Path)
parser.add_argument("--timeout", type=float, default=240)
options = parser.parse_args()
check(options.code, "code is not on PATH")
check((CLIENT / "node_modules").is_dir(),
"run `npm install` in clients/vscode once as a development step")
subprocess.run(["npm", "run", "compile"], cwd=CLIENT, check=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=120)
tests = CLIENT / "out/test/run.js"
check(tests.is_file(), "the extension test entry was not compiled")
executable = application(Path(options.code))
server = options.server.resolve(strict=True)
adapter = options.adapter.resolve(strict=True)
trace = options.trace.resolve(strict=True)
with tempfile.TemporaryDirectory(prefix="vls-vscode-client-") as temp:
work = Path(temp)
workspace = work / "workspace"
workspace.mkdir()
(workspace / "unit.cpp").write_text("int value = 17;\nint read() { return value; }\n",
encoding="utf-8")
command = [
str(executable),
f"--extensionDevelopmentPath={CLIENT}",
f"--extensionTestsPath={tests}",
f"--user-data-dir={work / 'user'}",
f"--extensions-dir={work / 'extensions'}",
"--no-sandbox", "--disable-gpu", "--disable-workspace-trust",
"--skip-welcome", "--skip-release-notes",
str(workspace),
]
environment = {**os.environ, "VLS_SERVER": str(server), "VLS_DAP": str(adapter),
"VLS_TRACE": str(trace)}
result = subprocess.run(command, env=environment, capture_output=True, text=True,
timeout=options.timeout)
output = result.stdout + result.stderr
if result.returncode != 0 or "VSCODE_CLIENT_PASS" not in output:
print(output[-5000:])
raise SystemExit(f"VS Code client acceptance failed (exit {result.returncode})")
print("VS Code client passed: LSP status, replay session, timeline, source, stale "
"rejection and transactional rename")
if __name__ == "__main__":
try:
main()
except (OSError, ValueError, subprocess.SubprocessError) as exc:
raise SystemExit(f"verify-vscode-client: {exc}")