Files
Language-Server/tests/native/StockOccurrences.py
T
faumaray da8003f6d4 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.
2026-12-05 14:06:50 +03:00

275 lines
13 KiB
Python

#!/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}")