Compare commits

..
25 Commits
Author SHA1 Message Date
lucioandClaude Opus 5.5 58520e586e Release 0.60.0: rename and references through generate block labels; rename warnings scoped to the renamed declaration
ci / checks (push) Successful in 1m37s
ci / corpus (push) Successful in 36s
release / build-and-publish (push) Successful in 8m2s
Version bump; the notes are in CHANGELOG.md (## 0.60.0) and
editors/vscode/CHANGELOG.md. TODO §65.1 plus the independent review's
H-1/H-2 and M-1/M-2 fixes. Gates on the tree: fmt and clippy -D warnings
clean, workspace lib/bins/tests 80 suites 5 078 passed 0 failed, node tests
6/6; doc-tests and the corpus gate run in CI.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-08 01:14:59 -07:00
lucioandClaude Opus 5.5 a062f62581 Docs for §65.1 match the code (review M-3)
ci / checks (push) Successful in 1m42s
ci / corpus (push) Successful in 33s
generate-label-rename README: "What changed" covers reworks 1-5 and the
review fixes; the stale "engine and verifier unchanged in code" claim is
replaced (what a rename rewrites is unchanged; the verifier gained no
normalization, only path-qualified file names). Status lists reworks 2-5,
P1/P2, §65.6 and the review; work log entries for M-2 and M-3, including
that QA's P1/P2 were fixed in the tree with no log entry. refactor-rename
README: dated correction. topo row 40: second half answered by row 43.
CHANGELOG: the two scoping bullets merged into one that matches rework 5
plus the H-1/H-2 fix. qa_warning_scope.rs P1/P2 test comments and the
rename module doc updated (comments only; that suite: 24 passed).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-07 02:06:47 -07:00
lucioandClaude Opus 5.5 6d1957076a Refactor messages: count shared file names once per set, not once per file named (review M-2)
Scope::name_of scanned every source on each call, and the define and
macro-argument warning scans named every file of the set before looking for
a site — two quadratic passes. scope::BaseNames counts base names once (kept
on Scope and on the port offers' Files; name_among folded into it).

OpenTitan engine probe, whole hw, entropy_src_main_sm.state_q: 2.95 s ->
2.23 s (defines 326 -> 7 ms, macro arguments 394 -> 77 ms), the same 47
warnings. Workspace: 80 suites, 5 078 passed, 0 failed, 51 ignored; clippy
-D warnings clean.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-07 02:05:33 -07:00
lucioandClaude Opus 5.5 38244e6aaf Rename: an include-related file's use that the rename edits is not said to be left unchanged (review M-1)
ci / checks (push) Successful in 1m51s
ci / corpus (push) Successful in 47s
fragment_use_warnings ignored the rename's edits, so renaming module `m`
while `all.sv` includes `m.sv` and `n.sv` rewrote `n.sv`'s instantiation and
still warned "n.sv:2: `m` is used in a file that includes `m.sv` … and was
left unchanged". Tokens covered by an edit in that file are skipped.

Test: rename_warning_scope.rs (fails with the skip disabled). Workspace:
80 suites, 5 077 passed, 0 failed, 51 ignored (first run cut by the guard at
1 800 s launching a fresh test binary — the §65.3 stall; re-run green).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-07 01:37:01 -07:00
lucioandClaude Opus 5.5 eadee02c37 Independent review of the §65.1 working tree (oct_review.md): 2 high (fixed), 3 medium, 13 low findings
ci / checks (push) Successful in 1m43s
ci / corpus (push) Successful in 52s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-07 01:01:41 -07:00
lucioandClaude Opus 5.5 e8e22c2364 Rename warnings: a macro argument the macro carries to the declaration is said wherever it is written (review H-1/H-2)
The home-set scoping dropped a bare macro argument outside the home set
whatever the macro did with it, and never saw a `bind` produced by a macro —
silent missed renames, regressions against 0.59.0 (`CONN(state_q)` building
`.state_q(state_q)` broke the instantiation without a word). New
rename/carry.rs decides per macro and formal position whether an argument is
carried: after a `.` (past blanks and pastes), into a carried position of
another macro, or by a macro that expands to a `bind` into the unit (every
position; its body is news and a file invoking it is home). An undefined
macro's arguments, one past the formals and a macro cycle are doubt and said.

Tests: tests/rename_macro_carry.rs (8), carry.rs unit tests (4). Workspace
lib/bins/tests: 80 suites, 5 076 passed, 0 failed, 51 ignored (guard exit 0).
OpenTitan engine probe against carrying disabled: state_q 47 = 47,
StIdle 0 = 0, cnt_q 13 = 13 warnings, timing unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-07 01:01:41 -07:00
lucioandClaude Opus 5.5 7794d3938b TODO §65.1: rename and references through a generate block label; rename warnings and mentions scoped to the renamed declaration
A path segment naming a block (bare, indexed, nested, cross-file) is now a
reference to its label: vlog_semantic declares a `for` block's label in the
enclosing scope, makes `generate … endgenerate` no scope, gives a block a
member scope, walks an index in a path, and files blocks on a module's
hierarchical surface under `module.label` (FACTS_FORMAT 21). The LSP, CLI
and MCP rename/references get it through the engine; lucisv-mcp's `block`
refusal is lifted. No verifier normalization (attacks in
check/qa_block_paths.rs, qa_block_attacks.rs).

Reworks after QA: unresolved path segments warned in every file of the set;
sibling-arm members warned; a label beside a net is a duplicate-declaration;
function-local block keys never collide; file names path-qualified when base
names collide; rename warnings and lucisv-mcp mentions scoped to the
declaration's home set (rename/home.rs, scoped.rs), falling back to unscoped
on any doubt. TODO §65.4 and §65.6 filed.

docs/features/generate-label-rename. Workspace lib/bins/tests: 79 suites,
5 064 passed, 0 failed, 51 ignored (guard exit 0).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-07 01:01:23 -07:00
lucioandClaude Fable 5.1 b9ee399ac6 TODO §65: stabilization round 1 — generate-label rename/references, LSP references fan-out to the pd_main tops, the doc-test stall
ci / checks (push) Successful in 1m39s
ci / corpus (push) Successful in 35s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-30 01:44:39 -07:00
lucioandClaude Fable 5.1 5316c0b127 Release 0.59.0: MCP read-only mode (--read-only, five tools, 1 797 bytes) and the hierarchy instance cap
ci / checks (push) Successful in 1m27s
ci / corpus (push) Successful in 34s
release / build-and-publish (push) Successful in 7m16s
Version bump; the notes are in CHANGELOG.md (## 0.59.0) and
editors/vscode/CHANGELOG.md. Gates: fmt and clippy -D warnings clean,
72 suites + 6 doc suites (4937 passed, 0 failed), corpus 814/820,
node tests 6/6.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-29 02:12:33 -07:00
lucioandClaude Fable 5.1 74c56318c0 MCP: hierarchy caps at 300 instances (100 with peek), peek lines no longer count; census round 5 (read-only, same-day base control) written up; 0.59.0 notes dated
ci / checks (push) Successful in 2m11s
ci / corpus (push) Successful in 45s
Round 5 found `hierarchy up` + `peek` cut to 20 of 77 instantiations by
the 300-line cap. Same-day base controls put read-only mode at parity
with file tools (a +8 %, d −8 %) and show the base arm itself moved
22–29 % in six days.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-29 01:38:54 -07:00
lucioandClaude Fable 5.1 b757e82161 MCP M8: read-only mode — lucisv-mcp --read-only lists five read tools (1 797 bytes), never writes inside a root; full mode unchanged
ci / checks (push) Successful in 1m50s
ci / corpus (push) Successful in 52s
The mode filters the registry; an edit tool name answers unknown-tool.
Extension setting lucisv.mcp.mode (full | read-only; any other value is
read-only and logged), label and copy-config key lucisv-ro, both smokes
in the release script. Tests: tests/read_only.rs, QA lane tests/qa_m8.rs.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-29 01:10:10 -07:00
lucioandClaude Fable 5.1 e992cca577 MCP plan §11 + lane M8: read-only mode (--read-only: five tools, ≤1 800 bytes, never writes inside a root; full mode unchanged)
ci / checks (push) Successful in 1m32s
ci / corpus (push) Successful in 33s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-29 00:40:34 -07:00
lucioandClaude Fable 5.1 03c566a08b Release 0.58.0: the lean MCP catalogue (nine tools, 3 440 bytes, trusted writes) and census round 4
ci / checks (push) Failing after 1m41s
ci / corpus (push) Successful in 38s
release / build-and-publish (push) Successful in 10m37s
Version bump; the notes are in CHANGELOG.md (## 0.58.0) and
editors/vscode/CHANGELOG.md. Gates: check/fmt/clippy clean, 4922 tests
passed 0 failed (75 suites), corpus 814/820 (baseline).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-24 03:00:54 -07:00
lucioandClaude Fable 5.1 9242594457 mcp_analysis.md: census round 4 on the lean catalogue (6/6 correct; a −1 %, d parity, b/c +9…+10 %); 0.58.0 notes dated
ci / checks (push) Successful in 2m36s
ci / corpus (push) Successful in 49s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-24 02:03:14 -07:00
lucioandClaude Fable 5.1 bfa8e98eb5 MCP M7: the lean catalogue — nine tools, 3 440 model-visible bytes, no dry_run/paging, short answers
ci / checks (push) Successful in 1m43s
ci / corpus (push) Successful in 36s
hierarchy (file:line per instance, peek), find (every declaration by
name, refs + unresolved mentions), outline, read, check, rename, port,
edit_item, format. Name lookup reaches every declaration the symbol
tables hold (tools/declared.rs); rename of a generate-block label is
refused (engine gap filed as topo §2.9 MCP-14). Text-only results,
engine sentences made root-relative. Tests ported or deleted per the
README; QA lane in tests/qa_m7.rs. Docs, smoke gate, release notes
(0.58.0 unreleased) updated.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-24 01:40:53 -07:00
lucioandClaude Fable 5.1 edad66947f MCP plan §10 + lane M7: the lean catalogue (nine tools, ≤3 500 model-visible bytes, no dry_run/paging, short answers)
ci / checks (push) Successful in 1m25s
ci / corpus (push) Successful in 32s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-23 23:55:04 -07:00
lucioandClaude Fable 5.1 77b3a2370b TODO-MCP: tick the release and round-3b boxes; 0.57.0 verified (8 assets, three binaries)
ci / checks (push) Successful in 1m32s
ci / corpus (push) Successful in 33s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-23 23:36:15 -07:00
lucioandClaude Fable 5.1 522ae70db9 Release 0.57.0: the MCP block (lucisv-mcp), packaging, cache reuse, three census rounds
ci / checks (push) Successful in 1m38s
ci / corpus (push) Successful in 34s
release / build-and-publish (push) Successful in 7m12s
Version bump only; the notes are in CHANGELOG.md (## 0.57.0) and
editors/vscode/CHANGELOG.md. Gates: check/fmt/clippy clean,
4953 tests passed 0 failed, corpus 814/820 (baseline).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-23 23:25:56 -07:00
lucioandClaude Fable 5.1 aba39e5535 mcp_analysis.md: round 3b re-measure on the final binary (task d −10 %, task a's opt-in lesson); raw run log updated
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-23 23:01:04 -07:00
lucioandClaude Fable 5.1 2954ae8a84 MCP feedback-3: the instantiation template and hierarchy overrides are opt-in; census round 3 and the verdict written; 0.57.0 notes drafted
ci / checks (push) Successful in 1m28s
ci / corpus (push) Successful in 32s
Round 3 of the census (mcp_analysis.md): with feedback-1/2 the whole-design question is one call and 15 % cheaper than plain file tools (47/47 in 9 calls); the small edits stay 4–19 % dearer; the cross-file rename is complete every time; a 71-instance hierarchy question costs a third of the tool calls but the same tokens because every unit_interface answer carried a 30-line template. Verdict: helpful, not a toy — no wrong answer in 20 runs, one-call whole-design answers, completeness on cross-file edits, verified writes — with a fixed catalogue tax and verbose answers as the cost. Feedback-3 (crates/lucisv_mcp/src/tools/{interface,hierarchy}.rs): `unit_interface` renders the template only with `template: true` (−40 % bytes), `hierarchy` renders `#(…)` only with `overrides: true` (−55…66 %), `ports (N):`/`parameters (N):` headers; QA proved the opt-in output byte-identical to the previous binary over every fixture and the opentitan clone. Docs: the Agents guide's tool table regenerated from the binary and the site rebuilt; CHANGELOG 0.57.0 section and the extension notes drafted for the closing release; TODO-MCP's M6 items closed; docs/mcp/census-runs.txt holds the raw run log. Gates through tools/guard.sh: fmt, clippy, workspace 4 953 passed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-23 22:53:18 -07:00
lucioandClaude Fable 5.1 c2e42b8840 MCP feedback-2: the count line leads every paged answer, default limit 500, in path-glob filter on the listing tools, post-edit check hint; census round 2 written up
ci / checks (push) Successful in 1m39s
ci / corpus (push) Successful in 33s
Census round 2 (mcp_analysis.md): with feedback-1 the rename task became complete (the unresolved-mentions list surfaced the DV string path) at a token cost inside the base arm's run-to-run variance; the port task was unchanged; the census task regressed — the agent chose `hierarchy up` (right) but paged the 77-row answer with a small limit and never read the trailing "… and N more". Fixes: every paged text answer opens with `N <noun> (showing a–b)` (JSON gains `shown`), DEFAULT_LIMIT 500; `list_units`, `search_symbols`, `references`, `hierarchy`, `diagnostics` and `defines` take `in`, a root-relative path glob (`*` within a component, `**` across, `?`; a bare directory means everything below it) applied before paging — `hierarchy up prim_fifo_sync` with `in: "ip/**/rtl/*.sv"` answers the census's 47 in one call; the six design-wide edits end with `check: diagnostics on <files>`. Catalogue 17 993 B, instructions 896 chars. QA (Opus): 14 qa_f2 tests, four notes. Gates through tools/guard.sh: fmt, clippy, workspace 4 943 passed (+1 lead test).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-23 21:50:34 -07:00
lucioandClaude Fable 5.1 4671b91704 MCP feedback-1: unresolved mentions on references and the edit tools, a smaller catalogue, hierarchy/references routing, add_port after, temp sweep; census round 1 written up
ci / checks (push) Successful in 1m30s
ci / corpus (push) Successful in 32s
Census round 1 (mcp_analysis.md, Sonnet arms on the opentitan clone): the mcp arm used more tokens than plain file tools on all three tasks (+18/+25/+20 %) and was incomplete on the rename — the `rename` tool renamed what the engine sees and warned about the macro argument, but nothing listed the old name still spelled as text (a DV force path built as the string ".state_q"), which the base arm's broad search found. Fixes (crates/lucisv_mcp/src/tools/{mentions,place,place/slot,place/verify}.rs + descriptions): `references`, `rename`, `remove_port` and `add_port` end with every whole-word spelling of the name in strings, comments, macro text, define bodies and macro-rooted paths that no engine answer accounted for, ranked edited-files-first, capped at 50, computed on the texts as written; `hierarchy` leads with "who instantiates a module", `references` routes a module name there, `instructions` say so; `tools/list` 30.2 kB → 18.0 kB with every argument still documented; `add_port` takes `after` — the engine appends, the placer moves the header element and each instance's connection to after the anchor in the neighbours' layout, refuses any list holding an unreadable element (an `(* attr *)` port the parser keeps as text would otherwise make the next port inherit the new type — QA's blocking find), and a checker compares every port's declaration text and pairs each comment with its anchoring name against the engine's result; stale `index-cache-mcp.*.tmp` files older than 10 min swept before a write. QA (Opus, two rounds): 23 qa_f1 tests. Gates through tools/guard.sh: fmt, clippy, workspace 4 918 passed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-23 20:44:06 -07:00
lucioandClaude Fable 5.1 0f4830afa5 MCP M6: read-only reuse of the editor's index cache, an own store, the forced-delete ruling, first instructions; the block's closing docs
ci / checks (push) Successful in 1m25s
ci / corpus (push) Successful in 31s
crates/lucisv_mcp/src/cache.rs: at startup `--index-cache DIR/index-cache` (the language server's store) is read READ-ONLY — header CACHE_FORMAT/FACTS_FORMAT/version must match this build or the store is ignored with one stderr line; each record line's checksum verified, decoded, keyed by (record path, content hash) and used only for a discovered file whose bytes hash to it, through IndexBuilder::add_facts instead of a parse; the server never writes that file. Its own `index-cache-mcp` is written once at exit, atomically, in the same codec (a test pins the restated framing against index_cache.rs's source). opentitan: cold 1.9 s → warm 0.8 s (walk 210 ms + merge 204 ms are the floor). delete_item with force may remove an item holding `define/`undef, warning which macros went (M4's ruling); INSTRUCTIONS names the read tools, the edit tools, dry_run and diagnostics. Closing docs: docs/topo.md gains the lucisv_mcp node and its six edges, the mcp-packaging spawn/packaging rows, the read-only cache row and §2.9 rows 35–42 (MCP-5/6/7/8/10/11/12/13 and the parser leniency the M3.5 verifier exposed); repository-analysis map row and nine-crate count; README architecture row; CLAUDE.md measurement for the new crate.

QA (Opus; interrupted by the owner moving the machine, verdict pass so far): swapped/stale/foreign/deleted/off-by-one-header/CRLF stores skipped, the editor's store byte-identical through a session, SIGKILL mid-write harmless, a 231 MB store linear, fingerprint parity over the whole checkout; two low items open — the README threat model reworded, and an orphaned `.tmp` after a kill between write and rename to be swept in the census round. Gates: fmt, clippy clean; lucisv_mcp 318 passed; the dev's workspace run 4 858 passed on the same code.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-23 17:14:43 -07:00
lucioandClaude Fable 5.1 d4ec571958 MCP M5: lucisv-mcp ships in every platform vsix; the extension registers it with VS Code's agent mode; Agents guide
tools/release.sh builds -p lucisv_mcp for the host and every cross triple, stages lucisv-mcp[.exe] beside the two binaries (three per platform package, fifteen in the all-platforms one; the universal package still carries none), smoke-tests it (editors/vscode/mcp_smoke.js: initialize, tools/list ≥ 26, project_overview) loose and unzipped from the host and all-platforms packages; tools/audit_artifacts.sh audits the third name and rejects any other; prune_release_assets.sh unchanged (seven vsix names). editors/vscode/mcp.js: the three-rung binary ladder (lucisv.mcp.path → bundled → PATH), one McpStdioServerDefinition per workspace folder — the constructor is POSITIONAL (label, command, args, env, version) with cwd set afterwards; the plan's object form was wrong and is corrected — with `--root <folder> --index-cache <storage>`, refreshed on folder and setting changes, guarded so VS Code < 1.101 registers nothing but the command; a missing binary refused at resolve time with one output-channel line; the `lucisv.mcp.copyConfig` command puts the Claude Code / Cursor / VS Code snippet on the clipboard. package.json: contributes.mcpServerDefinitionProviders, lucisv.mcp.enabled/path, the command; engine stays ^1.82.0 (vsce 4 accepts). ci.yml runs node --test over the extension's unit tests. Docs: docs/site guides/agents.md with the tool table generated from the binary (site rebuilt), README paragraph, RELEASING.md, extension README/CHANGELOG (Unreleased), manual-acceptance rows 18–25 for the live-VS Code checks.

QA (Opus): API signature confirmed against VS Code 1.138's vscode.d.ts; 8 mutation checks caught by mcp_test.js; release.sh run end to end, vsix contents listed (three binaries, mcp.js, no test files), SHA256SUMS verified, the embedded binary smoke-tested, the vsix installed into an isolated profile. Gates: node --test 6/6, fmt clean.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-23 15:59:07 -07:00
lucioandClaude Fable 5.1 23ec44455c MCP M4: structural edits — replace_item, insert_item, delete_item with the block's own verifier
crates/lucisv_mcp/src/tools/item.rs + item/{verify,lexical,span,refs,macros,star}.rs: the general token saver — an agent sends one item's text, never the file. Every edit is a byte-range splice of exactly the slice read_item shows (kind classes: module/interface/program/package/class/declaration/port declaration/always/initial/final/instance/function/task/generate/…), through apply::run (dry_run, freshness, atomic write). The verifier: 1a the text lexes on its own; 1b every token and comment outside the region is byte-identical, shifted, nothing straddles the region's end and no comment inside attaches to a token outside; 2 every item outside the region keeps its depth, kind class and span (a text opening a block or closing the enclosing module is refused); 3 the region holds what the tool promised, each item a kind its container may hold; 4 no new duplicate declaration; 5 ifdef/endif balance in the old and new bytes; 6 define entries inside the region unchanged unless the item is a directive; 7 fence markers unchanged. Normalisation: one trailing newline when the old slice ended a line, the file's line endings; a text that brings comments widens the replaced span over the item's own leading/trailing comments so repeats are `unchanged`; own comments stop at the first blank-line gap; a same-line comment goes with the item. delete_item refuses while a declared name is used — the whole-set engine, the file's own tables, macro-call arguments and define bodies (possible use), and `.*` instantiations in the item's scope whose module declares the port (bound) or cannot be resolved (possible) — unless force, listing the first sites.

QA (Opus, two rounds across an app restart): 45 qa_m4 tests + 23 dev attacks; four masked corruptions fixed (open comment swallowing a fence, macro and .* uses invisible to delete, banner comments deleted). Timings release: 40 000-line file replace 159 ms, insert 284 ms, delete 263 ms. Handshakes MCP-11 (batched find_references), MCP-12 (generate-loop hierarchical use missed by the engine), MCP-13 (lint gap on a directionless header port). Gates through tools/guard.sh: fmt, clippy, workspace 4 846 passed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-23 15:34:51 -07:00
186 changed files with 25843 additions and 5283 deletions

No files matched your search

+7 -3
View File
@@ -1,7 +1,7 @@
# CI: the three checks CLAUDE.md requires before any work is finished,
# plus the corpus gate, enforced on every push. Runs on the self-hosted
# mac-arm64 runner in host mode (no containers), so the toolchain is the
# same one releases are built with.
# plus the extension's JavaScript tests and the corpus gate, enforced on
# every push. Runs on the self-hosted mac-arm64 runner in host mode (no
# containers), so the toolchain is the same one releases are built with.
name: ci
on:
push:
@@ -19,6 +19,10 @@ jobs:
run: cargo clippy --all-targets -- -D warnings
- name: cargo test
run: cargo test --workspace
# The VS Code extension's headless checks (a stubbed `vscode`, no npm
# dependencies): node >= 18 for `--test`; the runner has node 22.
- name: extension tests
run: node --test editors/vscode/*_test.js
# The 99.1% headline, enforced: score the 820-file corpus and fail on any
# regression below scripts/corpus-baseline (verification errors and
+2 -2
View File
@@ -2,8 +2,8 @@
# publishes a Gitea release with the CHANGELOG section for that version as
# its notes. What the release page carries is the seven .vsix packages —
# the universal one, the five (darwin-arm64/darwin-x64/linux-x64/
# linux-arm64/win32-x64) with the lucisv + lucisv-server binaries embedded,
# and the all-platforms one carrying every pair at once — plus SHA256SUMS.
# linux-arm64/win32-x64) with the lucisv + lucisv-server + lucisv-mcp binaries embedded,
# and the all-platforms one carrying every platform's three binaries at once — plus SHA256SUMS.
# Every package is a must: a missing one fails the release, by name
# (tools/prune_release_assets.sh). The loose binaries are still built for
# every target
+220
View File
@@ -4,6 +4,226 @@ All notable changes to lucisv are recorded here. Versions follow
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
(see `README.md`) are the only frozen contract.
## 0.60.0 — 2026-10-08
### Rename and references through a generate block label
TODO §65.1, topo §2.9 row 43 (MCP-14). (`docs/features/generate-label-rename`.)
- **`rename` of a block label rewrites every path through it.** Renaming
`g_lane` in `for (…) begin : g_lane` used to rewrite the label alone,
leaving `g_lane[0].lane_q` (and `u_x.g_lane[1].sig` in another file)
naming a block that no longer existed, with no warning. The label, its
closing `end : g_lane`, and every path segment naming the block — bare,
indexed (`g[0].x`, `g[i].x`), nested (`g_a.g_b[2].x`), behind an instance
path from another file — are now one reference set, renamed all or
nothing; a spelling inside macro text or a string is a warning. A name
declared *inside* a block is likewise renamed through such a path. Named
procedural blocks: `begin : lbl`, `end : lbl` and `disable lbl;` (and the
`lbl: begin … end : lbl` form) are one set.
- **`find_references`** (LSP `textDocument/references`, `lucisv-mcp find
refs`) lists the declaration, the closing label and every segment, same
file and cross-file, with the declaring file open or closed.
- **`lucisv-mcp rename`** no longer refuses a `block`-kind declaration.
- Resolution changes every consumer sees: a `for` generate block's label is a
name of the enclosing module (its genvar is not); `generate … endgenerate`
is not a scope; `blk.x` and `arr[0].field` (a packed struct array) resolve
their tails; an unnamed `genblk1` still names nothing. The index cache
format moves to 21, so a 0.59.0 cache is rebuilt once.
- **A rename says so when a path it cannot resolve spells the name**: a
hierarchical path segment in any file of the rename's set that resolved to
no declaration (`tb.dut.gen_x[0].q`, rooted at a top module) is left
unchanged and warned about with its lines, for every kind of declaration;
and renaming a member one arm of a generate `if`/`case` declares warns
about the same-named member of the arm sharing its label.
- `duplicate-declaration` now also reports a block label beside a net,
variable, parameter or instance of the same name, and such a label is no
longer counted as a read of the net.
- Rename and port warnings name a file by its path whenever another file of
the set shares its base name (two `pwrmgr_if.sv` are two findable lines,
root-relative in `lucisv-mcp`), and a line a path warning names is not
repeated under `unresolved:`. Same-named members are warned about through
every enclosing same-label generate arm (`g.h.x`), and an escaped name's
unresolved paths are found too.
- **Rename warnings and mentions are about the renamed declaration.** For a
member of a module or interface (a net, variable, port, parameter, block,
…), a bare spelling of its name in a macro argument, a `` `define`` body, an
unstructured assertion, a comment or a string is reported only where it can
mean it: in the declaration's **home set** — the declaring file,
everything it `` `include``s, whatever includes it (transitively), and the
files the rename edits. In code, a spelling in the declaring file is
reported after a scope lookup finds the declaration there (an instantiating
module's own same-named signal is not); one in an included fragment always;
a `` `define`` body when the macro is invoked from the home set (through
other macros too — `ASSERT_DEFAULT_CLK`'s `clk_i`); a macro argument inside
a `bind` into the declaring module; and a bare use in the plain code of an
included fragment (`prim_util_memload.svh`'s `mem`) is named as a use the
rename could not edit. Reported wherever they are written: a dotted
spelling (`.state_q`, a possible hierarchical path); a bare macro argument
the macro carries to the declaration — after a `.` (`` `CONN(state_q)``
building `.state_q(state_q)`, `` `FORCE(state_q)`` building
`force u_m.state_q`), into a `bind` into the declaring module, or into a
macro lucisv has no definition of; and the body of a macro that expands to
such a `bind`. Not reported: a body whose spellings are only its own
parameter named like the declaration (unless the body also spells the name
after a `.`, or a default argument spells it), and a backtick inside a
string. Any doubt means no scoping: a module, interface, package or
package member, a declaration outside a module, or one whose home set holds
an include lucisv cannot resolve (a macro-built name, a file outside the
project such as `uvm_macros.svh`) is reported everywhere as before. On
opentitan the `state_q` rename's answer went from 274 lines (61 kB, 230
macro warnings, 229 about other modules) to about 72 lines (12 kB),
`hmac_core.StIdle`'s from 48 lines to 3.
- `duplicate-declaration` also reports a block label beside a port, genvar,
typedef, function or task, and two named procedural blocks of one label in
one scope.
- `lucisv-mcp rename` with many warnings is fast again: rooting the warning
paths was quadratic per warning (a `state_q` rename on opentitan: 125 s →
3.3 s). Naming the files in warnings no longer scans the whole set once per
file either: the engine's part of that rename went from 2.9 s to 2.2 s.
- A use in a file that includes the declaring file (or that it includes) is
no longer reported as "left unchanged" when the rename did rewrite it —
renaming a module whose instantiation sits in a file included beside it
said so wrongly.
## 0.59.0 — 2026-09-29
### MCP read-only mode
PLAN §11, the owner's request of 2026-09-29: one binary, two modes.
(`docs/features/mcp-read-only`.)
- **`lucisv-mcp --read-only`** offers exactly the five read tools —
`hierarchy`, `find`, `outline`, `read`, `check`, in that order, with the
same descriptions and schemas as full mode. The model-visible catalogue is
1 797 bytes (budget ≤ 1 800) and the instructions 297 bytes (≤ 300), both
pinned by `tests/read_only.rs`.
- The mode filters the tool registry: `tools/call` of `rename`, `port`,
`edit_item` or `format` is the unknown-tool error (`-32602`,
`unknown tool: rename (the server runs --read-only)`); no edit handler is
reachable. Resources answer as in full mode.
- **No write inside a root**, whatever is called: a test snapshots every
path, size and mtime (directories too) of a fixture copy, calls every
full-catalogue tool name (the four edits with valid edit arguments, which
a control test shows do write in full mode) and every resource, and finds
the snapshot unchanged after the server exits. The server's own index
store under `--index-cache` is still written (outside the roots unless
`--index-cache` names a directory inside one).
- **Full mode is byte-identical to 0.58.0** on the wire (`initialize`,
`tools/list`); only the usage line gains `[--read-only]`.
- **Extension:** setting `lucisv.mcp.mode` (`"full"` default, `"read-only"`)
— the definition gains `--read-only` and the label becomes
`lucisv read-only (<folder>)`; a change of the setting re-announces the
servers. **lucisv: Copy MCP server config** follows it (server key
`lucisv-ro`, args ending `--read-only`, the message names the mode).
- `editors/vscode/mcp_smoke.js <binary> --read-only` smokes the mode (five
tools, one `hierarchy`, `rename` refused, files untouched);
`tools/release.sh` runs both smokes on the host binary and on the one
embedded in the package.
- `hierarchy` caps at 300 instances, 100 with `peek`; `peek` lines no
longer count toward the cap (census round 5: `prim_fifo_sync` up with
peek showed 20 of 77 instantiations). Without `peek` the answer is
unchanged.
## 0.58.0 — 2026-09-24
### The lean MCP catalogue: nine tools, short answers, trusted writes
The census (`mcp_analysis.md`) found the server right on every run and
dearer than plain file reads on every small task: a 5 400-token catalogue
read each session, answers carrying more than the question, and agents
dry-running what they were told to trust. PLAN §10 is the owner's ruling:
accuracy over breadth. (`docs/features/mcp-lean-catalogue`.)
- **Nine tools, in this order: `hierarchy`, `find`, `outline`, `read`,
`check`, `rename`, `port`, `edit_item`, `format`.** The model-visible
catalogue (name, description, schema of every tool) is 3 440 bytes, was
17.9 kB; the `initialize` instructions are 398 bytes. Both budgets
(≤ 3 500 and ≤ 400) and the names and order are pinned by `tests/wire.rs`.
No `title`, no `structuredContent` (a result is its text), no
per-argument descriptions; the schemas are `type` (and `enum`) only.
- **`hierarchy`** — without `root`: `N files, M modules, K top` and each
top as `name file:line`; with `root`: the instance tree (`depth` 1–20,
default 1), every instance at its **instantiation site**; `up`: every
instantiation, all levels to `depth`; `peek`: each statement's source.
Opentitan's `top_earlgrey` names 0.57.0's instance set, pinned.
- **`find`** — every declaration of a name (or `unit.name`), macros
included, as `kind name file:line`; `refs` adds each declaration's uses
one file per line (`file:120,133`) and the unresolved mentions.
- **`outline`** (`file` or `unit`), **`read`** (one item; design-wide
without `file`), **`check`** (`file:line:col severity message [rule]`,
errors first, `ok` when clean — the 0.57.0 `diagnostics` line set).
- **`rename`** (by name; `file` and `name@LINE` pick a declaration),
**`port`** (`add` after `after`, or `remove`, in every instantiation),
**`edit_item`** (`replace`, `insert_before`, `insert_after`, `delete` —
the M4 verifier unchanged; `delete` has no `force` any more), **`format`**
(a path, directory or glob; `fix` applies the safe lint fixes first; a
file the formatter refuses is named, the rest written).
- **Census round 4** (`mcp_analysis.md`): on the same four OpenTitan tasks
the lean server answered every run correctly, at parity with plain file
tools on the whole-design questions (task a −1 %, task d −0.4 % over two
runs) and +9…+10 % on the two small edits (was +15…+25 % in round 1).
- **Gone from the wire:** `dry_run`, `limit`, `offset`, `in`, `template`,
`overrides`, `force`, and the tools `project_overview`, `list_units`,
`unit_interface`, `read_item`, `search_symbols`, `defines`, `definition`,
`references`, `diagnostics`, `fix_lint`, `expand_wildcard`,
`convert_ports`, `organize_imports`, `inline_module`, `propagate_ports`,
`remove_port`, `add_port`, `extract_module`, `replace_item`,
`insert_item`, `delete_item`, `instantiate` (the engines stay in the CLI
and the language server). Answers are capped (300 lines; `check` 200)
with one `… and N more` line.
## 0.57.0 — 2026-09-23
### The MCP block complete: structural edits, the server in the extension, cache reuse, and three census rounds
- **`lucisv-mcp` ships inside every platform package** and VS Code's
agent mode finds it with no configuration: the extension registers one
server per workspace folder through `mcpServerDefinitionProviders`
(VS Code 1.101+; older VS Code keeps working without it), passes it the
folder as root and the extension's storage as the index-cache directory,
and the command **lucisv: Copy MCP server config** puts the snippet for
Claude Code, Cursor or a `.vscode/mcp.json` on the clipboard. Settings
`lucisv.mcp.enabled` and `lucisv.mcp.path`. The Agents guide on the
docs site lists every tool. (`docs/features/mcp-packaging`.)
- **Structural edits — the token saver.** `replace_item`, `insert_item`
and `delete_item` take one item's text, never the file: a module, an
`always` block, a function, a declaration, selected the way `read_item`
slices it. The block's own verifier refuses anything that changes a byte
outside the item's lines, opens a block it does not close, closes the
enclosing module, changes an item's kind, declares a name twice, splits
an `ifdef`, alters a macro definition or a fence marker, or leaves a
comment or string running into the code after it; `delete_item` refuses
while a declared name is still used — by the engine, by a macro argument
or `define` body, or through a `.*` binding — unless `force` is passed.
45 QA attack tests. (`docs/features/mcp-structural-edits`.)
- **Warm start from the editor's index.** With `--index-cache DIR` the
server reads the language server's store read-only (never writes it),
skips the parse of every file whose bytes it already describes, and
keeps its own store beside it: opentitan startup 1.9 s → 0.8 s.
(`docs/features/mcp-cache-and-census`.)
- **What three census rounds changed** (`mcp_analysis.md`: four tasks,
20 sub-agent runs on opentitan, with and without the server): every
`references`, `rename`, `add_port` and `remove_port` answer now ends
with the *unresolved mentions* of the name — strings, comments, macro
text and macro-rooted paths no engine resolves — so a DV force path
built as a string is no longer missed; every paged answer opens with
`N things (showing a–b)` and the default limit is 500; the listing tools
take an `in` path glob (`ip/**/rtl/*.sv`), which turns "who
instantiates X under ip/, RTL only" into one call; `add_port` takes
`after` to place the port where the file's style wants it; the tool
catalogue is 40 % smaller; the instantiation template and hierarchy
overrides are opt-in. Verdict: no wrong answer in 20 runs, 15 % fewer
tokens on the whole-design question, small edits 4–19 % dearer, the
cross-file rename complete where plain search had missed a site.
- **Filed for the engines, not fixed here:** the parser's silence on a
trailing `,` in a connection list, `{d,, d}` and `type(x)'(y)` in a
connection; a false `remove_port` refusal on a same-file instantiation;
`extract_module` writing LF into a CRLF file; a lint gap on a
directionless header port; the LSP's `references` omitting three real
`aes` instantiations in the `*_pd_main.sv` tops (`docs/topo.md` §2.9
rows 35–42).
## 0.56.0 — 2026-09-23
### Rename keeps implicit connections bound; the MCP server, as a preview
+7
View File
@@ -77,6 +77,13 @@ the source selectors are three sentences), `perf.rs` 900 (reasoned),
`lexer.rs` 763, `vlog_formatter/src/format/stmt.rs` 604 (at the mark; the
next statement arm goes in a new module) — and everything else under it.
Re-measured 2026-09-23 for the MCP block (`crates/lucisv_mcp`, nine crates
now): largest files `tools/read.rs` 405, `tools/item.rs` 379, `tools/item/verify.rs`
363, `tools/nav.rs` 340, `tools/diagnostics.rs` 330, `tools/interface.rs` 322,
`tools/hierarchy.rs` 316 — everything under 600; the M3.5 engine lane left
`vlog_refactor/src/rename/connections.rs` at 477 and `check/mod.rs` at 426,
and `lucisv_server/src/state/mod.rs` at 985 (already over; TODO §55).
## Rust standards
- `cargo fmt` clean, `cargo clippy --all-targets` clean (no `#[allow]`
Generated
+9 -9
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.56.0"
version = "0.60.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.56.0"
version = "0.60.0"
[[package]]
name = "lucisv_mcp"
version = "0.56.0"
version = "0.60.0"
dependencies = [
"lucisv_core",
"serde",
@@ -126,7 +126,7 @@ dependencies = [
[[package]]
name = "lucisv_server"
version = "0.56.0"
version = "0.60.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.56.0"
version = "0.60.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.56.0"
version = "0.60.0"
dependencies = [
"lucisv_core",
"vlog_formatter",
@@ -279,11 +279,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.56.0"
version = "0.60.0"
[[package]]
name = "vlog_refactor"
version = "0.56.0"
version = "0.60.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -292,7 +292,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.56.0"
version = "0.60.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -13,7 +13,7 @@ members = [
]
[workspace.package]
version = "0.56.0"
version = "0.60.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+19 -3
View File
@@ -460,7 +460,7 @@ understand still lints the buffer. Full rules:
## Architecture (the ruff mapping)
The eight-crate workspace separates source syntax, reusable engines, project
The nine-crate workspace separates source syntax, reusable engines, project
inputs, and the CLI/LSP front ends. The formatter follows ruff's separation
of document layout from language rules:
@@ -475,6 +475,7 @@ of document layout from language rules:
| `crates/lucisv_core` | — | Shared config, filelists, walks, format cache, atomic replacement |
| `crates/lucisv` | the `ruff` CLI | Parallel per-file formatting/linting, reports, stdin, in-place writes |
| `crates/lucisv_server` | — | Synchronous LSP loop, open-buffer overlays, indexing, editor capabilities |
| `crates/lucisv_mcp` | — | Model Context Protocol server for coding agents: project understanding and verified, token-saving edits over stdio (`docs/mcp/PLAN.md`) |
`vlog_parser` and `lucisv_core` have no dependencies. The formatter depends
only on the parser; semantic analysis also depends only on the parser.
@@ -482,7 +483,8 @@ Linting consumes the parser, semantics and `lucisv_core` (for the one
`--exclude`-style matcher a waiver file's `--location` shares with the CLI);
refactoring consumes the parser and semantics. The CLI reaches
semantics through the linter and has no refactoring dependency. The server
composes all six libraries. See [topo.md](docs/topo.md) for the full graph,
composes all six libraries, and so does the MCP server (never the LSP
crate). See [topo.md](docs/topo.md) for the full graph,
including the linter’s and refactor’s formatter dependencies used only by tests.
Key ideas carried over from ruff/prettier:
@@ -929,7 +931,7 @@ parents into sections alongside Other Modules. Stars persist per workspace;
**VS Code needs no separate binary**: every release on the
[releases page](https://git.luci.ooo/lucio/lucisv/releases) carries a
platform-specific `.vsix` with both binaries inside it — pick yours
platform-specific `.vsix` with the binaries inside it — pick yours
(`darwin-arm64`, `darwin-x64`, `linux-x64`, `linux-arm64`, `win32-x64`)
and sideload it:
@@ -983,6 +985,20 @@ vim.lsp.enable('lucisv')
`nvim-lspconfig`, Vim 9 (`vim-lsp`) and coc.nvim equivalents:
`editors/nvim/README.md`.
**Agents (MCP).** `lucisv-mcp` is lucisv as a Model Context Protocol server
for coding agents: project overview, unit interfaces, outlines, one item's
source, definition/references/hierarchy, diagnostics, and verified edits
(format, lint fixes, rename, the port refactorings, single-item
replace/insert/delete), each with `dry_run`. The platform `.vsix` packages
carry it as a third binary and, on VS Code 1.101+, register it with agent
mode — one server per workspace folder, under **MCP: List Servers**
(`lucisv.mcp.enabled`, `lucisv.mcp.path`). For Claude Code or Cursor, run
**lucisv: Copy MCP server config** in VS Code, or by hand:
`cargo build --release -p lucisv_mcp`, then
`claude mcp add lucisv -- lucisv-mcp --root .`. The tool list, the config
snippets and the safety rules are in the
[Agents (MCP) guide](docs/site/src/content/docs/guides/agents.md).
**Which files the server indexes.** A filelist if the project has one — the
`filelist` key of its `lucisv.toml`, or the editor setting `lucisv.filelist`
(a path, absolute or relative to the workspace folder) — and then exactly the
+201 -32
View File
@@ -186,25 +186,25 @@ lane: the LSP's rename inherits the fix.
`tests/wire.rs` and `tests/attacks.rs` (new), fixtures, the
`mcp-structural-edits` README. Depends on M3 merged.
- [ ] `replace_item`, `insert_item`, `delete_item` with the PLAN §4.3
- [x] `replace_item`, `insert_item`, `delete_item` with the PLAN §4.3
contracts: bytes outside the span untouched (asserted by the test,
not trusted), strict re-parse of the whole file (or no growth in
tolerant error count when it did not parse before), one item at the
position, the declared name matches unless `rename: true`,
`delete_item` refuses over surviving references unless `force`
- [ ] `tests/attacks.rs`, written by the dev, every case asserted
- [x] `tests/attacks.rs`, written by the dev, every case asserted
**refused with the tree byte-identical**: a `text` opening a block it
does not close; one that closes the enclosing module; one that
re-declares a port; a UTF-8 boundary inside the span; an item inside
a format fence; a file with an unterminated string; an `insert_item`
after `end` — the CLAUDE.md invariant-4 discipline applied to the
block's own verifier
- [ ] README `mcp-structural-edits`: the contract as a table, the attack
- [x] README `mcp-structural-edits`: the contract as a table, the attack
list, what the tool deliberately does not check (semantic sense of
the new text)
- [ ] gates; sizes (`item.rs` is expected to be the largest file in the
- [x] gates; sizes (`item.rs` is expected to be the largest file in the
crate; if it passes 600 lines the verifier moves to `item/verify.rs`)
- [ ] QA: re-attack with at least eight new cases (a `text` that is two
- [x] QA: re-attack with at least eight new cases (a `text` that is two
items; an empty `text`; a `text` equal to the old bytes — must be a
no-op, not a refusal; a macro-bracketed item; a `generate` block
target; an item whose leading comment is shared with the previous
@@ -224,13 +224,13 @@ mcp_test.js,mcp_smoke.js,.vscodeignore,README.md,CHANGELOG.md}`,
trunk; touches no Rust. `extension.js` changes are limited to requiring
`mcp.js` and calling its `activate(context)`.
- [ ] `release.sh`: stage `lucisv-mcp[.exe]` into `bin/` (platform) and
- [x] `release.sh`: stage `lucisv-mcp[.exe]` into `bin/` (platform) and
`bin/<target>/` (all); `expect_vsix_bins` lists grow to three;
`mcp_smoke.js` run against the host binary and against the one
unzipped from the host vsix and the all-platforms vsix (mirror
`smoke_embedded_server`); `audit_artifacts.sh` accepts the third name;
the universal vsix still asserts no `extension/bin/*`
- [ ] `mcp.js`: the three-rung binary ladder reusing `bundledBinary`;
- [x] `mcp.js`: the three-rung binary ladder reusing `bundledBinary`;
the guarded `registerMcpServerDefinitionProvider("lucisv.mcp", …)`
with one `McpStdioServerDefinition` per workspace folder (`--root`,
`--index-cache <storagePath>`, `cwd`, `version` from `package.json`),
@@ -241,20 +241,20 @@ trunk; touches no Rust. `extension.js` changes are limited to requiring
binary; `mcp_test.js` with a stubbed `vscode` (the `hierarchyView_test`
pattern) covering the ladder, the guard on an old VS Code (no `lm`),
and the three snippets
- [ ] `package.json`: `contributes.mcpServerDefinitionProviders`, the two
- [x] `package.json`: `contributes.mcpServerDefinitionProviders`, the two
settings, the command + palette entry; engine stays `^1.82.0` unless
`vsce package` refuses — then bump to `^1.101.0` and record why in the
README and CHANGELOG
- [ ] docs: the site guide page (install via vsix → nothing to do; Claude
- [x] docs: the site guide page (install via vsix → nothing to do; Claude
Code / Cursor snippets; the standalone `cargo build` line; the tool
list generated from `tools/list` output, checked in); `README.md`
paragraph; `tools/RELEASING.md` (three binaries; the smoke); the
extension README and CHANGELOG
- [ ] CI: `node --test editors/vscode/*_test.js` in `ci.yml`
- [ ] README `mcp-packaging`; work log; `node --test` green; a local
- [x] CI: `node --test editors/vscode/*_test.js` in `ci.yml`
- [x] README `mcp-packaging`; work log; `node --test` green; a local
`tools/release.sh` (host only) producing a darwin-arm64 vsix with the
three binaries, unzipped and checked
- [ ] QA: install the vsix into a clean VS Code profile: the server listed
- [x] QA: install the vsix into a clean VS Code profile: the server listed
under **MCP: List Servers**, trusted, `project_overview` answered in
agent mode; `lucisv.mcp.enabled: false` removes it; a multi-root
workspace registers one server per folder; the universal vsix on a
@@ -273,38 +273,47 @@ MCP section), `docs/topo.md` (§1.1 node + §2.8 rows for `lucisv_mcp`, an
`mcp-cache-and-census` README, `TODO-MCP.md` (this file's closing entries).
Depends on M4 and M5 merged.
- [ ] `cache.rs`: the read-only reader of the LSP's `index-cache` (header
- [x] `cache.rs`: the read-only reader of the LSP's `index-cache` (header
check on `CACHE_FORMAT`/`FACTS_FORMAT`/version, per-line checksum,
`FileFacts::decode`, `record_path`); on `--index-cache DIR` a file
whose `content_hash` has a record is `add_facts`'d instead of parsed;
MCP's own `index-cache-mcp` written with the same codec on exit and
read on start; never a write to the LSP's file (a test opens the
store read-only and asserts its bytes after a full MCP session)
- [ ] startup timing on opentitan cold / warm-from-LSP-store /
— done 2026-09-23 (dev): `src/cache.rs`, `tests/cache.rs`; the M4
rule-6 ruling (`force` on `delete_item`) and the first `instructions`
revision delivered in the same lane (`docs/features/mcp-cache-and-census`)
- [x] startup timing on opentitan cold / warm-from-LSP-store /
warm-from-own-store, and the per-call stat sweep, recorded in
`docs/perf/README.md` next to the LSP's scan trace numbers; the
whole-set refactor cost from M3 measured on `rename` in `aes`
- [ ] the token census (PLAN §8): the three tasks, each run twice (file
tools only / with lucisv-mcp) by the same agent model, tokens in and
out from the transcripts, written up in `docs/mcp/census.md` with the
transcripts' task ids; if a task saved nothing, say so — the number
is the deliverable, not its sign
- [ ] `instructions` and tool descriptions revised from what the census
transcripts show the agent misunderstood; `prompts/*` added only if
the census shows a repeated multi-tool sequence worth one prompt
- [ ] `docs/topo.md`: the `lucisv_mcp` node (`──▶` the six libraries; `-.spawn
contract.->` from `editors/vscode`; `-.builds/packages.->` from
`tools/`), the §2.8 rows, the Handshake MCP-1 status (delivered or
still open), and MCP-3 filed in §2.9 if M2's hierarchy walk and the
server's snapshot drifted
- [ ] `CHANGELOG.md` section, `README.md` architecture table row (nine
crates), `docs/repository-analysis.md` map row, CLAUDE.md measurement
line refreshed with the new crate's sizes
- [ ] release **0.56.0** (or the next minor free at the time): tag, CI
— done 2026-09-23 (dev): cold 1.87 s, warm 0.83–0.85 s from either
store, sweep 5.6–6.1 ms, `rename` dry run 2.23–2.28 s
- [x] the token census (PLAN §8): four tasks over three rounds, 20 runs
(Sonnet arms, one Opus pair), base vs mcp on a clean opentitan clone,
graded against lead-computed ground truths — written up in
`mcp_analysis.md` (repo root; the owner's name for it) with the raw
run log in `docs/mcp/census-runs.txt`. Verdict: no wrong answer in
20 runs; −15 % tokens on the whole-design question, +4…+19 % on small
edits, completeness won on the rename
- [x] `instructions` and tool descriptions revised from what the census
transcripts showed (feedback-1/2/3); no `prompts/*` — the census
showed no repeated multi-tool sequence worth one
- [x] `docs/topo.md`: the `lucisv_mcp` node and six edges, the §2.8 rows,
MCP-1 delivered in M3, §2.9 rows 35–42 for the engine findings —
done 2026-09-23 with the M6 commit
- [x] `CHANGELOG.md` section (0.57.0), `README.md` architecture table row
(nine crates), `docs/repository-analysis.md` map row, CLAUDE.md
measurement line — done with the M6 commit and the closing release
- [x] release **0.56.0** (or the next minor free at the time): tag, CI
— done: 0.56.0 (72ff5df, M1–M3.5) and the closing **0.57.0**
(522ae70, tag v0.57.0, 2026-09-23): CI green, 8 assets, the
darwin-arm64 vsix holds bin/{lucisv,lucisv-server,lucisv-mcp} +
mcp.js, the bundled server answers `initialize` as 0.57.0
green, 8 assets, the darwin-arm64 vsix unzipped and checked for three
binaries, the MCP smoke in the release log; the install line and the
`claude mcp add` line given to the owner
- [ ] QA: the read-only promise on the LSP store attacked (a store with a
- [x] QA: the read-only promise on the LSP store attacked (a store with a
torn last line; one from a different version; one whose record hash
matches but whose facts checksum does not — each must be skipped, not
trusted, and the file left byte-identical); a cold start with no
@@ -312,6 +321,166 @@ Depends on M4 and M5 merged.
the census transcripts spot-checked for a tool answer the agent had
to correct by reading the file anyway (each is a finding against a
tool's rendering); verdict
— done 2026-09-23 (Opus; interrupted by the owner moving the
machine, verdict pass-so-far with no blocking finding, recorded in
the README's QA log; the lead reviewed and committed; the temp-file
sweep QA asked for landed in feedback-1 and the census exercised the
warm-start path across 20 runs)
## Feedback rounds (the token census → the server)
### Round 1 → lane feedback-1 (`docs/features/mcp-feedback-1`)
- [x] unresolved mentions (`src/tools/mentions.rs`): every whole-word
spelling of the name in strings, comments, macro text, `define bodies
and macro-rooted paths that no engine answer accounted for, capped at
50; `references` ends with the section, `rename`/`remove_port`/
`add_port` warn with it; `unresolved_mentions` in the JSON; opentitan
cost recorded — done 2026-09-23 (dev)
- [x] descriptions and `instructions`: `hierarchy` leads with "who
instantiates a module", `references` points a module name at
`hierarchy up`; every description trimmed; `tools/list` 30 221 B →
17 981 B (≤ 18 kB, pinned by a wire test) — done 2026-09-23 (dev)
- [x] `add_port` `after`: the port placed after a named one in its line's
layout, each named connection after `.after(…)`; verified against the
engine's appending edit (`src/tools/place.rs`) — done 2026-09-23 (dev)
- [x] stale `index-cache-mcp.*.tmp` swept before the own store is written;
M6 QA's ignored test un-ignored — done 2026-09-23 (dev)
- [x] wire tests: mentions on `references` and `rename`, `after` byte-exact
on an `aes_core`-shaped fixture, catalogue size, sweep — done
2026-09-23 (dev)
- [x] QA: attack the mentions scanner (false positives and misses) and the
`after` verifier; verdict
### Round 2 → lane feedback-2 (`docs/features/mcp-feedback-2`)
- [x] paging header: every paged answer opens `N <noun>` or
`N <noun> (showing a–b)`; `shown` in the JSON; `DEFAULT_LIMIT` 500;
`hierarchy up` from one root counts instantiations (`render.rs`,
the seven paging tools) — done 2026-09-23 (dev)
- [x] `in` path glob (`*`, `**`, `?`, root-relative, before paging) on
`list_units`, `search_symbols`, `references`, `hierarchy`,
`diagnostics`, `defines`; ``0 <noun> (none match `in`)``
(`read.rs::path_match`) — done 2026-09-23 (dev)
- [x] post-edit line `check: diagnostics on …` (`check after writing:` on a
dry run) on `rename`, `add_port`, `remove_port`, `expand_wildcard`,
`extract_module`, `inline_module` (`edit.rs::with_check`) — done
2026-09-23 (dev)
- [x] `INSTRUCTIONS` names `in` (896 characters); catalogue 17 993 B
(≤ 18 000) — done 2026-09-23 (dev)
- [x] wire tests (header cut and whole per tool, `in` per tool with `**`,
`?`, no-match and an escaped name, the check line); fixture
`tests/fixtures/paths/` — done 2026-09-23 (dev)
- [x] QA: attack the path matcher, the "none match" rule and the
`hierarchy` counting; verdict — PASS 2026-09-23 (QA,
`tests/qa_f2.rs`, 14 tests; four low notes in the QA log)
### Round 3 → lane feedback-3 (`docs/features/mcp-feedback-3`)
- [x] `unit_interface`: the instantiation template opt-in (`template`,
default false; text and JSON); `parameters (N):` / `ports (N):`
headers — done 2026-09-23 (dev)
- [x] `hierarchy`: the `#( … )` overrides on the text line opt-in
(`overrides`, default false); the JSON keeps them — done 2026-09-23
(dev)
- [x] `INSTRUCTIONS` names `overrides: true` (896 characters; `template:
true` did not fit); catalogue 17 943 B (≤ 18 000; `dry_run`'s
description trimmed in `edit.rs`, flagged) — done 2026-09-23 (dev)
- [x] wire tests for both defaults and both opt-ins; old pins moved to the
opt-in; measured on the eval clone (`unit_interface prim_fifo_sync`
596 B vs 999 B; `hierarchy up … in ip/**/rtl/*.sv` 22 163 B vs
64 783 B) — done 2026-09-23 (dev)
- [x] QA: attack both flags (defaults, `false`, wrong types, packages,
recursive/noted lines, JSON equality); verdict — PASS 2026-09-23 (QA;
`tests/qa_f3.rs`, 7 tests; differential vs the c2e42b8 binary)
- [x] re-measure census task d (and a, which now needs `overrides: true`)
— done 2026-09-23 as round 3b (d 96k, −10 % vs base; a 111k, the
opt-in was not discovered), written up in `mcp_analysis.md` (aba39e5)
## M7. The lean catalogue (0.58; PLAN §10 — owner's steer 2026-09-23)
Nine tools, the model-visible catalogue under 3 500 bytes, instructions
under 400, short answers, no dry_run/paging, edits told to be trusted.
Feature README `docs/features/mcp-lean-catalogue`. One dev (Opus), one QA
(Opus), on trunk.
- [x] registry: `TOOLS` holds exactly `hierarchy, find, outline, read,
check, rename, port, edit_item, format` in that order; `title` and
`structuredContent` removed from the wire (`Answer` is text only);
`Param.description` gone; `wire.rs` pins the names, the order, the
byte budgets (≤ 3 500 model-visible, ≤ 400 instructions) and that no
schema names `dry_run`, `limit`, `offset`, `in`, `template`,
`overrides`, `force`
- [x] `hierarchy`: no root → counts line + top modules; down = instance
tree with instantiation `file:line`; `up`; `peek`; cap 300;
unknown-root refusal with near matches; opentitan instance set
identical to the old tool (test against `tests/opentitan.rs` truth)
- [x] `find`: declarations + `refs` uses grouped one file per line +
`unresolved:`; macros found; near-match refusal
- [x] `outline` (`file` xor `unit`), `read` (design-wide lookup, ambiguity
refusal), `check` (`ok` when clean; old `diagnostics` line set
preserved on the fixtures)
- [x] `rename` (name-based, `file` disambiguates), `port` (add xor remove),
`edit_item` (four ops, the M4 verifier unchanged, `attacks.rs` green
unchanged), `format` (path or glob, `fix`)
- [x] instructions ≤ 400 bytes per PLAN §10.3; resources render through
the new renderers
- [x] tests: the old suites that exercise dropped tools are ported to the
surviving tool or deleted with a line in the README saying which;
every kept invariant (verifier attacks, all-or-nothing writes, roots,
freshness, cache read-only) keeps its test
- [x] docs: feature README; `docs/site/.../guides/agents.md` table
regenerated by `mcp_smoke.js --tool-table` (+ the promises paragraph:
no dry_run); extension README/CHANGELOG; `CHANGELOG.md` 0.58.0 notes
(unreleased); `docs/topo.md` §2.8 rows; PLAN §4.3/§4.5 marked
superseded by §10
- [x] QA: attack the byte budget (a description that grows), the caps, the
ambiguity refusals, `peek` on a multi-line instantiation with
comments, `port add` after a non-existent port, `edit_item delete`
of a used item, `format` with a glob that matches nothing; differential
`hierarchy`/`check` against the 0.57.0 binary on the fixtures and the
eval clone
- [x] census round 4 (lead): tasks a–d on the lean binary (`bin/lucisv-mcp-r5`),
base arm reused from round 3; written up in `mcp_analysis.md` — done
2026-09-24 (9242594): 6/6 correct incl. one Opus run; a −1 %, d parity
over two runs, b +10 %, c +9 % vs the base re-run
- [x] release 0.58.0 when round 4 meets PLAN §10.5 — tagged 2026-09-24
(a −1 %, d parity, b +10 %, c +9 % vs the base re-run; 6/6 correct);
gates: 4 922 tests / 0 failed, corpus 814/820
## M8. Read-only mode (0.59; PLAN §11 — owner's request 2026-09-29)
`lucisv-mcp --read-only`: five tools, ≤ 1 800 model-visible bytes,
instructions ≤ 300, never writes inside a root; full mode unchanged.
Feature README `docs/features/mcp-read-only`. One dev (Opus), one QA
(Opus), on trunk.
- [x] server: `--read-only` parsed, in the usage line; the registry
filtered by mode (`tools/list`, `tools/call`); read-only
instructions; the unknown-tool message for the four edit tools
- [x] tests (`tests/wire.rs` or a new `tests/read_only.rs`): names and
order, both budgets, full mode unchanged byte for byte, every
full-catalogue tool name called in read-only mode leaves the tree
untouched (sizes, mtimes, names)
- [x] extension: `lucisv.mcp.mode` setting, label, args, change event,
copy-config (`lucisv-ro` key, `--read-only`), node tests;
`mcp_smoke.js --read-only`; `tools/release.sh` runs both smokes
- [x] docs: feature README; Agents guide (a "Read-only mode" section, the
table's `writes` column already tells the five); extension
README/CHANGELOG; `CHANGELOG.md` 0.59.0 (unreleased);
`docs/topo.md` §2.8; `tools/RELEASING.md`; manual-acceptance rows
- [x] QA: attack the no-write promise (every edit tool name, resources,
malformed calls, a call racing a mode it does not have), the budgets,
full-mode identity against the 0.58.0 binary, the extension tests
- [x] census round 5 (lead): tasks a and d on `--read-only` — done
2026-09-29 (74c5631): 7 runs, all correct; with same-day base controls
a +8 %, d −8 % (parity); found and fixed the `peek` cap defect
(`hierarchy` caps at 300 instances, 100 with `peek`)
- [x] release 0.59.0 — tagged 2026-09-29; gates: clippy -D warnings, fmt,
72 suites + 6 doc suites (4 937 passed, 0 failed), corpus 814/820,
node tests 6/6. The first suite run stalled 25 min in the vlog_linter
doc-test and was cut by the guard; the doc-tests passed in under a
minute as their own gate
## Open questions for the owner (answer before the lane that needs it)
+145
View File
@@ -6939,3 +6939,148 @@ Nothing else.
(23e2e4b, v0.55.0), CI green on the release commit, 8 assets, the
darwin-arm64 vsix at 0.55.0 with both binaries,
`hierarchySections.js`, `extract.js`, no `*_test.js`.
## 65. Stabilization round 1 (planned 2026-09-30, owner's order) — two correctness gaps, then the doc-test stall
Three lanes, one at a time on trunk, dev (Opus) → QA (Opus) → lead review →
commit. Rules as §63/§64: every suite and sweep through `tools/guard.sh`,
never piped (log to a file, check `guard exit` and the suite count); no
`sleep` over 60 s; never `grep` without a path; opentitan read-only (the
eval clone `~/.cache/lucisv-eval/ot` may be read and, for an edit test,
restored with `git -C … checkout -- <file>`). Ships as 0.60.0.
### 65.1 Rename and references through a generate block label (topo §2.9-43, MCP-14)
`rename` of a generate block label (`for (…) begin : g_lane … end`) rewrites
the label and nothing else: a hierarchical path through it
(`g_lane[0].lane_q`, `u_x.g_lane[1].sig` from another file) keeps the old
name and no longer resolves, with no warning; `find_references` on the label
reports no use. The MCP layer refuses the rename (any `block`-kind
declaration); the LSP and the CLI still perform it. Feature README
`docs/features/generate-label-rename`.
The contract to reach, in `vlog_semantic` (resolution) and `vlog_refactor`
(`find_references`, `rename`, the verifier):
- [x] a path segment that names a generate block — bare (`g.x`), indexed
(`g[0].x`, `g[i].x`), nested (`g_a.g_b[2].x`), and behind an instance
path from another file (`u_x.g[0].x`) — resolves to the block's label
and is a reference to it
- [x] `find_references` on the label lists the declaration, the closing
`end : label` and every such segment, same-file and cross-file, through
the same fan-out §64.1 uses for hierarchical-surface declarations
- [x] `rename` rewrites all of them, all-or-nothing; a closing label is
rewritten with its opening one; a segment it cannot resolve (macro
text, a string) is a warning, as for any other declaration; an
unnamed block (`genblk1`) is not renameable
- [x] named procedural blocks (`begin : lbl` in `always`/`initial`/
functions/tasks): the label, its closing label and `disable lbl;` are
one reference set
- [x] the verifier accepts exactly these rewrites and nothing more:
masked-corruption attack tests for any normalization it gains
(CLAUDE.md invariant 4)
- [x] the LSP (`textDocument/references`, `rename`, `prepareRename`) and
the CLI get it through the engine; `lucisv-mcp`'s refusal of a
`block`-kind rename (`crates/lucisv_mcp/src/tools/edit.rs`) is lifted
and its tests (`tests/qa_m7.rs`) assert the rename instead
- [x] opentitan: a generate label with cross-file uses renamed on the eval
clone — every site rewritten, the files still parse, clone restored
- [x] rename warnings and mentions are scoped to the renamed declaration
(lead's inspection 2026-09-30: a module member's bare spelling
elsewhere is not news; a dotted one and a unit/package name's every
spelling still are)
- [x] QA: attack the index forms, nesting, shadowing (a net and a block of
the same name in different scopes), a label used only in a closing
label, `disable`, an escaped label, a label inside an `ifdef`
### 65.2 LSP `references` omits three `aes` instantiations (topo §2.9-36, MCP-6)
On opentitan, `textDocument/references` at the `aes` instantiation in
`hw/ip/aes/dv/tb/tb.sv` (and at its `.clk_i` connection) answers 11 and 9
locations; the whole-set engine answers 14 and 12 — the same plus the three
top-level instantiations in
`hw/top_{earlgrey,darjeeling,englishbreakfast}/rtl/autogen/*_pd_main.sv`
(`aes #(` and `.clk_i(clkmgr_clocks_i.clk_main_aes)`). Stable after a 30 s
settle, so not an indexing race. Feature README
`docs/features/references-fanout-pd-main`.
- [ ] root cause named (the fan-out/scope selection in `lucisv_server` —
`module_select`, `state/` scope widening, or the index's
instantiation facts for those three files; they are large generated
files, check the 1 MiB cap and the word census)
- [ ] the LSP answer equals the whole-set engine's for the module name and
for a port of it, from the declaration and from a use; a regression
test with a fixture that reproduces the cause (not only opentitan)
- [ ] an opentitan test (ignored by default, like `tests/opentitan.rs`)
pinning the 14 and 12
- [ ] QA: the same comparison for five other modules instantiated from a
`*_pd_main.sv` top, and for `rename`'s fan-out (does rename see the
three sites?)
### 65.3 The combined test command stalls entering the doc-tests
`cargo test --workspace` under `tools/guard.sh`: on 2026-09-29 (0.59.0 gate)
every suite finished in about two minutes and the run then sat 25 minutes
in `Doc-tests vlog_linter` until the guard cut it; on 2026-09-30 an
independent session's run hit its 600 s guard "entering the final doc-test
harness". `cargo test --workspace --doc` alone passes in under a minute.
- [ ] reproduce (how often, which doc-test, what the stuck process tree
is — `rustdoc`, `rust_out`, stdin?) and name the cause; `guard.sh`
runs the command with `0<&3` — check what the doc-test harness
inherits as stdin when the gate runs in the background
- [ ] fix at the cause (the harness, the doc-test, or the guard), and make
the release gate a script (`tools/gates.sh`) that runs fmt, clippy,
the test build, the suites, the doc-tests, the corpus gate and the
node tests as separate guarded steps with logs kept and a summary
that shows a kill — `tools/RELEASING.md` and CLAUDE.md point at it
- [ ] ten consecutive green runs of the gate script recorded
### 65.4 Resolve a hierarchical path rooted at a top-level module name (lead to schedule; from §65.1 QA F1)
A path whose head is a top module declared in another file — `tb.dut.u_x.sig`,
the shape every opentitan DV `force`/`$deposit`/`uvm_hdl_*` path takes
(IEEE 1800 §23.6: a top-level module name is the root of a hierarchical
name) — resolves nothing today: `tb` is bound as a `Target::Lexical` use,
misses in the writing file, and `resolve::member_site`'s `head_site` stops
the spine, so no segment after it is a reference and a rename of `dut`'s
declarations leaves the path behind (since §65.1 with a warning, not
silently). The root lookup belongs in `vlog_semantic/src/resolve.rs`
`head_site`: when the lexical walk misses **and** the head is followed by a
`.`, answer `MemberSite::Unit { path: head, surface: Hierarchical }` so the
workspace's `fold_path` walks `tb` → `dut`'s type → … exactly as it walks an
instance path today — with the head itself recorded as a `Target::Module`-like
use so `tb` stops being `NotFound`. QA's repro: `vlog_refactor/tests/
qa_generate_label.rs` `a_path_rooted_at_another_files_top_module_is_never_silently_left_behind`
(`probe.sv`: `assign o = tb.dut.g_sw[0].buf_q;`), and on opentitan
`hw/ip/keymgr_dpe/dv/env/keymgr_dpe_if.sv:514,515,517` (`force
tb.dut.gen_sw_assigns[i]…`) under `rename gen_sw_assigns`. Watch: a name
that is both a local and a top module (the local wins), `$root.tb…`, and the
index cost of the extra external candidates on every DV path.
- [ ] root lookup in `head_site`, the head recorded as a module use
- [ ] QA's repro renames the path instead of warning; the §65.1 warning
still fires for a root the workspace does not declare
### 65.6 Rename inside included fragments (lead to schedule; from §65.1 QA final H4)
A module that `` `include``s a fragment of its own body (`prim_ram_1p.sv`
including `prim_util_memload.svh`, every opentitan `*_assert.svh`) has that
fragment's text pasted into its scope, but lucisv analyses the fragment as a
file of its own: a bare `mem` there resolves to nothing, so `rename
prim_ram_1p.mem` edits the module and — since §65.1 — only *warns*
(`prim_util_memload.svh:12,24,32,43: `mem` is used in a file `prim_ram_1p.sv`
includes and was left unchanged`). Renaming there means binding a fragment
in the scope of the file that includes it (the include site's scope chain as
the fragment's outer scope, as `fragment-mode` does for a bare body) and
verifying the edit against that binding; a fragment included from two
modules is two bindings and must agree or be refused. QA's repro:
`vlog_refactor/tests/qa_warning_scope.rs`
`a_bare_use_in_plain_included_code_is_renamed_or_said` (`m_body.svh`:
`assign o = state_q;` included by `m.sv`).
- [ ] a fragment included by exactly one unit is bound in that unit's scope
and renamed with it; one included by several is refused unless every
binding agrees
- [ ] QA's repro renames the fragment's use; the §65.1 warning remains for
what cannot be bound
+28 -103
View File
@@ -1,8 +1,9 @@
//! The one write path every edit tool goes through.
//!
//! A tool hands over a [`Plan`] — per file, the text it computed against and
//! the text it wants written — and gets back either the unified diff
//! (`dry_run`) or a summary of what was written. The write is all-or-nothing
//! the text it wants written — and gets back which files were written. There
//! is no dry run (PLAN §10): an edit is a file write the agent is told to
//! trust, so the verification happens here, before it. The write is all-or-nothing
//! as far as a filesystem allows: every file's new text exists before the
//! first write; every target is checked to lie inside a root; every file is
//! re-read and compared with the text the plan was computed against, and a
@@ -16,12 +17,9 @@ use std::fs;
use std::path::{Path, PathBuf};
use lucisv_core::atomic::write_atomic;
use lucisv_core::diff::unified;
use serde_json::{json, Value};
use vlog_refactor::{RefactorEdit, TextEdit};
use crate::project::Project;
use crate::tools::Answer;
/// One file an edit rewrites or creates.
pub struct Change {
@@ -40,12 +38,8 @@ pub struct Change {
pub struct Plan {
/// The files to write, in any order.
pub changes: Vec<Change>,
/// Files the tool looked at and left as they were (`format`, `fix_lint`).
pub unchanged: Vec<PathBuf>,
/// The engine's sentences about what it deliberately left alone.
pub warnings: Vec<String>,
/// One line the tool adds to the summary (`fix_lint`'s rules), if any.
pub note: Option<String>,
}
impl Plan {
@@ -96,27 +90,37 @@ fn apply_edits(text: &str, edits: &[TextEdit]) -> Result<String, String> {
Ok(out)
}
/// Check, then diff or write, then summarise. `dry_run` writes nothing.
pub fn run(project: &Project, plan: Plan, dry_run: bool) -> Result<Answer, String> {
/// What a plan came to on disk: the root-relative files rewritten and
/// created, and those whose new text equals the old.
#[derive(Debug, Default)]
pub struct Written {
pub changed: Vec<String>,
pub created: Vec<String>,
pub unchanged: Vec<String>,
}
/// Check every target, then write every changed file, or nothing.
pub fn run(project: &Project, plan: &Plan) -> Result<Written, String> {
for change in &plan.changes {
contained(project, change)?;
}
let mut moved: Vec<&Change> =
plan.changes.iter().filter(|c| c.created || c.before != c.after).collect();
moved.sort_by(|a, b| a.path.cmp(&b.path));
let mut unchanged: Vec<String> = plan
.changes
.iter()
.filter(|c| !c.created && c.before == c.after)
.map(|c| project.relative(&c.path))
.chain(plan.unchanged.iter().map(|path| project.relative(path)))
.collect();
unchanged.sort();
let files: Vec<Written> = moved.iter().map(|change| Written::of(project, change)).collect();
if !dry_run {
commit(&moved, |path| project.relative(path))?;
commit(&moved, |path| project.relative(path))?;
let mut written = Written::default();
for change in &plan.changes {
let file = project.relative(&change.path);
match (change.created, change.before == change.after) {
(true, _) => written.created.push(file),
(false, false) => written.changed.push(file),
(false, true) => written.unchanged.push(file),
}
}
Ok(summary(&files, &unchanged, &plan, dry_run))
written.changed.sort();
written.created.sort();
written.unchanged.sort();
Ok(written)
}
/// A target must lie inside a root: an existing file resolves into one; a
@@ -195,85 +199,6 @@ pub fn commit(changes: &[&Change], shown: impl Fn(&Path) -> String) -> Result<()
Ok(())
}
/// One file of the summary: its name, its diff and the lines it moves.
struct Written {
file: String,
created: bool,
diff: String,
added: usize,
removed: usize,
}
impl Written {
fn of(project: &Project, change: &Change) -> Written {
let file = project.relative(&change.path);
let diff = unified(&file, &change.before, &change.after);
// The two header lines are `---`/`+++`; every later line starting
// with a sign is one line of the change.
let body = diff.lines().skip(2);
let added = body.clone().filter(|line| line.starts_with('+')).count();
let removed = body.filter(|line| line.starts_with('-')).count();
Written { file, created: change.created, diff, added, removed }
}
}
/// The text and JSON an edit answers with.
fn summary(files: &[Written], unchanged: &[String], plan: &Plan, dry_run: bool) -> Answer {
let created = files.iter().filter(|f| f.created).count();
let mut text = if files.is_empty() {
"unchanged\n".to_string()
} else {
let tail = if dry_run { " (dry run: nothing written)" } else { "" };
format!("files: {} changed, {created} created{tail}\n", files.len() - created)
};
for file in files {
let mark = if file.created { " (created)" } else { "" };
text.push_str(&format!(" {} +{} -{}{mark}\n", file.file, file.added, file.removed));
}
if !unchanged.is_empty() && !files.is_empty() {
text.push_str(&format!("unchanged: {}\n", unchanged.join(", ")));
}
if let Some(note) = &plan.note {
text.push_str(note);
text.push('\n');
}
push_warnings(&mut text, &plan.warnings);
if dry_run {
files.iter().for_each(|file| text.push_str(&file.diff));
}
Answer { text, structured: structured(files, unchanged, plan, dry_run) }
}
fn push_warnings(text: &mut String, warnings: &[String]) {
if warnings.is_empty() {
return;
}
text.push_str("warnings:\n");
for warning in warnings {
text.push_str(&format!(" {warning}\n"));
}
}
fn structured(files: &[Written], unchanged: &[String], plan: &Plan, dry_run: bool) -> Value {
let entry = |file: &Written| {
let mut entry = json!({ "file": file.file, "added": file.added, "removed": file.removed });
if dry_run {
entry["diff"] = Value::from(file.diff.clone());
}
entry
};
let changed: Vec<Value> = files.iter().filter(|f| !f.created).map(entry).collect();
let created: Vec<Value> = files.iter().filter(|f| f.created).map(entry).collect();
json!({
"changed": changed,
"created": created,
"unchanged": unchanged,
"warnings": plan.warnings,
"note": plan.note,
"dry_run": dry_run,
})
}
#[cfg(test)]
mod tests {
use super::*;
@@ -394,7 +319,7 @@ mod tests {
};
let refuse = |change: Change| {
let plan = Plan { changes: vec![change], ..Plan::default() };
run(&project, plan, false).err().unwrap()
run(&project, &plan).err().unwrap()
};
let beside = refuse(create(outside.join("n.sv")));
assert!(beside.contains("would be created outside every root"), "{beside}");
+223
View File
@@ -0,0 +1,223 @@
//! The index caches a startup reads instead of parsing (PLAN §6): the
//! language server's `index-cache`, **read only, never written**, and this
//! server's own `index-cache-mcp` beside it, in the same codec, written once
//! when the session ends.
//!
//! The codec is `lucisv_server::index_cache`'s, restated here because its
//! constants are private to that crate (Handshake MCP-14 in
//! `docs/features/mcp-cache-and-census/README.md`; a test pins the restated
//! header and line formats against that file's source text). A store is a
//! header line `lucisv-index-cache\t<CACHE_FORMAT>\t<FACTS_FORMAT>\t<version>`
//! and one record per line, `<content hash:016x>\t<encoded facts>\t<fnv of
//! the facts:016x>`. A record is used only for a file whose bytes hash to its
//! content hash, so it can only ever stand in for the parse of exactly those
//! bytes; a store from another build, a torn line or a line whose checksum
//! fails costs a parse and nothing else.
use std::collections::HashMap;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};
use lucisv_core::cache::content_hash;
use vlog_semantic::{record_path, FileFacts, FACTS_FORMAT};
/// The language server's store in the cache directory. Read, never written.
pub const EDITOR_STORE: &str = "index-cache";
/// This server's own store in the same directory.
pub const OWN_STORE: &str = "index-cache-mcp";
/// `lucisv_server::index_cache::CACHE_FORMAT`: the framing's version.
const CACHE_FORMAT: u32 = 2;
/// lucisv's version: another release may parse the same bytes into other
/// facts, so its store is not read.
const VERSION: &str = env!("CARGO_PKG_VERSION");
/// Which store a record came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Source {
/// The language server's `index-cache`.
Editor,
/// This server's `index-cache-mcp`.
Own,
}
/// The records of both stores, still encoded, keyed by the path they
/// describe and the hash of the bytes they were read from.
#[derive(Default)]
pub struct Records {
held: HashMap<(PathBuf, u64), (Source, String)>,
}
/// How a startup used the stores.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Reuse {
/// Files whose record came from the language server's store.
pub editor: usize,
/// Files whose record came from this server's own store.
pub own: usize,
}
impl Reuse {
/// One more file taken from `source`.
pub fn count(&mut self, source: Source) {
match source {
Source::Editor => self.editor += 1,
Source::Own => self.own += 1,
}
}
}
impl Records {
/// Both stores in `dir`. A missing directory or store is a cold start,
/// silently (the editor may not have made the directory yet); a store
/// from another build is ignored whole, with one line on stderr.
pub fn load(dir: &Path) -> Records {
let mut records = Records::default();
// Own first, so a record both stores hold is credited to the editor.
records.read(&dir.join(OWN_STORE), Source::Own);
records.read(&dir.join(EDITOR_STORE), Source::Editor);
records
}
/// Read one store into the map.
fn read(&mut self, store: &Path, source: Source) {
let Ok(bytes) = fs::read(store) else { return };
let mut lines = store_lines(&bytes).into_iter();
match lines.next() {
None => return,
Some(first) if first == header().as_bytes() => {}
Some(_) => {
eprintln!(
"lucisv-mcp: ignoring the index cache {}: not written by lucisv {VERSION}",
store.display()
);
return;
}
}
for line in lines {
if let Some((path, content, facts)) = std::str::from_utf8(line).ok().and_then(parse) {
self.held.insert((path, content), (source, facts.to_string()));
}
}
}
/// The facts of `path` when its bytes hash to `content`, and where they
/// came from. A record that no longer decodes is a miss.
pub fn take(&mut self, path: &Path, content: u64) -> Option<(FileFacts, Source)> {
let (source, encoded) = self.held.remove(&(path.to_path_buf(), content))?;
let facts = FileFacts::decode(&encoded)?;
(facts.path() == path).then_some((facts, source))
}
}
/// Write this server's own store in `dir`: the header, then one record per
/// `(content hash, facts)`, in the order given. Atomic — a temporary file
/// renamed over the store — so a reader sees the old store or the new one.
/// Never touches [`EDITOR_STORE`].
pub fn write_own(dir: &Path, records: &[(u64, &FileFacts)]) -> io::Result<usize> {
fs::create_dir_all(dir)?;
// Self-ignoring, as the language server marks the directory: a cache
// path inside the project is a plausible thing to pass.
let ignore = dir.join(".gitignore");
if !ignore.exists() {
let _ = fs::write(&ignore, "*\n");
}
sweep_stale_temps(dir);
let mut text = header();
text.push('\n');
let mut written = 0;
for (content, facts) in records {
// A path that cannot be written on a line (not UTF-8, a tab) is
// simply not cached.
if let Some(encoded) = facts.encode() {
text.push_str(&line(*content, &encoded));
text.push('\n');
written += 1;
}
}
let tmp = dir.join(format!("{OWN_STORE}.{}.tmp", std::process::id()));
let written_through =
fs::write(&tmp, text).and_then(|()| fs::rename(&tmp, dir.join(OWN_STORE)));
if let Err(problem) = written_through {
let _ = fs::remove_file(&tmp);
return Err(problem);
}
Ok(written)
}
/// How old a temporary store file must be before a writer counts it as a
/// dead writer's: a live writer renames its own within a second or two.
const STALE_TEMP: Duration = Duration::from_secs(600);
/// Remove the `index-cache-mcp.<pid>.tmp` files in `dir` older than
/// [`STALE_TEMP`] — left by a writer killed between its write and its
/// rename (M6 QA finding 2). A younger one may be a concurrent writer's,
/// and is left alone; anything else in the directory is never touched.
fn sweep_stale_temps(dir: &Path) {
let Ok(entries) = fs::read_dir(dir) else { return };
let now = SystemTime::now();
for entry in entries.flatten() {
let name = entry.file_name();
let Some(name) = name.to_str() else { continue };
let ours = name
.strip_prefix(OWN_STORE)
.and_then(|rest| rest.strip_prefix('.'))
.and_then(|rest| rest.strip_suffix(".tmp"))
.is_some_and(|pid| !pid.is_empty() && pid.bytes().all(|b| b.is_ascii_digit()));
let modified = entry.metadata().and_then(|meta| meta.modified());
let stale =
modified.is_ok_and(|at| now.duration_since(at).is_ok_and(|age| age > STALE_TEMP));
if ours && stale && entry.file_type().is_ok_and(|kind| kind.is_file()) {
let _ = fs::remove_file(entry.path());
}
}
}
/// The first line of a store this build reads and writes.
fn header() -> String {
format!("lucisv-index-cache\t{CACHE_FORMAT}\t{FACTS_FORMAT}\t{VERSION}")
}
/// One record: the content hash, the encoded facts, their checksum.
fn line(content: u64, facts: &str) -> String {
format!("{content:016x}\t{facts}\t{:016x}", content_hash(facts.as_bytes()))
}
/// One record read back: its path, content hash and still-encoded facts.
/// `None` for anything but a whole record whose facts match their checksum —
/// which includes a torn last line.
fn parse(line: &str) -> Option<(PathBuf, u64, &str)> {
let (hash, rest) = line.split_once('\t')?;
let content = hex16(hash)?;
// No encoded field holds a raw tab, so the facts run to the last one.
let (facts, checksum) = rest.rsplit_once('\t')?;
if hex16(checksum)? != content_hash(facts.as_bytes()) {
return None;
}
Some((record_path(facts)?, content, facts))
}
/// A 16-digit hexadecimal field, exactly as wide as [`line`] writes it.
fn hex16(field: &str) -> Option<u64> {
if field.len() != 16 {
return None;
}
u64::from_str_radix(field, 16).ok()
}
/// The store's lines as bytes (a torn multi-byte character costs its own
/// line only), `\r` stripped as `str::lines` would.
fn store_lines(bytes: &[u8]) -> Vec<&[u8]> {
let body = bytes.strip_suffix(b"\n").unwrap_or(bytes);
if body.is_empty() {
return Vec::new();
}
body.split(|byte| *byte == b'\n').map(|line| line.strip_suffix(b"\r").unwrap_or(line)).collect()
}
#[cfg(test)]
mod tests;
+143
View File
@@ -0,0 +1,143 @@
//! The caches against the rebuild oracle: an index started from records is
//! the index a cold build over the same files makes
//! (`WorkspaceIndex::fingerprint`), and every record that is not exactly
//! right is a parse, not an answer.
use std::fs;
use std::path::{Path, PathBuf};
use super::*;
use crate::project::Project;
fn scratch(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("lucisv-mcp-cache-{name}-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(dir.join("src")).unwrap();
fs::create_dir_all(dir.join("cache")).unwrap();
fs::canonicalize(dir).unwrap()
}
/// Three files that reach each other: a package, a module importing it, a
/// module instantiating that one through `.*`, and a macro.
fn design(dir: &Path) {
let src = dir.join("src");
fs::write(src.join("p.sv"), "package p; parameter int W = 4; endpackage\n").unwrap();
let leaf = "`define ONE 1'b1\nmodule leaf import p::*; (input logic [W-1:0] d);\nendmodule\n";
fs::write(src.join("leaf.sv"), leaf).unwrap();
let top = "module top(input logic [3:0] d);\n leaf u_leaf(.*);\nendmodule\n";
fs::write(src.join("top.sv"), top).unwrap();
}
fn cold(dir: &Path) -> String {
Project::open(vec![dir.join("src")], None).index().fingerprint()
}
fn warm(dir: &Path) -> Project {
Project::open_cached(vec![dir.join("src")], None, Some(dir.join("cache")))
}
/// A store in the language server's format, one record per file as its
/// parse finds it.
fn editor_store(dir: &Path) -> String {
let mut text = format!("{}\n", header());
let mut paths: Vec<PathBuf> =
fs::read_dir(dir.join("src")).unwrap().map(|e| e.unwrap().path()).collect();
paths.sort();
for path in paths {
let bytes = fs::read(&path).unwrap();
let facts = FileFacts::of(path.clone(), std::str::from_utf8(&bytes).unwrap());
text.push_str(&line(content_hash(&bytes), &facts.encode().unwrap()));
text.push('\n');
}
text
}
#[test]
fn the_codec_is_the_language_servers_own() {
let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("../lucisv_server/src/index_cache.rs");
let source = fs::read_to_string(source).unwrap();
for pinned in [
format!("const FILE: &str = \"{EDITOR_STORE}\";"),
format!("const CACHE_FORMAT: u32 = {CACHE_FORMAT};"),
"const VERSION: &str = env!(\"CARGO_PKG_VERSION\");".to_string(),
"format!(\"lucisv-index-cache\\t{CACHE_FORMAT}\\t{FACTS_FORMAT}\\t{VERSION}\")".to_string(),
"format!(\"{content:016x}\\t{facts}\\t{:016x}\", content_hash(facts.as_bytes()))"
.to_string(),
] {
assert!(source.contains(&pinned), "index_cache.rs no longer says {pinned}");
}
assert_eq!(header(), format!("lucisv-index-cache\t2\t{FACTS_FORMAT}\t{VERSION}"));
}
#[test]
fn a_warm_start_from_the_editors_store_is_the_cold_index() {
let dir = scratch("editor");
design(&dir);
fs::write(dir.join("cache").join(EDITOR_STORE), editor_store(&dir)).unwrap();
let project = warm(&dir);
assert_eq!(project.reuse(), Some(Reuse { editor: 3, own: 0 }));
assert_eq!(project.index().fingerprint(), cold(&dir));
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_warm_start_from_its_own_store_is_the_cold_index_and_a_changed_file_is_parsed() {
let dir = scratch("own");
design(&dir);
let first = warm(&dir);
assert_eq!(first.reuse(), Some(Reuse::default()));
let (store, written) = first.save_cache().unwrap().unwrap();
assert_eq!((store, written), (dir.join("cache").join(OWN_STORE), 3));
assert!(!dir.join("cache").join(EDITOR_STORE).exists(), "the editor's store is never written");
let second = warm(&dir);
assert_eq!(second.reuse(), Some(Reuse { editor: 0, own: 3 }));
assert_eq!(second.index().fingerprint(), cold(&dir));
fs::write(dir.join("src/top.sv"), "module top2; leaf u_leaf(.d(4'b0)); endmodule\n").unwrap();
let third = warm(&dir);
assert_eq!(third.reuse(), Some(Reuse { editor: 0, own: 2 }));
assert_eq!(third.index().fingerprint(), cold(&dir));
assert_eq!(third.index().units("top2").len(), 1);
assert!(third.index().units("top").is_empty());
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_torn_a_forged_and_a_foreign_record_are_each_a_parse() {
let dir = scratch("damaged");
design(&dir);
let good = editor_store(&dir);
let lines: Vec<&str> = good.lines().collect();
// Record 1 (leaf.sv): its hash still the file's, a macro renamed in its
// facts, its checksum left as it was.
assert!(lines[1].contains("/leaf.sv\t") && lines[1].contains("ONE"));
let forged = lines[1].replacen("ONE", "TWO", 1);
// Record 3 (top.sv): torn inside its facts, no newline.
let torn = &lines[3][..lines[3].len() / 2];
let store = format!("{}\n{forged}\n{}\n{torn}", lines[0], lines[2]);
fs::write(dir.join("cache").join(EDITOR_STORE), &store).unwrap();
let project = warm(&dir);
assert_eq!(project.reuse(), Some(Reuse { editor: 1, own: 0 }), "only p.sv is whole");
assert_eq!(project.index().fingerprint(), cold(&dir));
let foreign = good.replacen(VERSION, "0.0.0", 1);
fs::write(dir.join("cache").join(EDITOR_STORE), &foreign).unwrap();
assert_eq!(warm(&dir).reuse(), Some(Reuse::default()), "another version's store is not read");
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_record_filed_under_another_path_or_hash_is_not_taken() {
let mut records = Records::default();
let facts = FileFacts::of(PathBuf::from("/a.sv"), "module a; endmodule\n");
let encoded = facts.encode().unwrap();
let record = line(7, &encoded);
let parsed = parse(&record).unwrap();
assert_eq!((parsed.0.as_path(), parsed.1), (Path::new("/a.sv"), 7));
records.held.insert((parsed.0, parsed.1), (Source::Editor, parsed.2.to_string()));
assert!(records.take(Path::new("/a.sv"), 8).is_none(), "another hash");
assert!(records.take(Path::new("/b.sv"), 7).is_none(), "another path");
assert!(records.take(Path::new("/a.sv"), 7).is_some());
assert!(parse("0000000000000007\tx").is_none(), "no checksum");
assert!(parse("7\tx\t0000000000000000").is_none(), "a hash of the wrong width");
}
+17 -3
View File
@@ -8,6 +8,7 @@
//! `docs/features/mcp-transport/README.md`.
mod apply;
mod cache;
mod project;
mod render;
mod resources;
@@ -21,8 +22,7 @@ use std::process::ExitCode;
use vlog_parser::PARSE_STACK_SIZE;
/// What someone who spelled an argument wrong is told, on stderr.
const USAGE: &str =
"usage: lucisv-mcp [--root DIR]... [--filelist FILE] [--index-cache DIR] [--verbose]";
const USAGE: &str = "usage: lucisv-mcp [--root DIR]... [--filelist FILE] [--index-cache DIR] [--read-only] [--verbose]";
/// The command line, parsed.
#[derive(Debug, Default, PartialEq, Eq)]
@@ -31,8 +31,11 @@ pub struct Options {
pub roots: Vec<PathBuf>,
/// `--filelist FILE`: overrides the configured `filelist`.
pub filelist: Option<PathBuf>,
/// `--index-cache DIR`: accepted and stored; read from M6 on.
/// `--index-cache DIR`: the language server's index cache directory,
/// read at startup; this server's own store is written there on exit.
pub index_cache: Option<PathBuf>,
/// `--read-only`: the five read tools only (PLAN §11).
pub mode: tools::Mode,
/// `--verbose`: per-call timing lines on stderr.
pub verbose: bool,
}
@@ -86,6 +89,7 @@ fn parse_args(args: impl Iterator<Item = String>) -> Result<Options, String> {
"--root" => options.roots.push(value("--root")?),
"--filelist" => options.filelist = Some(value("--filelist")?),
"--index-cache" => options.index_cache = Some(value("--index-cache")?),
"--read-only" => options.mode = tools::Mode::ReadOnly,
"--verbose" => options.verbose = true,
other => return Err(format!("unknown option: {other}")),
}
@@ -112,13 +116,23 @@ mod tests {
"f.f",
"--index-cache",
"c",
"--read-only",
"--verbose",
])
.unwrap();
assert_eq!(options.roots, vec![PathBuf::from("a"), PathBuf::from("b")]);
assert_eq!(options.filelist, Some(PathBuf::from("f.f")));
assert_eq!(options.index_cache, Some(PathBuf::from("c")));
assert_eq!(options.mode, tools::Mode::ReadOnly);
assert!(options.verbose);
assert_eq!(parse(&["--verbose"]).unwrap().mode, tools::Mode::Full);
}
#[test]
fn the_usage_line_names_every_flag() {
for flag in ["--root", "--filelist", "--index-cache", "--read-only", "--verbose"] {
assert!(USAGE.contains(flag), "{flag}");
}
}
#[test]
+3 -29
View File
@@ -16,7 +16,7 @@ use vlog_parser::ast::SourceFile;
use vlog_parser::defines::{collect_defines, DefineTable};
use vlog_parser::token::Token;
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex, ParseDiagnostic};
use vlog_semantic::{analyze, resolve_external, ExternalResolutions, Semantics, WorkspaceIndex};
use vlog_semantic::{analyze, Semantics};
/// How many analyses are kept. An agent's calls cluster on a handful of
/// files; a whole-design answer never needs a file's analysis at all.
@@ -64,27 +64,6 @@ impl Analysis {
Analysis { text, lines, tokens, defines, tree, diagnostics, semantics }
}
/// The workspace overlay over this file's references, against `index` as
/// it is now. Not cached: the index moves under an unchanged file.
pub fn external(&self, index: &WorkspaceIndex) -> ExternalResolutions {
resolve_external(&self.semantics, index)
}
/// The token covering byte `offset`, if any.
pub fn token_at(&self, offset: u32) -> Option<&Token> {
let after = self.tokens.partition_point(|token| token.span.start <= offset);
let token = self.tokens.get(after.checked_sub(1)?)?;
token.span.contains(offset).then_some(token)
}
/// The text of 1-based line `line`, without its line ending.
pub fn line_text(&self, line: u32) -> &str {
match self.lines.line_range(line) {
Some(range) => self.slice(range.start, range.end).trim_end_matches('\r'),
None => "",
}
}
/// The 1-based first and last line a byte range covers. A range ending
/// just after a newline ends on the line before it.
pub fn line_span(&self, start: u32, end: u32) -> (u32, u32) {
@@ -139,18 +118,13 @@ mod tests {
assert_eq!(analysis.line_span(0, 10), (1, 1));
assert_eq!(analysis.slice(0, 6), "module");
assert!(analysis.diagnostics.is_empty());
assert_eq!(analysis.line_text(2), "endmodule");
assert_eq!(analysis.line_text(9), "");
}
#[test]
fn tokens_and_defines_are_kept_and_a_token_is_found_by_offset() {
fn tokens_and_defines_are_kept() {
let analysis = Analysis::of("`define W 8\r\nmodule a; endmodule\r\n".to_string());
assert_eq!(analysis.defines.latest("W").map(|d| d.body.as_str()), Some("8"));
assert_eq!(analysis.line_text(1), "`define W 8");
let module = analysis.token_at(14).map(|t| t.text.as_str());
assert_eq!(module, Some("module"));
assert!(analysis.token_at(1000).is_none());
assert!(analysis.tokens.iter().any(|t| t.text == "module"));
}
#[test]
+1 -1
View File
@@ -29,7 +29,7 @@ pub struct FileSet {
pub files: Vec<PathBuf>,
/// The filelist the set was read from, when it was.
pub filelist: Option<PathBuf>,
/// Problems worth one line each on stderr and in `project_overview`.
/// Problems worth one line each (unreadable filelists, links leaving a root).
pub warnings: Vec<String>,
/// Walked files skipped for being over [`MAX_FILE_BYTES`].
pub skipped_large: usize,
+86 -46
View File
@@ -10,9 +10,10 @@ use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::time::{Duration, Instant};
use lucisv_core::config::{Discovery, FileConfig};
use vlog_semantic::{FileFacts, IndexBuilder, WorkspaceIndex};
use crate::cache::{self, Records, Reuse};
pub use analysis::Analysis;
pub use files::Stamp;
@@ -39,8 +40,6 @@ pub struct Refresh {
pub struct Project {
roots: Vec<PathBuf>,
filelist_arg: Option<PathBuf>,
config: FileConfig,
config_problem: Option<String>,
files: BTreeMap<PathBuf, Stamp>,
index: WorkspaceIndex,
analyses: Analyses,
@@ -54,6 +53,10 @@ pub struct Project {
/// Whether the current call has already walked the roots — the open, a
/// stale or forced walk in `refresh`, or a miss's retry.
walked_in_call: bool,
/// `--index-cache DIR`: where the stores are read from and ours written.
cache_dir: Option<PathBuf>,
/// How many files the startup took from a store instead of parsing.
reuse: Reuse,
}
/// The canonical form of every `--root`, the current directory when none
@@ -77,49 +80,65 @@ pub fn canonical_roots(roots: &[PathBuf]) -> Result<Vec<PathBuf>, String> {
}
impl Project {
/// Discover the files under `roots` (already canonical) and index them.
/// Parses every file, so it runs on the stack-sized thread.
/// [`Project::open_cached`] without a cache directory — the tests' open.
#[cfg(test)]
pub fn open(roots: Vec<PathBuf>, filelist: Option<PathBuf>) -> Project {
Project::open_cached(roots, filelist, None)
}
/// Discover the files under `roots` (already canonical) and index them,
/// taking from the index caches in `cache_dir` the facts of every file
/// whose exact bytes a record was read from (PLAN §6) and parsing the
/// rest — on the stack-sized thread.
pub fn open_cached(
roots: Vec<PathBuf>,
filelist: Option<PathBuf>,
cache_dir: Option<PathBuf>,
) -> Project {
let started = Instant::now();
let mut discovery = Discovery::new(true);
let (config, config_problem) = match roots.first().map(|r| discovery.for_dir(r)) {
Some(Ok(config)) => (config, None),
Some(Err(problem)) => (FileConfig::default(), Some(problem)),
None => (FileConfig::default(), None),
};
let walk = discover(&roots, filelist.as_deref());
let mut builder = IndexBuilder::new();
let mut files = BTreeMap::new();
let mut unreadable = Vec::new();
for path in &walk.files {
match read_source(path) {
Ok((text, stamp)) => {
builder.add_file(path.clone(), &text);
files.insert(path.clone(), stamp);
}
Err(problem) => {
unreadable.push((path.clone(), problem.to_string()));
}
}
}
let mut records = cache_dir.as_deref().map(Records::load).unwrap_or_default();
let loaded = load(&walk.files, &mut records);
// The merge is part of the build: finished before the clock is read.
let index = loaded.builder.finish();
let now = Instant::now();
Project {
roots,
filelist_arg: filelist,
config,
config_problem,
files,
index: builder.finish(),
files: loaded.files,
index,
analyses: Analyses::default(),
walk,
walked_at: now,
updated_at: now,
build: now - started,
unreadable,
unreadable: loaded.unreadable,
walked_in_call: true,
cache_dir,
reuse: loaded.reuse,
}
}
/// Write the project's own index cache (`--index-cache DIR/index-cache-mcp`):
/// one record per indexed file, the facts the index holds under the hash
/// of the bytes they were read from. `Ok(None)` without a cache directory.
pub fn save_cache(&self) -> std::io::Result<Option<(PathBuf, usize)>> {
let Some(dir) = self.cache_dir.as_deref() else { return Ok(None) };
let records: Vec<(u64, &FileFacts)> = self
.files
.iter()
.filter_map(|(path, stamp)| Some((stamp.hash, self.index.facts_for(path)?)))
.collect();
let written = cache::write_own(dir, &records)?;
Ok(Some((dir.join(cache::OWN_STORE), written)))
}
/// How many files the startup took from the index caches, when a cache
/// directory was given.
pub fn reuse(&self) -> Option<Reuse> {
self.cache_dir.as_ref().map(|_| self.reuse)
}
/// Bring the index up to the disk: stat every file, re-read the ones
/// that moved, drop the ones that went, and — when a file went, when
/// `force_walk`, or when the last walk is stale — walk again for new
@@ -234,22 +253,6 @@ impl Project {
self.files.get(path)
}
/// The config governing the first root, and the problem reading it.
pub fn config(&self) -> (&FileConfig, Option<&str>) {
(&self.config, self.config_problem.as_deref())
}
/// The last discovery: its filelist, warnings and skipped files.
pub fn discovery(&self) -> &FileSet {
&self.walk
}
/// Files discovery found but could not read as UTF-8 text.
pub fn unreadable(&self) -> Vec<String> {
let shown = |(path, why): &(PathBuf, String)| format!("{}: {why}", self.relative(path));
self.unreadable.iter().map(shown).collect()
}
/// Every discovered file the index does not hold, with why: over the
/// size cap, or not UTF-8 text. An edit over the whole set must not
/// pretend these were searched.
@@ -307,6 +310,43 @@ impl Project {
}
}
/// What reading the discovered files at startup produced.
struct Loaded {
builder: IndexBuilder,
files: BTreeMap<PathBuf, Stamp>,
unreadable: Vec<(PathBuf, String)>,
reuse: Reuse,
}
/// Read and stamp every file; add its facts from a store record when one was
/// read off exactly these bytes, else parse it.
fn load(paths: &[PathBuf], records: &mut Records) -> Loaded {
let mut loaded = Loaded {
builder: IndexBuilder::new(),
files: BTreeMap::new(),
unreadable: Vec::new(),
reuse: Reuse::default(),
};
for path in paths {
let (text, stamp) = match read_source(path) {
Ok(read) => read,
Err(problem) => {
loaded.unreadable.push((path.clone(), problem.to_string()));
continue;
}
};
match records.take(path, stamp.hash) {
Some((facts, source)) => {
loaded.reuse.count(source);
loaded.builder.add_facts(facts);
}
None => loaded.builder.add_file(path.clone(), &text),
}
loaded.files.insert(path.clone(), stamp);
}
loaded
}
/// [`Project::relative`], for a caller that holds the roots but no project.
fn relative_to(roots: &[PathBuf], path: &Path) -> String {
let shown = roots.iter().find_map(|root| path.strip_prefix(root).ok()).unwrap_or(path);
+64 -103
View File
@@ -1,20 +1,14 @@
//! The rendering rules every tool's text answer follows (PLAN §4.5): the
//! The rendering rules every tool's text answer follows (PLAN §10.2): the
//! token budget is the product.
//!
//! - paths are root-relative, and a file is named once per group of lines
//! about it, never once per line;
//! - lines and columns are 1-based, a position is `line:col`, a range is
//! `first-last`;
//! - lists are capped, the cap is said with `… and N more` and the caller can
//! page with `offset`;
//! - no prose and no markdown headings: a label is a bare word and a colon,
//! a table only where the columns are fixed.
//! - one line per fact, root-relative paths, `file:line`; a line range is
//! `first–last`;
//! - no headers, no blank lines, no trailing hints;
//! - a fixed cap per tool, and one `… and N more` line when it cuts;
//! - counts only where they are the answer.
use vlog_semantic::SymbolKind;
/// How many entries a list answer holds unless the caller says otherwise.
pub const DEFAULT_LIMIT: usize = 200;
/// A declaration kind as one lower-case word — the keyword that declares it
/// where there is one.
pub fn kind(kind: SymbolKind) -> &'static str {
@@ -48,7 +42,7 @@ pub fn kind(kind: SymbolKind) -> &'static str {
}
}
/// Every word [`kind`] can produce — what `read_item` accepts before a `:`.
/// Every word [`kind`] can produce — what an item selector accepts before a `:`.
const KIND_WORDS: &[&str] = &[
"module",
"interface",
@@ -83,12 +77,12 @@ pub fn is_kind_word(word: &str) -> bool {
KIND_WORDS.contains(&word)
}
/// A line range as the answers print it: `12` or `12-40`.
/// A line range as the answers print it: `12`, or `12–40`.
pub fn lines(first: u32, last: u32) -> String {
if first == last {
first.to_string()
} else {
format!("{first}-{last}")
format!("{first}–{last}")
}
}
@@ -98,71 +92,53 @@ pub fn one_line(text: &str) -> String {
text.split_whitespace().collect::<Vec<_>>().join(" ")
}
/// The window `offset..offset + limit` of a list, and how many entries
/// follow it.
pub fn page<T>(items: &[T], offset: usize, limit: usize) -> (&[T], usize) {
let start = offset.min(items.len());
let end = start.saturating_add(limit).min(items.len());
(&items[start..end], items.len() - end)
}
/// The line that says a list was cut, or nothing when it was not.
pub fn more(out: &mut String, rest: usize) {
if rest > 0 {
out.push_str(&format!("… and {rest} more\n"));
/// `n` of a noun whose plural adds `s`: `1 file`, `3 files`.
pub fn count(n: usize, noun: &str) -> String {
if n == 1 {
format!("1 {noun}")
} else {
format!("{n} {noun}s")
}
}
/// Lines grouped under the file they are about: the file once, then each
/// of its lines indented by two spaces. Entries arrive in any order; groups
/// keep the order in which each file first appears.
pub fn grouped(entries: &[(String, String)]) -> String {
let mut order: Vec<&str> = Vec::new();
for (file, _) in entries {
if !order.contains(&file.as_str()) {
order.push(file);
}
/// `lines` cut at `cap`, ending with one `… and N more` line when cut.
pub fn capped(mut lines: Vec<String>, cap: usize) -> Vec<String> {
if lines.len() > cap {
let rest = lines.len() - cap;
lines.truncate(cap);
lines.push(more(rest));
}
let mut out = String::new();
for file in order {
out.push_str(file);
out.push('\n');
for (_, line) in entries.iter().filter(|(f, _)| f == file) {
out.push_str(" ");
out.push_str(line);
out.push('\n');
}
}
out
lines
}
/// Rows whose columns are padded to line up, the last column left ragged.
pub fn table(rows: &[Vec<String>]) -> String {
let columns = rows.iter().map(Vec::len).max().unwrap_or(0);
let mut widths = vec![0; columns];
for row in rows {
for (at, cell) in row.iter().enumerate() {
widths[at] = widths[at].max(cell.chars().count());
/// The line that says how many entries a cut list left out.
pub fn more(rest: usize) -> String {
format!("… and {rest} more")
}
/// Sites grouped one file per line, `file:12,40,41`: files in the order
/// each first appears, each line once, in the order given.
pub fn by_file(sites: &[(String, u32)]) -> Vec<String> {
let mut grouped: Vec<(&str, Vec<u32>)> = Vec::new();
for (file, line) in sites {
match grouped.iter_mut().find(|(held, _)| held == file) {
Some((_, lines)) if lines.contains(line) => {}
Some((_, lines)) => lines.push(*line),
None => grouped.push((file, vec![*line])),
}
}
let mut out = String::new();
for row in rows {
let mut line = String::new();
for (at, cell) in row.iter().enumerate() {
if at + 1 < row.len() {
// A column that is empty in every row takes no space at all.
if widths[at] > 0 {
line.push_str(&format!("{cell:<width$} ", width = widths[at]));
}
} else {
line.push_str(cell);
}
}
out.push_str(" ");
out.push_str(line.trim_end());
out.push('\n');
}
out
grouped
.into_iter()
.map(|(file, lines)| {
let lines: Vec<String> = lines.iter().map(u32::to_string).collect();
format!("{file}:{}", lines.join(","))
})
.collect()
}
/// One `warning: …` line per sentence an engine or the write path said.
pub fn warnings(out: &mut Vec<String>, warnings: &[String]) {
out.extend(warnings.iter().map(|warning| format!("warning: {}", one_line(warning))));
}
#[cfg(test)]
@@ -210,37 +186,22 @@ mod tests {
#[test]
fn a_range_of_one_line_is_one_number() {
assert_eq!(lines(3, 3), "3");
assert_eq!(lines(3, 9), "3-9");
}
#[test]
fn a_page_says_how_many_entries_follow_it() {
let items = [1, 2, 3, 4, 5];
assert_eq!(page(&items, 1, 2), (&items[1..3], 2));
assert_eq!(page(&items, 9, 2), (&items[5..5], 0));
let mut out = String::new();
more(&mut out, 2);
more(&mut out, 0);
assert_eq!(out, "… and 2 more\n");
}
#[test]
fn a_file_is_named_once_per_group() {
let entries = vec![
("b.sv".to_string(), "module b 1".to_string()),
("a.sv".to_string(), "module a 1".to_string()),
("b.sv".to_string(), "module c 9".to_string()),
];
assert_eq!(grouped(&entries), "b.sv\n module b 1\n module c 9\na.sv\n module a 1\n");
}
#[test]
fn table_columns_line_up_and_empty_columns_vanish() {
let rows = vec![
vec!["input".into(), "".into(), "logic".into(), "clk".into()],
vec!["output".into(), "".into(), "logic [7:0]".into(), "q".into()],
];
assert_eq!(table(&rows), " input logic clk\n output logic [7:0] q\n");
assert_eq!(lines(3, 9), "3–9");
assert_eq!(one_line("a\n b\t c "), "a b c");
assert_eq!((count(1, "file"), count(0, "site")), ("1 file".into(), "0 sites".into()));
}
#[test]
fn a_cut_list_ends_with_one_more_line() {
let all: Vec<String> = (0..5).map(|n| n.to_string()).collect();
assert_eq!(capped(all.clone(), 3), ["0", "1", "2", "… and 2 more"]);
assert_eq!(capped(all.clone(), 5), all);
}
#[test]
fn sites_are_grouped_one_file_per_line() {
let sites = [("b.sv", 3), ("a.sv", 1), ("b.sv", 9), ("b.sv", 3)];
let sites: Vec<(String, u32)> = sites.iter().map(|(f, l)| (f.to_string(), *l)).collect();
assert_eq!(by_file(&sites), ["b.sv:3,9", "a.sv:1"]);
}
}
+15 -17
View File
@@ -1,7 +1,7 @@
//! The `lucisv://` resources: the project overview, the lint rule
//! reference, one unit's interface and one file's outline — the same answers
//! the read tools give, addressable by URI for a host that attaches context
//! rather than calling tools.
//! reference, one unit's outline and one file's outline — the same answers
//! `hierarchy` and `outline` give, addressable by URI for a host that
//! attaches context rather than calling tools.
use serde_json::{json, Map, Value};
@@ -23,7 +23,7 @@ pub fn list() -> Value {
"uri": "lucisv://overview",
"name": "overview",
"title": "Project overview",
"description": "Files, units by kind, top-level modules and largest files of the indexed project.",
"description": "File and module counts and the top-level modules, as hierarchy without a root answers.",
"mimeType": "text/plain",
},
{
@@ -42,8 +42,8 @@ pub fn templates() -> Value {
{
"uriTemplate": "lucisv://unit/{name}",
"name": "unit",
"title": "Unit interface",
"description": "A module's or interface's parameters, ports and instantiation template; a package's or class's members.",
"title": "Unit outline",
"description": "A unit's file:line, parameters and ports (modports, package members), as outline unit answers.",
"mimeType": "text/plain",
},
{
@@ -78,7 +78,8 @@ impl Resource {
!matches!(self, Resource::Rules)
}
/// Whether answering walks the roots first, as `project_overview` does.
/// Whether answering walks the roots first, as `hierarchy` without a
/// root does.
pub fn rewalk(&self) -> bool {
matches!(self, Resource::Overview)
}
@@ -87,16 +88,11 @@ impl Resource {
pub fn read(&self, uri: &str, project: Option<&mut Project>) -> Result<Value, String> {
let (mime, text) = match (self, project) {
(Resource::Rules, _) => ("text/markdown", vlog_linter::rules_markdown()),
(Resource::Overview, Some(project)) => {
("text/plain", run(project, "project_overview", None)?)
}
(Resource::Overview, Some(project)) => ("text/plain", run(project, "hierarchy", None)?),
(Resource::Unit(name), Some(project)) => {
// A URI has no `file` argument to pick among declarations.
let text = run(project, "unit_interface", Some(("name", name))).map_err(|why| {
why.replace(
"pass `file` to pick one",
"call the unit_interface tool with its file argument to pick one",
)
// A URI has no argument to pick among declarations.
let text = run(project, "outline", Some(("unit", name))).map_err(|why| {
why.replace("outline one `file` instead", "read one file's outline resource")
})?;
("text/plain", text)
}
@@ -115,7 +111,9 @@ fn run(
tool: &str,
argument: Option<(&str, &str)>,
) -> Result<String, String> {
let tool = tools::find(tool).ok_or_else(|| format!("no tool `{tool}`"))?;
// A resource runs read tools only, so it answers the same in either mode.
let tool =
tools::find(tool, tools::Mode::ReadOnly).ok_or_else(|| format!("no tool `{tool}`"))?;
let mut arguments = Map::new();
if let Some((name, value)) = argument {
arguments.insert(name.to_string(), Value::from(value));
+64 -11
View File
@@ -13,7 +13,7 @@ use serde_json::{json, Map, Value};
use crate::project::Project;
use crate::resources::{self, Resource};
use crate::tools;
use crate::tools::{self, Mode};
use crate::transport::{Line, Transport};
use crate::Options;
@@ -35,8 +35,19 @@ const NOT_INITIALIZED: i64 = -32002;
/// MCP's "resource not found".
const RESOURCE_NOT_FOUND: i64 = -32002;
/// What the agent is told once, at `initialize`.
const INSTRUCTIONS: &str = "lucisv-mcp answers questions about the Verilog/SystemVerilog design under its roots, read from the files on disk (never from unsaved editor buffers). Prefer unit_interface for a module's parameters and ports, outline for what a file declares, and read_item for one module, function or always block over reading whole files; list_units and search_symbols find where things are declared. Paths in answers are relative to the root; lines and columns are 1-based.";
/// What the agent is told once, at `initialize` (PLAN §10.3, ≤ 400 bytes).
const INSTRUCTIONS: &str = "lucisv-mcp reads the SystemVerilog on disk (save first). Use it before reading files: hierarchy for instance trees and top modules, find for a name's declarations and uses, outline for a file or unit's ports, read for one item, check after edits. Edits (rename, port, edit_item, format) are verified, all-or-nothing writes: trust them as file writes, no dry run. Paths root-relative, lines 1-based.";
/// What the agent is told in `--read-only` mode (PLAN §11.1, ≤ 300 bytes).
const INSTRUCTIONS_READ_ONLY: &str = "lucisv-mcp reads the SystemVerilog on disk (save first); it never edits. Use it before reading files: hierarchy for instance trees and top modules, find for a name's declarations and uses, outline for a file or unit's ports, read for one item, check for issues. Paths root-relative, lines 1-based.";
/// The instructions for `mode`.
fn instructions(mode: Mode) -> &'static str {
match mode {
Mode::Full => INSTRUCTIONS,
Mode::ReadOnly => INSTRUCTIONS_READ_ONLY,
}
}
/// A JSON-RPC error object.
#[derive(Debug, Serialize)]
@@ -136,7 +147,10 @@ pub fn serve(options: Options) -> Result<(), String> {
let mut server = Server { options, version: None, project: None };
loop {
let reply = match transport.read_line().map_err(|e| format!("reading stdin: {e}"))? {
Line::Eof => return Ok(()),
Line::Eof => {
server.finish();
return Ok(());
}
Line::NotUtf8 => {
Some(response(&Value::Null, Err(fault(PARSE_ERROR, "the line is not UTF-8"))))
}
@@ -192,7 +206,7 @@ impl Server {
"initialize" => Ok(self.initialize(params.as_ref())),
"ping" => Ok(json!({})),
_ if self.version.is_none() => Err(fault(NOT_INITIALIZED, "server not initialized")),
"tools/list" => Ok(tools::list()),
"tools/list" => Ok(tools::list(self.options.mode)),
"tools/call" => self.call_tool(params),
"resources/list" => Ok(resources::list()),
"resources/templates/list" => Ok(resources::templates()),
@@ -214,7 +228,7 @@ impl Server {
"protocolVersion": version,
"capabilities": { "tools": {}, "resources": {}, "prompts": {} },
"serverInfo": { "name": "lucisv-mcp", "version": env!("CARGO_PKG_VERSION") },
"instructions": INSTRUCTIONS,
"instructions": instructions(self.options.mode),
})
}
@@ -230,8 +244,8 @@ impl Server {
let Some(Value::String(name)) = params.remove("name") else {
return Err(fault(INVALID_PARAMS, "tools/call params need a string `name`"));
};
let Some(tool) = tools::find(&name) else {
return Err(fault(INVALID_PARAMS, format!("unknown tool: {name}")));
let Some(tool) = tools::find(&name, self.options.mode) else {
return Err(fault(INVALID_PARAMS, unknown_tool(&name, self.options.mode)));
};
let arguments = match params.remove("arguments") {
None | Some(Value::Null) => Map::new(),
@@ -267,6 +281,20 @@ impl Server {
resource.read(uri, project).map_err(|why| not_found(&format!(" ({why})")))
}
/// The client closed stdin: write the project's own index cache, when
/// there is a project and a cache directory. A failure is one line on
/// stderr; the session ends either way.
fn finish(&self) {
let Some(project) = &self.project else { return };
match project.save_cache() {
Ok(Some((store, written))) if self.options.verbose => {
eprintln!("lucisv-mcp: wrote {written} records to {}", store.display());
}
Ok(_) => {}
Err(problem) => eprintln!("lucisv-mcp: cannot write the index cache: {problem}"),
}
}
/// The project, built on first use and brought up to the disk on every
/// later one.
fn project(&mut self, rewalk: bool) -> &mut Project {
@@ -285,18 +313,37 @@ impl Server {
/// Discover and index the project, saying on stderr how long it took.
fn open_project(options: &Options) -> Project {
let project = Project::open(options.roots.clone(), options.filelist.clone());
let project = Project::open_cached(
options.roots.clone(),
options.filelist.clone(),
options.index_cache.clone(),
);
let (build, _) = project.timing();
eprintln!("lucisv-mcp: indexed {} files in {} ms", project.files().count(), build.as_millis());
let reused = match project.reuse() {
Some(reuse) => {
format!(" ({} from the editor's cache, {} from its own)", reuse.editor, reuse.own)
}
None => String::new(),
};
let (files, ms) = (project.files().count(), build.as_millis());
eprintln!("lucisv-mcp: indexed {files} files in {ms} ms{reused}");
project
}
/// The `-32602` message for a tool `mode` does not offer. In read-only mode
/// it says why, so an agent does not retry an edit the server cannot make.
fn unknown_tool(name: &str, mode: Mode) -> String {
match mode {
Mode::Full => format!("unknown tool: {name}"),
Mode::ReadOnly => format!("unknown tool: {name} (the server runs --read-only)"),
}
}
/// A tool's answer as `tools/call` returns it.
fn tool_result(answer: Result<tools::Answer, String>) -> Value {
match answer {
Ok(answer) => json!({
"content": [{ "type": "text", "text": answer.text }],
"structuredContent": answer.structured,
"isError": false,
}),
Err(refusal) => json!({
@@ -318,6 +365,12 @@ mod tests {
reply["error"]["code"].as_i64().unwrap()
}
#[test]
fn the_instructions_stay_under_400_bytes() {
assert!(INSTRUCTIONS.len() <= 400, "{}", INSTRUCTIONS.len());
assert!(INSTRUCTIONS_READ_ONLY.len() <= 300, "{}", INSTRUCTIONS_READ_ONLY.len());
}
#[test]
fn the_handshake_echoes_a_known_revision_and_offers_the_newest_otherwise() {
let mut s = server();
+96
View File
@@ -0,0 +1,96 @@
//! The declarations the files' own symbol tables hold — every one the
//! semantic model knows and `outline` lists: typedefs, enum values,
//! functions, tasks, genvars, generate blocks and what they declare,
//! procedural locals, beside the ports, nets and variables the index also
//! records. The index's word census narrows the files read: a file that
//! declares a name writes it. One table for `find` (an exact name) and for
//! its near matches (a part of a name), so both see the same set.
use std::path::PathBuf;
use vlog_parser::ast::{Item, ItemKind};
use vlog_parser::span::TextRange;
use super::read_item::child_items;
use crate::project::{Analysis, Project};
use crate::render;
/// Which names the table is asked for.
pub enum Wanted<'a> {
/// Exactly this name.
Exact(&'a str),
/// Every name containing this part, any case (already lower-cased).
Containing(String),
}
impl Wanted<'_> {
fn accepts(&self, name: &str) -> bool {
match self {
Wanted::Exact(wanted) => name == *wanted,
Wanted::Containing(part) => name.to_ascii_lowercase().contains(part.as_str()),
}
}
/// Whether a file's sorted word census holds a wanted name.
fn in_census(&self, words: &[String]) -> bool {
match self {
Wanted::Exact(wanted) => words.binary_search_by(|w| w.as_str().cmp(wanted)).is_ok(),
Wanted::Containing(_) => words.iter().any(|word| self.accepts(word)),
}
}
}
/// One declaration read off a file's own symbol table.
pub struct Local {
pub path: PathBuf,
pub name: String,
pub kind: &'static str,
/// The byte offset of the name itself.
pub offset: u32,
/// The line shown: the completing declaration's for a non-ANSI port.
pub line: u32,
/// The module, interface, package or class the declaration is inside.
pub unit: Option<String>,
}
/// Every declaration whose name `wanted` accepts, in every indexed file
/// whose words hold such a name, read from disk now.
pub fn declared(project: &Project, wanted: &Wanted) -> Vec<Local> {
let mut out = Vec::new();
for (path, _) in project.files() {
let census = project.index().facts_for(path).map(|facts| facts.words());
if !census.is_some_and(|words| wanted.in_census(words)) {
continue;
}
let Ok(text) = std::fs::read_to_string(path) else { continue };
let analysis = Analysis::of(text);
for symbol in analysis.semantics.symbols().iter().filter(|s| wanted.accepts(&s.name)) {
let shown = symbol.detail_span.unwrap_or(symbol.name_span);
let offset = symbol.name_span.start;
out.push(Local {
path: path.clone(),
name: symbol.name.clone(),
kind: render::kind(symbol.kind),
offset,
line: analysis.lines.line_col(shown.start).0,
unit: unit_at(&analysis.tree.items, symbol.name_span).map(str::to_string),
});
}
}
out
}
/// The innermost module, interface, package or class whose item holds
/// `span`, other than one `span` names.
fn unit_at(items: &[Item], span: TextRange) -> Option<&str> {
let item =
items.iter().find(|item| item.span.start <= span.start && span.end <= item.span.end)?;
let own = match &item.kind {
ItemKind::Module(module) => Some((module.name.as_str(), module.name_span)),
ItemKind::Package { name, name_span, .. } => Some((name.as_str(), *name_span)),
ItemKind::Class(class) => Some((class.name.as_str(), class.name_span)),
_ => None,
};
let inner = child_items(&item.kind).into_iter().find_map(|items| unit_at(items, span));
inner.or(own.filter(|(_, name_span)| *name_span != span).map(|(name, _)| name))
}
-210
View File
@@ -1,210 +0,0 @@
//! `defines`: the `` `define`` table — one file's, one macro's every
//! definition across the project, or the whole project's — without reading
//! the files. Bookkeeping only, like `vlog_parser::defines`: nothing here
//! expands a macro (the README says why the one-step expansion is not
//! offered).
use std::path::{Path, PathBuf};
use serde_json::{json, Value};
use vlog_parser::defines::{Define, DefineKind};
use super::source::{self, Texts};
use super::{Answer, Args, Param, Tool, Ty};
use crate::project::Project;
use crate::render::{self, DEFAULT_LIMIT};
/// A body longer than this many characters is cut, with `…`.
const BODY_CAP: usize = 200;
pub const DEFINES: Tool = Tool {
name: "defines",
title: "Macro definitions",
description: "The `define table: name, parameters, body (on one line) and file:line — of one `file`, of one macro `name` across the project (every definition; which one a use sees depends on include order, so none is picked), or of the whole project. Prefer it over grepping for `define.",
params: &[
Param {
name: "file",
ty: Ty::Str,
required: false,
description: "Only this file's table (its `undef`s included), relative to a root or absolute inside one.",
},
Param {
name: "name",
ty: Ty::Str,
required: false,
description: "Only this macro, written with or without the backtick.",
},
Param {
name: "limit",
ty: Ty::Int { min: 1 },
required: false,
description: "Most entries to return (default 200).",
},
Param {
name: "offset",
ty: Ty::Int { min: 0 },
required: false,
description: "Entries to skip, for paging past `… and N more` (default 0).",
},
],
rewalk: false,
handler: defines,
};
/// One table row, ready to render.
struct Row {
file: String,
line: u32,
define: Define,
}
fn defines(project: &mut Project, args: &Args) -> Result<Answer, String> {
let name = args.str("name").map(|name| name.trim_start_matches('`')).filter(|n| !n.is_empty());
let (rows, rest, total) = match args.str("file") {
Some(file) => in_file(project, file, name, args)?,
None => {
let mut all = indexed(project, name);
if all.is_empty() && name.is_some() && project.ensure_walked_for_miss() {
all = indexed(project, name);
}
let (shown, rest) =
render::page(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
(rows_of(project, shown), rest, all.len())
}
};
let entries: Vec<(String, String)> = rows
.iter()
.map(|row| (row.file.clone(), format!("{} {}", row.line, spelled(&row.define))))
.collect();
let mut text = render::grouped(&entries);
render::more(&mut text, rest);
if total == 0 {
text = "no defines\n".to_string();
}
let listed: Vec<Value> = rows.iter().map(row_json).collect();
Ok(Answer { text, structured: json!({ "defines": listed, "total": total }) })
}
/// One file's table as it is on disk now, filtered by `name`.
fn in_file(
project: &mut Project,
file: &str,
name: Option<&str>,
args: &Args,
) -> Result<(Vec<Row>, usize, usize), String> {
let path = project.resolve(file)?;
let analysis = project.analysis(&path)?;
let shown_file = project.relative(&path);
let all: Vec<&Define> = analysis
.defines
.entries()
.iter()
.filter(|define| name.is_none_or(|name| define.name == name))
.collect();
let (shown, rest) =
render::page(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
let rows = shown
.iter()
.map(|define| Row {
file: shown_file.clone(),
line: analysis.lines.line_col(define.span.start).0,
define: (*define).clone(),
})
.collect();
Ok((rows, rest, all.len()))
}
/// Every indexed definition (of `name`, when given), in file order.
fn indexed(project: &Project, name: Option<&str>) -> Vec<(PathBuf, Define)> {
let index = project.index();
let of =
|file, define: &Define| index.path(file).map(|path| (path.to_path_buf(), define.clone()));
match name {
Some(name) => index.find_define(name).into_iter().filter_map(|(f, d)| of(f, d)).collect(),
None => (0..index.files().len() as u32)
.map(vlog_semantic::FileId)
.flat_map(|file| {
let entries = index.defines(file).map(|table| table.entries()).unwrap_or(&[]);
entries
.iter()
.filter(|d| d.kind == DefineKind::Define)
.filter_map(move |d| of(file, d))
})
.collect(),
}
}
/// Rows for indexed definitions, each line read off its file now; a
/// definition whose file no longer spells its name there is omitted.
fn rows_of(project: &Project, shown: &[(PathBuf, Define)]) -> Vec<Row> {
let mut texts = Texts::default();
shown
.iter()
.filter_map(|(path, define)| {
let line = checked_line(&mut texts, path, define)?;
Some(Row { file: project.relative(path), line, define: define.clone() })
})
.collect()
}
fn checked_line(texts: &mut Texts, path: &Path, define: &Define) -> Option<u32> {
let (text, lines) = texts.get(path)?;
let spelled = text.get(define.name_span.as_range())?;
(spelled == define.name).then(|| lines.line_col(define.span.start).0)
}
/// A definition as one line: `` `define NAME(a, b) body``, the body capped.
fn spelled(define: &Define) -> String {
if define.kind == DefineKind::Undef {
return format!("`undef {}", define.name);
}
let mut out = format!("`define {}", define.name);
if let Some(params) = &define.params {
out.push_str(&format!("({})", params.join(", ")));
}
let body = source::capped(&define.body, BODY_CAP);
if !body.is_empty() {
out.push(' ');
out.push_str(&body);
}
out
}
fn row_json(row: &Row) -> Value {
let define = &row.define;
json!({
"file": row.file,
"line": row.line,
"name": define.name,
"kind": if define.kind == DefineKind::Undef { "undef" } else { "define" },
"params": define.params,
"body": source::capped(&define.body, BODY_CAP),
})
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_parser::defines::collect_defines;
use vlog_parser::tokenize;
fn table(text: &str) -> Vec<Define> {
collect_defines(&tokenize(text).unwrap()).entries().to_vec()
}
#[test]
fn a_definition_is_spelled_on_one_line_with_its_parameters() {
let all = table("`define ADD(a, b = 1) \\\n ((a) + (b))\n`define W 8\n`undef W\n");
assert_eq!(spelled(&all[0]), "`define ADD(a, b = 1) ((a) + (b))");
assert_eq!(spelled(&all[1]), "`define W 8");
assert_eq!(spelled(&all[2]), "`undef W");
}
#[test]
fn a_long_body_is_cut_at_the_cap() {
let body = "x ".repeat(300);
let cut = source::capped(&body, BODY_CAP);
assert_eq!(cut.chars().count(), BODY_CAP + 1);
assert!(cut.ends_with('…'));
}
}
+68 -131
View File
@@ -1,14 +1,13 @@
//! `diagnostics`: what `lucisv check` would say about one file or the whole
//! project — the tolerant parse's errors first, then the lint findings —
//! with the CLI's JSON field names, so one contract serves CI and agents.
//! `check`: what `lucisv check` would say about one file or the whole
//! design — the tolerant parse's errors, then the lint findings — one line
//! each, `file:line:col severity message [rule]`, errors first.
//!
//! The lint run is the CLI's, rung for rung: the `lucisv.toml` governing each
//! file (`Discovery::for_file`) gives `[lint] select`/`ignore`, the
//! `[lint.<rule>]` options, the external `waivers` and the formatter's line
//! length; the `rules` argument replaces `select` as `--select` does; the
//! workspace rules run, their questions answered by the project index
//! ([`Mentions`]). Missing-closer warnings are the language server's own
//! (`pairs.rs`, not a library) and are not offered.
//! length; the workspace rules run, their questions answered by the project
//! index ([`Mentions`]). Missing-closer warnings are the language server's
//! own (`pairs.rs`, not a library) and are not offered.
use std::cell::RefCell;
use std::collections::{BTreeMap, HashMap};
@@ -16,7 +15,6 @@ use std::path::{Path, PathBuf};
use std::rc::Rc;
use lucisv_core::config::{Discovery, FileConfig};
use serde_json::{json, Value};
use vlog_linter::{
lint_with, select_rules, Exports, ExternalWaivers, LintContext, MentionOracle, ModuleInterface,
Rule, RuleOptions, Violation, WaiverUse,
@@ -26,58 +24,26 @@ use vlog_semantic::{FileId, PackageExports, SymbolKind, WorkspaceIndex};
use super::{Answer, Args, Param, Tool, Ty};
use crate::project::{Analysis, Project};
use crate::render::{self, DEFAULT_LIMIT};
use crate::render;
pub const DIAGNOSTICS: Tool = Tool {
name: "diagnostics",
title: "Diagnostics",
description: "Parse errors and lint findings for one `file`, or for every indexed file, grouped by file as `line:col severity message [rule]` — what `lucisv check` over the whole tree reports (cross-file rules on), under the project's lucisv.toml [lint] settings and waivers. Filter with `rules` (like --select) and `severity`. The whole-project form lints every file and returns the first `limit` findings with the total.",
params: &[
Param {
name: "file",
ty: Ty::Str,
required: false,
description: "One file, relative to a root or absolute inside one (default: every indexed file).",
},
Param {
name: "rules",
ty: Ty::Str,
required: false,
description: "Comma-separated rule names or severities to run instead of the configured set, like `--select`.",
},
Param {
name: "severity",
ty: Ty::Enum(&["error", "warning", "style"]),
required: false,
description: "Only findings of this severity (parse errors are `error`).",
},
Param {
name: "limit",
ty: Ty::Int { min: 1 },
required: false,
description: "Most findings to return (default 200).",
},
Param {
name: "offset",
ty: Ty::Int { min: 0 },
required: false,
description: "Findings to skip, for paging past `… and N more` (default 0).",
},
],
/// The most findings an answer lists before `… and N more`.
const CAP: usize = 200;
pub const CHECK: Tool = Tool {
name: "check",
description: "Parse errors and lint findings of `file` or the whole design, one per line (file:line:col severity message [rule]), errors first; `ok` when clean.",
params: &[Param { name: "file", ty: Ty::Str, required: false }],
rewalk: false,
handler: diagnostics,
handler: check,
};
/// One finding, in the CLI's JSON shape.
/// One finding: where, how bad, what, and which rule.
struct Finding {
file: String,
rule: String,
severity: &'static str,
message: String,
start: (u32, u32),
end: (u32, u32),
range: (u32, u32),
fix: Value,
}
/// What one config file makes of a lint run.
@@ -91,52 +57,73 @@ pub(super) struct Run {
used: RefCell<WaiverUse>,
}
fn diagnostics(project: &mut Project, args: &Args) -> Result<Answer, String> {
let selected: Option<Vec<String>> = args.str("rules").map(|rules| {
rules.split(',').map(str::trim).filter(|r| !r.is_empty()).map(str::to_string).collect()
});
let mut runs = Runs::new(selected);
let mut findings = Vec::new();
match args.str("file") {
fn check(project: &mut Project, args: &Args) -> Result<Answer, String> {
let mut runs = Runs::new();
let mut findings = match args.str("file") {
Some(file) => {
let path = project.resolve(file)?;
let analysis = project.analysis(&path)?;
let own = project.index().file_id(&path);
let oracle = Mentions::of_file(project.index(), own);
findings = file_findings(project, &mut runs, &path, &analysis, &oracle)?;
}
None => {
let census = Census::of(project.index());
let paths: Vec<PathBuf> = project.files().map(|(path, _)| path.clone()).collect();
for path in paths {
let Ok(text) = std::fs::read_to_string(&path) else { continue };
let analysis = Analysis::of(text);
let own = project.index().file_id(&path);
let oracle = Mentions { index: project.index(), census: Some(&census), own };
findings.extend(file_findings(project, &mut runs, &path, &analysis, &oracle)?);
}
// Only a complete run knows a waiver matched nothing.
findings.extend(runs.unused_waivers(project));
file_findings(project, &mut runs, &path, &analysis, &oracle)?
}
None => project_findings(project, &mut runs)?,
};
if findings.is_empty() {
return Ok(Answer::lines(vec!["ok".to_string()]));
}
if let Some(severity) = args.str("severity") {
findings.retain(|finding| finding.severity == severity);
// Errors first, then warnings, then the rest; each file's order within.
findings.sort_by_key(|finding| severity_rank(finding.severity));
let lines = findings.iter().map(Finding::render).collect();
Ok(Answer::lines(render::capped(lines, CAP)))
}
fn severity_rank(severity: &str) -> u8 {
match severity {
"error" => 0,
"warning" => 1,
_ => 2,
}
Ok(render_findings(&findings, args))
}
impl Finding {
/// `file:line:col severity message [rule]`.
fn render(&self) -> String {
let (line, col) = self.start;
let message = render::one_line(&self.message);
format!("{}:{line}:{col} {} {message} [{}]", self.file, self.severity, self.rule)
}
}
/// Every indexed file's findings, and the external waivers nothing used.
fn project_findings(project: &Project, runs: &mut Runs) -> Result<Vec<Finding>, String> {
let census = Census::of(project.index());
let paths: Vec<PathBuf> = project.files().map(|(path, _)| path.clone()).collect();
let mut findings = Vec::new();
for path in &paths {
let Ok(text) = std::fs::read_to_string(path) else { continue };
let analysis = Analysis::of(text);
let own = project.index().file_id(path);
let oracle = Mentions { index: project.index(), census: Some(&census), own };
findings.extend(file_findings(project, runs, path, &analysis, &oracle)?);
}
// Only a complete run knows a waiver matched nothing.
findings.extend(runs.unused_waivers(project));
Ok(findings)
}
/// The runs met so far in one call, one per governing config file — shared
/// with `fix_lint`, so a fix runs under exactly the rules a finding came from.
/// with `format`'s `fix`, so a fix runs under exactly the rules a finding
/// came from.
pub(super) struct Runs {
discovery: Discovery,
held: BTreeMap<Option<PathBuf>, Rc<Run>>,
selected: Option<Vec<String>>,
}
impl Runs {
/// No run built yet; `selected` replaces each config's `[lint] select`.
pub(super) fn new(selected: Option<Vec<String>>) -> Runs {
Runs { discovery: Discovery::new(true), held: BTreeMap::new(), selected }
/// No run built yet.
pub(super) fn new() -> Runs {
Runs { discovery: Discovery::new(true), held: BTreeMap::new() }
}
/// The run for the config governing `path`, built on first use. A config
@@ -153,10 +140,7 @@ impl Runs {
}
fn build(&self, config: &FileConfig) -> Result<Run, String> {
let select = match &self.selected {
Some(selected) => selected.clone(),
None => config.lint_select.clone().unwrap_or_default(),
};
let select = config.lint_select.clone().unwrap_or_default();
let ignore = config.lint_ignore.clone().unwrap_or_default();
let rules = select_rules(&select, &ignore, true)?;
let mut options = RuleOptions::new();
@@ -225,9 +209,6 @@ fn file_findings(
severity: "error",
message: error.message.clone(),
start: (error.line, error.col),
end: analysis.lines.line_col(error.span.end),
range: (error.span.start, error.span.end),
fix: Value::Null,
})
.collect();
let violations = violations(&run, path, analysis, oracle);
@@ -260,59 +241,15 @@ pub(super) fn violations(
}
fn lint_finding(file: &str, lines: &LineIndex, violation: &Violation) -> Finding {
let span = violation.span;
let fix = violation.fix.as_ref().map_or(Value::Null, |fix| {
let edits: Vec<Value> = fix
.edits
.iter()
.map(|(range, content)| json!({"start": range.start, "end": range.end, "content": content}))
.collect();
json!({ "applicability": fix.applicability.as_str(), "edits": edits })
});
Finding {
file: file.to_string(),
rule: violation.rule.to_string(),
severity: violation.severity.as_str(),
message: violation.message.clone(),
start: lines.line_col(span.start),
end: lines.line_col(span.end),
range: (span.start, span.end),
fix,
start: lines.line_col(violation.span.start),
}
}
/// Findings grouped by file, paged; the JSON is the CLI's array shape.
fn render_findings(findings: &[Finding], args: &Args) -> Answer {
let (shown, rest) =
render::page(findings, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
let entries: Vec<(String, String)> = shown
.iter()
.map(|f| {
let line =
format!("{}:{} {} {} [{}]", f.start.0, f.start.1, f.severity, f.message, f.rule);
(f.file.clone(), line)
})
.collect();
let mut text = render::grouped(&entries);
render::more(&mut text, rest);
if findings.is_empty() {
text = "no findings\n".to_string();
}
let listed: Vec<Value> = shown
.iter()
.map(|f| {
json!({
"filename": f.file, "rule": f.rule, "severity": f.severity, "message": f.message,
"location": {"line": f.start.0, "column": f.start.1},
"end_location": {"line": f.end.0, "column": f.end.1},
"range": {"start": f.range.0, "end": f.range.1},
"fix": f.fix,
})
})
.collect();
Answer { text, structured: json!({ "diagnostics": listed, "total": findings.len() }) }
}
/// How many files write each word, and the first of them — the whole-project
/// form's answer to "does another file mention this", built once per call
/// instead of walking every record per question.
+173 -233
View File
@@ -1,241 +1,110 @@
//! The refactorings that act at one position — `rename`, and the six the
//! editor offers as code actions at a cursor (`expand_wildcard`,
//! `convert_ports`, `organize_imports`, `inline_module`, `propagate_ports`,
//! `remove_port`) — plus what every edit tool shares: the `dry_run`
//! argument, the whole-set read the engines are handed, and the step from a
//! verified `RefactorEdit` to `apply::run`.
//! `rename`, and what every design-wide edit shares: the whole-set read the
//! engines are handed, and the step from a verified `RefactorEdit` to a
//! written plan with the name's unresolved mentions listed.
//!
//! Each engine gets **every indexed file**, read from disk at call time
//! (`source::WholeSet`, M2's ruling for `references`: a use can resolve
//! through a file that never spells its name, so no narrowing is sound).
//! The texts read are the texts the write-freshness rule compares against.
//! A file the index skipped (over 1 MiB, not UTF-8) is never edited around:
//! when its bytes spell a name the edit changes, the edit is refused;
//! otherwise it is named under `warnings:` (QA finding 2).
//! (`source::WholeSet`, M2's ruling: a use can resolve through a file that
//! never spells its name, so no narrowing is sound). The texts read are the
//! texts the write-freshness rule compares against. A file the index
//! skipped (over 1 MiB, not UTF-8) is never edited around: when its bytes
//! spell a name the edit changes, the edit is refused; otherwise it is named
//! on a `warning:` line (QA finding 2 of M3).
use std::path::{Path, PathBuf};
use vlog_refactor::RefactorEdit;
use vlog_parser::span::TextRange;
use vlog_refactor::{RefactorEdit, TextEdit};
use super::select::{target, Target};
use super::mentions::{self, Focus};
use super::names::{self, Declaration};
use super::read_item::split_line;
use super::source::WholeSet;
use super::{nav, Answer, Args, Param, Tool, Ty};
use super::{Answer, Args, Param, Tool, Ty};
use crate::apply::{self, Plan};
use crate::project::{Analysis, Project};
/// `dry_run`, which every edit tool takes.
pub(super) const DRY_RUN: Param = Param {
name: "dry_run",
ty: Ty::Bool,
required: false,
description: "Return the unified diff and write nothing (default false).",
};
const FILE: Param = Param {
name: "file",
ty: Ty::Str,
required: true,
description: "The file holding the position, relative to a root or absolute inside one.",
};
const LINE: Param = Param {
name: "line",
ty: Ty::Int { min: 1 },
required: false,
description: "1-based line in `file`; alone it means the line's first non-blank character.",
};
const COL: Param = Param {
name: "col",
ty: Ty::Int { min: 1 },
required: false,
description: "1-based column in bytes on `line`.",
};
const NAME: Param = Param {
name: "name",
ty: Ty::Str,
required: false,
description: "The name written at the position: with `line`, its occurrence on that line; without, its occurrence in `file`.",
};
/// The position arguments of the six cursor refactorings, then `dry_run`.
const AT: &[Param] = &[FILE, LINE, COL, NAME, DRY_RUN];
/// One engine that acts at a position.
type Engine = fn(&[(PathBuf, String)], &Path, u32) -> Result<RefactorEdit, String>;
/// The names an engine acting at a position changes — what a skipped file
/// must not spell.
type Stake = fn(&Analysis, u32) -> Vec<String>;
pub const EXPAND_WILDCARD: Tool = Tool {
name: "expand_wildcard",
title: "Expand .* connections",
description: "Replace one instantiation's `.*` with the named connections it binds, verified before anything is written. Point at the instance: `file`+`line` (+`col`, or the instance `name`). Refuses a `bind` instance, a positional list, and a port list whose binding depends on `ifdef`s, with the reason. `dry_run` returns the diff.",
params: AT,
rewalk: true,
handler: expand_wildcard,
};
pub const CONVERT_PORTS: Tool = Tool {
name: "convert_ports",
title: "Convert ports to ANSI",
description: "Rewrite a module's non-ANSI header (`module m(a, b); input a; …`) as an ANSI port list, verified before anything is written. Point at the module: `file`+`line` (+`col`, or the module `name`). Refuses a header it cannot convert exactly, with the reason. `dry_run` returns the diff.",
params: AT,
rewalk: true,
handler: convert_ports,
};
pub const ORGANIZE_IMPORTS: Tool = Tool {
name: "organize_imports",
title: "Organize imports",
description: "Remove the unused `import` items of the scope at a position and sort the rest, verified before anything is written. Point into the scope with `file`+`line`. Refuses where it cannot judge (a macro or `include` in the scope, an unknown package), with the reason. `dry_run` returns the diff.",
params: AT,
rewalk: true,
handler: organize_imports,
};
pub const INLINE_MODULE: Tool = Tool {
name: "inline_module",
title: "Inline a module instance",
description: "Replace one instantiation with the body of the module it instantiates, its connections substituted, verified before anything is written. Point at the instance: `file`+`line` (+`col`, or the instance `name`). Refuses what it cannot substitute exactly, with the reason. `dry_run` returns the diff.",
params: AT,
rewalk: true,
handler: inline_module,
};
pub const PROPAGATE_PORTS: Tool = Tool {
name: "propagate_ports",
title: "Connect missing ports",
description: "Add a named connection for every port one instantiation leaves unconnected, verified before anything is written. Point at the instance: `file`+`line` (+`col`, or the instance `name`). Refuses a positional or `.*` list, and an instance that already connects every port. `dry_run` returns the diff.",
params: AT,
rewalk: true,
handler: propagate_ports,
};
pub const REMOVE_PORT: Tool = Tool {
name: "remove_port",
title: "Remove a port",
description: "Delete one module port and its connection from every instantiation in the project, verified before anything is written. Point at the port: `file`+`line` (+`col`, or the port `name`). Refuses a port the body still uses, a positional instantiation, and a deletion that would drop a comment. `dry_run` returns the diff.",
params: AT,
rewalk: true,
handler: remove_port,
};
use crate::project::Project;
use crate::render;
pub const RENAME: Tool = Tool {
name: "rename",
title: "Rename a symbol",
description: "Rename one declaration and every reference to it across the project, verified before anything is written. Select as for `definition`: `file`+`line`+`col`, `file`+`line`+`name`, `file`+`name`, or `name` (+`unit`). Refuses an invalid or clashing name and a use it cannot account for; a name already `new_name` is `unchanged`. A `.*` or `.name` connection that bound the renamed name is written out explicitly (listed in `warnings`).",
description: "Rename declaration `name` (or unit.name) to `new_name` with every resolved use (.name/.* written out); `file` and name@LINE pick among declarations. Lists unresolved mentions.",
params: &[
Param { required: false, ..FILE },
Param {
description: "1-based line in `file`; give `col` too, or the `name` written on that line.",
..LINE
},
COL,
Param {
description: "The name to rename: alone, looked up across the project; with `file`, its occurrence there; with `file` and `line`, its occurrence on that line.",
..NAME
},
Param {
name: "unit",
ty: Ty::Str,
required: false,
description: "With a bare `name`: the module, interface, package or class declaring it.",
},
Param {
name: "new_name",
ty: Ty::Str,
required: true,
description: "The new name.",
},
DRY_RUN,
Param { name: "name", ty: Ty::Str, required: true },
Param { name: "new_name", ty: Ty::Str, required: true },
Param { name: "file", ty: Ty::Str, required: false },
],
rewalk: true,
handler: rename,
};
fn expand_wildcard(project: &mut Project, args: &Args) -> Result<Answer, String> {
at_cursor(project, args, vlog_refactor::expand_wildcard, instantiated)
fn rename(project: &mut Project, args: &Args) -> Result<Answer, String> {
let new_name = args.str("new_name").unwrap_or_default().trim();
let declaration = one_declaration(project, args)?;
let (name, path) = (declaration.name, declaration.path);
if name == new_name {
return Ok(Answer::lines(vec!["renamed 0 sites in 0 files".to_string()]));
}
let set = whole_set(project, Some(&path), std::slice::from_ref(&name))?;
let edit = vlog_refactor::rename(&set.files, &path, declaration.offset, new_name)
.map_err(|why| set.rooted(&why))?;
let sites: usize = edit.edits.iter().map(|(_, edits)| edits.len()).sum();
let unit = vlog_refactor::enclosing_module(&project.analysis(&path)?.text, declaration.offset);
// A member of a module is named bare only where it is declared or used;
// the module (or interface, program) itself is named anywhere.
let unit_itself = matches!(declaration.kind, "module" | "interface" | "program");
let member = unit.is_some() && !unit_itself;
let told = Told { name: &name, home: &path, unit: unit.as_deref(), member };
let done = write_telling(project, edit, &set, &told)?;
let (sites, files) = (render::count(sites, "site"), render::count(done.files, "file"));
let mut lines = vec![format!("renamed {sites} in {files}")];
lines.extend(done.tail);
Ok(Answer::lines(lines))
}
fn convert_ports(project: &mut Project, args: &Args) -> Result<Answer, String> {
at_cursor(project, args, vlog_refactor::convert_to_ansi, enclosing)
/// The declaration a rename means: `name` (or `name@LINE`), in `file` when
/// given — exactly one, else a refusal listing them.
struct Picked {
name: String,
path: PathBuf,
offset: u32,
/// The declaration's kind word (`module`, `var`, …).
kind: &'static str,
}
fn organize_imports(project: &mut Project, args: &Args) -> Result<Answer, String> {
// Only the file's own `import` items change; nothing another file spells.
at_cursor(project, args, vlog_refactor::organize_imports, |_, _| Vec::new())
}
fn inline_module(project: &mut Project, args: &Args) -> Result<Answer, String> {
at_cursor(project, args, vlog_refactor::inline_module, instantiated)
}
fn propagate_ports(project: &mut Project, args: &Args) -> Result<Answer, String> {
at_cursor(project, args, vlog_refactor::propagate_ports, instantiated)
}
fn remove_port(project: &mut Project, args: &Args) -> Result<Answer, String> {
let port_and_module = |analysis: &Analysis, offset: u32| {
let mut names = name_at(analysis, offset);
names.extend(instantiated(analysis, offset));
names
fn one_declaration(project: &mut Project, args: &Args) -> Result<Picked, String> {
let given = args.str("name").unwrap_or_default().trim().trim_start_matches('`');
let (name, line) = split_line(given)?;
let file = match args.str("file") {
Some(file) => Some(project.resolve(file)?),
None => None,
};
at_cursor(project, args, vlog_refactor::remove_port, port_and_module)
}
/// The declared name at a position.
fn name_at(analysis: &Analysis, offset: u32) -> Vec<String> {
vlog_refactor::rename_name_at(&analysis.semantics, offset).into_iter().collect()
}
/// The module an instantiation at a position names, or whose port it is on.
fn instantiated(analysis: &Analysis, offset: u32) -> Vec<String> {
vlog_refactor::port_action_modules_in(&analysis.tree, offset)
}
/// The module whose declaration covers a position.
pub(super) fn enclosing(analysis: &Analysis, offset: u32) -> Vec<String> {
vlog_refactor::enclosing_module(&analysis.text, offset).into_iter().collect()
}
/// Run `engine` at the position the arguments name, over the whole set.
fn at_cursor(
project: &mut Project,
args: &Args,
engine: Engine,
stake: Stake,
) -> Result<Answer, String> {
let (path, offset) = cursor(project, args)?;
let names = stake(&*project.analysis(&path)?, offset);
let set = whole_set(project, Some(&path), &names)?;
let edit = engine(&set.files, &path, offset)?;
finish(project, edit, &set, args)
}
/// The position a cursor refactoring acts at: `file` + `line` alone is the
/// line's first non-blank byte; anything else is `definition`'s selector,
/// which must name a file.
fn cursor(project: &mut Project, args: &Args) -> Result<(PathBuf, u32), String> {
if let (Some(file), Some(line), None, None) =
(args.str("file"), args.int("line"), args.int("col"), args.str("name"))
{
let path = project.resolve(file)?;
let analysis = project.analysis(&path)?;
let line = u32::try_from(line).unwrap_or(u32::MAX);
let Some(range) = analysis.lines.line_range(line) else {
let count = analysis.lines.line_count();
return Err(format!("line {line} is past the end ({count} lines) (in `{file}`)"));
};
let text = analysis.line_text(line);
let blank = text.len() - text.trim_start().len();
return Ok((path, range.start + blank as u32));
let found = names::declarations_walking(project, name);
if found.is_empty() {
return Err(names::no_declaration(project, name));
}
match target(project, args)? {
Target::At { path, offset, .. } => Ok((path, offset)),
Target::Named { .. } => Err("give the `file` the position is in.".into()),
let wanted = |d: &&Declaration| {
file.as_ref().is_none_or(|file| d.path == *file) && line.is_none_or(|line| d.line == line)
};
let picked: Vec<&Declaration> = found.iter().filter(wanted).collect();
match picked.as_slice() {
[] => Err(format!(
"`{given}` is not declared there; its declarations: {}.",
sites(&found.iter().collect::<Vec<_>>())
)),
[one] if one.is_macro() => {
Err(format!("`{name}` is a macro; lucisv does not rename macros."))
}
[one] => {
let name = names::qualified(name).1.to_string();
Ok(Picked { name, path: one.path.clone(), offset: one.offset, kind: one.kind })
}
many => Err(names::ambiguous(name, many, "pass `file`, and `name@LINE` within one file")),
}
}
fn sites(found: &[&Declaration]) -> String {
found.iter().map(|d| format!("{}:{}", d.file, d.line)).collect::<Vec<_>>().join(", ")
}
/// The whole set an engine is handed — refused when a file the index
/// skipped spells one of `names`, since the edit could not reach it.
pub(super) fn whole_set(
@@ -253,31 +122,102 @@ pub(super) fn whole_set(
Ok(set)
}
/// A verified edit over the set's texts, diffed or written; the files the
/// set left out are named under `warnings:`.
pub(super) fn finish(
/// The name an edit changes, for the unresolved-mentions block: the name,
/// the file declaring it, and the unit around it when known.
pub(super) struct Told<'a> {
pub name: &'a str,
pub home: &'a Path,
pub unit: Option<&'a str>,
/// Whether the name is a member of a module or interface: its bare
/// mentions outside its home set (`vlog_refactor::home_set`) are not
/// listed.
pub member: bool,
}
/// What a written edit says after its first line: how many files it wrote,
/// and the warning and `unresolved:` lines.
pub(super) struct Done {
pub files: usize,
pub tail: Vec<String>,
}
/// Write a verified edit over the set's texts, then list the unresolved
/// mentions of `told.name` the edit left alone — found in the texts as the
/// edit writes them, so each `file:line` is right after the write (QA
/// finding 4 of feedback-1).
pub(super) fn write_telling(
project: &Project,
edit: RefactorEdit,
set: &WholeSet,
args: &Args,
) -> Result<Answer, String> {
let mut plan = Plan::from_refactor(edit, &set.files)?;
plan.warnings.extend(set.warning(project));
apply::run(project, plan, args.flag("dry_run", false))
told: &Told,
) -> Result<Done, String> {
let accounted: Vec<(PathBuf, Vec<TextRange>)> =
edit.edits.iter().map(|(path, edits)| (path.clone(), written_ranges(edits))).collect();
let plan = Plan::from_refactor(edit, &set.files)?;
let warnings: Vec<String> = plan.warnings.iter().map(|w| set.rooted(w)).collect();
let named = path_warned(&warnings);
let written = set.files.iter().map(|(path, text)| {
let change = plan.changes.iter().find(|change| &change.path == path);
(path.as_path(), change.map_or(text.as_str(), |change| change.after.as_str()))
});
// The member's home set (the declaring file, what it includes and what
// includes it, and the edited files): where a bare mention can mean it.
let edited: Vec<PathBuf> = plan.changes.iter().map(|change| change.path.clone()).collect();
// `None` — list every mention — for a non-member, and for a member whose
// home set is not known (an include the engine cannot resolve).
let local = match told.member {
true => vlog_refactor::home_set(&set.files, told.home, &edited),
false => None,
};
let focus = Focus {
name: told.name,
home: told.home,
unit: told.unit,
accounted: &accounted,
named: &named,
local: local.as_deref(),
};
let mentions = mentions::find(project, written, &focus);
let done = apply::run(project, &plan)?;
let mut tail = Vec::new();
render::warnings(&mut tail, &warnings);
tail.extend(set.warning(project).map(|warning| format!("warning: {warning}")));
tail.extend(mentions.block());
Ok(Done { files: done.changed.len() + done.created.len(), tail })
}
fn rename(project: &mut Project, args: &Args) -> Result<Answer, String> {
let new_name = args.str("new_name").unwrap_or_default();
let (path, offset) = match target(project, args)? {
Target::At { path, offset, .. } => (path, offset),
Target::Named { name, unit } => nav::declaration_position(project, &name, unit.as_deref())?,
};
let names = name_at(&*project.analysis(&path)?, offset);
// Already renamed: a second identical call is a no-op, not a refusal.
if names.first().map(String::as_str) == Some(new_name) {
return apply::run(project, Plan::default(), args.flag("dry_run", false));
/// The `(file, line)` pairs the engine's unresolved-path warnings name
/// (`rtl/a.sv:3,7: a hierarchical path through …`), so the `unresolved:`
/// block does not list them a second time.
fn path_warned(warnings: &[String]) -> Vec<(String, u32)> {
let mut out = Vec::new();
for warning in warnings {
let Some((head, _)) = warning.split_once(": a hierarchical path through `") else {
continue;
};
let Some((file, lines)) = head.rsplit_once(':') else { continue };
out.extend(
lines
.split(',')
.filter_map(|line| line.parse().ok())
.map(|line| (file.to_string(), line)),
);
}
let set = whole_set(project, Some(&path), &names)?;
let edit = vlog_refactor::rename(&set.files, &path, offset, new_name)?;
finish(project, edit, &set, args)
out
}
/// Where each of one file's edits lands in the text as written: its start
/// shifted by what the edits before it added or removed, its length the
/// new text's.
fn written_ranges(edits: &[TextEdit]) -> Vec<TextRange> {
let mut sorted: Vec<&TextEdit> = edits.iter().collect();
sorted.sort_by_key(|edit| (edit.range.start, edit.range.end));
let mut shift: i64 = 0;
let mut out = Vec::new();
for edit in sorted {
let start = (i64::from(edit.range.start) + shift).max(0) as u32;
out.push(TextRange::new(start, start + edit.new_text.len() as u32));
shift += edit.new_text.len() as i64 - i64::from(edit.range.len());
}
out
}
+199
View File
@@ -0,0 +1,199 @@
//! `find`: where a name is declared and, on `refs`, where each declaration
//! is used — the question an agent otherwise answers by grepping and
//! reading. Declarations come from the index (`names.rs`); uses from
//! `vlog_refactor::find_references` over every indexed file read from disk
//! now (`source::WholeSet`, M2's ruling: a use can resolve through a file
//! that never spells the name); then the name's unresolved mentions —
//! strings, comments, macro text — that no engine resolved.
use std::path::PathBuf;
use vlog_parser::span::TextRange;
use vlog_parser::LineIndex;
use super::mentions::{self, Focus};
use super::names::{self, Declaration};
use super::source::WholeSet;
use super::{Answer, Args, Param, Tool, Ty};
use crate::project::Project;
use crate::render;
/// The most lines an answer holds before `… and N more`.
const CAP: usize = 300;
/// The most declarations whose uses one call lists: each is a whole-set
/// engine run (≈ 2 s on opentitan), and a name declared more often than
/// this is a question `read` or `outline` answers better.
const REFS_CAP: usize = 5;
pub const FIND: Tool = Tool {
name: "find",
description: "Every declaration of `name` or unit.name (kind name file:line; macros too); `refs: true` adds each one's uses as file:line and the unresolved mentions (strings, comments, macro text).",
params: &[
Param { name: "name", ty: Ty::Str, required: true },
Param { name: "refs", ty: Ty::Bool, required: false },
],
rewalk: false,
handler: find,
};
fn find(project: &mut Project, args: &Args) -> Result<Answer, String> {
let name = args.str("name").unwrap_or("").trim().trim_start_matches('`');
if name.is_empty() {
return Err("`name` is empty.".into());
}
let found = names::declarations_walking(project, name);
if found.is_empty() {
return Err(names::no_declaration(project, name));
}
let name = names::qualified(name).1;
if !args.flag("refs") {
let lines = found.iter().map(|declaration| declaration.render(name)).collect();
return Ok(Answer::lines(render::capped(lines, CAP)));
}
// The uses must be searched in every file, so one written since the last
// walk is walked into first.
project.ensure_walked_for_miss();
Ok(Answer::lines(render::capped(with_uses(project, name, &found), CAP)))
}
/// Each declaration's line followed by its uses, then the unresolved
/// mentions of the name no engine accounted for.
fn with_uses(project: &Project, name: &str, found: &[Declaration]) -> Vec<String> {
let set = WholeSet::read(project, None);
let mut lines = Vec::new();
let mut accounted: Vec<(PathBuf, Vec<TextRange>)> = Vec::new();
let mut searched = 0;
for declaration in found {
lines.push(declaration.render(name));
if declaration.is_macro() || searched == REFS_CAP {
continue;
}
searched += 1;
let hits = vlog_refactor::find_references(
&set.files,
&declaration.path,
declaration.offset,
false,
);
match hits {
Ok(hits) => {
lines
.extend(uses(project, &set, &hits).into_iter().map(|line| format!(" {line}")));
account(&mut accounted, hits);
}
Err(why) => {
let why = engine_refusal(&set.rooted(&why));
lines.push(format!(" uses not listed: {why}"));
}
}
}
let followed = found.iter().filter(|declaration| !declaration.is_macro()).count();
if followed > REFS_CAP {
lines.push(format!("uses listed for {REFS_CAP} of {followed} declarations"));
}
let home = &found[0].path;
let local = member_files(&set, found, &accounted);
let focus = Focus {
name,
home,
unit: None,
accounted: &accounted,
named: &[],
local: local.as_deref(),
};
let files = set.files.iter().map(|(path, text)| (path.as_path(), text.as_str()));
lines.extend(mentions::find(project, files, &focus).block());
lines.extend(set.warning(project).map(|warning| format!("warning: {warning}")));
lines
}
/// The files a bare mention of a **module member** can mean it in — each
/// declaration's home set (`vlog_refactor::home_set`) with every file the
/// engine found a use in — or `None` when
/// any declaration is not a member (a unit, a package member, a macro), whose
/// every mention is listed (§65.1, lead's inspection: a `state_q` found in forty
/// modules is not news about this one).
fn member_files(
set: &WholeSet,
found: &[Declaration],
accounted: &[(PathBuf, Vec<TextRange>)],
) -> Option<Vec<PathBuf>> {
if found.iter().any(Declaration::is_macro) {
return None;
}
let hit_files: Vec<PathBuf> = accounted.iter().map(|(path, _)| path.clone()).collect();
let mut local: Vec<PathBuf> = Vec::new();
for declaration in found {
let text = set.files.iter().find(|(p, _)| *p == declaration.path).map(|(_, t)| t)?;
let unit_itself = matches!(declaration.kind, "module" | "interface" | "program");
vlog_refactor::enclosing_module(text, declaration.offset).filter(|_| !unit_itself)?;
local.extend(vlog_refactor::home_set(&set.files, &declaration.path, &hit_files)?);
}
Some(local)
}
/// The engine's hits, one file per line: `file:12,40`.
fn uses(project: &Project, set: &WholeSet, hits: &[(PathBuf, TextRange)]) -> Vec<String> {
let mut sites: Vec<(String, u32)> = Vec::new();
let mut current: Option<(&PathBuf, LineIndex)> = None;
for (path, span) in hits {
if current.as_ref().is_none_or(|(held, _)| *held != path) {
let text = set.files.iter().find(|(held, _)| held == path).map_or("", |(_, t)| t);
current = Some((path, LineIndex::new(text)));
}
if let Some((_, lines)) = &current {
sites.push((project.relative(path), lines.line_col(span.start).0));
}
}
render::by_file(&sites)
}
/// The hits recorded per file, so the mentions pass skips them.
fn account(accounted: &mut Vec<(PathBuf, Vec<TextRange>)>, hits: Vec<(PathBuf, TextRange)>) {
for (path, span) in hits {
match accounted.iter_mut().find(|(held, _)| *held == path) {
Some((_, spans)) => spans.push(span),
None => accounted.push((path, vec![span])),
}
}
}
/// The engine's refusal, said as ours: `find_references` shares the
/// rename's resolution, so its sentences speak of renaming; these do not.
fn engine_refusal(sentence: &str) -> String {
const REWORDED: &[(&str, &str)] = &[
("there is no symbol to rename at this position", "there is no symbol at this position"),
(
"nothing outside the project scope can be renamed",
"nothing outside the project scope is followed",
),
("lucisv found nothing to rename for", "lucisv found no occurrence of"),
("the rename was abandoned", "the search was abandoned"),
("which declaration this rename means", "which declaration this position means"),
(", so a rename here would only be half a rename", ", so its uses cannot all be listed"),
];
let mut out = render::one_line(sentence);
for (from, to) in REWORDED {
out = out.replace(from, to);
}
out
}
#[cfg(test)]
mod tests {
use super::engine_refusal;
#[test]
fn engine_refusals_never_speak_of_renaming() {
for sentence in [
"there is no symbol to rename at this position.",
"`x` is declared outside the files lucisv indexes, so a rename here would only be half a rename.",
"lucisv found nothing to rename for `x`.",
"`x` is declared in more than one indexed file; lucisv will not guess which declaration this rename means.",
] {
let said = engine_refusal(sentence);
assert!(!said.contains("rename"), "{said}");
}
}
}
+87 -157
View File
@@ -1,103 +1,98 @@
//! `format` and `fix_lint`: the CLI's `lucisv format` and `lucisv check
//! --fix`, per file, through the one write path (`apply.rs`).
//! `format`: the CLI's `lucisv format` over a path or a glob, and with
//! `fix` the CLI's `lucisv check --fix` first — each file through the one
//! write path (`apply.rs`).
//!
//! `format` is `format_source` (or `format_range` for `lines`) under the
//! `lucisv.toml` governing each file — the formatter's own safety net decides,
//! and a refusal names the file and writes nothing anywhere. `fix_lint` runs
//! the lint pass `diagnostics` runs (the same config ladder, waivers and
//! cross-file oracle), applies the **safe** fixes whose edits stay out of
//! every `// lucisv: off` fence — the CLI's `--fix` filter — until the file
//! stops changing, and refuses a result that parses worse than the input.
//! Formatting is `format_source` under the `lucisv.toml` governing each file;
//! the formatter's own safety net decides, and a file it refuses is named
//! and left alone while the rest are written (PLAN §10.1). `fix` runs the
//! lint pass `check` runs (the same config ladder, waivers and cross-file
//! oracle), applies the **safe** fixes whose edits stay out of every
//! `// lucisv: off` fence — the CLI's `--fix` filter — until the file stops
//! changing, and refuses a result that parses worse than the input.
use std::collections::BTreeMap;
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::path::{Path, PathBuf};
use lucisv_core::config::{Discovery, FileConfig};
use vlog_formatter::fence::{self, Region};
use vlog_formatter::{format_range, format_source, Config, LineRanges};
use vlog_formatter::{format_source, Config};
use vlog_linter::{apply_fixes, Fix, Violation};
use super::diagnostics::{violations, Mentions, Runs};
use super::edit::DRY_RUN;
use super::glob::path_match;
use super::{Answer, Args, Param, Tool, Ty};
use crate::apply::{self, Change, Plan};
use crate::project::{Analysis, Project};
use crate::render;
/// How many fix-then-relint rounds one file gets — the CLI's cap, for the
/// CLI's reason: two overlapping fixes land in successive rounds.
const MAX_FIX_ROUNDS: usize = 10;
const FILE: Param = Param {
name: "file",
ty: Ty::Str,
required: false,
description: "One file, relative to a root or absolute inside one.",
};
const FILES: Param = Param {
name: "files",
ty: Ty::Str,
required: false,
description: "Several files, comma-separated, instead of `file`.",
};
pub const FORMAT: Tool = Tool {
name: "format",
title: "Format files",
description: "Format `file` (or the comma-separated `files`) as `lucisv format` does, under each file's lucisv.toml; `lines` (`12-40,55`, one file only) formats just the constructs meeting those lines. The formatter verifies its own output: a file it will not format safely refuses the whole call, naming it. An already formatted file is `unchanged`. `dry_run` returns the diff.",
description: "Format `files` (a path, directory or glob like `rtl/**/*.sv`) as lucisv format; `fix: true` applies safe lint fixes first. A file the formatter refuses is named and left alone.",
params: &[
FILE,
FILES,
Param {
name: "lines",
ty: Ty::Str,
required: false,
description: "1-based line ranges such as `12-40,55`; only with a single file.",
},
DRY_RUN,
Param { name: "files", ty: Ty::Str, required: true },
Param { name: "fix", ty: Ty::Bool, required: false },
],
rewalk: false,
handler: format,
};
pub const FIX_LINT: Tool = Tool {
name: "fix_lint",
title: "Apply safe lint fixes",
description: "Apply the safe automatic fixes of the lint findings in `file` (or the comma-separated `files`), as `lucisv check --fix` does: the project's [lint] config and waivers, never inside a `// lucisv: off` fence, never an unsafe fix. Reports which rules were fixed and how many findings remain (`diagnostics` lists them). `rules` narrows the run like --select. `dry_run` returns the diff.",
params: &[
FILE,
FILES,
Param {
name: "rules",
ty: Ty::Str,
required: false,
description: "Comma-separated rule names or severities to fix instead of the configured set.",
},
DRY_RUN,
],
rewalk: false,
handler: fix_lint,
};
/// The files a call names, resolved, each once, in the order given.
fn named_files(project: &Project, args: &Args) -> Result<Vec<PathBuf>, String> {
let given: Vec<&str> = match (args.str("file"), args.str("files")) {
(Some(_), Some(_)) => return Err("give `file` or `files`, not both.".into()),
(Some(file), None) => vec![file],
(None, Some(files)) => files.split(',').map(str::trim).filter(|f| !f.is_empty()).collect(),
(None, None) => return Err("give a `file`, or comma-separated `files`.".into()),
};
if given.is_empty() {
return Err("`files` names no file.".into());
}
let mut out: Vec<PathBuf> = Vec::new();
for file in given {
let path = project.resolve(file)?;
if !out.contains(&path) {
out.push(path);
fn format(project: &mut Project, args: &Args) -> Result<Answer, String> {
let paths = matching_files(project, args.str("files").unwrap_or_default().trim())?;
let fix = args.flag("fix");
let mut discovery = Discovery::new(true);
let mut runs = Runs::new();
let mut plan = Plan::default();
let mut refused: Vec<String> = Vec::new();
for path in paths {
let before = read(project, &path)?;
match fixed_and_formatted(project, &mut discovery, &mut runs, &path, &before, fix) {
Ok(after) => plan.changes.push(Change { path, before, after, created: false }),
Err(why) => refused.push(format!("not formatted: {} ({why})", project.relative(&path))),
}
}
Ok(out)
if plan.changes.is_empty() {
return Err(refused.join("; "));
}
let written = apply::run(project, &plan)?;
let formatted = written.changed.len() + written.unchanged.len();
let unchanged = written.unchanged.len();
let formatted = render::count(formatted, "file");
let mut lines = vec![format!("formatted {formatted} ({unchanged} unchanged)")];
lines.extend(refused);
Ok(Answer::lines(render::capped(lines, 200)))
}
/// The files `files` names: one path, every indexed file below a
/// directory, or every indexed file a glob matches — refused when none.
fn matching_files(project: &mut Project, files: &str) -> Result<Vec<PathBuf>, String> {
if files.is_empty() {
return Err("`files` is empty.".into());
}
let wildcard = files.contains(['*', '?']);
if !wildcard {
if let Ok(path) = project.resolve(files) {
return Ok(vec![path]);
}
}
let select = |project: &Project| -> Vec<PathBuf> {
let kept = |path: &&PathBuf| path_match(files, &project.relative(path));
project.files().map(|(path, _)| path).filter(kept).cloned().collect()
};
let mut found = select(project);
if found.is_empty() && project.ensure_walked_for_miss() {
found = select(project);
}
if found.is_empty() {
return Err(match wildcard {
true => format!("no indexed file matches `{files}`; nothing written."),
false => project.resolve(files).err().unwrap_or_default(),
});
}
Ok(found)
}
/// A file's text as it is on disk now.
@@ -106,24 +101,21 @@ fn read(project: &Project, path: &Path) -> Result<String, String> {
.map_err(|e| format!("cannot read `{}`: {e}", project.relative(path)))
}
fn format(project: &mut Project, args: &Args) -> Result<Answer, String> {
let paths = named_files(project, args)?;
let lines = match args.str("lines") {
None => None,
Some(_) if paths.len() > 1 => return Err("`lines` needs a single file.".into()),
Some(spec) => Some(LineRanges::parse(spec).map_err(|e| format!("`lines`: {e}"))?),
/// One file's new text: its safe lint fixes (on `fix`), then formatted.
fn fixed_and_formatted(
project: &Project,
discovery: &mut Discovery,
runs: &mut Runs,
path: &Path,
before: &str,
fix: bool,
) -> Result<String, String> {
let text = match fix {
true => fix_file(project, runs, path, before)?,
false => before.to_string(),
};
let mut discovery = Discovery::new(true);
let mut plan = Plan::default();
for path in paths {
let before = read(project, &path)?;
let config = formatter_config(&discovery.for_file(&path)?);
let after = formatted(&before, &config, lines.as_ref()).map_err(|why| {
format!("`{}` was not formatted: {why}; nothing written.", project.relative(&path))
})?;
plan.changes.push(Change { path, before, after, created: false });
}
apply::run(project, plan, args.flag("dry_run", false))
let config = formatter_config(&discovery.for_file(path)?);
formatted(&text, &config)
}
/// The formatter settings a file's `lucisv.toml` resolves to — the CLI's
@@ -144,11 +136,8 @@ fn formatter_config(file: &FileConfig) -> Config {
/// Format one text; a formatter panic is an error like any other, never the
/// end of the server.
fn formatted(text: &str, config: &Config, lines: Option<&LineRanges>) -> Result<String, String> {
let run = catch_unwind(AssertUnwindSafe(|| match lines {
Some(lines) => format_range(text, config, lines),
None => format_source(text, config),
}));
fn formatted(text: &str, config: &Config) -> Result<String, String> {
let run = catch_unwind(AssertUnwindSafe(|| format_source(text, config)));
match run {
Ok(Ok(out)) => Ok(out),
Ok(Err(e)) => Err(e.to_string()),
@@ -156,37 +145,6 @@ fn formatted(text: &str, config: &Config, lines: Option<&LineRanges>) -> Result<
}
}
fn fix_lint(project: &mut Project, args: &Args) -> Result<Answer, String> {
let paths = named_files(project, args)?;
let selected: Option<Vec<String>> = args.str("rules").map(|rules| {
rules.split(',').map(str::trim).filter(|r| !r.is_empty()).map(str::to_string).collect()
});
let mut runs = Runs::new(selected);
let mut plan = Plan::default();
let mut fixed: BTreeMap<&'static str, usize> = BTreeMap::new();
let mut left = 0;
for path in paths {
let before = read(project, &path)?;
let outcome = fix_file(project, &mut runs, &path, &before)?;
for (rule, count) in outcome.fixed {
*fixed.entry(rule).or_default() += count;
}
left += outcome.left;
plan.changes.push(Change { path, before, after: outcome.text, created: false });
}
plan.note = Some(fixed_note(&fixed, left));
apply::run(project, plan, args.flag("dry_run", false))
}
/// What fixing one file came to.
struct Fixed {
text: String,
/// Per rule, how many of its findings the fixes removed.
fixed: BTreeMap<&'static str, usize>,
/// Findings still reported after the last round.
left: usize,
}
/// Fix, re-lint, repeat until nothing more applies; refuse a result whose
/// tolerant parse reports more errors than the input's did.
fn fix_file(
@@ -194,13 +152,12 @@ fn fix_file(
runs: &mut Runs,
path: &Path,
before: &str,
) -> Result<Fixed, String> {
) -> Result<String, String> {
let run = runs.for_file(path)?;
let oracle = Mentions::of_file(project.index(), project.index().file_id(path));
let first = Analysis::of(before.to_string());
let errors_before = first.diagnostics.len();
let found = violations(&run, path, &first, &oracle);
let mut remaining = found.clone();
let mut remaining = violations(&run, path, &first, &oracle);
let mut text = before.to_string();
let mut errors_after = errors_before;
for _ in 0..MAX_FIX_ROUNDS {
@@ -215,12 +172,10 @@ fn fix_file(
}
if errors_after > errors_before {
return Err(format!(
"fixing `{}` would leave it with {errors_after} parse errors where it had {errors_before}; nothing written.",
project.relative(path)
"its fixes would leave {errors_after} parse errors where it had {errors_before}"
));
}
let fixed = removed_per_rule(&found, &remaining);
Ok(Fixed { text, fixed, left: remaining.len() })
Ok(text)
}
/// The findings whose fix may be applied: those whose every edit stays out
@@ -240,28 +195,3 @@ fn touches_fence(fix: &Fix, regions: &[Region]) -> bool {
.iter()
.any(|(range, _)| fence::is_protected(regions, range.start as usize, range.end as usize))
}
/// Per rule, how many fewer findings the fixed text has.
fn removed_per_rule(before: &[Violation], after: &[Violation]) -> BTreeMap<&'static str, usize> {
let count = |found: &[Violation]| {
let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
found.iter().for_each(|v| *counts.entry(v.rule).or_default() += 1);
counts
};
let after = count(after);
count(before)
.into_iter()
.filter_map(|(rule, n)| {
let gone = n.saturating_sub(after.get(rule).copied().unwrap_or(0));
(gone > 0).then_some((rule, gone))
})
.collect()
}
/// `fixed: rule ×2, rule ×1; 3 findings left`.
fn fixed_note(fixed: &BTreeMap<&'static str, usize>, left: usize) -> String {
let listed: Vec<String> = fixed.iter().map(|(rule, n)| format!("{rule} ×{n}")).collect();
let fixed = if listed.is_empty() { "nothing".to_string() } else { listed.join(", ") };
let plural = if left == 1 { "" } else { "s" };
format!("fixed: {fixed}; {left} finding{plural} left")
}
+102
View File
@@ -0,0 +1,102 @@
//! Path globs, as `format`'s `files` takes them: `*` and `?` within one
//! path component, `**` for any run of components, and a bare directory
//! for everything below it — the `.gitignore` / `rg -g` reading.
/// Whether `name` matches a glob of `*` (any run) and `?` (one character).
pub fn glob_match(pattern: &str, name: &str) -> bool {
let pattern: Vec<char> = pattern.chars().collect();
let name: Vec<char> = name.chars().collect();
// Classic two-pointer match with one backtrack point per `*`.
let (mut p, mut n, mut star, mut resume) = (0, 0, None, 0);
while n < name.len() {
if p < pattern.len() && (pattern[p] == '?' || pattern[p] == name[n]) {
p += 1;
n += 1;
} else if p < pattern.len() && pattern[p] == '*' {
star = Some(p);
resume = n;
p += 1;
} else if let Some(at) = star {
p = at + 1;
resume += 1;
n = resume;
} else {
return false;
}
}
pattern[p..].iter().all(|&c| c == '*')
}
/// Whether a root-relative `path` matches a path glob: `*` and `?` within
/// one component ([`glob_match`]), `**` as a whole component for any run of
/// components (none included). A trailing `/` means everything below.
pub fn path_match(pattern: &str, path: &str) -> bool {
let pattern = pattern.strip_prefix("./").unwrap_or(pattern);
// A bare directory (`ip/aes`, no wildcard) means everything below it, as
// it does for `.gitignore` and `rg -g` (feedback-2 QA note 2).
let literal = !pattern.contains(['*', '?']);
if literal && path.strip_prefix(pattern).is_some_and(|rest| rest.starts_with('/')) {
return true;
}
let mut parts: Vec<&str> = pattern.split('/').collect();
if parts.last() == Some(&"") && parts.len() > 1 {
parts.pop();
parts.push("**");
}
// `**/**` means what `**` means; collapsing keeps the search linear-ish.
parts.dedup_by(|a, b| *a == "**" && *b == "**");
let components: Vec<&str> = path.split('/').collect();
components_match(&parts, &components)
}
fn components_match(pattern: &[&str], path: &[&str]) -> bool {
match pattern.split_first() {
None => path.is_empty(),
Some((&"**", rest)) => (0..=path.len()).any(|skip| components_match(rest, &path[skip..])),
Some((first, rest)) => path
.split_first()
.is_some_and(|(part, below)| glob_match(first, part) && components_match(rest, below)),
}
}
#[cfg(test)]
mod tests {
use super::{glob_match, path_match};
#[test]
fn a_bare_directory_glob_means_everything_below_it() {
assert!(super::path_match("ip/aes", "ip/aes/rtl/aes.sv"));
assert!(super::path_match("ip/aes/", "ip/aes/rtl/aes.sv"));
assert!(!super::path_match("ip/aes", "ip/aes_x/rtl/aes.sv"));
assert!(!super::path_match("ip/aes", "ip/ae"));
assert!(super::path_match("ip/aes/rtl/aes.sv", "ip/aes/rtl/aes.sv"));
assert!(!super::path_match("ip/a?s", "ip/aes/rtl/aes.sv"), "a wildcard keeps glob rules");
}
#[test]
fn globs_match_runs_and_single_characters() {
assert!(glob_match("prim_*", "prim_fifo_sync"));
assert!(glob_match("*fifo*", "prim_fifo_sync"));
assert!(glob_match("a?c", "abc"));
assert!(glob_match("*", ""));
assert!(!glob_match("a?c", "ac"));
assert!(!glob_match("prim_*_async", "prim_fifo_sync"));
assert!(glob_match("*_sync", "prim_fifo_sync"));
}
#[test]
fn path_globs_keep_star_in_one_component_and_let_double_star_span_many() {
assert!(path_match("ip/**/rtl/*.sv", "ip/aes/rtl/aes.sv"));
assert!(path_match("ip/**/rtl/*.sv", "ip/aes/sub/rtl/aes.sv"));
assert!(path_match("ip/**/rtl/*.sv", "ip/rtl/x.sv"));
assert!(!path_match("ip/**/rtl/*.sv", "ip/aes/dv/aes.sv"));
assert!(!path_match("ip/*/*.sv", "ip/aes/rtl/aes.sv"));
assert!(!path_match("*.sv", "ip/aes.sv"));
assert!(path_match("**/*.sv", "ip/aes.sv") && path_match("**/*.sv", "top.sv"));
assert!(path_match("ip/ae?/**", "ip/aes/rtl/aes.sv"));
assert!(!path_match("ip/ae?/**", "ip/aesx/rtl/aes.sv"));
assert!(path_match("ip/", "ip/aes/rtl/aes.sv") && path_match("./ip/**", "ip/a.sv"));
assert!(path_match("**/**/**/rtl/**", "a/b/rtl/c/d.sv"));
assert!(!path_match("ip/**", "hw/ip/aes.sv"));
}
}
+186 -223
View File
@@ -1,7 +1,10 @@
//! `hierarchy`: the instance tree, down from a module (or from every
//! top-level module) or up to the modules that instantiate it — read off the
//! index's instantiation edges, textual rather than elaborated, exactly the
//! census the editor's hierarchy view and call hierarchy draw from.
//! `hierarchy`: the project's shape. Without a `root`, the counts and the
//! top modules; with one, the instance tree down from it or every
//! instantiation of it up to `depth` levels — read off the index's
//! instantiation edges, textual rather than elaborated, exactly the census
//! the editor's hierarchy view and call hierarchy draw from. Every instance
//! line points at its **instantiation site**, and `peek` shows the
//! statement written there.
//!
//! The walk is cut three ways: by `depth`, by a module already on the path
//! (a module that instantiates itself, through `generate` or otherwise, ends
@@ -12,61 +15,44 @@
use std::collections::HashMap;
use std::path::Path;
use serde_json::{json, Value};
use vlog_parser::span::TextRange;
use vlog_semantic::{
Def, FileId, InstanceOccurrence, InstantiationEdge, SymbolKind, WorkspaceIndex,
};
use super::source::{self, Texts};
use super::names;
use super::source::Texts;
use super::{Answer, Args, Param, Tool, Ty};
use crate::project::Project;
use crate::render::{self, DEFAULT_LIMIT};
use crate::render;
/// The deepest a walk may go, whatever `depth` asks.
const MAX_DEPTH: usize = 20;
/// The longest overrides text a line shows; the JSON carries all of it.
const OVERRIDES_CAP: usize = 200;
const MAX_DEPTH: i64 = 20;
/// The most nodes one walk collects before it stops.
const NODE_CAP: usize = 50_000;
/// The most lines the overview holds, and the most nodes (tree lines, the
/// root's included) a tree answer without `peek` shows, before
/// `… and N more`.
const CAP: usize = 300;
/// The most nodes a tree answer with `peek` shows. A node's `peek` lines
/// never count — the cap is on instances — but each costs up to 13 lines,
/// so the answer stays short (PLAN §10.1).
const PEEK_CAP: usize = 100;
/// The most source lines `peek` shows of one statement before `…`.
const PEEK_LINES: usize = 12;
pub const HIERARCHY: Tool = Tool {
name: "hierarchy",
title: "Instance hierarchy",
description: "The instance tree as indented `instance : module #(overrides)` lines, down from `root` (default: every top-level module), or with `direction: up` every `parent.instance` that instantiates `root`, with file:line. Textual, not elaborated: `generate` and `ifdef` branches all appear. Prefer it over reading files to find who instantiates what.",
description: "The instance tree of `root` to `depth` (1-20, default 1), each at its instantiation file:line; `up`: its instantiations; `peek`: each statement's source. No `root`: file/module counts and the top modules.",
params: &[
Param {
name: "root",
ty: Ty::Str,
required: false,
description: "The module to start from; required for `up` (default for `down`: every module nothing instantiates).",
},
Param {
name: "direction",
ty: Ty::Enum(&["down", "up"]),
required: false,
description: "`down` lists what `root` instantiates (default); `up` lists what instantiates it.",
},
Param {
name: "depth",
ty: Ty::Range { min: 1, max: MAX_DEPTH as i64 },
required: false,
description: "Levels to walk (default 3, at most 20).",
},
Param {
name: "limit",
ty: Ty::Int { min: 1 },
required: false,
description: "Most lines to return (default 200).",
},
Param {
name: "offset",
ty: Ty::Int { min: 0 },
required: false,
description: "Lines to skip, for paging past `… and N more` (default 0).",
},
Param { name: "root", ty: Ty::Str, required: false },
Param { name: "up", ty: Ty::Bool, required: false },
Param { name: "depth", ty: Ty::Range { min: 1, max: MAX_DEPTH }, required: false },
Param { name: "peek", ty: Ty::Bool, required: false },
],
rewalk: false,
handler: hierarchy,
@@ -82,75 +68,86 @@ struct Child {
site: TextRange,
/// The instance's own name.
name: TextRange,
/// Where the statement's first instance name starts: the `#(...)`
/// belongs to the whole statement and ends before it.
first: u32,
/// Where the statement's last instance ends.
end: u32,
}
impl Child {
/// One instance of an edge to `module`.
fn of(module: &str, edge: &InstantiationEdge, occurrence: &InstanceOccurrence) -> Child {
let first =
edge.instances.first().map_or(occurrence.name_span.start, |i| i.name_span.start);
let end = edge.instances.last().map_or(occurrence.span.end, |last| last.span.end);
Child {
instance: occurrence.name.clone(),
module: module.to_string(),
file: edge.file,
site: edge.site_span,
name: occurrence.name_span,
first,
end,
}
}
}
/// One line of the answer. A root line has no instance.
/// One line of a tree. A root line (down only) has no instance.
struct Node {
depth: usize,
/// Down: the instance; up: the instance of the line above it.
/// Down: the instance; up: the instance of the module on the line above.
instance: Option<Child>,
/// Down: the instantiated module; up: the instantiating one; root: itself.
module: String,
root: Option<Def>,
note: Option<String>,
}
/// A walk in progress: the edges by owner, what it collected, and the path
/// of modules above the current node.
struct Walk<'a> {
index: &'a WorkspaceIndex,
below: HashMap<(FileId, u32), Vec<Child>>,
max_depth: usize,
nodes: Vec<Node>,
path: Vec<String>,
note: Option<&'static str>,
declared: usize,
}
fn hierarchy(project: &mut Project, args: &Args) -> Result<Answer, String> {
let up = args.str("direction") == Some("up");
let root = args.str("root").filter(|root| !root.is_empty());
if up && root.is_none() {
return Err("`direction: up` needs a `root`.".into());
}
if let Some(root) = root {
if modules_named(project.index(), root).is_empty() {
project.ensure_walked_for_miss();
}
if modules_named(project.index(), root).is_empty() {
return Err(format!("no module or interface `{root}` is indexed."));
}
}
let max_depth = args.count("depth", 3);
let index = project.index();
let mut walk = Walk::new(index, max_depth, !up);
let roots: Vec<(String, Def)> = match root {
Some(root) => {
modules_named(index, root).into_iter().map(|d| (root.to_string(), d)).collect()
}
None => top_modules(index),
let Some(root) = args.str("root").map(str::trim).filter(|root| !root.is_empty()) else {
// Files written since the last walk are counted.
project.ensure_walked_for_miss();
return Ok(Answer::lines(overview(project)));
};
for (name, def) in roots {
walk.root(name, def, up);
if modules_named(project.index(), root).is_empty() {
project.ensure_walked_for_miss();
}
Ok(render(project, walk.nodes, up, args))
let index = project.index();
let declared = modules_named(index, root);
if declared.is_empty() {
let similar = names::similar_units(index, root, 10);
return Err(match similar.is_empty() {
true => format!("no module or interface named `{root}`."),
false => {
format!("no module or interface named `{root}`; similar: {}.", similar.join(", "))
}
});
}
let (up, depth) = (args.flag("up"), args.count("depth", 1));
let mut walk = Walk::new(index, depth, !up);
if up {
walk.path = vec![root.to_string()];
walk.up(root, 1);
} else {
for def in declared {
walk.root(root, def);
}
}
if up && walk.nodes.is_empty() {
return Ok(Answer::lines(vec![format!("nothing instantiates {root}")]));
}
Ok(Answer::lines(render_nodes(project, &walk.nodes, up, args.flag("peek"))))
}
/// `N files, M modules, K top`, then each top module as `name file:line`.
fn overview(project: &Project) -> Vec<String> {
let index = project.index();
let modules = index.units_of(SymbolKind::Module).count();
let tops = top_modules(index);
let files = project.files().count();
let (files, modules) = (render::count(files, "file"), render::count(modules, "module"));
let mut lines = vec![format!("{files}, {modules}, {} top", tops.len())];
for (name, def) in &tops {
let path = index.path(def.file).unwrap_or(Path::new(""));
lines.push(format!("{name} {}:{}", project.relative(path), def.lines.name));
}
render::capped(lines, CAP)
}
/// Every instantiable declaration of `name`.
@@ -168,8 +165,18 @@ fn top_modules(index: &WorkspaceIndex) -> Vec<(String, Def)> {
.collect()
}
/// A walk in progress: the edges by owner, what it collected, and the path
/// of modules above the current node.
struct Walk<'a> {
index: &'a WorkspaceIndex,
below: HashMap<(FileId, u32), Vec<Child>>,
max_depth: usize,
nodes: Vec<Node>,
path: Vec<String>,
}
impl<'a> Walk<'a> {
/// A walk over `index`; the owner table is built only for `down`.
/// A walk over the index; the owner table is built only for `down`.
fn new(index: &'a WorkspaceIndex, max_depth: usize, down: bool) -> Walk<'a> {
let mut below: HashMap<(FileId, u32), Vec<Child>> = HashMap::new();
for (module, edges) in index.instantiations().filter(|_| down) {
@@ -191,24 +198,21 @@ impl<'a> Walk<'a> {
}
/// One root line and its tree.
fn root(&mut self, name: String, def: Def, up: bool) {
fn root(&mut self, name: &str, def: Def) {
if self.full() {
return;
}
self.path = vec![name.clone()];
self.path = vec![name.to_string()];
let line = Node {
depth: 0,
instance: None,
module: name.clone(),
module: name.to_string(),
root: Some(def.clone()),
note: None,
declared: 1,
};
self.nodes.push(line);
if up {
self.up(&name, 1);
} else {
self.down(&def, 1);
}
self.down(&def, 1);
}
/// The instances `def` declares, and theirs, to `max_depth`.
@@ -222,10 +226,10 @@ impl<'a> Walk<'a> {
let declared = modules_named(self.index, &child.module);
let recursive = self.path.contains(&child.module);
let note = match declared.len() {
_ if recursive => Some("recursive".to_string()),
0 => Some("not indexed".to_string()),
_ if recursive => Some("recursive"),
0 => Some("not indexed"),
1 => None,
n => Some(format!("declared {n} times")),
_ => Some("declared"),
};
let expand = note.is_none() && depth < self.max_depth;
let module = child.module.clone();
@@ -235,6 +239,7 @@ impl<'a> Walk<'a> {
module: module.clone(),
root: None,
note,
declared: declared.len(),
});
if let (true, [only]) = (expand, declared.as_slice()) {
self.path.push(module);
@@ -254,14 +259,13 @@ impl<'a> Walk<'a> {
}
let parent = edge.owner.name.clone();
let recursive = self.path.contains(&parent);
let child = Child::of(module, edge, occurrence);
let note = recursive.then(|| "recursive".to_string());
self.nodes.push(Node {
depth,
instance: Some(child),
instance: Some(Child::of(module, edge, occurrence)),
module: parent.clone(),
root: None,
note,
note: recursive.then_some("recursive"),
declared: 1,
});
if !recursive && depth < self.max_depth {
self.path.push(parent.clone());
@@ -273,136 +277,95 @@ impl<'a> Walk<'a> {
}
}
/// The collected nodes, paged, as indented lines and as a flat JSON list.
fn render(project: &Project, nodes: Vec<Node>, up: bool, args: &Args) -> Answer {
let (shown, rest) =
render::page(&nodes, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
/// The nodes as lines, two spaces per level (`up` starts at no indent),
/// each followed by its statement on `peek`; at most [`CAP`] nodes
/// ([`PEEK_CAP`] with `peek`), then `… and N more` counting the nodes not
/// shown.
fn render_nodes(project: &Project, nodes: &[Node], up: bool, peek: bool) -> Vec<String> {
let mut texts = Texts::default();
let mut text = String::new();
let mut listed: Vec<Value> = Vec::new();
for node in shown {
let line = Line::of(project, &mut texts, node);
text.push_str(&" ".repeat(node.depth));
text.push_str(&line.text(node, up));
text.push('\n');
listed.push(line.json(node, up));
let mut lines: Vec<String> = Vec::new();
let cap = if peek { PEEK_CAP } else { CAP };
for (at, node) in nodes.iter().enumerate() {
if at == cap {
lines.push(render::more(nodes.len() - at));
return lines;
}
let level = if up { node.depth - 1 } else { node.depth };
let indent = " ".repeat(level);
lines.push(format!("{indent}{}", node_line(project, &mut texts, node, up)));
if let (true, Some(child)) = (peek, &node.instance) {
let source = statement(project, &mut texts, child);
// A blank line of the statement stays blank: no indent of ours.
let shown = |line: String| match line.is_empty() {
true => line,
false => format!("{indent} {line}"),
};
lines.extend(source.into_iter().map(shown));
}
}
render::more(&mut text, rest);
if nodes.len() >= NODE_CAP {
text.push_str(&format!("tree cut at {NODE_CAP} nodes; lower `depth` or pick a `root`\n"));
}
if nodes.is_empty() {
text = "no modules\n".to_string();
}
let direction = if up { "up" } else { "down" };
let structured = json!({
"direction": direction, "nodes": listed, "total": nodes.len(),
"cut": nodes.len() >= NODE_CAP,
});
Answer { text, structured }
lines
}
/// What one node's line needs from its file: where it is and the overrides.
struct Line {
file: String,
line: u32,
overrides: Option<String>,
}
impl Line {
fn of(project: &Project, texts: &mut Texts, node: &Node) -> Line {
let index = project.index();
if let Some(def) = &node.root {
/// One node: `instance: module file:line` down, `parent.instance file:line`
/// up, `module file:line` for a root — the instance's line is where it is
/// instantiated, the root's where it is declared.
fn node_line(project: &Project, texts: &mut Texts, node: &Node, up: bool) -> String {
let index = project.index();
let mut out = match (&node.instance, &node.root) {
(Some(child), _) => {
let path = index.path(child.file).unwrap_or(Path::new(""));
let line = texts.get(path).map_or(0, |(_, lines)| lines.line_col(child.name.start).0);
let at = format!("{}:{line}", project.relative(path));
match up {
false => format!("{}: {} {at}", child.instance, child.module),
true => format!("{}.{} {at}", node.module, child.instance),
}
}
(None, Some(def)) => {
let path = index.path(def.file).unwrap_or(Path::new(""));
return Line { file: project.relative(path), line: def.lines.name, overrides: None };
format!("{} {}:{}", node.module, project.relative(path), def.lines.name)
}
let Some(child) = &node.instance else {
return Line { file: String::new(), line: 0, overrides: None };
};
let path = index.path(child.file).unwrap_or(Path::new(""));
let file = project.relative(path);
let Some((text, lines)) = texts.get(path) else {
return Line { file, line: 0, overrides: None };
};
let line = lines.line_col(child.name.start).0;
Line { file, line, overrides: overrides(text, child) }
}
fn text(&self, node: &Node, up: bool) -> String {
let mut out = match (&node.instance, up) {
(None, _) => format!("{} {}:{}", node.module, self.file, self.line),
(Some(child), false) => format!("{} : {}", child.instance, child.module),
(Some(child), true) => format!("{}.{}", node.module, child.instance),
};
if let Some(overrides) = &self.overrides {
out.push(' ');
out.push_str(&source::capped(overrides, OVERRIDES_CAP));
}
if up && node.instance.is_some() {
out.push_str(&format!(" {}:{}", self.file, self.line));
}
if let Some(note) = &node.note {
out.push_str(&format!(" ({note})"));
}
out
}
fn json(&self, node: &Node, up: bool) -> Value {
let child = node.instance.as_ref();
json!({
"depth": node.depth,
"instance": child.map(|child| child.instance.clone()),
"module": child.map_or(node.module.clone(), |child| child.module.clone()),
"parent": child.filter(|_| up).map(|_| node.module.clone()),
"file": self.file,
"line": self.line,
"overrides": self.overrides,
"note": node.note,
})
(None, None) => node.module.clone(),
};
match node.note {
Some("declared") => out.push_str(&format!(" (declared {} times)", node.declared)),
Some(note) => out.push_str(&format!(" ({note})")),
None => {}
}
out
}
/// The `#(...)` written between the module name and the instance name,
/// comments dropped, on one line — when the file still spells the module
/// name at the site.
fn overrides(text: &str, child: &Child) -> Option<String> {
/// The instantiation statement around `child`, as written: from the start
/// of the line naming the module to the end of the line holding its `;`,
/// its common indentation removed, cut at [`PEEK_LINES`] lines. Nothing
/// when the file no longer spells the module there.
fn statement(project: &Project, texts: &mut Texts, child: &Child) -> Vec<String> {
let index = project.index();
let Some((text, _)) = index.path(child.file).and_then(|path| texts.get(path)) else {
return Vec::new();
};
if text.get(child.site.as_range()) != Some(child.module.as_str()) {
return None;
}
let between = text.get(child.site.end as usize..child.first as usize)?;
let written = source::without_comments(between);
let written = written.trim();
written.starts_with('#').then(|| render::one_line(written))
}
#[cfg(test)]
mod tests {
use super::*;
fn child(text: &str, module: &str, instance: &str) -> Child {
let site = text.find(module).unwrap() as u32;
let name = text.find(instance).unwrap() as u32;
Child {
instance: instance.to_string(),
module: module.to_string(),
file: FileId(0),
site: TextRange::new(site, site + module.len() as u32),
name: TextRange::new(name, name + instance.len() as u32),
first: text.find(" u_").unwrap() as u32 + 1,
}
}
#[test]
fn overrides_are_sliced_between_the_module_and_the_instance_name() {
let text = " fifo #( // sizes\n .Width (8),\n .Depth(2)\n ) u_fifo (.*);";
let fifo = child(text, "fifo", "u_fifo");
assert_eq!(overrides(text, &fifo).as_deref(), Some("#( .Width (8), .Depth(2) )"));
let plain = " fifo u_plain (.*);";
assert_eq!(overrides(plain, &child(plain, "fifo", "u_plain")), None);
let two = " fifo #(.W(2)) u_a (), u_b ();";
assert_eq!(overrides(two, &child(two, "fifo", "u_b")).as_deref(), Some("#(.W(2))"));
let mut stale = fifo.clone();
stale.module = "other".into();
assert_eq!(overrides(text, &stale), None);
return Vec::new();
}
let site = child.site.start as usize;
let end = (child.end as usize).min(text.len());
let start = text[..site].rfind('\n').map_or(0, |at| at + 1);
let semi = text[end..].find(';').map_or(end, |at| end + at + 1);
let stop = text[semi..].find('\n').map_or(text.len(), |at| semi + at);
let written: Vec<&str> = text[start..stop].lines().map(str::trim_end).collect();
let margin = written
.iter()
.filter(|line| !line.trim().is_empty())
.map(|line| line.len() - line.trim_start().len())
.min()
.unwrap_or(0);
let mut out: Vec<String> = written
.iter()
.take(PEEK_LINES)
.map(|line| line.get(margin..).unwrap_or("").to_string())
.collect();
if written.len() > PEEK_LINES {
out.push("…".to_string());
}
out
}
+66 -208
View File
@@ -1,75 +1,43 @@
//! `unit_interface`: what a unit offers the code that uses it — a module's
//! or interface's parameters, ports and instantiation template (plus an
//! interface's modports), a package's or class's exported members — without
//! the agent reading the file that declares it.
//! `outline unit:` — what a unit offers the code that uses it: a module's
//! or interface's parameters and ports in declaration order (plus an
//! interface's modports), a package's or class's members — without the
//! agent reading the file that declares it.
use std::path::PathBuf;
use serde_json::{json, Value};
use vlog_parser::ast::{Item, ItemKind};
use vlog_parser::span::TextRange;
use vlog_refactor::{instantiation_plan, InstantiationPlan, Layout};
use vlog_refactor::{instantiation_plan, InstantiationPlan};
use vlog_semantic::{Def, ScopeId, Semantics, Symbol, SymbolKind};
use super::read_item::child_items;
use super::{Answer, Args, Param, Tool, Ty};
use crate::project::{Analysis, Project};
use crate::render;
pub const UNIT_INTERFACE: Tool = Tool {
name: "unit_interface",
title: "Unit interface",
description: "The interface of one unit by name: a module's or interface's parameters with defaults, ports in declaration order (direction, type, range) and a ready-to-paste instantiation; an interface's modports; a package's or class's members. Prefer it over reading the declaring file. Refuses a name declared in several files unless `file` picks one.",
params: &[
Param {
name: "name",
ty: Ty::Str,
required: true,
description: "The unit's name; a class inside a package may be written `pkg::cls`.",
},
Param {
name: "file",
ty: Ty::Str,
required: false,
description: "The declaring file, when the name is declared more than once.",
},
],
rewalk: false,
handler: unit_interface,
};
/// A unit found in the index: where it is, and what it is.
struct Found {
path: PathBuf,
def: Def,
}
fn unit_interface(project: &mut Project, args: &Args) -> Result<Answer, String> {
let name = args.str("name").unwrap_or("");
let mut found = candidates(project, name, args.str("file"))?;
/// The unit's `file:line`, then its interface, one fact per line.
pub fn unit_outline(project: &mut Project, name: &str) -> Result<Vec<String>, String> {
let mut found = candidates(project, name);
if found.is_empty() && project.ensure_walked_for_miss() {
found = candidates(project, name, args.str("file"))?;
found = candidates(project, name);
}
let found = pick(project, found, name, args.str("file"))?;
let found = pick(project, found, name)?;
let analysis = project.analysis(&found.path)?;
let file = project.relative(&found.path);
let kind = super::read::unit_kind(project, &found.path, &found.def);
let head = format!("{kind} {name} {file}:{}\n", found.def.lines.name);
let head = format!("{}:{}", project.relative(&found.path), found.def.lines.name);
let short = name.rsplit("::").next().unwrap_or(name);
match found.def.kind {
SymbolKind::Module | SymbolKind::Interface => {
instantiable(&analysis, &found, short, head, &file).map(|mut answer| {
answer.structured["kind"] = Value::from(kind);
answer
})
}
_ => Ok(members(project, &analysis, &found, short, head, &file)),
SymbolKind::Module | SymbolKind::Interface => instantiable(&analysis, &found, short, head),
_ => Ok(members(project, &analysis, &found, short, head)),
}
}
/// Every indexed declaration of `name` (in `file`, when given). `Err` only
/// when `file` itself is refused.
fn candidates(project: &Project, name: &str, file: Option<&str>) -> Result<Vec<Found>, String> {
/// Every indexed unit declaration of `name` (`pkg::cls` for a class).
fn candidates(project: &Project, name: &str) -> Vec<Found> {
let index = project.index();
let unit_kinds =
[SymbolKind::Module, SymbolKind::Interface, SymbolKind::Package, SymbolKind::Class];
@@ -78,30 +46,23 @@ fn candidates(project: &Project, name: &str, file: Option<&str>) -> Result<Vec<F
None => index.units(name).to_vec(),
};
defs.retain(|def| unit_kinds.contains(&def.kind));
let mut found: Vec<Found> = defs
.into_iter()
defs.into_iter()
.filter_map(|def| Some(Found { path: index.path(def.file)?.to_path_buf(), def }))
.collect();
if let Some(file) = file {
let path = project.resolve(file)?;
found.retain(|f| f.path == path);
}
Ok(found)
.collect()
}
/// The one declaration among `found`, or a refusal that says why there is
/// not exactly one.
fn pick(
project: &Project,
mut found: Vec<Found>,
name: &str,
file: Option<&str>,
) -> Result<Found, String> {
fn pick(project: &Project, mut found: Vec<Found>, name: &str) -> Result<Found, String> {
match found.len() {
0 => Err(format!(
"no module, interface, package or class named `{name}` is indexed{}; search_symbols finds near names.",
file.map_or(String::new(), |f| format!(" in `{f}`"))
)),
0 => {
let similar = super::names::similar_units(project.index(), name, 10);
let near = match similar.is_empty() {
true => String::new(),
false => format!("; similar: {}", similar.join(", ")),
};
Err(format!("no module, interface, package or class named `{name}`{near}."))
}
1 => Ok(found.remove(0)),
_ => {
let sites: Vec<String> = found
@@ -109,7 +70,7 @@ fn pick(
.map(|f| format!("{}:{}", project.relative(&f.path), f.def.lines.name))
.collect();
Err(format!(
"`{name}` is declared {} times ({}); pass `file` to pick one.",
"`{name}` is declared {} times ({}); outline one `file` instead.",
sites.len(),
sites.join(", ")
))
@@ -117,38 +78,30 @@ fn pick(
}
}
/// A module's or interface's parameters, ports, modports and template.
/// A module's or interface's parameters, ports and modports.
fn instantiable(
analysis: &Analysis,
found: &Found,
name: &str,
head: String,
file: &str,
) -> Result<Answer, String> {
) -> Result<Vec<String>, String> {
let plan = instantiation_plan(name, &analysis.text, None)?;
let scope = unit_symbol(&analysis.semantics, found, name).and_then(|s| s.child_scope);
let ports = port_rows(&plan, analysis, scope);
let modports = match (found.def.kind, scope) {
(SymbolKind::Interface, Some(scope)) => modports_of(analysis, scope),
_ => Vec::new(),
};
let template = plan.render(&Layout::default());
let text = interface_text(head, &plan, &ports, &modports, &template);
let structured = json!({
"name": name,
"kind": render::kind(found.def.kind),
"file": file,
"line": found.def.lines.name,
"parameters": plan.params.iter().map(|p| json!({ "name": p.name, "default": p.default })).collect::<Vec<_>>(),
"ports": ports.iter().map(PortRow::to_json).collect::<Vec<_>>(),
"modports": modports,
"template": template,
"warnings": plan.warnings,
});
Ok(Answer { text, structured })
let mut lines = vec![head];
lines.extend(plan.params.iter().map(|p| match p.default.trim() {
"" => format!("param {}", p.name),
default => format!("param {} = {}", p.name, render::one_line(default)),
}));
lines.extend(port_lines(&plan, analysis, scope));
if let (SymbolKind::Interface, Some(scope)) = (found.def.kind, scope) {
lines.extend(modports_of(analysis, scope));
}
render::warnings(&mut lines, &plan.warnings);
Ok(lines)
}
/// An interface's modports, each as its declaration reads on one line.
/// An interface's modports, each as its declaration reads on one line,
/// led by the keyword.
fn modports_of(analysis: &Analysis, scope: ScopeId) -> Vec<String> {
analysis
.semantics
@@ -156,56 +109,13 @@ fn modports_of(analysis: &Analysis, scope: ScopeId) -> Vec<String> {
.iter()
.filter(|s| s.scope == scope && s.kind == SymbolKind::Modport)
.map(|s| render::one_line(analysis.slice(s.decl_span.start, s.decl_span.end)))
.map(|written| match written.starts_with("modport") {
true => written,
false => format!("modport {written}"),
})
.collect()
}
/// The text answer: the head line, then each non-empty section.
fn interface_text(
mut text: String,
plan: &InstantiationPlan,
ports: &[PortRow],
modports: &[String],
template: &str,
) -> String {
if !plan.params.is_empty() {
text.push_str("parameters:\n");
let rows: Vec<Vec<String>> =
plan.params.iter().map(|p| vec![p.name.clone(), default_cell(&p.default)]).collect();
text.push_str(&render::table(&rows));
}
if !ports.is_empty() {
text.push_str("ports:\n");
let rows: Vec<Vec<String>> = ports
.iter()
.map(|p| vec![p.dir.clone(), p.written_type(), p.name_with_unpacked()])
.collect();
text.push_str(&render::table(&rows));
}
if !modports.is_empty() {
text.push_str("modports:\n");
for modport in modports {
text.push_str(&format!(" {modport}\n"));
}
}
for warning in &plan.warnings {
text.push_str(&format!("warning: {warning}\n"));
}
text.push_str("template:\n");
text.push_str(template);
if !template.ends_with('\n') {
text.push('\n');
}
text
}
fn default_cell(default: &str) -> String {
if default.is_empty() {
"(no default)".to_string()
} else {
format!("= {}", render::one_line(default))
}
}
/// The unit's own symbol in the file's analysis: the declaration at the
/// indexed name, else the first of its kind spelling the name.
fn unit_symbol<'s>(semantics: &'s Semantics, found: &Found, name: &str) -> Option<&'s Symbol> {
@@ -222,59 +132,21 @@ fn unit_symbol<'s>(semantics: &'s Semantics, found: &Found, name: &str) -> Optio
)
}
/// One port as the answer shows it.
struct PortRow {
dir: String,
ty: String,
range: String,
name: String,
unpacked: String,
}
impl PortRow {
/// The type as the declaration writes it, packed range included — one
/// column, so a long type name widens one column rather than two.
fn written_type(&self) -> String {
match (self.ty.is_empty(), self.range.is_empty()) {
(_, true) => self.ty.clone(),
(true, false) => self.range.clone(),
(false, false) => format!("{} {}", self.ty, self.range),
}
}
fn name_with_unpacked(&self) -> String {
if self.unpacked.is_empty() {
self.name.clone()
} else {
format!("{} {}", self.name, self.unpacked)
}
}
fn to_json(&self) -> Value {
json!({
"direction": self.dir, "type": self.ty, "range": self.range,
"name": self.name, "unpacked": self.unpacked,
})
}
}
/// The plan's ports with the packed range split off the type, and the
/// unpacked dimensions an ANSI port writes after its name.
fn port_rows(
/// Each port as `dir type [range] name [unpacked]`, the empty parts left
/// out.
fn port_lines(
plan: &InstantiationPlan,
analysis: &Analysis,
scope: Option<ScopeId>,
) -> Vec<PortRow> {
) -> Vec<String> {
plan.ports
.iter()
.map(|port| {
let (ty, range) = match port.ty.find('[') {
Some(at) => (port.ty[..at].trim().to_string(), port.ty[at..].trim().to_string()),
None => (port.ty.clone(), String::new()),
};
let unpacked =
scope.map_or(String::new(), |scope| unpacked(analysis, scope, &port.name));
PortRow { dir: port.dir.clone(), ty, range, name: port.name.clone(), unpacked }
let parts = [port.dir.as_str(), port.ty.trim(), port.name.as_str(), unpacked.as_str()];
let parts: Vec<&str> = parts.into_iter().filter(|part| !part.is_empty()).collect();
render::one_line(&parts.join(" "))
})
.collect()
}
@@ -308,20 +180,19 @@ fn unpacked(analysis: &Analysis, scope: ScopeId, name: &str) -> String {
out
}
/// A package's or class's members, in declaration order, and a class's
/// base. `name` is the unit's own name, without a package prefix — which
/// two classes in two packages may share, so both answers are read off this
/// declaration: a member counts only when it is declared inside
/// `found.def.decl_span`, and the base is what this declaration's own
/// `extends` writes.
/// A package's or class's members, in declaration order, as `kind name
/// LINE`, and a class's base. `name` is the unit's own name, without a
/// package prefix — which two classes in two packages may share, so both
/// answers are read off this declaration: a member counts only when it is
/// declared inside `found.def.decl_span`, and the base is what this
/// declaration's own `extends` writes.
fn members(
project: &Project,
analysis: &Analysis,
found: &Found,
name: &str,
mut text: String,
file: &str,
) -> Answer {
head: String,
) -> Vec<String> {
let index = project.index();
let within = found.def.decl_span;
let mut rows: Vec<(u32, &'static str, String)> = index
@@ -336,25 +207,12 @@ fn members(
})
.collect();
rows.sort();
let base = class_base(&analysis.tree.items, found.def.name_span);
if let Some(base) = &base {
text.push_str(&format!("extends {base}\n"));
let mut lines = vec![head];
if let Some(base) = class_base(&analysis.tree.items, found.def.name_span) {
lines.push(format!("extends {base}"));
}
text.push_str("members:\n");
let table: Vec<Vec<String>> = rows
.iter()
.map(|(line, kind, member)| vec![kind.to_string(), member.clone(), line.to_string()])
.collect();
text.push_str(&render::table(&table));
let structured = json!({
"name": name,
"kind": render::kind(found.def.kind),
"file": file,
"line": found.def.lines.name,
"extends": base,
"members": rows.iter().map(|(line, kind, member)| json!({ "name": member, "kind": kind, "line": line })).collect::<Vec<_>>(),
});
Answer { text, structured }
lines.extend(rows.iter().map(|(line, kind, member)| format!("{kind} {member} {line}")));
lines
}
/// The base the class declared at `name_span` names in its `extends`, read
+375
View File
@@ -0,0 +1,375 @@
//! `edit_item` — the structural edits under one name (`replace`,
//! `insert_before`, `insert_after`, `delete`), the general token saver: an
//! agent sends one item's text, never the file.
//!
//! Each op finds its place with the slicer `read` uses
//! ([`read_item::select`]), so the bytes it replaces are exactly the bytes
//! `read` showed; builds a [`Splice`]; hands it to [`verify::check`] (the
//! rules are there); and writes through `apply::run`, the one write path
//! (freshness, atomic write). Contract and rules:
//! `docs/features/mcp-structural-edits/README.md`; the lean surface:
//! `docs/features/mcp-lean-catalogue/README.md`.
mod lexical;
mod macros;
mod refs;
mod span;
mod star;
mod verify;
use std::path::PathBuf;
use std::rc::Rc;
use vlog_formatter::fence;
use vlog_parser::ast::{Item, ItemKind};
use vlog_parser::span::TextRange;
use super::read_item::{child_items, select};
use super::{Answer, Args, Param, Tool, Ty};
use crate::apply::{self, Change, Plan};
use crate::project::{Analysis, Project};
use crate::render;
use span::{
alone_before, blank_line_at, blank_line_before, line_start, own_lines, past_doubled_blank,
replace_region, SHARED_LINE,
};
use verify::{Expect, Splice};
pub const EDIT_ITEM: Tool = Tool {
name: "edit_item",
description: "One item of `file` (selector as read): `op` replace it by `text` (same kind and names), insert `text` before/after it (item `end`/`end@UNIT`: a unit's end), or delete it if unused.",
params: &[
Param { name: "file", ty: Ty::Str, required: true },
Param {
name: "op",
ty: Ty::Enum(&["replace", "insert_before", "insert_after", "delete"]),
required: true,
},
Param { name: "item", ty: Ty::Str, required: true },
Param { name: "text", ty: Ty::Str, required: false },
],
rewalk: true,
handler: edit_item,
};
fn edit_item(project: &mut Project, args: &Args) -> Result<Answer, String> {
let op = args.str("op").unwrap_or_default();
let text = args.str("text");
match (op, text) {
("delete", None) => delete_item(project, args),
("delete", Some(_)) => Err("`delete` takes no `text`; nothing written.".into()),
(_, None) => Err(format!("`{op}` needs `text`; nothing written.")),
("replace", Some(text)) => replace_item(project, args, text),
(_, Some(text)) => insert_item(project, args, text, op == "insert_before"),
}
}
/// The file a call names: its path, its root-relative name and analysis.
/// A file that does not lex is refused here: no span in it can be trusted.
fn open(project: &mut Project, args: &Args) -> Result<(PathBuf, String, Rc<Analysis>), String> {
let path = project.resolve(args.str("file").unwrap_or(""))?;
let file = project.relative(&path);
let analysis = project.analysis(&path)?;
if analysis.tokens.is_empty() {
return Err(format!(
"`{file}` does not lex (an unterminated string or comment?); fix that first; nothing written."
));
}
Ok((path, file, analysis))
}
/// One item node and where it sits: its sibling list and its index there.
struct Located<'a> {
item: &'a Item,
siblings: &'a [Item],
index: usize,
}
/// The item node `selector` names. A declaration that is part of a larger
/// item (an ANSI port, a function argument) is refused: these tools edit
/// whole items.
fn target<'a>(analysis: &'a Analysis, selector: &str, file: &str) -> Result<Located<'a>, String> {
let (_, span) =
select(analysis, selector).map_err(|why| format!("{why} in `{file}`; nothing written."))?;
locate(&analysis.tree.items, span).ok_or_else(|| {
format!(
"`{selector}` is part of a larger item (a port in a module header, an argument, a generate branch), not an item of its own; edit the enclosing item (`port` for ports); nothing written."
)
})
}
/// The item whose span is exactly `span`, searched through nested scopes.
fn locate(items: &[Item], span: TextRange) -> Option<Located<'_>> {
for (index, item) in items.iter().enumerate() {
if item.span == span {
return Some(Located { item, siblings: items, index });
}
if item.span.start <= span.start && span.end <= item.span.end {
return child_items(&item.kind).into_iter().find_map(|list| locate(list, span));
}
}
None
}
/// A refusal from the verifier, said for this file.
fn refused(file: &str) -> impl Fn(String) -> String + '_ {
move |why| format!("{why} (in `{file}`); nothing written.")
}
/// Whether any byte of `start..end` (an insertion when empty) is fenced.
fn fenced(text: &str, start: u32, end: u32) -> bool {
let regions = fence::protected_regions(text);
fence::is_protected(&regions, start as usize, end as usize)
}
const FENCED: &str = "lies inside a `// lucisv: off` fence, which no lucisv tool edits";
fn replace_item(project: &mut Project, args: &Args, text: &str) -> Result<Answer, String> {
let (path, file, analysis) = open(project, args)?;
let selector = args.str("item").unwrap_or("").trim();
let located = target(&analysis, selector, &file)?;
let span = located.item.span;
let text = normalise(text, &analysis.text, false)?;
let (start, end) = replace_region(&analysis.text, located.item, &text);
let class = verify::class_of(&located.item.kind);
// The item as it already is: a no-op, not a refusal (even in a fence).
if text == analysis.slice(start, end) {
let (first, last) = analysis.line_span(span.start, span.end);
let names = verify::owned_names(&analysis, span);
return Ok(said("unchanged", class, &names, &file, (first, last), Vec::new()));
}
if fenced(&analysis.text, start, end) {
return Err(format!("`{selector}` {FENCED}; nothing written."));
}
let splice = Splice { start, old_end: end, text };
let outcome = verify::check(&analysis, &splice, Expect::One(class)).map_err(refused(&file))?;
let new_span = outcome.items.first().map_or(span, |(_, span)| *span);
let was = verify::owned_names(&analysis, span);
let now = verify::owned_names(&outcome.analysis, new_span);
name_rule(&was, &now)?;
let lines = outcome.analysis.line_span(new_span.start, new_span.end);
apply::run(project, &plan(path, &analysis, outcome.text, Vec::new()))?;
Ok(said("replaced", class, &now, &file, lines, Vec::new()))
}
/// The text declares the names the item did: a replacement that renames
/// would leave every reference behind (`rename` renames with references).
fn name_rule(was: &[String], now: &[String]) -> Result<(), String> {
if was == now {
return Ok(());
}
Err(format!(
"the text declares {} where the item declared {}; `rename` renames a declaration with its references; nothing written.",
listed(now),
listed(was)
))
}
fn insert_item(
project: &mut Project,
args: &Args,
text: &str,
before: bool,
) -> Result<Answer, String> {
let (path, file, analysis) = open(project, args)?;
let anchor = args.str("item").unwrap_or("").trim();
let text = normalise(text, &analysis.text, true)?;
let spot = match anchor.strip_prefix("end") {
Some(rest) if rest.is_empty() || rest.starts_with('@') => {
end_spot(&analysis, rest.trim_start_matches('@'), &file)?
}
_ => anchor_spot(&analysis, anchor, before, &file)?,
};
let block = spot.block(&analysis.text, &text);
let splice = Splice { start: spot.at, old_end: spot.at, text: block };
// The verifier first, so a text that cannot stand anywhere is refused
// as such; then the place.
let outcome = verify::check(&analysis, &splice, Expect::Some).map_err(refused(&file))?;
if fenced(&analysis.text, spot.at, spot.at) {
return Err(format!("the insertion point {FENCED}; nothing written."));
}
let (first, last) = match (outcome.items.first(), outcome.items.last()) {
(Some((_, first)), Some((_, last))) => (*first, *last),
_ => return Err(format!("the text holds no item (in `{file}`); nothing written.")),
};
let lines = outcome.analysis.line_span(first.start, last.end);
let classes: Vec<&str> = outcome.items.iter().map(|(class, _)| *class).collect();
let names: Vec<String> = outcome
.items
.iter()
.flat_map(|(_, span)| verify::owned_names(&outcome.analysis, *span))
.collect();
apply::run(project, &plan(path, &analysis, outcome.text, Vec::new()))?;
Ok(said("inserted", &classes.join(", "), &names, &file, lines, Vec::new()))
}
fn delete_item(project: &mut Project, args: &Args) -> Result<Answer, String> {
let (path, file, analysis) = open(project, args)?;
let selector = args.str("item").unwrap_or("").trim();
let located = target(&analysis, selector, &file)?;
let (start, end) = own_lines(&analysis.text, located.item)
.map_err(|why| format!("`{selector}` {why}; nothing written."))?;
let end = past_doubled_blank(&analysis.text, start, end);
if fenced(&analysis.text, start, end) || fence_comment(located.item) {
return Err(format!("`{selector}` {FENCED}; nothing written."));
}
let removed = TextRange::new(start, end);
let place = refs::Place { item: located.item.span, removed, scope: located.siblings };
let warnings = refs::check(project, &path, &analysis, &place)?;
let class = verify::class_of(&located.item.kind);
let splice = Splice { start, old_end: end, text: String::new() };
let outcome = verify::check(&analysis, &splice, Expect::Nothing).map_err(refused(&file))?;
let names = verify::owned_names(&analysis, located.item.span);
let lines = analysis.line_span(start, end);
apply::run(project, &plan(path, &analysis, outcome.text, Vec::new()))?;
Ok(said("deleted", class, &names, &file, lines, warnings))
}
/// `replaced function f file:12–20`, then any warning lines.
fn said(
verb: &str,
class: &str,
names: &[String],
file: &str,
(first, last): (u32, u32),
warnings: Vec<String>,
) -> Answer {
let named = if names.is_empty() { String::new() } else { format!(" {}", names.join(", ")) };
let mut lines = vec![format!("{verb} {class}{named} {file}:{}", render::lines(first, last))];
render::warnings(&mut lines, &warnings);
Answer::lines(lines)
}
/// Whether the item's own leading comments hold a fence line: deleting one
/// would move a fence's edge.
fn fence_comment(item: &Item) -> bool {
item.meta.leading.iter().any(|comment| fence::fence_of(&comment.text).is_some())
}
/// The one-file plan: the analysed text before, the verified text after.
fn plan(path: PathBuf, analysis: &Analysis, after: String, warnings: Vec<String>) -> Plan {
let change = Change { path, before: analysis.text.clone(), after, created: false };
Plan { changes: vec![change], warnings }
}
/// `` `a`, `b` `` for a list of names; `nothing` when empty.
fn listed(names: &[String]) -> String {
if names.is_empty() {
return "nothing".to_string();
}
names.iter().map(|name| format!("`{name}`")).collect::<Vec<_>>().join(", ")
}
/// `text` made ready to splice: surrounding blank space dropped (for an
/// insertion, the first line's indentation is kept), line endings made the
/// file's. Empty text is refused: deleting is `op: delete`'s.
fn normalise(text: &str, file_text: &str, keep_indent: bool) -> Result<String, String> {
let trimmed = text.trim_end_matches(|c: char| c.is_ascii_whitespace());
let trimmed = if keep_indent {
let first_code = trimmed.find(|c: char| !c.is_ascii_whitespace()).unwrap_or(0);
&trimmed[line_start(trimmed, first_code as u32) as usize..]
} else {
trimmed.trim_start_matches(|c: char| c.is_ascii_whitespace())
};
if trimmed.is_empty() {
return Err("`text` is empty; `op: delete` removes an item; nothing written.".into());
}
let lf = trimmed.replace("\r\n", "\n");
Ok(if line_ending(file_text) == "\r\n" { lf.replace('\n', "\r\n") } else { lf })
}
/// The file's line ending, judged by its first line.
fn line_ending(text: &str) -> &'static str {
match text.find('\n') {
Some(at) if text[..at].ends_with('\r') => "\r\n",
_ => "\n",
}
}
/// Where an insertion lands: a line start, and whether an item neighbours
/// it above and below (the blank-line policy).
struct Spot {
at: u32,
above: bool,
below: bool,
}
impl Spot {
/// `text` framed for this spot: a line break when the file's last line
/// has none, a blank line on each side that has a neighbouring item
/// unless one is already there, and the text's own line ending.
fn block(&self, file_text: &str, text: &str) -> String {
let nl = line_ending(file_text);
let mut block = String::new();
if self.at as usize == file_text.len()
&& !file_text.is_empty()
&& !file_text.ends_with('\n')
{
block.push_str(nl);
}
if self.above && !blank_line_before(file_text, self.at) {
block.push_str(nl);
}
block.push_str(text);
block.push_str(nl);
if self.below && !blank_line_at(file_text, self.at) {
block.push_str(nl);
}
block
}
}
/// Before the anchor item (and its leading comments) or after it (and its
/// trailing comment).
fn anchor_spot(
analysis: &Analysis,
selector: &str,
before: bool,
file: &str,
) -> Result<Spot, String> {
let located = target(analysis, selector, file)?;
let (first, last) = own_lines(&analysis.text, located.item)
.map_err(|why| format!("`{selector}` {why}; nothing written."))?;
Ok(if before {
Spot { at: first, above: located.index > 0, below: true }
} else {
let below = located.index + 1 < located.siblings.len();
Spot { at: last, above: true, below }
})
}
/// The line of a unit's end keyword: `unit` is empty for the file's last
/// unit, else a selector naming a module, interface, program, package or
/// class.
fn end_spot(analysis: &Analysis, unit: &str, file: &str) -> Result<Spot, String> {
let is_unit = |item: &Item| {
matches!(item.kind, ItemKind::Module(_) | ItemKind::Package { .. } | ItemKind::Class(_))
};
let item = if unit.is_empty() {
let last = analysis.tree.items.iter().rev().find(|item| is_unit(item));
last.ok_or_else(|| {
format!("`{file}` declares no module, package or class; nothing written.")
})?
} else {
let located = target(analysis, unit, file)?;
if !is_unit(located.item) {
return Err(format!("`{unit}` is not a module, package or class; nothing written."));
}
located.item
};
let keyword = analysis
.tokens
.iter()
.filter(|t| item.span.start <= t.span.start && t.span.end <= item.span.end)
.rfind(|t| END_WORDS.contains(&t.text.as_str()))
.ok_or_else(|| format!("the unit has no end keyword in `{file}`; nothing written."))?;
if !alone_before(&analysis.text, keyword.span.start) {
return Err(format!("`{}` {SHARED_LINE}; nothing written.", keyword.text));
}
let children = child_items(&item.kind);
let above = children.iter().any(|list| !list.is_empty());
Ok(Spot { at: line_start(&analysis.text, keyword.span.start), above, below: false })
}
/// The keywords that close a unit `end` may name.
const END_WORDS: &[&str] = &["endmodule", "endinterface", "endprogram", "endpackage", "endclass"];
+175
View File
@@ -0,0 +1,175 @@
//! The verifier's lexical rules — what a splice may do to the token stream
//! and its comments, before any parse is asked:
//!
//! - **1a.** `text` lexes on its own. A text ending in an open `/*`, string
//! or macro call lexes inside the file only by running into the code after
//! it — a `*/` further down closes it and the fence between is swallowed.
//! - **1b.** Outside the region nothing lexes differently: every token and
//! every comment before the region, and every one after it (shifted by
//! the length change), is the old file's — same kind, text and span. No
//! token or comment starts inside the region and ends past it, and no
//! comment the new bytes write is attached (`Token.leading`/`trailing`)
//! to a token outside them: a comment the text leaves on a line of its
//! own at its end would lead the next item, not this one.
//! - **7.** The region holds the same `lucisv: off`/`on` fence markers
//! before and after: a text neither opens nor closes a fence.
use vlog_formatter::fence;
use vlog_parser::token::{Comment, Token, TokenKind};
use crate::project::Analysis;
/// A splice's region in both files: `start..old_end` in the old one,
/// `start..new_end` in the new one.
#[derive(Clone, Copy)]
pub struct Region {
pub start: u32,
pub old_end: u32,
pub new_end: u32,
}
/// One lexical element of a file: a token or a comment.
#[derive(Clone, Copy, PartialEq, Eq)]
struct Element<'a> {
kind: Option<TokenKind>,
text: &'a str,
start: u32,
end: u32,
}
impl Element<'_> {
fn describe(&self, analysis: &Analysis) -> String {
let line = analysis.lines.line_col(self.start).0;
let text: String = self.text.chars().take(24).collect();
let what = if self.kind.is_some() { "token" } else { "comment" };
format!("the {what} `{text}` at line {line}")
}
}
fn comment(c: &Comment) -> Element<'_> {
Element { kind: None, text: &c.text, start: c.span.start, end: c.span.end }
}
/// Every token and comment of a stream, in source order.
fn elements(tokens: &[Token]) -> Vec<Element<'_>> {
let mut out = Vec::with_capacity(tokens.len() + tokens.len() / 4);
for token in tokens {
out.extend(token.leading.iter().map(comment));
let (start, end) = (token.span.start, token.span.end);
out.push(Element { kind: Some(token.kind), text: &token.text, start, end });
out.extend(token.trailing.iter().map(comment));
}
out
}
/// The elements before `start` and after `end` (shifted by `shift`); an
/// element that starts inside and ends past `end` is returned as `Err`.
fn sides<'a>(
all: &[Element<'a>],
start: u32,
end: u32,
shift: i64,
) -> Result<(Vec<Element<'a>>, Vec<Element<'a>>), Element<'a>> {
let moved = |at: u32| u32::try_from(i64::from(at) + shift).unwrap_or(u32::MAX);
let (mut before, mut after) = (Vec::new(), Vec::new());
for element in all {
if element.start < start {
before.push(*element);
} else if element.start >= end {
after.push(Element {
start: moved(element.start),
end: moved(element.end),
..*element
});
} else if element.end > end {
return Err(*element);
}
}
Ok((before, after))
}
/// Rule 1a: `text` lexes on its own.
pub fn lexes_alone(text: &str) -> Result<(), String> {
vlog_parser::tokenize(text).map(|_| ()).map_err(|e| {
format!(
"the text does not lex on its own (rule 1a: {}); a comment, string or macro call it leaves open would run into the code after it",
e.message
)
})
}
/// Rule 1b: the tokens and comments outside `start..old_end` (old) and
/// `start..new_end` (new) are the same, shifted; nothing straddles the new
/// region's end; no comment inside it is attached to a token outside it.
pub fn same_outside(old: &Analysis, new: &Analysis, region: Region) -> Result<(), String> {
let Region { start, old_end, new_end } = region;
let shift = i64::from(new_end) - i64::from(old_end);
let (was, now) = (elements(&old.tokens), elements(&new.tokens));
let changed = |element: &Element| {
format!("the edit would change how the code outside the item lexes (rule 1b: {} would not survive as it is)", element.describe(old))
};
let (was_before, was_after) = sides(&was, start, old_end, shift).map_err(|e| changed(&e))?;
let (now_before, now_after) = sides(&now, start, new_end, 0).map_err(|element| {
format!(
"{} would run past the text's end into the code after it (rule 1b)",
element.describe(new)
)
})?;
for (was, now) in [(&was_before, &now_before), (&was_after, &now_after)] {
if was != now {
let at = was.iter().zip(now.iter()).position(|(a, b)| a != b).unwrap_or(was.len());
let element = was.get(at).or(was.last()).or(now.get(at));
return Err(element.map_or_else(
|| {
"the edit would change how the code outside the item lexes (rule 1b)"
.to_string()
},
changed,
));
}
}
attached_inside(new, start, new_end)
}
/// Rule 1b's last clause: a comment the new bytes hold belongs to a token
/// they hold.
fn attached_inside(new: &Analysis, start: u32, end: u32) -> Result<(), String> {
let inside = |at: u32| start <= at && at < end;
for token in new.tokens.iter().filter(|token| !inside(token.span.start)) {
let stray = token.leading.iter().chain(&token.trailing).find(|c| inside(c.span.start));
if let Some(comment) = stray {
let line = new.lines.line_col(comment.span.start).0;
return Err(format!(
"the comment at line {line} of the text would belong to the code after it, not to the item (rule 1b); put the comment before the item or on its last line"
));
}
}
Ok(())
}
/// Rule 7: the fence markers inside the region are the same before and
/// after.
pub fn same_fences(old: &Analysis, new: &Analysis, region: Region) -> Result<(), String> {
let Region { start, old_end, new_end } = region;
let (was, now) = (markers(&old.tokens, start, old_end), markers(&new.tokens, start, new_end));
if was == now {
return Ok(());
}
let (verb, longer, shorter) =
if now.len() >= was.len() { ("add", &now, &was) } else { ("remove", &was, &now) };
let at = longer.iter().zip(shorter.iter()).position(|(a, b)| a != b).unwrap_or(shorter.len());
let marker = longer.get(at).copied().unwrap_or("// lucisv: off");
Err(format!(
"the edit would {verb} the fence marker `{marker}` (rule 7); `lucisv: off`/`on` fences are written by hand, not through these tools"
))
}
/// The fence-marker comments starting in `start..end`, in order.
fn markers(tokens: &[Token], start: u32, end: u32) -> Vec<&str> {
elements(tokens)
.into_iter()
.filter(|e| e.kind.is_none() && start <= e.start && e.start < end)
.filter(|e| fence::fence_of(e.text).is_some())
.map(|e| e.text.trim())
.collect()
}
+108
View File
@@ -0,0 +1,108 @@
//! `op: delete`'s macro rule: a name spelled inside a macro call's
//! arguments (`` `ASSERT_KNOWN(k, sig) ``) or a `` `define`` body is a use
//! no lucisv engine resolves — the lexer keeps a macro call as one token and
//! a `` `define`` as one directive. Each such spelling the engine and the
//! file's own tables did not account for is a *possible* use.
use vlog_parser::defines::{collect_defines, DefineKind};
use vlog_parser::span::TextRange;
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::tokenize;
use crate::tools::source::word_in;
/// Where `name` is spelled inside a macro call's arguments or a
/// `` `define`` body in `tokens`, outside `skip`: the byte offset of each
/// spelling (a `` `define``'s own start for a body).
pub fn macro_spellings(tokens: &[Token], name: &str, skip: TextRange) -> Vec<u32> {
let outside = |span: TextRange| span.end <= skip.start || span.start >= skip.end;
let mut out = Vec::new();
for token in tokens.iter().filter(|token| outside(token.span)) {
match token.kind {
TokenKind::Ident if token.text.starts_with('`') => {
call_arguments(&token.text, token.span.start, name, &mut out);
}
TokenKind::Directive if defines_with_body_spelling(token, name) => {
out.push(token.span.start);
}
_ => {}
}
}
out
}
/// The spellings of `name` in one macro call's arguments (`text` starts at
/// byte `at`), nested calls included. Arguments that do not lex are
/// searched as bytes.
fn call_arguments(text: &str, at: u32, name: &str, out: &mut Vec<u32>) {
let Some(open) = text.find('(') else {
return;
};
let args = &text[open..];
let base = at + open as u32;
match tokenize(args) {
Ok(tokens) => {
for token in tokens.iter().filter(|t| t.kind == TokenKind::Ident) {
let start = base + token.span.start;
if token.text == name {
out.push(start);
} else if token.text.starts_with('`') {
call_arguments(&token.text, start, name, out);
}
}
}
Err(_) => out.extend(word_in(args, name).map(|offset| base + offset as u32)),
}
}
/// Whether a `` `define`` directive's body spells `name` as an identifier
/// that is not one of its own formal arguments.
fn defines_with_body_spelling(token: &Token, name: &str) -> bool {
let table = collect_defines(std::slice::from_ref(token));
table.entries().iter().any(|define| {
let formal = define
.params
.iter()
.flatten()
.any(|param| param.split('=').next().is_some_and(|formal| formal.trim() == name));
define.kind == DefineKind::Define && !formal && body_spells(&define.body, name)
})
}
/// Whether a macro body spells `name` as an identifier, nested calls
/// included (searched as bytes when the body does not lex on its own —
/// token pasting, escaped quotes).
fn body_spells(body: &str, name: &str) -> bool {
let Ok(tokens) = tokenize(body) else {
return word_in(body, name).is_some();
};
let mut found = Vec::new();
for token in tokens.iter().filter(|t| t.kind == TokenKind::Ident) {
if token.text == name {
return true;
}
if token.text.starts_with('`') {
call_arguments(&token.text, 0, name, &mut found);
}
}
!found.is_empty()
}
#[cfg(test)]
mod tests {
use super::*;
fn spellings(src: &str, name: &str) -> Vec<u32> {
let tokens = tokenize(src).unwrap();
macro_spellings(&tokens, name, TextRange::new(0, 0))
}
#[test]
fn a_name_in_a_macro_call_or_a_define_body_is_found() {
let src = "`define B(x) x + sig\nassign o = `ID(`W(sig));\n";
assert_eq!(spellings(src, "sig"), [0, src.find("sig)").unwrap() as u32]);
assert!(spellings(src, "x").is_empty(), "a formal argument is not a use");
assert!(spellings("assign o = `ID(a) + sig;\n", "sig").is_empty());
assert!(spellings("`define S \"sig\"\n", "sig").is_empty(), "a string is not a use");
}
}
+262
View File
@@ -0,0 +1,262 @@
//! `edit_item op: delete`'s reference rule: an item is not deleted while a
//! name it owns (`verify::owned`) is still used anywhere in the project.
//!
//! Uses are `vlog_refactor::find_references` over the whole indexed set,
//! read from disk now (`WholeSet`, M2's ruling) — the census `references`
//! answers with — plus what that engine cannot see:
//!
//! - a `.*` in the item's scope that binds the name ([`star`]) — it binds
//! without spelling it, so this runs for every name;
//! - a spelling inside a macro call's arguments or a `` `define`` body
//! ([`macros`]), a *possible* use;
//! - in the item's own file, a use the file's tables resolve to the
//! declaration or to nothing ([`local_uses`]).
//!
//! Apart from `.*`, a name no file spells outside the removed lines has no
//! use to find, so the rest runs only for names some other text spells (a
//! whole-word byte search): an identifier, escaped or not, is always
//! written out where it is used.
use std::path::{Path, PathBuf};
use vlog_parser::ast::Item;
use vlog_parser::span::TextRange;
use vlog_parser::LineIndex;
use vlog_semantic::Symbol;
use super::macros::macro_spellings;
use super::star::star_uses;
use super::verify;
use crate::project::{Analysis, Project};
use crate::tools::source::{word_in, WholeSet};
/// How many surviving uses a refusal lists.
const SHOWN: usize = 5;
/// The uses and doubts found, the first few spelled out.
#[derive(Default)]
struct Census {
shown: Vec<String>,
total: usize,
}
impl Census {
fn add(&mut self, line: impl FnOnce() -> String) {
if self.shown.len() < SHOWN {
self.shown.push(line());
}
self.total += 1;
}
fn render(&self) -> String {
let more = self.total - self.shown.len();
let tail = if more > 0 { format!("; and {more} more") } else { String::new() };
format!("{}{tail}", self.shown.join("; "))
}
}
/// Where a deletion sits: the item's span, the bytes the deletion takes
/// (its comments included), and the item list it is taken from.
pub struct Place<'a> {
pub item: TextRange,
pub removed: TextRange,
pub scope: &'a [Item],
}
/// The warnings a deletion carries, or the refusal.
pub fn check(
project: &Project,
path: &Path,
analysis: &Analysis,
place: &Place,
) -> Result<Vec<String>, String> {
let symbols = verify::owned(analysis, place.item);
if symbols.is_empty() {
return Ok(Vec::new());
}
let set = WholeSet::read(project, Some(path));
let own = set.files.iter().find(|(held, _)| held == path).map(|(_, text)| text.as_str());
if own != Some(analysis.text.as_str()) {
let file = project.relative(path);
return Err(format!("`{file}` changed on disk while it was read; nothing written."));
}
let names: Vec<String> = symbols.iter().map(|symbol| symbol.name.clone()).collect();
let mut census = Census::default();
if let Some((skipped, why, name)) = set.mentioning(&names) {
let file = project.relative(skipped);
census.add(|| format!("{file} (skipped: {why}) may reference `{name}`"));
}
let scan = Scan { project, set: &set, path, analysis, place };
for symbol in symbols {
scan.uses_of(symbol, &mut census);
}
if census.total > 0 {
return Err(format!("still referenced: {}; nothing written.", census.render()));
}
Ok(set.warning(project).into_iter().collect())
}
/// What one deletion's reference scan reads.
struct Scan<'a> {
project: &'a Project,
set: &'a WholeSet,
path: &'a Path,
analysis: &'a Analysis,
place: &'a Place<'a>,
}
/// The spans some rule already counted (or knows to be another name's), per
/// file: a macro spelling at one of them is not counted twice.
type Accounted = Vec<(PathBuf, TextRange)>;
impl Scan<'_> {
/// Count the uses of one owned declaration that the deletion would leave.
fn uses_of(&self, symbol: &Symbol, census: &mut Census) {
let (name, removed) = (&symbol.name, self.place.removed);
if !within(symbol.name_span, removed) {
let line = self.analysis.lines.line_col(symbol.name_span.start).0;
census.add(|| {
format!("`{name}` is also declared on line {line}, which the deletion would leave incomplete")
});
return;
}
self.stars(name, census);
if !mentioned(self.set, self.path, removed, name) {
return;
}
let accounted = self.references(symbol, census);
self.macros(name, &accounted, census);
}
/// The engine's and the file's own uses, counted; what they account for.
fn references(&self, symbol: &Symbol, census: &mut Census) -> Accounted {
let (name, removed) = (&symbol.name, self.place.removed);
let mut uses = local_uses(self.analysis, symbol, removed);
let mut accounted: Accounted = self
.analysis
.semantics
.references()
.iter()
.filter(|use_| use_.name == *name)
.map(|use_| (self.path.to_path_buf(), use_.name_span))
.collect();
let found = vlog_refactor::find_references(
&self.set.files,
self.path,
symbol.name_span.start,
false,
);
match found {
Ok(hits) => {
for (file, span) in hits {
if file != self.path {
census.add(|| site(self.project, self.set, &file, span, name));
} else if !within(span, removed) && !uses.contains(&span) {
uses.push(span);
}
accounted.push((file, span));
}
}
Err(why) => census.add(|| {
format!("the uses of `{name}` cannot all be listed ({})", why.trim_end_matches('.'))
}),
}
uses.sort_by_key(|span| span.start);
for span in uses {
census.add(|| site(self.project, self.set, self.path, span, name));
}
accounted
}
/// Rule `.*`: the implicit connections in the item's scope that bind
/// (or may bind) `name`.
fn stars(&self, name: &str, census: &mut Census) {
let index = self.project.index();
for star in star_uses(index, self.place.scope, self.place.removed, name) {
let at = position(self.project, self.set, self.path, star.at);
census.add(|| match star.certain {
true => format!("bound by `.*` at {at} `{name}` (module `{}`)", star.module),
false => format!(
"possible use (`.*`) at {at} `{name}` (module `{}` does not resolve to one declaration)",
star.module
),
});
}
}
/// Rule macros: every spelling of `name` inside a macro call or a
/// `` `define`` body, in any file of the set, that nothing accounted for.
fn macros(&self, name: &str, accounted: &Accounted, census: &mut Census) {
for (file, text) in &self.set.files {
if word_in(text, name).is_none() {
continue;
}
let (own, lexed);
let tokens = if file == self.path {
own = &self.analysis.tokens;
own
} else if let Ok(tokens) = vlog_parser::tokenize(text) {
lexed = tokens;
&lexed
} else {
let at = self.project.relative(file);
census.add(|| format!("possible use in {at} (it does not lex) `{name}`"));
continue;
};
let skip = if file == self.path { self.place.removed } else { TextRange::new(0, 0) };
let lines = LineIndex::new(text);
for offset in macro_spellings(tokens, name, skip) {
if !accounted.iter().any(|(held, span)| held == file && span.start == offset) {
let at =
format!("{}:{}", self.project.relative(file), lines.line_col(offset).0);
census.add(|| format!("possible use (macro) at {at} `{name}`"));
}
}
}
}
}
fn within(inner: TextRange, outer: TextRange) -> bool {
outer.start <= inner.start && inner.end <= outer.end
}
/// The uses of `symbol` the file's own tables hold outside the removed
/// bytes: resolved to it, or to nothing at all. The second kind is what the
/// cross-file engine does not follow (a hierarchical path into a generate
/// loop, `gen_l[0].z`); counting it may refuse a deletion that was safe,
/// never allow one that was not.
fn local_uses(analysis: &Analysis, symbol: &Symbol, removed: TextRange) -> Vec<TextRange> {
let semantics = &analysis.semantics;
let id = semantics.symbol_at(symbol.name_span.start);
semantics
.references()
.iter()
.filter(|use_| use_.name == symbol.name && !within(use_.name_span, removed))
.filter(|use_| use_.resolved().is_none() || use_.resolved() == id)
.map(|use_| use_.name_span)
.collect()
}
/// Whether any text of the set, the removed bytes aside, spells `name`.
fn mentioned(set: &WholeSet, path: &Path, removed: TextRange, name: &str) -> bool {
set.files.iter().any(|(held, text)| {
if held != path {
return word_in(text, name).is_some();
}
let head = text.get(..removed.start as usize).unwrap_or("");
let tail = text.get(removed.end as usize..).unwrap_or("");
word_in(head, name).is_some() || word_in(tail, name).is_some()
})
}
/// `file:line:col `name`` for one use.
fn site(project: &Project, set: &WholeSet, file: &Path, span: TextRange, name: &str) -> String {
format!("{} `{name}`", position(project, set, file, span))
}
/// `file:line:col` of a span's start.
fn position(project: &Project, set: &WholeSet, file: &Path, span: TextRange) -> String {
let text = set.files.iter().find(|(held, _)| held == file).map_or("", |(_, t)| t.as_str());
let (line, col) = LineIndex::new(text).line_col(span.start);
format!("{}:{line}:{col}", project.relative(file))
}
+157
View File
@@ -0,0 +1,157 @@
//! Which bytes an item owns: the lines `edit_item`'s inserts and deletes
//! work on, and the span its `replace` replaces when its text brings comments.
//!
//! Two rules, stated once here and in the README:
//!
//! - **Own comments.** An item's leading comments (`Meta::leading`) are its
//! own back to the first gap holding a blank line: a banner a blank line
//! separates from the item belongs to what follows it, not to this item.
//! - **Own lines.** An item owns its lines unless another item's *code*
//! sits on its first or last line; a comment on the same line goes with
//! the item (`/* lead */ logic a;` owns its line).
use vlog_parser::ast::Item;
use vlog_parser::tokenize;
/// Why an item that does not own its lines is refused by insert and delete.
pub const SHARED_LINE: &str = "shares a line with other code; edit_item inserts and deletes work on items on lines of their own (run `format` first)";
/// The start of the item's own leading comments (the item's own start when
/// it has none): walking back over `Meta::leading`, up to the first gap
/// that holds a blank line.
pub fn own_comments_start(text: &str, item: &Item) -> u32 {
let mut first = item.span.start;
for comment in item.meta.leading.iter().rev() {
let gap = text.get(comment.span.end as usize..first as usize).unwrap_or("x");
if !gap.trim().is_empty() || gap.matches('\n').count() > 1 {
break;
}
first = comment.span.start;
}
first
}
/// The lines an item owns: from the line of its first own leading comment
/// to the end of its own last line (its trailing comment included). An item
/// whose first or last line holds other code owns no lines.
pub fn own_lines(text: &str, item: &Item) -> Result<(u32, u32), String> {
let first = own_comments_start(text, item);
if !alone_before(text, first) {
return Err(SHARED_LINE.to_string());
}
let trailing = item.meta.trailing.as_ref().map_or(0, |comment| comment.span.end);
let last = alone_after(text, item.span.end.max(trailing)).ok_or(SHARED_LINE)?;
Ok((line_start(text, first), last))
}
/// The bytes `op: replace` replaces with `text`: the item's span, widened
/// back over its own leading comments when `text` begins with a comment,
/// and forward over its trailing comment when `text` ends with one on its
/// last line — so the same call twice finds its own text and is
/// `unchanged`. A text that does not lex is left to the verifier.
pub fn replace_region(file_text: &str, item: &Item, text: &str) -> (u32, u32) {
let (mut start, mut end) = (item.span.start, item.span.end);
let Ok(tokens) = tokenize(text) else {
return (start, end);
};
let Some((eof, code)) = tokens.split_last() else {
return (start, end);
};
let leads = code.first().is_some_and(|token| !token.leading.is_empty());
let trails =
eof.leading.is_empty() && code.last().is_some_and(|token| token.trailing.is_some());
if leads {
start = own_comments_start(file_text, item);
}
if let Some(comment) = item.meta.trailing.as_ref().filter(|_| trails) {
end = end.max(comment.span.end);
}
(start, end)
}
/// `end`, moved past a blank line when the removal `start..end` would leave
/// two blank lines in a row.
pub fn past_doubled_blank(text: &str, start: u32, end: u32) -> u32 {
if blank_line_before(text, start) && blank_line_at(text, end) {
return alone_after(text, end).unwrap_or(end);
}
end
}
/// The first byte of the line holding `at`.
pub fn line_start(text: &str, at: u32) -> u32 {
text.get(..at as usize).and_then(|head| head.rfind('\n')).map_or(0, |nl| nl as u32 + 1)
}
/// Whether only spaces and tabs stand between `at` and its line's start.
pub fn alone_before(text: &str, at: u32) -> bool {
let head = text.get(line_start(text, at) as usize..at as usize).unwrap_or("x");
head.bytes().all(|b| b == b' ' || b == b'\t')
}
/// The end of the line holding `at`, past its line ending (or the file's
/// end), when only blank space follows `at` on it.
fn alone_after(text: &str, at: u32) -> Option<u32> {
let rest = text.get(at as usize..)?;
let (line, next) = match rest.find('\n') {
Some(nl) => (&rest[..nl], at + nl as u32 + 1),
None => (rest, text.len() as u32),
};
line.trim().is_empty().then_some(next)
}
/// Whether the line starting at `at` is blank (and exists).
pub fn blank_line_at(text: &str, at: u32) -> bool {
(at as usize) < text.len() && alone_after(text, at).is_some()
}
/// Whether the line ending just before `at` (a line start) is blank.
pub fn blank_line_before(text: &str, at: u32) -> bool {
at > 0 && blank_line_at(text, line_start(text, at - 1))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::project::Analysis;
/// The first item of the first module of `src`.
fn first_item(analysis: &Analysis) -> &Item {
match &analysis.tree.items[0].kind {
vlog_parser::ast::ItemKind::Module(module) => &module.items[0],
_ => panic!("not a module"),
}
}
#[test]
fn a_blank_line_ends_an_items_own_comments() {
let src = "module m;\n // banner\n\n // own\n logic a;\nendmodule\n";
let analysis = Analysis::of(src.to_string());
let item = first_item(&analysis);
let (start, end) = own_lines(src, item).unwrap();
assert_eq!(&src[start as usize..end as usize], " // own\n logic a;\n");
}
#[test]
fn a_comment_before_the_item_on_its_line_goes_with_it() {
let src = "module m;\n /* lead */ logic a;\nendmodule\n";
let analysis = Analysis::of(src.to_string());
let (start, end) = own_lines(src, first_item(&analysis)).unwrap();
assert_eq!(&src[start as usize..end as usize], " /* lead */ logic a;\n");
let shared = "module m; /* c */ logic a;\nendmodule\n";
let analysis = Analysis::of(shared.to_string());
assert!(own_lines(shared, first_item(&analysis)).is_err());
}
#[test]
fn a_text_with_comments_widens_the_replaced_span_over_the_items_own() {
let src = "module m;\n // doc\n logic a; // t\nendmodule\n";
let analysis = Analysis::of(src.to_string());
let item = first_item(&analysis);
let slice = |(s, e): (u32, u32)| &src[s as usize..e as usize];
assert_eq!(slice(replace_region(src, item, "logic b;")), "logic a;");
assert_eq!(slice(replace_region(src, item, "// x\nlogic b;")), "// doc\n logic a;");
assert_eq!(slice(replace_region(src, item, "logic b; // y")), "logic a; // t");
assert_eq!(slice(replace_region(src, item, "logic b;\n// own line")), "logic a;");
}
}
+96
View File
@@ -0,0 +1,96 @@
//! `op: delete`'s implicit-connection rule: a `.*` binds a signal without
//! spelling it, so `find_references` (which returns only spans that spell
//! the name) never lists it. For each deleted name, every `.*`
//! instantiation in the item's own scope — its sibling items and the
//! generate blocks among them, the removed bytes aside — counts as a use
//! when its module (one declaration in the project index) has a port of
//! that name, and as a *possible* use when its module does not resolve to
//! exactly one declaration.
use vlog_parser::ast::{Connections, Instantiation, Item, ItemKind};
use vlog_parser::span::TextRange;
use vlog_semantic::{SymbolKind, WorkspaceIndex};
use crate::tools::read_item::child_items;
/// One `.*` a deleted name meets: where the `.*` is written, and whether
/// the binding is certain (the module has the port) or only possible.
pub struct StarUse {
pub at: TextRange,
pub module: String,
pub certain: bool,
}
/// The `.*` connections in `scope` that bind (or may bind) `name`.
pub fn star_uses(
index: &WorkspaceIndex,
scope: &[Item],
removed: TextRange,
name: &str,
) -> Vec<StarUse> {
let mut stars = Vec::new();
collect(scope, removed, &mut stars);
stars
.into_iter()
.filter_map(|(instantiation, at)| {
let module = instantiation.module.clone();
match binds(index, &module, name) {
Some(false) => None,
Some(true) => Some(StarUse { at, module, certain: true }),
None => Some(StarUse { at, module, certain: false }),
}
})
.collect()
}
/// Every instantiation with a `.*` in `items` and the generate constructs
/// among them, outside `removed`, with the `.*`'s span.
fn collect<'a>(
items: &'a [Item],
removed: TextRange,
out: &mut Vec<(&'a Instantiation, TextRange)>,
) {
for item in items {
let inside = removed.start <= item.span.start && item.span.end <= removed.end;
if inside {
continue;
}
match &item.kind {
ItemKind::Instantiation(instantiation) => {
out.extend(wildcard(instantiation).map(|at| (instantiation, at)));
}
ItemKind::GenerateRegion { .. }
| ItemKind::GenIf(_)
| ItemKind::GenFor(_)
| ItemKind::GenCase(_)
| ItemKind::GenBlock(_) => {
for children in child_items(&item.kind) {
collect(children, removed, out);
}
}
_ => {}
}
}
}
/// The span of the first `.*` among an instantiation's connections.
fn wildcard(instantiation: &Instantiation) -> Option<TextRange> {
instantiation.instances.iter().find_map(|instance| match &instance.conns {
Connections::Named(conns) => {
conns.iter().filter_map(|conn| conn.ok()).find(|conn| conn.name == "*").map(|c| c.span)
}
Connections::Ordered(_) => None,
})
}
/// Whether `module` has a port `name`: `None` when the module does not
/// resolve to exactly one indexed module or interface.
fn binds(index: &WorkspaceIndex, module: &str, name: &str) -> Option<bool> {
let instantiable =
|kind: SymbolKind| matches!(kind, SymbolKind::Module | SymbolKind::Interface);
let declarations = index.units(module).iter().filter(|def| instantiable(def.kind)).count();
if declarations != 1 {
return None;
}
Some(index.member(module, name).iter().any(|def| def.kind == SymbolKind::Port))
}
+575
View File
@@ -0,0 +1,575 @@
//! The verifier the three structural edits share — the one new piece of
//! logic in the MCP block, so it is guilty until proven innocent: every rule
//! here has an attack in `tests/attacks.rs`.
//!
//! An edit is a [`Splice`]: the bytes `start..old_end` of the file become
//! `text`. The splice itself cannot touch a byte outside that range (it is a
//! string replacement), so what is verified is what the new bytes do to the
//! **lexing and the parse**:
//!
//! 1. the new file lexes, and parses strictly when the old one did (else its
//! tolerant error count does not grow); (1a) `text` lexes on its own;
//! (1b) every token and comment outside the region is the old file's,
//! shifted, and the text's comments attach to the text's tokens — both
//! in [`lexical`];
//! 2. every item outside the region — before it, after it, and the ones
//! enclosing it — is the same item as before: same depth, same kind
//! class, same start (items after the region shifted by the splice's
//! length change), same end. A text that leaves a block open, or closes
//! the enclosing module, moves some item's end and is refused;
//! 3. the items inside the region are what the tool expects ([`Expect`]),
//! one level below the enclosing items, and each is a kind the enclosing
//! scope may hold;
//! 4. no name is declared twice in one scope that was not already;
//! 5. the region's `` `ifdef``/`` `endif`` directives balance, in the old
//! bytes and in the new;
//! 6. the `` `define``/`` `undef`` entries inside the region are the same
//! before and after — except inside a directive or macro item at the
//! region's level, where editing the definition is the point (a deletion
//! is held to it too: the lean catalogue has no `force`, PLAN §10.1);
//! 7. the region holds the same fence markers before and after
//! ([`lexical`]).
//!
//! What is deliberately **not** verified: whether the new text makes sense —
//! its types, widths, the names it reads. `check` answers that.
use vlog_parser::ast::{Item, ItemKind};
use vlog_parser::defines::DefineKind;
use vlog_parser::span::TextRange;
use vlog_parser::token::{Token, TokenKind};
use vlog_semantic::Symbol;
use super::lexical::{self, Region};
use crate::project::Analysis;
use crate::tools::read_item::child_items;
/// Replace the bytes `start..old_end` of a file with `text`.
pub struct Splice {
pub start: u32,
pub old_end: u32,
pub text: String,
}
/// What the region must hold after the splice.
pub enum Expect {
/// Exactly one item, of this kind class (`op: replace`).
One(&'static str),
/// One item or more (`insert_before`, `insert_after`).
Some,
/// Nothing (`edit_item op: delete`).
Nothing,
}
/// A splice that passed: the new file, its analysis, and the items the
/// region now holds at its own level (kind class and span).
pub struct Outcome {
pub text: String,
pub analysis: Analysis,
pub items: Vec<(&'static str, TextRange)>,
}
/// Check `splice` against `old` (see the module comment); the refusal is one
/// sentence naming the rule broken.
pub fn check(old: &Analysis, splice: &Splice, expect: Expect) -> Result<Outcome, String> {
let text = spliced(&old.text, splice)?;
let analysis = Analysis::of(text.clone());
let new_end = splice.start + splice.text.len() as u32;
let region = Region { start: splice.start, old_end: splice.old_end, new_end };
parses_as_well(old, &analysis, &splice.text)?;
lexical::same_outside(old, &analysis, region)?;
let shift = i64::from(new_end) - i64::from(splice.old_end);
let before = split(old, &outline(&old.tree.items), splice.start, splice.old_end, shift)?;
let after = split(&analysis, &outline(&analysis.tree.items), splice.start, new_end, 0)?;
same_surroundings(old, &before, &after)?;
let level = after.enclosing.len();
let items: Vec<(&'static str, TextRange)> = after
.inside
.iter()
.filter(|node| node.depth == level)
.map(|node| (node.class, TextRange::new(node.start, node.end)))
.collect();
expected(&items, &expect)?;
let container = after.enclosing.last().map_or("file", |node| node.class);
if let Some((class, _)) = items.iter().find(|(class, _)| !fits(container, class)) {
return Err(format!("a {class} cannot stand in a {container}'s scope"));
}
same_macros(old, &analysis, region, (&before, &after))?;
no_new_duplicates(old, &analysis)?;
balanced(&old.tokens, splice.start, splice.old_end, "the old item")?;
balanced(&analysis.tokens, splice.start, new_end, "the new text")?;
lexical::same_fences(old, &analysis, region)?;
Ok(Outcome { text, analysis, items })
}
/// The old text with the splice applied; a range off a character boundary
/// is refused, never adjusted.
fn spliced(old: &str, splice: &Splice) -> Result<String, String> {
let (start, end) = (splice.start as usize, splice.old_end as usize);
match (old.get(..start), old.get(end..)) {
(Some(head), Some(tail)) if start <= end => Ok(format!("{head}{}{tail}", splice.text)),
_ => Err(format!("bytes {start}..{end} do not fall on character boundaries")),
}
}
/// Rule 1: the new file lexes, and so does `text` alone (1a); it parses
/// strictly when the old one did, and otherwise has no more tolerant parse
/// errors than the old one.
fn parses_as_well(old: &Analysis, new: &Analysis, text: &str) -> Result<(), String> {
if new.tokens.is_empty() {
return Err("the file would no longer lex (an unterminated string or comment?)".into());
}
lexical::lexes_alone(text)?;
if vlog_parser::parse_source(&old.text).is_ok() {
return vlog_parser::parse_source(&new.text)
.map(|_| ())
.map_err(|e| format!("the file would no longer parse ({e})"));
}
let (was, would) = (old.diagnostics.len(), new.diagnostics.len());
if would > was {
return Err(format!("the file already had {was} parse error(s) and would have {would}"));
}
Ok(())
}
/// One item of a file, flattened: how deep it sits, its kind class and span.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct Node {
depth: usize,
class: &'static str,
start: u32,
end: u32,
}
/// Every item of a tree, depth first, in source order.
fn outline(items: &[Item]) -> Vec<Node> {
let mut out = Vec::new();
flatten(items, 0, &mut out);
out
}
fn flatten(items: &[Item], depth: usize, out: &mut Vec<Node>) {
for item in items {
let span = item.span;
out.push(Node { depth, class: class_of(&item.kind), start: span.start, end: span.end });
for children in child_items(&item.kind) {
flatten(children, depth + 1, out);
}
}
}
/// A file's items relative to a region, in the new file's coordinates.
struct Split {
/// Items wholly before or wholly after the region (the latter shifted).
outside: Vec<Node>,
/// Items containing the region (their ends shifted).
enclosing: Vec<Node>,
/// Items wholly inside it.
inside: Vec<Node>,
}
/// Sort `nodes` around `start..end`, shifting what follows by `shift`. An
/// item that begins on one side of a region boundary and ends on the other
/// is the text opening or closing something it should not: refused.
fn split(
analysis: &Analysis,
nodes: &[Node],
start: u32,
end: u32,
shift: i64,
) -> Result<Split, String> {
let moved = |at: u32| u32::try_from(i64::from(at) + shift).unwrap_or(u32::MAX);
let mut out = Split { outside: Vec::new(), enclosing: Vec::new(), inside: Vec::new() };
for node in nodes {
if end > start && start <= node.start && node.end <= end {
out.inside.push(*node);
} else if node.end <= start {
out.outside.push(*node);
} else if node.start >= end {
out.outside.push(Node { start: moved(node.start), end: moved(node.end), ..*node });
} else if node.start < start && node.end >= end {
out.enclosing.push(Node { end: moved(node.end), ..*node });
} else {
let line = analysis.lines.line_col(node.start).0;
return Err(format!(
"the {} at line {line} would begin on one side of the edit and end on the other; the text must open and close everything it starts",
node.class
));
}
}
Ok(out)
}
/// Rule 2: the items around the region are the items that were there.
fn same_surroundings(old: &Analysis, before: &Split, after: &Split) -> Result<(), String> {
let describe = |node: Option<&Node>| match node {
Some(node) => {
format!("the {} at line {}", node.class, old.lines.line_col(node.start).0)
}
None => "the end of the file".to_string(),
};
for (was, now, place) in [
(&before.enclosing, &after.enclosing, "around"),
(&before.outside, &after.outside, "outside"),
] {
if was == now {
continue;
}
let at = was.iter().zip(now.iter()).position(|(a, b)| a != b).unwrap_or(was.len());
return Err(format!(
"the edit would change how the file parses {place} the item ({} would not survive as it is); the text must be complete items that open and close within themselves",
describe(was.get(at).or(was.last()))
));
}
Ok(())
}
/// Rule 3: the region holds what the tool promised.
fn expected(items: &[(&'static str, TextRange)], expect: &Expect) -> Result<(), String> {
match (expect, items) {
(Expect::One(class), [(found, _)]) if found == class => Ok(()),
(Expect::One(class), [(found, _)]) => Err(format!(
"the text is a {found} where a {class} was; `replace` keeps an item's kind (`delete`, then an insert, to change it)"
)),
(Expect::One(_), many) => Err(format!(
"the text holds {} items where one was; `replace` replaces one item with one (an insert adds more)",
many.len()
)),
(Expect::Some, []) => Err("the text holds no item".into()),
(Expect::Nothing, [_, ..]) => {
Err("the deletion would leave an item behind".into())
}
_ => Ok(()),
}
}
/// The kind class of an item: the unit of "the same kind" for
/// `op: replace`, and what [`fits`] asks about. The table is the README's.
pub fn class_of(kind: &ItemKind) -> &'static str {
match kind {
ItemKind::Module(module) => match module.kw.as_str() {
"interface" => "interface",
"program" => "program",
_ => "module",
},
ItemKind::Package { .. } => "package",
ItemKind::Class(_) => "class",
ItemKind::DataDecl(_)
| ItemKind::ParamDecl(_)
| ItemKind::Typedef(_)
| ItemKind::Let(_) => "declaration",
ItemKind::PortDecl(_) => "port declaration",
ItemKind::Genvar(_) => "genvar",
ItemKind::ContAssign(_) => "assign",
ItemKind::Alias(_) => "alias",
ItemKind::Always { .. } => "always",
ItemKind::Initial(_) => "initial",
ItemKind::Final(_) => "final",
ItemKind::Instantiation(_) | ItemKind::GateInstantiation(_) => "instance",
ItemKind::Function(_) => "function",
ItemKind::Task(_) => "task",
ItemKind::GenerateRegion { .. }
| ItemKind::GenIf(_)
| ItemKind::GenFor(_)
| ItemKind::GenCase(_)
| ItemKind::GenBlock(_) => "generate",
ItemKind::Import(_) => "import",
ItemKind::Export(_) => "export",
ItemKind::Modport(_) => "modport",
ItemKind::Clocking(_) => "clocking",
ItemKind::Constraint(_) => "constraint",
ItemKind::Covergroup(_) => "covergroup",
ItemKind::PropSeqDecl(_) => "property",
ItemKind::Assertion(_) | ItemKind::DefaultDisable(_) => "assertion",
ItemKind::Verbatim(raw) => verbatim_class(&raw.text),
ItemKind::Bind(_) => "bind",
ItemKind::Defparam(_) => "defparam",
ItemKind::Timeunit(_) => "timeunit",
ItemKind::ElabTask(_) => "elaboration task",
ItemKind::MacroItem(_) => "macro",
ItemKind::Directive(_) => "directive",
ItemKind::Empty => "empty item",
ItemKind::Error(_) => "unparsed text",
}
}
/// A verbatim item's class, read off its first words: the parser keeps a
/// concurrent assertion, and a constraint or covergroup its grammar did not
/// fit, as text — the same construct the parsed kinds classify.
fn verbatim_class(text: &str) -> &'static str {
let words: Vec<&str> = text
.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
.filter(|word| !word.is_empty())
.take(3)
.collect();
let has = |set: &[&str]| words.iter().any(|word| set.contains(word));
if has(&["assert", "assume", "cover", "restrict", "expect"]) {
"assertion"
} else if has(&["covergroup"]) {
"covergroup"
} else if has(&["constraint"]) {
"constraint"
} else if has(&["property", "sequence"]) {
"property"
} else {
"verbatim"
}
}
/// Kinds only a module-like body (module, interface, program, generate) holds.
const BODY_ONLY: &[&str] = &[
"always",
"initial",
"final",
"assign",
"alias",
"instance",
"generate",
"port declaration",
"modport",
"clocking",
"assertion",
"defparam",
"genvar",
"elaboration task",
];
/// Whether an item of `class` may stand directly in a `container` (a kind
/// class, or `file` for the compilation unit) — IEEE 1800 A.1: a file or a
/// package holds no processes, instances or port declarations; a package
/// or a class holds no design units; a package stands only in a file.
fn fits(container: &str, class: &str) -> bool {
let unit = matches!(class, "module" | "interface" | "program" | "package");
match container {
"file" => !BODY_ONLY.contains(&class),
"package" => !BODY_ONLY.contains(&class) && !unit,
"class" => !BODY_ONLY.contains(&class) && !unit && class != "bind",
_ => class != "package",
}
}
/// Rule 6: the macro definitions whose directives lie in the region are the
/// same before and after, those inside a directive or macro item at the
/// region's level aside — a text may not define or undefine a macro that
/// code outside it reads, except by editing the `` `define`` item itself.
fn same_macros(
old: &Analysis,
new: &Analysis,
region: Region,
(before, after): (&Split, &Split),
) -> Result<(), String> {
let was = definitions(old, region.start, region.old_end, before);
let now = definitions(new, region.start, region.new_end, after);
if was == now {
return Ok(());
}
let at =
was.iter().zip(now.iter()).position(|(a, b)| a != b).unwrap_or(was.len().min(now.len()));
let name = now.get(at).or(was.get(at)).map_or("", |define| define.1.as_str());
Err(format!(
"the text changes a macro definition (`{name}`) nested in an item (rule 6); edit the `define item itself"
))
}
/// A define entry as compared: kind, name, parameters, body.
type Definition = (DefineKind, String, Option<Vec<String>>, String);
/// The `` `define``/`` `undef`` entries starting in `start..end`, except those
/// inside a directive or macro item at the split's own level.
fn definitions(analysis: &Analysis, start: u32, end: u32, split: &Split) -> Vec<Definition> {
let level = split.enclosing.len();
let exempt: Vec<&Node> = split
.inside
.iter()
.filter(|node| node.depth == level && matches!(node.class, "directive" | "macro"))
.collect();
let in_exempt = |at: u32| exempt.iter().any(|node| node.start <= at && at < node.end);
analysis
.defines
.entries()
.iter()
.filter(|d| start <= d.span.start && d.span.start < end && !in_exempt(d.span.start))
.map(|d| (d.kind, d.name.clone(), d.params.clone(), d.body.clone()))
.collect()
}
/// Rule 4: every name the new file declares twice in one scope, it already
/// declared twice (counted per name).
fn no_new_duplicates(old: &Analysis, new: &Analysis) -> Result<(), String> {
let names = |analysis: &Analysis| {
let mut names: Vec<String> =
analysis.semantics.duplicates().iter().map(|d| d.name.clone()).collect();
names.sort();
names
};
let (was, now) = (names(old), names(new));
let count = |list: &[String], name: &str| list.iter().filter(|n| *n == name).count();
match now.iter().find(|name| count(&now, name) > count(&was, name)) {
Some(name) => Err(format!("`{name}` would be declared twice in one scope")),
None => Ok(()),
}
}
/// Rule 5: the conditional-compilation directives starting inside
/// `start..end` open and close within it.
fn balanced(tokens: &[Token], start: u32, end: u32, what: &str) -> Result<(), String> {
let mut depth = 0usize;
let inside = tokens
.iter()
.filter(|t| t.kind == TokenKind::Directive && start <= t.span.start && t.span.start < end);
for token in inside {
let word = token.text.split_whitespace().next().unwrap_or("");
match word {
"`ifdef" | "`ifndef" => depth += 1,
"`elsif" | "`else" if depth == 0 => return Err(unbalanced(what, word)),
"`endif" => depth = depth.checked_sub(1).ok_or_else(|| unbalanced(what, word))?,
_ => {}
}
}
if depth > 0 {
return Err(unbalanced(what, "`ifdef"));
}
Ok(())
}
fn unbalanced(what: &str, word: &str) -> String {
format!("{what} holds a `{}` whose other half is outside it", word.trim_start_matches('`'))
}
/// The declarations an item owns: those it writes (by name, or — for a
/// non-ANSI port's body declaration — by its detail) where its neighbours
/// can name them. Names bound in a scope a construct inside the item opens
/// (a module's signals, a function's arguments, an unnamed `begin`'s
/// locals) are the item's business; the header scope a generate loop opens
/// for its genvar and label, which spans exactly the item, is see-through.
pub fn owned(analysis: &Analysis, span: TextRange) -> Vec<&Symbol> {
let within = |inner: TextRange| span.start <= inner.start && inner.end <= span.end;
analysis
.semantics
.symbols()
.iter()
.filter(|symbol| within(symbol.name_span) || symbol.detail_span.is_some_and(within))
.filter(|symbol| seen_from_outside(analysis, symbol, span))
.collect()
}
/// Whether every scope between `symbol` and the first scope outside `span`
/// is one the item opened around itself (unnamed, spanning exactly it).
fn seen_from_outside(analysis: &Analysis, symbol: &Symbol, span: TextRange) -> bool {
let semantics = &analysis.semantics;
let mut at = Some(symbol.scope);
while let Some(id) = at {
// The file scope may span exactly the item when the file is that
// item and nothing else; it is never the item's own.
let Some(scope) = semantics.scope(id).filter(|_| id != semantics.file_scope()) else {
return true;
};
let inside = span.start <= scope.span.start && scope.span.end <= span.end;
if !inside {
return true;
}
if scope.owner.is_some() || scope.span != span {
return false;
}
at = scope.parent;
}
true
}
/// The names [`owned`] finds, sorted.
pub fn owned_names(analysis: &Analysis, span: TextRange) -> Vec<String> {
let mut names: Vec<String> =
owned(analysis, span).into_iter().map(|symbol| symbol.name.clone()).collect();
names.sort();
names
}
#[cfg(test)]
mod tests {
use super::*;
const SRC: &str = "module m (input logic d);\n logic a;\n always_comb a = d;\nendmodule\n";
fn run(start: u32, old_end: u32, text: &str, expect: Expect) -> Result<Outcome, String> {
let old = Analysis::of(SRC.to_string());
check(&old, &Splice { start, old_end, text: text.into() }, expect)
}
fn span_of(needle: &str) -> (u32, u32) {
let at = SRC.find(needle).unwrap() as u32;
(at, at + needle.len() as u32)
}
#[test]
fn a_same_kind_item_passes_and_reports_its_span() {
let (start, end) = span_of("logic a;");
let outcome = run(start, end, "logic [3:0] a;", Expect::One("declaration")).unwrap();
assert_eq!(outcome.items.len(), 1);
assert_eq!(outcome.items[0].1, TextRange::new(start, start + 14));
assert!(outcome.text.contains(" logic [3:0] a;\n always_comb"));
}
#[test]
fn each_rule_refuses_with_its_own_sentence() {
let (start, end) = span_of("logic a;");
let open = run(start, end, "always_comb begin a = d;", Expect::One("declaration"));
assert!(open.err().unwrap().contains("no longer parse"));
let closes = run(start, end, "logic a;\nendmodule\nmodule z;", Expect::One("declaration"));
assert!(closes.err().unwrap().contains("open and close"));
let two = run(start, end, "logic a; logic b;", Expect::One("declaration"));
assert!(two.err().unwrap().contains("holds 2 items"));
let kind = run(start, end, "initial a = 0;", Expect::One("declaration"));
assert!(kind.err().unwrap().contains("initial where a declaration was"));
let twice = run(start, end, "logic d;", Expect::One("declaration"));
assert!(twice.err().unwrap().contains("`d` would be declared twice"));
let half = run(start, end, "`ifdef X\nlogic a;", Expect::Some);
assert!(half.err().unwrap().contains("`ifdef"), "half");
let split = run(start + 1, end, "x", Expect::Some);
assert!(split.is_err());
}
#[test]
fn a_file_scope_insert_must_be_a_kind_the_file_may_hold() {
let at = SRC.len() as u32;
let always = run(at, at, "always_comb x = 1;\n", Expect::Some);
assert!(always.err().unwrap().contains("always cannot stand in a file's scope"));
assert!(run(at, at, "module z; endmodule\n", Expect::Some).is_ok());
}
#[test]
fn verbatim_items_are_classed_by_their_words() {
assert_eq!(verbatim_class("a1: assert property (p);"), "assertion");
assert_eq!(verbatim_class("covergroup cg @(e); endgroup"), "covergroup");
assert_eq!(verbatim_class("static constraint c { x; }"), "constraint");
assert_eq!(verbatim_class("sequence s; a; endsequence"), "property");
assert_eq!(verbatim_class("?"), "verbatim");
assert!(fits("module", "always") && !fits("package", "module") && !fits("class", "bind"));
}
#[test]
fn owned_names_are_the_ones_bound_around_the_item() {
let analysis = Analysis::of(SRC.to_string());
let whole = TextRange::new(0, SRC.len() as u32 - 1);
assert_eq!(owned_names(&analysis, whole), ["m"]);
let (start, end) = span_of("logic a;");
assert_eq!(owned_names(&analysis, TextRange::new(start, end)), ["a"]);
let (start, end) = span_of("always_comb a = d;");
assert!(owned_names(&analysis, TextRange::new(start, end)).is_empty());
}
#[test]
fn a_generate_loop_owns_its_label_and_an_unnamed_begin_keeps_its_locals() {
let src = "module g;\n for (genvar i = 0; i < 2; i++) begin : gen_l\n logic z;\n end\n always begin\n int k;\n end\nendmodule\n";
let analysis = Analysis::of(src.to_string());
let span = |needle: &str, len: usize| {
let at = src.find(needle).unwrap() as u32;
TextRange::new(at, at + len as u32)
};
let lp = span(
"for (genvar",
"for (genvar i = 0; i < 2; i++) begin : gen_l\n logic z;\n end".len(),
);
assert_eq!(owned_names(&analysis, lp), ["gen_l", "i"]);
let always = span("always begin", "always begin\n int k;\n end".len());
assert!(owned_names(&analysis, always).is_empty());
}
}
+347
View File
@@ -0,0 +1,347 @@
//! Unresolved mentions: every whole-word spelling of a name that no engine
//! answer accounted for and that sits where no lucisv engine looks — inside
//! a string literal, a comment, a macro call's text, a `` `define`` body, or
//! a hierarchical path rooted at a macro (`` `X_HIER.u_core.name``).
//!
//! These are the spellings a rename leaves behind without a word: a DV
//! force path built as the string `".state_q"`, a probe through a macro
//! path, a comment naming the signal. lucisv cannot tell whether any of them
//! means *this* declaration — a word is a word — so they are listed, never
//! edited, and the agent decides (feedback round 1, `mcp_analysis.md`).
//!
//! The pass reads nothing new: the engines were handed every indexed file's
//! text already (`source::WholeSet`), so each text is byte-searched for the
//! name, and only a text that spells it is lexed. The index's word censuses
//! (`files_mentioning`, `files_naming_in_macros`) cannot narrow it further:
//! comments and strings are not in them.
use std::path::{Path, PathBuf};
use vlog_parser::span::TextRange;
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::{tokenize, LineIndex};
use super::source::word_in;
use crate::project::Project;
use crate::render;
/// The most mentions an answer lists; the rest are counted.
pub const CAP: usize = 50;
/// One unresolved spelling: the file and line that hold it.
pub struct Mention {
pub file: String,
pub line: u32,
}
/// The mentions an answer lists (at most [`CAP`]) and how many there are.
#[derive(Default)]
pub struct Mentions {
pub listed: Vec<Mention>,
pub total: usize,
}
/// What the search is about: the name, where it is declared (the listing
/// starts nearest to it), and the spans the engine already accounted for.
pub struct Focus<'a> {
pub name: &'a str,
/// The declaration's file.
pub home: &'a Path,
/// The unit declaring the name, when known: a line naming it (an
/// instance `u_<unit>` on a macro path) is listed early.
pub unit: Option<&'a str>,
/// Per file, the spans an engine returned (hits) or rewrote (edits).
pub accounted: &'a [(PathBuf, Vec<TextRange>)],
/// `(file, line)` pairs an engine warning already names — a `rename`'s
/// unresolved-path warning — which are not repeated as mentions.
pub named: &'a [(String, u32)],
/// For a member of a module or interface (a net, a port, a block, …):
/// the files where a bare spelling can mean it — its home set: the
/// declaring file, what it includes and what includes it, and the files
/// the edit wrote or the engine found uses in. Elsewhere only a
/// spelling right after a `.` (`".state_q"`, `` `HIER.u.state_q``) is
/// listed. `None` for a name any file may spell bare (a unit, a package
/// member): every mention is listed.
pub local: Option<&'a [PathBuf]>,
}
impl Mentions {
/// Whether there is nothing to say.
pub fn is_empty(&self) -> bool {
self.total == 0
}
/// The `unresolved:` block an answer ends with — the label, then the
/// mentions one file per line (`file:12,40`), then the cut — or nothing.
pub fn block(&self) -> Vec<String> {
if self.is_empty() {
return Vec::new();
}
let sites: Vec<(String, u32)> =
self.listed.iter().map(|m| (m.file.clone(), m.line)).collect();
let mut out = vec!["unresolved:".to_string()];
out.extend(render::by_file(&sites).into_iter().map(|line| format!(" {line}")));
let rest = self.total - self.listed.len();
if rest > 0 {
out.push(format!(" {}", render::more(rest)));
}
out
}
}
/// The unresolved mentions of `focus.name` across `files`, nearest first.
pub fn find<'t>(
project: &Project,
files: impl Iterator<Item = (&'t Path, &'t str)>,
focus: &Focus,
) -> Mentions {
let mut found: Vec<(u8, usize, Mention)> = Vec::new();
for (path, text) in files {
if !text.contains(focus.name) {
continue;
}
let accounted = focus.accounted.iter().find(|(held, _)| held.as_path() == path);
let spans = accounted.map_or(&[][..], |(_, spans)| spans.as_slice());
let lines = LineIndex::new(text);
let mut last_line = 0;
let foreign = focus.local.is_some_and(|local| !local.iter().any(|p| p == path));
for (at, _) in spellings(text, focus.name) {
if foreign
&& !text.as_bytes().get((at as usize).wrapping_sub(1)).is_some_and(|&b| b == b'.')
{
continue;
}
let end = at + focus.name.len() as u32;
if spans.iter().any(|span| span.start <= at && end <= span.end) {
continue;
}
let line = lines.line_col(at).0;
if line == last_line {
continue;
}
last_line = line;
let source = lines
.line_range(line)
.and_then(|range| text.get(range.start as usize..range.end as usize))
.unwrap_or("");
let rank = rank(accounted.is_some(), focus.unit, source);
let mention = Mention { file: project.relative(path), line };
if focus.named.iter().any(|(file, at)| *file == mention.file && *at == line) {
continue;
}
found.push((rank, shared_components(path, focus.home), mention));
}
}
// Files the engine touched, then lines naming the declaring unit, then
// nearest to the declaration's directory; file and line order within.
found.sort_by(|a, b| (b.0, b.1, &a.2.file, a.2.line).cmp(&(a.0, a.1, &b.2.file, b.2.line)));
let total = found.len();
let listed = found.into_iter().take(CAP).map(|(_, _, mention)| mention).collect();
Mentions { listed, total }
}
/// How early a mention is listed: 2 in a file the engine touched, 1 on a
/// line that spells the declaring unit's name (`u_<unit>` included), 0
/// otherwise.
fn rank(touched: bool, unit: Option<&str>, line: &str) -> u8 {
if touched {
2
} else if unit.is_some_and(|unit| !unit.is_empty() && line.contains(unit)) {
1
} else {
0
}
}
/// How many leading path components two paths share.
fn shared_components(a: &Path, b: &Path) -> usize {
a.components().zip(b.components()).take_while(|(x, y)| x == y).count()
}
/// Every whole-word spelling of `name` in `text` that lies in a comment, a
/// string, a macro call, a `` `define`` body, or ends a macro-rooted path,
/// as `(byte offset, kind)` in source order. A file that does not lex has
/// every spelling listed (`text`): nothing in it was resolved.
fn spellings(text: &str, name: &str) -> Vec<(u32, &'static str)> {
let Ok(tokens) = tokenize(text) else {
return words(text, 0, name).into_iter().map(|at| (at, "text")).collect();
};
let mut out = Vec::new();
for (i, token) in tokens.iter().enumerate() {
for comment in token.leading.iter().chain(token.trailing.as_ref()) {
let at = comment.span.start;
out.extend(words(&comment.text, at, name).into_iter().map(|at| (at, "comment")));
}
let (at, source) = (token.span.start, token.text.as_str());
match token.kind {
TokenKind::String => {
out.extend(words(source, at, name).into_iter().map(|at| (at, "string")))
}
TokenKind::Ident if token.is_macro() => {
let after = macro_name_end(source);
let found = words(&source[after..], at + after as u32, name);
out.extend(found.into_iter().map(|at| (at, "macro")));
}
TokenKind::Directive => {
let Some((formals, body)) = define_parts(source) else { continue };
// A formal argument of that name shadows it in the body.
if word_in(&source[formals..body], name).is_some() {
continue;
}
let found = words(&source[body..], at + body as u32, name);
out.extend(found.into_iter().map(|at| (at, "define")));
}
TokenKind::Ident if token.text == name && macro_rooted(&tokens, i) => {
out.push((at, "path"));
}
_ => {}
}
}
out.sort_by_key(|(at, _)| *at);
out
}
/// Every whole-word occurrence of `name` in `text`, as offsets from `base`.
fn words(text: &str, base: u32, name: &str) -> Vec<u32> {
let mut out = Vec::new();
let mut from = 0;
while let Some(found) = text.get(from..).and_then(|rest| word_in(rest, name)) {
out.push(base + (from + found) as u32);
from += found + name.len();
}
out
}
/// Where a macro use's own name ends (`` `NAME`` then its arguments).
fn macro_name_end(text: &str) -> usize {
1 + ident_len(text.get(1..).unwrap_or(""))
}
/// The length of the identifier `text` starts with.
fn ident_len(text: &str) -> usize {
let glued = |c: char| c.is_ascii_alphanumeric() || c == '_' || c == '$';
text.find(|c: char| !glued(c)).unwrap_or(text.len())
}
/// A `` `define`` directive's formal argument list and body: where the list
/// starts (past the macro's name) and where the body starts (past the list).
/// `None` for any other directive.
fn define_parts(text: &str) -> Option<(usize, usize)> {
let rest = text.strip_prefix("`define")?;
let name_at = text.len() - rest.trim_start().len();
let formals = name_at + ident_len(&text[name_at..]);
if !text[formals..].starts_with('(') {
return Some((formals, formals));
}
let mut depth = 0usize;
for (offset, c) in text[formals..].char_indices() {
match c {
'(' => depth += 1,
')' if depth == 1 => return Some((formals, formals + offset + 1)),
')' => depth = depth.saturating_sub(1),
_ => {}
}
}
Some((formals, text.len()))
}
/// Whether the identifier at `i` ends a dotted path whose head is a macro
/// (`` `HIER.u_a[0].name``, `` `HIER(1).name``) — a path no engine follows.
fn macro_rooted(tokens: &[Token], i: usize) -> bool {
let symbol = |at: usize, text: &str| {
tokens.get(at).is_some_and(|t| t.kind == TokenKind::Symbol && t.text == text)
};
let mut at = i;
loop {
if at < 2 || !symbol(at - 1, ".") {
return false;
}
let mut head = at - 2;
// Skip the selects of the segment before the dot: `u_a[0][1]`.
while symbol(head, "]") {
let mut depth = 0usize;
loop {
if symbol(head, "]") {
depth += 1;
} else if symbol(head, "[") {
depth -= 1;
if depth == 0 {
break;
}
}
let Some(before) = head.checked_sub(1) else { return false };
head = before;
}
let Some(before) = head.checked_sub(1) else { return false };
head = before;
}
match tokens.get(head) {
Some(token) if token.is_macro() => return true,
Some(token) if token.kind == TokenKind::Ident => at = head,
_ => return false,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn kinds(src: &str, name: &str) -> Vec<(u32, &'static str)> {
spellings(src, name)
}
fn lines_of(src: &str, name: &str) -> Vec<(u32, &'static str)> {
let lines = LineIndex::new(src);
spellings(src, name).into_iter().map(|(at, kind)| (lines.line_col(at).0, kind)).collect()
}
#[test]
fn strings_comments_macro_text_and_macro_paths_are_found() {
let src = "module m;\n\
// state_q holds the state\n\
logic state_q;\n\
initial $display(\"%m.state_q\");\n\
`ASSERT(A, state_q == 0)\n\
`define PROBE(x) x.state_q\n\
assign o = `HIER.u_fsm[0].state_q;\n\
assign p = `SPI(1).u.state_q;\n\
assign q = u_fsm.state_q;\n\
endmodule /* state_q */\n";
assert_eq!(
lines_of(src, "state_q"),
[
(2, "comment"),
(4, "string"),
(5, "macro"),
(6, "define"),
(7, "path"),
(8, "path"),
(10, "comment"),
]
);
}
#[test]
fn a_word_inside_another_and_a_formal_argument_are_not_mentions() {
assert!(kinds("// state_qq and xstate_q\n", "state_q").is_empty());
assert!(kinds("`define F(state_q) state_q + 1\n", "state_q").is_empty());
assert!(kinds("`define G(a) a\n", "a").is_empty());
assert!(kinds("`state_q\n", "state_q").is_empty(), "a macro's own name");
assert_eq!(kinds("`ifdef state_q\n`endif\n", "state_q"), []);
}
#[test]
fn a_file_that_does_not_lex_lists_every_spelling() {
assert_eq!(kinds("x = \"state_q\n state_q", "state_q").len(), 2);
}
#[test]
fn ranking_prefers_touched_files_then_the_unit_then_nearness() {
assert_eq!(rank(true, None, ""), 2);
assert_eq!(rank(false, Some("main_sm"), "`HIER.u_main_sm.state_q"), 1);
assert_eq!(rank(false, Some("main_sm"), "`HIER.u_ack_sm.state_q"), 0);
let (a, b) = (Path::new("/hw/ip/es/rtl/a.sv"), Path::new("/hw/ip/es/dv/b.sv"));
assert_eq!(shared_components(a, b), 4);
}
}
+112 -80
View File
@@ -3,28 +3,44 @@
//! `inputSchema` a host shows the agent and the validation a call's
//! `arguments` go through, so the two cannot disagree.
mod defines;
mod declared;
mod diagnostics;
mod edit;
mod find;
mod format;
mod glob;
mod hierarchy;
mod interface;
mod nav;
mod item;
mod mentions;
mod names;
mod outline;
mod place;
mod port;
mod read;
mod read_item;
mod refactor;
mod select;
mod source;
use serde_json::{json, Map, Value};
use crate::project::Project;
/// What a tool hands back: the compact text rendering the agent reads, and
/// the same facts as JSON (`structuredContent`).
/// What a tool hands back: the text the agent reads. A result is its text;
/// there is no structured twin (PLAN §10.1).
pub struct Answer {
pub text: String,
pub structured: Value,
}
impl Answer {
/// An answer of these lines, each ended by a newline.
pub fn lines(lines: Vec<String>) -> Answer {
let mut text = String::new();
for line in lines {
text.push_str(&line);
text.push('\n');
}
Answer { text }
}
}
/// A tool's body. `Err` is a refusal: one sentence, sent as `isError: true`.
@@ -34,32 +50,30 @@ pub type Handler = fn(&mut Project, &Args) -> Result<Answer, String>;
pub enum Ty {
/// A string.
Str,
/// An integer no smaller than the bound.
Int { min: i64 },
/// One of a fixed set of strings.
Enum(&'static [&'static str]),
/// `true` or `false`.
Bool,
/// An integer inside `min..=max`.
/// An integer inside `min..=max` — checked here; the schema says only
/// `integer`, the tool's description names the range.
Range { min: i64, max: i64 },
}
/// One argument a tool takes.
/// One argument a tool takes. It has no description of its own: the tool's
/// one description names its arguments (PLAN §10.1).
pub struct Param {
pub name: &'static str,
pub ty: Ty,
pub required: bool,
pub description: &'static str,
}
/// One tool, as `tools/list` shows it and `tools/call` runs it.
pub struct Tool {
pub name: &'static str,
pub title: &'static str,
pub description: &'static str,
pub params: &'static [Param],
/// Whether the call walks the roots again before answering, so files
/// created since the last walk are counted (`project_overview`).
/// created since the last walk are part of the whole set an edit needs.
pub rewalk: bool,
pub handler: Handler,
}
@@ -71,8 +85,8 @@ pub enum Effect {
/// Nothing on disk changes; the same call on the same disk gives the
/// same answer.
Read,
/// Files inside the roots are rewritten (or created). `idempotent` when
/// a second identical call writes nothing more.
/// Files inside the roots are rewritten. `idempotent` when a second
/// identical call writes nothing more.
Edit { idempotent: bool },
}
@@ -80,57 +94,67 @@ use Effect::{Edit, Read};
/// Every tool this server offers, in the order `tools/list` gives them.
const TOOLS: &[(Tool, Effect)] = &[
(read::PROJECT_OVERVIEW, Read),
(read::LIST_UNITS, Read),
(interface::UNIT_INTERFACE, Read),
(read::OUTLINE, Read),
(read_item::READ_ITEM, Read),
(read::SEARCH_SYMBOLS, Read),
(defines::DEFINES, Read),
(nav::DEFINITION, Read),
(nav::REFERENCES, Read),
(hierarchy::HIERARCHY, Read),
(diagnostics::DIAGNOSTICS, Read),
(format::FORMAT, Edit { idempotent: true }),
(format::FIX_LINT, Edit { idempotent: true }),
(find::FIND, Read),
(outline::OUTLINE, Read),
(read::READ, Read),
(diagnostics::CHECK, Read),
(edit::RENAME, Edit { idempotent: false }),
(edit::EXPAND_WILDCARD, Edit { idempotent: true }),
(edit::CONVERT_PORTS, Edit { idempotent: true }),
(edit::ORGANIZE_IMPORTS, Edit { idempotent: true }),
(edit::INLINE_MODULE, Edit { idempotent: false }),
(edit::PROPAGATE_PORTS, Edit { idempotent: false }),
(edit::REMOVE_PORT, Edit { idempotent: false }),
(refactor::ADD_PORT, Edit { idempotent: false }),
(refactor::EXTRACT_MODULE, Edit { idempotent: false }),
(refactor::INSTANTIATE, Read),
(port::PORT, Edit { idempotent: false }),
(item::EDIT_ITEM, Edit { idempotent: false }),
(format::FORMAT, Edit { idempotent: true }),
];
/// The tool called `name`.
pub fn find(name: &str) -> Option<&'static Tool> {
TOOLS.iter().map(|(tool, _)| tool).find(|tool| tool.name == name)
/// Which part of the registry the server offers (PLAN §11).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Mode {
/// Every tool, the edits included.
#[default]
Full,
/// `--read-only`: the read tools alone; an edit tool is unknown.
ReadOnly,
}
/// The `tools/list` result: every tool, no pagination.
pub fn list() -> Value {
let tools: Vec<Value> = TOOLS.iter().map(|(tool, effect)| describe(tool, *effect)).collect();
impl Mode {
/// Whether a tool of this effect exists in this mode.
fn offers(self, effect: Effect) -> bool {
matches!((self, effect), (Mode::Full, _) | (Mode::ReadOnly, Read))
}
}
/// The tools `mode` offers, in `tools/list` order.
fn offered(mode: Mode) -> impl Iterator<Item = (&'static Tool, Effect)> {
TOOLS
.iter()
.filter(move |(_, effect)| mode.offers(*effect))
.map(|(tool, effect)| (tool, *effect))
}
/// The tool called `name`, when `mode` offers it.
pub fn find(name: &str, mode: Mode) -> Option<&'static Tool> {
offered(mode).map(|(tool, _)| tool).find(|tool| tool.name == name)
}
/// The `tools/list` result: every tool `mode` offers, no pagination.
pub fn list(mode: Mode) -> Value {
let tools: Vec<Value> = offered(mode).map(|(tool, effect)| describe(tool, effect)).collect();
json!({ "tools": tools })
}
fn describe(tool: &Tool, effect: Effect) -> Value {
// No tool consults anything outside the roots (`openWorldHint`), and no
// edit tool destroys: each rewrites files inside the roots through a
// verified engine, and `dry_run` shows the diff first.
// verified engine, all or nothing.
let (read_only, idempotent) = match effect {
Read => (true, true),
Edit { idempotent } => (false, idempotent),
};
json!({
"name": tool.name,
"title": tool.title,
"description": tool.description,
"inputSchema": schema(tool.params),
// Hosts read these; the model never sees them (PLAN §10.1).
"annotations": {
"title": tool.title,
"readOnlyHint": read_only,
"destructiveHint": false,
"idempotentHint": idempotent,
@@ -139,18 +163,17 @@ fn describe(tool: &Tool, effect: Effect) -> Value {
})
}
/// A JSON Schema object for an argument list: closed, with its required set.
/// A JSON Schema object for an argument list: closed, with its required
/// set, and `type` alone per property (an `enum` where one applies).
fn schema(params: &[Param]) -> Value {
let mut properties = Map::new();
for param in params {
let mut property = match param.ty {
let property = match param.ty {
Ty::Str => json!({ "type": "string" }),
Ty::Int { min } => json!({ "type": "integer", "minimum": min }),
Ty::Enum(values) => json!({ "type": "string", "enum": values }),
Ty::Bool => json!({ "type": "boolean" }),
Ty::Range { min, max } => json!({ "type": "integer", "minimum": min, "maximum": max }),
Ty::Range { .. } => json!({ "type": "integer" }),
};
property["description"] = Value::from(param.description);
properties.insert(param.name.to_string(), property);
}
let required: Vec<&str> =
@@ -172,19 +195,15 @@ impl Args {
self.0.get(name).and_then(Value::as_str)
}
/// An integer argument, when given.
pub fn int(&self, name: &str) -> Option<i64> {
self.0.get(name).and_then(Value::as_i64)
}
/// A boolean argument, or `default`.
pub fn flag(&self, name: &str, default: bool) -> bool {
self.0.get(name).and_then(Value::as_bool).unwrap_or(default)
/// A boolean argument; `false` when absent.
pub fn flag(&self, name: &str) -> bool {
self.0.get(name).and_then(Value::as_bool).unwrap_or(false)
}
/// A non-negative integer argument, or `default`.
pub fn count(&self, name: &str, default: usize) -> usize {
self.int(name).and_then(|n| usize::try_from(n).ok()).unwrap_or(default)
let given = self.0.get(name).and_then(Value::as_i64);
given.and_then(|n| usize::try_from(n).ok()).unwrap_or(default)
}
}
@@ -216,7 +235,6 @@ pub fn validate(tool: &Tool, arguments: Map<String, Value>) -> Result<Args, Stri
fn check_type(tool: &str, param: &Param, value: &Value) -> Result<(), String> {
let fits = match param.ty {
Ty::Str => value.is_string(),
Ty::Int { min } => value.as_i64().is_some_and(|n| n >= min),
Ty::Enum(values) => value.as_str().is_some_and(|s| values.contains(&s)),
Ty::Bool => value.is_boolean(),
Ty::Range { min, max } => value.as_i64().is_some_and(|n| (min..=max).contains(&n)),
@@ -226,7 +244,6 @@ fn check_type(tool: &str, param: &Param, value: &Value) -> Result<(), String> {
}
let wanted = match param.ty {
Ty::Str => "a string".to_string(),
Ty::Int { min } => format!("an integer >= {min}"),
Ty::Enum(values) => format!("one of {}", values.join(", ")),
Ty::Bool => "true or false".to_string(),
Ty::Range { min, max } => format!("an integer from {min} to {max}"),
@@ -243,12 +260,16 @@ mod tests {
}
#[test]
fn every_schema_is_closed_and_names_its_required_arguments() {
fn every_schema_is_closed_and_bare_and_every_name_is_unique() {
for (tool, _) in TOOLS {
let schema = schema(tool.params);
assert_eq!(schema["additionalProperties"], false, "{}", tool.name);
assert!(schema["required"].is_array(), "{}", tool.name);
assert!(!tool.description.is_empty() && tool.description.len() < 600, "{}", tool.name);
for (name, property) in schema["properties"].as_object().unwrap() {
let keys: Vec<&String> = property.as_object().unwrap().keys().collect();
assert!(keys.iter().all(|k| *k == "type" || *k == "enum"), "{name}: {keys:?}");
}
assert!(!tool.description.is_empty() && tool.description.len() < 300, "{}", tool.name);
}
let names: Vec<&str> = TOOLS.iter().map(|(tool, _)| tool.name).collect();
let mut unique = names.clone();
@@ -257,27 +278,38 @@ mod tests {
assert_eq!(names.len(), unique.len());
}
#[test]
fn read_only_mode_offers_the_read_tools_alone_in_order() {
let names = |mode| -> Vec<&str> { offered(mode).map(|(tool, _)| tool.name).collect() };
assert_eq!(names(Mode::ReadOnly), ["hierarchy", "find", "outline", "read", "check"]);
assert_eq!(names(Mode::Full).len(), TOOLS.len());
for edit in ["rename", "port", "edit_item", "format"] {
assert!(find(edit, Mode::ReadOnly).is_none(), "{edit}");
assert!(find(edit, Mode::Full).is_some(), "{edit}");
}
}
#[test]
fn validation_names_the_offending_argument() {
let tool = find("list_units").unwrap();
let unknown = validate(tool, args(json!({"nme": "x"}))).err().unwrap();
assert!(unknown.contains("`nme`"), "{unknown}");
let wrong = validate(tool, args(json!({"kind": "struct"}))).err().unwrap();
assert!(wrong.contains("`kind`") && wrong.contains("module"), "{wrong}");
let negative = validate(tool, args(json!({"limit": -1}))).err().unwrap();
assert!(negative.contains("`limit`"), "{negative}");
let missing = validate(find("outline").unwrap(), Map::new()).err().unwrap();
assert!(missing.contains("`file`"), "{missing}");
assert!(validate(tool, args(json!({"kind": "module", "glob": null}))).is_ok());
let references = find("references").unwrap();
let flag = validate(references, args(json!({"name": "x", "include_declaration": "no"})));
assert!(flag.err().unwrap().contains("true or false"));
let given = validate(references, args(json!({"name": "x", "include_declaration": false})));
assert!(!given.unwrap().flag("include_declaration", true));
let find = |name| find(name, Mode::Full);
let tool = find("check").unwrap();
let unknown = validate(tool, args(json!({"fil": "x"}))).err().unwrap();
assert!(unknown.contains("`fil`") && unknown.contains("file"), "{unknown}");
let wrong = validate(tool, args(json!({"file": 3}))).err().unwrap();
assert!(wrong.contains("`file`") && wrong.contains("a string"), "{wrong}");
let missing = validate(find("read").unwrap(), Map::new()).err().unwrap();
assert!(missing.contains("`item`"), "{missing}");
assert!(validate(tool, args(json!({"file": null}))).is_ok());
let edit = find("edit_item").unwrap();
let op = json!({"file": "a.sv", "op": "move", "item": "x"});
let op = validate(edit, args(op)).err().unwrap();
assert!(op.contains("`op`") && op.contains("replace"), "{op}");
let hierarchy = find("hierarchy").unwrap();
let flag = validate(hierarchy, args(json!({"up": "yes"}))).err().unwrap();
assert!(flag.contains("true or false"), "{flag}");
let deep = validate(hierarchy, args(json!({"depth": 21}))).err().unwrap();
assert!(deep.contains("`depth`") && deep.contains("from 1 to 20"), "{deep}");
assert!(validate(hierarchy, args(json!({"depth": 20}))).is_ok());
assert_eq!(schema(hierarchy.params)["properties"]["depth"]["maximum"], 20);
assert_eq!(schema(hierarchy.params)["properties"]["depth"], json!({"type": "integer"}));
}
}
+234
View File
@@ -0,0 +1,234 @@
//! Names looked up — the by-name half every lean tool shares: every
//! declaration of a name (the index's units, exported members and module
//! internals, every declaration the files' own symbol tables hold, and the
//! `` `define``s), each read off the bytes on disk, and the near matches a
//! refusal lists when there is none — from the same table — so the next
//! call is right.
use std::collections::{BTreeSet, HashSet};
use std::path::{Path, PathBuf};
use vlog_parser::defines::DefineKind;
use vlog_semantic::{Def, DefinitionKey, FileId, Surface, SymbolKind, WorkspaceIndex};
use super::declared::{declared, Local, Wanted};
use super::source::{checked_site, Texts};
use crate::project::Project;
use crate::render;
/// One declaration of a name, where it is written.
pub struct Declaration {
pub path: PathBuf,
/// The byte offset of the name itself.
pub offset: u32,
/// The kind word (`macro` for a `` `define``).
pub kind: &'static str,
pub file: String,
pub line: u32,
}
impl Declaration {
/// `kind name file:line`, as `find` lists it.
pub fn render(&self, name: &str) -> String {
format!("{} {name} {}:{}", self.kind, self.file, self.line)
}
/// Whether this is a `` `define`` (no engine follows its uses).
pub fn is_macro(&self) -> bool {
self.kind == "macro"
}
}
/// A name as written, split into the unit it is qualified by (`unit.name`,
/// `pkg::name`) and the name itself; an escaped identifier is never split.
pub fn qualified(name: &str) -> (Option<&str>, &str) {
if name.starts_with('\\') {
return (None, name);
}
let split = name.rsplit_once("::").or_else(|| name.rsplit_once('.'));
match split {
Some((unit, member)) if !unit.is_empty() && !member.is_empty() => (Some(unit), member),
_ => (None, name),
}
}
/// Every declaration of `name` — its declarations first, then its
/// `` `define``s — each whose file still spells the name there, in file
/// and line order within each group. `unit.name` (or `pkg::name`) is the
/// member of that unit only.
pub fn declarations(project: &Project, name: &str) -> Vec<Declaration> {
let index = project.index();
let (unit, name) = qualified(name);
let mut texts = Texts::default();
let mut out: Vec<Declaration> = Vec::new();
let defs = match unit {
Some(unit) => index.member_in(unit, name, Surface::Hierarchical).to_vec(),
None => defs_named(index, name),
};
for def in defs {
let Some(path) = index.path(def.file) else { continue };
let shown = def.detail_span.unwrap_or(def.name_span);
let kind = unit_kind(project, path, &def);
let site = checked_site(project, &mut texts, path, def.name_span, shown, name);
if let Some(site) = site {
let offset = def.name_span.start;
let (file, line) = (site.file, site.line);
out.push(Declaration { path: path.to_path_buf(), offset, kind, file, line });
}
}
let locals = declared(project, &Wanted::Exact(name));
let in_unit = |local: &&Local| unit.is_none_or(|unit| local.unit.as_deref() == Some(unit));
for local in locals.iter().filter(in_unit) {
let known = out.iter().any(|d| d.path == local.path && d.offset == local.offset);
if !known {
out.push(Declaration {
path: local.path.clone(),
offset: local.offset,
kind: local.kind,
file: project.relative(&local.path),
line: local.line,
});
}
}
out.sort_by(|a, b| (&a.file, a.line).cmp(&(&b.file, b.line)));
out.dedup_by(|a, b| (&a.file, a.line, a.offset) == (&b.file, b.line, b.offset));
if unit.is_some() {
return out;
}
let mut macros = macro_declarations(project, &mut texts, name);
macros.sort_by(|a, b| (&a.file, a.line).cmp(&(&b.file, b.line)));
out.extend(macros);
out
}
/// Every indexed non-macro declaration of `name`, each once.
fn defs_named(index: &WorkspaceIndex, name: &str) -> Vec<Def> {
let mut defs: Vec<Def> = index.units(name).to_vec();
let exported = index.workspace_symbols(name);
let members = exported.iter().filter(|hit| hit.name == name && hit.container.is_some());
defs.extend(members.map(|hit| hit.def.clone()));
defs.extend(index.hierarchical_declarations(name).map(|(_, def)| def.clone()));
let mut seen = HashSet::new();
defs.retain(|def| seen.insert(DefinitionKey::of(def)));
defs
}
/// Every indexed `` `define`` of `name` whose file still spells it there.
fn macro_declarations(project: &Project, texts: &mut Texts, name: &str) -> Vec<Declaration> {
let index = project.index();
let defined = index.find_define(name).into_iter().filter(|(_, d)| d.kind == DefineKind::Define);
defined
.filter_map(|(file, define)| {
let path = index.path(file)?;
let span = define.name_span;
let site = checked_site(project, texts, path, span, span, name)?;
let (file, line) = (site.file, site.line);
Some(Declaration {
path: path.to_path_buf(),
offset: span.start,
kind: "macro",
file,
line,
})
})
.collect()
}
/// A declaration's kind word, telling a `program` from the module it is
/// modelled as.
fn unit_kind(project: &Project, path: &Path, def: &Def) -> &'static str {
if def.kind == SymbolKind::Module && is_program(project, path, def) {
"program"
} else {
render::kind(def.kind)
}
}
/// Whether a `Module`-kind unit was declared with `program`. The semantic
/// layer models the two alike, so the keyword is read off the text between
/// the declaration's start and its name — only for the rare file whose text
/// spells `endprogram` at all.
fn is_program(project: &Project, path: &Path, def: &Def) -> bool {
if !project.stamp(path).is_some_and(|stamp| stamp.program) {
return false;
}
let Ok(text) = std::fs::read_to_string(path) else {
return false;
};
let head = text.get(def.decl_span.start as usize..def.name_span.start as usize);
head.is_some_and(|head| head.split_whitespace().any(|word| word == "program"))
}
/// Every declaration of `name`, walking the roots once first when the index
/// holds none (a file written since the last walk).
pub fn declarations_walking(project: &mut Project, name: &str) -> Vec<Declaration> {
let found = declarations(project, name);
if found.is_empty() && project.ensure_walked_for_miss() {
return declarations(project, name);
}
found
}
/// The refusal for a name nothing declares: the near matches, when any.
pub fn no_declaration(project: &Project, name: &str) -> String {
let similar = similar(project, qualified(name).1, 20);
match similar.is_empty() {
true => format!("no declaration named `{name}`."),
false => format!("no declaration named `{name}`; similar: {}.", similar.join(", ")),
}
}
/// Up to `cap` declared names (and macros) that contain `name`, any case —
/// the declarations [`declarations`] would list, read from the same table.
pub fn similar(project: &Project, name: &str, cap: usize) -> Vec<String> {
let index = project.index();
let mut names: BTreeSet<String> =
index.workspace_symbols(name).iter().map(|hit| hit.name.to_string()).collect();
let part = Wanted::Containing(name.to_ascii_lowercase());
names.extend(declared(project, &part).into_iter().map(|local| local.name));
for at in 0..index.files().len() {
let Some(table) = index.defines(FileId(at as u32)) else { continue };
let found = table.entries().iter().filter(|d| contains_any_case(&d.name, name));
names.extend(found.map(|define| define.name.clone()));
}
names.into_iter().filter(|found| found != name).take(cap).collect()
}
/// Up to `cap` module or interface names that contain `name`, any case.
pub fn similar_units(index: &WorkspaceIndex, name: &str, cap: usize) -> Vec<String> {
let mut names: Vec<String> = index
.instantiable_units()
.map(|(unit, _)| unit)
.filter(|unit| contains_any_case(unit, name))
.map(str::to_string)
.collect();
names.dedup();
names.truncate(cap);
names
}
fn contains_any_case(text: &str, part: &str) -> bool {
text.to_ascii_lowercase().contains(&part.to_ascii_lowercase())
}
/// The refusal for a name declared more than once: every site, and what
/// picks one.
pub fn ambiguous(name: &str, found: &[&Declaration], pick: &str) -> String {
let sites: Vec<String> = found.iter().map(|d| format!("{}:{}", d.file, d.line)).collect();
format!("`{name}` is declared {} times ({}); {pick}.", sites.len(), sites.join(", "))
}
#[cfg(test)]
mod tests {
use super::qualified;
#[test]
fn a_unit_qualifies_a_name_and_an_escaped_name_is_whole() {
assert_eq!(qualified("core.state_q"), (Some("core"), "state_q"));
assert_eq!(qualified("pkg::W"), (Some("pkg"), "W"));
assert_eq!(qualified("a::b::c"), (Some("a::b"), "c"));
assert_eq!(qualified("state_q"), (None, "state_q"));
assert_eq!(qualified("\\a.b "), (None, "\\a.b "));
assert_eq!(qualified(".x"), (None, ".x"));
}
}
-416
View File
@@ -1,416 +0,0 @@
//! `definition` and `references`: where a name is declared, and every place
//! the declaration is used — the two questions an agent otherwise answers by
//! grepping and reading.
//!
//! Both take one selector ([`target`]): a position (`file` + `line` + `col`,
//! or `file` + `line` + the `name` written on that line), a name in a file
//! (`file` + `name`), or a bare `name` (with an optional `unit`) looked up in
//! the index. `definition` walks the server's ladder — an `` `include`` line,
//! a macro use, the file's own symbol table, the workspace overlay — and
//! lists every site, never a guess. `references` hands the declaration to
//! `vlog_refactor::find_references` over every indexed file
//! (`source::WholeSet`).
//! The selector itself is `select.rs`.
use std::path::{Path, PathBuf};
use serde_json::{json, Value};
use vlog_parser::token::{Token, TokenKind};
use vlog_semantic::{Def, Definition, DefinitionKey, Surface, Symbol, WorkspaceIndex};
use super::select::{macro_name, target, Target};
use super::source::{self, checked_site, Site, Texts, WholeSet};
use super::{Answer, Args, Param, Tool, Ty};
use crate::project::{Analysis, Project};
use crate::render::{self, DEFAULT_LIMIT};
/// The selector's arguments, shared by both tools.
const FILE: Param = Param {
name: "file",
ty: Ty::Str,
required: false,
description: "The file holding the position, relative to a root or absolute inside one.",
};
const LINE: Param = Param {
name: "line",
ty: Ty::Int { min: 1 },
required: false,
description: "1-based line in `file`; give `col` too, or the `name` written on that line.",
};
const COL: Param = Param {
name: "col",
ty: Ty::Int { min: 1 },
required: false,
description: "1-based column in bytes on `line`.",
};
const NAME: Param = Param {
name: "name",
ty: Ty::Str,
required: false,
description: "The name: alone, looked up across the project (`` `NAME`` for a macro); with `file`, its first occurrence there; with `file` and `line`, its occurrence on that line.",
};
const UNIT: Param = Param {
name: "unit",
ty: Ty::Str,
required: false,
description: "With a bare `name`: the module, interface, package or class declaring it.",
};
pub const DEFINITION: Tool = Tool {
name: "definition",
title: "Go to definition",
description: "Where a name is declared: every declaration site as file:line:col, its kind and the declaration's own source line (a name declared in several places lists them all, never a guess). Select by position (`file`, `line`, `col`), by `file`+`line`+`name`, or by `name` (and `unit`) across the project; also answers a macro use and an `include` line. Prefer it over grepping for the declaration.",
params: &[FILE, LINE, COL, NAME, UNIT],
rewalk: false,
handler: definition,
};
pub const REFERENCES: Tool = Tool {
name: "references",
title: "Find references",
description: "Every use of one declaration across the project, grouped by file as line:col and the line's text — the same occurrences a rename would edit. Select as for `definition`; a bare `name` must name one declaration. Refuses a name lucisv cannot resolve to one declaration, with the reason.",
params: &[
FILE,
LINE,
COL,
NAME,
UNIT,
Param {
name: "include_declaration",
ty: Ty::Bool,
required: false,
description: "List the declaration itself too (default true).",
},
Param {
name: "limit",
ty: Ty::Int { min: 1 },
required: false,
description: "Most hits to return (default 200).",
},
Param {
name: "offset",
ty: Ty::Int { min: 0 },
required: false,
description: "Hits to skip, for paging past `… and N more` (default 0).",
},
],
rewalk: true,
handler: references,
};
fn definition(project: &mut Project, args: &Args) -> Result<Answer, String> {
let sites = match target(project, args)? {
Target::At { path, analysis, offset } => at_position(project, &path, &analysis, offset)?,
Target::Named { name, unit } => {
let mut sites = by_name(project, &name, unit.as_deref());
if sites.is_empty() && project.ensure_walked_for_miss() {
sites = by_name(project, &name, unit.as_deref());
}
if sites.is_empty() {
return Err(format!(
"no declaration of `{name}`{} is indexed.",
in_unit(unit.as_deref())
));
}
sites
}
};
Ok(source::answer(&sites, "definitions", "no declaration"))
}
fn in_unit(unit: Option<&str>) -> String {
unit.map_or(String::new(), |unit| format!(" in `{unit}`"))
}
/// The server's ladder at one position: `` `include`` line, macro use, then
/// both symbol layers.
fn at_position(
project: &Project,
path: &Path,
analysis: &Analysis,
offset: u32,
) -> Result<Vec<Site>, String> {
let file = project.relative(path);
let (line, col) = analysis.lines.line_col(offset);
if let Some(token) = analysis.token_at(offset) {
if token.kind == TokenKind::Directive && token.text.starts_with("`include") {
return included(project, path, token).map(|site| vec![site]);
}
if let Some(name) = macro_name(token).filter(|_| token.is_macro()) {
return macro_sites(project, analysis, &file, name);
}
}
let external = analysis.external(project.index());
match external.definition_of(&analysis.semantics, offset) {
Some(Definition::Local(symbol)) if !symbol.name_span.is_empty() => {
Ok(local_sites(analysis, &file, symbol))
}
Some(Definition::External(defs)) => {
let reference = analysis.semantics.reference_at(offset);
let name = reference.map_or("", |reference| reference.name.as_str());
Ok(def_sites(project, defs, name))
}
_ => Err(format!("nothing at {file}:{line}:{col} names a declaration.")),
}
}
/// A local declaration: its completing declaration first (a non-ANSI port's
/// body line), then the name, then every redeclaration the binder folded
/// into it (`output y; wire y;` declares `y` twice) — one site per line.
fn local_sites(analysis: &Analysis, file: &str, symbol: &Symbol) -> Vec<Site> {
let (text, lines) = (&analysis.text, &analysis.lines);
let kind = render::kind(symbol.kind);
let detail = symbol.detail_span.filter(|span| !span.is_empty());
let mut sites: Vec<Site> = detail
.into_iter()
.chain([symbol.name_span])
.map(|span| Site::at(file.to_string(), text, lines, span, kind))
.collect();
let id = analysis.semantics.symbol_at(symbol.name_span.start);
for again in analysis.semantics.duplicates().iter().filter(|d| Some(d.first) == id) {
let site =
Site::at(file.to_string(), text, lines, again.name_span, render::kind(again.kind));
if !sites.iter().any(|known| known.line == site.line) {
sites.push(site);
}
}
sites
}
/// Indexed declarations of `name`, each checked against its file's bytes.
fn def_sites(project: &Project, defs: &[Def], name: &str) -> Vec<Site> {
let mut texts = Texts::default();
let mut sites: Vec<Site> = Vec::new();
for def in defs {
let Some(path) = project.index().path(def.file) else { continue };
let shown = def.detail_span.unwrap_or(def.name_span);
let kind = render::kind(def.kind);
let site = checked_site(project, &mut texts, path, def.name_span, shown, name, kind);
if let Some(site) = site {
if !sites.iter().any(|s| (&s.file, s.line, s.col) == (&site.file, site.line, site.col))
{
sites.push(site);
}
}
}
sites
}
/// An `` `include`` line: the named file beside the including one. No
/// include-directory ladder is searched.
fn included(project: &Project, path: &Path, token: &Token) -> Result<Site, String> {
let written = token.text.trim_start_matches("`include").trim();
let spelled = written.trim_matches(|c| c == '"' || c == '<' || c == '>');
let beside = path.parent().unwrap_or(Path::new("")).join(spelled);
let found = beside.to_str().and_then(|candidate| project.resolve(candidate).ok());
let Some(target) = found else {
return Err(format!(
"`include {written} is not beside `{}` (only the including file's directory is searched).",
project.relative(path)
));
};
let text = render::one_line(&token.text);
Ok(Site { file: project.relative(&target), line: 1, col: 1, kind: "include", text })
}
/// A macro use: this file's own last definition when it has one, else every
/// indexed definition (the include graph is not modelled, so none is picked).
fn macro_sites(
project: &Project,
analysis: &Analysis,
file: &str,
name: &str,
) -> Result<Vec<Site>, String> {
if let Some(define) = analysis.defines.latest(name) {
let (text, lines) = (&analysis.text, &analysis.lines);
return Ok(vec![Site::at(file.to_string(), text, lines, define.name_span, "define")]);
}
let sites = define_sites(project, name);
if sites.is_empty() {
return Err(format!("`{name} is not defined in any indexed file."));
}
Ok(sites)
}
/// Every indexed `` `define`` of `name`.
pub(super) fn define_sites(project: &Project, name: &str) -> Vec<Site> {
let index = project.index();
let mut texts = Texts::default();
index
.find_define(name)
.into_iter()
.filter_map(|(file, define)| {
let path = index.path(file)?;
let span = define.name_span;
checked_site(project, &mut texts, path, span, span, name, "define")
})
.collect()
}
/// Declarations by name: a unit's member when `unit` is given, else every
/// unit, exported member and module internal of that name; a macro when the
/// name is written `` `NAME`` or nothing else declares it.
fn by_name(project: &Project, name: &str, unit: Option<&str>) -> Vec<Site> {
if let Some(spelled) = name.strip_prefix('`') {
return define_sites(project, spelled);
}
let defs = declarations(project.index(), name, unit);
let sites = def_sites(project, &defs, name);
if sites.is_empty() && unit.is_none() {
return define_sites(project, name);
}
sites
}
/// Every indexed declaration of `name` (in `unit`, when given).
fn declarations(index: &WorkspaceIndex, name: &str, unit: Option<&str>) -> Vec<Def> {
if let Some(unit) = unit {
return index.member_in(unit, name, Surface::Hierarchical).to_vec();
}
let mut defs: Vec<Def> = index.units(name).to_vec();
let exported = index.workspace_symbols(name);
let members = exported.iter().filter(|hit| hit.name == name && hit.container.is_some());
defs.extend(members.map(|hit| hit.def.clone()));
defs.extend(index.hierarchical_declarations(name).map(|(_, def)| def.clone()));
let mut seen = std::collections::HashSet::new();
defs.retain(|def| seen.insert(DefinitionKey::of(def)));
defs
}
fn references(project: &mut Project, args: &Args) -> Result<Answer, String> {
let (path, analysis, offset) = match target(project, args)? {
Target::At { path, analysis, offset } => (path, analysis, offset),
Target::Named { name, unit } => {
let (path, offset) = declaration_position(project, &name, unit.as_deref())?;
let analysis = project.analysis(&path)?;
(path, analysis, offset)
}
};
if let Some(name) = analysis.token_at(offset).filter(|t| t.is_macro()).and_then(macro_name) {
return Err(format!("`{name} is a macro; {MACRO_REFUSAL}"));
}
let set = WholeSet::read(project, Some(&path));
let include = args.flag("include_declaration", true);
let found = vlog_refactor::find_references(&set.files, &path, offset, include)
.map_err(engine_refusal)?;
let partial = set.warning(project);
let mut texts = Texts::default();
for (held, text) in set.files {
texts.hold(held, text);
}
let hits: Vec<Site> = found
.iter()
.filter_map(|(file, span)| {
let (text, lines) = texts.get(file)?;
Some(Site::at(project.relative(file), text, lines, *span, "use"))
})
.collect();
let mut answer = render_hits(&hits, args);
// A file the index skipped was not searched: the census is partial.
if let Some(partial) = partial {
answer.text.push_str(&format!("warning: {partial}\n"));
answer.structured["warning"] = Value::from(partial);
}
Ok(answer)
}
/// The one declaration a bare `name` selects for `references` (and `rename`).
pub(super) fn declaration_position(
project: &mut Project,
name: &str,
unit: Option<&str>,
) -> Result<(PathBuf, u32), String> {
let mut defs = declarations(project.index(), name, unit);
if defs.is_empty() && project.ensure_walked_for_miss() {
defs = declarations(project.index(), name, unit);
}
let sites = def_sites(project, &defs, name);
match (defs.as_slice(), sites.len()) {
([def], 1) => {
let path = project.index().path(def.file).map(Path::to_path_buf);
path.map(|path| (path, def.name_span.start))
.ok_or_else(|| format!("`{name}`'s file is no longer indexed."))
}
(_, 0)
if unit.is_none()
&& !define_sites(project, name.trim_start_matches('`')).is_empty() =>
{
Err(format!("`{name}` is a macro; {MACRO_REFUSAL}"))
}
(_, 0) => Err(format!("no declaration of `{name}`{} is indexed.", in_unit(unit))),
_ => {
let listed: Vec<String> =
sites.iter().map(|site| format!("{}:{}", site.file, site.line)).collect();
Err(format!(
"`{name}` is declared {} times ({}); pick one with `file` and `line`.",
listed.len(),
listed.join(", ")
))
}
}
}
/// Why `references` does not answer for a macro.
const MACRO_REFUSAL: &str =
"references follows declarations, not macros (`defines` lists its definitions).";
/// The engine's refusal, said as ours: prefixed, and its rename wording —
/// `find_references` shares the rename's resolution — turned into this
/// tool's.
fn engine_refusal(sentence: String) -> String {
const REWORDED: &[(&str, &str)] = &[
("there is no symbol to rename at this position", "there is no symbol at this position"),
(
"nothing outside the project scope can be renamed",
"nothing outside the project scope is followed",
),
("lucisv found nothing to rename for", "lucisv found no occurrence of"),
("the rename was abandoned", "the search was abandoned"),
("which declaration this rename means", "which declaration this position means"),
(", so a rename here would only be half a rename", ", so its uses cannot all be listed"),
];
let mut out = sentence;
for (from, to) in REWORDED {
out = out.replace(from, to);
}
format!("lucisv cannot follow this position: {out}")
}
/// Hits grouped by file, `line:col text`, paged.
fn render_hits(hits: &[Site], args: &Args) -> Answer {
let (shown, rest) =
render::page(hits, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
let entries: Vec<(String, String)> = shown
.iter()
.map(|hit| (hit.file.clone(), format!("{}:{} {}", hit.line, hit.col, hit.text)))
.collect();
let mut text = render::grouped(&entries);
render::more(&mut text, rest);
if hits.is_empty() {
text = "no references\n".to_string();
}
let listed: Vec<Value> = shown
.iter()
.map(|hit| json!({ "file": hit.file, "line": hit.line, "col": hit.col, "text": hit.text }))
.collect();
Answer { text, structured: json!({ "hits": listed, "total": hits.len() }) }
}
#[cfg(test)]
mod tests {
use super::engine_refusal;
#[test]
fn engine_refusals_are_prefixed_and_never_speak_of_renaming() {
for sentence in [
"there is no symbol to rename at this position.",
"`x` is declared outside the files lucisv indexes, so a rename here would only be half a rename.",
"lucisv found nothing to rename for `x`.",
"`x` is declared in more than one indexed file; lucisv will not guess which declaration this rename means.",
] {
let said = engine_refusal(sentence.to_string());
assert!(said.starts_with("lucisv cannot follow this position: "), "{said}");
assert!(!said.contains("rename"), "{said}");
}
}
}
+61
View File
@@ -0,0 +1,61 @@
//! `outline`: a file's declarations as a tree with line ranges (its parse
//! errors first), or — for `unit` — what a unit offers the code that uses
//! it (`interface.rs`), so an agent reads the shape before the source.
use vlog_semantic::DocumentSymbol;
use super::interface;
use super::{Answer, Args, Param, Tool, Ty};
use crate::project::{Analysis, Project};
use crate::render;
/// The most lines an answer holds before `… and N more`.
pub const CAP: usize = 300;
pub const OUTLINE: Tool = Tool {
name: "outline",
description: "Exactly one of: `file`, its declarations as a tree with line ranges, parse errors first; `unit`, its file:line, parameters and ports in order (modports, package members).",
params: &[
Param { name: "file", ty: Ty::Str, required: false },
Param { name: "unit", ty: Ty::Str, required: false },
],
rewalk: false,
handler: outline,
};
fn outline(project: &mut Project, args: &Args) -> Result<Answer, String> {
let lines = match (args.str("file"), args.str("unit")) {
(Some(file), None) => file_outline(project, file)?,
(None, Some(unit)) => interface::unit_outline(project, unit.trim())?,
_ => return Err("give exactly one of `file` and `unit`.".into()),
};
Ok(Answer::lines(render::capped(lines, CAP)))
}
/// `error LINE: message` per parse error, then `kind name first–last`,
/// two spaces per level.
pub fn file_outline(project: &mut Project, file: &str) -> Result<Vec<String>, String> {
let path = project.resolve(file)?;
let analysis = project.analysis(&path)?;
let mut lines: Vec<String> = analysis
.diagnostics
.iter()
.map(|error| format!("error {}: {}", error.line, render::one_line(&error.message)))
.collect();
tree(&analysis, &analysis.semantics.document_symbols(), 0, &mut lines);
Ok(lines)
}
/// The outline tree in pre-order.
fn tree(analysis: &Analysis, nodes: &[DocumentSymbol], level: usize, out: &mut Vec<String>) {
for node in nodes {
let Some(symbol) = analysis.semantics.symbol(node.symbol) else {
continue;
};
let (first, last) = analysis.line_span(symbol.decl_span.start, symbol.decl_span.end);
let (kind, name) = (render::kind(symbol.kind), &symbol.name);
let indent = " ".repeat(level);
out.push(format!("{indent}{kind} {name} {}", render::lines(first, last)));
tree(analysis, &node.children, level + 1, out);
}
}
+448
View File
@@ -0,0 +1,448 @@
//! `port`'s `after`: the new port placed right after a named one, in the
//! layout of the line it follows, and each named connection placed right
//! after the instance's `.after(…)`.
//!
//! The engine (`vlog_refactor::add_port`) only appends. So it runs first,
//! unchanged, and its verified edit is the reference: this module moves the
//! header's new element, and each instance's new connection, to the slot
//! after the anchor's separator ([`slot`]) — and then checks that the
//! result is the engine's result with elements moved and nothing else
//! ([`verify`]).
//!
//! What it refuses (the engine's refusals come first): a non-ANSI or empty
//! port list; a port list, or the connection list of an instance it would
//! place into, holding an element the parser could not read (it cannot see
//! what that element inherits or binds — QA finding 5); an `after` that is
//! not a port; a next port that would inherit from the new one; an anchor
//! inside an `` `ifdef`` arm; and a positional instantiation unless `after`
//! is the last port. An instance whose connection cannot be placed (no
//! `.after(…)`, an `` `ifdef`` around it) keeps the engine's appended
//! connection and is said under `warnings`.
mod slot;
mod verify;
use std::path::{Path, PathBuf};
use vlog_parser::ast::{AnsiPort, Connections, Instance, Item, ItemKind, ListDirective};
use vlog_parser::ast::{ListElem, Module, PortList, RawText};
use vlog_parser::span::TextRange;
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::{parse_source_tolerant, tokenize};
use vlog_refactor::{RefactorEdit, TextEdit};
use super::read_item::child_items;
use crate::render::one_line;
use slot::{aligned_connection, aligned_port, slot};
/// What is being placed: the module, where it is written, the anchor port,
/// the new port's name and declaration, and how a file is named in a
/// sentence (root-relative, as every answer names it).
pub struct Spec<'a> {
pub module: &'a str,
pub file: &'a Path,
pub after: &'a str,
pub port: &'a str,
pub declaration: &'a str,
pub show: &'a dyn Fn(&Path) -> String,
}
/// The engine's appending `edit`, re-placed after `spec.after` and
/// verified against it; the warnings name each instance left appended.
pub fn after(
files: &[(PathBuf, String)],
edit: &RefactorEdit,
spec: &Spec,
) -> Result<RefactorEdit, String> {
let home = text_of(files, spec.file)?;
let (tree, _) = parse_source_tolerant(home);
let module = find_module(&tree.items, spec.module)
.ok_or_else(|| format!("lucisv can no longer find `{}`.", spec.module))?;
let (header, region, last_port) = header(home, module, spec)?;
let mut placed = RefactorEdit { warnings: edit.warnings.clone(), ..RefactorEdit::default() };
for (path, edits) in &edit.edits {
let mut kept: Vec<TextEdit> = edits.clone();
if path == spec.file {
kept.retain(|edit| !region.contains(edit.range.start));
kept.extend(header.iter().cloned());
}
let text = text_of(files, path)?;
let tokens = lexed(text, spec, path)?;
let (tree, _) = parse_source_tolerant(text);
let mut instances = Vec::new();
collect_instances(&tree.items, spec.module, &mut instances);
for instance in instances {
let inside = |edit: &TextEdit| {
instance.span.start <= edit.range.start && edit.range.start <= instance.span.end
};
let appended: Vec<TextEdit> = kept.iter().filter(|e| inside(e)).cloned().collect();
if appended.is_empty() || positional(instance, last_port, spec, path)? {
continue;
}
let at = || format!("`{}` in {}", instance.name, (spec.show)(path));
if let Some(raw) = unreadable_connection(instance) {
return Err(unreadable(&at(), raw));
}
match connection(text, &tokens, instance, &appended, spec) {
Ok(edits) => {
kept.retain(|edit| !inside(edit));
kept.extend(edits);
}
Err(why) => placed.warnings.push(format!(
"{}: the connection of `{}` was appended at the end ({why}).",
at(),
spec.port
)),
}
}
kept.sort_by_key(|edit| (edit.range.start, edit.range.end));
placed.edits.push((path.clone(), kept));
}
verify::verify(files, edit, &placed, spec)?;
Ok(placed)
}
fn text_of<'f>(files: &'f [(PathBuf, String)], path: &Path) -> Result<&'f str, String> {
files
.iter()
.find(|(held, _)| held == path)
.map(|(_, text)| text.as_str())
.ok_or_else(|| format!("the edit names `{}`, which was not read", path.display()))
}
fn lexed(text: &str, spec: &Spec, path: &Path) -> Result<Vec<Token>, String> {
tokenize(text).map_err(|_| format!("{} does not lex.", (spec.show)(path)))
}
/// The module called `name`, looked for in modules and packages.
fn find_module<'t>(items: &'t [Item], name: &str) -> Option<&'t Module> {
items.iter().find_map(|item| match &item.kind {
ItemKind::Module(module) if module.name == name => Some(module),
ItemKind::Module(module) => find_module(&module.items, name),
ItemKind::Package { items, .. } => find_module(items, name),
_ => None,
})
}
/// Every instance of `module` in `items`, generate blocks and `bind`s
/// included.
fn collect_instances<'t>(items: &'t [Item], module: &str, out: &mut Vec<&'t Instance>) {
for item in items {
match &item.kind {
ItemKind::Instantiation(inst) if inst.module == module => out.extend(&inst.instances),
ItemKind::Bind(bind) if bind.inst.module == module => out.extend(&bind.inst.instances),
kind => child_items(kind).into_iter().for_each(|c| collect_instances(c, module, out)),
}
}
}
/// Whether `next`, written right after the new port (directed `new_dir`,
/// placed after an anchor directed `anchor_dir`), would take something
/// from it that it took from the anchor before: with neither direction nor
/// type it inherits both; with a type but no direction, the direction —
/// harmless only when the two directions are the same. A modport port
/// (`bus_if.mp bus`) has no direction to inherit (QA finding 3); an
/// unreadable element cannot be judged.
fn inherits(next: &ListElem<AnsiPort>, new_dir: Option<&str>, anchor_dir: Option<&str>) -> bool {
let ListElem::Ok(next) = next else { return true };
if next.dir.is_some() {
return false;
}
if next.ty.is_implicit() && next.net.is_none() {
return true;
}
let modport = next.ty.name.contains('.');
!modport && (new_dir.is_none() || new_dir != anchor_dir)
}
/// The header edit placing the new port after the anchor, the port list's
/// bytes (where the engine's appended element lands), and whether the
/// anchor is the last port.
fn header(
text: &str,
module: &Module,
spec: &Spec,
) -> Result<(Vec<TextEdit>, TextRange, bool), String> {
let PortList::Ansi(ports) = &module.ports else {
return Err(format!(
"`after` places a port in an ANSI port list, and `{}` has none; omit `after`.",
spec.module
));
};
// `index` counts every element, readable or not, as
// `ListDirective::before` does (QA finding 5b).
let found = ports.iter().enumerate().find_map(|(index, element)| {
element.ok().filter(|port| port.name == spec.after).map(|port| (index, port))
});
let Some((index, anchor)) = found else {
return Err(no_such_port(ports, spec));
};
if !balanced_before(&module.port_directives, index) {
return Err(format!(
"`{}` sits inside an `ifdef arm of the port list, so a port placed after it would exist in one configuration only; place it by hand.",
spec.after
));
}
if let Some(raw) = ports.iter().find_map(error_of) {
return Err(unreadable(&format!("`{}`'s port list", spec.module), raw));
}
let (new_dir, anchor_dir) = (new_direction(spec.declaration), anchor.dir.as_deref());
let inheriting = |next: &&ListElem<AnsiPort>| inherits(next, new_dir.as_deref(), anchor_dir);
if let Some(next) = ports.get(index + 1).filter(inheriting) {
let name = next.ok().map_or("", |port| port.name.as_str());
return Err(format!(
"`{name}` takes its direction (or type) from the port before it, so a port placed after `{}` would change it; name another `after`.",
spec.after
));
}
let tokens = lexed(text, spec, spec.file)?;
let at = slot(text, &tokens, anchor.span)
.map_err(|why| format!("after `{}`, {why}.", spec.after))?;
let element = match &at.line {
Some(line) => aligned_port(text, line, anchor, spec.declaration),
None => one_line(spec.declaration),
};
let region = list_region(&tokens, ports)?;
Ok((at.edits(&element), region, index + 1 == ports.len()))
}
/// The refusal for an `after` no readable port is named.
fn no_such_port(ports: &[ListElem<AnsiPort>], spec: &Spec) -> String {
let names: Vec<&str> = ports.iter().filter_map(ListElem::ok).map(|p| p.name.as_str()).collect();
let more = if names.len() > 12 { ", …" } else { "" };
let shown = names.iter().take(12).copied().collect::<Vec<_>>().join(", ");
format!("`{}` has no port `{}` (its ports: {shown}{more}).", spec.module, spec.after)
}
/// The direction keyword a declaration starts with.
fn new_direction(declaration: &str) -> Option<String> {
let tokens = tokenize(declaration).ok()?;
tokens.first().filter(|t| t.kind == TokenKind::Keyword).map(|t| t.text.clone())
}
/// The refusal for an element the parser could not read.
fn unreadable(list: &str, raw: &RawText) -> String {
format!(
"{list} holds `{}`, which lucisv cannot read, so it cannot tell what a port placed beside it would change; nothing written — omit `after` or place the port by hand.",
crate::tools::source::capped(&raw.text, 80)
)
}
/// The first element of an instance's connection list the parser could not
/// read.
fn unreadable_connection(instance: &Instance) -> Option<&RawText> {
match &instance.conns {
Connections::Named(conns) => conns.iter().find_map(error_of),
Connections::Ordered(conns) => conns.iter().find_map(error_of),
}
}
fn error_of<T>(element: &ListElem<T>) -> Option<&RawText> {
match element {
ListElem::Error(raw) => Some(raw),
ListElem::Ok(_) => None,
}
}
/// Whether the `` `ifdef``s written before element `index + 1` of a list
/// are all closed again — an element inserted there is unconditional.
/// `index` counts every element of the list, as `ListDirective::before`
/// does.
fn balanced_before(directives: &[ListDirective], index: usize) -> bool {
let mut depth = 0i32;
for directive in directives.iter().filter(|d| d.before <= index) {
match directive.raw.text.split_whitespace().next().unwrap_or_default() {
"`ifdef" | "`ifndef" => depth += 1,
"`endif" => depth -= 1,
_ => {}
}
}
depth == 0
}
/// The bytes from the first port to the port list's `)`.
fn list_region(tokens: &[Token], ports: &[ListElem<AnsiPort>]) -> Result<TextRange, String> {
let span = |element: &ListElem<AnsiPort>| match element {
ListElem::Ok(port) => port.span,
ListElem::Error(raw) => raw.span,
};
let (Some(first), Some(last)) = (ports.first().map(span), ports.last().map(span)) else {
return Err("lucisv cannot find this module's port list.".to_string());
};
let close = tokens
.iter()
.find(|t| t.span.start >= last.end && t.kind == TokenKind::Symbol && t.text == ")")
.ok_or_else(|| "lucisv cannot find where this module's port list ends.".to_string())?;
Ok(TextRange::new(first.start, close.span.end))
}
/// Whether an instance connects by position — its appended connection
/// stays where the engine put it, which is right only when the new port is
/// last; anywhere else it is refused.
fn positional(
instance: &Instance,
last_port: bool,
spec: &Spec,
path: &Path,
) -> Result<bool, String> {
match &instance.conns {
Connections::Ordered(_) if last_port => Ok(true),
Connections::Ordered(_) => Err(format!(
"`{}` in {} connects `{}` by position, so a port placed after `{}` would shift every later connection; give it named connections first, or omit `after`.",
instance.name,
(spec.show)(path),
spec.module,
spec.after
)),
Connections::Named(_) => Ok(false),
}
}
/// The edit placing one instance's new connection after `.after(…)`, its
/// expression taken from the engine's appended one.
fn connection(
text: &str,
tokens: &[Token],
instance: &Instance,
appended: &[TextEdit],
spec: &Spec,
) -> Result<Vec<TextEdit>, String> {
let Connections::Named(conns) = &instance.conns else {
return Err("a positional list".to_string());
};
let found = conns.iter().enumerate().find_map(|(index, conn)| {
conn.ok().filter(|conn| conn.name == spec.after).map(|conn| (index, conn))
});
let Some((index, anchor)) = found else {
return Err(format!("it does not connect `.{}`", spec.after));
};
if !balanced_before(&instance.conn_directives, index) {
return Err(format!("`.{}` sits inside an `ifdef arm", spec.after));
}
let written: String = appended.iter().map(|edit| edit.new_text.as_str()).collect();
let expr = appended_expr(&written, spec.port)
.ok_or_else(|| "lucisv could not read the appended connection".to_string())?;
let at = slot(text, tokens, anchor.span)?;
let element = match &at.line {
Some(line) => aligned_connection(text, line, anchor, spec.port, &expr),
None => format!(".{}({expr})", spec.port),
};
Ok(at.edits(&element))
}
/// The expression inside the engine's appended `.port(expr)`.
fn appended_expr(written: &str, port: &str) -> Option<String> {
let open = written.find(&format!(".{port}("))? + port.len() + 2;
let mut depth = 1usize;
for (offset, c) in written[open..].char_indices() {
match c {
'(' => depth += 1,
')' if depth == 1 => return Some(written[open..open + offset].trim().to_string()),
')' => depth -= 1,
_ => {}
}
}
None
}
/// The port a declaration's tokens name: the last identifier outside
/// brackets before any `=` default.
pub fn port_name(tokens: &[Token]) -> Option<&Token> {
let mut depth = 0usize;
let mut name = None;
for token in tokens {
match (token.kind, token.text.as_str()) {
(TokenKind::Symbol, "[" | "(" | "{") => depth += 1,
(TokenKind::Symbol, "]" | ")" | "}") => depth = depth.saturating_sub(1),
(TokenKind::Symbol, "=") if depth == 0 => break,
(TokenKind::Ident, _) if depth == 0 && !token.is_macro() => name = Some(token),
_ => {}
}
}
name
}
#[cfg(test)]
mod tests {
use super::*;
use crate::apply::Plan;
const TOP: &str = "module top(input logic a, output logic y);\n m u_m (\n .a (a), // in\n .y (y)\n );\nendmodule\n";
fn design(header: &str) -> Vec<(PathBuf, String)> {
let m = format!("module m (\n{header}\n);\nendmodule\n");
vec![(PathBuf::from("/d/m.sv"), m), (PathBuf::from("/d/top.sv"), TOP.to_string())]
}
fn show(path: &Path) -> String {
path.file_name().map_or(String::new(), |name| name.to_string_lossy().into_owned())
}
fn spec<'a>(after: &'a str) -> Spec<'a> {
let (file, declaration) = (Path::new("/d/m.sv"), "input logic en");
Spec { module: "m", file, after, port: "en", declaration, show: &show }
}
fn engine(files: &[(PathBuf, String)]) -> RefactorEdit {
vlog_refactor::add_port(files, vlog_refactor::ModuleRef::Name("m"), "input logic en")
.unwrap()
}
fn texts(files: &[(PathBuf, String)], edit: &RefactorEdit) -> Vec<String> {
let plan = Plan::from_refactor(edit.clone(), files).unwrap();
plan.changes.into_iter().map(|change| change.after).collect()
}
fn refusal(files: &[(PathBuf, String)], after_port: &str) -> String {
after(files, &engine(files), &spec(after_port)).err().unwrap_or_default()
}
#[test]
fn a_placed_port_and_connection_follow_their_anchors() {
let files = design(" input logic a, // first\n output logic y");
let placed = after(&files, &engine(&files), &spec("a")).unwrap();
let [m, top] = texts(&files, &placed).try_into().unwrap();
let header = " input logic a, // first\n input logic en,\n output logic y\n";
assert_eq!(m, format!("module m (\n{header});\nendmodule\n"));
// `top` has no `en`: the engine's placeholder, placed.
let placed = " .a (a), // in\n .en (/* TODO: connect */),\n .y (y)\n";
assert!(top.contains(placed), "{top}");
}
#[test]
fn what_a_placement_cannot_see_or_would_change_is_refused() {
let inherit = refusal(&design(" input logic [7:0] a, b,\n output logic y"), "a");
assert!(inherit.contains("`b` takes its direction"), "{inherit}");
let typed = refusal(&design(" output logic a, logic [3:0] b,\n output logic y"), "a");
assert!(typed.contains("`b` takes its direction"), "{typed}");
let arm = refusal(&design("`ifdef X\n input logic a,\n`endif\n output logic y"), "a");
assert!(arm.contains("inside an `ifdef arm"), "{arm}");
let hidden =
refusal(&design(" input logic [7:0] a,\n (* keep *) b,\n output logic y"), "a");
assert!(hidden.contains("`m`'s port list holds `(* keep *) b`"), "{hidden}");
let mut files = design(" input logic a,\n output logic y");
files[1].1 =
"module top(input logic a, en, output logic y);\n m u_m (a, y);\nendmodule\n".into();
let edit = engine(&files);
let refused = after(&files, &edit, &spec("a")).unwrap_err();
assert!(refused.contains("`u_m` in top.sv connects `m` by position"), "{refused}");
assert!(after(&files, &edit, &spec("y")).is_ok(), "last is fine");
}
#[test]
fn a_modport_or_a_same_directed_typed_port_after_the_anchor_is_placed() {
let files = design(" input logic a,\n bus_if.mp bus,\n output logic y");
assert!(after(&files, &engine(&files), &spec("a")).is_ok());
let files = design(" input logic a, logic [3:0] b,\n output logic y");
assert!(after(&files, &engine(&files), &spec("a")).is_ok());
}
#[test]
fn the_engines_appended_expression_is_read_back() {
assert_eq!(appended_expr(",\n .dbg_i(dbg_i)", "dbg_i").as_deref(), Some("dbg_i"));
let todo = appended_expr(", .d(/* TODO: connect */)", "d");
assert_eq!(todo.as_deref(), Some("/* TODO: connect */"));
assert_eq!(appended_expr(".d(f(a))", "d").as_deref(), Some("f(a)"));
assert_eq!(appended_expr(".e(x)", "d"), None);
}
}
+306
View File
@@ -0,0 +1,306 @@
//! Where a new list element goes after its anchor, and how it is written.
//!
//! The element always goes **after the separator that follows the anchor**
//! — past the anchor's `,` (and any comment on that comma's line), or, for
//! a last anchor, after a `,` added at the anchor's end and past the
//! comments on its line — never at the anchor's end, where it would take
//! over a comment written between the anchor and its comma (QA finding 1).
//! A new line copies the anchor's indentation and line ending, and, when
//! the anchor stands alone on its line, its column layout.
use vlog_parser::ast::{AnsiPort, Connection};
use vlog_parser::span::TextRange;
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::tokenize;
use vlog_refactor::TextEdit;
use crate::render::one_line;
/// The line an anchor starts on: where it starts, its indentation, and
/// whether the anchor is the first thing on it.
pub struct AnchorLine {
start: usize,
indent: String,
alone: bool,
}
/// Where the new element is written: a `,` at `comma_at` when the anchor
/// was last, then `prefix element suffix` at `at`. `line` is the anchor's
/// line when the element gets a line of its own in the anchor's layout.
pub struct Slot {
comma_at: Option<u32>,
at: u32,
prefix: String,
suffix: &'static str,
pub line: Option<AnchorLine>,
}
impl Slot {
/// The insertions writing `element` here.
pub fn edits(&self, element: &str) -> Vec<TextEdit> {
let at = |offset: u32| TextRange::new(offset, offset);
let mut edits: Vec<TextEdit> = self
.comma_at
.map(|comma| TextEdit { range: at(comma), new_text: ",".to_string() })
.into_iter()
.collect();
let new_text = format!("{}{element}{}", self.prefix, self.suffix);
edits.push(TextEdit { range: at(self.at), new_text });
edits
}
}
/// The slot after the element spanning `anchor`, read off the file's
/// tokens: the anchor must be followed by its list's `,` or `)`.
pub fn slot(text: &str, tokens: &[Token], anchor: TextRange) -> Result<Slot, String> {
let index = tokens.iter().position(|t| t.span.start >= anchor.end);
let next = index.and_then(|i| tokens.get(i)).filter(|t| t.kind == TokenKind::Symbol);
let line = anchor_line(text, anchor.start as usize);
match next.map(|t| t.text.as_str()) {
Some(",") => {
let comma = next.map_or(anchor.end, |t| t.span.end);
let following = index.and_then(|i| tokens.get(i + 1));
let Some(following) = following.filter(|t| starts_line(text, t.span.start as usize))
else {
// The next element shares the comma's line: `a, en, b`.
let suffix = ",";
return Ok(Slot {
comma_at: None,
at: comma,
prefix: " ".into(),
suffix,
line: None,
});
};
let (at, newline) = line_end(text, comma as usize, tokens);
let indent = match line.alone {
true => line.indent.clone(),
false => indentation(text, following.span.start as usize),
};
let prefix = format!("{newline}{indent}");
let line = line.alone.then_some(line);
Ok(Slot { comma_at: None, at, prefix, suffix: ",", line })
}
Some(")") => {
let close = next.map_or(anchor.end, |t| t.span.start);
let between = &text[anchor.end as usize..close as usize];
if starts_line(text, close as usize) {
let (at, newline) = line_end(text, anchor.end as usize, tokens);
let prefix = format!("{newline}{}", line.indent);
let line = line.alone.then_some(line);
return Ok(Slot { comma_at: Some(anchor.end), at, prefix, suffix: "", line });
}
if between.trim().is_empty() {
let prefix = ", ".to_string();
return Ok(Slot { comma_at: None, at: anchor.end, prefix, suffix: "", line: None });
}
// A comment between the last anchor and `)`: it stays the anchor's.
let prefix = " ".to_string();
Ok(Slot { comma_at: Some(anchor.end), at: close, prefix, suffix: "", line: None })
}
_ => Err("lucisv cannot find the `,` or `)` after it".to_string()),
}
}
fn anchor_line(text: &str, from: usize) -> AnchorLine {
let start = text[..from].rfind('\n').map_or(0, |at| at + 1);
let before = &text[start..from];
let alone = before.chars().all(|c| c == ' ' || c == '\t');
AnchorLine { start, indent: indentation(text, from), alone }
}
/// The blanks a line starts with, the line holding `offset`.
fn indentation(text: &str, offset: usize) -> String {
let start = text[..offset].rfind('\n').map_or(0, |at| at + 1);
text[start..].chars().take_while(|c| *c == ' ' || *c == '\t').collect()
}
/// Whether only blanks precede `offset` on its line.
fn starts_line(text: &str, offset: usize) -> bool {
let start = text[..offset].rfind('\n').map_or(0, |at| at + 1);
text[start..offset].chars().all(|c| c == ' ' || c == '\t')
}
/// The end of the line `from` is on — past any comment that closes on a
/// later line — before its line ending, and that line ending.
fn line_end(text: &str, from: usize, tokens: &[Token]) -> (u32, &'static str) {
let comments: Vec<TextRange> = tokens
.iter()
.flat_map(|t| t.leading.iter().chain(t.trailing.as_ref()))
.map(|comment| comment.span)
.collect();
let mut at = from;
loop {
let newline = text[at..].find('\n').map_or(text.len(), |found| at + found);
match comments.iter().find(|c| (c.start as usize) < newline && newline < c.end as usize) {
Some(comment) => at = comment.end as usize,
None => {
return match text[..newline].strip_suffix('\r') {
Some(_) => ((newline - 1) as u32, "\r\n"),
None => (newline as u32, "\n"),
}
}
}
}
}
/// Character columns on the anchor's line.
fn column(text: &str, line: &AnchorLine, offset: usize) -> usize {
text[line.start..offset].chars().count()
}
/// `out` (which follows the line's indentation) padded so its end reaches
/// `col`; one space when it is already past or there is no column.
fn pad_to(out: &mut String, line: &AnchorLine, col: Option<usize>) {
let width = line.indent.chars().count() + out.chars().count();
match col {
Some(col) if width < col => out.push_str(&" ".repeat(col - width)),
_ => out.push(' '),
}
}
/// The declaration in the anchor's layout (without the indentation):
/// direction, type and name each at the anchor's column when the text
/// before it fits, else one space apart.
pub fn aligned_port(text: &str, line: &AnchorLine, anchor: &AnsiPort, declaration: &str) -> String {
let declaration = declaration.trim();
let (Some(parts), Some(dir)) = (split_declaration(declaration), anchor.dir.as_deref()) else {
return one_line(declaration);
};
let dir_end = anchor.span.start as usize + dir.len();
if text.get(anchor.span.start as usize..dir_end) != Some(dir) {
return one_line(declaration);
}
let type_at = dir_end + (text[dir_end..].len() - text[dir_end..].trim_start().len());
let name_at = anchor.name_span.start as usize;
let type_col = (type_at < name_at).then(|| column(text, line, type_at));
let mut out = parts.dir.to_string();
if !parts.ty.is_empty() {
pad_to(&mut out, line, type_col);
out.push_str(&one_line(parts.ty));
}
pad_to(&mut out, line, Some(column(text, line, name_at)));
out.push_str(&one_line(parts.rest));
out
}
/// The connection `.port(expr)` in the anchor's layout: the `(` and the `)`
/// at the anchor's columns when they fit, the anchor's blanks inside them.
pub fn aligned_connection(
text: &str,
line: &AnchorLine,
anchor: &Connection,
port: &str,
expr: &str,
) -> String {
let plain = format!(".{port}({expr})");
let Some(value) = anchor.expr.as_ref().filter(|_| anchor.after_dot.is_empty()) else {
return plain;
};
let name_end = anchor.name_span.end as usize;
let open = name_end + (text[name_end..].len() - text[name_end..].trim_start().len());
let close = (anchor.span.end as usize).saturating_sub(1);
let (start, end) = (value.span.start as usize, value.span.end as usize);
let blank = |from: usize, to: usize| {
text.get(from..to).filter(|gap| gap.chars().all(|c| c == ' ' || c == '\t'))
};
let (Some(before_open), Some(inside), Some(_)) =
(blank(name_end, open), blank(open + 1, start), blank(end, close))
else {
return plain;
};
if text.get(open..open + 1) != Some("(") || text.get(close..close + 1) != Some(")") {
return plain;
}
let mut out = format!(".{port}");
// An anchor that glues its `(` to the name is followed; else aligned.
if !before_open.is_empty() {
pad_to(&mut out, line, Some(column(text, line, open)));
}
out.push('(');
out.push_str(inside);
out.push_str(expr);
let width = line.indent.chars().count() + out.chars().count();
let close_col = column(text, line, close);
match width < close_col {
true => out.push_str(&" ".repeat(close_col - width)),
false => out.push_str(inside),
}
out.push(')');
out
}
/// A declaration split where a layout puts its columns: the direction, the
/// type between it and the name, and the name with what follows it.
struct Parts<'a> {
dir: &'a str,
ty: &'a str,
rest: &'a str,
}
fn split_declaration(declaration: &str) -> Option<Parts<'_>> {
let tokens = tokenize(declaration).ok()?;
let dir = tokens.first().filter(|t| t.kind == TokenKind::Keyword)?;
let name = super::port_name(&tokens)?;
let (dir_end, name_start) = (dir.span.end as usize, name.span.start as usize);
Some(Parts {
dir: &declaration[..dir_end],
ty: declaration[dir_end..name_start].trim(),
rest: declaration[name_start..].trim(),
})
}
#[cfg(test)]
mod tests {
use super::*;
/// `text` with `element` written in the slot after `anchor`.
fn placed(text: &str, anchor: &str, element: &str) -> String {
let tokens = tokenize(text).unwrap();
let start = text.find(anchor).unwrap() as u32;
let span = TextRange::new(start, start + anchor.len() as u32);
let slot = slot(text, &tokens, span).unwrap();
let mut out = text.to_string();
for edit in slot.edits(element).iter().rev() {
out.insert_str(edit.range.start as usize, &edit.new_text);
}
out
}
#[test]
fn the_element_goes_after_the_separator_and_its_comments() {
let e = "input e";
assert_eq!(
placed("(\n input a,\n input b\n);", "input a", e),
"(\n input a,\n input e,\n input b\n);"
);
assert_eq!(
placed("(\n input a /* about a */,\n input b\n);", "input a", e),
"(\n input a /* about a */,\n input e,\n input b\n);"
);
assert_eq!(
placed("(\n input b // about b\n , input c);", "input b", e),
"(\n input b // about b\n , input e, input c);"
);
assert_eq!(placed("(input a, input b);", "input a", e), "(input a, input e, input b);");
assert_eq!(
placed("(\n input y /* last */\n);", "input y", e),
"(\n input y, /* last */\n input e\n);"
);
assert_eq!(placed("(input y /* c */);", "input y", e), "(input y, /* c */ input e);");
assert_eq!(placed("(input y);", "input y", e), "(input y, input e);");
assert_eq!(
placed("(\r\n input a, /* x\r\n y */\r\n input b\r\n);", "input a", e),
"(\r\n input a, /* x\r\n y */\r\n input e,\r\n input b\r\n);"
);
}
#[test]
fn a_declaration_splits_at_its_name() {
let parts = split_declaration("input logic [W-1:0] cfg [2] = 0").unwrap();
assert_eq!((parts.dir, parts.ty, parts.rest), ("input", "logic [W-1:0]", "cfg [2] = 0"));
let parts = split_declaration("output pkg::t_e st").unwrap();
assert_eq!((parts.ty, parts.rest), ("pkg::t_e", "st"));
assert_eq!(split_declaration("input dbg_i").unwrap().ty, "");
}
}
+310
View File
@@ -0,0 +1,310 @@
//! The check a placement must pass before anything is written: the placed
//! edit is the engine's verified edit with elements **moved and nothing
//! else**. Per file, against the engine's result:
//!
//! 1. the same tokens (kind and text), as a multiset;
//! 2. every comment attached to the same identifier — the one before it for
//! a comment on its token's line, the one after it for a comment on
//! lines of its own — so a comment cannot slide onto the new element
//! (QA finding 1);
//! 3. no more parse diagnostics;
//! 4. the module's port list, **every** element counted (an element the
//! parser could not read included, by its text): the engine's order with
//! the new port moved to right after the anchor; each port's declaration
//! the engine's, blanks collapsed (QA finding 5); and the port after the
//! new one does not inherit from it;
//! 5. every instance's connections the same: named ones as a set of
//! `.name(expr)` with blanks squeezed, positional ones in order.
//!
//! Guilty until proven innocent: each rule has an attack in this module's
//! tests.
use std::path::PathBuf;
use vlog_parser::ast::{Connections, Instance, Item, ListElem, PortList};
use vlog_parser::span::TextRange;
use vlog_parser::token::TokenKind;
use vlog_parser::{parse_source_tolerant, tokenize};
use vlog_refactor::RefactorEdit;
use super::{collect_instances, find_module, inherits, Spec};
use crate::apply::Plan;
use crate::render::one_line;
/// Check `placed` against `engine` (see the module comment); the refusal
/// names the file and the rule broken.
pub fn verify(
files: &[(PathBuf, String)],
engine: &RefactorEdit,
placed: &RefactorEdit,
spec: &Spec,
) -> Result<(), String> {
let expected = Plan::from_refactor(engine.clone(), files)?;
let got = Plan::from_refactor(placed.clone(), files)?;
let refuse = |why: String| {
format!(
"placing `{}` after `{}` failed a check ({why}); nothing written.",
spec.port, spec.after
)
};
if expected.changes.len() != got.changes.len() {
return Err(refuse("a different set of files".into()));
}
for (want, have) in expected.changes.iter().zip(&got.changes) {
let shown = (spec.show)(&have.path);
if want.path != have.path {
return Err(refuse(format!("{shown} is not the engine's file")));
}
let lexed = lexed(&have.after);
if lexed.is_none() || lexed != self::lexed(&want.after) {
return Err(refuse(format!("{shown} lexes to other tokens or comments")));
}
let (want_tree, want_errors) = parse_source_tolerant(&want.after);
let (have_tree, have_errors) = parse_source_tolerant(&have.after);
if have_errors.len() > want_errors.len() {
return Err(refuse(format!("{shown} parses worse")));
}
if have.path == spec.file {
let want = (want.after.as_str(), want_tree.items.as_slice());
let have = (have.after.as_str(), have_tree.items.as_slice());
ports_in_order(have, want, spec).map_err(&refuse)?;
}
let mut wanted = Vec::new();
let mut had = Vec::new();
collect_instances(&want_tree.items, spec.module, &mut wanted);
collect_instances(&have_tree.items, spec.module, &mut had);
let signature = |text: &str, instances: &[&Instance]| -> Vec<Vec<String>> {
instances.iter().map(|instance| connections(text, instance)).collect()
};
if signature(&want.after, &wanted) != signature(&have.after, &had) {
return Err(refuse(format!("{shown}'s connections differ")));
}
}
Ok(())
}
/// Every token's kind and text, and every comment with the identifier it is
/// attached to, sorted: equal for two texts that hold the same tokens in
/// any order, with each comment still beside the same name.
fn lexed(text: &str) -> Option<Vec<String>> {
let tokens = tokenize(text).ok()?;
let ident = |token: &vlog_parser::token::Token| token.kind == TokenKind::Ident;
let mut out: Vec<String> = Vec::new();
let mut last_ident = "";
for (i, token) in tokens.iter().enumerate() {
out.push(format!("{:?} {}", token.kind, token.text));
if !token.leading.is_empty() {
let next = tokens[i..].iter().find(|t| ident(t)).map_or("", |t| t.text.as_str());
out.extend(token.leading.iter().map(|c| format!("comment before {next}: {}", c.text)));
}
if ident(token) {
last_ident = &token.text;
}
if let Some(comment) = &token.trailing {
out.push(format!("comment after {last_ident}: {}", comment.text));
}
}
out.sort();
Some(out)
}
/// A port list's elements as the check compares them: each readable port
/// as `name: declaration` (blanks collapsed), each unreadable one by text.
fn port_elements(text: &str, items: &[Item], spec: &Spec) -> Option<Vec<(String, String)>> {
let module = find_module(items, spec.module)?;
let PortList::Ansi(ports) = &module.ports else { return None };
let written = |span: TextRange| one_line(text.get(span.as_range()).unwrap_or(""));
let elements = ports.iter().map(|element| match element {
ListElem::Ok(port) => (port.name.clone(), written(port.span)),
ListElem::Error(raw) => (String::new(), one_line(&raw.text)),
});
Some(elements.collect())
}
/// The module's ports in the placed text are the engine's, each declared
/// as the engine left it, with the new one moved to right after the anchor;
/// the port after it does not inherit from it.
fn ports_in_order(
(have_text, have): (&str, &[Item]),
(want_text, want): (&str, &[Item]),
spec: &Spec,
) -> Result<(), String> {
let (Some(have_ports), Some(mut want_ports)) =
(port_elements(have_text, have, spec), port_elements(want_text, want, spec))
else {
return Err(format!("`{}` has no ANSI port list", spec.module));
};
let new = want_ports.iter().position(|(name, _)| name == spec.port);
let Some(new) = new.map(|at| want_ports.remove(at)) else {
return Err("the engine's result has no new port".to_string());
};
let at = want_ports.iter().position(|(name, _)| name == spec.after).map_or(0, |at| at + 1);
want_ports.insert(at, new);
if have_ports != want_ports {
let names: Vec<String> =
have_ports.iter().map(|(name, written)| format!("{name}: {written}")).collect();
return Err(format!("the ports are {}", names.join("; ")));
}
let module = find_module(have, spec.module).ok_or("the module is gone")?;
let PortList::Ansi(ports) = &module.ports else { return Err("no port list".into()) };
let dir = |at: usize| ports.get(at).and_then(ListElem::ok).and_then(|p| p.dir.as_deref());
let anchor_dir = at.checked_sub(1).and_then(dir);
if ports.get(at + 1).is_some_and(|next| inherits(next, dir(at), anchor_dir)) {
return Err("the port after the new one would inherit from it".to_string());
}
Ok(())
}
/// One instance's connections, blanks squeezed: sorted for a named list
/// (order does not bind) and in order for a positional one; an unreadable
/// element by its text.
fn connections(text: &str, instance: &Instance) -> Vec<String> {
let squeeze = |span: TextRange| -> String {
text.get(span.as_range()).unwrap_or("").split_whitespace().collect()
};
match &instance.conns {
Connections::Named(conns) => {
let mut out: Vec<String> = conns
.iter()
.map(|conn| match conn {
ListElem::Ok(conn) => squeeze(conn.span),
ListElem::Error(raw) => squeeze(raw.span),
})
.collect();
out.sort();
out
}
Connections::Ordered(conns) => conns
.iter()
.map(|conn| match conn {
ListElem::Ok(conn) => squeeze(conn.span),
ListElem::Error(raw) => squeeze(raw.span),
})
.collect(),
}
}
#[cfg(test)]
mod tests {
use std::path::Path;
use vlog_refactor::TextEdit;
use super::super::after;
use super::*;
const TOP: &str = "module top(input logic a, output logic y);\n m u_m (\n .a (a), // in\n .y (y)\n );\nendmodule\n";
fn design(header: &str) -> Vec<(PathBuf, String)> {
let m = format!("module m (\n{header}\n);\nendmodule\n");
vec![(PathBuf::from("/d/m.sv"), m), (PathBuf::from("/d/top.sv"), TOP.to_string())]
}
fn show(path: &Path) -> String {
path.display().to_string()
}
fn spec<'a>(after: &'a str, declaration: &'a str) -> Spec<'a> {
let file = Path::new("/d/m.sv");
Spec { module: "m", file, after, port: "en", declaration, show: &show }
}
fn engine(files: &[(PathBuf, String)], declaration: &str) -> RefactorEdit {
vlog_refactor::add_port(files, vlog_refactor::ModuleRef::Name("m"), declaration).unwrap()
}
/// `edit` with the module file's edits replaced by `header`.
fn with_header(edit: &RefactorEdit, header: Vec<TextEdit>) -> RefactorEdit {
let mut bad = edit.clone();
bad.edits[0].1 = header;
bad
}
fn insert(at: usize, text: &str) -> TextEdit {
TextEdit { range: TextRange::new(at as u32, at as u32), new_text: text.to_string() }
}
/// Masked-corruption attacks: a placed edit that is not the engine's
/// with elements moved is refused, whatever it looks like.
#[test]
fn a_placement_that_is_not_a_move_is_refused() {
let files = design(" input logic a, // first\n output logic y");
let decl = "input logic en";
let edit = engine(&files, decl);
let good = after(&files, &edit, &spec("a", decl)).unwrap();
assert!(verify(&files, &edit, &good, &spec("a", decl)).is_ok());
let m = &files[0].1;
let first = m.find("// first").unwrap();
// The anchor line's comment taken by the new line.
let stolen = with_header(&good, vec![insert(first, "\n input logic en, ")]);
assert!(verify(&files, &edit, &stolen, &spec("a", decl)).is_err());
// A wider type on the new port.
let wide = m.find("\n output").unwrap();
let wider = with_header(&good, vec![insert(wide, "\n input logic [1:0] en,")]);
assert!(verify(&files, &edit, &wider, &spec("a", decl)).is_err());
// A connection to another signal.
let mut rewired = good.clone();
let conn = rewired.edits[1].1.iter_mut().find(|e| e.new_text.contains(".en")).unwrap();
conn.new_text = conn.new_text.replace("TODO: connect */", "*/ a");
assert!(verify(&files, &edit, &rewired, &spec("a", decl)).is_err());
// The engine's own append, where `after` asked for `a`.
let last = verify(&files, &edit, &edit, &spec("a", decl)).unwrap_err();
assert!(last.contains("the ports are"), "{last}");
}
/// QA finding 5's pair: the type swapped between the anchor and the new
/// port — the same tokens, names in order, parse and connections.
#[test]
fn a_type_swapped_between_the_anchor_and_the_new_port_is_refused() {
let files = design(" input logic [7:0] a,\n output logic y");
let decl = "input logic en";
let edit = engine(&files, decl);
let m = &files[0].1;
let dims = m.find("[7:0] ").unwrap();
let comma = m.find("a,").unwrap() + 2;
let swapped = with_header(
&edit,
vec![
TextEdit {
range: TextRange::new(dims as u32, dims as u32 + 6),
new_text: String::new(),
},
insert(comma, "\n input logic [7:0] en,"),
],
);
let said = verify(&files, &edit, &swapped, &spec("a", decl)).unwrap_err();
assert!(said.contains("the ports are"), "{said}");
}
/// QA finding 1's shapes: a comment glued to the anchor's comma, and a
/// leading-comma list, each with the new element placed at the anchor's
/// end — the comment then documents the new port.
#[test]
fn a_comment_moved_onto_the_new_element_is_refused() {
for header in [
" input logic a /* about a */,\n output logic y",
" input logic a // about a\n , output logic y",
] {
let files = design(header);
let decl = "input logic en";
let edit = engine(&files, decl);
let end = files[0].1.find("logic a").unwrap() + "logic a".len();
let glued = with_header(&edit, vec![insert(end, ", input logic en")]);
let said = verify(&files, &edit, &glued, &spec("a", decl)).unwrap_err();
assert!(said.contains("comments"), "{header}: {said}");
// The slot after the separator keeps it.
let placed = after(&files, &edit, &spec("a", decl)).unwrap();
assert!(verify(&files, &edit, &placed, &spec("a", decl)).is_ok(), "{header}");
}
}
#[test]
fn comments_pair_with_the_name_they_are_written_beside() {
let pairs = lexed("a /* x */, b // y\n// z\nc").unwrap();
let comments: Vec<&String> = pairs.iter().filter(|p| p.starts_with("comment")).collect();
assert_eq!(
comments,
["comment after a: /* x */", "comment after b: // y", "comment before c: // z"]
);
}
}
+146
View File
@@ -0,0 +1,146 @@
//! `port`: add a port to a module and connect it by name in every
//! instantiation, or remove one and its connection everywhere — the
//! design-wide edit a file write cannot do safely. `add` is
//! `vlog_refactor::add_port`, placed after `after` by `place.rs`; `remove`
//! is `vlog_refactor::remove_port`, refused by the engine while the body
//! uses the port. Both write through the one write path and list the port
//! name's unresolved mentions.
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use vlog_refactor::{module_definition, ModuleRef};
use vlog_semantic::SymbolKind;
use super::edit::{whole_set, write_telling, Told};
use super::place;
use super::{Answer, Args, Param, Tool, Ty};
use crate::project::Project;
use crate::render;
pub const PORT: Tool = Tool {
name: "port",
description: "On `module`, `add` an ANSI port declaration (after port `after`, else last) connected in every instantiation, or `remove` a port and its connections (refused while used).",
params: &[
Param { name: "module", ty: Ty::Str, required: true },
Param { name: "add", ty: Ty::Str, required: false },
Param { name: "after", ty: Ty::Str, required: false },
Param { name: "remove", ty: Ty::Str, required: false },
],
rewalk: true,
handler: port,
};
fn port(project: &mut Project, args: &Args) -> Result<Answer, String> {
let module = args.str("module").unwrap_or_default().trim();
let file = declaring_file(project, module)?;
match (args.str("add"), args.str("remove"), args.str("after")) {
(Some(add), None, after) => add_port(project, module, &file, add, after),
(None, Some(remove), None) => remove_port(project, module, &file, remove.trim()),
(None, Some(_), Some(_)) => Err("`after` goes with `add`, not `remove`.".into()),
_ => Err("give exactly one of `add` and `remove`.".into()),
}
}
/// The one file declaring module `module`, walking once for a module
/// written since the last walk.
fn declaring_file(project: &mut Project, module: &str) -> Result<PathBuf, String> {
let found = module_definition(project.index(), module).map(Path::to_path_buf);
match found {
Err(_) if project.ensure_walked_for_miss() => {
module_definition(project.index(), module).map(Path::to_path_buf)
}
found => found,
}
}
fn add_port(
project: &mut Project,
module: &str,
file: &Path,
declaration: &str,
after: Option<&str>,
) -> Result<Answer, String> {
let set = whole_set(project, None, &[module.to_string()])?;
let edit = vlog_refactor::add_port(&set.files, ModuleRef::Name(module), declaration)
.map_err(|why| set.rooted(&why))?;
let tokens = vlog_parser::tokenize(declaration).unwrap_or_default();
let port = place::port_name(&tokens).map(|token| token.text.clone()).unwrap_or_default();
let show = &|path: &Path| project.relative(path);
let edit = match after.map(str::trim) {
Some(after) => {
let spec = place::Spec { module, file, after, port: &port, declaration, show };
place::after(&set.files, &edit, &spec).map_err(|why| set.rooted(&why))?
}
None => edit,
};
let told = Told { name: &port, home: file, unit: Some(module), member: true };
let (count, files) = instantiations(project, module);
let done = write_telling(project, edit, &set, &told)?;
let head = format!("added port {port} in module {module}: {}", census(count, files));
Ok(Answer::lines(std::iter::once(head).chain(done.tail).collect()))
}
fn remove_port(
project: &mut Project,
module: &str,
file: &Path,
port: &str,
) -> Result<Answer, String> {
let offset = port_offset(project, module, file, port)?;
let set = whole_set(project, Some(file), &[port.to_string(), module.to_string()])?;
let edit =
vlog_refactor::remove_port(&set.files, file, offset).map_err(|why| set.rooted(&why))?;
let told = Told { name: port, home: file, unit: Some(module), member: true };
let (count, files) = instantiations(project, module);
let done = write_telling(project, edit, &set, &told)?;
let head = format!("removed port {port} in module {module}: {}", census(count, files));
Ok(Answer::lines(std::iter::once(head).chain(done.tail).collect()))
}
/// Where port `port` of `module` is named in the module's file: its header
/// entry (an ANSI port, or a non-ANSI header name).
fn port_offset(
project: &mut Project,
module: &str,
file: &Path,
port: &str,
) -> Result<u32, String> {
let analysis = project.analysis(file)?;
let semantics = &analysis.semantics;
let unit = semantics
.symbols_named(module)
.filter_map(|id| semantics.symbol(id))
.find(|symbol| symbol.kind.is_instantiable())
.and_then(|symbol| symbol.child_scope);
let found = semantics
.symbols_named(port)
.filter_map(|id| semantics.symbol(id))
.find(|symbol| symbol.kind == SymbolKind::Port && Some(symbol.scope) == unit);
match found {
Some(symbol) => Ok(symbol.name_span.start),
None => {
let ports: Vec<&str> = semantics
.symbols()
.iter()
.filter(|symbol| symbol.kind == SymbolKind::Port && Some(symbol.scope) == unit)
.map(|symbol| symbol.name.as_str())
.collect();
Err(format!("`{module}` has no port `{port}` (its ports: {}).", ports.join(", ")))
}
}
}
/// `N instantiations in K files`.
fn census(count: usize, files: usize) -> String {
format!("{} in {}", render::count(count, "instantiation"), render::count(files, "file"))
}
/// How many instances of `module` the index holds, and in how many files —
/// the instantiations a port edit connects or disconnects.
fn instantiations(project: &Project, module: &str) -> (usize, usize) {
let edges = project.index().instantiations_of(module);
let count = edges.iter().map(|edge| edge.instances.len()).sum();
let files: BTreeSet<_> = edges.iter().map(|edge| edge.file).collect();
(count, files.len())
}
+59 -453
View File
@@ -1,474 +1,80 @@
//! The whole-project read tools: `project_overview`, `list_units`,
//! `outline` and `search_symbols`. Each answers from the index (or from one
//! file's analysis) and renders by the rules in `render.rs`.
//! `read`: one item's exact source — a slice, never the file — preceded by
//! `file:first–last`. In a named `file` the item is sliced as
//! `read_item::select` slices it; without one the name is looked up
//! design-wide and must be declared exactly once.
use std::path::Path;
use serde_json::{json, Value};
use vlog_semantic::{Def, DocumentSymbol, SymbolKind, WorkspaceIndex};
use std::path::PathBuf;
use super::names;
use super::read_item::{declared_lines, select, split_kind, split_line, BY_LINE};
use super::{Answer, Args, Param, Tool, Ty};
use crate::project::Project;
use crate::render::{self, DEFAULT_LIMIT};
use crate::render;
const LIMIT: Param = Param {
name: "limit",
ty: Ty::Int { min: 1 },
required: false,
description: "Most entries to return (default 200).",
};
const OFFSET: Param = Param {
name: "offset",
ty: Ty::Int { min: 0 },
required: false,
description: "Entries to skip, for paging past `… and N more` (default 0).",
};
pub const PROJECT_OVERVIEW: Tool = Tool {
name: "project_overview",
title: "Project overview",
description: "Summarise the Verilog/SystemVerilog project under the roots: file count, units by kind, top-level modules (nothing instantiates them) and the largest files. Call it first to orient yourself instead of listing directories.",
params: &[],
rewalk: true,
handler: project_overview,
};
pub const LIST_UNITS: Tool = Tool {
name: "list_units",
title: "List design units",
description: "List the modules, interfaces, packages, classes and programs declared in the project with their file:line, optionally filtered by kind and a name glob (`*`, `?`). Prefer it over grepping for `module` to find where a unit lives.",
pub const READ: Tool = Tool {
name: "read",
description: "One item's exact source after its file:first–last line. `item`: name, kind:name, name@LINE, or always@LINE; `file` is needed for always@LINE or a name declared in several files.",
params: &[
Param {
name: "kind",
ty: Ty::Enum(&["module", "interface", "package", "class", "program"]),
required: false,
description: "Only units of this kind.",
},
Param {
name: "glob",
ty: Ty::Str,
required: false,
description: "Only names matching this pattern; `*` is any run, `?` one character.",
},
LIMIT,
OFFSET,
Param { name: "item", ty: Ty::Str, required: true },
Param { name: "file", ty: Ty::Str, required: false },
],
rewalk: false,
handler: list_units,
handler: read,
};
pub const OUTLINE: Tool = Tool {
name: "outline",
title: "File outline",
description: "The declarations in one file as a tree with 1-based line ranges (units, ports, parameters, signals, functions, instances, blocks), plus its parse errors. Prefer it over reading a file to see what it contains; then use read_item for the part you need.",
params: &[
Param {
name: "file",
ty: Ty::Str,
required: true,
description: "The file, relative to a root or absolute inside one.",
},
Param {
name: "depth",
ty: Ty::Int { min: 1 },
required: false,
description: "Levels to show; 1 is the file's units only (default: all).",
},
LIMIT,
OFFSET,
],
rewalk: false,
handler: outline,
};
pub const SEARCH_SYMBOLS: Tool = Tool {
name: "search_symbols",
title: "Search symbols",
description: "Find declarations whose name contains `query` (case-insensitive) across the project: units, and the ports, parameters and package/class members other files can name. Answers file and line per hit; a module's internal signals are not included (use outline for those).",
params: &[
Param {
name: "query",
ty: Ty::Str,
required: true,
description: "Substring of the name to find; empty matches everything.",
},
LIMIT,
OFFSET,
],
rewalk: false,
handler: search_symbols,
};
/// One unit in a listing.
struct Unit {
name: String,
kind: &'static str,
file: String,
line: u32,
}
/// Every unit the index holds, file-scope ones and the classes a package
/// declares (named `pkg::cls`), sorted by file then line.
fn units(project: &Project) -> Vec<Unit> {
let index = project.index();
let mut out = Vec::new();
for kind in [SymbolKind::Module, SymbolKind::Interface, SymbolKind::Package, SymbolKind::Class]
{
for (name, def) in index.units_of(kind) {
out.push(unit(project, name.to_string(), def));
}
fn read(project: &mut Project, args: &Args) -> Result<Answer, String> {
let selector = args.str("item").unwrap_or("").trim();
if selector.is_empty() {
return Err("`item` is empty.".into());
}
for (package, _) in index.units_of(SymbolKind::Package) {
for (name, defs) in index.members_of(package) {
for def in defs.iter().filter(|def| def.kind == SymbolKind::Class) {
out.push(unit(project, format!("{package}::{name}"), def));
}
}
}
out.sort_by(|a, b| (&a.file, a.line, &a.name).cmp(&(&b.file, b.line, &b.name)));
out
}
fn unit(project: &Project, name: String, def: &Def) -> Unit {
let path = project.index().path(def.file).unwrap_or(Path::new(""));
Unit {
name,
kind: unit_kind(project, path, def),
file: project.relative(path),
line: def.lines.name,
}
}
/// A unit's kind word, telling a `program` from the module it is modelled as.
pub fn unit_kind(project: &Project, path: &Path, def: &Def) -> &'static str {
if def.kind == SymbolKind::Module && is_program(project, path, def) {
"program"
} else {
render::kind(def.kind)
}
}
/// Whether a `Module`-kind unit was declared with `program`. The semantic
/// layer models the two alike, so the keyword is read off the text between
/// the declaration's start and its name — only for the rare file whose text
/// spells `endprogram` at all.
fn is_program(project: &Project, path: &Path, def: &Def) -> bool {
if !project.stamp(path).is_some_and(|stamp| stamp.program) {
return false;
}
let Ok(text) = std::fs::read_to_string(path) else {
return false;
let path = match args.str("file") {
Some(file) => project.resolve(file)?,
None => locate(project, selector)?,
};
let head = text.get(def.decl_span.start as usize..def.name_span.start as usize);
head.is_some_and(|head| head.split_whitespace().any(|word| word == "program"))
}
/// Whether `name` matches a glob of `*` (any run) and `?` (one character).
pub fn glob_match(pattern: &str, name: &str) -> bool {
let pattern: Vec<char> = pattern.chars().collect();
let name: Vec<char> = name.chars().collect();
// Classic two-pointer match with one backtrack point per `*`.
let (mut p, mut n, mut star, mut resume) = (0, 0, None, 0);
while n < name.len() {
if p < pattern.len() && (pattern[p] == '?' || pattern[p] == name[n]) {
p += 1;
n += 1;
} else if p < pattern.len() && pattern[p] == '*' {
star = Some(p);
resume = n;
p += 1;
} else if let Some(at) = star {
p = at + 1;
resume += 1;
n = resume;
} else {
return false;
}
}
pattern[p..].iter().all(|&c| c == '*')
}
fn list_units(project: &mut Project, args: &Args) -> Result<Answer, String> {
let mut all = matching_units(project, args);
// A glob names something the agent expects to exist — often a file it
// has just written — so a miss walks once before it is believed.
if all.is_empty() && args.str("glob").is_some() && project.ensure_walked_for_miss() {
all = matching_units(project, args);
}
let (shown, rest) =
render::page(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
let entries: Vec<(String, String)> = shown
.iter()
.map(|u| (u.file.clone(), format!("{} {} {}", u.kind, u.name, u.line)))
.collect();
let mut text = render::grouped(&entries);
render::more(&mut text, rest);
if all.is_empty() {
text = "no units match\n".to_string();
}
let structured: Vec<Value> = shown
.iter()
.map(|u| json!({ "name": u.name, "kind": u.kind, "file": u.file, "line": u.line }))
.collect();
Ok(Answer { text, structured: json!({ "units": structured, "total": all.len() }) })
}
/// The units `list_units`'s `kind` and `glob` select.
fn matching_units(project: &Project, args: &Args) -> Vec<Unit> {
units(project)
.into_iter()
.filter(|unit| args.str("kind").is_none_or(|kind| unit.kind == kind))
.filter(|unit| args.str("glob").is_none_or(|glob| glob_match(glob, &unit.name)))
.collect()
}
fn project_overview(project: &mut Project, _: &Args) -> Result<Answer, String> {
let overview = Overview::of(project);
Ok(Answer { text: overview.text(), structured: overview.json() })
}
/// What `project_overview` reports, gathered once and rendered twice.
struct Overview {
roots: Vec<String>,
config: Option<String>,
filelist: Option<String>,
files: usize,
skipped_large: usize,
by_kind: Vec<(&'static str, usize)>,
build_ms: u128,
age_s: u64,
tops: Vec<String>,
more_tops: usize,
largest: Vec<(String, u64)>,
warnings: Vec<String>,
}
impl Overview {
fn of(project: &Project) -> Overview {
let all = units(project);
let kinds = ["module", "interface", "package", "class", "program"];
let by_kind = kinds
.iter()
.map(|&kind| (kind, all.iter().filter(|u| u.kind == kind).count()))
.collect();
let tops = top_modules(project.index());
let (shown, more_tops) = render::page(&tops, 0, DEFAULT_LIMIT);
let (config, config_problem) = project.config();
let discovery = project.discovery();
let (build, age) = project.timing();
let mut warnings: Vec<String> = discovery.warnings.clone();
warnings.extend(config_problem.map(str::to_string));
warnings.extend(project.unreadable().iter().cloned());
Overview {
roots: project.roots().iter().map(|r| r.display().to_string()).collect(),
config: config.source.as_ref().map(|path| path.display().to_string()),
filelist: discovery.filelist.as_ref().map(|path| path.display().to_string()),
files: project.files().count(),
skipped_large: discovery.skipped_large,
by_kind,
build_ms: build.as_millis(),
age_s: age.as_secs(),
tops: shown.to_vec(),
more_tops,
largest: largest_files(project, 10),
warnings,
}
}
fn text(&self) -> String {
let mut text = format!("roots: {}\n", self.roots.join(", "));
text.push_str(&format!("config: {}\n", self.config.as_deref().unwrap_or("none")));
text.push_str(&format!(
"filelist: {}\n",
self.filelist.as_deref().unwrap_or("none (walked)")
));
text.push_str(&format!(
"files: {} indexed, {} over 1 MiB skipped\n",
self.files, self.skipped_large
));
let counts: Vec<String> =
self.by_kind.iter().map(|(kind, n)| format!("{n} {kind}")).collect();
text.push_str(&format!("units: {}\n", counts.join(", ")));
text.push_str(&format!(
"index: built in {} ms, last changed {} s ago\n",
self.build_ms, self.age_s
));
text.push_str(&format!("top: {}\n", self.tops.join(" ")));
render::more(&mut text, self.more_tops);
text.push_str("largest:\n");
let rows: Vec<Vec<String>> =
self.largest.iter().map(|(file, size)| vec![size.to_string(), file.clone()]).collect();
text.push_str(&render::table(&rows));
for warning in self.warnings.iter().take(10) {
text.push_str(&format!("warning: {warning}\n"));
}
render::more(&mut text, self.warnings.len().saturating_sub(10));
text
}
fn json(&self) -> Value {
let units: serde_json::Map<String, Value> =
self.by_kind.iter().map(|(kind, n)| (kind.to_string(), json!(n))).collect();
let largest: Vec<Value> = self
.largest
.iter()
.map(|(file, bytes)| json!({ "file": file, "bytes": bytes }))
.collect();
json!({
"roots": self.roots,
"config": self.config,
"filelist": self.filelist,
"files": self.files,
"skipped_large": self.skipped_large,
"units": units,
"index_build_ms": self.build_ms as u64,
"index_age_s": self.age_s,
"top_modules": self.tops,
"more_top_modules": self.more_tops,
"largest_files": largest,
"warnings": self.warnings,
})
}
}
/// Modules (programs included) nothing in the index instantiates, by name.
fn top_modules(index: &WorkspaceIndex) -> Vec<String> {
let mut tops: Vec<String> = index
.instantiable_units()
.filter(|(_, def)| def.kind == SymbolKind::Module)
.filter(|(name, _)| index.instantiations_of(name).is_empty())
.map(|(name, _)| name.to_string())
.collect();
tops.dedup();
tops
}
/// The `n` largest indexed files, largest first.
fn largest_files(project: &Project, n: usize) -> Vec<(String, u64)> {
let mut sizes: Vec<(u64, &Path)> =
project.files().map(|(path, stamp)| (stamp.size, path.as_path())).collect();
sizes.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(b.1)));
sizes.into_iter().take(n).map(|(size, path)| (project.relative(path), size)).collect()
}
fn outline(project: &mut Project, args: &Args) -> Result<Answer, String> {
let path = project.resolve(args.str("file").unwrap_or(""))?;
let analysis = project.analysis(&path)?;
let depth = args.count("depth", usize::MAX);
let mut rows: Vec<(usize, String, &'static str, u32, u32)> = Vec::new();
flatten(&analysis, &analysis.semantics.document_symbols(), 0, depth, &mut rows);
let (shown, rest) =
render::page(&rows, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
let file = project.relative(&path);
let mut text = format!("{file}\n");
let errors = &analysis.diagnostics;
if let Some(first) = errors.first() {
text.push_str(&format!(
"parse errors: {} (first {}:{} {})\n",
errors.len(),
first.line,
first.col,
first.message
));
let analysis = project.analysis(&path)?;
let (_, span) = select(&analysis, selector).map_err(|why| format!("{why} in `{file}`."))?;
let (first, last) = analysis.line_span(span.start, span.end);
let mut text =
format!("{file}:{}\n{}", render::lines(first, last), analysis.slice(span.start, span.end));
if !text.ends_with('\n') {
text.push('\n');
}
for (level, name, kind, first, last) in shown {
let indent = " ".repeat(level + 1);
text.push_str(&format!("{indent}{kind} {name} {}\n", render::lines(*first, *last)));
}
render::more(&mut text, rest);
let symbols: Vec<Value> = shown
.iter()
.map(|(level, name, kind, first, last)| {
json!({ "name": name, "kind": kind, "depth": level + 1, "lines": [first, last] })
})
.collect();
let parse_errors: Vec<Value> = errors
.iter()
.map(|e| json!({ "line": e.line, "col": e.col, "message": e.message }))
.collect();
let structured = json!({
"file": file, "parse_errors": parse_errors, "symbols": symbols, "total": rows.len(),
});
Ok(Answer { text, structured })
Ok(Answer { text })
}
/// The outline tree in pre-order, each node with its depth and line range.
fn flatten(
analysis: &crate::project::Analysis,
nodes: &[DocumentSymbol],
level: usize,
depth: usize,
out: &mut Vec<(usize, String, &'static str, u32, u32)>,
) {
if level >= depth {
return;
/// The one file declaring what `selector` names, design-wide; a refusal
/// listing every site when there are several, or the near matches when
/// there are none.
fn locate(project: &mut Project, selector: &str) -> Result<PathBuf, String> {
let (head, line) = split_line(selector)?;
if line.is_some() && BY_LINE.contains(&head) {
return Err(format!("`{selector}` names a block by its line; give its `file`."));
}
for node in nodes {
let Some(symbol) = analysis.semantics.symbol(node.symbol) else {
continue;
};
let (first, last) = analysis.line_span(symbol.decl_span.start, symbol.decl_span.end);
out.push((level, symbol.name.clone(), render::kind(symbol.kind), first, last));
flatten(analysis, &node.children, level + 1, depth, out);
let (_, name) = split_kind(head);
let mut files: Vec<PathBuf> = Vec::new();
for declaration in names::declarations_walking(project, name) {
if !declaration.is_macro() && !files.contains(&declaration.path) {
files.push(declaration.path);
}
}
}
fn search_symbols(project: &mut Project, args: &Args) -> Result<Answer, String> {
let query = args.str("query").unwrap_or("");
// A miss may be a file written since the last walk: walk once, then answer.
if project.index().workspace_symbols(query).is_empty() {
project.ensure_walked_for_miss();
let mut sites: Vec<(PathBuf, String)> = Vec::new();
for path in files {
let analysis = project.analysis(&path)?;
let file = project.relative(&path);
let lines = declared_lines(&analysis, selector);
sites.extend(lines.into_iter().map(|line| (path.clone(), format!("{file}:{line}"))));
}
let index = project.index();
let hits = index.workspace_symbols(query);
let (shown, rest) =
render::page(&hits, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
let mut entries = Vec::new();
let mut structured = Vec::new();
for hit in shown {
let name = match hit.container {
Some(unit) => format!("{unit}{}{}", separator(index, unit), hit.name),
None => hit.name.to_string(),
};
let file = project.relative(index.path(hit.def.file).unwrap_or(Path::new("")));
// A line and no column: the index records a client (UTF-16) column
// for units only, and every column this server prints is a byte one.
let line = hit.def.lines.name;
entries.push((file.clone(), format!("{} {name} {line}", render::kind(hit.def.kind))));
structured.push(json!({
"name": name, "kind": render::kind(hit.def.kind), "file": file, "line": line,
}));
}
let mut text = render::grouped(&entries);
render::more(&mut text, rest);
if hits.is_empty() {
text = "no symbols match\n".to_string();
}
Ok(Answer { text, structured: json!({ "symbols": structured, "total": hits.len() }) })
}
/// How a member is spelled after its unit: `unit.x` for a module or
/// interface (a hierarchical name), `unit::x` for a package or a class —
/// including a class the index holds only as a package member.
fn separator(index: &WorkspaceIndex, unit: &str) -> &'static str {
match index.units(unit).first().map(|def| def.kind) {
Some(kind) if kind.is_instantiable() => ".",
_ => "::",
}
}
#[cfg(test)]
mod tests {
use super::glob_match;
#[test]
fn globs_match_runs_and_single_characters() {
assert!(glob_match("prim_*", "prim_fifo_sync"));
assert!(glob_match("*fifo*", "prim_fifo_sync"));
assert!(glob_match("a?c", "abc"));
assert!(glob_match("*", ""));
assert!(!glob_match("a?c", "ac"));
assert!(!glob_match("prim_*_async", "prim_fifo_sync"));
assert!(glob_match("*_sync", "prim_fifo_sync"));
match sites.as_slice() {
[] => Err(names::no_declaration(project, name)),
[(path, _)] => Ok(path.clone()),
many => {
let listed: Vec<&str> = many.iter().map(|(_, site)| site.as_str()).collect();
Err(format!(
"`{selector}` is declared {} times ({}); give `file`, and `name@LINE` within one file.",
listed.len(),
listed.join(", ")
))
}
}
}
+38 -59
View File
@@ -1,65 +1,22 @@
//! `read_item`: one item's exact text, sliced out of its file — a module, a
//! function, a declaration, an instance, or an unlabelled `always` block
//! named by the line it covers.
//! The item slicer `read` and `edit_item` share: one item's exact span in
//! a file — a module, a function, a declaration, an instance, or an
//! unlabelled `always` block named by the line it covers.
//!
//! The slicing rule is the one the M4 structural edits will replace by, so
//! it lives here on its own: an item is the parser's `Item` node (its
//! The slicing rule is the one the structural edits replace by, so it
//! lives here on its own: an item is the parser's `Item` node (its
//! attributes included, its leading comments not) that declares the name,
//! or — for a declaration a larger construct only *contains* (an ANSI port
//! in a module header, a function argument) — the declaration's own span.
use serde_json::json;
use vlog_parser::ast::{GenBlock, GenElse, GenIf, Item, ItemKind};
use vlog_parser::span::TextRange;
use vlog_semantic::Symbol;
use super::{Answer, Args, Param, Tool, Ty};
use crate::project::{Analysis, Project};
use crate::project::Analysis;
use crate::render;
pub const READ_ITEM: Tool = Tool {
name: "read_item",
title: "Read one item",
description: "The exact source text and 1-based line range of one item in a file: `name`, `kind:name` (e.g. `function:crc`), `name@LINE` when a name is declared twice, or `always@LINE` / `initial@LINE` / `final@LINE` / `assign@LINE` for the unlabelled block or assignment covering that line (`@LINE` is the last `@` followed only by digits, so `\\a@b@1` is `\\a@b` on line 1). Prefer it over reading the whole file; outline shows what there is.",
params: &[
Param {
name: "file",
ty: Ty::Str,
required: true,
description: "The file, relative to a root or absolute inside one.",
},
Param {
name: "item",
ty: Ty::Str,
required: true,
description: "`name`, `kind:name`, `name@LINE`, or `always@LINE` (also initial, final, assign).",
},
],
rewalk: false,
handler: read_item,
};
/// The keywords that name an unlabelled item by the line it covers.
const BY_LINE: &[&str] = &["always", "initial", "final", "assign"];
fn read_item(project: &mut Project, args: &Args) -> Result<Answer, String> {
let path = project.resolve(args.str("file").unwrap_or(""))?;
let file = project.relative(&path);
let analysis = project.analysis(&path)?;
let selector = args.str("item").unwrap_or("").trim();
let (kind, span) =
select(&analysis, selector).map_err(|problem| format!("{problem} in `{file}`."))?;
let (first, last) = analysis.line_span(span.start, span.end);
let body = analysis.slice(span.start, span.end);
let mut text = format!("{file}:{}\n{body}", render::lines(first, last));
if !text.ends_with('\n') {
text.push('\n');
}
let structured = json!({
"file": file, "item": selector, "kind": kind, "lines": [first, last], "text": body,
});
Ok(Answer { text, structured })
}
pub const BY_LINE: &[&str] = &["always", "initial", "final", "assign"];
/// The item `selector` names in this file: its kind word and byte span, or
/// the reason there is not exactly one.
@@ -83,7 +40,7 @@ pub fn select(analysis: &Analysis, selector: &str) -> Result<(&'static str, Text
/// `kind:` is a prefix only when it is one of the kind words; otherwise the
/// colon is part of the name (`\k:l`, an escaped identifier).
fn split_kind(head: &str) -> (Option<&str>, &str) {
pub fn split_kind(head: &str) -> (Option<&str>, &str) {
match head.split_once(':') {
Some((kind, name)) if render::is_kind_word(kind) => (Some(kind), name),
_ => (None, head),
@@ -92,7 +49,7 @@ fn split_kind(head: &str) -> (Option<&str>, &str) {
/// Split `head@LINE` at the last `@` when only digits follow it; any other
/// `@` belongs to the name (`\a@b`).
fn split_line(selector: &str) -> Result<(&str, Option<u32>), String> {
pub fn split_line(selector: &str) -> Result<(&str, Option<u32>), String> {
match selector.rsplit_once('@') {
Some((head, digits))
if !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()) =>
@@ -106,6 +63,34 @@ fn split_line(selector: &str) -> Result<(&str, Option<u32>), String> {
}
}
/// The lines of every declaration a by-name `selector` matches in this
/// file — none for a malformed or by-line selector.
pub fn declared_lines(analysis: &Analysis, selector: &str) -> Vec<u32> {
let Ok((head, line)) = split_line(selector) else { return Vec::new() };
let (kind, name) = split_kind(head);
let mut found = matching(analysis, name, kind, line);
if found.is_empty() && line.is_some() && name.starts_with('\\') {
found = matching(analysis, split_kind(selector).1, kind, None);
}
found.iter().map(|symbol| analysis.lines.line_col(symbol.name_span.start).0).collect()
}
/// Every declaration of `name` matching the optional kind word and line.
fn matching<'a>(
analysis: &'a Analysis,
name: &str,
kind: Option<&str>,
line: Option<u32>,
) -> Vec<&'a Symbol> {
let semantics = &analysis.semantics;
semantics
.symbols_named(name)
.filter_map(|id| semantics.symbol(id))
.filter(|s| kind.is_none_or(|kind| render::kind(s.kind) == kind))
.filter(|s| line.is_none_or(|line| analysis.lines.line_col(s.name_span.start).0 == line))
.collect()
}
/// The one declaration of `name` matching the optional kind word and line.
fn by_name<'a>(
analysis: &'a Analysis,
@@ -113,13 +98,7 @@ fn by_name<'a>(
kind: Option<&str>,
line: Option<u32>,
) -> Result<&'a Symbol, String> {
let semantics = &analysis.semantics;
let matches: Vec<&Symbol> = semantics
.symbols_named(name)
.filter_map(|id| semantics.symbol(id))
.filter(|s| kind.is_none_or(|kind| render::kind(s.kind) == kind))
.filter(|s| line.is_none_or(|line| analysis.lines.line_col(s.name_span.start).0 == line))
.collect();
let matches = matching(analysis, name, kind, line);
match matches.as_slice() {
[one] => Ok(one),
[] => Err(format!("no declaration matches `{name}`{}{}", on_kind(kind), on_line(line))),
-291
View File
@@ -1,291 +0,0 @@
//! The refactorings that are not "act at this cursor": `add_port` (a module
//! and a declaration), `extract_module` (a line range and a new name), and
//! `instantiate`, which writes nothing at all — it answers with the text of
//! an instantiation for the agent to place.
use std::path::{Path, PathBuf};
use vlog_refactor::{instantiation_plan, module_definition, Home, Layout, ModuleRef};
use super::edit::{enclosing, finish, whole_set, DRY_RUN};
use super::{Answer, Args, Param, Tool, Ty};
use crate::project::Project;
pub const ADD_PORT: Tool = Tool {
name: "add_port",
title: "Add a port",
description: "Add one ANSI port to a module and a connection for it to every instantiation in the project, verified before anything is written. Name the module by `module`, or by `file`+`line` inside its declaration; `declaration` is the port as written in the header (`input logic [7:0] cfg`). Refuses a port that exists, an ordered instantiation of a different length, and a list split by `ifdef`s. `dry_run` returns the diff.",
params: &[
Param {
name: "module",
ty: Ty::Str,
required: false,
description: "The module's name (declared once in the project).",
},
Param {
name: "file",
ty: Ty::Str,
required: false,
description: "Instead of `module`: the file declaring it, with `line`.",
},
Param {
name: "line",
ty: Ty::Int { min: 1 },
required: false,
description: "1-based line inside the module's declaration in `file`.",
},
Param {
name: "declaration",
ty: Ty::Str,
required: true,
description: "One directed ANSI port declaration, e.g. `input logic [7:0] cfg`.",
},
DRY_RUN,
],
rewalk: true,
handler: add_port,
};
pub const EXTRACT_MODULE: Tool = Tool {
name: "extract_module",
title: "Extract lines into a module",
description: "Move the whole items on lines `start_line`..`end_line` of a module into a new module `new_name`, whose ports come from the dataflow across the selection, and instantiate it in their place; verified before anything is written. `home: new_file` (default) creates `new_name.sv` beside the file (refused if it exists); `same_file` writes it below the module. Refuses a partial item and names it cannot carry. `dry_run` returns the diff.",
params: &[
Param {
name: "file",
ty: Ty::Str,
required: true,
description: "The file holding the module, relative to a root or absolute inside one.",
},
Param {
name: "start_line",
ty: Ty::Int { min: 1 },
required: true,
description: "First line of the selection (1-based).",
},
Param {
name: "end_line",
ty: Ty::Int { min: 1 },
required: true,
description: "Last line of the selection (1-based, included).",
},
Param {
name: "new_name",
ty: Ty::Str,
required: true,
description: "The new module's name; nothing in the project may declare it yet.",
},
Param {
name: "home",
ty: Ty::Enum(&["new_file", "same_file"]),
required: false,
description: "Where the new module goes: `new_file` (default) or `same_file`.",
},
DRY_RUN,
],
rewalk: true,
handler: extract_module,
};
pub const INSTANTIATE: Tool = Tool {
name: "instantiate",
title: "Instantiation template",
description: "The text of an instantiation of module `name` for the agent to place — parameters with their defaults, the instance name, and each port connected to a same-named signal (`named`) or as `.*` (`wildcard`). Writes nothing. Refuses a module that is not indexed or is declared twice (pass `file` to pick one).",
params: &[
Param {
name: "name",
ty: Ty::Str,
required: true,
description: "The module (or interface) to instantiate.",
},
Param {
name: "style",
ty: Ty::Enum(&["named", "wildcard"]),
required: false,
description: "`named` connections (default) or `.*`.",
},
Param {
name: "with_params",
ty: Ty::Bool,
required: false,
description: "Write the `#( … )` parameter overrides (default true).",
},
Param {
name: "instance",
ty: Ty::Str,
required: false,
description: "The instance name (default `u_<name>`).",
},
Param {
name: "file",
ty: Ty::Str,
required: false,
description: "The file declaring the module, when more than one does.",
},
],
rewalk: false,
handler: instantiate,
};
fn add_port(project: &mut Project, args: &Args) -> Result<Answer, String> {
let declaration = args.str("declaration").unwrap_or_default();
match (args.str("module"), args.str("file"), args.int("line")) {
(Some(name), None, None) => {
let set = whole_set(project, None, &[name.to_string()])?;
let edit = vlog_refactor::add_port(&set.files, ModuleRef::Name(name), declaration)?;
finish(project, edit, &set, args)
}
(None, Some(file), Some(line)) => {
let path = project.resolve(file)?;
let offset = line_start(project, &path, line)?;
let names = enclosing(&*project.analysis(&path)?, offset);
let set = whole_set(project, Some(&path), &names)?;
let module = ModuleRef::At { file: &path, offset };
let edit = vlog_refactor::add_port(&set.files, module, declaration)?;
finish(project, edit, &set, args)
}
_ => Err("name the module by `module`, or by `file` and `line`, not both.".into()),
}
}
/// The byte offset where 1-based `line` of `path` starts; `end` asks for
/// where it ends instead (its line ending excluded).
fn line_offset(project: &mut Project, path: &Path, line: i64, end: bool) -> Result<u32, String> {
let analysis = project.analysis(path)?;
let count = analysis.lines.line_count();
let range = u32::try_from(line).ok().and_then(|line| analysis.lines.line_range(line));
let Some(range) = range else {
let file = project.relative(path);
return Err(format!("line {line} is past the end of `{file}` ({count} lines)."));
};
Ok(if end { range.end } else { range.start })
}
fn line_start(project: &mut Project, path: &Path, line: i64) -> Result<u32, String> {
line_offset(project, path, line, false)
}
fn extract_module(project: &mut Project, args: &Args) -> Result<Answer, String> {
let file = args.str("file").unwrap_or_default();
let path = project.resolve(file)?;
let (first, last) = (args.int("start_line").unwrap_or(1), args.int("end_line").unwrap_or(1));
if last < first {
return Err(format!("`end_line` {last} is before `start_line` {first}."));
}
let start = line_start(project, &path, first)?;
let end = line_offset(project, &path, last, true)?;
let home = match args.str("home") {
Some("same_file") => Home::SameFile,
_ => Home::NewFile,
};
let new_name = args.str("new_name").unwrap_or_default();
let names = enclosing(&*project.analysis(&path)?, start);
let set = whole_set(project, Some(&path), &names)?;
let edit = vlog_refactor::extract_module(&set.files, &path, start, end, new_name, home)?;
finish(project, edit, &set, args)
}
fn instantiate(project: &mut Project, args: &Args) -> Result<Answer, String> {
let name = args.str("name").unwrap_or_default();
let path = declaring_file(project, name, args.str("file"))?;
let text = std::fs::read_to_string(&path)
.map_err(|e| format!("cannot read `{}`: {e}", project.relative(&path)))?;
let mut plan = instantiation_plan(name, &text, None)?;
if !args.flag("with_params", true) {
plan.params.clear();
}
let wildcard = args.str("style") == Some("wildcard");
if wildcard {
plan.ports.clear();
}
let instance = match args.str("instance") {
Some(instance) => identifier(instance)?.to_string(),
None => plan.instance_name(),
};
// `render_with` numbers the fill-ins: each parameter, then the instance.
let instance_hole = plan.params.len() + 1;
let mut hole = |n: usize, default: &str| {
if n == instance_hole {
instance.clone()
} else {
default.into()
}
};
let mut skeleton = plan.render_with(&layout(project), &mut hole);
if wildcard {
// With no ports the skeleton ends `u_x ();`.
skeleton.truncate(skeleton.len() - "();".len());
skeleton.push_str("(.*);");
}
skeleton.push('\n');
let file = project.relative(&path);
let structured = serde_json::json!({
"module": name, "file": file, "text": skeleton, "warnings": plan.warnings,
});
let mut text = skeleton;
for warning in &plan.warnings {
text.push_str(&format!("warning: {warning}\n"));
}
Ok(Answer { text, structured })
}
/// The one file declaring module `name` — `file` when given (it must be a
/// file the index says declares it), else the index's single answer, after
/// one walk for a module written since the last one.
fn declaring_file(
project: &mut Project,
name: &str,
file: Option<&str>,
) -> Result<PathBuf, String> {
if let Some(file) = file {
let path = project.resolve(file)?;
let declares = project.index().units(name).iter().any(|def| {
def.kind.is_instantiable() && project.index().path(def.file) == Some(path.as_path())
});
if !declares {
return Err(format!("`{file}` declares no module named `{name}`."));
}
return Ok(path);
}
let found = module_definition(project.index(), name).map(Path::to_path_buf);
match found {
Err(_) if project.ensure_walked_for_miss() => {
module_definition(project.index(), name).map(Path::to_path_buf)
}
found => found,
}
.map_err(|why| {
if why.contains("more than one") {
format!("{why} Pass `file` to pick one.")
} else {
why
}
})
}
/// `name`, when it is one SystemVerilog identifier: a simple one
/// (`[A-Za-z_][A-Za-z0-9_$]*`, not a keyword) or an escaped one (`\`, then
/// printable non-space characters, then one space). Anything else would
/// render text that does not parse.
fn identifier(name: &str) -> Result<&str, String> {
let simple = name.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
&& name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
&& !vlog_parser::token::is_keyword(name);
let escaped = name
.strip_prefix('\\')
.and_then(|rest| rest.strip_suffix(' '))
.is_some_and(|body| !body.is_empty() && body.chars().all(|c| c.is_ascii_graphic()));
if simple || escaped {
return Ok(name);
}
Err(format!(
"`instance` must be one identifier — `[A-Za-z_][A-Za-z0-9_$]*` and not a keyword, or an escaped identifier `\\name ` ending in one space; `{name}` is not."
))
}
/// Column zero, one indentation step as the project's lucisv.toml spells it.
fn layout(project: &Project) -> Layout {
let indent =
project.config().0.indent.unwrap_or(vlog_formatter::Config::default().indent_width);
Layout { base: String::new(), step: " ".repeat(indent) }
}
-212
View File
@@ -1,212 +0,0 @@
//! The selector `definition` and `references` share: a position (`file` +
//! `line` + `col`, or `file` + `line` + the `name` written on that line), a
//! name in a file (`file` + `name`), or a bare `name` (with an optional
//! `unit`) looked up in the index. A position is picked by **token**, never
//! by text, so a comment, a string or a macro argument cannot stand in for
//! the code; and a pick that would be a guess is refused with the choices.
use std::path::PathBuf;
use std::rc::Rc;
use vlog_parser::token::{Token, TokenKind};
use vlog_semantic::{Definition, ExternalResolutions, Symbol};
use super::Args;
use crate::project::{Analysis, Project};
/// What a selector points at.
pub(super) enum Target {
/// A byte position in a file.
At { path: PathBuf, analysis: Rc<Analysis>, offset: u32 },
/// A name to look up in the index, optionally inside one unit.
Named { name: String, unit: Option<String> },
}
/// Read the selector; the refusal says which combination is wanted.
pub(super) fn target(project: &mut Project, args: &Args) -> Result<Target, String> {
let Some(file) = args.str("file") else {
if args.int("line").is_some() || args.int("col").is_some() {
return Err("`line` and `col` need `file`.".into());
}
let Some(name) = args.str("name").filter(|name| !name.is_empty()) else {
return Err("give `file` with `line` and `col` (or `name`), or a `name`.".into());
};
let unit = args.str("unit").map(str::to_string);
return Ok(Target::Named { name: name.to_string(), unit });
};
if args.str("unit").is_some() {
return Err("`unit` belongs to the by-name form; drop `file`, `line` and `col`.".into());
}
let path = project.resolve(file)?;
let analysis = project.analysis(&path)?;
let shown = project.relative(&path);
let offset =
offset_in(project, &shown, &analysis, args).map_err(|e| format!("{e} (in `{file}`)"))?;
Ok(Target::At { path, analysis, offset })
}
/// The byte offset the position arguments name in one file.
fn offset_in(
project: &Project,
file: &str,
analysis: &Analysis,
args: &Args,
) -> Result<u32, String> {
let name = args.str("name").filter(|name| !name.is_empty());
let line = args.int("line").map(|line| u32::try_from(line).unwrap_or(u32::MAX));
let col = args.int("col").map(|col| u32::try_from(col).unwrap_or(u32::MAX));
match (line, col, name) {
(Some(line), Some(col), _) => at_column(analysis, line, col),
(Some(line), None, Some(name)) => on_line(analysis, line, name),
(Some(_), None, None) => Err("with `line`, give `col` or the `name` on that line".into()),
(None, Some(_), _) => Err("`col` needs `line`".into()),
(None, None, Some(name)) => first_occurrence(project, file, analysis, name),
(None, None, None) => Err("say what: `line` with `col` or `name`, or a `name`".into()),
}
}
/// `line:col`, refused when the line does not exist or the column lies past
/// its end (one past the last byte is the end itself, and allowed).
fn at_column(analysis: &Analysis, line: u32, col: u32) -> Result<u32, String> {
let lines = analysis.lines.line_count();
let Some(range) = analysis.lines.line_range(line) else {
return Err(format!("line {line} is past the end ({lines} lines)"));
};
let length = analysis.line_text(line).len() as u32;
if col > length.saturating_add(1) {
return Err(format!("line {line} is {length} bytes long; `col` {col} is past its end"));
}
Ok(range.start + col - 1)
}
/// The first token on `line` that spells `name`: an identifier, or a macro
/// use when `name` is written `` `NAME``. A name found only inside a macro
/// call's argument text is refused — lucisv does not resolve those.
fn on_line(analysis: &Analysis, line: u32, name: &str) -> Result<u32, String> {
let Some(range) = analysis.lines.line_range(line) else {
return Err(format!("line {line} is past the end ({} lines)", analysis.lines.line_count()));
};
let touching =
|| analysis.tokens.iter().filter(|t| t.span.end > range.start && t.span.start <= range.end);
let wanted_macro = name.strip_prefix('`');
let hit = touching().find(|token| match wanted_macro {
Some(spelled) => token.is_macro() && macro_name(token) == Some(spelled),
None => {
token.kind == TokenKind::Ident && !token.is_macro() && token.text.trim_end() == name
}
});
if let Some(token) = hit {
return Ok(token.span.start.max(range.start));
}
let in_argument =
touching().any(|t| t.is_macro() && super::source::word_in(&t.text, name).is_some());
if wanted_macro.is_none() && in_argument {
return Err(format!(
"`{name}` on line {line} is inside a macro argument, which lucisv does not resolve; give `col` on a plain use"
));
}
Err(format!("`{name}` is not written on line {line}"))
}
/// Where `name` occurs in a file: its one declaration, else its uses when
/// they all name one declaration, else its first macro use.
fn first_occurrence(
project: &Project,
file: &str,
analysis: &Analysis,
name: &str,
) -> Result<u32, String> {
let semantics = &analysis.semantics;
let declared: Vec<&Symbol> =
semantics.symbols_named(name).filter_map(|id| semantics.symbol(id)).collect();
match declared.as_slice() {
[one] => return Ok(one.name_span.start),
[] => {}
many => {
let lines: Vec<String> = many
.iter()
.map(|symbol| analysis.lines.line_col(symbol.name_span.start).0.to_string())
.collect();
return Err(format!(
"`{name}` is declared {} times (lines {}); add `line`",
many.len(),
lines.join(", ")
));
}
}
if let Some(offset) = one_use(project, file, analysis, name)? {
return Ok(offset);
}
let spelled = name.strip_prefix('`').unwrap_or(name);
analysis
.tokens
.iter()
.find(|token| token.is_macro() && macro_name(token) == Some(spelled))
.map(|token| token.span.start)
.ok_or_else(|| format!("`{name}` is not written here"))
}
/// The first use of `name` in a file that declares none — refused, listing
/// a line per declaration, when its uses name different declarations.
fn one_use(
project: &Project,
file: &str,
analysis: &Analysis,
name: &str,
) -> Result<Option<u32>, String> {
let semantics = &analysis.semantics;
let mut uses = semantics.references().iter().filter(|reference| reference.name == name);
let Some(first) = uses.next() else { return Ok(None) };
let external = analysis.external(project.index());
let mut targets: Vec<(u32, String)> = Vec::new();
for reference in std::iter::once(first).chain(uses) {
let offset = reference.name_span.start;
let Some(target) = declared_at(project, file, analysis, &external, offset) else {
continue;
};
if !targets.iter().any(|(_, known)| *known == target) {
targets.push((analysis.lines.line_col(offset).0, target));
}
}
if targets.len() > 1 {
let listed: Vec<String> =
targets.iter().map(|(line, target)| format!("line {line} → {target}")).collect();
return Err(format!("`{name}` on {}; add `line`", listed.join(", ")));
}
Ok(Some(first.name_span.start))
}
/// Where the use at `offset` is declared, as `file:line` (several joined
/// with ` or `), or `None` when nothing resolves it.
fn declared_at(
project: &Project,
file: &str,
analysis: &Analysis,
external: &ExternalResolutions,
offset: u32,
) -> Option<String> {
match external.definition_of(&analysis.semantics, offset)? {
Definition::Local(symbol) => {
Some(format!("{file}:{}", analysis.lines.line_col(symbol.name_span.start).0))
}
Definition::External(defs) => {
let index = project.index();
let sites: Vec<String> = defs
.iter()
.filter_map(|def| {
let path = index.path(def.file)?;
Some(format!("{}:{}", project.relative(path), def.lines.name))
})
.collect();
(!sites.is_empty()).then(|| sites.join(" or "))
}
}
}
/// The macro a use token names: `` `NAME(args) `` → `NAME`.
pub(super) fn macro_name(token: &Token) -> Option<&str> {
let rest = token.text.strip_prefix('`')?;
let end = rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '$');
let name = &rest[..end.unwrap_or(rest.len())];
(!name.is_empty()).then_some(name)
}
+88 -104
View File
@@ -1,13 +1,13 @@
//! Declaration sites read back off the disk: the navigation tools answer
//! with `file:line:col`, the kind, and the declaration's own source line,
//! for declarations in files no analysis is held for. One read per file per
//! call ([`Texts`]); the index's spans are checked against the bytes before
//! they are printed, so a stale span is omitted, never mislocated.
//! Declaration sites read back off the disk: `find` and the by-name tools
//! answer with `file:line` for declarations in files no analysis is held
//! for. One read per file per call ([`Texts`]); the index's spans are
//! checked against the bytes before they are printed, so a stale span is
//! omitted, never mislocated. Also the whole set a cross-file engine is
//! handed, and the small text helpers the answers share.
use std::collections::{BTreeSet, HashMap};
use std::path::{Path, PathBuf};
use serde_json::{json, Value};
use vlog_parser::span::TextRange;
use vlog_parser::LineIndex;
@@ -31,53 +31,12 @@ impl Texts {
});
held.as_ref().map(|(text, lines)| (text.as_str(), lines))
}
/// Keep a text the caller already read, so it is not read again.
pub fn hold(&mut self, path: PathBuf, text: String) {
let lines = LineIndex::new(&text);
self.held.insert(path, Some((text, lines)));
}
}
/// One place a declaration (or a use) is written.
pub struct Site {
pub file: String,
pub line: u32,
pub col: u32,
pub kind: &'static str,
/// The source line, whitespace collapsed.
pub text: String,
}
impl Site {
/// The site of `span` in `text`: its 1-based line and byte column, and
/// that line collapsed to one line of text.
pub fn at(
file: String,
text: &str,
lines: &LineIndex,
span: TextRange,
kind: &'static str,
) -> Site {
let (line, col) = lines.line_col(span.start);
let source = lines
.line_range(line)
.and_then(|range| text.get(range.start as usize..range.end as usize))
.unwrap_or("");
Site { file, line, col, kind, text: render::one_line(source) }
}
/// `file:line:col kind: text`.
pub fn render(&self) -> String {
format!("{}:{}:{} {}: {}", self.file, self.line, self.col, self.kind, self.text)
}
pub fn json(&self) -> Value {
json!({
"file": self.file, "line": self.line, "col": self.col,
"kind": self.kind, "text": self.text,
})
}
}
/// The site of an indexed span in `path`, when the file's bytes there still
@@ -90,24 +49,12 @@ pub fn checked_site(
name_span: TextRange,
shown: TextRange,
name: &str,
kind: &'static str,
) -> Option<Site> {
let (text, lines) = texts.get(path)?;
if text.get(name_span.as_range()) != Some(name) {
return None;
}
Some(Site::at(project.relative(path), text, lines, shown, kind))
}
/// Sites as a text answer (one per line, or `none_text`) and as JSON under
/// `key`, with the total.
pub fn answer(sites: &[Site], key: &str, none_text: &str) -> super::Answer {
let mut text: String = sites.iter().map(|site| site.render() + "\n").collect();
if sites.is_empty() {
text = format!("{none_text}\n");
}
let listed: Vec<Value> = sites.iter().map(Site::json).collect();
super::Answer { text, structured: json!({ key: listed, "total": sites.len() }) }
Some(Site { file: project.relative(path), line: lines.line_col(shown.start).0 })
}
/// `text` on one line, cut at `cap` characters with `…`.
@@ -120,34 +67,6 @@ pub fn capped(text: &str, cap: usize) -> String {
format!("{cut}…")
}
/// `text` with its `//` and `/* */` comments replaced by a space; string
/// literals are kept whole.
pub fn without_comments(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(at) = rest.find(['/', '"']) {
out.push_str(&rest[..at]);
let tail = &rest[at..];
let skip = if let Some(line) = tail.strip_prefix("//") {
out.push(' ');
2 + line.find('\n').unwrap_or(line.len())
} else if let Some(block) = tail.strip_prefix("/*") {
out.push(' ');
2 + block.find("*/").map_or(block.len(), |end| end + 2)
} else if let Some(string) = tail.strip_prefix('"') {
let end = 1 + string.find('"').map_or(string.len(), |end| end + 1);
out.push_str(&tail[..end]);
end
} else {
out.push('/');
1
};
rest = &tail[skip..];
}
out.push_str(rest);
out
}
/// The whole in-scope set a cross-file engine is handed: every indexed file,
/// and one more when asked, read from disk now — plus every file the set
/// could not include (over the size cap, not UTF-8, no longer readable),
@@ -157,6 +76,10 @@ pub struct WholeSet {
pub files: Vec<(PathBuf, String)>,
/// The files left out, with why.
pub skipped: Vec<(PathBuf, String)>,
/// How an engine sentence names each file of the set, and the
/// root-relative spelling it becomes — built once per set by
/// [`WholeSet::read`] ([`WholeSet::rooted`]).
names: Vec<(String, String)>,
}
impl WholeSet {
@@ -166,13 +89,14 @@ impl WholeSet {
pub fn read(project: &Project, extra: Option<&Path>) -> WholeSet {
let mut wanted: BTreeSet<PathBuf> = project.index().files().iter().cloned().collect();
wanted.extend(extra.map(Path::to_path_buf));
let mut set = WholeSet { files: Vec::new(), skipped: project.skipped() };
let mut set = WholeSet { files: Vec::new(), skipped: project.skipped(), names: Vec::new() };
for path in wanted {
match std::fs::read_to_string(&path) {
Ok(text) => set.files.push((path, text)),
Err(e) => set.skipped.push((path, format!("no longer reads: {e}"))),
}
}
set.names = names_of(project, &set.files);
set
}
@@ -186,6 +110,22 @@ impl WholeSet {
})
}
/// An engine sentence with every file of the set written root-relative.
/// The engines name a file by its base name when that is unique in the
/// set they were handed (`p1.sv:2` → `rtl/p1.sv:2`) and by the path they
/// were given otherwise (`/abs/…/top_a/pwrmgr_if.sv:80` →
/// `top_a/…/pwrmgr_if.sv:80`, generate-label-rename R1). One pass over
/// the set's spellings per sentence; the table itself is built once.
pub fn rooted(&self, sentence: &str) -> String {
let mut out = sentence.to_string();
for (spelled, shown) in &self.names {
if out.contains(spelled.as_str()) {
out = replace_file_name(&out, spelled, shown);
}
}
out
}
/// One line naming the skipped files (ten at most), or `None` when the
/// set is complete.
pub fn warning(&self, project: &Project) -> Option<String> {
@@ -204,6 +144,54 @@ impl WholeSet {
}
}
/// Every file's engine spelling and its root-relative one: the full path for
/// a base name several files share, else the base name (skipped when it is
/// already the relative path). Full paths first, so a bare base name never
/// rewrites the tail of one.
fn names_of(project: &Project, files: &[(PathBuf, String)]) -> Vec<(String, String)> {
let mut count: HashMap<&std::ffi::OsStr, usize> = HashMap::new();
for (path, _) in files {
if let Some(base) = path.file_name() {
*count.entry(base).or_default() += 1;
}
}
let (mut full, mut bare) = (Vec::new(), Vec::new());
for (path, _) in files {
let Some(base) = path.file_name() else { continue };
let shown = project.relative(path);
match count.get(base) {
Some(1) => {
if let Some(base) = base.to_str().filter(|base| *base != shown) {
bare.push((base.to_string(), shown));
}
}
_ => full.push((path.display().to_string(), shown)),
}
}
full.extend(bare);
full
}
/// `text` with every occurrence of the file name `base` that stands alone —
/// not the tail of a longer path or name — replaced by `path`.
fn replace_file_name(text: &str, base: &str, path: &str) -> String {
let glued_before = |c: char| is_ident_char(c) || matches!(c, '/' | '\\' | '.' | '-');
let glued_after = |c: char| is_ident_char(c) || matches!(c, '/' | '-');
let mut out = String::with_capacity(text.len());
let mut from = 0;
while let Some(found) = text[from..].find(base) {
let (start, end) = (from + found, from + found + base.len());
let before = text[..start].chars().next_back();
let after = text[end..].chars().next();
let alone = !before.is_some_and(glued_before) && !after.is_some_and(glued_after);
out.push_str(&text[from..start]);
out.push_str(if alone { path } else { base });
from = end;
}
out.push_str(&text[from..]);
out
}
/// Whether `name` occurs in `bytes` not glued to an identifier character on
/// either side — how an identifier, escaped or not, is written.
fn word_in_bytes(bytes: &[u8], name: &[u8]) -> bool {
@@ -258,6 +246,16 @@ mod tests {
assert_eq!(word_in("anything", ""), None);
}
#[test]
fn a_bare_file_name_is_replaced_only_where_it_stands_alone() {
let said = "at `u_s` (p1.sv:2), in p1.sv, not rtl/p1.sv, xp1.sv or p1.svh";
assert_eq!(
replace_file_name(said, "p1.sv", "rtl/p1.sv"),
"at `u_s` (rtl/p1.sv:2), in rtl/p1.sv, not rtl/p1.sv, xp1.sv or p1.svh"
);
assert_eq!(replace_file_name("p1.sv:6", "p1.sv", "a/p1.sv"), "a/p1.sv:6");
}
#[test]
fn a_skipped_file_is_searched_for_whole_words_only() {
assert!(word_in_bytes(b"leaf u (.d(x));", b"d"));
@@ -268,22 +266,8 @@ mod tests {
}
#[test]
fn comments_are_dropped_and_strings_kept() {
let text = "#( // why\n .W(8), /* old: 4 */ .S(\"a//b\"), .D(4 / 2) )";
assert_eq!(
render::one_line(&without_comments(text)),
"#( .W(8), .S(\"a//b\"), .D(4 / 2) )"
);
assert_eq!(without_comments("a /* open"), "a ");
fn a_capped_text_is_one_line_cut_with_an_ellipsis() {
assert_eq!(capped("x y", 2), "x …");
assert_eq!(capped("x y", 3), "x y");
}
#[test]
fn a_site_prints_its_line_collapsed() {
let text = "module m;\n logic [3:0] x;\nendmodule\n";
let lines = LineIndex::new(text);
let site = Site::at("m.sv".into(), text, &lines, TextRange::new(27, 28), "var");
assert_eq!(site.render(), "m.sv:2:18 var: logic [3:0] x;");
}
}
+786
View File
@@ -0,0 +1,786 @@
//! The dev's attack suite on the structural edits' verifier (lane M4) —
//! CLAUDE.md invariant 4 applied to the MCP block's own safety net: every
//! case is an edit the verifier could plausibly let through, asserted
//! **refused with the tree byte-identical** (every file hashed before and
//! after). A few controls sit beside them: the nearest edit that must pass,
//! so a refusal is known to come from the rule and not from a broken setup.
//!
//! The cases were written against `replace_item`, `insert_item` and
//! `delete_item`; the lean catalogue folds the three into `edit_item`
//! (PLAN §10.1), so [`lean`] maps each call and the cases stay as written.
//! What the lean surface removed (`dry_run`, `rename`, `force`) is gone from
//! the cases too: a refusal is checked once, and a forced deletion is now a
//! refusal like any other.
use std::collections::hash_map::DefaultHasher;
use std::collections::BTreeMap;
use std::fs;
use std::hash::{Hash, Hasher};
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{self, Receiver};
use std::time::{Duration, Instant};
use serde_json::{json, Value};
const ANSWER_TIMEOUT: Duration = Duration::from_secs(120);
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
/// A scratch tree: the `item` fixture plus the files a case adds.
struct Tree(PathBuf);
impl Tree {
fn with(files: &[(&str, &str)]) -> Tree {
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
let dir = std::env::temp_dir()
.join(format!("lucisv-mcp-attacks-{}-{unique}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
let fixture = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/item");
copy_tree(&fixture, &dir);
for (name, text) in files {
fs::write(dir.join(name), text).unwrap();
}
Tree(fs::canonicalize(dir).unwrap())
}
/// Every file, root-relative, with the hash of its bytes.
fn hashes(&self) -> BTreeMap<String, u64> {
fn walk(dir: &Path, root: &Path, out: &mut BTreeMap<String, u64>) {
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
walk(&path, root, out);
continue;
}
let mut hasher = DefaultHasher::new();
fs::read(&path).unwrap().hash(&mut hasher);
let name = path.strip_prefix(root).unwrap().to_string_lossy().into_owned();
out.insert(name, hasher.finish());
}
}
let mut out = BTreeMap::new();
walk(&self.0, &self.0, &mut out);
out
}
fn read(&self, file: &str) -> String {
fs::read_to_string(self.0.join(file)).unwrap()
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn copy_tree(from: &Path, to: &Path) {
fs::create_dir_all(to).unwrap();
for entry in fs::read_dir(from).unwrap() {
let entry = entry.unwrap();
let target = to.join(entry.file_name());
if entry.file_type().unwrap().is_dir() {
copy_tree(&entry.path(), &target);
} else {
fs::copy(entry.path(), target).unwrap();
}
}
}
/// One running server, initialised.
struct Session {
child: Child,
stdin: ChildStdin,
lines: Receiver<String>,
next_id: i64,
}
impl Session {
fn over(tree: &Tree) -> Session {
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
.args(["--root", tree.0.to_str().unwrap()])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
let stdout = child.stdout.take().unwrap();
let (send, lines) = mpsc::channel();
std::thread::spawn(move || {
for line in BufReader::new(stdout).lines().map_while(Result::ok) {
if send.send(line).is_err() {
break;
}
}
});
let stdin = child.stdin.take().unwrap();
let mut session = Session { child, stdin, lines, next_id: 0 };
session.request("initialize", json!({"protocolVersion": "2025-06-18", "capabilities": {}}));
session.send(&json!({"jsonrpc": "2.0", "method": "notifications/initialized"}));
session
}
fn send(&mut self, message: &Value) {
writeln!(self.stdin, "{message}").unwrap();
self.stdin.flush().unwrap();
}
fn request(&mut self, method: &str, params: Value) -> Value {
self.next_id += 1;
let id = self.next_id;
self.send(&json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}));
let line = self.lines.recv_timeout(ANSWER_TIMEOUT).expect("the server answered");
let reply: Value = serde_json::from_str(&line).unwrap();
assert_eq!(reply["id"], id);
reply
}
/// A tool call: whether it was refused, and its text.
fn call(&mut self, tool: &str, arguments: Value) -> (bool, String) {
let (tool, arguments) = lean(tool, arguments);
let reply = self.request("tools/call", json!({"name": tool, "arguments": arguments}));
let result = &reply["result"];
let text = result["content"][0]["text"].as_str().unwrap_or_default().to_string();
(result["isError"] == true, text)
}
}
impl Drop for Session {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
/// An M4 call as `edit_item` takes it: `replace_item`'s `item`,
/// `insert_item`'s `anchor` and `position`, `delete_item`'s `item`, each
/// under its `op`.
fn lean(tool: &str, mut args: Value) -> (&'static str, Value) {
let op = match tool {
"replace_item" => "replace",
"delete_item" => "delete",
"insert_item" => {
let before = args["position"] == "before";
let object = args.as_object_mut().unwrap();
object.remove("position");
let anchor = object.remove("anchor").unwrap();
object.insert("item".into(), anchor);
if before {
"insert_before"
} else {
"insert_after"
}
}
other => panic!("not a structural edit: {other}"),
};
args["op"] = Value::from(op);
("edit_item", args)
}
/// Run `tool` and assert it refuses with a sentence holding `why`, leaving
/// every file of the tree byte-identical.
fn refused(tree: &Tree, server: &mut Session, tool: &str, args: Value, why: &str) {
let before = tree.hashes();
let (error, text) = server.call(tool, args.clone());
assert!(error, "{tool} {args}: not refused: {text}");
assert!(text.contains(why), "{tool} {args}: `{why}` not in: {text}");
assert!(text.ends_with("nothing written.") || text.contains("nothing written"), "{text}");
assert_eq!(before, tree.hashes(), "{tool} {args}: a refusal wrote");
}
/// Run `tool` and assert it wrote (the control beside an attack).
fn accepted(server: &mut Session, tool: &str, args: Value) -> String {
let (error, text) = server.call(tool, args.clone());
assert!(!error, "{tool} {args}: refused: {text}");
text
}
fn core(item: &str, text: &str) -> Value {
json!({"file": "rtl/core.sv", "item": item, "text": text})
}
#[test]
fn a_text_that_opens_a_block_it_does_not_close_is_refused() {
let tree = Tree::with(&[]);
let mut server = Session::over(&tree);
let open = "always_ff @(posedge clk) begin\n r <= d;";
refused(&tree, &mut server, "replace_item", core("always@12", open), "no longer parse");
let unclosed_function = "function automatic int f(int a);\n return a;";
let args = json!({"file": "rtl/core.sv", "anchor": "r", "text": unclosed_function});
refused(&tree, &mut server, "insert_item", args, "no longer parse");
}
#[test]
fn a_text_that_closes_the_enclosing_module_is_refused() {
let tree = Tree::with(&[]);
let mut server = Session::over(&tree);
// Still a valid file: `r` ends `core` and the rest becomes `sneaky`.
let closes = "logic [7:0] r;\nendmodule\nmodule sneaky;";
refused(&tree, &mut server, "replace_item", core("r", closes), "open and close");
let end = json!({"file": "rtl/wrap.sv", "anchor": "end", "text": "endmodule\nmodule sneaky;"});
refused(&tree, &mut server, "insert_item", end, "open and close");
}
#[test]
fn a_text_that_redeclares_a_port_is_refused() {
let tree = Tree::with(&[]);
let mut server = Session::over(&tree);
// The duplicate rule fires before the name rule: a port is never
// redeclared.
refused(
&tree,
&mut server,
"replace_item",
core("p", "logic d;"),
"`d` would be declared twice",
);
let insert = json!({"file": "rtl/core.sv", "anchor": "p", "text": "logic [3:0] clk;"});
refused(&tree, &mut server, "insert_item", insert, "`clk` would be declared twice");
}
#[test]
fn two_items_where_one_was_and_an_empty_text_are_refused() {
let tree = Tree::with(&[]);
let mut server = Session::over(&tree);
let two = "logic p;\n logic p2;";
refused(&tree, &mut server, "replace_item", core("p", two), "holds 2 items where one was");
let empty_item = "logic p;;";
refused(&tree, &mut server, "replace_item", core("p", empty_item), "holds 2 items");
for empty in ["", " \n\t\r\n"] {
refused(&tree, &mut server, "replace_item", core("p", empty), "`op: delete` removes");
let args = json!({"file": "rtl/core.sv", "anchor": "end", "text": empty});
refused(&tree, &mut server, "insert_item", args, "`text` is empty");
}
}
const UTF8: &str =
"module u;\n logic a;// \u{fc}\u{20ac} note\n /*\u{e9}*/logic b;/*\u{df}*/\nendmodule\n";
#[test]
fn a_multibyte_neighbour_stays_byte_identical_and_a_non_ascii_name_is_refused() {
let tree = Tree::with(&[("rtl/u.sv", UTF8)]);
let mut server = Session::over(&tree);
let args = json!({"file": "rtl/u.sv", "item": "b", "text": "logic b\u{e9};"});
refused(&tree, &mut server, "replace_item", args, "the file would no longer");
let after = json!({"file": "rtl/u.sv", "anchor": "a", "text": "logic \u{e9};"});
refused(&tree, &mut server, "insert_item", after, "would no longer");
// The control: the comments hugging `b` on both sides, multibyte, stay.
accepted(
&mut server,
"replace_item",
json!({"file": "rtl/u.sv", "item": "b", "text": "logic [1:0] b;"}),
);
assert_eq!(tree.read("rtl/u.sv"), UTF8.replace("logic b;", "logic [1:0] b;"));
// A multibyte comment inside the new text is the agent's to write.
accepted(
&mut server,
"replace_item",
json!({"file": "rtl/u.sv", "item": "b", "text": "logic b; // \u{e9}"}),
);
}
#[test]
fn nothing_inside_a_format_fence_is_edited() {
let tree = Tree::with(&[]);
let mut server = Session::over(&tree);
let fence = "`// lucisv: off` fence";
refused(&tree, &mut server, "replace_item", core("keep_me", "logic keep_me;"), fence);
refused(
&tree,
&mut server,
"delete_item",
json!({"file": "rtl/core.sv", "item": "keep_me"}),
fence,
);
for position in ["before", "after"] {
let args = json!({"file": "rtl/core.sv", "anchor": "keep_me", "position": position, "text": "logic z;"});
refused(&tree, &mut server, "insert_item", args, fence);
}
// Deleting the fenced region's owner, or an item whose leading comment
// is the `on` fence, would move a fence.
refused(
&tree,
&mut server,
"delete_item",
json!({"file": "rtl/core.sv", "item": "core"}),
fence,
);
refused(
&tree,
&mut server,
"delete_item",
json!({"file": "rtl/core.sv", "item": "always@22"}),
fence,
);
}
#[test]
fn a_file_or_a_text_with_an_unterminated_string_is_refused() {
let broken = "module s;\n initial $display(\"oops);\n logic a;\nendmodule\n";
let tree = Tree::with(&[("rtl/s.sv", broken)]);
let mut server = Session::over(&tree);
let args = json!({"file": "rtl/s.sv", "item": "a", "text": "logic [1:0] a;"});
refused(&tree, &mut server, "replace_item", args, "does not lex");
let end = json!({"file": "rtl/s.sv", "anchor": "end", "text": "logic b;"});
refused(&tree, &mut server, "insert_item", end, "does not lex");
refused(&tree, &mut server, "replace_item", core("p", "logic p = \"x;"), "no longer lex");
}
#[test]
fn an_insert_after_endmodule_must_be_something_a_file_may_hold() {
let tree = Tree::with(&[]);
let mut server = Session::over(&tree);
// Both parse: the parser accepts module items at file scope.
for text in ["always_comb q = r;", "assign q = 8'h0;", "core u_again (.*);"] {
let args =
json!({"file": "rtl/wrap.sv", "anchor": "wrap", "position": "after", "text": text});
refused(&tree, &mut server, "insert_item", args, "cannot stand in a file's scope");
}
let in_package =
json!({"file": "rtl/item_pkg.sv", "anchor": "end", "text": "initial $display(1);"});
refused(&tree, &mut server, "insert_item", in_package, "cannot stand in a package's scope");
// The control: a module after a module.
let module =
json!({"file": "rtl/wrap.sv", "anchor": "wrap", "text": "module extra;\nendmodule"});
accepted(&mut server, "insert_item", module);
assert!(tree.read("rtl/wrap.sv").ends_with("endmodule\n\nmodule extra;\nendmodule\n"));
}
#[test]
fn a_valid_item_of_another_kind_is_refused() {
let tree = Tree::with(&[]);
let mut server = Session::over(&tree);
let function = "function automatic int f(int a);\n return a;\n endfunction";
refused(
&tree,
&mut server,
"replace_item",
core("always@12", function),
"a function where a always was",
);
let initial = "initial r = '0;";
refused(
&tree,
&mut server,
"replace_item",
core("always@12", initial),
"initial where a always",
);
refused(
&tree,
&mut server,
"replace_item",
core("p", "assign q = 8'h1;"),
"assign where a declaration",
);
// The control: `always_ff` may become `always_comb` — one class.
accepted(&mut server, "replace_item", core("always@22", "always @* p = ^r;"));
}
const ESCAPED: &str = "module e;\n logic \\a+b ;\n assign \\a+b = 1'b0;\nendmodule\n";
#[test]
fn an_escaped_name_is_matched_exactly() {
let tree = Tree::with(&[("rtl/e.sv", ESCAPED)]);
let mut server = Session::over(&tree);
let args = json!({"file": "rtl/e.sv", "item": "\\a+b", "text": "logic \\a+c ;"});
refused(
&tree,
&mut server,
"replace_item",
args,
"declares `\\a+c` where the item declared `\\a+b`",
);
let delete = json!({"file": "rtl/e.sv", "item": "\\a+b"});
refused(&tree, &mut server, "delete_item", delete, "rtl/e.sv:3:10 `\\a+b`");
let args = json!({"file": "rtl/e.sv", "item": "\\a+b", "text": "logic [1:0] \\a+b ;"});
accepted(&mut server, "replace_item", args);
assert_eq!(tree.read("rtl/e.sv"), ESCAPED.replace("logic \\a+b", "logic [1:0] \\a+b"));
}
#[test]
fn half_an_ifdef_is_refused_in_either_direction() {
let guarded = "module g;\n`ifdef FAST\n logic a;\n`endif\n logic b;\nendmodule\n";
let tree = Tree::with(&[("rtl/g.sv", guarded)]);
let mut server = Session::over(&tree);
let open = "`ifdef FAST\n logic [7:0] r;";
refused(&tree, &mut server, "replace_item", core("r", open), "holds 2 items");
// One item — a module — carrying half a guard inside it.
let inside = "module tick (\n input logic clk\n);\n`ifdef X\nendmodule";
let args = json!({"file": "rtl/tick.sv", "item": "tick", "text": inside});
refused(&tree, &mut server, "replace_item", args, "`ifdef` whose other half");
let close = json!({"file": "rtl/core.sv", "anchor": "r", "text": "`endif\nlogic z;"});
refused(&tree, &mut server, "insert_item", close, "`endif` whose other half");
let orphan =
json!({"file": "rtl/g.sv", "anchor": "b", "position": "before", "text": "`else\nlogic c;"});
refused(&tree, &mut server, "insert_item", orphan, "`else` whose other half");
// The controls: a balanced guard inserts; an item inside one replaces.
let whole =
json!({"file": "rtl/g.sv", "anchor": "b", "text": "`ifdef SLOW\n logic c;\n`endif"});
accepted(&mut server, "insert_item", whole);
accepted(
&mut server,
"replace_item",
json!({"file": "rtl/g.sv", "item": "a", "text": "logic [1:0] a;"}),
);
}
#[test]
fn an_insert_or_delete_on_a_shared_line_is_refused() {
let shared = "module n; logic q; logic w; endmodule\n";
let tree = Tree::with(&[("rtl/n.sv", shared)]);
let mut server = Session::over(&tree);
let delete = json!({"file": "rtl/n.sv", "item": "q"});
refused(&tree, &mut server, "delete_item", delete, "shares a line");
let insert = json!({"file": "rtl/n.sv", "anchor": "w", "text": "logic e;"});
refused(&tree, &mut server, "insert_item", insert, "shares a line");
let end = json!({"file": "rtl/n.sv", "anchor": "end", "text": "logic e;"});
refused(&tree, &mut server, "insert_item", end, "shares a line");
// `replace_item` needs no line of its own: the span is the span.
accepted(
&mut server,
"replace_item",
json!({"file": "rtl/n.sv", "item": "q", "text": "logic [1:0] q;"}),
);
assert_eq!(tree.read("rtl/n.sv"), "module n; logic [1:0] q; logic w; endmodule\n");
}
#[test]
fn a_port_in_a_header_is_not_an_item_and_a_non_ansi_body_port_keeps_its_header() {
let non_ansi =
"module k (a, b);\n input [3:0] a;\n output b;\n assign b = 1'b0;\nendmodule\n";
let tree = Tree::with(&[("rtl/k.sv", non_ansi)]);
let mut server = Session::over(&tree);
refused(
&tree,
&mut server,
"replace_item",
core("d", "input logic [3:0] d"),
"part of a larger item",
);
refused(
&tree,
&mut server,
"delete_item",
json!({"file": "rtl/core.sv", "item": "clk"}),
"part of a larger item",
);
let body = json!({"file": "rtl/k.sv", "item": "a"});
refused(&tree, &mut server, "delete_item", body, "`a` is also declared on line 1");
let widen = json!({"file": "rtl/k.sv", "item": "a", "text": "input [7:0] a;"});
accepted(&mut server, "replace_item", widen);
}
/// A module of `lines` lines: `logic sN;` declarations with one always
/// block in the middle.
fn big_module(lines: usize) -> String {
let mut text = String::from("module big (input logic clk);\n");
for n in 0..lines - 3 {
if n == lines / 2 {
text.push_str(" always_ff @(posedge clk) s0 <= ~s0;\n");
} else {
text.push_str(&format!(" logic s{n};\n"));
}
}
text.push_str("endmodule\n");
text
}
#[test]
fn a_forty_thousand_line_file_is_verified_in_bounded_time() {
let big = big_module(40_000);
let tree = Tree::with(&[("rtl/big.sv", &big)]);
let mut server = Session::over(&tree);
let line = big.lines().position(|l| l.contains("always_ff")).unwrap() + 1;
let item = format!("always@{line}");
let timed = |server: &mut Session, tool: &str, args: Value| {
let started = Instant::now();
let answer = server.call(tool, args);
(answer, started.elapsed().as_millis())
};
let before = tree.hashes();
let open =
json!({"file": "rtl/big.sv", "item": item, "text": "always_ff @(posedge clk) begin"});
let ((error, text), refused_ms) = timed(&mut server, "replace_item", open);
assert!(error && text.contains("no longer parse"), "{text}");
assert_eq!(before, tree.hashes());
let good =
json!({"file": "rtl/big.sv", "item": item, "text": "always_ff @(posedge clk) s0 <= s0;"});
let ((error, text), replaced_ms) = timed(&mut server, "replace_item", good);
assert!(!error, "{text}");
let insert = json!({"file": "rtl/big.sv", "anchor": "end", "text": "logic tail;"});
let ((error, text), inserted_ms) = timed(&mut server, "insert_item", insert);
assert!(!error, "{text}");
let delete = json!({"file": "rtl/big.sv", "item": "s7"});
let ((error, text), deleted_ms) = timed(&mut server, "delete_item", delete);
assert!(!error, "{text}");
println!(
"40 000 lines: refused replace {refused_ms} ms, replace {replaced_ms} ms, insert {inserted_ms} ms, delete {deleted_ms} ms"
);
}
const LOOP: &str = "module h;\n for (genvar i = 0; i < 2; i++) begin : gen_l\n logic z;\n end\n assign gen_l[0].z = 1'b0;\nendmodule\n";
#[test]
fn a_generate_loop_owns_its_label() {
let tree = Tree::with(&[("rtl/h.sv", LOOP)]);
let mut server = Session::over(&tree);
let relabel = "for (genvar i = 0; i < 2; i++) begin : gen_m\n logic z;\n end";
let args = json!({"file": "rtl/h.sv", "item": "gen_l", "text": relabel});
refused(
&tree,
&mut server,
"replace_item",
args,
"declares `gen_m`, `i` where the item declared `gen_l`, `i`",
);
let delete = json!({"file": "rtl/h.sv", "item": "gen_l"});
refused(&tree, &mut server, "delete_item", delete, "rtl/h.sv:5:10 `gen_l`");
// The control: a wider body under the same label.
let wider = "for (genvar i = 0; i < 2; i++) begin : gen_l\n logic [1:0] z;\n end";
accepted(
&mut server,
"replace_item",
json!({"file": "rtl/h.sv", "item": "gen_l", "text": wider}),
);
}
// ---- the rework's attacks (QA findings 1–8, 2026-09-23) --------------------
const FENCE_BELOW: &str = "module f;
logic a;
logic b; // b's own
// lucisv: off
/* hand aligned */
logic keep_me;
// lucisv: on
logic z;
endmodule
";
/// Rule 1a/1b (finding 1): a text may not reach past its own end — an open
/// comment a later `*/` closes, or a comment left on a line of its own that
/// would lead the next item.
#[test]
fn a_text_reaching_past_its_end_is_refused_by_the_lexical_rules() {
let tree = Tree::with(&[("rtl/f.sv", FENCE_BELOW)]);
let mut server = Session::over(&tree);
let args = json!({"file": "rtl/f.sv", "item": "a", "text": "logic a; /* note"});
refused(&tree, &mut server, "replace_item", args, "rule 1a");
let args = json!({"file": "rtl/f.sv", "anchor": "a", "text": "logic y; /* note"});
refused(&tree, &mut server, "insert_item", args, "rule 1a");
let args = json!({"file": "rtl/f.sv", "item": "a", "text": "logic a;\n // about b"});
refused(&tree, &mut server, "replace_item", args, "rule 1b");
// The control: a comment on the item's own line stays the item's.
let args = json!({"file": "rtl/f.sv", "item": "a", "text": "logic a; /* note */"});
accepted(&mut server, "replace_item", args);
assert_eq!(tree.read("rtl/f.sv"), FENCE_BELOW.replace("logic a;", "logic a; /* note */"));
}
const DOCUMENTED: &str = "module d;
// Section banner
// old doc of a
logic a; // old trailing
logic b;
endmodule
";
/// Finding 2: a text carrying the item's comments replaces the item's own
/// comments with it, so the same call twice is `unchanged`; a banner a blank
/// line separates from the item is not the item's.
#[test]
fn a_text_with_comments_replaces_the_items_own_and_repeats_unchanged() {
let tree = Tree::with(&[("rtl/d.sv", DOCUMENTED)]);
let mut server = Session::over(&tree);
let text = "// new doc of a\n logic [1:0] a; // new trailing";
let args = json!({"file": "rtl/d.sv", "item": "a", "text": text});
accepted(&mut server, "replace_item", args.clone());
let once = tree.read("rtl/d.sv");
let expected = DOCUMENTED.replace(
"// old doc of a\n logic a; // old trailing",
"// new doc of a\n logic [1:0] a; // new trailing",
);
assert_eq!(once, expected);
let again = accepted(&mut server, "replace_item", args);
assert!(again.starts_with("unchanged"), "{again}");
assert_eq!(tree.read("rtl/d.sv"), once);
// Without comments in the text, the item's comments stay where they are.
let args = json!({"file": "rtl/d.sv", "item": "a", "text": "logic a;"});
accepted(&mut server, "replace_item", args);
assert_eq!(tree.read("rtl/d.sv"), once.replace("logic [1:0] a;", "logic a;"));
}
const MACROS: &str = "`define ID(x) x
`define CHECK(s) initial assert (!$isunknown(s));
module mc (output logic o);
logic in_arg;
logic in_nested;
logic in_other_body;
logic free;
assign o = `ID(in_arg);
`CHECK(`ID(in_nested))
// free is only named in this comment
initial $display(\"free\");
endmodule
";
const MACRO_HEADER: &str = "`define READ_OTHER in_other_body\n";
/// Finding 3: a spelling inside a macro call (nested too) or another file's
/// `` `define`` body is a possible use; a comment or a string is not.
#[test]
fn a_name_spelled_inside_a_macro_is_a_possible_use() {
let tree = Tree::with(&[("rtl/mc.sv", MACROS), ("rtl/defs.svh", MACRO_HEADER)]);
let mut server = Session::over(&tree);
for (name, line) in [("in_arg", "rtl/mc.sv:8"), ("in_nested", "rtl/mc.sv:9")] {
let args = json!({"file": "rtl/mc.sv", "item": name});
refused(
&tree,
&mut server,
"delete_item",
args,
&format!("possible use (macro) at {line} `{name}`"),
);
}
let args = json!({"file": "rtl/mc.sv", "item": "in_other_body"});
refused(
&tree,
&mut server,
"delete_item",
args,
"possible use (macro) at rtl/defs.svh:1 `in_other_body`",
);
// The control: a name spelled only in a comment and a string goes.
accepted(&mut server, "delete_item", json!({"file": "rtl/mc.sv", "item": "free"}));
}
const BANNERS: &str = "// File banner
module fb;
// Registers
// the a flop
logic a;
logic b;
endmodule
";
/// Finding 4: a comment a blank line separates from the item is not the
/// item's — not a section banner, not the file banner above a module.
#[test]
fn a_delete_leaves_the_comments_a_blank_line_separates_from_the_item() {
let tree = Tree::with(&[("rtl/fb.sv", BANNERS)]);
let mut server = Session::over(&tree);
accepted(&mut server, "delete_item", json!({"file": "rtl/fb.sv", "item": "a"}));
assert_eq!(tree.read("rtl/fb.sv"), BANNERS.replace(" // the a flop\n logic a;\n", ""));
accepted(&mut server, "delete_item", json!({"file": "rtl/fb.sv", "item": "fb"}));
assert_eq!(tree.read("rtl/fb.sv"), "// File banner\n\n");
}
/// Finding 5: a comment before the item on its line goes with the item; only
/// another item's code on the line makes it shared.
#[test]
fn a_same_line_comment_goes_with_its_item_and_code_still_shares_the_line() {
let src = "module sl;\n /* lead */ logic a;\n logic x; /* c */ logic y;\nendmodule\n";
let tree = Tree::with(&[("rtl/sl.sv", src)]);
let mut server = Session::over(&tree);
let delete = json!({"file": "rtl/sl.sv", "item": "y"});
refused(&tree, &mut server, "delete_item", delete, "shares a line");
accepted(&mut server, "delete_item", json!({"file": "rtl/sl.sv", "item": "a"}));
assert_eq!(tree.read("rtl/sl.sv"), "module sl;\n logic x; /* c */ logic y;\nendmodule\n");
}
const DEFINES: &str = "`define W 1'b1
module dm (output logic o, output logic p);
always_comb begin
p = 1'b0;
end
assign o = `W;
endmodule
";
/// Rule 6 (finding 6): a `` `define``/`` `undef`` nested in an item changes
/// code outside it — refused by replace, insert and delete; a directive item
/// of its own is the control.
#[test]
fn a_macro_definition_nested_in_an_item_is_refused() {
let tree = Tree::with(&[("rtl/dm.sv", DEFINES)]);
let mut server = Session::over(&tree);
let nested = "always_comb begin\n`undef W\n p = 1'b0;\n end";
let args = json!({"file": "rtl/dm.sv", "item": "always@3", "text": nested});
refused(&tree, &mut server, "replace_item", args, "changes a macro definition (`W`)");
let insert = json!({"file": "rtl/dm.sv", "anchor": "always@3", "text": "initial begin\n`define W 1'b0\n end"});
refused(&tree, &mut server, "insert_item", insert, "(rule 6)");
let with_define = DEFINES.replace(" p = 1'b0;\n", "`define Q 1\n p = 1'b0;\n");
let tree = Tree::with(&[("rtl/dm.sv", &with_define)]);
let mut server = Session::over(&tree);
let delete = json!({"file": "rtl/dm.sv", "item": "always@3"});
refused(&tree, &mut server, "delete_item", delete, "(`Q`)");
// The control: a directive item of its own may be inserted.
let args = json!({"file": "rtl/dm.sv", "anchor": "always@3", "text": "`define R 2"});
accepted(&mut server, "insert_item", args);
}
/// Rule 7 (finding 7): a text neither opens nor closes a fence.
#[test]
fn a_text_may_not_carry_a_fence_marker() {
let tree = Tree::with(&[]);
let mut server = Session::over(&tree);
let text = "// lucisv: off\n logic lo;";
let args = json!({"file": "rtl/core.sv", "anchor": "p", "text": text});
refused(&tree, &mut server, "insert_item", args, "fence marker `// lucisv: off`");
let text = "always_comb begin\n // lucisv: on\n p = ^r;\n end";
refused(&tree, &mut server, "replace_item", core("always@22", text), "(rule 7)");
// The control: an ordinary comment in the same place.
let text = "always_comb begin\n // lucisv: parity\n p = ^r;\n end";
accepted(&mut server, "replace_item", core("always@22", text));
}
const STARS: &str = "module sw;
logic clk;
logic rst_ni;
logic [7:0] d;
logic [7:0] q;
logic unrelated;
if (1) begin : g
core u_core (.*);
end
endmodule
module other;
logic d;
ghost u_ghost (.*);
endmodule
";
/// Finding 8: a `.*` binds without spelling the name — a port of the
/// instantiated module is a use (generate blocks included); a module the
/// index cannot resolve makes every name a possible use in that scope.
#[test]
fn a_signal_bound_by_a_dot_star_is_still_referenced() {
let tree = Tree::with(&[("rtl/sw.sv", STARS)]);
let mut server = Session::over(&tree);
let args = json!({"file": "rtl/sw.sv", "item": "d@4"});
refused(
&tree,
&mut server,
"delete_item",
args,
"bound by `.*` at rtl/sw.sv:8:18 `d` (module `core`)",
);
let args = json!({"file": "rtl/sw.sv", "item": "d@12"});
refused(
&tree,
&mut server,
"delete_item",
args,
"possible use (`.*`) at rtl/sw.sv:13:18 `d` (module `ghost`",
);
// The controls: a signal the module has no port for; a module's own `.*`
// does not reach another module's names.
accepted(&mut server, "delete_item", json!({"file": "rtl/sw.sv", "item": "unrelated"}));
let clk = json!({"file": "rtl/sw.sv", "item": "clk"});
refused(&tree, &mut server, "delete_item", clk, "bound by `.*` at rtl/sw.sv:7:18 `clk`");
}
+257
View File
@@ -0,0 +1,257 @@
//! The index caches over the wire (TODO-MCP M6, PLAN §6): the language
//! server's `index-cache` is read and never written — its bytes are hashed
//! before and after a whole session that indexes, answers and edits — every
//! record that is not exactly right is skipped, a missing or unwritable
//! cache directory costs a cold start and nothing else, and the server's own
//! `index-cache-mcp` is written on exit and read on the next start.
use std::fs;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use lucisv_core::cache::content_hash;
use serde_json::{json, Value};
use vlog_semantic::{FileFacts, FACTS_FORMAT};
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
/// The design fixture's file count.
const FILES: usize = 7;
/// A fresh copy of `tests/fixtures/design` under `<dir>/src`, and `<dir>/cache`
/// for the stores; removed on drop.
struct Scratch(PathBuf);
impl Scratch {
fn new() -> Scratch {
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
let dir =
std::env::temp_dir().join(format!("lucisv-mcp-cache-{}-{unique}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/design");
copy_tree(&source, &dir.join("src"));
Scratch(fs::canonicalize(dir).unwrap())
}
fn src(&self) -> PathBuf {
self.0.join("src")
}
fn cache(&self) -> PathBuf {
self.0.join("cache")
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn copy_tree(from: &Path, to: &Path) {
fs::create_dir_all(to).unwrap();
for entry in fs::read_dir(from).unwrap() {
let entry = entry.unwrap();
let target = to.join(entry.file_name());
if entry.file_type().unwrap().is_dir() {
copy_tree(&entry.path(), &target);
} else {
fs::copy(entry.path(), target).unwrap();
}
}
}
/// Every file under `dir`, sorted.
fn files(dir: &Path) -> Vec<PathBuf> {
let mut out = Vec::new();
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
out.extend(files(&path));
} else {
out.push(path);
}
}
out.sort();
out
}
/// The language server's header for this build.
fn header(version: &str) -> String {
format!("lucisv-index-cache\t2\t{FACTS_FORMAT}\t{version}")
}
/// One record in the language server's format.
fn record(path: &Path) -> String {
let bytes = fs::read(path).unwrap();
let facts = FileFacts::of(path.to_path_buf(), std::str::from_utf8(&bytes).unwrap());
let encoded = facts.encode().unwrap();
let checksum = content_hash(encoded.as_bytes());
format!("{:016x}\t{encoded}\t{checksum:016x}", content_hash(&bytes))
}
/// A store the way the language server writes one, over every source file.
fn editor_store(scratch: &Scratch, version: &str) -> Vec<String> {
let mut lines = vec![header(version)];
lines.extend(files(&scratch.src()).iter().map(|path| record(path)));
lines
}
/// One server over the scratch design with `--index-cache`.
struct Session {
child: Child,
next_id: i64,
stdout: std::io::BufReader<std::process::ChildStdout>,
}
impl Session {
fn start(scratch: &Scratch) -> Session {
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
.arg("--root")
.arg(scratch.src())
.arg("--index-cache")
.arg(scratch.cache())
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let stdout = std::io::BufReader::new(child.stdout.take().unwrap());
let mut session = Session { child, next_id: 0, stdout };
session.request("initialize", json!({"protocolVersion": "2025-06-18"}));
session
}
fn request(&mut self, method: &str, params: Value) -> Value {
use std::io::BufRead;
self.next_id += 1;
let line =
json!({"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params});
let stdin = self.child.stdin.as_mut().unwrap();
writeln!(stdin, "{line}").unwrap();
stdin.flush().unwrap();
let mut answer = String::new();
self.stdout.read_line(&mut answer).unwrap();
serde_json::from_str(&answer).unwrap()
}
/// A tool call that must succeed: its text.
fn text(&mut self, tool: &str, arguments: Value) -> String {
let reply = self.request("tools/call", json!({"name": tool, "arguments": arguments}));
assert_eq!(reply["result"]["isError"], false, "{tool}: {reply}");
reply["result"]["content"][0]["text"].as_str().unwrap().to_string()
}
/// Close stdin, as a host does, and return everything said on stderr.
fn end(mut self) -> String {
drop(self.child.stdin.take());
let status = self.child.wait().unwrap();
assert!(status.success(), "{status}");
let mut stderr = String::new();
self.child.stderr.take().unwrap().read_to_string(&mut stderr).unwrap();
stderr
}
}
/// A session that indexes, answers, edits and ends; its stderr.
fn whole_session(scratch: &Scratch) -> String {
let mut session = Session::start(scratch);
assert!(session.text("hierarchy", json!({})).starts_with("7 files, "));
assert!(session.text("outline", json!({"unit": "leaf"})).starts_with("rtl/leaf.sv:1\n"));
session.text("format", json!({"files": "rtl/top.sv"}));
// One more call, so the index has absorbed whatever the edit wrote.
session.text("outline", json!({"file": "rtl/top.sv"}));
let stderr = session.end();
assert!(stderr.contains(&format!("lucisv-mcp: indexed {FILES} files in ")), "{stderr}");
stderr
}
/// The startup line's tail: `ms (E from the editor's cache, O from its own)`
/// after `indexed 7 files in`.
fn reused(editor: usize, own: usize) -> String {
format!(" ms ({editor} from the editor's cache, {own} from its own)\n")
}
fn hash_file(path: &Path) -> u64 {
content_hash(&fs::read(path).unwrap())
}
#[test]
fn the_editors_store_is_read_skipping_bad_records_and_never_written() {
let scratch = Scratch::new();
let mut lines = editor_store(&scratch, env!("CARGO_PKG_VERSION"));
// A record whose hash matches its file but whose facts no longer match
// their checksum: an instance renamed inside it.
let at = lines.iter().position(|line| line.contains("/rtl/top.sv\t")).unwrap();
let forged = lines[at].replacen("\tu_leaf\t", "\tu_lesf\t", 1);
assert_ne!(forged, lines[at], "the forgery changed the facts");
lines[at] = forged;
// A torn last record, no newline.
let last = lines.len() - 1;
lines[last] = lines[last][..lines[last].len() / 2].to_string();
fs::create_dir_all(scratch.cache()).unwrap();
let store = scratch.cache().join("index-cache");
fs::write(&store, lines.join("\n")).unwrap();
let before = (hash_file(&store), fs::metadata(&store).unwrap().modified().unwrap());
let stderr = whole_session(&scratch);
assert!(stderr.contains(&reused(FILES - 2, 0)), "{stderr}");
let after = (hash_file(&store), fs::metadata(&store).unwrap().modified().unwrap());
assert_eq!(before, after, "the language server's store is byte-identical, untouched");
let own = fs::read_to_string(scratch.cache().join("index-cache-mcp")).unwrap();
assert!(own.starts_with(&format!("{}\n", header(env!("CARGO_PKG_VERSION")))));
assert_eq!(own.lines().count(), 1 + FILES);
}
#[test]
fn a_store_from_another_version_is_ignored_whole_with_one_line() {
let scratch = Scratch::new();
fs::create_dir_all(scratch.cache()).unwrap();
let store = scratch.cache().join("index-cache");
fs::write(&store, editor_store(&scratch, "0.0.0").join("\n") + "\n").unwrap();
let before = hash_file(&store);
let stderr = whole_session(&scratch);
assert_eq!(stderr.matches("ignoring the index cache").count(), 1, "{stderr}");
assert!(stderr.contains(&reused(0, 0)), "{stderr}");
assert_eq!(hash_file(&store), before);
}
#[test]
fn a_missing_directory_starts_cold_and_its_own_store_serves_the_next_start() {
let scratch = Scratch::new();
let stderr = whole_session(&scratch);
assert!(stderr.contains(&reused(0, 0)), "{stderr}");
assert!(!stderr.contains("ignoring") && !stderr.contains("cannot"), "{stderr}");
assert!(!scratch.cache().join("index-cache").exists(), "the editor's store is not made");
assert!(scratch.cache().join("index-cache-mcp").exists());
let stderr = whole_session(&scratch);
assert!(stderr.contains(&reused(0, FILES)), "{stderr}");
// A file changed since its record: its hash misses, it is parsed, and
// the answer is the new text's.
let leaf = scratch.src().join("rtl/leaf.sv");
let text = fs::read_to_string(&leaf).unwrap().replace("module leaf", "module leaf2");
fs::write(&leaf, text).unwrap();
let mut session = Session::start(&scratch);
let units = session.text("find", json!({"name": "leaf2"}));
assert!(units.contains("module leaf2"), "{units}");
let stderr = session.end();
assert!(stderr.contains(&reused(0, FILES - 1)), "{stderr}");
}
#[cfg(unix)]
#[test]
fn an_unwritable_cache_directory_still_answers_and_says_so_on_exit() {
use std::os::unix::fs::PermissionsExt;
let scratch = Scratch::new();
fs::create_dir_all(scratch.cache()).unwrap();
fs::set_permissions(scratch.cache(), fs::Permissions::from_mode(0o555)).unwrap();
let stderr = whole_session(&scratch);
fs::set_permissions(scratch.cache(), fs::Permissions::from_mode(0o755)).unwrap();
assert!(stderr.contains(&reused(0, 0)), "{stderr}");
assert_eq!(stderr.matches("cannot write the index cache").count(), 1, "{stderr}");
assert!(fs::read_dir(scratch.cache()).unwrap().next().is_none(), "nothing was written");
}
@@ -0,0 +1,7 @@
`define CORE_HIER tb.u_core
`define SM_STATE `CORE_HIER.u_main_sm.state_q
interface probe_if;
string path = {"tb.u_core.u_main_sm", ".state_q"};
logic seen;
assign seen = `CORE_HIER.u_main_sm.state_q;
endinterface
+12
View File
@@ -0,0 +1,12 @@
module cipher #(
parameter bit Masking = 1
) (
input logic clk_i,
input logic rst_ni,
// Data
input logic [31:0] data_i,
output logic valid_o
);
assign valid_o = data_i[0] & rst_ni;
endmodule
+11
View File
@@ -0,0 +1,11 @@
module core (
input logic clk_i,
output logic busy_o,
output logic probe_o
);
main_sm u_main_sm (
.clk_i (clk_i),
.busy_o (busy_o)
);
assign probe_o = u_main_sm.state_q;
endmodule
@@ -0,0 +1,8 @@
module other_sm (
input logic clk_i,
output logic busy_o
);
logic state_q;
always_ff @(posedge clk_i) state_q <= ~state_q;
assign busy_o = state_q;
endmodule
+11
View File
@@ -0,0 +1,11 @@
// The main state machine; state_q is its register.
`define FLOP(d, q) always_ff @(posedge clk_i) q <= d;
module main_sm (
input logic clk_i,
output logic busy_o
);
logic state_d, state_q;
`FLOP(state_d, state_q)
assign state_d = ~state_q;
assign busy_o = state_q;
endmodule
+17
View File
@@ -0,0 +1,17 @@
module wrap (
input logic clk_i,
input logic rst_ni,
input logic dbg_i,
input logic [31:0] data_i,
output logic valid_o
);
cipher #(
.Masking ( 1 )
) u_cipher (
.clk_i ( clk_i ),
.rst_ni ( rst_ni ),
.data_i ( data_i ), // payload
.valid_o ( valid_o )
);
endmodule
+23
View File
@@ -0,0 +1,23 @@
module core (
input logic clk,
input logic rst_ni,
input logic [7:0] d,
output logic [7:0] q
);
logic [7:0] r; // the register
// Parity of r.
logic p;
// Register the input.
always_ff @(posedge clk or negedge rst_ni)
if (!rst_ni) r <= '0;
else r <= d;
assign q = r;
// lucisv: off
logic keep_me;
// lucisv: on
always_comb p = item_pkg::parity(r);
endmodule
+13
View File
@@ -0,0 +1,13 @@
package item_pkg;
parameter int WIDTH = 8;
// Parity of a word.
function automatic logic parity(logic [WIDTH-1:0] w);
return ^w;
endfunction
// Nobody calls this one.
function automatic logic spare(logic a);
return a;
endfunction
endpackage
+4
View File
@@ -0,0 +1,4 @@
module tick (
input logic clk
);
endmodule
+9
View File
@@ -0,0 +1,9 @@
module wrap (
input logic clk,
input logic rst_ni,
input logic [7:0] d,
output logic [7:0] q
);
core u_core (.*);
tick u_tick (.clk);
endmodule
@@ -0,0 +1,5 @@
`define AES_TB 1
module aes_tb;
logic clk_i;
aes_core u_dut (.clk_i(clk_i), .q_o());
endmodule
@@ -0,0 +1,8 @@
`define AES_W 8
module aes_core (
input logic clk_i,
output logic [`AES_W - 1:0] q_o
);
logic \esc*name ;
assign q_o = '0;
endmodule
@@ -0,0 +1,3 @@
package aes_pkg;
parameter int \esc*w = 4;
endpackage
@@ -0,0 +1,2 @@
module uart_fifo;
endmodule
@@ -0,0 +1,8 @@
module uart (
input logic clk_i,
input logic spare_i
);
logic idle_x;
aes_core u_aes (.clk_i(clk_i), .q_o());
uart_fifo u_fifo ();
endmodule
+2
View File
@@ -0,0 +1,2 @@
[lint]
select = ["unused-signal"]
+7
View File
@@ -0,0 +1,7 @@
module chip (
input logic clk_i,
input logic spare_i
);
uart u_uart (.*);
aes_core u_aes2 (.clk_i(clk_i), .q_o());
endmodule
+137
View File
@@ -0,0 +1,137 @@
//! The `hierarchy` cap counts instances, never `peek` lines (census round 5,
//! 2026-09-29): an agent asking for every instantiation of a module with
//! `peek` gets every one up to 100 (300 without `peek`), each with its
//! statement, not a quarter of them. Each test writes a generated design into a scratch directory and
//! talks to the real binary over it.
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use serde_json::{json, Value};
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
/// A scratch design, removed on drop.
struct Tree(PathBuf);
impl Tree {
fn with(files: &[(&str, String)]) -> Tree {
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
let dir = std::env::temp_dir()
.join(format!("lucisv-mcp-hierarchy-cap-{}-{unique}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
for (rel, text) in files {
fs::write(dir.join(rel), text).unwrap();
}
Tree(fs::canonicalize(dir).unwrap())
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
/// One `hierarchy` call over `tree` that must succeed: its text.
fn hierarchy(tree: &Tree, arguments: Value) -> String {
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
.args(["--root", tree.0.to_str().unwrap()])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
let init = json!({"jsonrpc": "2.0", "id": 0, "method": "initialize", "params": {
"protocolVersion": "2025-06-18", "capabilities": {},
"clientInfo": {"name": "hierarchy_cap", "version": "0"}}});
let params = json!({"name": "hierarchy", "arguments": arguments});
let call = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": params});
let mut stdin = child.stdin.take().unwrap();
stdin.write_all(format!("{init}\n{call}\n").as_bytes()).unwrap();
drop(stdin);
let output = child.wait_with_output().unwrap();
let stdout = String::from_utf8(output.stdout).unwrap();
let reply: Value = stdout
.lines()
.map(|line| serde_json::from_str::<Value>(line).unwrap())
.find(|reply| reply["id"] == 1)
.expect("the call is answered");
assert_eq!(reply["result"]["isError"], false, "{reply}");
reply["result"]["content"][0]["text"].as_str().unwrap().to_string()
}
/// `count` instantiations of `sub` in `top`, each written over `ports + 2`
/// lines: the header, one line per port, the closer.
fn crowded(count: usize, ports: usize) -> Tree {
let names: Vec<String> = (0..ports).map(|p| format!("p{p}")).collect();
let declared: Vec<String> = names.iter().map(|n| format!("input logic {n}")).collect();
let sub = format!("module sub #(parameter int W = 1) ({});\nendmodule\n", declared.join(", "));
let mut top = format!("module top;\n logic {};\n", names.join(", "));
for i in 0..count {
top.push_str(&format!(" sub #(.W({i})) u_{i:03} (\n"));
for (at, name) in names.iter().enumerate() {
let comma = if at + 1 < names.len() { "," } else { "" };
top.push_str(&format!(" .{name}({name}){comma}\n"));
}
top.push_str(" );\n");
}
top.push_str("endmodule\n");
Tree::with(&[("sub.sv", sub), ("top.sv", top)])
}
/// The tree lines of an answer: every line that is not a peeked statement.
fn node_lines(text: &str, statement_indent: &str) -> Vec<String> {
text.lines().filter(|l| !l.starts_with(statement_indent)).map(str::to_string).collect()
}
#[test]
fn up_with_peek_lists_every_instantiation_whatever_the_statements_cost() {
// 30 instantiations of 14 lines each: peek shows 12 lines and `…` per
// statement, 420 lines in all — every one is still there.
let tree = crowded(30, 12);
let text = hierarchy(&tree, json!({"root": "sub", "up": true, "peek": true}));
let nodes = node_lines(&text, " ");
let expected: Vec<String> =
(0..30).map(|i| format!("top.u_{i:03} top.sv:{}", 3 + i * 14)).collect();
assert_eq!(nodes, expected, "{text}");
assert!(!text.contains("… and "), "{text}");
assert_eq!(text.lines().count(), 30 * 14);
// Each statement: its first 12 lines as written, then `…`.
let first: Vec<&str> = text.lines().skip(1).take(13).collect();
assert_eq!(first[0], " sub #(.W(0)) u_000 (");
assert_eq!(first[11], " .p10(p10),");
assert_eq!(first[12], " …");
}
#[test]
fn over_100_instances_with_peek_shows_100_and_over_300_without_shows_300() {
let tree = crowded(350, 1);
// Up with peek: 350 instantiations, 100 shown, each with its 3-line statement.
let up = hierarchy(&tree, json!({"root": "sub", "up": true, "peek": true}));
let lines: Vec<&str> = up.lines().collect();
assert_eq!(lines.len(), 100 * 4 + 1, "{up}");
assert_eq!(*lines.last().unwrap(), "… and 250 more");
let nodes = node_lines(&up, " ");
assert_eq!(nodes.len(), 101);
assert_eq!(nodes[99], "top.u_099 top.sv:300");
assert_eq!(lines[lines.len() - 2], " );", "the last statement is whole");
// Down with peek: the root line and 99 instances make 100 nodes; 251 are left.
let down = hierarchy(&tree, json!({"root": "top", "peek": true}));
let nodes = node_lines(&down, " ");
assert_eq!(nodes.len(), 101, "{down}");
assert_eq!(nodes[0], "top top.sv:1");
assert_eq!(nodes[99], " u_098: sub top.sv:297");
assert_eq!(nodes[100], "… and 251 more");
// Without peek: 300 lines, then the count.
let plain = hierarchy(&tree, json!({"root": "sub", "up": true}));
assert_eq!(plain.lines().count(), 301);
assert!(plain.ends_with("\n… and 50 more\n"), "{plain}");
let plain = hierarchy(&tree, json!({"root": "top"}));
assert_eq!(plain.lines().count(), 301);
assert!(plain.ends_with("\n… and 51 more\n"), "{plain}");
}
+186 -57
View File
@@ -1,16 +1,18 @@
//! The opentitan census (TODO-MCP M2): the navigation tools over a real
//! checkout, read-only, each answer checked against what the language
//! server answers for the same question (`docs/features/references-nav`,
//! `references-hierarchical-surface`) and each call's wall time printed.
//! The opentitan census (TODO-MCP M2, ported to the lean catalogue in M7):
//! `find`, `hierarchy`, `check` and `outline` over a real checkout,
//! read-only, each answer checked against what the language server answers
//! for the same question (`docs/features/references-nav`,
//! `references-hierarchical-surface`) or what 0.57.0 answered, and each
//! call's wall time printed.
//!
//! `#[ignore]`: it needs the checkout. Run with
//! `LUCISV_OPENTITAN=/path/to/opentitan tools/guard.sh -- cargo test -p
//! lucisv_mcp --test opentitan -- --ignored --nocapture`.
use std::io::{BufRead, BufReader, Write};
use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
use std::time::Instant;
use std::time::{Duration, Instant};
use serde_json::{json, Value};
@@ -24,33 +26,55 @@ fn checkout() -> PathBuf {
/// One server over the checkout.
struct Session {
child: Child,
stdin: ChildStdin,
stdin: Option<ChildStdin>,
stdout: BufReader<ChildStdout>,
next_id: i64,
}
impl Session {
fn over(root: &Path) -> Session {
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
.args(["--root", root.to_str().unwrap()])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
let stdin = child.stdin.take().unwrap();
Session::spawn(root, None)
}
/// A server with `--index-cache cache` when given; its stderr is kept
/// for [`Session::end`] only then (the one line it writes is small).
fn spawn(root: &Path, cache: Option<&Path>) -> Session {
let mut command = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"));
command.args(["--root", root.to_str().unwrap()]);
if let Some(cache) = cache {
command.arg("--index-cache").arg(cache);
}
let stderr = if cache.is_some() { Stdio::piped() } else { Stdio::null() };
let mut child =
command.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(stderr).spawn().unwrap();
let stdin = child.stdin.take();
let stdout = BufReader::new(child.stdout.take().unwrap());
let mut session = Session { child, stdin, stdout, next_id: 0 };
session.request("initialize", json!({"protocolVersion": "2025-06-18"}));
session
}
/// Close stdin as a host does; the time the server took to exit (its
/// own store is written then) and what it said on stderr.
fn end(mut self) -> (Duration, String) {
let started = Instant::now();
drop(self.stdin.take());
self.child.wait().unwrap();
let took = started.elapsed();
let mut stderr = String::new();
if let Some(mut pipe) = self.child.stderr.take() {
pipe.read_to_string(&mut stderr).unwrap();
}
(took, stderr)
}
fn request(&mut self, method: &str, params: Value) -> Value {
self.next_id += 1;
let line =
json!({"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params});
writeln!(self.stdin, "{line}").unwrap();
self.stdin.flush().unwrap();
let stdin = self.stdin.as_mut().unwrap();
writeln!(stdin, "{line}").unwrap();
stdin.flush().unwrap();
let mut answer = String::new();
self.stdout.read_line(&mut answer).unwrap();
serde_json::from_str(&answer).unwrap()
@@ -73,19 +97,24 @@ impl Session {
result["content"][0]["text"].as_str().unwrap().to_string()
}
/// Every `references` hit as `file:line:col`.
fn hits(&mut self, arguments: Value) -> Vec<String> {
let result = self.call("references", arguments);
let hits = result["structuredContent"]["hits"].as_array().unwrap().clone();
hits.iter()
.map(|h| format!("{}:{}:{}", h["file"].as_str().unwrap(), h["line"], h["col"]))
.collect()
/// The uses `find` lists for `name` (a `unit.name` picks one
/// declaration), as `file:line`.
fn uses(&mut self, name: &str) -> Vec<String> {
let text = self.text("find", json!({"name": name, "refs": true}));
let mut out = Vec::new();
let used = text.lines().skip(1).take_while(|line| line.starts_with(" "));
for line in used {
let (file, numbers) = line.trim().rsplit_once(':').unwrap();
out.extend(numbers.split(',').map(|n| format!("{file}:{n}")));
}
assert!(!out.is_empty(), "no uses: {text}");
out
}
}
/// The language server's answer for the same position (release
/// `lucisv-server` over the same checkout, 2026-09-23): every location it
/// lists must be in ours.
/// `lucisv-server` over the same checkout, 2026-09-23), as `file:line`:
/// every location it lists must be in ours.
fn assert_covers(ours: &[String], server: &[&str]) {
for location in server {
assert!(ours.iter().any(|hit| hit == location), "missing {location}: {ours:?}");
@@ -111,51 +140,151 @@ fn opentitan_navigation_matches_the_language_server() {
let before = status(&root);
let mut s = Session::over(&root);
// The first call builds the index; its time is the startup cost.
s.text("project_overview", json!({}));
s.text("hierarchy", json!({}));
let masking =
json!({"file": "hw/ip/aes/rtl/aes.sv", "name": "entropy_masking_req", "limit": 1000});
let masking = s.hits(masking);
let aes = "hw/ip/aes/rtl/aes.sv";
let bind = "hw/ip/aes/dv/sva/aes_bind.sv";
let server = [&format!("{bind}:45:27"), &format!("{bind}:54:26"), &format!("{aes}:89:52")];
let masking = s.uses("aes.entropy_masking_req");
let server = [&format!("{bind}:45"), &format!("{bind}:54"), &format!("{aes}:137")];
assert_covers(&masking, &server.map(String::as_str));
assert_eq!(masking.len(), 6, "{masking:?}");
let sm = "hw/ip/entropy_src/rtl/entropy_src_main_sm.sv";
let state = s.hits(json!({"file": sm, "line": 42, "name": "state_q"}));
assert_covers(&state, &["hw/ip/entropy_src/rtl/entropy_src_core.sv:3092:30"]);
assert_eq!(state.len(), 5, "{state:?}");
let state = s.uses("entropy_src_main_sm.state_q");
assert_covers(&state, &["hw/ip/entropy_src/rtl/entropy_src_core.sv:3092"]);
// The references-nav positions: the `aes` instantiation and its `.clk_i`
// in the testbench. The server lists 11 and 9; we list those and the
// three top-level `*_pd_main.sv` instantiations it omits (README, work log).
let tb = "hw/ip/aes/dv/tb/tb.sv";
let instantiated = s.hits(json!({"file": tb, "line": 45, "name": "aes"}));
// The `aes` instantiations the server lists, and the three top-level
// `*_pd_main.sv` ones it omits (README of mcp-navigation, work log).
let instantiated = s.uses("aes");
let server = [
"hw/ip/aes/dv/cov/aes_cov_bind.sv:8:8",
"hw/ip/aes/dv/sva/aes_bind.sv:50:8",
"hw/ip/aes/dv/tb/tb.sv:45:3",
"hw/ip/aes/pre_dv/aes_tb/rtl/aes_tb.sv:215:3",
"hw/ip/aes/rtl/aes.sv:9:8",
"hw/ip/aes/rtl/aes_wrap.sv:79:3",
"hw/ip/aes/dv/cov/aes_cov_bind.sv:8",
"hw/ip/aes/dv/sva/aes_bind.sv:50",
"hw/ip/aes/dv/tb/tb.sv:45",
"hw/ip/aes/pre_dv/aes_tb/rtl/aes_tb.sv:215",
"hw/ip/aes/rtl/aes_wrap.sv:79",
];
assert_covers(&instantiated, &server);
let clock = s.hits(json!({"file": tb, "line": 46, "name": "clk_i"}));
assert_covers(&clock, &["hw/ip/aes/rtl/aes.sv:42:53", "hw/ip/aes/rtl/aes.sv:197:31"]);
let top = s.text("hierarchy", json!({"root": "top_earlgrey", "depth": 2, "limit": 500}));
assert!(top.contains("\n u_aes : aes #("), "{top}");
let top = s.text("hierarchy", json!({"root": "top_earlgrey", "depth": 2}));
assert!(top.contains("\n u_aes: aes hw/top_earlgrey/rtl/autogen/"), "{top}");
let peek = s.text("hierarchy", json!({"root": "top_earlgrey", "peek": true}));
assert!(peek.contains("\n earlgrey_pd_main"), "{peek}");
let fifo = s.text("definition", json!({"name": "prim_fifo_sync"}));
assert!(fifo.starts_with("hw/ip/prim/rtl/prim_fifo_sync.sv:"), "{fifo}");
let fifo = s.text("find", json!({"name": "prim_fifo_sync"}));
assert!(fifo.starts_with("module prim_fifo_sync hw/ip/prim/rtl/prim_fifo_sync.sv:"), "{fifo}");
let up = s.text("hierarchy", json!({"root": "prim_fifo_sync", "direction": "up", "depth": 1}));
let up = s.text("hierarchy", json!({"root": "prim_fifo_sync", "up": true}));
assert!(up.contains(".u_"), "{up}");
s.text("diagnostics", json!({"file": "hw/ip/aes/rtl/aes.sv"}));
let clk = json!({"file": "hw/ip/prim/rtl/prim_fifo_sync.sv", "name": "clk_i"});
s.text("references", clk);
s.text("check", json!({"file": aes}));
s.text("outline", json!({"unit": "aes"}));
s.text("read", json!({"item": "module:aes_wrap"}));
drop(s);
assert_eq!(status(&root), before, "the checkout was only read");
}
/// `top_earlgrey`'s instances two levels down as 0.57.0's `hierarchy`
/// answered them (`depth: 2`, every line), `level instance:module`.
const TOP_EARLGREY_DEPTH_2: &str = "1earlgrey_pd_main:earlgrey_pd_main 2u_dft_tap_breakout:pinmux_jtag_breakout 2u_uart0:uart 2u_uart1:uart 2u_uart2:uart 2u_uart3:uart 2u_gpio:gpio 2u_spi_device:spi_device 2u_i2c0:i2c 2u_i2c1:i2c 2u_i2c2:i2c 2u_rv_timer:rv_timer 2u_otp_ctrl:otp_ctrl 2u_lc_ctrl:lc_ctrl 2u_alert_handler:alert_handler 2u_spi_host0:spi_host 2u_spi_host1:spi_host 2u_usbdev:usbdev 2u_pinmux:pinmux 2u_rram_ctrl:rram_ctrl 2u_rram_macro:rram_macro 2u_rv_dm:rv_dm 2u_rv_plic:rv_plic 2u_aes:aes 2u_hmac:hmac 2u_kmac:kmac 2u_otbn:otbn 2u_keymgr_dpe:keymgr_dpe 2u_csrng:csrng 2u_entropy_src:entropy_src 2u_edn0:edn 2u_edn1:edn 2u_sram_ctrl_main:sram_ctrl 2u_sram_ctrl_sec:sram_ctrl 2u_rom_ctrl:rom_ctrl 2u_rv_core_ibex:rv_core_ibex 2u_cheriot:cheriot 2u_sram_ctrl_meta:sram_ctrl 2u_xbar_main:xbar_main 2u_xbar_peri:xbar_peri 1earlgrey_pd_aon:earlgrey_pd_aon 2u_pwrmgr:pwrmgr 2u_rstmgr:rstmgr 2u_clkmgr:clkmgr 2u_sysrst_ctrl:sysrst_ctrl 2u_adc_ctrl:adc_ctrl 2u_aon_timer:aon_timer 2u_sensor_ctrl:sensor_ctrl 2u_sram_ctrl_ret:sram_ctrl";
/// PLAN §10.5: the lean `hierarchy` names the instance set 0.57.0 named,
/// in the same order, each at its instantiation site.
#[test]
#[ignore = "needs an opentitan checkout (LUCISV_OPENTITAN)"]
fn opentitan_top_earlgrey_is_the_0_57_instance_set() {
let root = checkout();
let before = status(&root);
let mut s = Session::over(&root);
let tree = s.text("hierarchy", json!({"root": "top_earlgrey", "depth": 2}));
let ours: Vec<String> = tree
.lines()
.skip(1)
.map(|line| {
let level = (line.len() - line.trim_start().len()) / 2;
let (instance, rest) = line.trim().split_once(": ").unwrap();
let module = rest.split(' ').next().unwrap();
format!("{level}{instance}:{module}")
})
.collect();
assert_eq!(ours.join(" "), TOP_EARLGREY_DEPTH_2, "{tree}");
assert!(tree.lines().skip(1).all(|line| line.contains(".sv:")), "each at its site: {tree}");
drop(s);
assert_eq!(status(&root), before, "the checkout was only read");
}
/// The median of some wall times, in milliseconds.
fn median_ms(mut times: Vec<Duration>) -> f64 {
times.sort();
times[times.len() / 2].as_secs_f64() * 1000.0
}
/// One startup over the checkout with the stores in `cache`: the first
/// call's wall time, the exit's, and the server's `indexed …` line.
fn startup(root: &Path, cache: &Path, label: &str) -> Session {
let mut s = Session::spawn(root, Some(cache));
let started = Instant::now();
s.text("hierarchy", json!({}));
println!("startup: {label}: first call {} ms", started.elapsed().as_millis());
s
}
/// Close a session, printing its exit time and startup line.
fn finish(s: Session, label: &str) {
let (exit, stderr) = s.end();
let line = stderr.lines().find(|l| l.contains("indexed")).unwrap_or("").to_string();
println!("startup: {label}: {line}; exit (own store written) {} ms", exit.as_millis());
}
/// TODO-MCP M6: startup cold, warm from the editor's store and warm from
/// this server's own; the per-call stat sweep; a whole-set `find` with
/// `refs` (the read-only stand-in for the whole-set `rename`: the checkout
/// is never written). The
/// stores live in a scratch directory outside the checkout; the editor's is
/// the own store renamed — the same codec, byte for byte (`src/cache.rs`,
/// pinned against the language server's source by its unit test).
#[test]
#[ignore = "needs an opentitan checkout (LUCISV_OPENTITAN)"]
fn opentitan_startup_cold_and_warm_and_the_stat_sweep() {
let root = checkout();
let before = status(&root);
let cache = std::env::temp_dir().join(format!("lucisv-mcp-ot-cache-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&cache);
finish(startup(&root, &cache, "cold, no store"), "cold, no store");
let mut s = startup(&root, &cache, "warm, own store");
// The stat sweep: a call whose answer is cached after its first run, so
// what is left is the sweep over every file; `tools/list` is the floor.
let outline = json!({"file": "hw/ip/prim/rtl/prim_fifo_sync.sv"});
s.text("outline", outline.clone());
let mut swept = Vec::new();
let mut floor = Vec::new();
for _ in 0..21 {
let started = Instant::now();
s.request("tools/list", json!({}));
floor.push(started.elapsed());
let started = Instant::now();
s.text("outline", outline.clone());
swept.push(started.elapsed());
}
println!(
"sweep: outline median {:.2} ms, tools/list median {:.2} ms",
median_ms(swept),
median_ms(floor)
);
let uses = json!({"name": "aes_cipher_core", "refs": true});
for pass in ["first", "second"] {
let started = Instant::now();
let text = s.text("find", uses.clone());
assert!(text.starts_with("module aes_cipher_core "), "{text}");
println!("find: aes_cipher_core refs, {pass} call {} ms", started.elapsed().as_millis());
}
finish(s, "warm, own store");
let own = cache.join("index-cache-mcp");
std::fs::rename(&own, cache.join("index-cache")).unwrap();
let editor = std::fs::read(cache.join("index-cache")).unwrap();
let s = startup(&root, &cache, "warm, editor's store");
finish(s, "warm, editor's store");
assert_eq!(std::fs::read(cache.join("index-cache")).unwrap(), editor, "read, never written");
println!("store: {} bytes", editor.len());
let _ = std::fs::remove_dir_all(&cache);
assert_eq!(status(&root), before, "the checkout was only read");
}
+698
View File
@@ -0,0 +1,698 @@
//! QA attacks on lane feedback-1 (unresolved mentions, `add_port`'s `after`
//! and its move-checker, the trimmed catalogue, the temp-store sweep),
//! 2026-09-23 — ported to the lean catalogue: `add_port` is `port` with
//! `add` (the calls are mapped by [`Session::call`]); the mentions are the
//! `unresolved:` block of `find`, `rename` and `port`.
//!
//! Every test spawns the real binary over a scratch tree, as a host would.
//! Placements are asserted byte for byte; refusals with every file of the
//! tree byte-identical.
//!
//! A test that pins a QA finding asserts the *correct* behaviour and is
//! `#[ignore = "QA finding N"]` until a rework flips it; the findings are
//! numbered as in the QA log of `docs/features/mcp-feedback-1/README.md`.
use std::collections::BTreeMap;
use std::fs;
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{self, Receiver};
use std::time::Duration;
use serde_json::{json, Value};
const ANSWER_TIMEOUT: Duration = Duration::from_secs(120);
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
/// A scratch tree holding the files a case writes; removed on drop.
struct Tree(PathBuf);
impl Tree {
fn with(files: &[(&str, &str)]) -> Tree {
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
let dir =
std::env::temp_dir().join(format!("lucisv-mcp-qa-f1-{}-{unique}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
for (name, text) in files {
let path = dir.join(name);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, text).unwrap();
}
Tree(fs::canonicalize(dir).unwrap())
}
/// Every file, root-relative, with its bytes.
fn snapshot(&self) -> BTreeMap<String, Vec<u8>> {
fn walk(dir: &Path, root: &Path, out: &mut BTreeMap<String, Vec<u8>>) {
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
walk(&path, root, out);
} else {
let name = path.strip_prefix(root).unwrap().to_string_lossy().into_owned();
out.insert(name, fs::read(&path).unwrap());
}
}
}
let mut out = BTreeMap::new();
walk(&self.0, &self.0, &mut out);
out
}
fn read(&self, file: &str) -> String {
fs::read_to_string(self.0.join(file)).unwrap()
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
/// One running server, initialised.
struct Session {
child: Child,
stdin: Option<ChildStdin>,
lines: Receiver<String>,
next_id: i64,
/// The `initialize` reply.
init: Value,
}
impl Session {
fn over(tree: &Tree) -> Session {
Session::spawn(&["--root", tree.0.to_str().unwrap()])
}
fn spawn(args: &[&str]) -> Session {
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
let stdout = child.stdout.take().unwrap();
let (send, lines) = mpsc::channel();
std::thread::spawn(move || {
for line in BufReader::new(stdout).lines().map_while(Result::ok) {
if send.send(line).is_err() {
break;
}
}
});
let stdin = child.stdin.take().unwrap();
let mut session =
Session { child, stdin: Some(stdin), lines, next_id: 0, init: Value::Null };
session.init = session
.request("initialize", json!({"protocolVersion": "2025-06-18", "capabilities": {}}));
session.send(&json!({"jsonrpc": "2.0", "method": "notifications/initialized"}));
session
}
fn send(&mut self, message: &Value) {
let stdin = self.stdin.as_mut().unwrap();
writeln!(stdin, "{message}").unwrap();
stdin.flush().unwrap();
}
fn request(&mut self, method: &str, params: Value) -> Value {
self.next_id += 1;
let id = self.next_id;
self.send(&json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}));
let line = self.lines.recv_timeout(ANSWER_TIMEOUT).expect("the server answered");
let reply: Value = serde_json::from_str(&line).unwrap();
assert_eq!(reply["id"], id);
reply
}
/// A tool call: whether it was refused, its text, and the `file:line`
/// of every unresolved mention it lists. `add_port` is `port` with `add`.
fn call(&mut self, tool: &str, mut arguments: Value) -> (bool, String, Value) {
let tool = match tool {
"add_port" => {
let object = arguments.as_object_mut().unwrap();
let declaration = object.remove("declaration").unwrap();
object.insert("add".into(), declaration);
"port"
}
other => other,
};
let reply = self.request("tools/call", json!({"name": tool, "arguments": arguments}));
let result = &reply["result"];
let text = result["content"][0]["text"].as_str().unwrap_or_default().to_string();
let mentions = unresolved(&text);
(result["isError"] == true, text, mentions)
}
/// Close stdin and wait for the server to exit on its own.
fn end(mut self) {
self.stdin.take();
let _ = self.child.wait();
}
}
impl Drop for Session {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
/// A tree and a server over it.
fn served(files: &[(&str, &str)]) -> (Tree, Session) {
let tree = Tree::with(files);
let server = Session::over(&tree);
(tree, server)
}
/// The `unresolved:` block of an answer, one `file:line` per mention.
fn unresolved(text: &str) -> Value {
let Some((_, block)) = text.split_once("unresolved:\n") else { return json!([]) };
let mut sites = Vec::new();
for line in block.lines().map(str::trim).filter(|line| !line.starts_with('…')) {
let (file, lines) = line.rsplit_once(':').unwrap();
sites.extend(lines.split(',').map(|n| Value::from(format!("{file}:{n}"))));
}
Value::from(sites)
}
/// Run `tool` and assert it refuses with a sentence holding `why`, leaving
/// every file of the tree byte-identical.
fn refused(tree: &Tree, server: &mut Session, tool: &str, args: Value, why: &str) -> String {
let before = tree.snapshot();
let (error, text, _) = server.call(tool, args.clone());
assert!(error, "{tool} {args}: not refused: {text}");
assert!(text.contains(why), "{tool} {args}: `{why}` not in: {text}");
assert!(before == tree.snapshot(), "{tool} {args}: a refusal wrote");
text
}
/// Run `tool` for real and assert it wrote; its text and its mentions.
fn written(server: &mut Session, tool: &str, args: Value) -> (String, Value) {
let (error, text, structured) = server.call(tool, args.clone());
assert!(!error, "{tool} {args}: refused: {text}");
(text, structured)
}
// ---------------------------------------------------------------------------
// 1. `add_port` `after`: placements, byte for byte.
// ---------------------------------------------------------------------------
const M_HEADER: &str = "module m (\n input logic a, // anchor comment\n input logic b,\n output logic y /* last */\n);\n assign y = a & b;\nendmodule\n";
const M_TOP: &str = "module top (input logic a, b, en, output logic y);\n m u_m (\n .a (a), // in\n .b (b),\n .y (y)\n );\n m u_n (.a(a), .b(b), .y()), u_o (.a(a), .b(b), .y());\n generate if (1) begin : g_one\n m u_g (\n .a ( a ),\n .b ( b ),\n .y ( )\n );\n end endgenerate\nendmodule\n";
#[test]
fn qa_after_keeps_the_anchor_lines_comment_and_places_every_instance_shape() {
let (tree, mut server) = served(&[("rtl/m.sv", M_HEADER), ("rtl/top.sv", M_TOP)]);
let args = json!({"module": "m", "declaration": "input logic en", "after": "a"});
written(&mut server, "add_port", args.clone());
// The anchor's own comment stays on the anchor's line; the new line
// follows it in the anchor's columns.
assert_eq!(
tree.read("rtl/m.sv"),
M_HEADER.replace("comment\n", "comment\n input logic en,\n")
);
// One-per-line (aligned), two instances in one statement (inline, each
// placed), an instance in a generate block (aligned to its own anchor).
let want = M_TOP
.replace(" .a (a), // in\n", " .a (a), // in\n .en (en),\n")
.replace(
".a(a), .b(b), .y()), u_o (.a(a), .b(b)",
".a(a), .en(en), .b(b), .y()), u_o (.a(a), .en(en), .b(b)",
)
.replace(" .a ( a ),\n", " .a ( a ),\n .en ( en ),\n");
assert_eq!(tree.read("rtl/top.sv"), want);
// The same call again: the port exists, the engine refuses, nothing moves.
refused(&tree, &mut server, "add_port", args, "already has a port named `en`");
}
#[test]
fn qa_after_the_last_port_puts_the_comma_before_its_trailing_comment() {
let (tree, mut server) = served(&[("rtl/m.sv", M_HEADER), ("rtl/top.sv", M_TOP)]);
let args = json!({"module": "m", "declaration": "input logic en", "after": "y"});
written(&mut server, "add_port", args);
let header = " output logic y, /* last */\n input logic en\n);\n";
assert_eq!(
tree.read("rtl/m.sv"),
M_HEADER.replace(" output logic y /* last */\n);\n", header)
);
let top = tree.read("rtl/top.sv");
assert!(top.contains(" .y (y),\n .en (en)\n );\n"), "{top}");
assert!(top.contains(".y(), .en(en)), u_o (.a(a), .b(b), .y(), .en(en));"), "{top}");
}
#[test]
fn qa_after_keeps_crlf_and_tabs_and_places_an_instance_in_the_modules_own_file() {
let m = "module m (\r\n\tinput logic a,\t// tabbed\r\n\toutput logic y\r\n);\r\nendmodule\r\nmodule top2 (input logic a, en, output logic y);\r\n m u_s (\r\n .a (a),\r\n .y (y)\r\n );\r\nendmodule\r\n";
let (tree, mut server) = served(&[("rtl/m.sv", m)]);
let args = json!({"module": "m", "declaration": "input logic en", "after": "a"});
written(&mut server, "add_port", args);
let want = m
.replace("// tabbed\r\n", "// tabbed\r\n\tinput logic en,\r\n")
.replace(" .a (a),\r\n", " .a (a),\r\n .en (en),\r\n");
assert_eq!(tree.read("rtl/m.sv"), want);
}
#[test]
fn qa_positional_instances_append_after_the_last_port_and_refuse_elsewhere() {
let top = "module top (input logic a, b, en, output logic y);\n m u_p (a, b, y);\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", M_HEADER), ("rtl/top.sv", top)]);
let args = json!({"module": "m", "declaration": "input logic en", "after": "b"});
refused(&tree, &mut server, "add_port", args, "connects `m` by position");
let args = json!({"module": "m", "declaration": "input logic en", "after": "y"});
written(&mut server, "add_port", args);
assert_eq!(tree.read("rtl/top.sv"), top.replace("(a, b, y)", "(a, b, y, en)"));
}
#[test]
fn qa_after_a_parameter_an_unknown_name_or_an_ifdef_arm_is_refused() {
let m = "module m #(parameter int W = 1) (\n input logic a,\n`ifdef X\n input logic b,\n`endif\n output logic y\n);\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", m)]);
let decl = "input logic en";
let args = json!({"module": "m", "declaration": decl, "after": "W"});
refused(&tree, &mut server, "add_port", args, "`m` has no port `W` (its ports: a, b, y)");
let args = json!({"module": "m", "declaration": decl, "after": "b"});
refused(&tree, &mut server, "add_port", args, "inside an `ifdef arm");
// Just before the arm, and just after it: placed outside it.
let args = json!({"module": "m", "declaration": decl, "after": "a"});
written(&mut server, "add_port", args);
let before_arm = m.replace(" input logic a,\n", " input logic a,\n input logic en,\n");
assert_eq!(tree.read("rtl/m.sv"), before_arm);
fs::write(tree.0.join("rtl/m.sv"), m).unwrap();
let args = json!({"module": "m", "declaration": decl, "after": "y"});
written(&mut server, "add_port", args);
let want = m.replace(" output logic y\n", " output logic y,\n input logic en\n");
assert_eq!(tree.read("rtl/m.sv"), want);
}
#[test]
fn qa_a_connection_anchor_in_an_ifdef_arm_keeps_the_engines_append_and_says_so() {
let m = "module m (\n input logic a,\n output logic y\n);\nendmodule\n";
let top = "module top (input logic a, en, output logic y);\n m u_i (\n`ifdef X\n .a (a),\n`endif\n .y (y)\n );\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]);
let args = json!({"module": "m", "declaration": "input logic en", "after": "a"});
let (text, _) = written(&mut server, "add_port", args);
assert!(text.contains("`u_i` in "), "{text}");
assert!(
text.contains(
"the connection of `en` was appended at the end (`.a` sits inside an `ifdef arm)"
),
"{text}"
);
assert_eq!(text.matches("\nwarning: ").count(), 1, "{text}");
assert_eq!(tree.read("rtl/top.sv"), top.replace(" .y (y)\n", " .y (y),\n .en(en)\n"));
assert!(tree.read("rtl/m.sv").contains(" input logic a,\n input logic en,\n"));
}
// ---------------------------------------------------------------------------
// Findings on `after` (QA log, findings 1–4).
// ---------------------------------------------------------------------------
/// Finding 1: an anchor whose comment sits between it and its comma (or on
/// the anchor's line before a leading-comma next element) is placed inline
/// at the anchor's end, so the new port lands *between* the anchor and its
/// comment: `a, input logic en /* about a */,`. The comment now documents
/// the new port. `place::verify` compares comment texts as a sorted
/// multiset, so it forgives the move. Correct: the comment stays right
/// after its anchor (insert before the comma token, after the trivia).
#[test]
fn qa_a_comment_between_the_anchor_and_its_comma_stays_with_the_anchor() {
let m = "module m (\n input logic a /* about a */,\n input logic b // about b\n , input logic c,\n output logic y\n);\nendmodule\n";
let top = "module top (input logic a, b, c, en, output logic y);\n m u_m (\n .a (a) /* conn a */,\n .b (b),\n .c (c),\n .y (y)\n );\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]);
let args = json!({"module": "m", "declaration": "input logic en", "after": "a"});
written(&mut server, "add_port", args);
let text = tree.read("rtl/m.sv") + &tree.read("rtl/top.sv");
assert!(!text.contains("en /* about a */"), "the anchor's comment moved to `en`:\n{text}");
assert!(!text.contains(".en(en) /* conn a */"), "the connection's comment moved:\n{text}");
let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]);
let args = json!({"module": "m", "declaration": "input logic en", "after": "b"});
written(&mut server, "add_port", args);
let text = tree.read("rtl/m.sv");
assert!(!text.contains("en // about b"), "the anchor's comment moved to `en`:\n{text}");
}
/// Finding 2: the warnings and refusals `place.rs` writes name the file by
/// its absolute path (`path.display()`, place.rs:84 and :221); every other
/// answer names files relative to a root.
#[test]
fn qa_place_names_files_relative_to_the_root() {
let m = "module m (\n input logic a,\n output logic y\n);\nendmodule\n";
let top = "module top (input logic a, en, output logic y);\n m u_i (\n`ifdef X\n .a (a),\n`endif\n .y (y)\n );\n m u_p (a, y);\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]);
let root = tree.0.to_str().unwrap().to_string();
let args = json!({"module": "m", "declaration": "input logic en", "after": "a"});
let said = refused(&tree, &mut server, "add_port", args, "by position");
assert!(!said.contains(&root) && said.contains("rtl/top.sv"), "{said}");
fs::write(tree.0.join("rtl/top.sv"), top.replace(" m u_p (a, y);\n", "")).unwrap();
let args = json!({"module": "m", "declaration": "input logic en", "after": "a"});
let (text, _) = written(&mut server, "add_port", args);
assert!(!text.contains(&root) && text.contains("rtl/top.sv"), "{text}");
}
/// Finding 3: a next port that is an interface port (`bus_if.mp bus`) has
/// no direction, but does not inherit one either; `after` the port before
/// it is refused as if it did (place.rs:155).
#[test]
fn qa_a_modport_port_after_the_anchor_does_not_refuse() {
let n = "interface bus_if; logic v; modport mp(input v); endinterface\nmodule n (\n input logic clk,\n bus_if.mp bus,\n output logic y\n);\nendmodule\n";
let (_tree, mut server) = served(&[("rtl/n.sv", n)]);
let args = json!({"module": "n", "declaration": "input logic en", "after": "clk"});
let (error, text, _) = server.call("add_port", args);
assert!(!error, "{text}");
}
/// Finding 4: the edit tools list mentions with the line numbers of the
/// text *before* the edit; after a real write that adds or removes lines
/// (`add_port`, `remove_port`, a rename writing out `.*`), a mention below
/// the edit in an edited file names the wrong line.
#[test]
fn qa_mention_lines_name_the_file_as_written() {
let m = "module m (\n input logic a,\n input logic b,\n output logic y\n);\n // en gates y\n assign y = a & b;\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", m)]);
let args = json!({"module": "m", "declaration": "input logic en", "after": "a"});
let (_, mentions) = written(&mut server, "add_port", args);
assert_eq!(mentions, json!(["rtl/m.sv:7"]));
let on_disk = tree.read("rtl/m.sv");
assert_eq!(on_disk.lines().nth(6).map(str::trim), Some("// en gates y"), "{on_disk}");
}
/// Finding 5 (BLOCKING), a: a port list holding an element the parser
/// could not read (`(* keep *) b` — legal SV: an attribute on a port that
/// inherits `a`'s direction and type) hides that element from `place.rs`,
/// which reads the list through `ListElem::ok`. The port placed after `a`
/// lands before `b`, so `b` now inherits `input logic` — its width drops
/// from 8 to 1 — and `place::verify` (which also sees only the well-formed
/// ports, the same token multiset and the same error count) writes it.
/// Correct: refused, nothing written.
#[test]
fn qa_a_port_hidden_by_a_parse_error_does_not_change_its_inherited_type() {
let m = "module m (\n input logic [7:0] a,\n (* keep *) b,\n output logic y\n);\n assign y = ^b;\nendmodule\n";
let top = "module top (input logic [7:0] a, b, input logic en, output logic y);\n m u_m (\n .a (a),\n .b (b),\n .y (y)\n );\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]);
let args = json!({"module": "m", "declaration": "input logic en", "after": "a"});
let before = tree.snapshot();
let (error, text, _) = server.call("add_port", args);
assert!(error, "written: {text}\n{}", tree.read("rtl/m.sv"));
assert!(before == tree.snapshot());
}
/// Finding 5 (BLOCKING), b: `balanced_before` is handed the anchor's index
/// among the *well-formed* ports, but `ListDirective::before` counts every
/// element. One unreadable element before the anchor shifts the count, so
/// an anchor inside an `` `ifdef`` arm passes as outside it: the new port
/// is written inside the arm (it exists only when `X` is defined) while
/// every connection is unconditional — and the engine's own warning, still
/// in the answer, says the port was added "outside every conditional arm".
/// place.rs:161 (header) and :244 (connections) share the bug.
#[test]
fn qa_an_unreadable_element_does_not_let_an_anchor_in_an_ifdef_arm_through() {
let m = "module m (\n input logic a,\n (* keep *) input logic d,\n`ifdef X\n input logic b,\n`endif\n output logic y\n);\nendmodule\n";
let top = "module top (input logic a, b, d, en, output logic y);\n m u_m (\n .a (a),\n .d (d),\n`ifdef X\n .b (b),\n`endif\n .y (y)\n );\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]);
let args = json!({"module": "m", "declaration": "input logic en", "after": "b"});
refused(&tree, &mut server, "add_port", args, "inside an `ifdef arm");
}
// ---------------------------------------------------------------------------
// Re-check of the rework (2026-09-23): the new rules, attacked.
// ---------------------------------------------------------------------------
const PLAIN_M: &str = "module m (\n input logic a,\n output logic y\n);\nendmodule\nmodule o (input logic p, q);\nendmodule\n";
/// An unreadable connection (`..q (p)`) in an instance nothing is placed
/// into — another module's, and a `.*` instance of `m` the engine leaves
/// alone — does not refuse; in an instance the port is placed into, it does,
/// named root-relative, with nothing written.
#[test]
fn qa_r_only_an_affected_instances_unreadable_connection_refuses() {
let top = "module top (input logic a, en, p, output logic y);\n o u_o (\n .p (p),\n ..q (p)\n );\n m u_w (.*, ..z (p));\n m u_m (\n .a (a),\n .y (y)\n );\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", PLAIN_M), ("rtl/top.sv", top)]);
let args = json!({"module": "m", "declaration": "input logic en", "after": "a"});
written(&mut server, "add_port", args.clone());
assert_eq!(
tree.read("rtl/top.sv"),
top.replace(" .a (a),\n", " .a (a),\n .en (en),\n")
);
assert!(tree.read("rtl/m.sv").contains(" input logic a,\n input logic en,\n"));
let affected = top.replace(" .y (y)\n", " .y (y),\n ..z (p)\n");
let (tree, mut server) = served(&[("rtl/m.sv", PLAIN_M), ("rtl/top.sv", &affected)]);
let said = refused(&tree, &mut server, "add_port", args, "`u_m` in rtl/top.sv holds `..z (p)`");
assert!(said.contains("nothing written"), "{said}");
}
/// The last anchor under an own-line comment, with an own-line comment
/// closing the list: the comma goes on the anchor, the new element right
/// below it, both comments stay where they were — header and connections.
#[test]
fn qa_r_own_line_comments_around_the_last_anchor_stay_put() {
let m = "module m (\n input logic a,\n // the result\n output logic y\n // end of ports\n);\nendmodule\n";
let top = "module top (input logic a, en, output logic y);\n m u_m (\n .a (a),\n // the result\n .y (y)\n // end\n );\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]);
let args = json!({"module": "m", "declaration": "input logic en", "after": "y"});
written(&mut server, "add_port", args);
let header = " output logic y,\n input logic en\n // end of ports\n";
assert_eq!(tree.read("rtl/m.sv"), m.replace(" output logic y\n // end of ports\n", header));
let conns = " .y (y),\n .en (en)\n // end\n";
assert_eq!(tree.read("rtl/top.sv"), top.replace(" .y (y)\n // end\n", conns));
}
/// A `//` comment after the separator on the anchor's line (with a block
/// comment before the separator too) stays on the anchor's line; a last
/// anchor with a comment before `)` on the same line keeps it; a
/// leading-comma list gets the element after the separator.
#[test]
fn qa_r_comments_on_the_anchors_line_stay_on_it() {
let m = "module m (\n input logic a /* c1 */, // c2\n input logic b // about b\n , output logic y\n);\nendmodule\nmodule n (input logic a, output logic y /* c */);\nendmodule\n";
let top = "module top (input logic a, b, en, output logic y);\n m u_m (\n .a (a), // in a\n .b (b),\n .y (y)\n );\n n u_n (.a(a), .y(y) /* k */);\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]);
let args = json!({"module": "m", "declaration": "input logic en", "after": "a"});
written(&mut server, "add_port", args);
let want = m.replace("// c2\n", "// c2\n input logic en,\n");
assert_eq!(tree.read("rtl/m.sv"), want);
let want_top = top.replace("// in a\n", "// in a\n .en (en),\n");
assert_eq!(tree.read("rtl/top.sv"), want_top);
let args = json!({"module": "m", "declaration": "input logic f", "after": "b"});
written(&mut server, "add_port", args);
let header = " input logic b // about b\n , input logic f, output logic y\n";
assert_eq!(
tree.read("rtl/m.sv"),
want.replace(" input logic b // about b\n , output logic y\n", header)
);
let args = json!({"module": "n", "declaration": "input logic en", "after": "y"});
written(&mut server, "add_port", args);
let m_now = tree.read("rtl/m.sv");
assert!(
m_now.contains("module n (input logic a, output logic y, /* c */ input logic en);"),
"{m_now}"
);
let top_now = tree.read("rtl/top.sv");
assert!(top_now.contains(" n u_n (.a(a), .y(y), /* k */ .en(en));"), "{top_now}");
}
/// A typed port without a direction after the anchor inherits the anchor's
/// direction: a new port of the same direction keeps it (placed, byte for
/// byte); of another direction would turn it (refused, nothing written).
#[test]
fn qa_r_a_typed_undirected_next_port_is_placed_only_under_the_same_direction() {
let m = "module m (\n input logic a,\n logic [3:0] b,\n output logic y\n);\nendmodule\n";
let top = "module top (input logic a, en, input logic [3:0] b, output logic y);\n m u_m (\n .a (a),\n .b (b),\n .y (y)\n );\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]);
let args = json!({"module": "m", "declaration": "output logic en", "after": "a"});
refused(&tree, &mut server, "add_port", args, "`b` takes its direction");
let args = json!({"module": "m", "declaration": "input logic en", "after": "a"});
written(&mut server, "add_port", args);
assert_eq!(
tree.read("rtl/m.sv"),
m.replace(" input logic a,\n", " input logic a,\n input logic en,\n")
);
assert_eq!(
tree.read("rtl/top.sv"),
top.replace(" .a (a),\n", " .a (a),\n .en (en),\n")
);
}
/// A rename that writes out a `.*` binding adds a line above the mentions;
/// the written answer names the lines of the file as written.
#[test]
fn qa_r_mention_lines_after_a_rename_writing_out_a_star_binding() {
let m = "module m (\n input logic a,\n output logic y\n);\n assign y = a;\nendmodule\n";
let top = "module top (input logic a, output logic y);\n m u_m (\n .*\n );\n // a feeds u_m\n initial $display(\"a\");\nendmodule\n";
let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]);
let args = json!({"name": "a", "file": "rtl/m.sv", "new_name": "a_i"});
let (text, mentions) = written(&mut server, "rename", args);
assert!(text.contains("added `.a_i(a)`"), "{text}");
let on_disk = tree.read("rtl/top.sv");
assert!(on_disk.contains(" .*,\n .a_i(a)\n"), "{on_disk}");
assert_eq!(mentions, json!(["rtl/top.sv:6", "rtl/top.sv:7"]), "{text}");
let lines: Vec<&str> = on_disk.lines().map(str::trim).collect();
assert_eq!((lines[5], lines[6]), ("// a feeds u_m", "initial $display(\"a\");"));
}
// ---------------------------------------------------------------------------
// 2. Unresolved mentions.
// ---------------------------------------------------------------------------
const SM: &str = "module main_sm (\n input logic clk_i,\n output logic busy_o\n);\n logic state_q, state_q_d;\n // see tb.u_main_sm.state_q for the probe\n // state_q_d is not it, nor xstate_q\n `uvm_info(\"SM\", $sformatf(\"state_q=%0d\", state_q_d), UVM_LOW)\n `define F(state_q) state_q + 1\n `define G(x) x.state_q\n assign busy_o = state_q;\n initial $display(\"%m.state_q\");\n // \\state_q escaped\nendmodule\n";
const DV: &str = "module dv_x;\n logic a, b;\n assign a = `HIER.u_a[2].state_q;\n assign b = `HIER.u_a[2].state_q_d;\n assign b = `HIER.u_a[state_q].x;\nendmodule\n";
// Dotted spellings: `state_q` is a member of `main_sm`, so since §65.1's
// scoping of mentions a bare spelling in another file is not listed, and a
// path-like one (`.state_q`) still is — which keeps this CRLF check alive.
const CRLF: &str =
"module c;\r\n // one\r\n // u.state_q two\r\n string s = \"u.state_q\";\r\n // state_q bare, not listed\r\nendmodule\r\n";
#[test]
fn qa_mentions_find_every_kind_and_only_whole_words() {
let files = [("rtl/sm.sv", SM), ("rtl/sub/crlf.sv", CRLF), ("dv/x.sv", DV)];
let (_tree, mut server) = served(&files);
let (text, mentions) = written(&mut server, "find", json!({"name": "state_q", "refs": true}));
assert_eq!(
mentions,
json!([
// The file of the hits first: a hierarchical path in a comment,
// a string inside a macro's arguments, a `define body (not the
// `define whose formal is the name), a string, an escaped
// spelling in a comment.
"rtl/sm.sv:6",
"rtl/sm.sv:8",
"rtl/sm.sv:10",
"rtl/sm.sv:12",
"rtl/sm.sv:13",
// Then nearest the declaration; CRLF lines counted right.
"rtl/sub/crlf.sv:3",
"rtl/sub/crlf.sv:4",
// A macro-rooted path through an index; `state_q_d` and a
// name used as an index are not the path's last name.
"dv/x.sv:3",
]),
"{text}"
);
assert!(text
.ends_with("unresolved:\n rtl/sm.sv:6,8,10,12,13\n rtl/sub/crlf.sv:3,4\n dv/x.sv:3\n"));
assert!(!text.contains('\r'), "no carriage return in an answer");
}
#[test]
fn qa_mentions_are_capped_at_50_with_the_edited_file_first() {
// Path-like, so listed from a file that neither declares nor uses the
// member (§65.1's scoping of mentions drops a bare one there).
let far: String = (0..60).map(|i| format!("// u.state_q far {i}\n")).collect::<String>()
+ "module far; endmodule\n";
let files = [("rtl/sm.sv", SM), ("zz/far.sv", far.as_str())];
let (tree, mut server) = served(&files);
let args = json!({"name": "state_q", "new_name": "st_q"});
let (text, mentions) = written(&mut server, "rename", args);
let listed = mentions.as_array().unwrap();
assert_eq!(listed.len(), 50);
assert_eq!(listed[0], "rtl/sm.sv:6", "the edited file first");
assert_eq!(listed[5], "zz/far.sv:1");
assert_eq!(listed[49], "zz/far.sv:45");
assert!(text.ends_with("\n … and 15 more\n"), "{text}");
// The renamed spellings are not mentions; the edit left the rest alone.
assert!(!listed.iter().any(|site| site == "rtl/sm.sv:5" || site == "rtl/sm.sv:11"));
let sm = tree.read("rtl/sm.sv");
assert_eq!(
sm,
SM.replace("logic state_q,", "logic st_q,").replace("busy_o = state_q;", "busy_o = st_q;")
);
}
// ---------------------------------------------------------------------------
// 3. The catalogue and the instructions.
// ---------------------------------------------------------------------------
#[test]
fn qa_the_catalogue_is_small_bare_and_spec_shaped() {
let tree = Tree::with(&[]);
let mut server = Session::over(&tree);
let reply = server.request("tools/list", json!({}));
let tools = reply["result"]["tools"].as_array().unwrap();
assert_eq!(tools.len(), 9);
for tool in tools {
let name = tool["name"].as_str().unwrap();
assert!(tool.get("title").is_none(), "{name}: `title` is gone (PLAN §10.1)");
assert!(tool["description"].as_str().is_some_and(|d| !d.is_empty()), "{name}");
let annotations = tool["annotations"].as_object().unwrap();
assert!(!annotations.contains_key("title"), "{name}: annotations.title is gone");
for hint in ["readOnlyHint", "destructiveHint", "idempotentHint"] {
assert!(annotations[hint].is_boolean(), "{name}.{hint}");
}
let schema = &tool["inputSchema"];
assert_eq!(schema["type"], "object", "{name}");
for (param, property) in schema["properties"].as_object().unwrap() {
assert!(property.get("description").is_none(), "{name}.{param} carries a description");
assert!(
tool["description"].as_str().unwrap().contains(param.as_str()),
"{name} names `{param}`"
);
}
}
let port = tools.iter().find(|t| t["name"] == "port").unwrap();
assert_eq!(port["inputSchema"]["properties"]["after"], json!({"type": "string"}));
assert_eq!(port["inputSchema"]["required"], json!(["module"]));
// The instructions: short, and every tool they name exists.
let instructions = server.init["result"]["instructions"].as_str().unwrap();
assert!(instructions.len() <= 400, "{}", instructions.len());
let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
let words = instructions.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'));
for word in words.filter(|w| w.contains('_')) {
assert!(names.contains(&word), "the instructions name `{word}`, which is not a tool");
}
for word in names {
assert!(instructions.contains(word), "{word}");
}
}
// ---------------------------------------------------------------------------
// 4. The temp-store sweep.
// ---------------------------------------------------------------------------
#[test]
fn qa_the_sweep_takes_only_old_files_of_the_exact_temp_name() {
let tree = Tree::with(&[("rtl/a.sv", "module a; endmodule\n")]);
let cache = tree.0.join("cache");
fs::create_dir_all(&cache).unwrap();
let hour_ago = std::time::SystemTime::now() - Duration::from_secs(3600);
let old = |path: &Path| {
fs::File::open(path).unwrap().set_modified(hour_ago).unwrap();
};
let stale = cache.join("index-cache-mcp.1.tmp");
let spared_names = [
"index-cache-mcp..tmp",
"index-cache-mcp.12a.tmp",
"index-cache-mcp.12.tmp.bak",
"index-cache.12.tmp",
"xindex-cache-mcp.12.tmp",
];
for name in std::iter::once("index-cache-mcp.1.tmp").chain(spared_names) {
fs::write(cache.join(name), "torn").unwrap();
old(&cache.join(name));
}
// An old directory of the exact name is not a file: left alone.
let dir = cache.join("index-cache-mcp.77.tmp");
fs::create_dir_all(dir.join("inside")).unwrap();
old(&dir);
let mut server = Session::spawn(&[
"--root",
tree.0.to_str().unwrap(),
"--index-cache",
cache.to_str().unwrap(),
]);
server.call("hierarchy", json!({}));
server.end();
assert!(cache.join("index-cache-mcp").is_file(), "the own store is still written");
assert!(!stale.exists(), "an hour-old `<store>.<pid>.tmp` is swept");
for name in spared_names {
assert!(cache.join(name).exists(), "{name} is not ours to sweep");
}
assert!(dir.join("inside").is_dir(), "a directory is never swept");
}
+284
View File
@@ -0,0 +1,284 @@
//! QA attacks on lane feedback-2 (the count line on every paged answer, the
//! `in` path glob, the post-edit check line), 2026-09-23 — ported to the
//! lean catalogue: paging, `in` and the check line are gone (PLAN §10.2),
//! so what remains is the hierarchy walk over this tree and the path glob,
//! which lives on as `format`'s `files` (`docs/features/mcp-lean-catalogue`
//! lists what was deleted).
//!
//! A test that pins a QA finding asserts the *correct* behaviour and is
//! `#[ignore = "QA finding N"]` until a rework flips it; the findings are
//! numbered as in the QA log of `docs/features/mcp-feedback-2/README.md`.
use std::collections::BTreeMap;
use std::fs;
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{self, Receiver};
use std::time::Duration;
use serde_json::{json, Value};
const ANSWER_TIMEOUT: Duration = Duration::from_secs(120);
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
/// A scratch tree holding the files a case writes; removed on drop.
struct Tree(PathBuf);
impl Tree {
fn with(files: &[(&str, &str)]) -> Tree {
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
let dir =
std::env::temp_dir().join(format!("lucisv-mcp-qa-f2-{}-{unique}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
for (name, text) in files {
let path = dir.join(name);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, text).unwrap();
}
Tree(fs::canonicalize(dir).unwrap())
}
/// Every file, root-relative, with its bytes.
fn snapshot(&self) -> BTreeMap<String, Vec<u8>> {
fn walk(dir: &Path, root: &Path, out: &mut BTreeMap<String, Vec<u8>>) {
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
walk(&path, root, out);
} else {
let name = path.strip_prefix(root).unwrap().to_string_lossy().into_owned();
out.insert(name, fs::read(&path).unwrap());
}
}
}
let mut out = BTreeMap::new();
walk(&self.0, &self.0, &mut out);
out
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
/// One running server, initialised.
struct Session {
child: Child,
stdin: Option<ChildStdin>,
lines: Receiver<String>,
next_id: i64,
/// The `initialize` reply.
init: Value,
}
impl Session {
fn over(tree: &Tree) -> Session {
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
.args(["--root", tree.0.to_str().unwrap()])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
let stdout = child.stdout.take().unwrap();
let (send, lines) = mpsc::channel();
std::thread::spawn(move || {
for line in BufReader::new(stdout).lines().map_while(Result::ok) {
if send.send(line).is_err() {
break;
}
}
});
let stdin = child.stdin.take().unwrap();
let mut session =
Session { child, stdin: Some(stdin), lines, next_id: 0, init: Value::Null };
session.init = session
.request("initialize", json!({"protocolVersion": "2025-06-18", "capabilities": {}}));
session.send(&json!({"jsonrpc": "2.0", "method": "notifications/initialized"}));
session
}
fn send(&mut self, message: &Value) {
let stdin = self.stdin.as_mut().unwrap();
writeln!(stdin, "{message}").unwrap();
stdin.flush().unwrap();
}
fn request(&mut self, method: &str, params: Value) -> Value {
self.next_id += 1;
let id = self.next_id;
self.send(&json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}));
let line = self.lines.recv_timeout(ANSWER_TIMEOUT).expect("the server answered");
let reply: Value = serde_json::from_str(&line).unwrap();
assert_eq!(reply["id"], id);
reply
}
/// A tool call: whether it was refused, and its text.
fn call(&mut self, tool: &str, arguments: Value) -> (bool, String) {
let reply = self.request("tools/call", json!({"name": tool, "arguments": arguments}));
let result = &reply["result"];
let text = result["content"][0]["text"].as_str().unwrap_or_default().to_string();
(result["isError"] == true, text)
}
/// A call that must answer: its text.
fn text(&mut self, tool: &str, arguments: Value) -> String {
let (error, text) = self.call(tool, arguments.clone());
assert!(!error, "{tool} {arguments}: refused: {text}");
text
}
}
impl Drop for Session {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
// ---------------------------------------------------------------------------
// The tree: three depths under `ip/`, a `hw/ip/` decoy for anchoring, a
// `lib/` the RTL instantiates, an escaped name holding `*`, a comment
// mention outside `ip/`, a no-tabs finding and an unused external waiver.
// ---------------------------------------------------------------------------
const TREE: &[(&str, &str)] = &[
(
"lucisv.toml",
"[lint]\nselect = [\"unused-signal\", \"no-tabs\", \"unused-waiver\"]\nwaivers = [\"w.waiver\"]\n",
),
("w.waiver", "waive --rule=no-tabs --location=nothing.sv\n"),
(
"ip/x.sv",
"`define IPX 1\nmodule ipx (input logic clk_i);\n logic dead_a;\n leaf u_a (.clk_i(clk_i));\nendmodule\n",
),
(
"ip/aes/rtl/aes.sv",
"`define AES_A 1\n`define AES_B 2\nmodule aes (input logic clk_i);\n logic dead_b;\n leaf u_b (.clk_i(clk_i));\n mid u_m (.clk_i(clk_i));\nendmodule\n",
),
(
"ip/aes/rtl/sub/deep.sv",
"module deep (input logic clk_i);\n logic dead_c;\n leaf u_c (.clk_i(clk_i));\nendmodule\n",
),
(
"ip/aes/dv/tb.sv",
"module tb;\n logic clk_i; // clk_i drives leaf\n aes u_dut (.clk_i(clk_i));\n leaf u_d (.clk_i(clk_i));\nendmodule\n",
),
("hw/ip/y.sv", "module hwy (input logic clk_i);\n\tleaf u_e (.clk_i(clk_i));\nendmodule\n"),
("lib/leaf.sv", "module leaf (input logic clk_i);\nendmodule\n"),
(
"lib/mid.sv",
"module mid (input logic clk_i);\n leaf u_f (.clk_i(clk_i));\n deep u_g (.clk_i(clk_i));\nendmodule\n",
),
("doc/notes.sv", "// leaf is the unit under test\nmodule notes; endmodule\n"),
("esc/e.sv", "module \\esc*mod (input logic a);\nendmodule\n"),
];
fn served() -> (Tree, Session) {
let tree = Tree::with(TREE);
let server = Session::over(&tree);
(tree, server)
}
// ---------------------------------------------------------------------------
// 1. The hierarchy over this tree.
// ---------------------------------------------------------------------------
#[test]
fn qa_hierarchy_up_lists_every_instantiation_at_every_level() {
let (_tree, mut server) = served();
let whole = server.text("hierarchy", json!({"root": "leaf", "up": true, "depth": 3}));
// Deeper lines are instantiations of the ancestors.
assert_eq!(whole.lines().count(), 11, "{whole}");
let direct = server.text("hierarchy", json!({"root": "leaf", "up": true}));
assert_eq!(direct.lines().count(), 6, "{direct}");
assert!(direct.contains("aes.u_b ip/aes/rtl/aes.sv:5\n"), "{direct}");
assert!(direct.lines().all(|line| !line.starts_with(' ')), "one level: {direct}");
assert_eq!(
server.text("hierarchy", json!({"root": "tb", "up": true})),
"nothing instantiates tb\n"
);
assert_eq!(
server.text("hierarchy", json!({"root": "aes", "up": true})),
"tb.u_dut ip/aes/dv/tb.sv:3\n"
);
}
#[test]
fn qa_hierarchy_up_from_a_root_declared_twice_lists_each_instantiation_once() {
let tree = Tree::with(&[
("a/d1.sv", "module dup; endmodule\n"),
("b/d2.sv", "module dup; endmodule\n"),
("a/user.sv", "module user; dup u1 (); dup u2 (); endmodule\n"),
]);
let mut server = Session::over(&tree);
assert_eq!(
server.text("hierarchy", json!({"root": "dup", "up": true})),
"user.u1 a/user.sv:1\nuser.u2 a/user.sv:1\n"
);
// Down, each declaration is a root of its own.
assert_eq!(server.text("hierarchy", json!({"root": "dup"})), "dup a/d1.sv:1\ndup b/d2.sv:1\n");
}
#[test]
fn qa_hierarchy_without_a_root_names_every_top_at_its_declaration() {
let (_tree, mut server) = served();
assert_eq!(
server.text("hierarchy", json!({})),
"9 files, 9 modules, 5 top\n\\esc*mod esc/e.sv:1\nhwy hw/ip/y.sv:1\nipx ip/x.sv:2\nnotes doc/notes.sv:2\ntb ip/aes/dv/tb.sv:1\n"
);
}
// ---------------------------------------------------------------------------
// 2. The path glob, as `format`'s `files` reads it.
// ---------------------------------------------------------------------------
/// How many files `format` took for `files` over a fresh copy of the tree
/// (or its refusal); every file it wrote must lie under `within`.
fn formatted_within(files: &str, within: &str) -> String {
let (tree, mut server) = served();
let before = tree.snapshot();
let (error, text) = server.call("format", json!({"files": files}));
let after = tree.snapshot();
for (file, bytes) in &after {
assert!(before[file] == *bytes || file.starts_with(within), "{files} wrote {file}");
}
if error {
return text;
}
text.split(" file").next().unwrap().trim_start_matches("formatted ").to_string()
}
fn formatted(files: &str) -> String {
formatted_within(files, "")
}
#[test]
fn qa_a_star_stays_in_one_component_and_a_double_star_spans_zero_or_more() {
assert_eq!(formatted("ip/**/*.sv"), "4");
assert_eq!(formatted_within("ip/*.sv", "ip/x.sv"), "1");
assert_eq!(formatted("ip/ae?/*/*.sv"), "2");
assert_eq!(formatted("**/rtl/**"), "2");
assert_eq!(formatted("*.sv"), "no indexed file matches `*.sv`; nothing written.");
}
#[test]
fn qa_a_bare_directory_means_everything_below_it_and_never_a_prefix() {
assert_eq!(formatted_within("ip/aes", "ip/aes/"), "3");
assert_eq!(formatted("ip/aes/"), "3");
assert_eq!(formatted("lib"), "2");
assert!(formatted("ip/ae").contains("`ip/ae`"), "a prefix of a name is no directory");
}
#[test]
fn qa_the_glob_matches_paths_never_names_even_escaped_ones_holding_a_star() {
assert_eq!(formatted("esc/*.sv"), "1");
assert!(formatted("\\esc*mod").contains("\\esc*mod"), "a unit name is not a path");
}
+167 -261
View File
@@ -254,11 +254,12 @@ fn qa_ten_megabyte_lines_are_answered_and_the_next_line_still_is() {
let mut s = Session::ready(&scratch);
let big_query = "q".repeat(10 * 1024 * 1024);
let big_call = json!({"jsonrpc":"2.0","id":"big","method":"tools/call",
"params":{"name":"search_symbols","arguments":{"query": big_query}}});
"params":{"name":"find","arguments":{"name": big_query}}});
s.send(&big_call.to_string());
let reply = s.receive();
assert_eq!(reply["id"], "big");
assert_eq!(reply["result"]["isError"], false);
let said = reply["result"]["content"][0]["text"].as_str().unwrap();
assert!(said.starts_with("no declaration named `qqq"), "an answer, not a fault");
s.send(&"z".repeat(10 * 1024 * 1024));
let reply = s.receive();
assert_eq!(reply["error"]["code"], -32700);
@@ -275,9 +276,8 @@ fn qa_everything_but_initialize_and_ping_waits_for_the_handshake() {
}
assert!(s.pings());
s.initialize();
// M2 added five tools (defines, definition, references, hierarchy,
// diagnostics) to M1's six; M3 added twelve edit tools.
assert_eq!(s.request("tools/list", json!({}))["result"]["tools"].as_array().unwrap().len(), 23);
// The lean catalogue: nine tools (PLAN §10.1).
assert_eq!(s.request("tools/list", json!({}))["result"]["tools"].as_array().unwrap().len(), 9);
}
#[test]
@@ -296,16 +296,16 @@ fn qa_an_unsupported_protocol_version_is_offered_our_newest() {
fn qa_bad_tool_arguments_are_tool_errors_that_name_the_field() {
let scratch = Scratch::with(SMALL);
let mut s = Session::ready(&scratch);
let missing = s.refusal("read_item", json!({"file": "x.sv"}));
let missing = s.refusal("read", json!({"file": "x.sv"}));
assert!(missing.contains("`item`"), "{missing}");
let extra = s.refusal("outline", json!({"file": "x.sv", "verbose": true}));
assert!(extra.contains("`verbose`"), "{extra}");
let wrong = s.refusal("outline", json!({"file": 7}));
assert!(wrong.contains("`file`") && wrong.contains("string"), "{wrong}");
let float = s.refusal("list_units", json!({"limit": 2.5}));
assert!(float.contains("`limit`"), "{float}");
let kind = s.refusal("list_units", json!({"kind": "struct"}));
assert!(kind.contains("`kind`"), "{kind}");
let float = s.refusal("hierarchy", json!({"root": "x", "depth": 2.5}));
assert!(float.contains("`depth`"), "{float}");
let op = s.refusal("edit_item", json!({"file": "x.sv", "op": "struct", "item": "y"}));
assert!(op.contains("`op`"), "{op}");
// An envelope the method cannot read at all stays a protocol error.
let reply = s.request("tools/call", json!({"name": "outline", "arguments": [1]}));
assert_eq!(reply["error"]["code"], -32602);
@@ -382,13 +382,13 @@ fn qa_stdout_carries_only_json_lines_even_under_verbose() {
input.push_str(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#);
input.push('\n');
let calls = [
json!({"name": "project_overview", "arguments": {}}),
json!({"name": "list_units", "arguments": {}}),
json!({"name": "unit_interface", "arguments": {"name": "a"}}),
json!({"name": "hierarchy", "arguments": {}}),
json!({"name": "find", "arguments": {"name": "a", "refs": true}}),
json!({"name": "outline", "arguments": {"unit": "a"}}),
json!({"name": "outline", "arguments": {"file": "b.sv"}}),
json!({"name": "outline", "arguments": {"file": "bad.sv"}}),
json!({"name": "read_item", "arguments": {"file": "a.sv", "item": "u_b"}}),
json!({"name": "search_symbols", "arguments": {"query": ""}}),
json!({"name": "read", "arguments": {"file": "a.sv", "item": "u_b"}}),
json!({"name": "check", "arguments": {}}),
];
for (at, call) in calls.iter().enumerate() {
let line = json!({"jsonrpc":"2.0","id": at + 2,"method":"tools/call","params": call});
@@ -423,19 +423,17 @@ fn qa_an_invalid_request_with_a_readable_id_keeps_that_id() {
// --------------------------------------------------------------- rendering
#[test]
fn qa_an_escaped_identifier_unit_is_listed_described_and_instantiable() {
fn qa_an_escaped_identifier_unit_is_found_outlined_and_read() {
let scratch = Scratch::with(&[(
"esc.sv",
"module \\my-mod (input logic [7:0] a [0:3], output logic b);\nendmodule\n",
)]);
let mut s = Session::ready(&scratch);
assert!(s.text("list_units", json!({})).contains("module \\my-mod 1"));
let answer = s.text("unit_interface", json!({"name": "\\my-mod"}));
assert!(answer.starts_with("module \\my-mod esc.sv:1\n"), "{answer}");
// The template must still be legal: an escaped name ends at whitespace.
assert!(answer.contains("\\my-mod \\u_my-mod ("), "{answer}");
let item = s.text("read_item", json!({"file": "esc.sv", "item": "\\my-mod"}));
assert!(item.starts_with("esc.sv:1-2\nmodule \\my-mod (input"), "{item}");
assert_eq!(s.text("find", json!({"name": "\\my-mod"})), "module \\my-mod esc.sv:1\n");
let answer = s.text("outline", json!({"unit": "\\my-mod"}));
assert!(answer.starts_with("esc.sv:1\ninput logic [7:0] a [0:3]\n"), "{answer}");
let item = s.text("read", json!({"file": "esc.sv", "item": "\\my-mod"}));
assert!(item.starts_with("esc.sv:1–2\nmodule \\my-mod (input"), "{item}");
}
#[test]
@@ -445,14 +443,10 @@ fn qa_packed_and_unpacked_ranges_are_both_reported() {
"module hp (input logic [7:0] a [0:3], output logic [3:0][1:0] b [2][0:1]);\nendmodule\n",
)]);
let mut s = Session::ready(&scratch);
let result = s.call("unit_interface", json!({"name": "hp"}));
let ports = &result["structuredContent"]["ports"];
assert_eq!(ports[0]["range"], "[7:0]");
assert_eq!(ports[0]["unpacked"], "[0:3]");
assert_eq!(ports[1]["range"], "[3:0][1:0]");
assert_eq!(ports[1]["unpacked"], "[2][0:1]");
let text = result["content"][0]["text"].as_str().unwrap();
assert!(text.contains("input logic [7:0] a [0:3]"), "{text}");
assert_eq!(
s.text("outline", json!({"unit": "hp"})),
"hp.sv:1\ninput logic [7:0] a [0:3]\noutput logic [3:0][1:0] b [2][0:1]\n"
);
}
#[test]
@@ -462,29 +456,29 @@ fn qa_a_typed_parameter_keeps_its_default_and_a_localparam_is_not_offered() {
"module tp #(parameter type T = logic [3:0], parameter int unsigned N = 4,\n localparam int L = 2) (input T a);\nendmodule\n",
)]);
let mut s = Session::ready(&scratch);
let result = s.call("unit_interface", json!({"name": "tp"}));
let params = &result["structuredContent"]["parameters"];
assert_eq!(
params,
&json!([{"name": "T", "default": "logic [3:0]"}, {"name": "N", "default": "4"}])
s.text("outline", json!({"unit": "tp"})),
"tp.sv:1\nparam T = logic [3:0]\nparam N = 4\ninput T a\n"
);
assert!(result["structuredContent"]["template"].as_str().unwrap().contains(".T(logic [3:0])"));
}
#[test]
fn qa_crlf_files_keep_their_line_numbers_and_read_item_returns_the_exact_bytes() {
fn qa_crlf_files_keep_their_line_numbers_and_read_returns_the_exact_bytes() {
let text = "// head\r\nmodule crlf (\r\n input logic clk,\r\n output logic q\r\n);\r\n logic x;\r\n always_ff @(posedge clk)\r\n q <= x;\r\nendmodule\r\n";
let scratch = Scratch::with(&[("crlf.sv", text)]);
let mut s = Session::ready(&scratch);
let outline = s.text("outline", json!({"file": "crlf.sv"}));
assert_eq!(outline, "crlf.sv\n module crlf 2-9\n port clk 3\n port q 4\n var x 6\n");
let result = s.call("read_item", json!({"file": "crlf.sv", "item": "always@8"}));
assert_eq!(result["structuredContent"]["lines"], json!([7, 8]));
assert_eq!(result["structuredContent"]["text"], "always_ff @(posedge clk)\r\n q <= x;");
let module = s.call("read_item", json!({"file": "crlf.sv", "item": "crlf"}));
assert_eq!(
s.text("outline", json!({"file": "crlf.sv"})),
"module crlf 2–9\n port clk 3\n port q 4\n var x 6\n"
);
assert_eq!(
s.text("read", json!({"file": "crlf.sv", "item": "always@8"})),
"crlf.sv:7–8\nalways_ff @(posedge clk)\r\n q <= x;\n"
);
let module = s.text("read", json!({"file": "crlf.sv", "item": "crlf"}));
let start = text.find("module").unwrap();
assert_eq!(module["structuredContent"]["text"], &text[start..text.len() - 2]);
assert_eq!(s.text("list_units", json!({})), "crlf.sv\n module crlf 2\n");
assert_eq!(module, format!("crlf.sv:2–9\n{}\n", &text[start..text.len() - 2]));
assert_eq!(s.text("hierarchy", json!({})), "1 file, 1 module, 1 top\ncrlf crlf.sv:2\n");
}
#[test]
@@ -494,11 +488,11 @@ fn qa_multibyte_text_before_an_item_keeps_lines_right() {
"// été ünïcode 日本語\nmodule utf (input logic a); /* é */ logic z;\n /* 日本 */ logic w;\nendmodule\n",
)]);
let mut s = Session::ready(&scratch);
let outline = s.text("outline", json!({"file": "utf.sv"}));
assert_eq!(outline, "utf.sv\n module utf 2-4\n port a 2\n var z 2\n var w 3\n");
let w = s.call("read_item", json!({"file": "utf.sv", "item": "w"}));
assert_eq!(w["structuredContent"]["text"], "logic w;");
assert_eq!(w["structuredContent"]["lines"], json!([3, 3]));
assert_eq!(
s.text("outline", json!({"file": "utf.sv"})),
"module utf 2–4\n port a 2\n var z 2\n var w 3\n"
);
assert_eq!(s.text("read", json!({"file": "utf.sv", "item": "w"})), "utf.sv:3\nlogic w;\n");
}
#[test]
@@ -508,13 +502,16 @@ fn qa_a_module_declared_in_two_files_is_refused_naming_both() {
("sub/d2.sv", "// two\nmodule dup (input a); endmodule\n"),
]);
let mut s = Session::ready(&scratch);
let refusal = s.refusal("unit_interface", json!({"name": "dup"}));
let refusal = s.refusal("outline", json!({"unit": "dup"}));
assert!(refusal.contains("d1.sv:1") && refusal.contains("sub/d2.sv:2"), "{refusal}");
let picked = s.text("unit_interface", json!({"name": "dup", "file": "sub/d2.sv"}));
assert!(picked.contains("input a"), "{picked}");
// Listed once each, and a top module is named once.
let overview = s.call("project_overview", json!({}));
assert_eq!(overview["structuredContent"]["top_modules"], json!(["dup"]));
assert!(s.text("outline", json!({"file": "sub/d2.sv"})).contains("port a 2"));
let read = s.refusal("read", json!({"item": "dup"}));
assert!(read.contains("d1.sv:1") && read.contains("sub/d2.sv:2"), "{read}");
// Each declaration is a top of its own, at its own line.
assert_eq!(
s.text("hierarchy", json!({})),
"2 files, 2 modules, 2 top\ndup d1.sv:1\ndup sub/d2.sv:2\n"
);
}
#[test]
@@ -524,56 +521,12 @@ fn qa_a_name_declared_twice_in_one_file_is_refused_with_both_spellings() {
"module twice; logic w; endmodule\nmodule other;\n logic w;\nendmodule\n",
)]);
let mut s = Session::ready(&scratch);
let refusal = s.refusal("read_item", json!({"file": "w.sv", "item": "w"}));
let refusal = s.refusal("read", json!({"file": "w.sv", "item": "w"}));
assert!(refusal.contains("var:w@1") && refusal.contains("var:w@3"), "{refusal}");
assert_eq!(
s.call("read_item", json!({"file": "w.sv", "item": "w@3"}))["structuredContent"]["text"],
"logic w;"
);
}
#[test]
fn qa_list_units_glob_question_mark_is_exactly_one_character() {
let scratch = Scratch::with(&[(
"g.sv",
"module dup; endmodule\nmodule dp; endmodule\nmodule duup; endmodule\nmodule d_p; endmodule\n",
)]);
let mut s = Session::ready(&scratch);
let result = s.call("list_units", json!({"glob": "d?p"}));
let names: Vec<&str> = result["structuredContent"]["units"]
.as_array()
.unwrap()
.iter()
.map(|u| u["name"].as_str().unwrap())
.collect();
assert_eq!(names, vec!["dup", "d_p"]);
}
#[test]
fn qa_outline_depth_zero_is_refused_and_a_huge_limit_is_fine() {
let scratch = Scratch::with(SMALL);
let mut s = Session::ready(&scratch);
let refusal = s.refusal("outline", json!({"file": "x.sv", "depth": 0}));
assert!(refusal.contains("`depth`"), "{refusal}");
let all = s.call("outline", json!({"file": "x.sv", "limit": i64::MAX, "offset": 0}));
assert_eq!(all["structuredContent"]["total"], 3);
let past = s.call("outline", json!({"file": "x.sv", "offset": i64::MAX}));
assert_eq!(past["structuredContent"]["symbols"], json!([]));
let top = s.call("outline", json!({"file": "x.sv", "depth": 1}));
assert_eq!(top["structuredContent"]["symbols"].as_array().unwrap().len(), 1);
}
#[test]
fn qa_search_symbols_with_an_empty_query_matches_everything_and_pages() {
let scratch = Scratch::with(&[
("a.sv", "module a (input p, input q); endmodule\n"),
("b.sv", "package b; parameter int K = 1; endpackage\n"),
]);
let mut s = Session::ready(&scratch);
let all = s.call("search_symbols", json!({"query": ""}));
assert_eq!(all["structuredContent"]["total"], 5);
let page = s.call("search_symbols", json!({"query": "", "limit": 2}));
assert!(page["content"][0]["text"].as_str().unwrap().ends_with("… and 3 more\n"));
assert_eq!(s.text("read", json!({"file": "w.sv", "item": "w@3"})), "w.sv:3\nlogic w;\n");
let design = s.refusal("read", json!({"item": "w"}));
assert!(design.contains("w.sv:1, w.sv:3"), "{design}");
assert_eq!(s.text("read", json!({"item": "w@3"})), "w.sv:3\nlogic w;\n");
}
#[test]
@@ -585,12 +538,9 @@ fn qa_a_class_reports_its_own_base_not_a_same_named_class_s() {
("c.sv", "class c; int top_member; endclass\n"),
]);
let mut s = Session::ready(&scratch);
let p1 = s.call("unit_interface", json!({"name": "p1::c"}));
assert_eq!(p1["structuredContent"]["extends"], "base1");
let p2 = s.call("unit_interface", json!({"name": "p2::c"}));
assert_eq!(p2["structuredContent"]["extends"], "base2", "{p2}");
let top = s.call("unit_interface", json!({"name": "c"}));
assert_eq!(top["structuredContent"]["extends"], Value::Null, "{top}");
assert_eq!(s.text("outline", json!({"unit": "p1::c"})), "p1.sv:2\nextends base1\nvar a 2\n");
assert_eq!(s.text("outline", json!({"unit": "p2::c"})), "p2.sv:2\nextends base2\nvar b 2\n");
assert_eq!(s.text("outline", json!({"unit": "c"})), "c.sv:1\nvar top_member 1\n");
}
#[test]
@@ -600,32 +550,19 @@ fn qa_two_same_named_classes_in_one_file_do_not_share_members() {
"package p1; class c; int a; endclass endpackage\npackage p2; class c; int b; endclass endpackage\n",
)]);
let mut s = Session::ready(&scratch);
let p1 = s.call("unit_interface", json!({"name": "p1::c"}));
assert_eq!(
p1["structuredContent"]["members"],
json!([{"name": "a", "kind": "var", "line": 1}])
);
let p2 = s.call("unit_interface", json!({"name": "p2::c"}));
assert_eq!(
p2["structuredContent"]["members"],
json!([{"name": "b", "kind": "var", "line": 2}])
);
assert_eq!(s.text("outline", json!({"unit": "p1::c"})), "pk.sv:1\nvar a 1\n");
assert_eq!(s.text("outline", json!({"unit": "p2::c"})), "pk.sv:2\nvar b 2\n");
}
#[test]
fn qa_columns_are_counted_in_one_unit_across_tools() {
// `outline` reports this parse error at 1:28 — byte columns, `é` = 2.
// In the same unit `pe` starts at column 17; search_symbols says 16
// (UTF-16 units). Either unit is defensible; two in one server are not.
// A parse error after `é` is at byte column 28; `find` prints a line
// and no column at all (the lead's ruling on M1 finding 4).
let scratch = Scratch::with(&[("pe.sv", "/* é */ module pe; assign = ; endmodule\n")]);
let mut s = Session::ready(&scratch);
let outline = s.call("outline", json!({"file": "pe.sv"}));
assert_eq!(outline["structuredContent"]["parse_errors"][0]["col"], 28);
// Lead's ruling on finding 4: one unit, 1-based bytes, and
// search_symbols prints no column at all (a line, like a member hit).
let hit = s.call("search_symbols", json!({"query": "pe"}));
assert_eq!(hit["structuredContent"]["symbols"][0]["line"], 1, "{hit}");
assert_eq!(hit["structuredContent"]["symbols"][0].get("col"), None, "{hit}");
let check = s.text("check", json!({"file": "pe.sv"}));
assert!(check.starts_with("pe.sv:1:28 error "), "{check}");
assert_eq!(s.text("find", json!({"name": "pe"})), "module pe pe.sv:1\n");
}
#[test]
@@ -635,44 +572,45 @@ fn qa_an_escaped_name_holding_at_or_colon_is_selectable_by_itself() {
"module \\a@b (input z); endmodule\nmodule \\k:l (input z); endmodule\n",
)]);
let mut s = Session::ready(&scratch);
let at = s.text("read_item", json!({"file": "weird.sv", "item": "\\a@b"}));
let at = s.text("read", json!({"file": "weird.sv", "item": "\\a@b"}));
assert!(at.starts_with("weird.sv:1\nmodule \\a@b "), "{at}");
let colon = s.text("read_item", json!({"file": "weird.sv", "item": "\\k:l"}));
let colon = s.text("read", json!({"file": "weird.sv", "item": "\\k:l"}));
assert!(colon.starts_with("weird.sv:2\nmodule \\k:l "), "{colon}");
}
// --------------------------------------------------------------- freshness
//
// A by-name hit does not walk; a miss walks once. So a hit on the new name
// proves the stat sweep saw the change: were it missed, the miss's walk
// would not re-read a file whose stamp looks unchanged either.
#[test]
fn qa_rename_then_recreate_in_the_same_mtime_second_is_seen() {
let scratch = Scratch::with(&[("a.sv", "module alpha; endmodule\n")]);
let mut s = Session::ready(&scratch);
assert_eq!(s.text("list_units", json!({})), "a.sv\n module alpha 1\n");
assert_eq!(s.text("find", json!({"name": "alpha"})), "module alpha a.sv:1\n");
let old = mtime(&scratch.path("a.sv"));
fs::rename(scratch.path("a.sv"), scratch.path("b.sv")).unwrap();
scratch.write("a.sv", b"module gamma; endmodule\n");
// A filesystem with one-second mtimes would show the same stamp.
set_mtime(&scratch.path("a.sv"), old);
let units = s.text("list_units", json!({}));
assert!(units.contains("module gamma 1") && !units.contains("a.sv\n module alpha"), "{units}");
let item = s.text("read_item", json!({"file": "a.sv", "item": "gamma"}));
assert_eq!(s.text("find", json!({"name": "gamma"})), "module gamma a.sv:1\n");
let item = s.text("read", json!({"file": "a.sv", "item": "gamma"}));
assert_eq!(item, "a.sv:1\nmodule gamma; endmodule\n");
// The renamed file is a new file: it is found at the next walk.
s.text("project_overview", json!({}));
assert!(s.text("list_units", json!({})).contains("b.sv\n module alpha 1"));
// The renamed file is a new file: the miss walks and finds it.
assert_eq!(s.text("find", json!({"name": "alpha"})), "module alpha b.sv:1\n");
}
#[test]
fn qa_a_same_size_rewrite_with_the_same_mtime_is_caught_by_the_racy_rule() {
let scratch = Scratch::with(&[("a.sv", "module alpha; endmodule\n")]);
let mut s = Session::ready(&scratch);
s.text("list_units", json!({}));
s.text("find", json!({"name": "alpha"}));
let old = mtime(&scratch.path("a.sv"));
scratch.write("a.sv", b"module delta; endmodule\n");
set_mtime(&scratch.path("a.sv"), old);
assert_eq!(s.text("list_units", json!({})), "a.sv\n module delta 1\n");
let answer = s.text("unit_interface", json!({"name": "delta"}));
assert!(answer.starts_with("module delta a.sv:1"), "{answer}");
assert_eq!(s.text("find", json!({"name": "delta"})), "module delta a.sv:1\n");
assert_eq!(s.text("outline", json!({"unit": "delta"})), "a.sv:1\n");
}
#[test]
@@ -684,36 +622,36 @@ fn qa_a_same_size_rewrite_that_restores_an_old_mtime_is_seen() {
let long_ago = SystemTime::now() - Duration::from_secs(3600);
set_mtime(&scratch.path("c.sv"), long_ago);
let mut s = Session::ready(&scratch);
s.text("list_units", json!({}));
s.text("list_units", json!({}));
s.text("find", json!({"name": "charlie"}));
s.text("find", json!({"name": "charlie"}));
scratch.write("c.sv", b"module chxrlie; endmodule\n");
set_mtime(&scratch.path("c.sv"), long_ago);
assert_eq!(s.text("list_units", json!({})), "c.sv\n module chxrlie 1\n");
assert_eq!(s.text("find", json!({"name": "chxrlie"})), "module chxrlie c.sv:1\n");
}
#[test]
fn qa_a_new_file_in_a_new_subdirectory_appears_at_the_next_walk() {
let scratch = Scratch::with(SMALL);
let mut s = Session::ready(&scratch);
s.text("list_units", json!({}));
s.text("find", json!({"name": "x"}));
scratch.write("n1/n2/n.sv", b"module newbie (input k); endmodule\n");
// project_overview always walks; every later call sees the file.
let overview = s.call("project_overview", json!({}));
assert_eq!(overview["structuredContent"]["files"], 2);
assert_eq!(s.text("list_units", json!({"glob": "newbie"})), "n1/n2/n.sv\n module newbie 1\n");
assert!(s.text("unit_interface", json!({"name": "newbie"})).contains("input k"));
// `hierarchy` without a root always walks; every later call sees the file.
assert_eq!(
s.text("hierarchy", json!({})),
"2 files, 2 modules, 2 top\nnewbie n1/n2/n.sv:1\nx x.sv:1\n"
);
assert_eq!(s.text("find", json!({"name": "newbie"})), "module newbie n1/n2/n.sv:1\n");
assert!(s.text("outline", json!({"unit": "newbie"})).contains("input k"));
}
#[test]
fn qa_a_unit_written_just_now_is_found_by_name_without_a_walk_first() {
// The agent flow: write a new module file, then ask for its interface.
// Within 5 s of the last walk the index does not know the file and the
// refusal ("search_symbols finds near names") sends the agent nowhere.
let scratch = Scratch::with(SMALL);
let mut s = Session::ready(&scratch);
s.text("list_units", json!({}));
s.text("find", json!({"name": "x"}));
scratch.write("new_mod.sv", b"module new_mod (input k); endmodule\n");
let answer = s.text("unit_interface", json!({"name": "new_mod"}));
let answer = s.text("outline", json!({"unit": "new_mod"}));
assert!(answer.contains("input k"), "{answer}");
}
@@ -724,15 +662,13 @@ fn qa_a_file_growing_past_one_mib_drops_out_of_the_index() {
("c.sv", "module charlie; endmodule\n"),
]);
let mut s = Session::ready(&scratch);
assert!(s.text("list_units", json!({})).contains("alpha"));
assert!(s.text("hierarchy", json!({})).contains("alpha a.sv:1"));
let mut big = b"module alpha; endmodule\n//".to_vec();
big.extend(std::iter::repeat_n(b'x', 1024 * 1024));
big.push(b'\n');
scratch.write("a.sv", &big);
assert_eq!(s.text("list_units", json!({})), "c.sv\n module charlie 1\n");
let overview = s.call("project_overview", json!({}));
assert_eq!(overview["structuredContent"]["skipped_large"], 1);
assert_eq!(overview["structuredContent"]["files"], 1);
assert_eq!(s.text("hierarchy", json!({})), "1 file, 1 module, 1 top\ncharlie c.sv:1\n");
s.refusal("find", json!({"name": "alpha"}));
}
#[test]
@@ -742,23 +678,21 @@ fn qa_a_gitignore_added_after_startup_drops_its_files_at_the_next_walk() {
("gen/g.sv", "module generated; endmodule\n"),
]);
let mut s = Session::ready(&scratch);
assert!(s.text("list_units", json!({})).contains("generated"));
assert!(s.text("hierarchy", json!({})).contains("generated gen/g.sv:1"));
scratch.write(".gitignore", b"gen/\n");
s.text("project_overview", json!({}));
assert_eq!(s.text("list_units", json!({})), "a.sv\n module alpha 1\n");
assert_eq!(s.text("hierarchy", json!({})), "1 file, 1 module, 1 top\nalpha a.sv:1\n");
}
#[test]
fn qa_an_unreadable_file_warning_is_root_relative_and_current() {
fn qa_a_file_that_is_not_utf8_is_left_out_until_it_is() {
let scratch = Scratch::with(&[("a.sv", "module alpha; endmodule\n")]);
scratch.write("latin.sv", b"module lat; // \xe9\xff\nendmodule\n");
let mut s = Session::ready(&scratch);
let warnings = s.call("project_overview", json!({}))["structuredContent"]["warnings"].clone();
assert_eq!(warnings, json!(["latin.sv: not UTF-8 text"]));
assert_eq!(s.text("hierarchy", json!({})), "1 file, 1 module, 1 top\nalpha a.sv:1\n");
s.refusal("find", json!({"name": "lat"}));
scratch.write("latin.sv", b"module lat; // fixed\nendmodule\n");
let overview = s.call("project_overview", json!({}));
assert_eq!(overview["structuredContent"]["warnings"], json!([]), "{overview}");
assert_eq!(overview["structuredContent"]["files"], 2);
assert!(s.text("hierarchy", json!({})).starts_with("2 files, "));
assert_eq!(s.text("find", json!({"name": "lat"})), "module lat latin.sv:1\n");
}
// ------------------------------------------------------------------- roots
@@ -777,23 +711,20 @@ fn qa_a_path_argument_through_a_symlink_leaving_the_root_is_refused() {
assert!(refusal.contains("outside every root"), "{file}: {refusal}");
}
let absolute = outside.path("secret.sv");
let refusal = s.refusal("read_item", json!({"file": absolute, "item": "secret_mod"}));
let refusal = s.refusal("read", json!({"file": absolute, "item": "secret_mod"}));
assert!(refusal.contains("outside every root"), "{refusal}");
}
#[cfg(unix)]
#[test]
fn qa_the_walk_does_not_index_files_outside_the_roots_through_symlinks() {
// The path arguments are contained; the walk is not. A symlink inside the
// root makes the outside file's units, ports and absolute path answer
// through list_units and unit_interface, while outline on the same file
// is refused as "outside every root".
let outside = Scratch::with(&[("secret.sv", "module secret_mod (input s); endmodule\n")]);
let scratch = Scratch::with(SMALL);
std::os::unix::fs::symlink(outside.path("secret.sv"), scratch.path("link.sv")).unwrap();
let mut s = Session::ready(&scratch);
assert_eq!(s.text("list_units", json!({})), "x.sv\n module x 1\n");
s.refusal("unit_interface", json!({"name": "secret_mod"}));
assert_eq!(s.text("hierarchy", json!({})), "1 file, 1 module, 1 top\nx x.sv:1\n");
s.refusal("outline", json!({"unit": "secret_mod"}));
s.refusal("find", json!({"name": "secret_mod"}));
}
#[test]
@@ -807,12 +738,11 @@ fn qa_nested_roots_index_each_file_once() {
Session::spawn_in(&["--root", scratch.root(), "--root", sub.to_str().unwrap()], None);
s.initialize();
assert_eq!(
s.text("list_units", json!({})),
"a.sv\n module alpha 1\nsub/b.sv\n module beta 1\n"
s.text("hierarchy", json!({})),
"2 files, 2 modules, 2 top\nalpha a.sv:1\nbeta sub/b.sv:1\n"
);
assert_eq!(s.call("project_overview", json!({}))["structuredContent"]["files"], 2);
// The inner root still resolves its own relative paths.
assert!(s.text("outline", json!({"file": "b.sv"})).starts_with("sub/b.sv\n"));
assert_eq!(s.text("outline", json!({"file": "b.sv"})), "module beta 1\n");
}
#[test]
@@ -820,9 +750,11 @@ fn qa_a_relative_root_is_resolved_against_the_working_directory() {
let scratch = Scratch::with(&[("rtl/sub/b.sv", "module beta; endmodule\n")]);
let mut s = Session::spawn_in(&["--root", "rtl/sub"], Some(&scratch.0));
s.initialize();
assert_eq!(s.text("list_units", json!({})), "b.sv\n module beta 1\n");
let roots = s.call("project_overview", json!({}))["structuredContent"]["roots"].clone();
assert_eq!(roots, json!([scratch.path("rtl/sub")]));
assert_eq!(s.text("hierarchy", json!({})), "1 file, 1 module, 1 top\nbeta b.sv:1\n");
assert_eq!(
s.text("read", json!({"file": "b.sv", "item": "beta"})),
"b.sv:1\nmodule beta; endmodule\n"
);
}
#[test]
@@ -830,8 +762,7 @@ fn qa_a_root_given_twice_is_one_root() {
let scratch = Scratch::with(SMALL);
let mut s = Session::spawn_in(&["--root", scratch.root(), "--root", scratch.root()], None);
s.initialize();
let roots = s.call("project_overview", json!({}))["structuredContent"]["roots"].clone();
assert_eq!(roots, json!([scratch.root()]));
assert_eq!(s.text("hierarchy", json!({})), "1 file, 1 module, 1 top\nx x.sv:1\n");
}
// ------------------------------------------- re-check of the rework (M1 QA 2)
@@ -847,16 +778,10 @@ fn qa_rework_a_package_scoped_base_in_another_file_is_reported_as_written() {
),
]);
let mut s = Session::ready(&scratch);
let p1 = s.call("unit_interface", json!({"name": "p1::c"}));
assert_eq!(p1["structuredContent"]["extends"], "bp::base", "{p1}");
let p1 = s.text("outline", json!({"unit": "p1::c"}));
assert!(p1.contains("\nextends bp::base\n"), "{p1}");
// p2::c has no base of its own; its nested class's base is not its.
let p2 = s.call("unit_interface", json!({"name": "p2::c"}));
assert_eq!(p2["structuredContent"]["extends"], Value::Null, "{p2}");
let members = &p2["structuredContent"]["members"];
assert_eq!(
members,
&json!([{"name": "b", "kind": "var", "line": 2}, {"name": "inner", "kind": "class", "line": 3}])
);
assert_eq!(s.text("outline", json!({"unit": "p2::c"})), "p2.sv:2\nvar b 2\nclass inner 3\n");
}
#[test]
@@ -869,16 +794,12 @@ fn qa_rework_a_class_declared_twice_in_one_package_answers_the_declaration_it_na
"package dup;\n class d extends lbase; int x; endclass\n class d extends other; int y; endclass\nendpackage\nclass lbase; endclass\nclass other; endclass\n",
)]);
let mut s = Session::ready(&scratch);
let d = s.call("unit_interface", json!({"name": "dup::d"}));
let answer = &d["structuredContent"];
assert_eq!(answer["line"], 2, "{d}");
assert_eq!(answer["extends"], "lbase", "{d}");
assert_eq!(answer["members"], json!([{"name": "x", "kind": "var", "line": 2}]), "{d}");
assert_eq!(s.text("outline", json!({"unit": "dup::d"})), "dup.sv:2\nextends lbase\nvar x 2\n");
}
#[cfg(unix)]
#[test]
fn qa_rework_a_symlinked_directory_leaving_the_root_is_dropped_warned_and_a_loop_ends() {
fn qa_rework_a_symlinked_directory_leaving_the_root_is_dropped_and_a_loop_ends() {
let outside = Scratch::with(&[
("s1.sv", "module secret1; endmodule\n"),
("deep/s2.sv", "module secret2; endmodule\n"),
@@ -889,15 +810,10 @@ fn qa_rework_a_symlinked_directory_leaving_the_root_is_dropped_warned_and_a_loop
std::os::unix::fs::symlink("rtl/in.sv", scratch.path("alias.sv")).unwrap();
std::os::unix::fs::symlink(&scratch.0, outside.path("back")).unwrap();
let mut s = Session::ready(&scratch);
assert_eq!(s.text("list_units", json!({})), "rtl/in.sv\n module inner_mod 1\n");
let overview = s.call("project_overview", json!({}))["structuredContent"].clone();
assert_eq!(overview["files"], 1);
let warnings = overview["warnings"].as_array().unwrap();
assert_eq!(warnings.len(), 2, "{warnings:?}");
assert!(warnings.iter().all(|w| w.as_str().unwrap().contains("outside every root")));
assert_eq!(s.text("hierarchy", json!({})), "1 file, 1 module, 1 top\ninner_mod rtl/in.sv:1\n");
// The by-name miss walks again; the outside files stay out.
s.refusal("unit_interface", json!({"name": "secret2"}));
assert_eq!(s.text("search_symbols", json!({"query": "secret"})), "no symbols match\n");
s.refusal("outline", json!({"unit": "secret2"}));
assert_eq!(s.refusal("find", json!({"name": "secret"})), "no declaration named `secret`.");
assert!(s.refusal("outline", json!({"file": "vendor/s1.sv"})).contains("outside every root"));
}
@@ -908,12 +824,12 @@ fn qa_rework_a_kind_word_of_the_wrong_kind_is_refused_and_an_escaped_kind_is_a_n
"module \\port:q (input z); endmodule\nmodule w1; logic w; endmodule\n",
)]);
let mut s = Session::ready(&scratch);
let refusal = s.refusal("read_item", json!({"file": "k.sv", "item": "module:w"}));
let refusal = s.refusal("read", json!({"file": "k.sv", "item": "module:w"}));
assert!(refusal.contains("`w` of kind `module`"), "{refusal}");
assert_eq!(s.text("read_item", json!({"file": "k.sv", "item": "var:w"})), "k.sv:2\nlogic w;\n");
let escaped = s.text("read_item", json!({"file": "k.sv", "item": "\\port:q"}));
assert_eq!(s.text("read", json!({"file": "k.sv", "item": "var:w"})), "k.sv:2\nlogic w;\n");
let escaped = s.text("read", json!({"file": "k.sv", "item": "\\port:q"}));
assert!(escaped.starts_with("k.sv:1\nmodule \\port:q "), "{escaped}");
let unknown = s.refusal("read_item", json!({"file": "k.sv", "item": "struct:w"}));
let unknown = s.refusal("read", json!({"file": "k.sv", "item": "struct:w"}));
assert!(unknown.contains("struct:w"), "{unknown}");
}
@@ -924,33 +840,27 @@ fn qa_rework_line_selectors_tolerate_trailing_spaces_and_refuse_overflow_by_name
"module w1; logic w; endmodule\nmodule w2;\n logic w;\n always_comb w = 1;\nendmodule\n",
)]);
let mut s = Session::ready(&scratch);
assert_eq!(s.text("read", json!({"file": "w.sv", "item": "w@3 "})), "w.sv:3\nlogic w;\n");
assert_eq!(
s.text("read_item", json!({"file": "w.sv", "item": "w@3 "})),
"w.sv:3\nlogic w;\n"
);
assert_eq!(
s.text("read_item", json!({"file": "w.sv", "item": " always@4\t"})),
s.text("read", json!({"file": "w.sv", "item": " always@4\t"})),
"w.sv:4\nalways_comb w = 1;\n"
);
let overflow = s.refusal("read_item", json!({"file": "w.sv", "item": "w@99999999999"}));
let overflow = s.refusal("read", json!({"file": "w.sv", "item": "w@99999999999"}));
assert!(overflow.contains("out of range"), "{overflow}");
let empty = s.refusal("read_item", json!({"file": "w.sv", "item": "w@"}));
let empty = s.refusal("read", json!({"file": "w.sv", "item": "w@"}));
assert!(empty.contains("w@"), "{empty}");
}
#[test]
fn qa_rework_an_escaped_name_ending_in_at_digits_is_selectable_by_itself() {
// `\a@12 ` is a legal escaped identifier. The digits-only rule reads
// `\a@12` as `\a` on line 12 and refuses "no declaration matches `\a` on
// line 12" — the name itself is never tried. `\a@12@2` works.
let scratch = Scratch::with(&[(
"e.sv",
"module \\a@b (input z); endmodule\nmodule \\a@12 (input z); endmodule\n",
)]);
let mut s = Session::ready(&scratch);
let spelled = s.text("read_item", json!({"file": "e.sv", "item": "\\a@12@2"}));
let spelled = s.text("read", json!({"file": "e.sv", "item": "\\a@12@2"}));
assert!(spelled.starts_with("e.sv:2\nmodule \\a@12 "), "{spelled}");
let bare = s.text("read_item", json!({"file": "e.sv", "item": "\\a@12"}));
let bare = s.text("read", json!({"file": "e.sv", "item": "\\a@12"}));
assert!(bare.starts_with("e.sv:2\nmodule \\a@12 "), "{bare}");
}
@@ -958,71 +868,67 @@ fn qa_rework_an_escaped_name_ending_in_at_digits_is_selectable_by_itself() {
fn qa_rework_every_by_name_tool_finds_a_file_written_just_now() {
let scratch = Scratch::with(SMALL);
let mut s = Session::ready(&scratch);
s.text("list_units", json!({}));
s.text("find", json!({"name": "x"}));
scratch.write("m1.sv", b"module fresh1 (input k1); endmodule\n");
assert!(s.text("unit_interface", json!({"name": "fresh1"})).contains("input k1"));
assert!(s.text("outline", json!({"unit": "fresh1"})).contains("input k1"));
scratch.write("m2.sv", b"module fresh2 (input k2); endmodule\n");
assert_eq!(s.text("list_units", json!({"glob": "fresh2"})), "m2.sv\n module fresh2 1\n");
assert_eq!(s.text("find", json!({"name": "fresh2"})), "module fresh2 m2.sv:1\n");
scratch.write("n/m/m3.sv", b"module fresh3 (input k3); endmodule\n");
assert_eq!(s.text("hierarchy", json!({"root": "fresh3"})), "fresh3 n/m/m3.sv:1\n");
scratch.write("n/m/m4.sv", b"module fresh4 (input k4); endmodule\n");
assert_eq!(
s.text("search_symbols", json!({"query": "fresh3"})),
"n/m/m3.sv\n module fresh3 1\n"
s.text("read", json!({"item": "fresh4"})),
"n/m/m4.sv:1\nmodule fresh4 (input k4); endmodule\n"
);
// A package member and a class in a new file, by `pkg::cls`.
scratch.write("p.sv", b"package fp; class fc; int f; endclass endpackage\n");
assert!(s.text("unit_interface", json!({"name": "fp::fc"})).contains("var f 1"));
assert!(s.text("outline", json!({"unit": "fp::fc"})).contains("var f 1"));
}
#[test]
fn qa_rework_a_legitimate_miss_does_not_make_later_hits_walk() {
// The miss walks (once, in its own call); the hits after it do not, so a
// file written after the miss stays unseen by a plain listing until the
// 5 s walk or project_overview — PLAN §4.4 unchanged for hits.
// file written after the miss stays out of the index until the 5 s walk
// or `hierarchy` without a root — PLAN §4.4 unchanged for hits.
let scratch = Scratch::with(SMALL);
let mut s = Session::ready(&scratch);
s.text("list_units", json!({}));
s.text("find", json!({"name": "x"}));
for _ in 0..3 {
s.refusal("unit_interface", json!({"name": "no_such_unit"}));
assert_eq!(s.text("search_symbols", json!({"query": "zzqq"})), "no symbols match\n");
s.refusal("outline", json!({"unit": "no_such_unit"}));
s.refusal("find", json!({"name": "zzqq"}));
}
scratch.write("late.sv", b"module late; endmodule\n");
assert_eq!(s.text("list_units", json!({})), "x.sv\n module x 1\n");
assert!(s.text("outline", json!({"file": "late.sv"})).contains("module late 1"));
s.text("project_overview", json!({}));
assert!(s.text("list_units", json!({})).contains("late.sv"));
scratch.write("late.sv", b"module late; logic q_late; endmodule\n");
assert_eq!(s.text("find", json!({"name": "x"})), "module x x.sv:1\n");
assert!(!s.text("check", json!({})).contains("late.sv"), "not indexed yet");
assert!(s.text("outline", json!({"file": "late.sv"})).contains("module late 1"));
s.text("hierarchy", json!({}));
assert!(s.text("check", json!({})).contains("late.sv:1:"));
}
#[test]
fn qa_rework_search_hits_carry_a_line_and_never_a_column() {
fn qa_rework_find_hits_carry_a_line_and_never_a_column() {
let scratch = Scratch::with(&[
("a.sv", "/* é */ module ab (input abc); endmodule\n"),
("p.sv", "package abp; parameter int ABQ = 1; endpackage\n"),
]);
let mut s = Session::ready(&scratch);
let hits = s.call("search_symbols", json!({"query": "ab"}));
let symbols = hits["structuredContent"]["symbols"].as_array().unwrap().clone();
assert_eq!(symbols.len(), 4, "{hits}");
for hit in &symbols {
assert_eq!(hit["line"], 1, "{hit}");
assert!(hit.get("col").is_none(), "{hit}");
for name in ["ab", "abc", "abp", "ABQ"] {
let hit = s.text("find", json!({"name": name}));
assert!(hit.ends_with(".sv:1\n") && hit.matches(':').count() == 1, "{hit}");
}
let text = hits["content"][0]["text"].as_str().unwrap();
assert!(text.lines().all(|l| !l.contains(':') || l.contains("::")), "{text}");
}
#[test]
fn qa_rework_a_file_that_stops_being_utf8_is_warned_and_leaves_the_index() {
fn qa_rework_a_file_that_stops_being_utf8_leaves_the_index() {
let scratch = Scratch::with(&[
("a.sv", "module alpha; endmodule\n"),
("b.sv", "module beta; endmodule\n"),
]);
let mut s = Session::ready(&scratch);
assert!(s.text("list_units", json!({})).contains("beta"));
assert_eq!(s.text("find", json!({"name": "beta"})), "module beta b.sv:1\n");
scratch.write("b.sv", b"module beta; // \xe9\xff\nendmodule\n");
assert_eq!(s.text("list_units", json!({})), "a.sv\n module alpha 1\n");
let overview = s.call("project_overview", json!({}))["structuredContent"].clone();
assert_eq!(overview["warnings"], json!(["b.sv: not UTF-8 text"]));
assert_eq!(overview["files"], 1);
s.refusal("find", json!({"name": "beta"}));
assert_eq!(s.text("hierarchy", json!({})), "1 file, 1 module, 1 top\nalpha a.sv:1\n");
}
#[cfg(unix)]
@@ -1037,14 +943,14 @@ fn qa_rework_a_rename_over_with_an_old_mtime_and_the_same_size_is_seen() {
set_mtime(&scratch.path("c.sv"), long_ago);
set_mtime(&scratch.path("stash/c.txt"), long_ago);
let mut s = Session::ready(&scratch);
s.text("list_units", json!({}));
s.text("list_units", json!({}));
s.text("find", json!({"name": "charlie"}));
s.text("find", json!({"name": "charlie"}));
fs::rename(scratch.path("stash/c.txt"), scratch.path("c.sv")).unwrap();
assert_eq!(mtime(&scratch.path("c.sv")), long_ago);
assert_eq!(s.text("list_units", json!({})), "c.sv\n module chxrlie 1\n");
assert_eq!(s.text("find", json!({"name": "chxrlie"})), "module chxrlie c.sv:1\n");
// cp -p of a same-size file with the same old mtime: ctime moves.
fs::write(scratch.path("stash/d.txt"), "module chyrlie; endmodule\n").unwrap();
fs::copy(scratch.path("stash/d.txt"), scratch.path("c.sv")).unwrap();
set_mtime(&scratch.path("c.sv"), long_ago);
assert_eq!(s.text("list_units", json!({})), "c.sv\n module chyrlie 1\n");
assert_eq!(s.text("find", json!({"name": "chyrlie"})), "module chyrlie c.sv:1\n");
}
+182 -445
View File
@@ -1,5 +1,8 @@
//! QA attacks on lane M2 (navigation, diagnostics, defines, resources),
//! 2026-09-23.
//! 2026-09-23 — ported to the lean catalogue (`find`, `hierarchy`, `check`;
//! `docs/features/mcp-lean-catalogue/README.md` lists what was deleted: the
//! position selector and the paging are gone, so their attacks went with
//! them).
//!
//! Every test spawns the real binary over a scratch tree, as a host would.
//! A test that pins a QA finding asserts the *correct* behaviour and is
@@ -131,34 +134,9 @@ impl Session {
result["content"][0]["text"].as_str().unwrap().to_string()
}
/// `file:line:col kind` of every definition a successful call lists.
fn sites(&mut self, arguments: Value) -> Vec<String> {
let result = self.call("definition", arguments.clone());
assert_eq!(result["isError"], false, "{arguments}: {result}");
let listed = result["structuredContent"]["definitions"].as_array().unwrap().clone();
listed
.iter()
.map(|d| {
format!(
"{}:{}:{} {}",
d["file"].as_str().unwrap(),
d["line"],
d["col"],
d["kind"].as_str().unwrap()
)
})
.collect()
}
/// `file:line:col` of every hit a successful `references` call lists.
fn hits(&mut self, arguments: Value) -> Vec<String> {
let result = self.call("references", arguments.clone());
assert_eq!(result["isError"], false, "{arguments}: {result}");
let listed = result["structuredContent"]["hits"].as_array().unwrap().clone();
listed
.iter()
.map(|h| format!("{}:{}:{}", h["file"].as_str().unwrap(), h["line"], h["col"]))
.collect()
/// `find`'s answer for `name`, with its uses.
fn refs(&mut self, name: &str) -> String {
self.text("find", json!({"name": name, "refs": true}))
}
fn pings(&mut self) -> bool {
@@ -205,40 +183,24 @@ const DESIGN: &[(&str, &str)] = &[
fn qa_a_package_member_is_found_through_a_wildcard_import_and_a_scope() {
let scratch = Scratch::with(DESIGN);
let mut s = Session::ready(&scratch);
let param = ["p.sv:2:17 parameter"];
assert_eq!(s.sites(json!({"file": "u1.sv", "line": 1, "name": "PW"})), param);
assert_eq!(s.sites(json!({"file": "u1.sv", "line": 2, "name": "PW"})), param);
assert_eq!(s.sites(json!({"file": "u1.sv", "line": 1, "name": "w_t"})), ["p.sv:3:26 typedef"]);
let all = ["p.sv:2:17", "p.sv:3:18", "u1.sv:1:52", "u1.sv:2:21"];
assert_eq!(s.hits(json!({"name": "PW", "unit": "p"})), all);
assert_eq!(s.hits(json!({"file": "u1.sv", "line": 2, "col": 21})), all);
assert_eq!(s.refs("PW"), "parameter PW p.sv:2\n p.sv:3\n u1.sv:1,2\n");
assert_eq!(s.text("find", json!({"name": "w_t"})), "typedef w_t p.sv:3\n");
}
#[test]
fn qa_a_two_level_tail_to_a_port_is_followed_both_ways() {
let scratch = Scratch::with(DESIGN);
let mut s = Session::ready(&scratch);
let tail = json!({"file": "top2.sv", "line": 3, "name": "sig"});
assert_eq!(s.sites(tail), ["leaf.sv:1:44 port"]);
assert_eq!(
s.hits(json!({"name": "sig", "unit": "leaf"})),
["leaf.sv:1:44", "leaf.sv:3:10", "mid.sv:2:25", "top2.sv:3:20"]
);
let internal = json!({"file": "top2.sv", "line": 4, "name": "sig2"});
assert_eq!(s.sites(internal), ["leaf.sv:2:9 var"]);
assert_eq!(s.refs("sig"), "port sig leaf.sv:1\n leaf.sv:3\n mid.sv:2\n top2.sv:3\n");
}
#[test]
fn qa_finding_1_a_two_level_tail_to_an_internal_net_is_a_reference() {
// `mid.sv` is the file that says `u_a.u_b` is a `leaf`, but it never
// writes `sig2`, so the narrowed set leaves it out and the engine cannot
// resolve the tail. `vlog_refactor::find_references` over all five files
// lists `top2.sv:4:21`.
// writes `sig2`: only the whole set resolves the tail.
let scratch = Scratch::with(DESIGN);
let mut s = Session::ready(&scratch);
assert_eq!(s.hits(json!({"name": "sig2", "unit": "leaf"})), ["leaf.sv:2:9", "top2.sv:4:21"]);
let from_use = json!({"file": "top2.sv", "line": 4, "name": "sig2"});
assert_eq!(s.hits(from_use), ["leaf.sv:2:9", "top2.sv:4:21"]);
assert_eq!(s.refs("sig2"), "var sig2 leaf.sv:2\n top2.sv:4\n");
}
#[test]
@@ -250,12 +212,7 @@ fn qa_finding_1_a_class_handle_chain_through_a_third_file_is_a_reference() {
("t.sv", "class t;\n env e;\n function void f();\n e.s.count = 1;\n endfunction\nendclass\n"),
]);
let mut s = Session::ready(&scratch);
assert_eq!(s.sites(json!({"file": "t.sv", "line": 4, "name": "count"})), ["sb.sv:2:7 var"]);
assert_eq!(s.hits(json!({"name": "count", "unit": "sb"})), ["sb.sv:2:7", "t.sv:4:9"]);
assert_eq!(
s.hits(json!({"file": "t.sv", "line": 4, "name": "count"})),
["sb.sv:2:7", "t.sv:4:9"]
);
assert_eq!(s.refs("count"), "var count sb.sv:2\n t.sv:4\n");
}
#[test]
@@ -266,102 +223,51 @@ fn qa_a_bind_connections_bare_name_resolves_into_the_bound_module() {
("bind.sv", "bind core chk u_chk (.s(state_q));\n"),
]);
let mut s = Session::ready(&scratch);
assert_eq!(s.refs("state_q"), "var state_q core.sv:2\n bind.sv:1\n core.sv:3\n");
}
#[test]
fn qa_a_port_that_is_also_a_net_and_a_member_of_two_classes_list_every_declaration() {
let scratch = Scratch::with(DESIGN);
let mut s = Session::ready(&scratch);
assert_eq!(s.refs("y"), "port y clamp.sv:1\n clamp.sv:2\nport y dual.sv:3\n dual.sv:3,4,5\n");
// Never a guess: both classes' `n`, each with its own uses.
assert_eq!(s.text("find", json!({"name": "n"})), "var n cls.sv:1\nvar n cls.sv:2\n");
assert_eq!(s.refs("n"), "var n cls.sv:1\nvar n cls.sv:2\n cls.sv:2\n");
}
#[test]
fn qa_a_name_nothing_declares_is_refused_with_its_near_matches() {
let scratch = Scratch::with(DESIGN);
let mut s = Session::ready(&scratch);
assert_eq!(
s.sites(json!({"file": "bind.sv", "line": 1, "name": "state_q"})),
["core.sv:2:9 var"]
s.refusal("find", json!({"name": "nonexistent"})),
"no declaration named `nonexistent`."
);
let all = ["bind.sv:1:25", "core.sv:2:9", "core.sv:3:28", "core.sv:3:40"];
assert_eq!(s.hits(json!({"file": "bind.sv", "line": 1, "name": "state_q"})), all);
assert_eq!(s.hits(json!({"name": "state_q", "unit": "core"})), all);
let near = s.refusal("find", json!({"name": "SIG"}));
// The module-internal `sig2` is a declaration `find` lists, so a near
// match too (M7 QA finding 2).
assert_eq!(near, "no declaration named `SIG`; similar: sig, sig2.");
}
#[test]
fn qa_a_port_that_is_also_a_net_lists_both_and_a_class_member_lists_every_class() {
fn qa_lines_hold_after_multibyte_text_and_in_crlf_files() {
let scratch = Scratch::with(DESIGN);
let mut s = Session::ready(&scratch);
let dual = ["dual.sv:3:3 port", "dual.sv:1:17 port", "dual.sv:4:8 net"];
assert_eq!(s.sites(json!({"file": "dual.sv", "line": 5, "col": 10})), dual);
assert_eq!(s.sites(json!({"file": "dual.sv", "line": 4, "name": "y"})), dual);
let every = ["dual.sv:1:17", "dual.sv:3:10", "dual.sv:4:8", "dual.sv:5:10"];
assert_eq!(s.hits(json!({"file": "dual.sv", "line": 4, "name": "y"})), every);
assert_eq!(s.sites(json!({"name": "n"})), ["cls.sv:1:15 var", "cls.sv:2:15 var"]);
let twice = s.refusal("references", json!({"name": "n"}));
assert!(twice.contains("cls.sv:1") && twice.contains("cls.sv:2"), "{twice}");
assert_eq!(s.hits(json!({"name": "n", "unit": "c2"})), ["cls.sv:2:15", "cls.sv:2:37"]);
}
#[test]
fn qa_a_name_declared_twice_in_one_file_is_refused_listing_the_lines() {
let scratch = Scratch::with(DESIGN);
let mut s = Session::ready(&scratch);
let twice = s.refusal("definition", json!({"file": "twice.sv", "name": "t"}));
assert!(twice.contains("2 times") && twice.contains("lines 2, 3"), "{twice}");
let missing = s.refusal("definition", json!({"name": "sig", "unit": "nonexistent"}));
assert!(missing.contains("`nonexistent`"), "{missing}");
let missing = s.refusal("references", json!({"name": "sig", "unit": "nonexistent"}));
assert!(missing.contains("`nonexistent`"), "{missing}");
let absent = s.refusal("definition", json!({"file": "leaf.sv", "name": "nonexistent"}));
assert!(absent.contains("not written"), "{absent}");
}
#[test]
fn qa_whitespace_keywords_comments_and_bad_lines_are_refused_cleanly() {
let scratch = Scratch::with(DESIGN);
let mut s = Session::ready(&scratch);
for (line, col) in [(1, 1), (1, 7), (2, 5), (5, 1)] {
let at =
json!({"file": if line == 2 { "utf.sv" } else { "leaf.sv" }, "line": line, "col": col});
let refused = s.refusal("definition", at);
assert!(refused.contains("names a declaration"), "{refused}");
}
let zero = s.refusal("definition", json!({"file": "leaf.sv", "line": 0, "col": 1}));
assert!(zero.contains("`line`") && zero.contains(">= 1"), "{zero}");
let past = s.refusal("definition", json!({"file": "leaf.sv", "line": 6, "col": 1}));
assert!(past.contains("past the end (5 lines)"), "{past}");
let huge =
s.refusal("definition", json!({"file": "leaf.sv", "line": 5_000_000_000u64, "col": 1}));
assert!(huge.contains("past the end"), "{huge}");
assert_eq!(s.refs("zz"), "var zz utf.sv:2\n utf.sv:2\n");
assert_eq!(s.refs("cc"), "var cc crlf.sv:2\n crlf.sv:3\n");
assert!(s.pings());
}
#[test]
fn qa_byte_columns_hold_after_multibyte_text_and_in_crlf_files() {
fn qa_escaped_identifiers_and_macro_only_names_are_found_as_written() {
let scratch = Scratch::with(DESIGN);
let mut s = Session::ready(&scratch);
// `/* héllo wörld */` is 19 bytes and 17 characters: `zz` is byte column 29.
assert_eq!(s.sites(json!({"file": "utf.sv", "line": 2, "name": "zz"})), ["utf.sv:2:29 var"]);
assert_eq!(s.sites(json!({"file": "utf.sv", "line": 2, "col": 40})), ["utf.sv:2:29 var"]);
assert_eq!(
s.hits(json!({"file": "utf.sv", "line": 2, "col": 29})),
["utf.sv:2:29", "utf.sv:2:40"]
);
// A column inside `é` (bytes 7-8 on the line) is refused, never a panic.
for col in [8, 9] {
s.refusal("definition", json!({"file": "utf.sv", "line": 2, "col": col}));
s.refusal("references", json!({"file": "utf.sv", "line": 2, "col": col}));
}
assert_eq!(s.sites(json!({"file": "crlf.sv", "line": 3, "name": "cc"})), ["crlf.sv:2:9 var"]);
let crlf = s.text("references", json!({"file": "crlf.sv", "line": 3, "col": 10}));
assert_eq!(crlf, "crlf.sv\n 2:9 logic cc;\n 3:10 assign cc = a;\n");
assert!(s.pings());
}
#[test]
fn qa_escaped_identifiers_and_macro_only_names_are_selected_as_written() {
let scratch = Scratch::with(DESIGN);
let mut s = Session::ready(&scratch);
assert_eq!(s.sites(json!({"name": "\\a+b"})), ["esc.sv:2:9 var"]);
assert_eq!(
s.hits(json!({"file": "esc.sv", "line": 4, "name": "\\a+b"})),
["esc.sv:2:9", "esc.sv:3:10", "esc.sv:4:12"]
);
let define = ["mac.sv:1:9 define"];
assert_eq!(s.sites(json!({"name": "ONLY_MAC"})), define);
assert_eq!(s.sites(json!({"file": "mac.sv", "name": "`ONLY_MAC"})), define);
assert_eq!(s.sites(json!({"file": "mac.sv", "line": 3, "name": "`ONLY_MAC"})), define);
let refused =
s.refusal("references", json!({"file": "mac.sv", "line": 3, "name": "`ONLY_MAC"}));
assert!(refused.contains("is a macro"), "{refused}");
assert_eq!(s.refs("\\a+b"), "var \\a+b esc.sv:2\n esc.sv:3,4\n");
assert_eq!(s.text("find", json!({"name": "ONLY_MAC"})), "macro ONLY_MAC mac.sv:1\n");
assert_eq!(s.text("find", json!({"name": "`ONLY_MAC"})), "macro ONLY_MAC mac.sv:1\n");
// A macro's uses are not followed; its definition is still listed.
assert_eq!(s.refs("ONLY_MAC"), "macro ONLY_MAC mac.sv:1\n");
}
const MACRO_ARG: &[(&str, &str)] = &[
@@ -371,73 +277,30 @@ const MACRO_ARG: &[(&str, &str)] = &[
"top.sv",
"`include \"defs.svh\"\nmodule top (input logic clk);\n logic peek;\n core u_core0 (.clk, .q());\n assign peek = `ID(u_core0.state_q);\nendmodule\n",
),
("third.sv", "module third;\n // state_q is mentioned here\n initial $display(\"state_q\");\nendmodule\n"),
(
"third.sv",
"module third;\n // u_core0.state_q is mentioned here\n initial $display(\"u_core0.state_q\");\n // a bare state_q here is another module's word\nendmodule\n",
),
("m.sv", "module m (input logic a, output logic q);\n /* q */ assign q = a;\nendmodule\n"),
];
#[test]
fn qa_references_never_report_a_comment_a_string_or_macro_text() {
fn qa_uses_never_include_a_comment_a_string_or_macro_text() {
let scratch = Scratch::with(MACRO_ARG);
let mut s = Session::ready(&scratch);
// `third.sv` writes the word only in a comment and a string; `top.sv`
// only inside a macro call's argument, which the engine does not follow
// (the rename engine warns about such files; references is silent).
assert_eq!(s.hits(json!({"name": "state_q", "unit": "core"})), ["core.sv:2:9", "core.sv:3:14"]);
let paged =
s.call("references", json!({"name": "state_q", "unit": "core", "limit": 1, "offset": 1}));
assert_eq!(paged["structuredContent"]["total"], 2);
assert_eq!(paged["structuredContent"]["hits"][0]["line"], 3);
let past = s.call("references", json!({"name": "state_q", "unit": "core", "offset": 9}));
// `third.sv` writes the word only in a comment and a string (dotted —
// a bare spelling in a file that neither declares nor uses the member
// is not listed since §65.1's scoping of mentions); `top.sv`
// only inside a macro call's argument, which the engine does not follow:
// those are the unresolved mentions, never uses.
assert_eq!(
(paged["structuredContent"]["total"].clone(), past["structuredContent"]["hits"].clone()),
(json!(2), json!([]))
s.refs("state_q"),
"var state_q core.sv:2\n core.sv:3\nunresolved:\n third.sv:2,3\n top.sv:5\n"
);
let bare = json!({"name": "state_q", "unit": "core", "include_declaration": false});
assert_eq!(s.hits(bare), ["core.sv:3:14"]);
}
#[test]
fn qa_finding_2_a_name_inside_a_macro_argument_is_not_answered_with_the_macro() {
// `name: state_q` on `` `ID(u_core0.state_q) `` finds the word inside the
// one macro token and answers `ID`'s `define` — a declaration of a
// different name. The right answers are a refusal or `core.sv:2`.
let scratch = Scratch::with(MACRO_ARG);
let mut s = Session::ready(&scratch);
let result = s.call("definition", json!({"file": "top.sv", "line": 5, "name": "state_q"}));
let listed = result["structuredContent"]["definitions"].as_array().cloned().unwrap_or_default();
assert!(result["isError"] == true || listed.iter().all(|d| d["kind"] != "define"), "{result}");
}
#[test]
fn qa_finding_3_a_name_first_written_in_a_comment_is_still_found_on_its_line() {
let scratch = Scratch::with(MACRO_ARG);
let mut s = Session::ready(&scratch);
// Line 2 is `/* q */ assign q = a;`: the code `q` is at column 18.
assert_eq!(s.sites(json!({"file": "m.sv", "line": 2, "name": "q"})), ["m.sv:1:39 port"]);
}
#[test]
fn qa_finding_8_a_column_past_the_end_of_its_line_is_refused_as_such() {
let scratch = Scratch::with(DESIGN);
let mut s = Session::ready(&scratch);
// Line 2 is 14 bytes; column 99 is silently clamped to 15 today and the
// refusal names `clamp.sv:2:15`, a position the agent never asked about.
let refused = s.refusal("definition", json!({"file": "clamp.sv", "line": 2, "col": 99}));
assert!(refused.contains("99"), "{refused}");
}
#[test]
fn qa_finding_9_references_refusals_do_not_speak_of_renaming() {
let scratch = Scratch::with(DESIGN);
let mut s = Session::ready(&scratch);
let blank = s.refusal("references", json!({"file": "leaf.sv", "line": 1, "col": 7}));
assert!(!blank.contains("rename"), "{blank}");
}
#[test]
fn qa_finding_11_a_name_used_twice_in_a_file_for_two_declarations_is_not_a_guess() {
// `top3.sv` declares no `sig`; its uses name `leaf`'s and `other`'s.
// `file` + `name` takes the first use and answers `leaf` alone.
fn qa_finding_11_a_name_used_for_two_declarations_lists_both_never_a_guess() {
let scratch = Scratch::with(&[
("leaf.sv", "module leaf (output logic sig); endmodule\n"),
("other.sv", "module other (output logic sig); endmodule\n"),
@@ -447,10 +310,10 @@ fn qa_finding_11_a_name_used_twice_in_a_file_for_two_declarations_is_not_a_guess
),
]);
let mut s = Session::ready(&scratch);
let result = s.call("definition", json!({"file": "top3.sv", "name": "sig"}));
let listed = result["structuredContent"]["definitions"].as_array().cloned().unwrap_or_default();
assert!(result["isError"] == true || listed.len() == 2, "{result}");
s.refusal("references", json!({"file": "top3.sv", "name": "sig"}));
assert_eq!(
s.refs("sig"),
"port sig leaf.sv:1\n top3.sv:2,3\nport sig other.sv:1\n top3.sv:6,7\n"
);
}
// ------------------------------------------------------------ hierarchy
@@ -483,11 +346,14 @@ fn qa_hierarchy_terminates_on_self_and_mutual_recursion() {
let scratch = Scratch::with(HIER);
let mut s = Session::ready(&scratch);
let selfm = s.text("hierarchy", json!({"root": "selfm", "depth": 20}));
assert_eq!(selfm, "selfm self.sv:1\n u_s : selfm #(.N(N-1)) (recursive)\n");
assert_eq!(selfm, "selfm self.sv:1\n u_s: selfm self.sv:3 (recursive)\n");
let mutual = s.text("hierarchy", json!({"root": "ma", "depth": 20}));
assert_eq!(mutual, "ma mutual.sv:1\n u_b : mb\n u_a : ma (recursive)\n");
let up = s.text("hierarchy", json!({"root": "ma", "direction": "up", "depth": 20}));
assert_eq!(up, "ma mutual.sv:1\n mb.u_a mutual.sv:2\n ma.u_b mutual.sv:1 (recursive)\n mtop.u mutual.sv:3\n");
assert_eq!(
mutual,
"ma mutual.sv:1\n u_b: mb mutual.sv:1\n u_a: ma mutual.sv:2 (recursive)\n"
);
let up = s.text("hierarchy", json!({"root": "ma", "up": true, "depth": 20}));
assert_eq!(up, "mb.u_a mutual.sv:2\n ma.u_b mutual.sv:1 (recursive)\nmtop.u mutual.sv:3\n");
}
#[test]
@@ -495,29 +361,19 @@ fn qa_hierarchy_depth_is_capped_and_bad_arguments_are_schema_refusals() {
let scratch = Scratch::with(&[("chain.sv", &chain(30))]);
let mut s = Session::ready(&scratch);
let deep = s.text("hierarchy", json!({"root": "c0", "depth": 20}));
// The root, twenty levels.
assert_eq!(deep.lines().count(), 21, "{deep}");
assert!(deep.ends_with("u19 : c20\n") && !deep.contains("c21"), "{deep}");
for depth in [json!(0), json!(-1), json!(2.5), json!("3")] {
assert!(deep.ends_with("u19: c20 chain.sv:20\n") && !deep.contains("c21"), "{deep}");
for depth in [json!(0), json!(-1), json!(2.5), json!("3"), json!(21)] {
let refused = s.refusal("hierarchy", json!({"root": "c0", "depth": depth}));
assert!(refused.contains("`depth`"), "{refused}");
assert!(refused.contains("`depth`") && refused.contains("from 1 to 20"), "{refused}");
}
for direction in ["Up", "sideways", ""] {
let refused = s.refusal("hierarchy", json!({"root": "c0", "direction": direction}));
assert!(refused.contains("one of down, up"), "{refused}");
for up in [json!("up"), json!(1), json!("true")] {
let refused = s.refusal("hierarchy", json!({"root": "c0", "up": up}));
assert!(refused.contains("true or false"), "{refused}");
}
}
#[test]
fn qa_finding_7_a_depth_above_the_cap_is_refused_or_said() {
// `depth: 21` answers exactly what `depth: 20` does, and the schema
// declares no maximum: the agent cannot tell it was capped.
let scratch = Scratch::with(&[("chain.sv", &chain(30))]);
let mut s = Session::ready(&scratch);
let result = s.call("hierarchy", json!({"root": "c0", "depth": 21}));
let text = result["content"][0]["text"].as_str().unwrap_or("");
assert!(result["isError"] == true || text.contains("depth"), "{result}");
}
#[test]
fn qa_hierarchy_marks_not_modules_duplicates_and_two_parents() {
let scratch = Scratch::with(HIER);
@@ -527,36 +383,36 @@ fn qa_hierarchy_marks_not_modules_duplicates_and_two_parents() {
assert!(refused.contains(&format!("`{root}`")), "{refused}");
}
let dupe = s.text("hierarchy", json!({"root": "usedupe"}));
assert_eq!(dupe, "usedupe usedupe.sv:1\n u_d : dupe (declared 2 times)\n");
let up = s.text("hierarchy", json!({"root": "leaf", "direction": "up"}));
assert!(up.contains(" p1.u_l1 p1.sv:1\n p1.u_l2 p1.sv:1\n p2.u_l p2.sv:1\n"), "{up}");
assert_eq!(dupe, "usedupe usedupe.sv:1\n u_d: dupe usedupe.sv:1 (declared 2 times)\n");
let up = s.text("hierarchy", json!({"root": "leaf", "up": true}));
assert!(up.contains("p1.u_l1 p1.sv:1\np1.u_l2 p1.sv:1\np2.u_l p2.sv:1\n"), "{up}");
}
#[test]
fn qa_hierarchy_overrides_drop_comments_and_keep_nested_parentheses() {
fn qa_hierarchy_peek_keeps_comments_and_nested_parentheses_as_written() {
let scratch = Scratch::with(HIER);
let mut s = Session::ready(&scratch);
let result = s.call("hierarchy", json!({"root": "ov"}));
let nodes = result["structuredContent"]["nodes"].as_array().unwrap().clone();
assert_eq!(nodes[1]["instance"], "u_ov");
assert_eq!(nodes[1]["overrides"], "#( .W(c#(4)::N), .S(\"u_x (\"), .D({2{1'b0}}) )");
assert_eq!(nodes[2]["overrides"], "#(.W(2))");
let peek = s.text("hierarchy", json!({"root": "ov", "peek": true}));
assert!(
peek.starts_with("ov ov.sv:1\n u_ov: leaf ov.sv:3\n leaf #( /* W = 4 ) oops */ .W(c#(4)::N), // tail ) comment\n .S(\"u_x (\"), .D({2{1'b0}}) ) u_ov ();\n"),
"{peek}"
);
}
#[test]
fn qa_finding_4_every_instance_of_one_statement_shows_only_the_overrides() {
// `leaf #(.W(2)) u_a (), u_b ();` — `u_b` shows `#(.W(2)) u_a (),`.
fn qa_finding_4_every_instance_of_one_statement_peeks_at_the_whole_statement() {
let scratch = Scratch::with(HIER);
let mut s = Session::ready(&scratch);
let result = s.call("hierarchy", json!({"root": "ov"}));
assert_eq!(result["structuredContent"]["nodes"][3]["instance"], "u_b");
assert_eq!(result["structuredContent"]["nodes"][3]["overrides"], "#(.W(2))");
let up = s.text("hierarchy", json!({"root": "leaf", "direction": "up"}));
assert!(up.contains(" ov.u_b #(.W(2)) ov.sv:4\n"), "{up}");
let up = s.text("hierarchy", json!({"root": "leaf", "up": true, "peek": true}));
let statement = " leaf #(.W(2)) u_a (), u_b ();\n";
assert!(
up.contains(&format!("ov.u_a ov.sv:4\n{statement}ov.u_b ov.sv:4\n{statement}")),
"{up}"
);
}
#[test]
fn qa_hierarchy_stops_at_the_node_cap_and_says_so() {
fn qa_hierarchy_stops_at_the_node_cap_and_the_line_cap() {
let wide = |name: &str, child: &str| {
let body: String = (0..250).map(|i| format!(" {child} u{i} ();\n")).collect();
format!("module {name};\n{body}endmodule\n")
@@ -565,10 +421,9 @@ fn qa_hierarchy_stops_at_the_node_cap_and_says_so() {
let scratch =
Scratch::with(&[("w1.sv", &w1), ("w2.sv", &w2), ("w3.sv", "module w3; endmodule\n")]);
let mut s = Session::ready(&scratch);
let result = s.call("hierarchy", json!({"root": "w1", "limit": 2}));
assert_eq!(result["structuredContent"]["total"], 50_000);
assert_eq!(result["structuredContent"]["cut"], true);
assert!(result["content"][0]["text"].as_str().unwrap().contains("tree cut at 50000 nodes"));
let text = s.text("hierarchy", json!({"root": "w1", "depth": 2}));
assert_eq!(text.lines().count(), 301, "300 lines, then the cut");
assert!(text.ends_with("\n… and 49700 more\n"), "{}", &text[text.len() - 60..]);
}
// ---------------------------------------------------------- diagnostics
@@ -587,56 +442,34 @@ const LINT: &[(&str, &str)] = &[
];
#[test]
fn qa_diagnostics_follow_each_files_own_config_directory() {
fn qa_check_follows_each_files_own_config_directory() {
let scratch = Scratch::with(LINT);
let mut s = Session::ready(&scratch);
// Root config: select 3, ignore no-tabs, length 45, a/waived.sv waived.
assert_eq!(
s.text("diagnostics", json!({"file": "a/m.sv"})),
"a/m.sv\n 2:46 style line is 50 characters; the limit is 45 [line-length]\n"
s.text("check", json!({"file": "a/m.sv"})),
"a/m.sv:2:46 style line is 50 characters; the limit is 45 [line-length]\n"
);
assert_eq!(s.text("diagnostics", json!({"file": "a/waived.sv"})), "no findings\n");
assert_eq!(s.text("check", json!({"file": "a/waived.sv"})), "ok\n");
// b/lucisv.toml: its own select (no-tabs back) and its own line-length
// 60, which the 59-character line 2 is inside (45 would flag it).
assert_eq!(
s.text("diagnostics", json!({"file": "b/n.sv"})),
"b/n.sv\n 2:1 style tab character; indent with spaces [no-tabs]\n"
s.text("check", json!({"file": "b/n.sv"})),
"b/n.sv:2:1 style tab character; indent with spaces [no-tabs]\n"
);
// `rules` replaces select; the config's ignore still applies.
assert_eq!(
s.text("diagnostics", json!({"file": "a/m.sv", "rules": "no-tabs"})),
"no findings\n"
);
let style = s.text("diagnostics", json!({"file": "a/m.sv", "rules": "style"}));
assert!(style.contains("[port-name-suffix]") && !style.contains("[no-tabs]"), "{style}");
let warnings = s.call("diagnostics", json!({"file": "a/m.sv", "severity": "warning"}));
assert_eq!(warnings["structuredContent"]["total"], 0);
}
#[test]
fn qa_diagnostics_list_parse_errors_before_lint_findings_and_page_the_project() {
fn qa_check_lists_parse_errors_before_lint_findings() {
let scratch = Scratch::with(LINT);
let mut s = Session::ready(&scratch);
let broken = s.call("diagnostics", json!({"file": "c/broken.sv"}));
let rules: Vec<String> = broken["structuredContent"]["diagnostics"]
.as_array()
.unwrap()
.iter()
.map(|d| format!("{}@{}", d["rule"].as_str().unwrap(), d["location"]["line"]))
.collect();
assert_eq!(rules, ["parse-error@3", "line-length@2"]);
let all = s.call("diagnostics", json!({}));
let total = all["structuredContent"]["total"].as_u64().unwrap();
assert_eq!(total, 4);
let mut paged = Vec::new();
for offset in 0..total {
let one = s.call("diagnostics", json!({"limit": 1, "offset": offset}));
assert_eq!(one["structuredContent"]["total"], total);
paged.push(one["structuredContent"]["diagnostics"][0].clone());
}
assert_eq!(Value::from(paged), all["structuredContent"]["diagnostics"]);
let errors = s.call("diagnostics", json!({"severity": "error"}));
assert_eq!(errors["structuredContent"]["total"], 1);
let broken = s.text("check", json!({"file": "c/broken.sv"}));
let rules: Vec<&str> =
broken.lines().map(|line| line.rsplit_once('[').unwrap().1.trim_end_matches(']')).collect();
assert_eq!(rules, ["parse-error", "line-length"], "{broken}");
let all = s.text("check", json!({}));
assert_eq!(all.lines().count(), 4, "{all}");
assert!(all.starts_with("c/broken.sv:3:"), "errors first: {all}");
}
#[test]
@@ -646,16 +479,12 @@ fn qa_a_bad_lint_option_is_refused_naming_the_config_file_and_line() {
("m.sv", "module m; endmodule\n"),
]);
let mut s = Session::ready(&scratch);
let refused = s.refusal("diagnostics", json!({"file": "m.sv"}));
let refused = s.refusal("check", json!({"file": "m.sv"}));
assert!(refused.contains("lucisv.toml:5") && refused.contains("`line-length`"), "{refused}");
let unknown = s.refusal("diagnostics", json!({"file": "m.sv", "rules": "no-such-rule"}));
assert!(unknown.contains("unknown rule: no-such-rule"), "{unknown}");
}
#[test]
fn qa_finding_6_an_unused_external_waiver_is_reported_as_the_cli_does() {
// `lucisv check .` reports `w.waiver:1:1 unused-waiver`; the MCP drops
// `lint_with`'s used-waiver answer.
let scratch = Scratch::with(&[
(
"lucisv.toml",
@@ -665,57 +494,38 @@ fn qa_finding_6_an_unused_external_waiver_is_reported_as_the_cli_does() {
("m.sv", "module m;\nendmodule\n"),
]);
let mut s = Session::ready(&scratch);
let all = s.text("diagnostics", json!({}));
let all = s.text("check", json!({}));
assert!(all.contains("[unused-waiver]"), "{all}");
}
#[test]
fn qa_finding_5_one_files_diagnostics_match_lucisv_check_of_the_whole_tree() {
// Lead's ruling on finding 5: `diagnostics` answers "what will CI say",
// i.e. `lucisv check .` over the whole tree, where the cross-file rules
// run — so one file's answer includes `unknown-port` here, as
// `lucisv check .` reports for top.sv (`lucisv check top.sv` alone does
// not). Rewritten by the dev from the single-file assertion QA offered
// for deletion under this ruling.
fn qa_finding_5_one_files_check_matches_lucisv_check_of_the_whole_tree() {
// `check` answers "what will CI say", i.e. `lucisv check .` over the
// whole tree, where the cross-file rules run.
let scratch = Scratch::with(&[
("leaf.sv", "module leaf (input logic a);\nendmodule\n"),
("top.sv", "module top;\n leaf u (.b(1'b0));\nendmodule\n"),
]);
let mut s = Session::ready(&scratch);
let one = s.text("diagnostics", json!({"file": "top.sv"}));
let one = s.text("check", json!({"file": "top.sv"}));
assert!(one.contains("[unknown-port]"), "{one}");
}
// -------------------------------------------------------------- defines
#[test]
fn qa_defines_list_every_definition_and_never_pick_one() {
fn qa_find_lists_every_macro_definition_and_never_picks_one() {
let scratch = Scratch::with(&[
("a.svh", "`define TWICE 1\n`define MULTI(a, b) \\\n begin \\\n a = b; \\\n end\n"),
("b.svh", "`define TWICE 2\n`undef TWICE\n"),
("d.sv", "module d; localparam int P = `TWICE; endmodule\n"),
]);
let mut s = Session::ready(&scratch);
let twice = "a.svh\n 1 `define TWICE 1\nb.svh\n 1 `define TWICE 2\n";
assert_eq!(s.text("defines", json!({"name": "TWICE"})), twice);
assert_eq!(s.text("defines", json!({"name": "`TWICE"})), twice);
assert_eq!(
s.sites(json!({"file": "d.sv", "line": 1, "name": "`TWICE"})),
["a.svh:1:9 define", "b.svh:1:9 define"]
);
let multi = s.call("defines", json!({"name": "MULTI"}));
assert_eq!(
multi["structuredContent"]["defines"][0],
json!({"file": "a.svh", "line": 2, "name": "MULTI", "kind": "define", "params": ["a", "b"], "body": "begin a = b; end"})
);
assert_eq!(s.text("defines", json!({"name": "NOPE"})), "no defines\n");
assert_eq!(
s.text("defines", json!({"file": "b.svh", "name": "TWICE"})),
"b.svh\n 1 `define TWICE 2\n 2 `undef TWICE\n"
);
assert_eq!(s.text("defines", json!({"file": "a.svh", "name": "NOPE"})), "no defines\n");
let missing = s.refusal("defines", json!({"file": "nope.sv"}));
assert!(missing.contains("nope.sv"), "{missing}");
let twice = "macro TWICE a.svh:1\nmacro TWICE b.svh:1\n";
assert_eq!(s.text("find", json!({"name": "TWICE"})), twice);
assert_eq!(s.text("find", json!({"name": "`TWICE"})), twice);
assert_eq!(s.text("find", json!({"name": "MULTI"})), "macro MULTI a.svh:2\n");
s.refusal("find", json!({"name": "NOPE"}));
}
// ------------------------------------------------------------ resources
@@ -737,15 +547,14 @@ fn qa_resources_refuse_what_they_cannot_name_and_decode_escapes() {
}
}
let read = |s: &mut Session, uri: &str| s.request("resources/read", json!({"uri": uri}));
for (uri, starts) in [
("lucisv://file/sp%20ace/f%20ile.sv/outline", "sp ace/f ile.sv\n"),
("lucisv://file/%C3%BC/%C3%B1.sv/outline", "ü/ñ.sv\n"),
("lucisv://file/pct%25/a.sv/outline", "pct%/a.sv\n"),
("lucisv://file/x/dup1.sv/outline", "x/dup1.sv\n"),
for (uri, outline) in [
("lucisv://file/sp%20ace/f%20ile.sv/outline", "module spc 1\n"),
("lucisv://file/%C3%BC/%C3%B1.sv/outline", "module uni 1\n"),
("lucisv://file/pct%25/a.sv/outline", "module pct 1\n"),
("lucisv://file/x/dup1.sv/outline", "module dup 1\n"),
] {
let reply = read(&mut s, uri);
let text = reply["result"]["contents"][0]["text"].as_str().unwrap_or("");
assert!(text.starts_with(starts), "{uri}: {reply}");
assert_eq!(reply["result"]["contents"][0]["text"], outline, "{uri}: {reply}");
}
for uri in [
"lucisv://unit/dup",
@@ -777,32 +586,35 @@ fn qa_finding_10_an_ambiguous_unit_resource_does_not_ask_for_a_file_argument() {
// ------------------------------------------------------------ freshness
#[test]
fn qa_references_and_hierarchy_follow_edits_and_deletions() {
fn qa_find_and_hierarchy_follow_edits_and_deletions() {
let scratch = Scratch::with(&[
("leaf.sv", "module leaf (input logic a);\nendmodule\n"),
("top.sv", "module top;\n logic a;\n leaf u1 (.a(a));\nendmodule\n"),
]);
let mut s = Session::ready(&scratch);
assert_eq!(s.hits(json!({"name": "leaf"})), ["leaf.sv:1:8", "top.sv:3:3"]);
assert_eq!(s.refs("leaf"), "module leaf leaf.sv:1\n top.sv:3\n");
scratch.write(
"top.sv",
"module top;\n logic a;\n leaf u1 (.a(a));\n leaf u2 (.a(a));\nendmodule\n",
);
assert_eq!(s.hits(json!({"name": "leaf"})), ["leaf.sv:1:8", "top.sv:3:3", "top.sv:4:3"]);
assert_eq!(s.refs("leaf"), "module leaf leaf.sv:1\n top.sv:3,4\n");
assert_eq!(
s.text("hierarchy", json!({"root": "top"})),
"top top.sv:1\n u1 : leaf\n u2 : leaf\n"
"top top.sv:1\n u1: leaf top.sv:3\n u2: leaf top.sv:4\n"
);
fs::remove_file(scratch.path("top.sv")).unwrap();
assert!(s.refusal("hierarchy", json!({"root": "top"})).contains("`top`"));
assert_eq!(s.text("hierarchy", json!({"root": "leaf", "direction": "up"})), "leaf leaf.sv:1\n");
assert_eq!(
s.text("hierarchy", json!({"root": "leaf", "up": true})),
"nothing instantiates leaf\n"
);
scratch.write("other.sv", "module other; leaf u9 (.a()); endmodule\n");
fs::remove_file(scratch.path("leaf.sv")).unwrap();
assert_eq!(
s.text("hierarchy", json!({"root": "other"})),
"other other.sv:1\n u9 : leaf (not indexed)\n"
"other other.sv:1\n u9: leaf other.sv:1 (not indexed)\n"
);
assert!(s.refusal("definition", json!({"name": "leaf"})).contains("`leaf`"));
assert!(s.refusal("find", json!({"name": "leaf"})).contains("`leaf`"));
}
// ------------------------------------------------ re-check after rework
@@ -824,29 +636,13 @@ const CHAINS: &[(&str, &str)] = &[
];
#[test]
fn qa_recheck_every_site_of_a_tail_and_a_handle_chain_gives_the_whole_set_answer() {
fn qa_recheck_a_tail_and_a_handle_chain_give_the_whole_set_answer() {
// The expected lists are `vlog_refactor::find_references` over all
// seven files (QA's oracle), asked from each site in turn.
// seven files (QA's oracle).
let scratch = Scratch::with(CHAINS);
let mut s = Session::ready(&scratch);
let tail = ["leaf.sv:2:9", "top2.sv:3:21", "top2.sv:4:21"];
for site in [
json!({"name": "sig2", "unit": "leaf"}),
json!({"file": "leaf.sv", "line": 2, "name": "sig2"}),
json!({"file": "top2.sv", "line": 3, "name": "sig2"}),
json!({"file": "top2.sv", "line": 4, "col": 21}),
] {
assert_eq!(s.hits(site.clone()), tail, "{site}");
}
let chain = ["sb.sv:2:7", "sb.sv:3:24", "t.sv:4:9", "t2.sv:3:33"];
for site in [
json!({"name": "count", "unit": "sb"}),
json!({"file": "sb.sv", "line": 3, "name": "count"}),
json!({"file": "t.sv", "line": 4, "name": "count"}),
json!({"file": "t2.sv", "line": 3, "name": "count"}),
] {
assert_eq!(s.hits(site.clone()), chain, "{site}");
}
assert_eq!(s.refs("sig2"), "var sig2 leaf.sv:2\n top2.sv:3,4\n");
assert_eq!(s.refs("count"), "var count sb.sv:2\n sb.sv:3\n t.sv:4\n t2.sv:3\n");
}
const TOKENS: &[(&str, &str)] = &[
@@ -858,38 +654,16 @@ const TOKENS: &[(&str, &str)] = &[
];
#[test]
fn qa_recheck_a_comment_a_string_and_a_macro_argument_never_stand_in_for_the_use() {
fn qa_recheck_a_comment_a_string_and_a_macro_argument_are_mentions_never_uses() {
let scratch = Scratch::with(TOKENS);
let mut s = Session::ready(&scratch);
// Line 3 writes `q` in a comment, a string, a macro argument, as code
// (column 60) and in a trailing comment: only the code counts.
let q = json!({"file": "m.sv", "line": 3, "name": "q"});
assert_eq!(s.sites(q.clone()), ["m.sv:2:39 port"]);
assert_eq!(s.hits(q), ["m.sv:2:39", "m.sv:3:60", "m.sv:5:10", "m.sv:5:31"]);
// Line 6 writes `q` only inside strings.
let strings = s.refusal("definition", json!({"file": "m.sv", "line": 6, "name": "q"}));
assert!(strings.contains("not written on line 6"), "{strings}");
// Line 3 writes `q` in a comment, a string, a macro argument, as code and
// in a trailing comment: only the code is a use; line 6 only in strings.
assert_eq!(s.refs("q"), "port q m.sv:2\n m.sv:3,5\nunresolved:\n m.sv:3,4,6\n");
}
#[test]
fn qa_recheck_a_name_only_in_a_macro_argument_is_refused_on_that_line_alone() {
let scratch = Scratch::with(TOKENS);
let mut s = Session::ready(&scratch);
for (line, name) in [(4, "q"), (5, "a")] {
let at = json!({"file": "m.sv", "line": line, "name": name});
let refused = s.refusal("definition", at.clone());
assert!(refused.contains("inside a macro argument"), "{refused}");
assert!(s.refusal("references", at).contains("inside a macro argument"));
}
// The same names written plainly elsewhere are found, and the macro
// itself is still selectable as `` `ID``.
assert_eq!(s.sites(json!({"file": "m.sv", "line": 5, "name": "q"})), ["m.sv:2:39 port"]);
assert_eq!(s.sites(json!({"file": "m.sv", "name": "a"})), ["m.sv:2:23 port"]);
assert_eq!(s.sites(json!({"file": "m.sv", "line": 4, "name": "`ID"})), ["defs.svh:1:9 define"]);
}
#[test]
fn qa_recheck_overrides_split_across_lines_and_comments_between_instances() {
fn qa_recheck_peek_shows_overrides_split_across_lines_and_comments_between_instances() {
let scratch = Scratch::with(&[
("leaf.sv", "module leaf #(parameter int W = 1) (); endmodule\n"),
(
@@ -898,16 +672,19 @@ fn qa_recheck_overrides_split_across_lines_and_comments_between_instances() {
),
]);
let mut s = Session::ready(&scratch);
assert_eq!(
s.text("hierarchy", json!({"root": "ov"})),
"ov ov.sv:1\n u_a : leaf #(.W(2))\n u_b : leaf #(.W(2))\n u_c : leaf #(.W(2))\n u_d : leaf\n u_e : leaf\n u_f : leaf\n u_g : leaf #( .W(3) )\n u_h : leaf #( .W(3) )\n u_i : leaf #( .W(3) )\n u_j : leaf #(.W(4))\n u_k : leaf #(.W(5))\n u_l : leaf\n u_m : leaf\n"
);
let up = s.text("hierarchy", json!({"root": "leaf", "direction": "up"}));
assert!(up.contains(" ov.u_i #( .W(3) ) ov.sv:9\n ov.u_j #(.W(4)) ov.sv:10\n"), "{up}");
let tree = s.text("hierarchy", json!({"root": "ov"}));
let instances: Vec<&str> =
tree.lines().skip(1).map(|line| line.trim().split(':').next().unwrap()).collect();
let all =
["u_a", "u_b", "u_c", "u_d", "u_e", "u_f", "u_g", "u_h", "u_i", "u_j", "u_k", "u_l", "u_m"];
assert_eq!(instances, all);
let up = s.text("hierarchy", json!({"root": "leaf", "up": true, "peek": true}));
let split = " leaf #(\n .W(3) // three\n )\n u_g (), /* between ) , */\n u_h ()\n , u_i ();\n";
assert!(up.contains(&format!("ov.u_i ov.sv:9\n{split}ov.u_j ov.sv:10\n")), "{up}");
}
#[test]
fn qa_recheck_depth_twenty_is_the_schema_maximum() {
fn qa_recheck_depth_twenty_is_the_maximum_and_the_schema_says_integer() {
let scratch = Scratch::with(&[("chain.sv", &chain(30))]);
let mut s = Session::ready(&scratch);
let tools = s.request("tools/list", json!({}));
@@ -918,37 +695,18 @@ fn qa_recheck_depth_twenty_is_the_schema_maximum() {
.find(|tool| tool["name"] == "hierarchy")
.unwrap()
.clone();
let depth = &hierarchy["inputSchema"]["properties"]["depth"];
assert_eq!((depth["minimum"].clone(), depth["maximum"].clone()), (json!(1), json!(20)));
// PLAN §10.1: `type` alone per property; the description names the range.
assert_eq!(hierarchy["inputSchema"]["properties"]["depth"], json!({"type": "integer"}));
assert!(hierarchy["description"].as_str().unwrap().contains("1-20"));
assert_eq!(s.text("hierarchy", json!({"root": "c0", "depth": 20})).lines().count(), 21);
let refused = s.refusal("hierarchy", json!({"root": "c0", "depth": 21}));
assert!(refused.contains("from 1 to 20"), "{refused}");
}
#[test]
fn qa_recheck_a_column_at_and_just_past_the_last_byte_is_a_position() {
// Line 2 is ` wire b = a;` (13 bytes, then CRLF); line 3 is `endmodule`
// with no newline at all.
let scratch =
Scratch::with(&[("crlf.sv", "module crlf (input logic a);\r\n wire b = a;\r\nendmodule")]);
let mut s = Session::ready(&scratch);
assert_eq!(s.sites(json!({"file": "crlf.sv", "line": 2, "col": 12})), ["crlf.sv:1:26 port"]);
for (line, col) in [(2, 13), (2, 14), (3, 9), (3, 10)] {
let refused = s.refusal("definition", json!({"file": "crlf.sv", "line": line, "col": col}));
assert!(refused.contains(&format!("crlf.sv:{line}:{col} names")), "{refused}");
}
for (line, col, length) in [(2, 15, 13), (3, 11, 9)] {
let refused = s.refusal("definition", json!({"file": "crlf.sv", "line": line, "col": col}));
assert!(refused.contains(&format!("line {line} is {length} bytes long")), "{refused}");
}
}
#[test]
fn qa_recheck_references_from_a_file_the_walk_skips_answer_without_a_crash() {
fn qa_recheck_by_name_uses_count_the_indexed_files_only() {
// `ignored/` is gitignored and `notes.txt` is not a source: neither is
// indexed, but both are files inside the root, which every read tool
// accepts (M1's path rule). Asked from there, the answer is real and
// names the file asked from; by name it is the indexed files only.
// indexed, so neither is searched by name.
let scratch = Scratch::with(&[
(".gitignore", "ignored/\n"),
("leaf.sv", "module leaf (input logic a);\nendmodule\n"),
@@ -957,45 +715,29 @@ fn qa_recheck_references_from_a_file_the_walk_skips_answer_without_a_crash() {
("notes.txt", "leaf u8 (.a());\n"),
]);
let mut s = Session::ready(&scratch);
assert_eq!(
s.hits(json!({"file": "ignored/ig.sv", "line": 2, "name": "leaf"})),
["ignored/ig.sv:2:3", "leaf.sv:1:8", "top.sv:3:3"]
);
assert_eq!(
s.hits(json!({"file": "notes.txt", "line": 1, "name": "leaf"})),
["leaf.sv:1:8", "notes.txt:1:1", "top.sv:3:3"]
);
assert_eq!(s.hits(json!({"name": "leaf"})), ["leaf.sv:1:8", "top.sv:3:3"]);
let missing = s.refusal("references", json!({"file": "ignored/none.sv", "line": 1, "col": 1}));
assert!(missing.contains("none.sv"), "{missing}");
assert_eq!(s.refs("leaf"), "module leaf leaf.sv:1\n top.sv:3\n");
// The unindexed file is still one a read tool accepts by path.
assert!(s.text("outline", json!({"file": "ignored/ig.sv"})).starts_with("module ig 1–3\n"));
assert!(s.pings());
}
#[test]
fn qa_recheck_whole_set_references_drop_a_file_deleted_mid_session() {
fn qa_recheck_whole_set_uses_drop_a_file_deleted_mid_session() {
let scratch = Scratch::with(&[
("leaf.sv", "module leaf (input logic a);\nendmodule\n"),
("top.sv", "module top;\n logic a;\n leaf u1 (.a(a));\nendmodule\n"),
("gone.sv", "module gone;\n leaf u9 (.a(1'b0));\nendmodule\n"),
]);
let mut s = Session::ready(&scratch);
assert_eq!(s.hits(json!({"name": "leaf"})), ["gone.sv:2:3", "leaf.sv:1:8", "top.sv:3:3"]);
assert_eq!(s.refs("leaf"), "module leaf leaf.sv:1\n gone.sv:2\n top.sv:3\n");
fs::remove_file(scratch.path("gone.sv")).unwrap();
assert_eq!(s.hits(json!({"name": "leaf"})), ["leaf.sv:1:8", "top.sv:3:3"]);
assert_eq!(
s.hits(json!({"file": "top.sv", "line": 3, "name": "leaf"})),
["leaf.sv:1:8", "top.sv:3:3"]
);
assert_eq!(s.refs("leaf"), "module leaf leaf.sv:1\n top.sv:3\n");
fs::remove_file(scratch.path("leaf.sv")).unwrap();
let orphan = s.refusal("references", json!({"file": "top.sv", "line": 3, "name": "leaf"}));
assert!(
orphan.starts_with("lucisv cannot follow this position: ") && !orphan.contains("rename"),
"{orphan}"
);
s.refusal("find", json!({"name": "leaf", "refs": true}));
}
#[test]
fn qa_recheck_three_uses_naming_three_declarations_are_refused_line_by_line() {
fn qa_recheck_three_declarations_of_one_name_are_listed_each_with_its_uses() {
let scratch = Scratch::with(&[
("l1.sv", "module l1 (output logic sig); endmodule\n"),
("l2.sv", "module l2 (output logic sig); endmodule\n"),
@@ -1007,21 +749,17 @@ fn qa_recheck_three_uses_naming_three_declarations_are_refused_line_by_line() {
("same.sv", "module sa;\n l1 u1 ();\n wire w = u1.sig;\n wire v = u1.sig;\nendmodule\n"),
]);
let mut s = Session::ready(&scratch);
let listed = "`sig` on line 3 → l1.sv:1, line 7 → l2.sv:1, line 12 → l3.sv:1; add `line`";
for tool in ["definition", "references"] {
let refused = s.refusal(tool, json!({"file": "top.sv", "name": "sig"}));
assert!(refused.starts_with(listed), "{refused}");
}
assert_eq!(s.sites(json!({"file": "top.sv", "line": 7, "name": "sig"})), ["l2.sv:1:25 port"]);
// Two uses of one declaration are not ambiguous.
assert_eq!(s.sites(json!({"file": "same.sv", "name": "sig"})), ["l1.sv:1:25 port"]);
assert_eq!(
s.refs("sig"),
"port sig l1.sv:1\n same.sv:3,4\n top.sv:3\nport sig l2.sv:1\n top.sv:7,8\nport sig l3.sv:1\n top.sv:12\n"
);
}
#[test]
fn qa_recheck_unused_waivers_match_lucisv_check_of_the_tree() {
// `lucisv check .` here: one `unused-waiver` at w.waiver:1:1 (the second
// directive is used by m.sv; `sub/` names the same file and it is read
// once); `--select no-tabs` reports nothing.
// once).
let scratch = Scratch::with(&[
(
"lucisv.toml",
@@ -1037,15 +775,14 @@ fn qa_recheck_unused_waivers_match_lucisv_check_of_the_tree() {
]);
let mut s = Session::ready(&scratch);
assert_eq!(
s.text("diagnostics", json!({})),
"w.waiver\n 1:1 style unused waiver for `no-tabs` [unused-waiver]\n"
s.text("check", json!({})),
"w.waiver:1:1 style unused waiver for `no-tabs` [unused-waiver]\n"
);
assert_eq!(s.text("diagnostics", json!({"rules": "no-tabs"})), "no findings\n");
assert_eq!(s.text("diagnostics", json!({"file": "m.sv"})), "no findings\n");
assert_eq!(s.text("check", json!({"file": "m.sv"})), "ok\n");
}
#[test]
fn qa_recheck_one_files_diagnostics_are_its_lines_of_lucisv_check_dot() {
fn qa_recheck_one_files_check_is_its_lines_of_lucisv_check_dot() {
// `lucisv check .` prints `./top.sv:2:12: error: `leaf` declares no port
// `b` [unknown-port]` and nothing else.
let scratch = Scratch::with(&[
@@ -1054,8 +791,8 @@ fn qa_recheck_one_files_diagnostics_are_its_lines_of_lucisv_check_dot() {
]);
let mut s = Session::ready(&scratch);
assert_eq!(
s.text("diagnostics", json!({"file": "top.sv"})),
"top.sv\n 2:12 error `leaf` declares no port `b` [unknown-port]\n"
s.text("check", json!({"file": "top.sv"})),
"top.sv:2:12 error `leaf` declares no port `b` [unknown-port]\n"
);
assert_eq!(s.text("diagnostics", json!({"file": "leaf.sv"})), "no findings\n");
assert_eq!(s.text("check", json!({"file": "leaf.sv"})), "ok\n");
}
+198 -366
View File
@@ -1,9 +1,11 @@
//! QA attacks on lane M3 (the edit tools and their one write path),
//! 2026-09-23.
//! 2026-09-23 — ported to the lean catalogue (`rename`, `port`,
//! `edit_item`, `format`); the tools it dropped took their attacks with
//! them (`docs/features/mcp-lean-catalogue/README.md` lists which).
//!
//! Two kinds of test. The first half includes the production write path,
//! `src/apply.rs`, verbatim (`#[path]`) over two small stand-ins for the
//! modules it names (`Project`'s roots and `Answer`), so `commit` — the
//! `src/apply.rs`, verbatim (`#[path]`) over a small stand-in for the
//! module it names (`Project`'s roots), so `commit` — the
//! write-freshness rule — can be attacked directly with stale texts; no
//! black box can hook the gap between a tool's read and its write. The
//! second half spawns the real binary over scratch trees, as a host would.
@@ -48,14 +50,6 @@ mod project {
}
}
/// Stand-in for `crate::tools`: the answer type `apply.rs` builds.
mod tools {
pub struct Answer {
pub text: String,
pub structured: serde_json::Value,
}
}
#[path = "../src/apply.rs"]
mod apply;
@@ -261,13 +255,6 @@ fn text_of(result: &Value) -> String {
result["content"][0]["text"].as_str().unwrap().to_string()
}
/// `arguments` with `dry_run` set.
fn dry(arguments: &Value, dry_run: bool) -> Value {
let mut arguments = arguments.clone();
arguments["dry_run"] = Value::from(dry_run);
arguments
}
/// The `lucisv` CLI built beside `lucisv-mcp`, when the build made it
/// (`cargo test --workspace` does; `-p lucisv_mcp` alone may not).
fn cli() -> Option<PathBuf> {
@@ -275,15 +262,6 @@ fn cli() -> Option<PathBuf> {
path.exists().then_some(path)
}
/// `+`/`-` body lines of a unified diff (headers skipped).
fn signed_lines(diff: &str) -> (usize, usize) {
let body = diff.lines().filter(|l| !l.starts_with("--- ") && !l.starts_with("+++ "));
let body: Vec<&str> = body.collect();
let added = body.iter().filter(|l| l.starts_with('+')).count();
let removed = body.iter().filter(|l| l.starts_with('-')).count();
(added, removed)
}
// ================================================ apply::commit, directly
fn change(path: &Path, before: &str, after: &str) -> apply::Change {
@@ -432,95 +410,72 @@ fn qa_plan_refuses_an_unread_file_overlapping_edits_and_a_split_character() {
..RefactorEdit::default()
};
assert!(apply::Plan::from_refactor(two, &texts).err().unwrap().contains("overlap"));
// A fitting edit plans, and `run` in dry-run mode writes nothing.
// A fitting edit plans, and `run` writes it and says so.
fs::write(&read, &texts[0].1).unwrap();
let plan = apply::Plan::from_refactor(edit(&read, 0, 6), &texts).unwrap();
assert!(plan.warnings.is_empty());
let project = project::Project::open(vec![scratch.0.clone()], None);
let pristine = snapshot(&scratch.0);
let answer = apply::run(&project, plan, true).unwrap();
assert!(answer.text.contains("(dry run: nothing written)"), "{}", answer.text);
assert_eq!(answer.structured["changed"][0]["file"], "r.sv");
assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty());
let written = apply::run(&project, &plan).unwrap();
assert_eq!((written.changed, written.created), (vec!["r.sv".to_string()], vec![]));
assert_eq!(moved(&pristine, &snapshot(&scratch.0)), ["r.sv"]);
assert_eq!(fs::read_to_string(&read).unwrap(), "z é; endmodule\n");
}
// ================================================ corruption hunt (attack 1)
/// Every edit tool, one real call over a fresh fixture copy: exactly the
/// reported files move, each reported count matches the dry run's diff, the
/// dry-run diff is the diff of what was written, and the same call again
/// writes nothing.
/// expected files move, the answer's counts are the files that moved, and
/// the same call again writes nothing.
#[test]
fn qa_every_edit_writes_only_what_it_reports_and_a_repeat_writes_nothing() {
let calls = [
("rename", json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "din_i"})),
("rename", json!({"name": "d", "unit": "leaf", "new_name": "din_i"})),
("expand_wildcard", json!({"file": "rtl/wild.sv", "line": 6})),
("convert_ports", json!({"file": "rtl/old.sv", "line": 1})),
("organize_imports", json!({"file": "rtl/top.sv", "line": 6})),
("inline_module", json!({"file": "rtl/inl.sv", "line": 5})),
("propagate_ports", json!({"file": "rtl/partial.sv", "line": 6})),
("remove_port", json!({"file": "rtl/spare.sv", "line": 3, "name": "unused_i"})),
("add_port", json!({"module": "leaf", "declaration": "input logic en"})),
fn qa_every_edit_writes_only_what_it_says_and_a_repeat_writes_nothing() {
let calls: [(&str, Value, &[&str]); 7] = [
(
"add_port",
json!({"file": "rtl/cell.sv", "line": 3, "declaration": "input logic rst_ni"}),
"rename",
json!({"name": "d", "file": "rtl/leaf.sv", "new_name": "din_i"}),
&["rtl/leaf.sv", "rtl/mid.sv", "rtl/top.sv"],
),
(
"extract_module",
json!({"file": "rtl/ext.sv", "start_line": 7, "end_line": 7, "new_name": "adder"}),
"port",
json!({"module": "spare", "remove": "unused_i"}),
&["rtl/spare.sv", "rtl/spare_user.sv"],
),
(
"extract_module",
json!({"file": "rtl/ext.sv", "start_line": 8, "end_line": 8, "new_name": "reg8", "home": "same_file"}),
"port",
json!({"module": "leaf", "add": "input logic en"}),
&["rtl/leaf.sv", "rtl/mid.sv", "rtl/top.sv"],
),
(
"port",
json!({"module": "leaf", "add": "input logic en", "after": "clk"}),
&["rtl/leaf.sv", "rtl/mid.sv", "rtl/top.sv"],
),
("format", json!({"files": "fmt/messy.sv"}), &["fmt/messy.sv"]),
("format", json!({"files": "fmt/messy.sv", "fix": true}), &["fmt/messy.sv"]),
(
"edit_item",
json!({"file": "rtl/leaf.sv", "op": "insert_after", "item": "end", "text": "logic spare_q;"}),
&["rtl/leaf.sv"],
),
("format", json!({"files": "fmt/messy.sv,rtl/mid.sv"})),
("fix_lint", json!({"file": "fmt/messy.sv"})),
];
for (tool, arguments) in calls {
for (tool, arguments, expected) in calls {
let scratch = Scratch::edit_fixture();
scratch.write("fmt/messy.sv", "module messy(input logic a,output logic b); \nassign b=a;\n // keep this comment\nendmodule");
let mut server = Session::over(&scratch);
let pristine = snapshot(&scratch.0);
let preview = server.ok(tool, dry(&arguments, true))["structuredContent"].clone();
assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty(), "{tool}: dry run wrote");
let result = server.ok(tool, dry(&arguments, false));
let said = server.text(tool, arguments.clone());
let written = snapshot(&scratch.0);
let reported = &result["structuredContent"];
let mut listed: Vec<String> = ["changed", "created"]
.iter()
.flat_map(|key| reported[*key].as_array().unwrap().clone())
.map(|entry| entry["file"].as_str().unwrap().to_string())
.collect();
listed.sort();
assert_eq!(moved(&pristine, &written), listed, "{tool} {arguments}: {result}");
for key in ["changed", "created"] {
for (real, shown) in
reported[key].as_array().unwrap().iter().zip(preview[key].as_array().unwrap())
{
let file = real["file"].as_str().unwrap();
let before = pristine.get(file).map(|(_, b)| b.clone()).unwrap_or_default();
let after = &written[file].1;
let diff = lucisv_core::diff::unified(
file,
std::str::from_utf8(&before).unwrap(),
std::str::from_utf8(after).unwrap(),
);
assert_eq!(shown["diff"].as_str().unwrap(), diff, "{tool}: {file}");
let (added, removed) = signed_lines(&diff);
assert_eq!(
(real["added"].as_u64(), real["removed"].as_u64()),
(Some(added as u64), Some(removed as u64)),
"{tool}: {file}"
);
}
assert_eq!(moved(&pristine, &written), expected, "{tool} {arguments}: {said}");
if tool == "rename" {
assert!(said.starts_with("renamed 4 sites in 3 files\n"), "{said}");
}
let again = server.call(tool, dry(&arguments, false));
// Not idempotent: the same insertion again would declare twice.
let again = server.call(tool, arguments.clone());
let said = text_of(&again);
assert!(
said.starts_with("unchanged") || again["isError"] == true,
"{tool}: a repeat must write nothing: {said}"
moved(&written, &snapshot(&scratch.0)).is_empty(),
"{tool}: the repeat wrote: {said}"
);
assert!(moved(&written, &snapshot(&scratch.0)).is_empty(), "{tool}: the repeat wrote");
}
}
@@ -539,44 +494,24 @@ fn qa_every_refusal_leaves_every_byte_and_mode_identical() {
let mut server = Session::over(&scratch);
let pristine = snapshot(&scratch.0);
let outside_pristine = snapshot(&outside.0);
let leaf_d = |new_name: &str| json!({"name": "d", "file": "rtl/leaf.sv", "new_name": new_name});
let refused = [
("rename", json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "module"})),
("rename", json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "clk"})),
("rename", json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "\\a+b "})),
("rename", leaf_d("module")),
("rename", leaf_d("clk")),
("rename", leaf_d("\\a+b ")),
("rename", json!({"name": "clk", "new_name": "ck"})),
("rename", json!({"file": "out/o.sv", "line": 1, "col": 8, "new_name": "p"})),
("expand_wildcard", json!({"file": "rtl/pos.sv", "line": 2})),
("convert_ports", json!({"file": "rtl/leaf.sv", "line": 1})),
("organize_imports", json!({"file": "rtl/leaf.sv", "line": 99})),
("inline_module", json!({"file": "rtl/pos.sv", "line": 2})),
("inline_module", json!({"file": "rtl/wild.sv", "line": 6})),
("propagate_ports", json!({"file": "rtl/mid.sv", "line": 6})),
("propagate_ports", json!({"file": "rtl/wild.sv", "line": 6})),
("remove_port", json!({"file": "rtl/cell.sv", "line": 3, "name": "en"})),
("remove_port", json!({"file": "rtl/pos.sv", "line": 1, "name": "en"})),
("add_port", json!({"module": "cell", "declaration": "input logic en"})),
("add_port", json!({"module": "cell", "declaration": "input logic newp"})),
(
"extract_module",
json!({"file": "rtl/ext.sv", "start_line": 1, "end_line": 2, "new_name": "x2"}),
),
(
"extract_module",
json!({"file": "rtl/ext.sv", "start_line": 7, "end_line": 7, "new_name": "leaf"}),
),
(
"extract_module",
json!({"file": "rtl/ext.sv", "start_line": 7, "end_line": 7, "new_name": "../x"}),
),
(
"extract_module",
json!({"file": "out/o.sv", "start_line": 1, "end_line": 1, "new_name": "x3"}),
),
("format", json!({"files": "fmt/messy.sv,fmt/broken.sv"})),
("format", json!({"file": "out/o.sv"})),
("format", json!({"file": "fmt/messy.sv", "lines": "3-1"})),
("fix_lint", json!({"file": "/etc/hosts"})),
("instantiate", json!({"name": "nothing_here"})),
("rename", json!({"name": "o", "file": "out/o.sv", "new_name": "p"})),
("port", json!({"module": "cell", "remove": "en"})),
("port", json!({"module": "pos", "remove": "en"})),
("port", json!({"module": "cell", "add": "input logic en"})),
("port", json!({"module": "cell", "add": "input logic newp"})),
("port", json!({"module": "leaf", "add": "input logic x", "after": "nope"})),
("edit_item", json!({"file": "rtl/leaf.sv", "op": "delete", "item": "leaf"})),
("edit_item", json!({"file": "out/o.sv", "op": "delete", "item": "o"})),
("format", json!({"files": "fmt/broken.sv"})),
("format", json!({"files": "out/o.sv"})),
("format", json!({"files": "/etc/hosts"})),
("format", json!({"files": "fpv/**/*.sv"})),
];
for (tool, arguments) in refused {
let said = server.refusal(tool, arguments.clone());
@@ -587,8 +522,8 @@ fn qa_every_refusal_leaves_every_byte_and_mode_identical() {
}
/// Comments beside every edited span survive: a port with a trailing
/// comment renamed, a `.*` with comments in its list expanded, a block with
/// a leading and a trailing comment extracted.
/// comment renamed, a `.*` with comments in its list written out by the
/// rename, a port placed after a commented one.
#[test]
fn qa_comments_around_every_edited_span_survive() {
let scratch = Scratch::with(&[
@@ -600,10 +535,6 @@ fn qa_comments_around_every_edited_span_survive() {
"top.sv",
"module top (\n input logic clk,\n input logic [7:0] d,\n output logic [7:0] q\n);\n // the instance\n leaf u_leaf (\n // leading\n .* // trailing star comment\n /* block */\n );\nendmodule\n",
),
(
"ext.sv",
"module ext (\n input logic clk,\n input logic [7:0] a,\n output logic [7:0] q\n);\n logic [7:0] s;\n // the adder\n assign s = a + 8'd1; // plus one\n always_ff @(posedge clk) q <= s;\nendmodule\n",
),
]);
let comments = [
"// the clock",
@@ -614,8 +545,6 @@ fn qa_comments_around_every_edited_span_survive() {
"// leading",
"// trailing star comment",
"/* block */",
"// the adder",
"// plus one",
];
let count = |scratch: &Scratch, comment: &str| -> usize {
snapshot(&scratch.0)
@@ -625,12 +554,8 @@ fn qa_comments_around_every_edited_span_survive() {
};
let before: Vec<usize> = comments.iter().map(|c| count(&scratch, c)).collect();
let mut server = Session::over(&scratch);
server.text("expand_wildcard", json!({"file": "top.sv", "line": 7}));
server.text(
"extract_module",
json!({"file": "ext.sv", "start_line": 7, "end_line": 8, "new_name": "adder"}),
);
server.text("rename", json!({"file": "leaf.sv", "line": 3, "name": "d", "new_name": "din"}));
server.text("rename", json!({"name": "d", "file": "leaf.sv", "new_name": "din"}));
server.text("port", json!({"module": "leaf", "add": "input logic en", "after": "clk"}));
let after: Vec<usize> = comments.iter().map(|c| count(&scratch, c)).collect();
assert_eq!(before, after, "{:?}", snapshot(&scratch.0).keys().collect::<Vec<_>>());
assert!(scratch.read("leaf.sv").contains("din, // data in"), "{}", scratch.read("leaf.sv"));
@@ -650,7 +575,7 @@ fn qa_a_rename_racing_a_writer_never_tears_a_file() {
let files = ["rtl/leaf.sv", "rtl/mid.sv", "rtl/top.sv"];
let target = "rtl/mid.sv";
let mut server = Session::over(&scratch);
let at = |from: &str, to: &str| json!({"file": "rtl/leaf.sv", "line": 3, "name": from, "new_name": to});
let at = |from: &str, to: &str| json!({"name": from, "file": "rtl/leaf.sv", "new_name": to});
let original: Vec<String> = files.iter().map(|f| scratch.read(f)).collect();
server.text("rename", at("d", "din_i"));
let renamed: Vec<String> = files.iter().map(|f| scratch.read(f)).collect();
@@ -704,36 +629,23 @@ fn qa_a_rename_racing_a_writer_never_tears_a_file() {
// ================================================ paths (attack 3)
#[test]
fn qa_created_and_rewritten_paths_never_leave_the_root() {
fn qa_rewritten_paths_never_leave_the_root() {
let scratch = Scratch::edit_fixture();
let outside = Scratch::with(&[("ext.sv", &Scratch::edit_fixture().read("rtl/ext.sv"))]);
std::os::unix::fs::symlink(&outside.0, scratch.path("link")).unwrap();
std::os::unix::fs::symlink(outside.path("adder.sv"), scratch.path("rtl/adder.sv")).unwrap();
let mut server = Session::over(&scratch);
let pristine = snapshot(&scratch.0);
let outside_pristine = snapshot(&outside.0);
let extract = |file: &str, name: &str| json!({"file": file, "start_line": 7, "end_line": 7, "new_name": name});
for name in ["../evil", "/tmp/evil", "\\../../evil ", "a/b", ""] {
let said = server.refusal("extract_module", extract("rtl/ext.sv", name));
assert!(!said.is_empty());
}
let said = server.refusal("extract_module", extract("link/ext.sv", "adder"));
assert!(said.contains("outside every root"), "{said}");
let abs = outside.path("ext.sv");
let said = server.refusal("extract_module", extract(abs.to_str().unwrap(), "adder"));
assert!(said.contains("outside every root"), "{said}");
// A dangling symlink at the created path, pointing out of the root.
let said = server.refusal("extract_module", extract("rtl/ext.sv", "adder"));
assert!(said.contains("adder.sv"), "{said}");
fs::remove_file(scratch.path("rtl/adder.sv")).unwrap();
fs::create_dir(scratch.path("rtl/adder.sv")).unwrap();
let said = server.refusal("extract_module", extract("rtl/ext.sv", "adder"));
assert!(said.contains("adder.sv"), "{said}");
fs::remove_dir(scratch.path("rtl/adder.sv")).unwrap();
std::os::unix::fs::symlink(outside.path("adder.sv"), scratch.path("rtl/adder.sv")).unwrap();
for file in ["link/ext.sv", abs.to_str().unwrap()] {
let delete = json!({"file": file, "op": "delete", "item": "s"});
assert!(server.refusal("edit_item", delete).contains("outside every root"));
assert!(server.refusal("format", json!({"files": file})).contains("outside every root"));
let rename = json!({"name": "s", "file": file, "new_name": "t"});
assert!(server.refusal("rename", rename).contains("outside every root"));
}
assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty());
assert!(moved(&outside_pristine, &snapshot(&outside.0)).is_empty());
assert!(!Path::new("/tmp/evil.sv").exists());
}
#[test]
@@ -742,19 +654,17 @@ fn qa_a_read_only_target_refuses_before_the_first_write() {
let scratch = Scratch::edit_fixture();
// `top.sv` sorts last of the rename's three files.
fs::set_permissions(scratch.path("rtl/top.sv"), fs::Permissions::from_mode(0o444)).unwrap();
// A trailing blank so `fix_lint` has something to write.
// A trailing blank so `fix` has something to write.
scratch.write("fmt/messy.sv", &scratch.read("fmt/messy.sv").replace("b=a;", "b=a; "));
fs::set_permissions(scratch.path("fmt/messy.sv"), fs::Permissions::from_mode(0o444)).unwrap();
let mut server = Session::over(&scratch);
let pristine = snapshot(&scratch.0);
let said = server.refusal(
"rename",
json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "din_i"}),
);
let said =
server.refusal("rename", json!({"name": "d", "file": "rtl/leaf.sv", "new_name": "din_i"}));
assert_eq!(said, "`rtl/top.sv` is read-only; nothing written.");
let said = server.refusal("format", json!({"files": "fmt/messy.sv"}));
assert_eq!(said, "`fmt/messy.sv` is read-only; nothing written.");
let said = server.refusal("fix_lint", json!({"file": "fmt/messy.sv"}));
let said = server.refusal("format", json!({"files": "fmt/messy.sv", "fix": true}));
assert_eq!(said, "`fmt/messy.sv` is read-only; nothing written.");
assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty());
}
@@ -764,10 +674,11 @@ fn qa_formatting_through_a_symlink_writes_the_file_and_keeps_the_link() {
let scratch = Scratch::with(&[("real.sv", "module r(input logic a);\nendmodule\n")]);
std::os::unix::fs::symlink("real.sv", scratch.path("alias.sv")).unwrap();
let mut server = Session::over(&scratch);
let text = server.text("format", json!({"files": "alias.sv,real.sv"}));
assert_eq!(text, "files: 1 changed, 0 created\n real.sv +1 -1\n");
let text = server.text("format", json!({"files": "alias.sv"}));
assert_eq!(text, "formatted 1 file (0 unchanged)\n");
assert!(fs::symlink_metadata(scratch.path("alias.sv")).unwrap().file_type().is_symlink());
assert_eq!(scratch.read("real.sv"), "module r (input logic a);\nendmodule\n");
assert_eq!(server.text("format", json!({"files": "*.sv"})), "formatted 1 file (1 unchanged)\n");
}
// ================================================ concurrency with the CLI (attack 4)
@@ -809,16 +720,15 @@ fn qa_lucisv_check_over_the_same_tree_while_the_server_formats() {
})
};
let mut server = Session::over(&scratch);
let files = names.join(",");
for _ in 0..5 {
for (name, text) in &messy {
scratch.write(name, text);
}
let result = server.call("format", json!({"files": files}));
let result = server.call("format", json!({"files": "m*.sv"}));
let said = text_of(&result);
assert!(result["isError"] == false || said.contains("changed on disk"), "{said}");
}
server.text("format", json!({"files": files}));
server.text("format", json!({"files": "m*.sv"}));
stop.store(true, Ordering::SeqCst);
let codes = checker.join().unwrap();
assert!(!codes.is_empty());
@@ -831,9 +741,7 @@ fn qa_lucisv_check_over_the_same_tree_while_the_server_formats() {
// ================================================ format (attack 5)
/// `format` writes what `lucisv` writes, byte for byte: a CRLF file, a file
/// under a nested lucisv.toml with a different line length, a fenced
/// region, and `lines` ranges that overlap, run backwards in order, or pass
/// the end.
/// under a nested lucisv.toml with a different line length, a fenced region.
#[test]
fn qa_format_writes_the_clis_bytes() {
let Some(cli) = cli() else {
@@ -850,7 +758,6 @@ fn qa_format_writes_the_clis_bytes() {
"fence.sv",
"module f(input logic a,output logic b);\n// lucisv: off\nassign b=a;\n// lucisv: on\nlogic c;\nendmodule\n",
),
("r.sv", "module r(input logic a,output logic b);\nlogic x;\nassign b=a;\nlogic y;\nendmodule\n"),
];
let mcp = Scratch::with(files);
let mut server = Session::over(&mcp);
@@ -858,50 +765,33 @@ fn qa_format_writes_the_clis_bytes() {
let cli_tree = Scratch::with(files);
let out = Command::new(&cli).arg("--no-cache").arg(cli_tree.path(file)).output().unwrap();
assert!(out.status.success(), "{out:?}");
server.text("format", json!({"file": file}));
server.text("format", json!({"files": file}));
assert_eq!(mcp.read(file), cli_tree.read(file), "{file}");
}
for lines in ["2,1-2,99", "4,2", "4-4,2-2", "50-60", "1-999"] {
let cli_tree = Scratch::with(files);
let out = Command::new(&cli)
.args(["--no-cache", "--lines", lines])
.arg(cli_tree.path("r.sv"))
.output()
.unwrap();
assert!(out.status.success(), "{lines}: {out:?}");
mcp.write("r.sv", files[5].1);
server.text("format", json!({"file": "r.sv", "lines": lines}));
assert_eq!(mcp.read("r.sv"), cli_tree.read("r.sv"), "lines {lines}");
}
// A duplicate in `files` is one file, written once.
mcp.write("w.sv", long);
let text = server.text("format", json!({"files": "w.sv, w.sv,./w.sv", "dry_run": true}));
assert_eq!(text.matches("--- w.sv\n").count(), 1, "{text}");
}
// ================================================ fix_lint (attack 1, 5)
// ================================================ fix (attack 1, 5)
/// `fix_lint` writes what `lucisv check --fix` writes: nothing inside a
/// `// lucisv: off` or `// verilog_format: off` fence, and never the
/// unsafe `always-comb` fix, even when that rule is the only one asked for.
/// `format` with `fix` writes what `lucisv check --fix` then `lucisv`
/// write: nothing inside a `// lucisv: off` or `// verilog_format: off`
/// fence, and never the unsafe `always-comb` fix.
#[test]
fn qa_fix_lint_matches_check_fix_and_never_touches_a_fence_or_an_unsafe_fix() {
fn qa_fix_matches_check_fix_and_never_touches_a_fence_or_an_unsafe_fix() {
let source = "module f (input logic a, output logic b, output logic c);\n\tlogic t; \n // lucisv: off \n assign b = a;; \n\tassign t = a;\n // lucisv: on\n always @* c = a;\n assign t2 = 4'b1;;\n // verilog_format: off\n wire z;; \n // verilog_format: on\nendmodule";
let scratch = Scratch::with(&[("f.sv", source)]);
let mut server = Session::over(&scratch);
let unsafe_only = server.text("fix_lint", json!({"file": "f.sv", "rules": "always-comb"}));
assert!(unsafe_only.starts_with("unchanged\n"), "{unsafe_only}");
assert_eq!(scratch.read("f.sv"), source);
server.text("fix_lint", json!({"file": "f.sv"}));
server.text("format", json!({"files": "f.sv", "fix": true}));
let fixed = scratch.read("f.sv");
for fenced in [" // lucisv: off \n assign b = a;; \n\tassign t = a;\n", " wire z;; \n"]
{
assert!(fixed.contains(fenced), "a fenced line moved: {fixed:?}");
}
assert!(fixed.contains("always @* c = a;"), "an unsafe fix was applied: {fixed:?}");
assert!(!fixed.contains("always_comb"), "an unsafe fix was applied: {fixed:?}");
assert!(!fixed.contains("4'b1;;"), "the safe fix was not applied: {fixed:?}");
if let Some(cli) = cli() {
let cli_tree = Scratch::with(&[("f.sv", source)]);
Command::new(&cli).args(["check", "--fix"]).arg(cli_tree.path("f.sv")).output().unwrap();
Command::new(&cli).arg("--no-cache").arg(cli_tree.path("f.sv")).output().unwrap();
assert_eq!(fixed, cli_tree.read("f.sv"));
}
}
@@ -938,7 +828,7 @@ fn qa_rename_writes_exactly_what_the_engine_answers_over_all_files() {
assert_eq!(expected.len(), 3);
let mut server = Session::over(&scratch);
let pristine = snapshot(&scratch.0);
server.text("rename", json!({"name": "d", "unit": "leaf", "new_name": "din_i"}));
server.text("rename", json!({"name": "d", "file": "rtl/leaf.sv", "new_name": "din_i"}));
let written: Vec<String> = moved(&pristine, &snapshot(&scratch.0));
assert_eq!(written, expected.keys().cloned().collect::<Vec<_>>());
for (file, text) in &expected {
@@ -947,31 +837,25 @@ fn qa_rename_writes_exactly_what_the_engine_answers_over_all_files() {
}
#[test]
fn qa_rename_by_bare_name_picks_the_declaration_references_picks() {
fn qa_rename_by_name_writes_the_files_find_lists() {
let scratch = Scratch::edit_fixture();
let mut server = Session::over(&scratch);
let refs = server.ok("references", json!({"name": "din"}))["structuredContent"].clone();
let mut hit_files: Vec<String> = refs["hits"]
.as_array()
.unwrap()
.iter()
.map(|h| h["file"].as_str().unwrap().to_string())
let found = server.text("find", json!({"name": "din", "refs": true}));
let mut files: Vec<String> = found
.lines()
.map(|line| line.trim().rsplit(' ').next().unwrap().split(':').next().unwrap().to_string())
.collect();
hit_files.dedup();
let preview = server.ok("rename", json!({"name": "din", "new_name": "d_in", "dry_run": true}));
let files: Vec<String> = preview["structuredContent"]["changed"]
.as_array()
.unwrap()
.iter()
.map(|c| c["file"].as_str().unwrap().to_string())
.collect();
assert_eq!(files, hit_files);
files.sort();
files.dedup();
let pristine = snapshot(&scratch.0);
server.text("rename", json!({"name": "din", "new_name": "d_in"}));
assert_eq!(moved(&pristine, &snapshot(&scratch.0)), files, "{found}");
// Ambiguous: refused, listing every site.
let said = server.refusal("rename", json!({"name": "q", "new_name": "qq"}));
for site in ["rtl/ext.sv:4", "rtl/leaf.sv:4"] {
assert!(said.contains(site), "{said}");
}
assert!(said.contains("pick one"), "{said}");
assert!(said.contains("pass `file`"), "{said}");
}
#[test]
@@ -984,19 +868,17 @@ fn qa_rename_surfaces_the_engines_macro_warning() {
),
]);
let mut server = Session::over(&scratch);
let text = server.text(
"rename",
json!({"file": "m.sv", "line": 2, "name": "sig_a", "new_name": "sig_b", "dry_run": true}),
);
assert!(text.contains("warnings:\n `sig_a` appears in the arguments of the macro"), "{text}");
let text = server.text("rename", json!({"name": "sig_a", "new_name": "sig_b"}));
assert!(text.contains("\nwarning: `sig_a` appears in the arguments of the macro"), "{text}");
assert!(text.ends_with("unresolved:\n m.sv:3\n"), "{text}");
}
// ================================================ findings
/// Finding 1 (blocking, engine): renaming a port bound by an implicit
/// connection (`.*` or `.name`), or a net such a connection binds, writes a
/// "verified" edit that silently changes the connectivity. It must refuse
/// (or rewrite the connection explicitly) — never leave the binding broken.
/// connection (`.*` or `.name`), or a net such a connection binds, must
/// refuse or rewrite the connection explicitly — never leave the binding
/// broken (M3.5).
#[test]
fn qa_rename_never_breaks_an_implicit_port_connection() {
let files: &[(&str, &str)] = &[
@@ -1015,11 +897,11 @@ fn qa_rename_never_breaks_an_implicit_port_connection() {
];
let cases = [
// The port: `.*` in top.sv and `.d` in top2.sv stop binding it.
json!({"file": "leaf.sv", "line": 1, "name": "d", "new_name": "din"}),
json!({"name": "d", "file": "leaf.sv", "new_name": "din"}),
// The net `.*` binds.
json!({"file": "top.sv", "line": 1, "name": "d", "new_name": "x"}),
json!({"name": "d", "file": "top.sv", "new_name": "x"}),
// The net `.d` binds.
json!({"file": "top2.sv", "line": 1, "name": "d", "new_name": "x"}),
json!({"name": "d", "file": "top2.sv", "new_name": "x"}),
];
for arguments in cases {
let scratch = Scratch::with(files);
@@ -1041,9 +923,8 @@ fn qa_rename_never_breaks_an_implicit_port_connection() {
}
}
/// Finding 2 (blocking): a rename leaves unrenamed every use in a file the
/// index skipped (over 1 MiB, or not UTF-8) and reports success without a
/// word. It must refuse, or at least name the file it could not read.
/// Finding 2 (blocking): a rename must not leave unrenamed a use in a file
/// the index skipped (over 1 MiB, or not UTF-8) without a word.
#[test]
fn qa_rename_says_so_when_a_skipped_file_mentions_the_name() {
let filler: String = (0..12_000)
@@ -1060,8 +941,7 @@ fn qa_rename_says_so_when_a_skipped_file_mentions_the_name() {
);
fs::write(scratch.path("rtl/mid2.sv"), latin1).unwrap();
let mut server = Session::over(&scratch);
let result = server
.call("rename", json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "din_i"}));
let result = server.rename_d();
let said = text_of(&result);
assert!(
result["isError"] == true || (said.contains("rtl/big.sv") && said.contains("rtl/mid2.sv")),
@@ -1069,52 +949,23 @@ fn qa_rename_says_so_when_a_skipped_file_mentions_the_name() {
);
}
/// Finding 3 (non-blocking, engine): `extract_module` into a CRLF file
/// writes its instantiation with LF line endings, leaving the file mixed.
/// Finding 4 (lead's ruling: no change), kept for the flags that remain:
/// JSON null is "not given" for every argument; `"true"` and `1` are
/// refused as non-booleans.
#[test]
#[ignore = "QA finding 3: engine-side, Handshake MCP-10 to vlog_refactor"]
fn qa_extract_module_keeps_a_crlf_file_crlf() {
let scratch = Scratch::edit_fixture();
let crlf = scratch.read("rtl/ext.sv").replace('\n', "\r\n");
scratch.write("rtl/ext.sv", &crlf);
let mut server = Session::over(&scratch);
server.text(
"extract_module",
json!({"file": "rtl/ext.sv", "start_line": 7, "end_line": 7, "new_name": "adder"}),
);
let ext = scratch.read("rtl/ext.sv");
let bare = ext.split_inclusive('\n').filter(|line| !line.ends_with("\r\n")).count();
assert_eq!(bare, 0, "{ext:?}");
}
/// Finding 4 (non-blocking, lead's ruling: no change): `"dry_run": null`
/// means absent — JSON null is "not given" for every argument — so the edit
/// is written; `"true"` and `1` are refused as non-booleans.
#[test]
fn qa_a_null_dry_run_is_absent_and_a_non_boolean_is_refused() {
fn qa_a_null_flag_is_absent_and_a_non_boolean_is_refused() {
let scratch = Scratch::edit_fixture();
let mut server = Session::over(&scratch);
let pristine = snapshot(&scratch.0);
for not_boolean in [json!("true"), json!(1)] {
let arguments = json!({"file": "fmt/messy.sv", "dry_run": not_boolean});
let arguments = json!({"files": "fmt/messy.sv", "fix": not_boolean});
server.refusal("format", arguments);
assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty());
}
let result = server.call("format", json!({"file": "fmt/messy.sv", "dry_run": null}));
let result = server.call("format", json!({"files": "fmt/messy.sv", "fix": null}));
assert_eq!(moved(&pristine, &snapshot(&scratch.0)), ["fmt/messy.sv"], "{}", text_of(&result));
}
/// Finding 5 (non-blocking): `instantiate` takes any `instance` string, so
/// an empty or non-identifier name renders text that does not parse.
#[test]
fn qa_instantiate_refuses_an_instance_name_that_is_not_an_identifier() {
let scratch = Scratch::edit_fixture();
let mut server = Session::over(&scratch);
for instance in ["", "a b", "u_x); evil (", "module"] {
server.refusal("instantiate", json!({"name": "leaf", "instance": instance}));
}
}
// ================================================ re-check, 2026-09-23 (finding 2's rework)
/// A 1.1 MB file: `module big` with `line` before `endmodule`.
@@ -1132,7 +983,12 @@ fn latin1(body: &[u8]) -> Vec<u8> {
bytes
}
const RENAME_D: fn(bool) -> Value = |dry_run| json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "din_i", "dry_run": dry_run});
impl Session {
/// A rename of `leaf`'s port `d` to `din_i`.
fn rename_d(&mut self) -> Value {
self.call("rename", json!({"name": "d", "file": "rtl/leaf.sv", "new_name": "din_i"}))
}
}
#[test]
fn qa_recheck_a_skipped_file_spelling_the_name_refuses_naming_file_and_reason() {
@@ -1146,13 +1002,12 @@ fn qa_recheck_a_skipped_file_spelling_the_name_refuses_naming_file_and_reason()
fs::write(scratch.path(file), &bytes).unwrap();
let mut server = Session::over(&scratch);
let pristine = snapshot(&scratch.0);
for dry_run in [true, false] {
let said = server.refusal("rename", RENAME_D(dry_run));
assert_eq!(
said,
format!("`{file}` (skipped: {why}) may reference `d`; lucisv-mcp will not edit around a file it cannot index; nothing written.")
);
}
let result = server.rename_d();
assert_eq!(result["isError"], true, "{result}");
assert_eq!(
text_of(&result),
format!("`{file}` (skipped: {why}) may reference `d`; lucisv-mcp will not edit around a file it cannot index; nothing written.")
);
assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty(), "{file}");
}
}
@@ -1171,8 +1026,9 @@ fn qa_recheck_a_substring_only_is_written_with_the_skipped_file_named() {
fs::write(scratch.path(file), &bytes).unwrap();
let mut server = Session::over(&scratch);
let pristine = snapshot(&scratch.0);
let text = server.text("rename", RENAME_D(false));
let line = format!("warnings:\n not indexed, so not searched or edited: {file} ({why})\n");
let result = server.rename_d();
let text = text_of(&result);
let line = format!("warning: not indexed, so not searched or edited: {file} ({why})\n");
assert!(text.contains(&line), "{text}");
assert_eq!(text.matches("not indexed").count(), 1, "{text}");
let written = moved(&pristine, &snapshot(&scratch.0));
@@ -1198,14 +1054,14 @@ fn qa_recheck_the_whole_word_rule_holds_at_every_edge() {
let scratch = Scratch::edit_fixture();
fs::write(scratch.path("rtl/lat.sv"), bytes).unwrap();
let mut server = Session::over(&scratch);
let said = server.refusal("rename", RENAME_D(true));
let said = text_of(&server.rename_d());
assert!(said.starts_with("`rtl/lat.sv` (skipped: not UTF-8 text)"), "{bytes:?}: {said}");
}
let mut at_end = oversized("").into_bytes();
at_end.extend_from_slice(b"d");
let scratch = Scratch::edit_fixture();
fs::write(scratch.path("rtl/big.sv"), at_end).unwrap();
let said = Session::over(&scratch).refusal("rename", RENAME_D(true));
let said = text_of(&Session::over(&scratch).rename_d());
assert!(said.starts_with("`rtl/big.sv` (skipped: over 1 MiB)"), "{said}");
}
@@ -1215,8 +1071,7 @@ fn qa_recheck_the_whole_word_rule_holds_at_every_edge() {
#[test]
fn qa_recheck_an_escaped_name_is_guarded_by_its_escaped_spelling() {
let esc = "module esc (input logic \\a+b , output logic y);\n assign y = \\a+b ;\nendmodule\n";
let rename =
json!({"file": "rtl/esc.sv", "line": 2, "col": 14, "new_name": "ab", "dry_run": true});
let rename = json!({"name": "\\a+b", "file": "rtl/esc.sv", "new_name": "ab"});
let cases: [(&[u8], bool); 5] = [
(b"\\a+b\t", true),
(b"x = \\a+b\n;", true),
@@ -1238,9 +1093,9 @@ fn qa_recheck_an_escaped_name_is_guarded_by_its_escaped_spelling() {
}
}
/// Every whole-set edit tool refuses over its stake (the README's table)
/// when only a skipped file spells it; `organize_imports`, which stakes
/// nothing, writes and names the skipped file.
/// Every whole-set edit refuses over its stake when only a skipped file
/// spells it; a rename of a name the skipped file does not spell writes and
/// names the skipped file.
#[test]
fn qa_recheck_every_edit_tool_refuses_over_its_stake() {
let scratch = Scratch::edit_fixture();
@@ -1250,22 +1105,10 @@ fn qa_recheck_every_edit_tool_refuses_over_its_stake() {
let mut server = Session::over(&scratch);
let pristine = snapshot(&scratch.0);
let staked = [
("expand_wildcard", json!({"file": "rtl/wild.sv", "line": 6}), "cell"),
("propagate_ports", json!({"file": "rtl/partial.sv", "line": 6}), "cell"),
("inline_module", json!({"file": "rtl/inl.sv", "line": 5}), "inv"),
("convert_ports", json!({"file": "rtl/old.sv", "line": 1}), "old"),
("remove_port", json!({"file": "rtl/spare.sv", "line": 3, "name": "unused_i"}), "spare"),
("add_port", json!({"module": "cell", "declaration": "input logic x_i"}), "cell"),
(
"add_port",
json!({"file": "rtl/cell.sv", "line": 2, "declaration": "input logic x_i"}),
"cell",
),
(
"extract_module",
json!({"file": "rtl/ext.sv", "start_line": 7, "end_line": 7, "new_name": "adder"}),
"ext",
),
("port", json!({"module": "cell", "add": "input logic x_i"}), "cell"),
("port", json!({"module": "spare", "remove": "unused_i"}), "spare"),
("rename", json!({"name": "inv", "new_name": "inv2"}), "inv"),
("rename", json!({"name": "old", "new_name": "old2"}), "old"),
];
for (tool, arguments, name) in staked {
let said = server.refusal(tool, arguments.clone());
@@ -1273,95 +1116,88 @@ fn qa_recheck_every_edit_tool_refuses_over_its_stake() {
assert!(said.starts_with(&expected), "{tool} {arguments}: {said}");
assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty(), "{tool}");
}
let text = server.text("organize_imports", json!({"file": "rtl/top.sv", "line": 6}));
let text = server.text("rename", json!({"name": "unused_i", "new_name": "spare_i"}));
assert!(text.contains("not indexed, so not searched or edited: rtl/lat.sv"), "{text}");
}
/// A skipped file that is rewritten small and UTF-8 is searched once the
/// next walk sees it (until then the edit stays refused — the safe side);
/// an indexed file that stops being UTF-8 is refused on the very next call.
/// A skipped file that is rewritten small and UTF-8 is searched at once
/// (every edit walks first); an indexed file that stops being UTF-8 is
/// refused on the very next call.
#[test]
fn qa_recheck_a_file_leaving_or_entering_the_skipped_set_is_followed() {
let use_d = " leaf u_l (.clk(clk), .d(x), .q(y));\n";
let scratch = Scratch::edit_fixture();
scratch.write("rtl/big.sv", &oversized(use_d));
let mut server = Session::over(&scratch);
assert!(server.refusal("rename", RENAME_D(true)).starts_with("`rtl/big.sv`"));
assert!(text_of(&server.rename_d()).starts_with("`rtl/big.sv`"));
scratch.write("rtl/big.sv", &format!("module big (input logic clk);\n{use_d}endmodule\n"));
let soon = server.call("rename", RENAME_D(true));
assert!(soon["isError"] == true || text_of(&soon).contains("--- rtl/big.sv"), "{soon}");
std::thread::sleep(Duration::from_millis(5_500));
let later = server.text("rename", RENAME_D(true));
assert!(later.contains("--- rtl/big.sv\n"), "{later}");
assert!(!later.contains("not indexed"), "{later}");
let written = server.rename_d();
assert_eq!(written["isError"], false, "{written}");
assert!(!text_of(&written).contains("not indexed"), "{written}");
assert!(scratch.read("rtl/big.sv").contains(".din_i(x)"));
// The other way: `mid.sv` gains a Latin-1 byte.
let mid = scratch.read("rtl/mid.sv");
fs::write(scratch.path("rtl/mid.sv"), latin1(mid.as_bytes())).unwrap();
let said = server.refusal("rename", RENAME_D(true));
assert!(said.starts_with("`rtl/mid.sv` (skipped: not UTF-8 text) may reference `d`"), "{said}");
let back = json!({"name": "din_i", "file": "rtl/leaf.sv", "new_name": "d"});
let said = server.refusal("rename", back);
assert!(
said.starts_with("`rtl/mid.sv` (skipped: not UTF-8 text) may reference `din_i`"),
"{said}"
);
}
/// The merge of `edit.rs::sources` and `nav.rs::all_files` into
/// `WholeSet::read` left `references` alone: at every identifier of the nav
/// fixture, adding a skipped file that spells nothing changes the answer
/// only by the one trailing warning line.
/// `find`'s answers over a tree with a skipped file that spells nothing
/// differ from the plain tree's only by the one trailing warning line, for
/// every name the nav fixture spells.
#[test]
fn qa_recheck_references_answers_only_gain_the_warning_line() {
fn qa_recheck_find_answers_only_gain_the_warning_line() {
let nav = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/nav");
let (plain, partial) = (Scratch::empty(), Scratch::empty());
copy_tree(&nav, &plain.0);
copy_tree(&nav, &partial.0);
fs::write(partial.path("rtl/zz.sv"), latin1(b"\xa9\xa9\n")).unwrap();
let (mut a, mut b) = (Session::over(&plain), Session::over(&partial));
let warning = "not indexed, so not searched or edited: rtl/zz.sv (not UTF-8 text)";
let mut answered = 0;
let warning = "warning: not indexed, so not searched or edited: rtl/zz.sv (not UTF-8 text)\n";
let mut words: Vec<String> = Vec::new();
for (file, (_, bytes)) in snapshot(&plain.0) {
if !file.ends_with(".sv") && !file.ends_with(".svh") {
continue;
}
let text = String::from_utf8(bytes).unwrap();
for (i, line) in text.lines().enumerate() {
let bytes = line.as_bytes();
for col in 0..bytes.len() {
let starts = (bytes[col].is_ascii_alphabetic() || bytes[col] == b'_')
&& (col == 0
|| !(bytes[col - 1].is_ascii_alphanumeric() || bytes[col - 1] == b'_'));
if !starts {
continue;
}
let args = json!({"file": file, "line": i + 1, "col": col + 1});
let (x, mut y) =
(a.call("references", args.clone()), b.call("references", args.clone()));
if x["isError"] == true {
assert_eq!(x, y, "{args}");
continue;
}
answered += 1;
assert_eq!(text_of(&y), format!("{}warning: {warning}\n", text_of(&x)), "{args}");
assert_eq!(y["structuredContent"]["warning"], warning, "{args}");
y["structuredContent"].as_object_mut().unwrap().remove("warning");
assert_eq!(x["structuredContent"], y["structuredContent"], "{args}");
}
if file.ends_with(".sv") || file.ends_with(".svh") {
let text = String::from_utf8(bytes).unwrap();
let spelled = text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'));
words.extend(
spelled
.filter(|w| w.starts_with(|c: char| c.is_ascii_alphabetic()))
.map(String::from),
);
}
}
assert!(answered > 50, "{answered}");
words.sort();
words.dedup();
let mut answered = 0;
for word in words {
let args = json!({"name": word, "refs": true});
let (x, y) = (a.call("find", args.clone()), b.call("find", args.clone()));
if x["isError"] == true {
assert_eq!(x, y, "{args}");
continue;
}
answered += 1;
assert_eq!(text_of(&y), format!("{}{warning}", text_of(&x)), "{args}");
}
assert!(answered > 20, "{answered}");
}
/// Finding 6 (blocking): the whole set is "every indexed file", and the
/// index sees a file created since the last walk only after `REWALK_AFTER`
/// (5 s) — the edit tools do not walk (`rewalk: false`). A rename right
/// after an agent writes a new instantiation leaves it unrenamed and says
/// nothing; a new over-1 MiB file escapes the skipped-file guard the same way.
/// Finding 6 (blocking): an edit sees a file created just before it — every
/// edit tool walks first (`rewalk: true`).
#[test]
fn qa_an_edit_sees_a_file_created_just_before_it() {
let scratch = Scratch::edit_fixture();
let mut server = Session::over(&scratch);
server.text("rename", RENAME_D(true));
server.text("find", json!({"name": "leaf"}));
scratch.write(
"rtl/newer.sv",
"module newer (input logic clk, input logic [7:0] x, output logic [7:0] y);\n leaf u_l (.clk(clk), .d(x), .q(y));\nendmodule\n",
);
let result = server.call("rename", RENAME_D(false));
let result = server.rename_d();
let newer = scratch.read("rtl/newer.sv");
assert!(
result["isError"] == true || newer.contains(".din_i(x)"),
@@ -1371,11 +1207,7 @@ fn qa_an_edit_sees_a_file_created_just_before_it() {
}
/// Finding 7 (non-blocking): an over-1 MiB file reached through a symlink
/// leading out of the root is recorded as skipped (`project/files.rs`, the
/// size-cap branch skips the containment check the indexed branch makes),
/// so it refuses edits inside the root and the refusal prints its absolute
/// path outside the root. A small file behind the same kind of link is
/// dropped, as M1 rules; the large one should be too.
/// leading out of the root is not in the skipped set.
#[test]
fn qa_a_large_file_behind_a_link_out_of_the_root_is_not_in_the_skipped_set() {
let scratch = Scratch::edit_fixture();
@@ -1383,6 +1215,6 @@ fn qa_a_large_file_behind_a_link_out_of_the_root_is_not_in_the_skipped_set() {
outside.write("big.sv", &oversized(" leaf u_l (.clk(clk), .d(x), .q(y));\n"));
std::os::unix::fs::symlink(outside.path("big.sv"), scratch.path("rtl/big_link.sv")).unwrap();
let mut server = Session::over(&scratch);
let text = server.text("rename", RENAME_D(true));
let text = text_of(&server.rename_d());
assert!(!text.contains(outside.root()), "{text}");
}
File diff suppressed because it is too large. Load diff
+683
View File
@@ -0,0 +1,683 @@
//! QA attacks on lane M6 (the index caches and the rule-6 ruling),
//! 2026-09-23.
//!
//! Every test spawns the real binary over a scratch copy of the `design`
//! fixture with `--index-cache` pointing at a scratch directory, as a host
//! would. The wrong-record hunt comes first: a record may only ever stand in
//! for the parse of exactly the bytes it was read from, so every store below
//! that is not exactly right must cost a parse — never an answer — and the
//! language server's store must be left byte-identical.
//!
//! A test that pins a QA finding asserts the *correct* behaviour and is
//! `#[ignore = "QA finding N"]` until a rework flips it; the findings are
//! numbered as in the QA log of `docs/features/mcp-cache-and-census/README.md`.
use std::fs;
use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdout, Command, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, SystemTime};
use lucisv_core::cache::content_hash;
use serde_json::{json, Value};
use vlog_semantic::{FileFacts, FACTS_FORMAT};
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
/// The design fixture's file count.
const FILES: usize = 7;
const VERSION: &str = env!("CARGO_PKG_VERSION");
/// A fresh copy of `tests/fixtures/design` under `<dir>/src`, and `<dir>/cache`
/// (not created) for the stores; removed on drop.
struct Scratch(PathBuf);
impl Scratch {
fn new() -> Scratch {
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
let dir =
std::env::temp_dir().join(format!("lucisv-mcp-qa-m6-{}-{unique}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/design");
copy_tree(&source, &dir.join("src"));
Scratch(fs::canonicalize(dir).unwrap())
}
fn src(&self) -> PathBuf {
self.0.join("src")
}
fn file(&self, rel: &str) -> PathBuf {
self.src().join(rel)
}
fn cache(&self) -> PathBuf {
self.0.join("cache")
}
fn editor_store(&self) -> PathBuf {
self.cache().join("index-cache")
}
fn own_store(&self) -> PathBuf {
self.cache().join("index-cache-mcp")
}
/// Write the language server's store from `lines`, one per line, with a
/// final newline.
fn write_editor_store(&self, lines: &[String]) {
fs::create_dir_all(self.cache()).unwrap();
fs::write(self.editor_store(), lines.join("\n") + "\n").unwrap();
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn copy_tree(from: &Path, to: &Path) {
fs::create_dir_all(to).unwrap();
for entry in fs::read_dir(from).unwrap() {
let entry = entry.unwrap();
let target = to.join(entry.file_name());
if entry.file_type().unwrap().is_dir() {
copy_tree(&entry.path(), &target);
} else {
fs::copy(entry.path(), target).unwrap();
}
}
}
/// Every file under `dir`, sorted.
fn files(dir: &Path) -> Vec<PathBuf> {
let mut out = Vec::new();
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
out.extend(files(&path));
} else {
out.push(path);
}
}
out.sort();
out
}
fn header() -> String {
format!("lucisv-index-cache\t2\t{FACTS_FORMAT}\t{VERSION}")
}
/// The encoded facts `path` would have if its bytes were `text`.
fn facts_of(path: &Path, text: &str) -> String {
FileFacts::of(path.to_path_buf(), text).encode().unwrap()
}
/// One record line with a *valid* checksum: `content` as the hash field,
/// `facts` as the record — whatever they describe.
fn line(content: u64, facts: &str) -> String {
format!("{content:016x}\t{facts}\t{:016x}", content_hash(facts.as_bytes()))
}
/// The honest record of `path` as it is on disk.
fn record(path: &Path) -> String {
let bytes = fs::read(path).unwrap();
line(content_hash(&bytes), &facts_of(path, std::str::from_utf8(&bytes).unwrap()))
}
/// The honest store over every source file.
fn honest_store(scratch: &Scratch) -> Vec<String> {
let mut lines = vec![header()];
lines.extend(files(&scratch.src()).iter().map(|path| record(path)));
lines
}
/// One server over the scratch design.
struct Session {
child: Child,
next_id: i64,
stdout: BufReader<ChildStdout>,
}
impl Session {
/// With `--index-cache cache` when given.
fn start(scratch: &Scratch, cache: Option<&Path>) -> Session {
let mut command = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"));
command.arg("--root").arg(scratch.src());
if let Some(cache) = cache {
command.arg("--index-cache").arg(cache);
}
let mut child = command
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let stdout = BufReader::new(child.stdout.take().unwrap());
let mut session = Session { child, next_id: 0, stdout };
session.request("initialize", json!({"protocolVersion": "2025-06-18"}));
session
}
/// The usual shape: `--index-cache <scratch>/cache`.
fn cached(scratch: &Scratch) -> Session {
Session::start(scratch, Some(&scratch.cache()))
}
fn request(&mut self, method: &str, params: Value) -> Value {
self.next_id += 1;
let line =
json!({"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params});
let stdin = self.child.stdin.as_mut().unwrap();
writeln!(stdin, "{line}").unwrap();
stdin.flush().unwrap();
let mut answer = String::new();
self.stdout.read_line(&mut answer).unwrap();
serde_json::from_str(&answer).unwrap()
}
/// A tool call's whole result (success or refusal).
fn call(&mut self, tool: &str, arguments: Value) -> Value {
self.request("tools/call", json!({"name": tool, "arguments": arguments}))["result"].clone()
}
/// A tool call that must succeed: its text.
fn text(&mut self, tool: &str, arguments: Value) -> String {
let result = self.call(tool, arguments);
assert_eq!(result["isError"], false, "{tool}: {result}");
result["content"][0]["text"].as_str().unwrap().to_string()
}
/// Close stdin, as a host does; everything said on stderr.
fn end(mut self) -> String {
drop(self.child.stdin.take());
let status = self.child.wait().unwrap();
assert!(status.success(), "{status}");
let mut stderr = String::new();
self.child.stderr.take().unwrap().read_to_string(&mut stderr).unwrap();
stderr
}
}
/// Whether `find` knows a declaration of `name`.
fn declared(session: &mut Session, name: &str) -> bool {
session.call("find", json!({"name": name}))["isError"] == false
}
/// The startup line's tail for `E` editor and `O` own hits.
fn reused(editor: usize, own: usize) -> String {
format!(" ms ({editor} from the editor's cache, {own} from its own)\n")
}
/// A session that asks what the tests below check the index with; its
/// answers and stderr.
fn probe(scratch: &Scratch, cache: Option<&Path>) -> (Vec<String>, String) {
let mut session = Session::start(scratch, cache);
let answers = [
("hierarchy", json!({})),
("outline", json!({"unit": "leaf"})),
("outline", json!({"unit": "top"})),
("outline", json!({"file": "rtl/top.sv"})),
("outline", json!({"file": "rtl/leaf.sv"})),
("find", json!({"name": "word_t"})),
("find", json!({"name": "leaf", "refs": true})),
("hierarchy", json!({"root": "top", "depth": 3})),
("check", json!({})),
]
.into_iter()
.map(|(tool, args)| session.text(tool, args))
.collect();
(answers, session.end())
}
fn hash_file(path: &Path) -> u64 {
content_hash(&fs::read(path).unwrap())
}
/// Everything the store's owner could notice changed: bytes, mtime, mode.
#[cfg(unix)]
fn fingerprint(path: &Path) -> (u64, SystemTime, u32) {
use std::os::unix::fs::PermissionsExt;
let meta = fs::metadata(path).unwrap();
(hash_file(path), meta.modified().unwrap(), meta.permissions().mode())
}
/// Temporary files left in `dir`.
fn temp_files(dir: &Path) -> Vec<String> {
fs::read_dir(dir)
.unwrap()
.map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
.filter(|name| name.ends_with(".tmp"))
.collect()
}
// ---------------------------------------------------------------------------
// 1. The wrong-record hunt.
// ---------------------------------------------------------------------------
/// Two records' facts swapped, each checksum recomputed so every line is
/// valid: the record under `leaf.sv`'s hash now describes `top.sv` and the
/// other way round. The store is keyed by the path *inside* the facts, so
/// each lands under (other path, this hash) and matches no file: both are
/// parsed, and the answers are the cold ones.
#[test]
fn qa_swapped_records_with_valid_checksums_are_never_served() {
let scratch = Scratch::new();
let (cold, _) = probe(&scratch, None);
let (leaf, top) = (scratch.file("rtl/leaf.sv"), scratch.file("rtl/top.sv"));
let text = |path: &Path| fs::read_to_string(path).unwrap();
let mut lines = vec![header()];
for path in files(&scratch.src()) {
if path != leaf && path != top {
lines.push(record(&path));
}
}
lines.push(line(hash_file(&leaf), &facts_of(&top, &text(&top))));
lines.push(line(hash_file(&top), &facts_of(&leaf, &text(&leaf))));
scratch.write_editor_store(&lines);
let (warm, stderr) = probe(&scratch, Some(&scratch.cache()));
assert!(stderr.contains(&reused(FILES - 2, 0)), "{stderr}");
assert_eq!(warm, cold, "the answers are a cold start's");
}
/// Records for a file that no longer exists and for one outside every root
/// (it exists, beside the root): neither module is indexed, and neither
/// record survives into the store this server writes.
#[test]
fn qa_records_for_gone_files_or_outside_the_roots_are_not_indexed_nor_kept() {
let scratch = Scratch::new();
let outside = scratch.0.join("outside.sv");
fs::write(&outside, "module outside_root; endmodule\n").unwrap();
let ghost = scratch.file("rtl/ghost.sv");
let ghost_text = "module ghost_unit; endmodule\n";
let mut lines = honest_store(&scratch);
lines.push(record(&outside));
lines.push(line(content_hash(ghost_text.as_bytes()), &facts_of(&ghost, ghost_text)));
scratch.write_editor_store(&lines);
let mut session = Session::cached(&scratch);
assert!(!declared(&mut session, "outside_root") && !declared(&mut session, "ghost_unit"));
let stderr = session.end();
assert!(stderr.contains(&reused(FILES, 0)), "{stderr}");
let own = fs::read_to_string(scratch.own_store()).unwrap();
assert_eq!(own.lines().count(), 1 + FILES, "one record per indexed file");
assert!(!own.contains("outside.sv") && !own.contains("ghost.sv"), "{own}");
}
/// The language server appends: one path may have a record for an older
/// version of the file and one for the current. Keyed by (path, hash), both
/// are held, and the one whose hash is the file's bytes is served — here the
/// *older* one, after the file was put back. Two records for one (path, hash)
/// with different facts: the later line wins, as in the language server
/// (`IndexCache::open`); with the honest record last, the answer is right.
#[test]
fn qa_several_records_for_one_path_serve_only_the_bytes_on_disk() {
let scratch = Scratch::new();
let leaf = scratch.file("rtl/leaf.sv");
let original = fs::read_to_string(&leaf).unwrap();
let edited = original.replace("module leaf", "module leaf_v2");
let mut lines = honest_store(&scratch);
// A record for the edited version (not on disk), then a checksum-valid
// record under the current hash describing the edited text, then the
// honest one again: the last line for (leaf.sv, hash) wins.
lines.push(line(content_hash(edited.as_bytes()), &facts_of(&leaf, &edited)));
lines.push(line(content_hash(original.as_bytes()), &facts_of(&leaf, &edited)));
lines.push(record(&leaf));
scratch.write_editor_store(&lines);
let mut session = Session::cached(&scratch);
assert!(declared(&mut session, "leaf") && !declared(&mut session, "leaf_v2"));
session.end();
// Now the edited version is on disk: its own record serves it.
fs::write(&leaf, &edited).unwrap();
fs::remove_file(scratch.own_store()).unwrap();
let mut session = Session::cached(&scratch);
assert!(declared(&mut session, "leaf_v2"));
let stderr = session.end();
assert!(stderr.contains(&reused(FILES, 0)), "{stderr}");
}
/// A store whose lines end `\r\n` (an editor or a checkout rewrote it): the
/// `\r` is stripped the way `str::lines` and the language server strip it,
/// the checksums still hold over the facts, and the answers are cold's.
#[test]
fn qa_a_crlf_store_is_read_as_the_language_server_reads_it() {
let scratch = Scratch::new();
let (cold, _) = probe(&scratch, None);
fs::create_dir_all(scratch.cache()).unwrap();
fs::write(scratch.editor_store(), honest_store(&scratch).join("\r\n") + "\r\n").unwrap();
let before = hash_file(&scratch.editor_store());
let (warm, stderr) = probe(&scratch, Some(&scratch.cache()));
assert!(stderr.contains(&reused(FILES, 0)), "{stderr}");
assert_eq!(warm, cold);
assert_eq!(hash_file(&scratch.editor_store()), before);
}
/// Headers one step away from this build's: each store is ignored whole with
/// exactly one stderr line, the index is cold, the file byte-identical.
#[test]
fn qa_header_near_misses_are_ignored_whole_and_left_byte_identical() {
let (major_minor, patch) = VERSION.rsplit_once('.').unwrap();
let next_patch = format!("{major_minor}.{}", patch.parse::<u32>().unwrap() + 1);
let headers = [
format!("lucisv-index-cache\t2\t{FACTS_FORMAT}\t{next_patch}"),
format!("lucisv-index-cache\t2\t{}\t{VERSION}", FACTS_FORMAT + 1),
format!("lucisv-index-cache\t2\t{}\t{VERSION}", FACTS_FORMAT - 1),
format!("lucisv-index-cache\t1\t{FACTS_FORMAT}\t{VERSION}"),
format!("lucisv-index-cache\t3\t{FACTS_FORMAT}\t{VERSION}"),
format!("{} ", header()),
format!("\u{feff}{}", header()),
format!("lucisv-index-cache\t2\t{FACTS_FORMAT}\t{VERSION}\textra"),
];
for first in headers {
let scratch = Scratch::new();
let mut lines = honest_store(&scratch);
lines[0] = first.clone();
scratch.write_editor_store(&lines);
let before = hash_file(&scratch.editor_store());
let mut session = Session::cached(&scratch);
assert!(declared(&mut session, "leaf"));
let stderr = session.end();
assert!(stderr.contains(&reused(0, 0)), "{first:?}: {stderr}");
assert_eq!(stderr.matches("ignoring the index cache").count(), 1, "{first:?}: {stderr}");
assert_eq!(hash_file(&scratch.editor_store()), before, "{first:?}");
}
}
// ---------------------------------------------------------------------------
// 2. The read-only promise and the own store's writes.
// ---------------------------------------------------------------------------
/// An empty store and a header-only store are silent cold starts; so is a
/// directory where the editor's store would be.
#[test]
fn qa_empty_stores_and_a_directory_named_index_cache_are_silent_cold_starts() {
for shape in ["empty", "header only", "directory"] {
let scratch = Scratch::new();
fs::create_dir_all(scratch.cache()).unwrap();
match shape {
"empty" => fs::write(scratch.editor_store(), "").unwrap(),
"header only" => fs::write(scratch.editor_store(), header() + "\n").unwrap(),
_ => fs::create_dir(scratch.editor_store()).unwrap(),
}
let mut session = Session::cached(&scratch);
assert!(declared(&mut session, "leaf"));
let stderr = session.end();
assert!(stderr.contains(&reused(0, 0)), "{shape}: {stderr}");
assert_eq!(stderr.lines().count(), 1, "{shape}: only the startup line: {stderr}");
assert!(scratch.own_store().is_file(), "{shape}");
}
}
/// A directory where this server's own store goes: the read is a silent
/// miss, the write fails with one stderr line, no temporary file is left,
/// and the answers were right.
#[test]
fn qa_a_directory_named_index_cache_mcp_costs_one_line_and_leaves_no_temp() {
let scratch = Scratch::new();
fs::create_dir_all(scratch.own_store()).unwrap();
let mut session = Session::cached(&scratch);
assert!(session.text("outline", json!({"unit": "leaf"})).starts_with("rtl/leaf.sv:1\n"));
let stderr = session.end();
assert!(stderr.contains(&reused(0, 0)), "{stderr}");
assert_eq!(stderr.matches("cannot write the index cache").count(), 1, "{stderr}");
assert!(scratch.own_store().is_dir(), "the directory is left alone");
assert!(temp_files(&scratch.cache()).is_empty(), "{:?}", temp_files(&scratch.cache()));
}
/// `--index-cache` naming a file, not a directory: the stores cannot be read
/// under it (a silent miss), the write fails with one line, and the file is
/// byte-identical.
#[test]
fn qa_index_cache_naming_a_file_answers_and_leaves_the_file_alone() {
let scratch = Scratch::new();
let file = scratch.0.join("not-a-dir");
fs::write(&file, "keep me\n").unwrap();
let mut session = Session::start(&scratch, Some(&file));
assert!(declared(&mut session, "leaf"));
let stderr = session.end();
assert!(stderr.contains(&reused(0, 0)), "{stderr}");
assert_eq!(stderr.matches("cannot write the index cache").count(), 1, "{stderr}");
assert_eq!(fs::read_to_string(&file).unwrap(), "keep me\n");
}
/// A cache directory with no permissions at all (mode 000, holding a whole
/// honest editor store): nothing can be read, so the start is cold; the
/// answers are right; the exit says it could not write, once; the store in
/// it is untouched.
#[cfg(unix)]
#[test]
fn qa_a_cache_directory_without_permission_is_a_cold_start_that_answers() {
use std::os::unix::fs::PermissionsExt;
let scratch = Scratch::new();
let (cold, _) = probe(&scratch, None);
scratch.write_editor_store(&honest_store(&scratch));
let before = hash_file(&scratch.editor_store());
fs::set_permissions(scratch.cache(), fs::Permissions::from_mode(0o000)).unwrap();
let (answers, stderr) = probe(&scratch, Some(&scratch.cache()));
fs::set_permissions(scratch.cache(), fs::Permissions::from_mode(0o755)).unwrap();
assert_eq!(answers, cold);
assert!(stderr.contains(&reused(0, 0)), "{stderr}");
assert_eq!(stderr.matches("cannot write the index cache").count(), 1, "{stderr}");
assert_eq!(hash_file(&scratch.editor_store()), before);
assert!(!scratch.own_store().exists());
}
/// The editor's store read-only on disk (0444) and in the shape a live
/// language server leaves between compactions — out of path order, a
/// duplicate line, a torn line in the middle, a checksum-failing line: a
/// session that indexes, answers, formats a file and ends leaves its bytes,
/// mtime and mode exactly as they were (nothing "tidies" it), and the good
/// records were all used.
#[cfg(unix)]
#[test]
fn qa_the_editors_store_is_never_tidied_whatever_its_shape() {
use std::os::unix::fs::PermissionsExt;
let scratch = Scratch::new();
let mut lines = honest_store(&scratch);
lines[1..].reverse();
lines.push(lines[1].clone());
let torn = lines[2][..lines[2].len() / 3].to_string();
lines.insert(2, torn);
let bad = lines[3].replacen("\t", "\tX", 2);
lines.insert(3, bad);
scratch.write_editor_store(&lines);
fs::set_permissions(scratch.editor_store(), fs::Permissions::from_mode(0o444)).unwrap();
let before = fingerprint(&scratch.editor_store());
let mut session = Session::cached(&scratch);
assert!(session.text("hierarchy", json!({})).starts_with("7 files, "));
session.text("format", json!({"files": "rtl/top.sv"}));
session.text("outline", json!({"file": "rtl/top.sv"}));
let stderr = session.end();
assert!(stderr.contains(&reused(FILES, 0)), "{stderr}");
assert_eq!(fingerprint(&scratch.editor_store()), before, "bytes, mtime and mode unchanged");
assert!(scratch.own_store().is_file());
fs::set_permissions(scratch.editor_store(), fs::Permissions::from_mode(0o644)).unwrap();
}
/// A session killed (SIGKILL) after it answered — the host crashed, it never
/// saw EOF — writes nothing: the previous own store is byte-identical and
/// no temporary file is left, even though the file it would describe changed.
#[test]
fn qa_a_killed_session_leaves_the_previous_own_store_intact() {
let scratch = Scratch::new();
let session = Session::cached(&scratch);
drop(session.end()); // no call: no project, nothing written
assert!(!scratch.own_store().exists(), "a session that never answered writes no store");
let mut session = Session::cached(&scratch);
session.text("hierarchy", json!({}));
session.end();
let first = fs::read(scratch.own_store()).unwrap();
let leaf = scratch.file("rtl/leaf.sv");
let text = fs::read_to_string(&leaf).unwrap().replace("module leaf", "module leaf_k");
fs::write(&leaf, text).unwrap();
let mut session = Session::cached(&scratch);
assert!(declared(&mut session, "leaf_k"));
session.child.kill().unwrap();
session.child.wait().unwrap();
assert_eq!(fs::read(scratch.own_store()).unwrap(), first, "the previous store, whole");
assert!(temp_files(&scratch.cache()).is_empty(), "{:?}", temp_files(&scratch.cache()));
// And the next start is right about the changed file (its hash misses).
let mut session = Session::cached(&scratch);
assert!(declared(&mut session, "leaf_k"));
let stderr = session.end();
assert!(stderr.contains(&reused(0, FILES - 1)), "{stderr}");
}
/// QA finding 2: a write killed between the temp file and the rename leaves
/// `index-cache-mcp.<pid>.tmp` (reproduced on opentitan: 9.4 MB of a 46 MB
/// store) and nothing ever removes it — each crash adds one. The language
/// server has the same leak, filed by its own QA (2026-08-27,
/// `index_cache.rs` `an_orphaned_compaction_tmp_file_is_never_swept_up`).
/// Correct behaviour: the next write sweeps a stale temp file of its own
/// store's name (an old mtime, so a concurrent writer's live one is spared).
#[test]
fn qa_an_orphaned_temp_file_is_swept_by_the_next_write() {
let scratch = Scratch::new();
fs::create_dir_all(scratch.cache()).unwrap();
let orphan = scratch.cache().join("index-cache-mcp.999999.tmp");
fs::write(&orphan, "lucisv-index-cache\t2\ttorn").unwrap();
let old = SystemTime::now() - Duration::from_secs(3600);
fs::File::options().write(true).open(&orphan).unwrap().set_modified(old).unwrap();
let mut session = Session::cached(&scratch);
session.text("hierarchy", json!({}));
session.end();
assert!(scratch.own_store().is_file());
assert!(!orphan.exists(), "an hour-old temp file of our store is a dead writer's");
}
// ---------------------------------------------------------------------------
// 3. Parity and freshness.
// ---------------------------------------------------------------------------
/// Warm from the editor's store, warm from its own, and cold: the same
/// answers to every read tool the probe asks.
#[test]
fn qa_warm_answers_equal_cold_answers_from_either_store() {
let scratch = Scratch::new();
let (cold, _) = probe(&scratch, None);
scratch.write_editor_store(&honest_store(&scratch));
let (from_editor, stderr) = probe(&scratch, Some(&scratch.cache()));
assert!(stderr.contains(&reused(FILES, 0)), "{stderr}");
assert_eq!(from_editor, cold);
fs::remove_file(scratch.editor_store()).unwrap();
let (from_own, stderr) = probe(&scratch, Some(&scratch.cache()));
assert!(stderr.contains(&reused(0, FILES)), "{stderr}");
assert_eq!(from_own, cold);
}
/// Since the store was written: a same-size edit (only the hash can tell)
/// is re-parsed and answered new, and a new file is indexed.
#[test]
fn qa_a_same_size_edit_and_a_new_file_since_the_store_are_seen() {
let scratch = Scratch::new();
scratch.write_editor_store(&honest_store(&scratch));
let leaf = scratch.file("rtl/leaf.sv");
let before = fs::read_to_string(&leaf).unwrap();
let after = before.replace("held", "hold");
assert_eq!(before.len(), after.len(), "premise: the size does not change");
fs::write(&leaf, after).unwrap();
fs::write(scratch.file("rtl/extra.sv"), "module extra_unit; endmodule\n").unwrap();
let mut session = Session::cached(&scratch);
let outline = session.text("outline", json!({"file": "rtl/leaf.sv"}));
assert!(outline.contains("hold") && !outline.contains("held"), "{outline}");
assert!(declared(&mut session, "extra_unit"));
let stderr = session.end();
assert!(stderr.contains(&reused(FILES - 1, 0)), "{stderr}");
assert!(stderr.contains(&format!("indexed {} files", FILES + 1)), "{stderr}");
}
// ---------------------------------------------------------------------------
// 4. Rule 6: the delete of a macro definition holder.
// ---------------------------------------------------------------------------
const HOLDER: &str = "module keep_before;
endmodule
module holder;
`define LOCAL 3
`define LOCAL 4
always_comb begin
`undef GONE
end
endmodule
module user_after (output logic [3:0] o);
assign o = `LOCAL;
endmodule
";
/// A module holding a `define that code after it reads: refused (the
/// lean catalogue has no `force`, so the refusal offers none), the tree
/// byte-identical.
#[test]
fn qa_a_delete_of_a_define_holder_is_refused_and_writes_nothing() {
let scratch = Scratch::new();
let file = scratch.file("rtl/holder.sv");
fs::write(&file, HOLDER).unwrap();
let mut session = Session::start(&scratch, None);
let args = json!({"file": "rtl/holder.sv", "op": "delete", "item": "holder"});
let refused = session.call("edit_item", args);
assert_eq!(refused["isError"], true, "{refused}");
let said = refused["content"][0]["text"].as_str().unwrap();
assert!(said.contains("rule 6") && !said.contains("force"), "{said}");
assert_eq!(fs::read_to_string(&file).unwrap(), HOLDER, "a refusal writes nothing");
session.end();
}
/// A deletion whose item holds no macro says nothing about macros.
#[test]
fn qa_a_delete_says_nothing_about_macros_it_did_not_remove() {
let scratch = Scratch::new();
fs::write(scratch.file("rtl/holder.sv"), HOLDER).unwrap();
let mut session = Session::start(&scratch, None);
let args = json!({"file": "rtl/holder.sv", "op": "delete", "item": "keep_before"});
let applied = session.text("edit_item", args);
assert!(!applied.contains("macro"), "{applied}");
session.end();
}
// ---------------------------------------------------------------------------
// 5. The instructions.
// ---------------------------------------------------------------------------
/// ≤ 400 bytes (PLAN §10.3); names the nine tools, the disk, the
/// all-or-nothing writes and that there is no dry run; and every snake_case
/// word in it is a tool `tools/list` has.
#[test]
fn qa_the_instructions_are_short_and_name_only_real_tools() {
let scratch = Scratch::new();
let mut session = Session::start(&scratch, None);
let init = session.request("initialize", json!({"protocolVersion": "2025-06-18"}));
let text = init["result"]["instructions"].as_str().unwrap().to_string();
let listed = session.request("tools/list", json!({}));
let tools: Vec<String> = listed["result"]["tools"]
.as_array()
.unwrap()
.iter()
.map(|tool| tool["name"].as_str().unwrap().to_string())
.collect();
session.end();
assert!(text.len() <= 400, "{} bytes", text.len());
for named in
["hierarchy", "find", "outline", "read", "check", "rename", "port", "edit_item", "format"]
{
assert!(text.contains(named), "the instructions name {named}");
assert!(tools.iter().any(|tool| tool == named), "{named} is a real tool");
}
for word in text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) {
if word.contains('_') {
assert!(tools.iter().any(|tool| tool == word), "`{word}` is not a tool");
}
}
for phrase in ["on disk", "no dry run", "all-or-nothing", "root-relative", "1-based"] {
assert!(text.contains(phrase), "{phrase}: {text}");
}
}
+869
View File
@@ -0,0 +1,869 @@
//! QA attacks on lane M7 (the lean catalogue), 2026-09-24.
//!
//! Every test writes a small design into its own scratch directory, spawns
//! the real binary over it, sends `initialize` and a batch of `tools/call`s,
//! closes stdin and reads every answer — the host's view, nothing else.
//!
//! A test that pins a QA finding asserts the *correct* behaviour and is
//! `#[ignore = "QA finding N"]` until a rework flips it; the findings are
//! numbered as in the QA log of `docs/features/mcp-lean-catalogue/README.md`.
use std::collections::BTreeMap;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use serde_json::{json, Value};
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
/// A scratch design, removed on drop.
struct Tree(PathBuf);
impl Tree {
/// A tree holding `files` (`(relative path, text)`).
fn with(files: &[(&str, &str)]) -> Tree {
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
let dir =
std::env::temp_dir().join(format!("lucisv-mcp-qa-m7-{}-{unique}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
let tree = Tree(fs::canonicalize(dir).unwrap());
for (rel, text) in files {
tree.write(rel, text);
}
tree
}
fn path(&self, rel: &str) -> PathBuf {
self.0.join(rel)
}
fn write(&self, rel: &str, text: &str) {
let path = self.path(rel);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, text).unwrap();
}
fn read(&self, rel: &str) -> String {
fs::read_to_string(self.path(rel)).unwrap()
}
/// Every file's bytes, by relative path.
fn snapshot(&self) -> BTreeMap<String, Vec<u8>> {
fn walk(dir: &Path, root: &Path, out: &mut BTreeMap<String, Vec<u8>>) {
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
walk(&path, root, out);
} else {
let rel = path.strip_prefix(root).unwrap().to_string_lossy().to_string();
out.insert(rel, fs::read(&path).unwrap());
}
}
}
let mut out = BTreeMap::new();
walk(&self.0, &self.0, &mut out);
out
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
/// One answer: whether it was refused, and its text.
struct Said {
refused: bool,
text: String,
}
/// Run `calls` in one session over `tree`, in order.
fn session(tree: &Tree, calls: &[(&str, Value)]) -> Vec<Said> {
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
.args(["--root", tree.0.to_str().unwrap()])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
let mut lines = vec![json!({"jsonrpc": "2.0", "id": 0, "method": "initialize", "params": {
"protocolVersion": "2025-06-18", "capabilities": {},
"clientInfo": {"name": "qa_m7", "version": "0"}}})
.to_string()];
lines.push(json!({"jsonrpc": "2.0", "method": "notifications/initialized"}).to_string());
for (at, (tool, arguments)) in calls.iter().enumerate() {
let params = json!({"name": tool, "arguments": arguments});
let call =
json!({"jsonrpc": "2.0", "id": at + 1, "method": "tools/call", "params": params});
lines.push(call.to_string());
}
let mut stdin = child.stdin.take().unwrap();
stdin.write_all((lines.join("\n") + "\n").as_bytes()).unwrap();
drop(stdin);
let output = child.wait_with_output().unwrap();
let replies: Vec<Value> = String::from_utf8(output.stdout)
.unwrap()
.lines()
.map(|line| serde_json::from_str(line).unwrap())
.collect();
(1..=calls.len())
.map(|id| {
let reply = replies.iter().find(|r| r["id"] == id).expect("every call is answered");
let result = &reply["result"];
Said {
refused: result["isError"] == true,
text: result["content"][0]["text"].as_str().unwrap_or_default().to_string(),
}
})
.collect()
}
/// One call that must succeed: its text.
fn text(tree: &Tree, tool: &str, arguments: Value) -> String {
let said = session(tree, &[(tool, arguments.clone())]).remove(0);
assert!(!said.refused, "{tool} {arguments}: {}", said.text);
said.text
}
/// One call that must be refused, leaving every file byte-identical.
fn refusal(tree: &Tree, tool: &str, arguments: Value) -> String {
let before = tree.snapshot();
let said = session(tree, &[(tool, arguments.clone())]).remove(0);
assert!(said.refused, "{tool} {arguments}: not refused: {}", said.text);
assert!(before == tree.snapshot(), "{tool} {arguments}: a refusal wrote");
said.text
}
/// The `… and N more` lines of an answer.
fn more_lines(text: &str) -> Vec<&str> {
text.lines()
.filter(|line| line.starts_with("… and ") || line.trim_start().starts_with("… and "))
.collect()
}
// ---------------------------------------------------------------------------
// Caps: exactly one `… and N more`, the count right, every line whole.
// ---------------------------------------------------------------------------
/// `big` instantiates `leaf` 400 times; `wide` has 350 ports and 320 nets
/// no one reads; 320 modules each declare `sig`.
fn crowded() -> Tree {
let mut big = String::from("module big;\n logic a;\n");
for i in 0..400 {
big.push_str(&format!(" leaf u_{i:03} (.a(a));\n"));
}
big.push_str("endmodule\n");
let ports: Vec<String> = (0..350).map(|i| format!(" input logic p{i}")).collect();
let mut wide = format!("module wide (\n{}\n);\n", ports.join(",\n"));
for i in 0..320 {
wide.push_str(&format!(" logic w{i};\n"));
}
wide.push_str("endmodule\n");
let mut files: Vec<(String, String)> = vec![
("rtl/leaf.sv".into(), "module leaf(input logic a);\nendmodule\n".into()),
("rtl/big.sv".into(), big),
("rtl/wide.sv".into(), wide),
];
for i in 0..320 {
files.push((
format!("rtl/m{i:03}.sv"),
format!("module m{i:03};\n logic sig;\nendmodule\n"),
));
}
let borrowed: Vec<(&str, &str)> = files.iter().map(|(p, t)| (p.as_str(), t.as_str())).collect();
Tree::with(&borrowed)
}
#[test]
fn qa_every_cap_cuts_once_with_the_right_count_and_whole_lines() {
let tree = crowded();
let calls = [
("hierarchy", json!({"root": "big"})),
("hierarchy", json!({"root": "leaf", "up": true})),
("hierarchy", json!({"root": "big", "peek": true})),
("hierarchy", json!({})),
("find", json!({"name": "sig"})),
("outline", json!({"unit": "wide"})),
("outline", json!({"file": "rtl/wide.sv"})),
("check", json!({})),
];
let said = session(&tree, &calls);
// (shown lines before the cut line, the count the cut line says)
let expected = [
(300, 101), // the root line + 400 instances
(300, 100), // 400 instantiations
(199, 301), // root + 99 two-line blocks: with peek the cap is 100 nodes
(300, 23), // counts line + 322 tops
(300, 20), // 320 declarations
(300, 51), // file:line + 350 ports
(300, 371), // module + 350 ports + 320 nets
(200, 120), // 320 unused nets
];
for ((call, said), (shown, rest)) in calls.iter().zip(&said).zip(expected) {
assert!(!said.refused, "{call:?}: {}", said.text);
let lines: Vec<&str> = said.text.lines().collect();
assert_eq!(more_lines(&said.text), [format!("… and {rest} more")], "{call:?}");
assert_eq!(lines.len(), shown + 1, "{call:?}");
assert_eq!(*lines.last().unwrap(), format!("… and {rest} more"), "{call:?}");
assert!(lines.iter().all(|line| !line.trim().is_empty()), "{call:?}");
}
// Every line before the cut is a whole fact: a tree line names its site.
for line in said[0].text.lines().skip(1).take(299) {
let (head, site) = line.trim_start().rsplit_once(' ').unwrap();
assert!(head.starts_with("u_") && head.ends_with(": leaf"), "{line}");
let (file, number) = site.split_once(':').unwrap();
assert_eq!(file, "rtl/big.sv");
number.parse::<u32>().unwrap();
}
// A peek block is never split: the last shown line is the 99th
// instance's statement.
let peek: Vec<&str> = said[2].text.lines().collect();
assert_eq!(peek[197], " u_098: leaf rtl/big.sv:101");
assert_eq!(peek[198], " leaf u_098 (.a(a));");
for line in said[7].text.lines().take(200) {
assert!(line.starts_with("rtl/wide.sv:") && line.ends_with("[unused-signal]"), "{line}");
}
}
// ---------------------------------------------------------------------------
// peek
// ---------------------------------------------------------------------------
const PEEKED: &str = "module leaf #(parameter int W = 1) (
input logic clk,
input logic [W-1:0] d,
output logic [W-1:0] q
);
always_ff @(posedge clk) q <= d;
endmodule
";
const PEEKER: &str = "module top (
input logic clk,
input logic [3:0] d,
output logic [3:0] q
);
logic [3:0] mid;
// a comment before the statement
leaf #(
.W(4) // width; with a semicolon in the comment
) u_a (
.clk, /* block ; comment */
.d (d),
.q (mid)
);
\tleaf #(.W(4)) u_b (.*);
leaf #(
.W(4)
) u_long (
.clk(clk),
// spaced
.d(mid),
.q(q)
// one
// two
// three
// four
// five
);
leaf u_c (.clk(clk), .d(d[0]), .q()), u_d (.clk(clk), .d(d[1]), .q());
endmodule
";
#[test]
fn qa_peek_shows_a_commented_overridden_statement_exactly_and_cuts_at_12() {
let tree = Tree::with(&[("rtl/leaf.sv", PEEKED), ("rtl/top.sv", PEEKER)]);
let down = text(&tree, "hierarchy", json!({"root": "top", "peek": true}));
let expected = "top rtl/top.sv:1
u_a: leaf rtl/top.sv:10
leaf #(
.W(4) // width; with a semicolon in the comment
) u_a (
.clk, /* block ; comment */
.d (d),
.q (mid)
);
u_b: leaf rtl/top.sv:15
leaf #(.W(4)) u_b (.*);
u_long: leaf rtl/top.sv:18
leaf #(
.W(4)
) u_long (
.clk(clk),
// spaced
.d(mid),
.q(q)
// one
// two
// three
// four
// five
…
u_c: leaf rtl/top.sv:29
leaf u_c (.clk(clk), .d(d[0]), .q()), u_d (.clk(clk), .d(d[1]), .q());
u_d: leaf rtl/top.sv:29
leaf u_c (.clk(clk), .d(d[0]), .q()), u_d (.clk(clk), .d(d[1]), .q());
";
assert_eq!(down, expected);
// Up shows the same statements under `parent.instance` lines.
let up = text(&tree, "hierarchy", json!({"root": "leaf", "up": true, "peek": true}));
assert!(up.starts_with("top.u_a rtl/top.sv:10\n leaf #(\n .W(4) // width;"), "{up}");
assert_eq!(up.matches('…').count(), 1, "{up}");
// Exactly 12 lines is not cut.
let twelve = PEEKER.replace(" // five\n", "");
tree.write("rtl/top.sv", &twelve);
let down = text(&tree, "hierarchy", json!({"root": "top", "peek": true}));
assert!(!down.contains('…'), "{down}");
}
#[test]
fn qa_peek_never_answers_a_whitespace_only_line() {
let spaced = PEEKER.replace(" .clk(clk),\n // spaced", " .clk(clk),\n\n // spaced");
let tree = Tree::with(&[("rtl/leaf.sv", PEEKED), ("rtl/top.sv", &spaced)]);
let down = text(&tree, "hierarchy", json!({"root": "top", "peek": true}));
// Lead's ruling on finding 4: the statement's blank line is an empty
// line — no indent, no trailing spaces; every other line stays exact.
assert!(down.lines().all(|line| line.is_empty() || !line.trim().is_empty()), "{down}");
assert!(down.contains(" .clk(clk),\n\n // spaced"), "{down}");
}
// ---------------------------------------------------------------------------
// Ambiguity and unknown names
// ---------------------------------------------------------------------------
const OTHER: &str = "module other (input logic clk);
logic mid;
assign mid = clk;
endmodule
";
const MID: &str = "module top2 (input logic clk);
logic mid;
assign mid = clk;
endmodule
";
#[test]
fn qa_ambiguous_and_unknown_names_are_refused_with_what_picks_one() {
let tree = Tree::with(&[
("rtl/leaf.sv", PEEKED),
("rtl/other.sv", OTHER),
("rtl/top2.sv", MID),
("rtl/dup.sv", "module leaf (input logic clk);\nendmodule\n"),
]);
let read = refusal(&tree, "read", json!({"item": "mid"}));
assert!(read.contains("rtl/other.sv:2, rtl/top2.sv:2") && read.contains("`file`"), "{read}");
let rename = refusal(&tree, "rename", json!({"name": "mid", "new_name": "m2"}));
assert!(rename.contains("rtl/other.sv:2, rtl/top2.sv:2"), "{rename}");
let module = refusal(&tree, "rename", json!({"name": "leaf", "new_name": "leaf2"}));
assert!(module.contains("rtl/dup.sv:1, rtl/leaf.sv:1"), "{module}");
// `file` picks one; `unit.name` picks one without it.
let picked = text(&tree, "read", json!({"item": "mid", "file": "rtl/top2.sv"}));
assert_eq!(picked, "rtl/top2.sv:2\nlogic mid;\n");
let renamed = text(&tree, "rename", json!({"name": "other.mid", "new_name": "m3"}));
assert_eq!(renamed, "renamed 2 sites in 1 file\n");
assert!(tree.read("rtl/top2.sv").contains("logic mid;"));
let find = refusal(&tree, "find", json!({"name": "lea"}));
assert_eq!(find, "no declaration named `lea`; similar: leaf.");
let none = refusal(&tree, "find", json!({"name": "qqq"}));
assert_eq!(none, "no declaration named `qqq`.");
let root = refusal(&tree, "hierarchy", json!({"root": "OTH"}));
assert_eq!(root, "no module or interface named `OTH`; similar: other.");
}
const FSM: &str = "module fsm (input logic clk, output logic busy);
typedef enum logic [1:0] {StIdle, StBusy} state_e;
state_e state_q;
function automatic logic helper(input logic x);
return ~x;
endfunction
for (genvar gi = 0; gi < 2; gi++) begin : g_lane
logic lane_q;
end
assign busy = helper(state_q == StBusy);
always_ff @(posedge clk) state_q <= StIdle;
endmodule
";
#[test]
fn qa_find_and_rename_reach_every_declaration_outline_lists() {
let tree = Tree::with(&[("rtl/fsm.sv", FSM)]);
// `outline` lists these; `read` with `file` slices them; 0.57.0's
// `rename` renamed them by position. By name, the lean tools say they
// do not exist.
for name in ["state_e", "StIdle", "helper", "g_lane", "lane_q"] {
let said = session(&tree, &[("find", json!({"name": name}))]).remove(0);
assert!(!said.refused, "find {name}: {}", said.text);
}
let renamed = text(&tree, "rename", json!({"name": "StIdle", "new_name": "StRest"}));
assert!(renamed.starts_with("renamed 2 sites in 1 file"), "{renamed}");
}
#[test]
fn qa_find_near_matches_include_the_module_internals_find_lists() {
let tree = Tree::with(&[("rtl/other.sv", OTHER)]);
assert_eq!(text(&tree, "find", json!({"name": "mid"})), "var mid rtl/other.sv:2\n");
let near = refusal(&tree, "find", json!({"name": "mi"}));
assert!(near.contains("similar: mid"), "{near}");
}
// ---------------------------------------------------------------------------
// port
// ---------------------------------------------------------------------------
const SUB: &str = "module sub (
input logic clk,
input logic a,
output logic y
);
assign y = a;
endmodule
";
const P1: &str = "module p1 (input logic clk, input logic a, output logic y);
sub u_s (
.clk(clk),
.a (a),
.y (y)
);
endmodule
";
const P2: &str = "module p2 (input logic clk, input logic a, input logic b, output logic y);
logic y1, y2;
sub u_s1 (.clk, .a, .y(y1));
sub u_s2 (.*);
assign y = y1;
endmodule
";
#[test]
fn qa_port_refuses_bad_shapes_and_connects_every_instantiation_or_none() {
let tree = Tree::with(&[
("rtl/sub.sv", SUB),
("rtl/p1.sv", P1),
("rtl/p2.sv", P2),
("rtl/p3.sv", "module p3 (input logic clk, a, output logic y);\n sub u_pos (clk, a, y);\nendmodule\n"),
]);
let add = |after: Option<&str>| match after {
Some(after) => json!({"module": "sub", "add": "input logic b", "after": after}),
None => json!({"module": "sub", "add": "input logic b"}),
};
// A positional instantiation in one file refuses the whole edit.
let whole = refusal(&tree, "port", add(None));
assert!(whole.contains("p3.sv") && whole.contains("no edits were made"), "{whole}");
fs::remove_file(tree.path("rtl/p3.sv")).unwrap();
let anchor = refusal(&tree, "port", add(Some("nope")));
assert_eq!(anchor, "`sub` has no port `nope` (its ports: clk, a, y).");
let neither = refusal(&tree, "port", json!({"module": "sub"}));
assert_eq!(neither, "give exactly one of `add` and `remove`.");
let both =
refusal(&tree, "port", json!({"module": "sub", "add": "input logic b", "remove": "a"}));
assert_eq!(both, "give exactly one of `add` and `remove`.");
let stray = refusal(&tree, "port", json!({"module": "sub", "remove": "a", "after": "clk"}));
assert_eq!(stray, "`after` goes with `add`, not `remove`.");
let used = refusal(&tree, "port", json!({"module": "sub", "remove": "a"}));
assert!(used.contains("`a` is still used inside `sub`"), "{used}");
let unknown = refusal(&tree, "port", json!({"module": "nosuch", "add": "input logic b"}));
assert!(unknown.contains("`nosuch`"), "{unknown}");
// Three instantiations in two files, each connected.
let added = text(&tree, "port", add(Some("clk")));
assert!(
added.starts_with("added port b in module sub: 3 instantiations in 2 files\n"),
"{added}"
);
assert!(tree.read("rtl/sub.sv").contains(" input logic clk,\n input logic b,\n"));
assert!(
tree.read("rtl/p1.sv").contains(" .clk(clk),\n .b"),
"{}",
tree.read("rtl/p1.sv")
);
assert!(
tree.read("rtl/p2.sv").contains("sub u_s1 (.clk, .b(b), .a, .y(y1));"),
"{}",
tree.read("rtl/p2.sv")
);
assert!(tree.read("rtl/p2.sv").contains("sub u_s2 (.*);"));
}
// ---------------------------------------------------------------------------
// edit_item
// ---------------------------------------------------------------------------
const ITEMS: &str = "module m (input logic clk, output logic y);
logic used_sig;
logic unused_sig;
// the helper
function automatic logic helper(input logic x);
return ~x;
endfunction
assign used_sig = clk;
assign y = helper(used_sig);
endmodule
module n;
logic z;
endmodule
";
#[test]
fn qa_edit_item_refuses_used_deletes_and_renaming_replaces_and_inserts_at_a_units_end() {
let tree = Tree::with(&[("rtl/m.sv", ITEMS)]);
let edit = |op: &str, item: &str, text: Option<&str>| match text {
Some(text) => json!({"file": "rtl/m.sv", "op": op, "item": item, "text": text}),
None => json!({"file": "rtl/m.sv", "op": op, "item": item}),
};
let used = refusal(&tree, "edit_item", edit("delete", "used_sig", None));
assert_eq!(
used,
"still referenced: rtl/m.sv:8:10 `used_sig`; rtl/m.sv:9:21 `used_sig`; nothing written."
);
let called = refusal(&tree, "edit_item", edit("delete", "helper", None));
assert!(called.contains("rtl/m.sv:9:14 `helper`"), "{called}");
let renamed = refusal(&tree, "edit_item", edit("replace", "unused_sig", Some("logic other;")));
assert!(renamed.contains("`rename` renames"), "{renamed}");
let at_end = text(&tree, "edit_item", edit("insert_after", "end@n", Some(" logic w;")));
assert_eq!(at_end, "inserted declaration w rtl/m.sv:15\n");
assert!(tree.read("rtl/m.sv").ends_with("module n;\n logic z;\n\n logic w;\nendmodule\n"));
let nowhere = refusal(&tree, "edit_item", edit("insert_after", "end@nope", Some("logic q;")));
assert!(nowhere.contains("`nope`"), "{nowhere}");
// The control: an unused item goes, with its line.
let gone = text(&tree, "edit_item", edit("delete", "unused_sig", None));
assert_eq!(gone, "deleted declaration unused_sig rtl/m.sv:3\n");
}
// ---------------------------------------------------------------------------
// format
// ---------------------------------------------------------------------------
#[test]
fn qa_format_names_the_refused_file_writes_the_rest_and_refuses_an_empty_glob() {
let tree = Tree::with(&[
("rtl/a.sv", "module a(input logic x);\nlogic y;\nendmodule\n"),
("rtl/b.sv", "module b;\n logic y ;\nendmodule\n"),
("rtl/c.sv", "module c;\n logic y;\nendmodule\n"),
("rtl/bad.sv", "module bad(\n input logic x\n logic y;\nendmodule\n"),
]);
let nothing = refusal(&tree, "format", json!({"files": "rtl/**/*.vhd"}));
assert_eq!(nothing, "no indexed file matches `rtl/**/*.vhd`; nothing written.");
let bad = tree.read("rtl/bad.sv");
let answer = text(&tree, "format", json!({"files": "rtl/*.sv"}));
let lines: Vec<&str> = answer.lines().collect();
assert_eq!(lines[0], "formatted 3 files (1 unchanged)");
assert_eq!(lines.len(), 2, "{answer}");
assert!(lines[1].starts_with("not formatted: rtl/bad.sv (parse error: 3:3"), "{answer}");
assert_eq!(tree.read("rtl/a.sv"), "module a (input logic x);\n logic y;\nendmodule\n");
assert_eq!(tree.read("rtl/b.sv"), "module b;\n logic y;\nendmodule\n");
assert_eq!(tree.read("rtl/bad.sv"), bad);
let again = text(&tree, "format", json!({"files": "rtl"}));
assert!(
again.starts_with("formatted 3 files (3 unchanged)\nnot formatted: rtl/bad.sv"),
"{again}"
);
// Only the refused file: the call itself is a refusal.
let alone = refusal(&tree, "format", json!({"files": "rtl/bad.sv"}));
assert!(alone.starts_with("not formatted: rtl/bad.sv"), "{alone}");
}
// ---------------------------------------------------------------------------
// All-or-nothing
// ---------------------------------------------------------------------------
#[test]
fn qa_a_rename_whose_later_file_is_read_only_writes_nothing() {
let tree = Tree::with(&[("rtl/sub.sv", SUB), ("rtl/p1.sv", P1), ("rtl/p2.sv", P2)]);
let p2 = tree.path("rtl/p2.sv");
let mut permissions = fs::metadata(&p2).unwrap().permissions();
permissions.set_readonly(true);
fs::set_permissions(&p2, permissions.clone()).unwrap();
// `p1.sv` sorts first and would be written first: it must not be.
let refused = refusal(&tree, "rename", json!({"name": "sub", "new_name": "sub2"}));
assert_eq!(refused, "`rtl/p2.sv` is read-only; nothing written.");
#[allow(clippy::permissions_set_readonly_false)] // a test undoing its own chmod
permissions.set_readonly(false);
fs::set_permissions(&p2, permissions).unwrap();
let renamed = text(&tree, "rename", json!({"name": "sub", "new_name": "sub2"}));
assert_eq!(renamed, "renamed 4 sites in 3 files\n");
}
// ---------------------------------------------------------------------------
// Answer shape (PLAN §10.2)
// ---------------------------------------------------------------------------
#[test]
fn qa_answers_are_root_relative_one_fact_per_line_without_hints() {
let tree = Tree::with(&[("rtl/leaf.sv", PEEKED), ("rtl/top.sv", PEEKER), ("rtl/fsm.sv", FSM)]);
let calls = [
("hierarchy", json!({})),
("hierarchy", json!({"root": "top", "depth": 3})),
("hierarchy", json!({"root": "leaf", "up": true})),
("find", json!({"name": "leaf", "refs": true})),
("find", json!({"name": "mid", "refs": true})),
("outline", json!({"file": "rtl/fsm.sv"})),
("outline", json!({"unit": "leaf"})),
("check", json!({})),
("check", json!({"file": "rtl/leaf.sv"})),
];
let root = tree.0.to_string_lossy().to_string();
for (call, said) in calls.iter().zip(session(&tree, &calls)) {
assert!(!said.refused, "{call:?}: {}", said.text);
assert!(said.text.ends_with('\n'), "{call:?}");
for line in said.text.lines() {
assert!(!line.trim().is_empty(), "{call:?}: a blank line in {}", said.text);
assert_eq!(line, line.trim_end(), "{call:?}");
assert!(!line.contains(&root) && !line.contains("/private/"), "{call:?}: {line}");
for hint in ["check:", "dry run", "use `", "call `", "next:"] {
assert!(!line.contains(hint), "{call:?}: {line}");
}
}
}
assert_eq!(text(&tree, "check", json!({"file": "rtl/leaf.sv"})), "ok\n");
}
// ---------------------------------------------------------------------------
// find refs: at most five declarations followed
// ---------------------------------------------------------------------------
#[test]
fn qa_find_refs_follows_five_declarations_and_says_so() {
let files: Vec<(String, String)> = (0..7)
.map(|i| {
let text = format!(
"module r{i} (output logic y);\n logic sig;\n assign y = sig;\nendmodule\n"
);
(format!("rtl/r{i}.sv"), text)
})
.collect();
let borrowed: Vec<(&str, &str)> = files.iter().map(|(p, t)| (p.as_str(), t.as_str())).collect();
let tree = Tree::with(&borrowed);
let answer = text(&tree, "find", json!({"name": "sig", "refs": true}));
let mut expected = String::new();
for i in 0..7 {
expected.push_str(&format!("var sig rtl/r{i}.sv:2\n"));
if i < 5 {
expected.push_str(&format!(" rtl/r{i}.sv:3\n"));
}
}
expected.push_str("uses listed for 5 of 7 declarations\n");
assert_eq!(answer, expected);
}
// ---------------------------------------------------------------------------
// Re-check of the rework (2026-09-24): `declared.rs`, `rooted`, `similar`.
// ---------------------------------------------------------------------------
const LOCALS: &str = "module fsm (input logic clk, output logic busy);
typedef enum logic [1:0] {StIdle, StBusy} state_e;
state_e state_q;
function automatic logic helper(input logic x);
logic hl;
hl = ~x;
return hl;
endfunction
task automatic poke(output logic o);
o = 1'b0;
endtask
for (genvar gi = 0; gi < 2; gi++) begin : g_lane
logic lane_q;
assign lane_q = gi[0];
end
always_comb begin
automatic logic tmp;
tmp = helper(state_q == StBusy);
busy = tmp | g_lane[0].lane_q;
end
always_ff @(posedge clk) state_q <= StIdle;
endmodule
";
#[test]
fn qa_rework_every_local_kind_is_found_and_renamed_by_name_file_and_unit() {
let cases = [
("state_e", "typedef state_e rtl/fsm.sv:2", "renamed 2 sites in 1 file"),
("StIdle", "enum_value StIdle rtl/fsm.sv:2", "renamed 2 sites in 1 file"),
("helper", "function helper rtl/fsm.sv:4", "renamed 2 sites in 1 file"),
("hl", "var hl rtl/fsm.sv:5", "renamed 3 sites in 1 file"),
("poke", "task poke rtl/fsm.sv:9", "renamed 1 site in 1 file"),
("gi", "genvar gi rtl/fsm.sv:12", "renamed 4 sites in 1 file"),
("tmp", "var tmp rtl/fsm.sv:17", "renamed 3 sites in 1 file"),
];
for (name, found, renamed) in cases {
let named = [
json!({"name": name, "new_name": "zz_new"}),
json!({"name": name, "new_name": "zz_new", "file": "rtl/fsm.sv"}),
json!({"name": format!("fsm.{name}"), "new_name": "zz_new"}),
];
for args in named {
let tree = Tree::with(&[("rtl/fsm.sv", LOCALS)]);
assert_eq!(text(&tree, "find", json!({"name": name})), format!("{found}\n"));
assert_eq!(
text(&tree, "find", json!({"name": format!("fsm.{name}")})),
format!("{found}\n")
);
assert_eq!(text(&tree, "rename", args.clone()), format!("{renamed}\n"), "{args}");
let after = tree.read("rtl/fsm.sv");
let left = after
.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
.any(|word| word == name);
assert!(!left, "{args}: `{name}` left in\n{after}");
}
}
}
#[test]
fn qa_rework_renaming_a_generate_label_never_leaves_a_path_through_it_behind() {
// `find g_lane refs` used to list no use and `rename` answered `renamed
// 1 site`, leaving `g_lane[0].lane_q` naming a block that no longer
// existed — while `edit_item delete g_lane` saw the use
// (`rtl/fsm.sv:19:18`). Lead's ruling R1 had the MCP layer refuse the
// rename; TODO §65.1 fixed the engine (a path segment through a block is
// a reference to its label), and the refusal is lifted.
let tree = Tree::with(&[("rtl/fsm.sv", LOCALS)]);
let found = text(&tree, "find", json!({"name": "g_lane", "refs": true}));
assert_eq!(found, "block g_lane rtl/fsm.sv:12\n rtl/fsm.sv:19\n");
let renamed = text(&tree, "rename", json!({"name": "g_lane", "new_name": "g_ln"}));
assert_eq!(renamed, "renamed 2 sites in 1 file\n");
assert_eq!(tree.read("rtl/fsm.sv"), LOCALS.replace("g_lane", "g_ln"));
assert!(tree.read("rtl/fsm.sv").contains("busy = tmp | g_ln[0].lane_q;"));
}
#[test]
fn qa_rework_a_shared_base_name_is_named_by_path_or_left_alone() {
let tree = Tree::with(&[
("rtl/x/p1.sv", "module px (input logic clk);\n logic dup;\n assign dup = clk;\nendmodule\n"),
(
"rtl/y/p1.sv",
"module py (input logic clk);\n logic dup;\n assign dup = ~clk;\n sub u_s (.*);\nendmodule\n",
),
("rtl/z/sub.sv", "module sub (input logic clk, input logic a);\nendmodule\n"),
("rtl/z/p1b.sv", "module pz (input logic clk);\n logic a;\n sub u_s (.clk, .a);\nendmodule\n"),
]);
let both = refusal(&tree, "rename", json!({"name": "dup", "new_name": "d2"}));
assert!(both.contains("(rtl/x/p1.sv:2, rtl/y/p1.sv:2)"), "{both}");
let one = json!({"name": "dup", "new_name": "d2", "file": "rtl/y/p1.sv"});
assert_eq!(text(&tree, "rename", one), "renamed 2 sites in 1 file\n");
assert!(tree.read("rtl/y/p1.sv").contains("logic d2;"));
assert!(tree.read("rtl/x/p1.sv").contains("logic dup;"));
// The engine's sentences: `p1.sv` is two files, so the engine names it by
// the path it was given and the answer makes that root-relative (§65.1
// re-check R1 — it used to stay a bare, unplaceable `p1.sv`); `p1b.sv`
// is one, so it is named by its path too.
let added = text(&tree, "port", json!({"module": "sub", "add": "input logic zz"}));
assert!(
added.contains("`u_s` at rtl/y/p1.sv:4 connects with `.*` and rtl/y/p1.sv has"),
"{added}"
);
assert!(added.contains("(rtl/z/p1b.sv:3)"), "{added}");
assert!(!added.contains("rtl/z/rtl/"), "{added}");
}
#[test]
fn qa_rework_an_enum_value_in_case_arms_is_renamed_across_files_with_its_mentions() {
let tree = Tree::with(&[
("rtl/st_pkg.sv", "package st_pkg;\n typedef enum logic [1:0] {StIdle, StRun, StDone} st_e;\nendpackage\n"),
(
"rtl/a.sv",
"module a import st_pkg::*; (input logic clk, output logic o);\n st_e s;\n // StRun is the busy state\n always_comb begin\n case (s)\n StIdle: o = 1'b0;\n StRun: o = 1'b1;\n default: o = 1'b0;\n endcase\n end\n always_ff @(posedge clk) s <= StRun;\nendmodule\n",
),
(
"rtl/b.sv",
"module b (input logic clk, output logic o);\n st_pkg::st_e s;\n initial $display(\"StRun\");\n always_comb begin\n unique case (s)\n st_pkg::StRun: o = 1'b1;\n default: o = 1'b0;\n endcase\n end\n always_ff @(posedge clk) s <= st_pkg::StIdle;\nendmodule\n",
),
]);
let found = text(&tree, "find", json!({"name": "StRun", "refs": true}));
let mentions = "unresolved:\n rtl/a.sv:3\n rtl/b.sv:3\n";
assert_eq!(
found,
format!("enum_value StRun rtl/st_pkg.sv:2\n rtl/a.sv:7,11\n rtl/b.sv:6\n{mentions}")
);
// Only in a comment or a string: no declaration, a sane near match.
assert_eq!(refusal(&tree, "find", json!({"name": "busy"})), "no declaration named `busy`.");
assert_eq!(
refusal(&tree, "find", json!({"name": "StRu"})),
"no declaration named `StRu`; similar: StRun."
);
let renamed = text(&tree, "rename", json!({"name": "st_pkg::StRun", "new_name": "StBusy"}));
assert_eq!(renamed, format!("renamed 4 sites in 3 files\n{mentions}"));
assert!(tree.read("rtl/b.sv").contains("st_pkg::StBusy: o"));
assert!(
tree.read("rtl/a.sv").contains("// StRun is")
&& tree.read("rtl/a.sv").contains("s <= StBusy;")
);
}
#[test]
fn qa_rework_an_escaped_net_is_still_found_through_the_index() {
let text_e = "module e (input logic clk, output logic o);\n logic \\my.sig ;\n assign \\my.sig = clk;\n assign o = \\my.sig ;\nendmodule\n";
let tree = Tree::with(&[("rtl/e.sv", text_e)]);
let found = text(&tree, "find", json!({"name": "\\my.sig", "refs": true}));
assert_eq!(found, "var \\my.sig rtl/e.sv:2\n rtl/e.sv:3,4\n");
}
#[test]
#[ignore = "QA re-check finding R2"]
fn qa_rework_an_escaped_local_outline_lists_is_found() {
// The word census holds identifier-shaped words only, so `declared.rs`
// never opens a file for an escaped name the index does not record.
let text_g = "module g (input logic clk, output logic o);\n function automatic logic fn(input logic x);\n logic \\loc.v ;\n \\loc.v = x;\n return \\loc.v ;\n endfunction\n assign o = fn(clk);\nendmodule\n";
let tree = Tree::with(&[("rtl/g.sv", text_g)]);
assert!(text(&tree, "outline", json!({"file": "rtl/g.sv"})).contains("var \\loc.v 3"));
assert_eq!(text(&tree, "find", json!({"name": "\\loc.v"})), "var \\loc.v rtl/g.sv:3\n");
}
#[test]
fn a_rename_names_each_same_named_file_by_its_root_relative_path_once() {
// §65.1 re-check R1 and the lead's fifth ruling: two `x_if.sv` holding an
// unresolved path through the label are two findable warning lines, and
// neither line is repeated under `unresolved:`.
let probe = "module probe_IDX (output logic o);\n assign o = tb.dut.g_sw.q;\nendmodule\n";
let (a, b) = (probe.replace("IDX", "a"), probe.replace("IDX", "b"));
let tree = Tree::with(&[
("rtl/dut.sv", "module dut_x;\n if (1) begin : g_sw\n logic q;\n end\nendmodule\n"),
("dv/a/x_if.sv", a.as_str()),
("dv/b/x_if.sv", b.as_str()),
]);
let said = text(&tree, "rename", json!({"name": "g_sw", "new_name": "g_hw"}));
let path_lines: Vec<&str> =
said.lines().filter(|line| line.contains("a hierarchical path through")).collect();
assert_eq!(path_lines.len(), 2, "{said}");
assert!(path_lines[0].starts_with("warning: dv/a/x_if.sv:2: "), "{said}");
assert!(path_lines[1].starts_with("warning: dv/b/x_if.sv:2: "), "{said}");
assert!(!said.contains("unresolved:"), "each line is said once: {said}");
assert!(tree.read("rtl/dut.sv").contains("begin : g_hw"));
}
#[test]
fn a_members_rename_lists_only_its_own_mentions_and_dotted_ones_elsewhere() {
// §65.1, lead's inspection: two modules each with a `state_q`, each
// spelling it in an `ASSERT argument, a comment and a string. Renaming
// `a`'s warns and lists only `a`'s — plus `b`'s dotted spellings, which
// may be paths to it. A package-level name still lists everything.
let defs = "`define ASSERT(n, e) n: assert property (e);\n";
let a = "module a (input logic clk);\n logic state_q;\n always_ff @(posedge clk) state_q <= ~state_q;\n `ASSERT(A_T, state_q)\n // state_q is a's\n initial $display(\"state_q\");\nendmodule\n";
let b = "module b (input logic clk);\n logic state_q;\n a u_a (.clk);\n always_ff @(posedge clk) state_q <= ~state_q;\n `ASSERT(B_T, state_q)\n `ASSERT(B_P, u_a.state_q)\n // state_q is b's\n initial $display(\"state_q\");\n initial $display(\"u_a.state_q\");\nendmodule\n";
let pkg = "package p;\n localparam int W = 1;\nendpackage\n";
let user = "module u import p::*;\n // W is p's\n localparam int X = W;\nendmodule\n";
let tree = Tree::with(&[
("rtl/defs.svh", defs),
("rtl/a.sv", a),
("rtl/b.sv", b),
("rtl/p.sv", pkg),
("rtl/u.sv", user),
]);
let said = text(&tree, "rename", json!({"name": "a.state_q", "new_name": "state_r"}));
let macro_lines: Vec<&str> = said.lines().filter(|l| l.contains("macro invocation")).collect();
assert_eq!(macro_lines.len(), 2, "{said}");
assert!(
macro_lines[0].contains("rtl/a.sv:4") && macro_lines[1].contains("rtl/b.sv:6"),
"{said}"
);
assert!(said.ends_with("unresolved:\n rtl/a.sv:4,5,6\n rtl/b.sv:6,9\n"), "{said}");
assert!(tree.read("rtl/b.sv").contains("logic state_q;"), "b's own stays");
let found = text(&tree, "find", json!({"name": "p.W", "refs": true}));
assert!(found.contains("unresolved:\n rtl/u.sv:2\n"), "a package member lists all: {found}");
}
+557
View File
@@ -0,0 +1,557 @@
//! QA attacks on lane M8 (`--read-only`), 2026-09-29.
//!
//! Every test copies a fixture into its own scratch directory, spawns the
//! real binary over it, writes a whole session to stdin, closes it and reads
//! every answer — the host's view, nothing else. The no-write promise is
//! checked by a snapshot of every entry under the root: a file's size, mtime
//! and bytes, a directory's mtime (which moves when anything is created,
//! renamed or removed in it, a temporary file included).
use std::collections::BTreeMap;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::SystemTime;
use serde_json::{json, Value};
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
/// The message a read-only server refuses `name` with.
fn refused(name: &str) -> String {
format!("unknown tool: {name} (the server runs --read-only)")
}
/// A scratch directory, removed on drop.
struct Tree(PathBuf);
impl Tree {
fn empty() -> Tree {
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
let dir =
std::env::temp_dir().join(format!("lucisv-mcp-qa-m8-{}-{unique}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
Tree(fs::canonicalize(dir).unwrap())
}
/// A fresh copy of `tests/fixtures/<fixture>`.
fn of(fixture: &str) -> Tree {
let tree = Tree::empty();
let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures").join(fixture);
copy_tree(&source, &tree.0);
tree
}
fn arg(&self) -> &str {
self.0.to_str().unwrap()
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn copy_tree(from: &Path, to: &Path) {
fs::create_dir_all(to).unwrap();
for entry in fs::read_dir(from).unwrap() {
let entry = entry.unwrap();
let target = to.join(entry.file_name());
if entry.file_type().unwrap().is_dir() {
copy_tree(&entry.path(), &target);
} else {
fs::copy(entry.path(), target).unwrap();
}
}
}
/// One entry under a root: a file's size, mtime and bytes; a directory's mtime.
type Entry = (Option<u64>, SystemTime, Option<Vec<u8>>);
fn snapshot(tree: &Tree) -> BTreeMap<String, Entry> {
fn walk(dir: &Path, root: &Path, out: &mut BTreeMap<String, Entry>) {
let relative = |path: &Path| path.strip_prefix(root).unwrap().to_string_lossy().to_string();
let meta = fs::symlink_metadata(dir).unwrap();
out.insert(format!("{}/", relative(dir)), (None, meta.modified().unwrap(), None));
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
let meta = fs::symlink_metadata(&path).unwrap();
if meta.is_dir() {
walk(&path, root, out);
} else {
let bytes = fs::read(&path).unwrap();
out.insert(
relative(&path),
(Some(meta.len()), meta.modified().unwrap(), Some(bytes)),
);
}
}
}
let mut out = BTreeMap::new();
walk(&tree.0, &tree.0, &mut out);
out
}
/// Run the binary with `args`, send `lines` (one JSON-RPC message each),
/// close stdin and wait for it to exit.
fn run(args: &[&str], lines: &[Value]) -> Output {
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let mut stdin = child.stdin.take().unwrap();
for line in lines {
// A raw line is passed as a JSON string, everything else serialised.
let text = match line {
Value::String(raw) => raw.clone(),
other => other.to_string(),
};
writeln!(stdin, "{text}").unwrap();
}
drop(stdin);
child.wait_with_output().unwrap()
}
/// Every answer on stdout, by its id as JSON text (`"\"c\""`, `null`).
fn answers(output: &Output) -> BTreeMap<String, Value> {
let stdout = String::from_utf8(output.stdout.clone()).unwrap();
let mut out = BTreeMap::new();
for line in stdout.lines().filter(|l| !l.trim().is_empty()) {
let reply: Value = serde_json::from_str(line).expect("every stdout line is JSON");
out.entry(reply["id"].to_string()).or_insert(reply);
}
out
}
fn request(id: &str, method: &str, params: Value) -> Value {
json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params})
}
fn call(id: &str, name: Value, arguments: Value) -> Value {
request(id, "tools/call", json!({"name": name, "arguments": arguments}))
}
fn initialize(id: &str) -> Value {
request(id, "initialize", json!({"protocolVersion": "2025-06-18", "capabilities": {}}))
}
/// Every shape of every edit tool, each a real write in full mode
/// (`qa_every_edit_shape_writes_in_full_mode`), on the `edit` fixture.
fn edit_shapes() -> Vec<(&'static str, Value)> {
vec![
("rename", json!({"name": "leaf", "new_name": "leaf2"})),
("rename", json!({"name": "d", "file": "rtl/leaf.sv", "new_name": "din_i"})),
("port", json!({"module": "spare", "add": "input logic en"})),
("port", json!({"module": "spare", "add": "input logic en2", "after": "clk"})),
("port", json!({"module": "spare", "remove": "unused_i"})),
(
"edit_item",
json!({"file": "rtl/mid.sv", "op": "replace", "item": "u_leaf", "text": "leaf u_leaf (.clk(clk), .d(din), .q(dout));"}),
),
(
"edit_item",
json!({"file": "rtl/leaf.sv", "op": "insert_before", "item": "end", "text": "logic spare_b;"}),
),
(
"edit_item",
json!({"file": "rtl/leaf.sv", "op": "insert_after", "item": "end", "text": "logic spare_a;"}),
),
("edit_item", json!({"file": "rtl/spare_user.sv", "op": "delete", "item": "spare_user"})),
("format", json!({"files": "fmt/messy.sv"})),
("format", json!({"files": "fmt/messy.sv", "fix": true})),
("format", json!({"files": "**/*.sv", "fix": true})),
("format", json!({"files": "rtl"})),
]
}
#[test]
fn qa_every_edit_shape_writes_in_full_mode() {
// The control for the promise: each shape really edits without the flag.
for (index, (name, arguments)) in edit_shapes().into_iter().enumerate() {
let tree = Tree::of("edit");
let before = snapshot(&tree);
let lines = [initialize("i"), call("c", json!(name), arguments.clone())];
let output = run(&["--root", tree.arg()], &lines);
let reply = &answers(&output)["\"c\""];
assert_eq!(reply["result"]["isError"], false, "{index} {name} {arguments}: {reply}");
assert_ne!(before, snapshot(&tree), "{index} {name} wrote nothing in full mode");
}
}
/// The malformed and near-miss calls a read-only server must refuse, each
/// with the code and message it must answer.
fn hostile_calls() -> Vec<(Value, i64, String)> {
let mut out = Vec::new();
// Names that differ from an edit tool by case, whitespace or spelling.
for name in [
"Rename",
"RENAME",
" rename",
"rename ",
"rename\n",
"rename\u{0}",
"edit-item",
"editItem",
"Format",
"port ",
"\u{ff52}ename",
"format\t",
] {
out.push((call(&format!("n{}", out.len()), json!(name), json!({})), -32602, refused(name)));
}
// A name that is not a string.
let not_string = "tools/call params need a string `name`".to_string();
for name in [json!(6), json!(["rename"]), json!({"name": "rename"}), json!(null), json!(true)] {
out.push((call(&format!("t{}", out.len()), name, json!({})), -32602, not_string.clone()));
}
// An edit name with malformed or smuggled arguments.
// The name is looked up before the arguments are read.
for arguments in
[json!(null), json!([]), json!("x"), json!({"name": 1}), json!({"mode": "full"})]
{
let line = call(&format!("a{}", out.len()), json!("rename"), arguments);
out.push((line, -32602, refused("rename")));
}
let meta = request(
"meta",
"tools/call",
json!({"name": "format", "arguments": {"files": "rtl"}, "_meta": {"mode": "full"}, "mode": "full"}),
);
out.push((meta, -32602, refused("format")));
out
}
#[test]
fn qa_read_only_never_changes_a_byte_whatever_arrives() {
let tree = Tree::of("edit");
let before = snapshot(&tree);
let mut lines = Vec::new();
// Before `initialize`: refused as not initialized, never run.
for (index, (name, arguments)) in edit_shapes().into_iter().enumerate() {
lines.push(call(&format!("early{index}"), json!(name), arguments));
}
lines.push(initialize("init"));
lines.push(json!({"jsonrpc": "2.0", "method": "notifications/initialized"}));
// Every edit shape as a request and as a notification (no id).
for (index, (name, arguments)) in edit_shapes().into_iter().enumerate() {
lines.push(call(&format!("edit{index}"), json!(name), arguments.clone()));
let params = json!({"name": name, "arguments": arguments});
lines.push(json!({"jsonrpc": "2.0", "method": "tools/call", "params": params}));
lines.push(
json!({"jsonrpc": "2.0", "method": format!("notifications/{name}"), "params": params}),
);
}
let hostile = hostile_calls();
lines.extend(hostile.iter().map(|(line, _, _)| line.clone()));
// A batch, a duplicate `name` key, a second `initialize` asking for more.
lines.push(json!([call("batched", json!("format"), json!({"files": "rtl"}))]));
lines.push(json!(r#"{"jsonrpc":"2.0","id":"dup","method":"tools/call","params":{"name":"check","name":"format","arguments":{"files":"rtl"}}}"#));
lines.push(request(
"reinit",
"initialize",
json!({"capabilities": {"experimental": {"mode": "full"}}}),
));
lines.push(call("after-reinit", json!("format"), json!({"files": "rtl"})));
for uri in [
"lucisv://overview",
"lucisv://rules",
"lucisv://unit/leaf",
"lucisv://unit/spare",
"lucisv://file/rtl/leaf.sv/outline",
"lucisv://file/fmt%2Fmessy.sv/outline",
"lucisv://format/fmt/messy.sv",
"lucisv://unit/..%2F..%2Fetc",
] {
lines.push(request(&format!("res {uri}"), "resources/read", json!({"uri": uri})));
}
for method in ["notifications/cancelled", "notifications/roots/list_changed", "notifications/x"]
{
lines.push(json!({"jsonrpc": "2.0", "method": method, "params": {"requestId": "edit0"}}));
}
lines.push(call("still", json!("check"), json!({})));
let output = run(&["--root", tree.arg(), "--read-only"], &lines);
assert!(output.status.success(), "{:?}", output.status);
let answers = answers(&output);
for index in 0..edit_shapes().len() {
assert_eq!(answers[&format!("\"early{index}\"")]["error"]["code"], -32002);
}
for (index, (name, _)) in edit_shapes().into_iter().enumerate() {
let reply = &answers[&format!("\"edit{index}\"")];
assert_eq!(reply["error"]["code"], -32602, "{reply}");
assert_eq!(reply["error"]["message"], refused(name), "{reply}");
}
for (line, code, message) in &hostile {
let reply = &answers[&line["id"].to_string()];
assert_eq!(reply["error"]["code"], *code, "{line} -> {reply}");
assert_eq!(reply["error"]["message"], *message, "{line} -> {reply}");
}
assert_eq!(answers["null"]["error"]["code"], -32600, "the batch is refused");
assert_eq!(answers["\"dup\""]["error"]["message"], refused("format"), "last key wins");
assert_eq!(answers["\"after-reinit\""]["error"]["message"], refused("format"));
assert_eq!(answers["\"still\""]["result"]["isError"], false);
assert_eq!(before, snapshot(&tree), "read-only mode changed the tree");
}
/// The first `tools/list` answer's tool names for a server started with `args`.
fn listed(args: &[&str]) -> (Option<Vec<String>>, Output) {
let output = run(args, &[initialize("i"), request("l", "tools/list", json!({}))]);
let names = answers(&output).get("\"l\"").map(|reply| {
let tools = reply["result"]["tools"].as_array().unwrap();
tools.iter().map(|t| t["name"].as_str().unwrap().to_string()).collect()
});
(names, output)
}
#[test]
fn qa_argument_order_and_repetition_cannot_undo_read_only() {
let tree = Tree::of("design");
let root = tree.arg();
let five = ["hierarchy", "find", "outline", "read", "check"].map(String::from).to_vec();
for args in [
vec!["--read-only", "--root", root],
vec!["--root", root, "--read-only", "--read-only"],
vec!["--read-only", "--verbose", "--root", root, "--read-only"],
] {
let (names, output) = listed(&args);
assert_eq!(names.as_ref(), Some(&five), "{args:?}: {output:?}");
}
// A value for the flag is refused by the usage rule, never read as full.
for args in [
vec!["--root", root, "--read-only=false"],
vec!["--root", root, "--read-only", "false"],
vec!["--root", root, "--read-only=true"],
vec!["--root", root, "--readonly"],
vec!["--root", root, "--no-read-only"],
] {
let (names, output) = listed(&args);
assert_eq!(names, None, "{args:?} started a server");
assert_eq!(output.status.code(), Some(2), "{args:?}");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("unknown option") && stderr.contains("[--read-only]"), "{stderr}");
}
}
/// The text of every `tools/call` and `resources/read` answer, by id.
fn texts(args: &[&str], lines: &[Value]) -> BTreeMap<String, String> {
let mut session = vec![initialize("i")];
session.extend_from_slice(lines);
let output = run(args, &session);
let mut out = BTreeMap::new();
for (id, reply) in answers(&output) {
let result = &reply["result"];
let text = result["content"][0]["text"]
.as_str()
.or_else(|| result["contents"][0]["text"].as_str())
.map(str::to_string)
.unwrap_or_else(|| reply.to_string());
out.insert(id, text);
}
out.remove("\"i\"");
out
}
#[test]
fn qa_the_read_tools_and_resources_answer_identically_in_both_modes() {
let reads = [
("design", "hierarchy", json!({})),
("design", "hierarchy", json!({"root": "top", "depth": 3, "peek": true})),
("design", "find", json!({"name": "leaf", "refs": true})),
("design", "outline", json!({"file": "rtl/top.sv"})),
("design", "read", json!({"item": "top"})),
("design", "check", json!({})),
("design", "check", json!({"file": "rtl/broken.sv"})),
("design", "find", json!({"nome": "x"})),
("edit", "hierarchy", json!({"root": "leaf", "up": true})),
("edit", "outline", json!({"unit": "spare"})),
("edit", "check", json!({"file": "fmt/messy.sv"})),
("edit", "read", json!({"item": "u_leaf", "file": "rtl/mid.sv"})),
];
for fixture in ["design", "edit"] {
let tree = Tree::of(fixture);
let mut lines: Vec<Value> = reads
.iter()
.enumerate()
.filter(|(_, (f, _, _))| *f == fixture)
.map(|(index, (_, name, arguments))| {
call(&format!("r{index}"), json!(name), arguments.clone())
})
.collect();
for uri in ["lucisv://overview", "lucisv://rules", "lucisv://unit/leaf", "lucisv://nope"] {
lines.push(request(uri, "resources/read", json!({"uri": uri})));
}
for method in ["resources/list", "resources/templates/list", "prompts/list"] {
lines.push(request(method, method, json!({})));
}
let full = texts(&["--root", tree.arg()], &lines);
let read_only = texts(&["--root", tree.arg(), "--read-only"], &lines);
assert_eq!(full.len(), lines.len(), "{fixture}: {full:?}");
assert_eq!(full, read_only, "{fixture}");
}
}
#[test]
fn qa_a_read_only_index_cache_outside_the_root_leaves_the_root_alone() {
// The store is written where it is told (the extension's workspace
// storage); the root is not, even with the store beside it.
let parent = Tree::empty();
let root = parent.0.join("root");
copy_tree(&Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/edit"), &root);
let tree = Tree(root);
let cache = parent.0.join("cache");
let before = snapshot(&tree);
let lines = [
initialize("i"),
call("c", json!("format"), json!({"files": "rtl"})),
call("k", json!("check"), json!({})),
];
let output = run(
&["--root", tree.arg(), "--index-cache", cache.to_str().unwrap(), "--read-only"],
&lines,
);
assert!(output.status.success());
assert_eq!(before, snapshot(&tree));
assert!(cache.join(".gitignore").exists(), "the store directory was written");
}
// ---------------------------------------------------------------------------
// Re-check 2026-09-29: `hierarchy`'s cap counts nodes, never peek lines.
// ---------------------------------------------------------------------------
/// `module name` with `count` instances of `child`, each written over 14
/// lines (header, 12 port lines, closer), so each peek block is cut to 12
/// lines and `…` — 14 answer lines per node.
fn wide_parent(name: &str, child: &str, count: usize) -> (String, String) {
let mut text = format!("module {name};\n");
for i in 0..count {
text.push_str(&format!(" {child} u_{i:03} (\n"));
for p in 0..12 {
let comma = if p < 11 { "," } else { "" };
text.push_str(&format!(" .p{p}(1'b0){comma}\n"));
}
text.push_str(" );\n");
}
text.push_str("endmodule\n");
(format!("{name}.sv"), text)
}
/// A 12-input leaf module.
fn leaf(name: &str) -> (String, String) {
let ports: Vec<String> = (0..12).map(|p| format!("input logic p{p}")).collect();
(format!("{name}.sv"), format!("module {name} ({});\nendmodule\n", ports.join(", ")))
}
/// `dN` declares N instances (N + 1 nodes with its root line); `uN` is
/// instantiated N times (N nodes up). Sizes sit on both caps' boundaries:
/// 300/301 nodes without `peek`, 100/101 with it.
fn boundary_tree() -> Tree {
let tree = Tree::empty();
let files = [
leaf("x"),
leaf("y"),
leaf("u100"),
leaf("u101"),
leaf("u300"),
leaf("u301"),
wide_parent("d99", "x", 99),
wide_parent("d100", "y", 100),
wide_parent("d299", "x", 299),
wide_parent("d300", "y", 300),
wide_parent("h100", "u100", 100),
wide_parent("h101", "u101", 101),
wide_parent("h300", "u300", 300),
wide_parent("h301", "u301", 301),
];
for (path, text) in files {
fs::write(tree.0.join(path), text).unwrap();
}
tree
}
/// Each call's text, in order, from one session in `mode_args`.
fn hierarchy_texts(tree: &Tree, calls: &[Value], mode_args: &[&str]) -> Vec<String> {
let mut args = vec!["--root", tree.arg()];
args.extend_from_slice(mode_args);
let mut lines = vec![initialize("i")];
lines.extend(
calls
.iter()
.enumerate()
.map(|(n, a)| call(&format!("h{n}"), json!("hierarchy"), a.clone())),
);
let answers = answers(&run(&args, &lines));
(0..calls.len())
.map(|n| {
let reply = &answers[&format!("\"h{n}\"")];
assert_eq!(reply["result"]["isError"], false, "{reply}");
reply["result"]["content"][0]["text"].as_str().unwrap().to_string()
})
.collect()
}
/// The node cap without `peek` (PLAN §10.1).
const PLAIN_CAP: usize = 300;
/// The node cap with `peek` (M8 rework 3).
const PEEK_CAP: usize = 100;
#[test]
fn qa_the_node_cap_is_exact_at_300_and_301_plain_and_100_and_101_with_peek() {
let tree = boundary_tree();
// (arguments, nodes in the whole answer, statement indent)
let cases = [
(json!({"root": "d99"}), 100, " "),
(json!({"root": "d100"}), 101, " "),
(json!({"root": "d299"}), 300, " "),
(json!({"root": "d300"}), 301, " "),
(json!({"root": "u100", "up": true}), 100, " "),
(json!({"root": "u101", "up": true}), 101, " "),
(json!({"root": "u300", "up": true}), 300, " "),
(json!({"root": "u301", "up": true}), 301, " "),
];
let mut calls = Vec::new();
for (arguments, _, _) in &cases {
calls.push(arguments.clone());
let mut peeked = arguments.clone();
peeked["peek"] = json!(true);
calls.push(peeked);
}
let full = hierarchy_texts(&tree, &calls, &[]);
assert_eq!(full, hierarchy_texts(&tree, &calls, &["--read-only"]), "the modes disagree");
for (at, (arguments, total, indent)) in cases.iter().enumerate() {
let root_lines = usize::from(arguments["up"] != true);
let cut_line = |cap: usize| (*total > cap).then(|| format!("… and {} more", total - cap));
// Without peek: one line per node, at most 300, then the cut line.
let plain: Vec<&str> = full[2 * at].lines().collect();
let (plain_shown, plain_cut) = ((*total).min(PLAIN_CAP), cut_line(PLAIN_CAP));
assert_eq!(plain.len(), plain_shown + usize::from(plain_cut.is_some()), "{arguments}");
if let Some(cut) = &plain_cut {
assert_eq!(plain.last().copied(), Some(cut.as_str()), "{arguments}");
}
// With peek: the first 100 of the same node lines, then its own cut line.
let peek: Vec<&str> = full[2 * at + 1].lines().collect();
let (shown, cut) = ((*total).min(PEEK_CAP), cut_line(PEEK_CAP));
let nodes: Vec<&str> = peek.iter().copied().filter(|l| !l.starts_with(indent)).collect();
let mut expected: Vec<&str> = plain[..shown].to_vec();
if let Some(cut) = &cut {
expected.push(cut.as_str());
}
assert_eq!(nodes, expected, "{arguments}");
// Every instance node is followed by a whole block: 12 lines, then `…`.
let instances = shown - root_lines;
let cut_lines = usize::from(cut.is_some());
assert_eq!(peek.len(), root_lines + instances * 14 + cut_lines, "{arguments}");
let blocks = peek.iter().filter(|l| l.trim() == "…").count();
assert_eq!(blocks, instances, "{arguments}");
if cut.is_some() {
// The block before the cut line is whole: it ends in `…`.
assert_eq!(peek[peek.len() - 2].trim(), "…", "{arguments}");
}
}
}
+341
View File
@@ -0,0 +1,341 @@
//! `lucisv-mcp --read-only` (PLAN §11), pinned against the real binary: the
//! five read tools within their budget, the edit tools unknown, full mode as
//! 0.58.0 shipped it, and the promise that nothing inside a root is created,
//! written, renamed or removed whatever is called.
use std::collections::BTreeMap;
use std::fs;
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{self, Receiver};
use std::time::{Duration, SystemTime};
use serde_json::{json, Value};
/// How long one answer may take before the test calls the server hung.
const ANSWER_TIMEOUT: Duration = Duration::from_secs(60);
/// The five read tools, in the order `tools/list` gives them.
const FIVE: [&str; 5] = ["hierarchy", "find", "outline", "read", "check"];
/// The four edit tools full mode adds after them.
const EDITS: [&str; 4] = ["rename", "port", "edit_item", "format"];
/// The read-only ceilings (PLAN §11.1).
const CATALOGUE_BUDGET: usize = 1_800;
const INSTRUCTIONS_BUDGET: usize = 300;
/// The instructions 0.58.0 shipped (PLAN §10.3), which full mode keeps.
const FULL_INSTRUCTIONS: &str = "lucisv-mcp reads the SystemVerilog on disk (save first). Use it before reading files: hierarchy for instance trees and top modules, find for a name's declarations and uses, outline for a file or unit's ports, read for one item, check after edits. Edits (rename, port, edit_item, format) are verified, all-or-nothing writes: trust them as file writes, no dry run. Paths root-relative, lines 1-based.";
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
/// A fresh directory under the system temp dir, removed on drop.
struct Tree(PathBuf);
impl Tree {
fn empty() -> Tree {
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
let dir = std::env::temp_dir()
.join(format!("lucisv-mcp-read-only-{}-{unique}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
Tree(fs::canonicalize(dir).unwrap())
}
/// A fresh copy of `tests/fixtures/<fixture>`.
fn of(fixture: &str) -> Tree {
let tree = Tree::empty();
let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures").join(fixture);
copy_tree(&source, &tree.0);
tree
}
fn arg(&self) -> &str {
self.0.to_str().unwrap()
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn copy_tree(from: &Path, to: &Path) {
fs::create_dir_all(to).unwrap();
for entry in fs::read_dir(from).unwrap() {
let entry = entry.unwrap();
let target = to.join(entry.file_name());
if entry.file_type().unwrap().is_dir() {
copy_tree(&entry.path(), &target);
} else {
fs::copy(entry.path(), target).unwrap();
}
}
}
/// One running server.
struct Session {
child: Child,
stdin: Option<ChildStdin>,
lines: Receiver<String>,
next_id: i64,
}
impl Session {
fn spawn(args: &[&str]) -> Session {
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
let stdout = child.stdout.take().unwrap();
let (send, lines) = mpsc::channel();
std::thread::spawn(move || {
for line in BufReader::new(stdout).lines() {
let Ok(line) = line else { break };
if send.send(line).is_err() {
break;
}
}
});
let stdin = child.stdin.take();
Session { child, stdin, lines, next_id: 0 }
}
/// A server over `tree`, in read-only mode unless `full`, initialised;
/// returns the `initialize` result too.
fn over(tree: &Tree, full: bool) -> (Session, Value) {
let mut args = vec!["--root", tree.arg()];
if !full {
args.push("--read-only");
}
let mut server = Session::spawn(&args);
let init = server.initialize();
(server, init)
}
fn request(&mut self, method: &str, params: Value) -> Value {
self.next_id += 1;
let id = self.next_id;
let line = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params});
let stdin = self.stdin.as_mut().unwrap();
writeln!(stdin, "{line}").unwrap();
stdin.flush().unwrap();
let reply = self.lines.recv_timeout(ANSWER_TIMEOUT).expect("the server answered");
let reply: Value = serde_json::from_str(&reply).expect("every stdout line is JSON");
assert_eq!(reply["id"], id, "answers come back in order");
reply
}
fn initialize(&mut self) -> Value {
let params = json!({"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "read-only", "version": "0"}});
self.request("initialize", params)["result"].clone()
}
fn call(&mut self, tool: &str, arguments: Value) -> Value {
self.request("tools/call", json!({"name": tool, "arguments": arguments}))
}
/// Close stdin and wait for the server to exit (it writes its own index
/// store, when it has one, on the way out).
fn finish(mut self) {
drop(self.stdin.take());
let status = self.child.wait().unwrap();
assert!(status.success(), "{status}");
}
}
impl Drop for Session {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
/// The tools a `tools/list` answer offers.
fn tools(server: &mut Session) -> Vec<Value> {
server.request("tools/list", json!({}))["result"]["tools"].as_array().unwrap().clone()
}
fn names(tools: &[Value]) -> Vec<String> {
tools.iter().map(|t| t["name"].as_str().unwrap().to_string()).collect()
}
/// What the model reads every session: name, description and schema of
/// every tool, compact JSON — the measure `wire.rs` budgets full mode by.
fn visible_bytes(tools: &[Value]) -> usize {
let visible: Vec<Value> = tools
.iter()
.map(|t| json!({"name": t["name"], "description": t["description"], "inputSchema": t["inputSchema"]}))
.collect();
serde_json::to_string(&visible).unwrap().len()
}
#[test]
fn read_only_offers_the_five_read_tools_in_order_within_both_budgets() {
let tree = Tree::of("design");
let (mut server, init) = Session::over(&tree, false);
let instructions = init["instructions"].as_str().unwrap();
assert!(instructions.len() <= INSTRUCTIONS_BUDGET, "instructions: {}", instructions.len());
assert!(instructions.contains("it never edits"), "{instructions}");
for name in FIVE {
assert!(instructions.contains(name), "{name}: {instructions}");
}
let words: Vec<&str> = instructions.split(|c: char| !c.is_alphanumeric() && c != '_').collect();
for name in EDITS {
assert!(!words.contains(&name), "{name}: {instructions}");
}
let offered = tools(&mut server);
assert_eq!(names(&offered), FIVE);
let bytes = visible_bytes(&offered);
assert!(bytes <= CATALOGUE_BUDGET, "the read-only catalogue is {bytes} bytes");
for tool in &offered {
assert_eq!(tool["annotations"]["readOnlyHint"], true, "{tool}");
}
// The same five, word for word and schema for schema, as full mode's.
let (mut full, _) = Session::over(&tree, true);
assert_eq!(offered[..], tools(&mut full)[..5]);
}
#[test]
fn an_edit_tool_in_read_only_mode_is_an_unknown_tool() {
let tree = Tree::of("edit");
let (mut server, _) = Session::over(&tree, false);
for (name, arguments) in edit_calls() {
let reply = server.call(name, arguments);
assert!(reply.get("result").is_none(), "{name}: {reply}");
assert_eq!(reply["error"]["code"], -32602, "{name}: {reply}");
assert_eq!(
reply["error"]["message"],
format!("unknown tool: {name} (the server runs --read-only)")
);
}
// A read tool still answers after the refusals.
let reply = server.call("check", json!({"file": "rtl/leaf.sv"}));
assert_eq!(reply["result"]["isError"], false, "{reply}");
}
#[test]
fn full_mode_is_the_nine_tools_and_the_058_instructions() {
let tree = Tree::of("design");
let (mut server, init) = Session::over(&tree, true);
assert_eq!(init["instructions"], FULL_INSTRUCTIONS);
let offered = tools(&mut server);
let expected: Vec<&str> = FIVE.iter().chain(EDITS.iter()).copied().collect();
assert_eq!(names(&offered), expected);
let reply = server.call("nope", json!({}));
assert_eq!(reply["error"]["message"], "unknown tool: nope");
}
// ---------------------------------------------------------------------------
// The promise: nothing inside a root changes, whatever is called.
// ---------------------------------------------------------------------------
/// A valid edit for each edit tool on the `edit` fixture — each one writes
/// in full mode (`the_edit_calls_write_in_full_mode`).
fn edit_calls() -> Vec<(&'static str, Value)> {
vec![
("rename", json!({"name": "d", "file": "rtl/leaf.sv", "new_name": "din_i"})),
("port", json!({"module": "spare", "add": "input logic en"})),
(
"edit_item",
json!({"file": "rtl/leaf.sv", "op": "insert_before", "item": "end", "text": "logic spare_w;"}),
),
("format", json!({"files": "fmt/messy.sv", "fix": true})),
]
}
/// A plausible call of each read tool on the `edit` fixture.
fn read_calls() -> Vec<(&'static str, Value)> {
vec![
("hierarchy", json!({})),
("hierarchy", json!({"root": "top", "depth": 5, "peek": true})),
("hierarchy", json!({"root": "leaf", "up": true})),
("find", json!({"name": "d", "refs": true})),
("outline", json!({"file": "rtl/leaf.sv"})),
("outline", json!({"unit": "leaf"})),
("read", json!({"item": "leaf"})),
("check", json!({})),
("check", json!({"file": "fmt/messy.sv"})),
]
}
/// Every entry under a tree, root-relative: a file's size and mtime, a
/// directory's mtime (which moves when an entry is created, renamed or
/// removed in it, even a temporary one).
fn snapshot(tree: &Tree) -> BTreeMap<String, (Option<u64>, SystemTime)> {
fn walk(dir: &Path, root: &Path, out: &mut BTreeMap<String, (Option<u64>, SystemTime)>) {
let meta = fs::metadata(dir).unwrap();
let relative = dir.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/");
out.insert(format!("{relative}/"), (None, meta.modified().unwrap()));
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
walk(&path, root, out);
} else {
let meta = fs::metadata(&path).unwrap();
let relative =
path.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/");
out.insert(relative, (Some(meta.len()), meta.modified().unwrap()));
}
}
}
let mut out = BTreeMap::new();
walk(&tree.0, &tree.0, &mut out);
out
}
#[test]
fn read_only_mode_never_touches_the_tree_whatever_is_called() {
let tree = Tree::of("edit");
let cache = Tree::empty();
let before = snapshot(&tree);
let args = ["--root", tree.arg(), "--index-cache", cache.arg(), "--read-only"];
let mut server = Session::spawn(&args);
server.initialize();
for (name, arguments) in read_calls().into_iter().chain(edit_calls()) {
let reply = server.call(name, arguments);
assert!(reply.get("result").is_some() || reply.get("error").is_some(), "{reply}");
}
// Every name again with no arguments, and with arguments it does not take.
for name in FIVE.iter().chain(EDITS.iter()) {
server.call(name, json!({}));
server.call(name, json!({"force": true, "dry_run": false}));
}
for method in ["resources/list", "resources/templates/list"] {
assert!(server.request(method, json!({})).get("result").is_some(), "{method}");
}
for uri in [
"lucisv://overview",
"lucisv://rules",
"lucisv://unit/leaf",
"lucisv://file/rtl/leaf.sv/outline",
] {
let reply = server.request("resources/read", json!({"uri": uri}));
assert!(reply.get("result").is_some(), "{uri}: {reply}");
}
server.finish();
assert_eq!(before, snapshot(&tree), "read-only mode changed the tree");
// The server's own store is outside the roots, and still written.
assert!(fs::read_dir(&cache.0).unwrap().next().is_some(), "no index store was written");
}
#[test]
fn the_edit_calls_write_in_full_mode() {
// The control for the promise above: the same arguments are real edits.
for (name, arguments) in edit_calls() {
let tree = Tree::of("edit");
let before = snapshot(&tree);
let (mut server, _) = Session::over(&tree, true);
let reply = server.call(name, arguments);
assert_eq!(reply["result"]["isError"], false, "{name}: {reply}");
server.finish();
assert_ne!(before, snapshot(&tree), "{name} wrote nothing in full mode");
}
}
File diff suppressed because it is too large. Load diff
+32 -34
View File
@@ -170,16 +170,10 @@ fn leaves_this_file(ws: &Workspace, doc: &Document, offset: u32) -> bool {
}
// A member is reachable as `unit::name`, as `.name` in a connection list
// or as the tail of a hierarchical path, so the unit that owns the
// declaring scope is what to ask about.
let owner = doc
.semantics
.scope(symbol.scope)
.and_then(|scope| scope.owner)
.and_then(|owner| doc.semantics.symbol(owner));
match owner {
Some(owner) => {
!ws.index().member_in(&owner.name, &symbol.name, Surface::Hierarchical).is_empty()
}
// declaring scope is what to ask about — under the key the index files
// it by, which for a named block is `module.label`.
match doc.semantics.member_key(symbol.scope) {
Some(key) => !ws.index().member_in(&key, &symbol.name, Surface::Hierarchical).is_empty(),
None => false,
}
}
@@ -262,11 +256,8 @@ fn indexed_def_in_file<'a>(
let defs = if symbol.scope == semantics.file_scope() {
ws.index().units(&symbol.name)
} else {
let owner = semantics
.scope(symbol.scope)
.and_then(|scope| scope.owner)
.and_then(|owner| semantics.symbol(owner))?;
ws.index().member_in(&owner.name, &symbol.name, Surface::Hierarchical)
let key = semantics.member_key(symbol.scope)?;
ws.index().member_in(&key, &symbol.name, Surface::Hierarchical)
};
if defs.len() != 1 {
return None;
@@ -1510,8 +1501,8 @@ endmodule
);
assert!(leaves_this_file(&ws, doc, at(text, "module m") + 7), "and the module is a unit");
assert!(
!leaves_this_file(&ws, doc, at(text, "wire gen_only") + 5),
"but a generate-block-scoped net is on neither surface"
leaves_this_file(&ws, doc, at(text, "wire gen_only") + 5),
"and since TODO §65.1 so is a generate-block-scoped net, under `m.g`: `u_m.g.gen_only`"
);
assert!(
!leaves_this_file(&ws, doc, at(text, "assign b") + 7),
@@ -2248,13 +2239,13 @@ endpackage
let _ = fs::remove_dir_all(&dir);
}
/// A net declared inside a **generate block** is on neither surface: its
/// scope is the block's, not the module's (`hierarchical-tail`, "a unit's
/// members are the symbols of its own scope"). So the gate still says no
/// and the answer is still the honest single-file one — the same refusal
/// a rename gives `u_x.g.sig`.
/// A net declared inside a **generate block**. Until TODO §65.1 it was on
/// neither surface and this pinned the honest single-file answer; a named
/// block is now on its module's hierarchical surface and its members under
/// `gleaf.g` (`docs/features/generate-label-rename/README.md`), so the gate
/// says yes and `u_g.g.gsig` in the other file is one of the references.
#[test]
fn a_generate_block_scoped_net_still_never_asks_the_workspace() {
fn a_generate_block_scoped_net_is_found_through_the_instance_path() {
let dir = temp_dir("hier_generate");
let leaf = "\
module gleaf;
@@ -2278,11 +2269,15 @@ endmodule
let decl = at(leaf, "wire gsig") + 5;
let doc = ws.document(&leaf_uri).expect("open");
assert!(!leaves_this_file(&ws, doc, decl), "the index exports it on no surface");
assert!(leaves_this_file(&ws, doc, decl), "the index exports it hierarchically");
assert_eq!(
places(&references(&ws, &leaf_uri, decl, true)),
vec![("gleaf.sv".to_string(), 2), ("gleaf.sv".to_string(), 3)],
"this file only, and `u_g.g.gsig` is left to the editor"
vec![
("gleaf.sv".to_string(), 2),
("gleaf.sv".to_string(), 3),
("guser.sv".to_string(), 3)
],
"this file and `u_g.g.gsig`"
);
let _ = fs::remove_dir_all(&dir);
}
@@ -2941,12 +2936,11 @@ endmodule
}
/// Case (a), sharpened: an **indexed generate array**, not just a named
/// block. `u_g.gen[0].gsig` is still on neither surface — the array
/// index changes how many instances of the scope exist, not which scope
/// `gsig` belongs to — so the honest single-file fallback must hold here
/// too.
/// block. The array index changes how many instances of the scope exist,
/// not which scope `gsig` belongs to — which since TODO §65.1 is exactly
/// why `u_g.gen[0].gsig` is walked as `u_g.gen.gsig` and found.
#[test]
fn qa_a_generate_for_arrays_scoped_net_still_never_asks_the_workspace() {
fn qa_a_generate_for_arrays_scoped_net_is_found_through_the_indexed_path() {
let dir = temp_dir("qa_generate_for");
let leaf = "\
module gfleaf;
@@ -2970,11 +2964,15 @@ endmodule
let decl = at(leaf, "wire gsig") + 5;
let doc = ws.document(&leaf_uri).expect("open");
assert!(!leaves_this_file(&ws, doc, decl), "an indexed generate scope is on no surface");
assert!(leaves_this_file(&ws, doc, decl), "a generate array's scope is exported too");
assert_eq!(
places(&references(&ws, &leaf_uri, decl, true)),
vec![("gfleaf.sv".to_string(), 2), ("gfleaf.sv".to_string(), 3)],
"this file only; `u_g.gen[0].gsig` is left to the editor"
vec![
("gfleaf.sv".to_string(), 2),
("gfleaf.sv".to_string(), 3),
("gfuser.sv".to_string(), 3)
],
"this file and `u_g.gen[0].gsig`"
);
let _ = fs::remove_dir_all(&dir);
}
+6 -1
View File
@@ -1168,7 +1168,12 @@ mod tests {
#[test]
fn a_macro_file_the_rename_does_read_is_warned_about_exactly_once() {
let tree = Tree::new("macrocontrol");
let far = format!("module far;\n sub u_far (.sig(1'b0));\n {M_FAR}endmodule\n");
// Spelled after a `.`: since §65.1's scoping of rename warnings, a
// *bare* `sig` in `far`'s own macro is `far`'s word, not `sub`'s port,
// and the engine rightly says nothing about it; a dotted one may be a
// path to the port and is still said — once.
let dotted = M_FAR.replace("sig)", "u_far.sig)");
let far = format!("module far;\n sub u_far (.sig(1'b0));\n {dotted}endmodule\n");
let (ws, uri) = macro_workspace(&tree, &far);
let handed = ws.rename_sources_traced(&tree.path.join("top.sv"), "sig", Some("probe")).0;
@@ -58,7 +58,9 @@ mod large_file;
mod lint_snapshot;
mod progress;
mod pull_diagnostics;
mod qa_generate_label;
mod qa_rename_implicit;
mod rename_generate_label;
mod rename_implicit;
mod requests;
mod scan;
@@ -0,0 +1,86 @@
//! QA attacks on TODO §65.1 over the wire: `references` and `rename` through
//! a block label with the other files closed, and the `member_key` spelling
//! of a block that lives inside a function.
//! `docs/features/generate-label-rename/README.md`, QA log 2026-09-30.
use super::*;
/// `(file name, line)` of every location in a `references` answer.
fn places(found: &Value) -> Vec<(String, u64)> {
let mut out: Vec<(String, u64)> = found
.as_array()
.expect("an array")
.iter()
.map(|l| {
let uri = l["uri"].as_str().unwrap_or("?");
let name = uri.rsplit('/').next().unwrap_or("?").to_string();
(name, l["range"]["start"]["line"].as_u64().unwrap_or(0))
})
.collect();
out.sort();
out
}
fn position(uri: &Uri, text: &str, line: usize, name: &str) -> Value {
let row = text.lines().nth(line).expect("the line");
let character = row.find(name).expect("the name on that line");
serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": line, "character": character },
"context": { "includeDeclaration": true },
})
}
/// A module `ff` with a block `fb` holding `t`, and — in another file — a
/// function `ff` with a named block `fb` holding its own `t`. The function's
/// `t` is a local: nothing outside the function can name it, and the module's
/// `t` is a different declaration.
const MODULE_FF: &str = "module ff;\n if (1) begin : fb\n logic t;\n end\nendmodule\n";
const USER: &str =
"module user (output logic o);\n ff u_ff ();\n assign o = u_ff.fb.t;\nendmodule\n";
const FUNC: &str = "module host;\n function automatic void ff();\n begin : fb\n logic t;\n t = 1'b0;\n end\n endfunction\nendmodule\n";
#[test]
fn a_function_local_in_a_named_block_is_never_mistaken_for_a_modules_block_member() {
let tree = Tree::new("qa_genlabel_member_key");
tree.write("ff.sv", MODULE_FF);
tree.write("user.sv", USER);
tree.write("host.sv", FUNC);
let mut session = Session::wide(vec![tree.path.clone()], false);
let host = session.open(&tree.path.join("host.sv"), FUNC);
let found = places(&session.result(References::METHOD, position(&host, FUNC, 3, "t;")));
assert_eq!(found, vec![("host.sv".to_string(), 3), ("host.sv".to_string(), 4)]);
let mut params = position(&host, FUNC, 3, "t;");
params["newName"] = serde_json::json!("t2");
let answer = session.request(Rename::METHOD, params).response_result.expect("renames");
let changes = answer["changes"].as_object().expect("changes");
assert_eq!(changes.len(), 1, "only host.sv: {answer:#}");
}
/// Three files: the block's module, an intermediate module instantiating it,
/// and a testbench naming a member through two instances and the block. Only
/// the declaring file is open.
const LEAF: &str = "module leaf;\n for (genvar i = 0; i < 2; i++) begin : g_l\n logic s;\n end : g_l\nendmodule\n";
const MID: &str = "module mid;\n leaf u_leaf ();\nendmodule\n";
const TB: &str = "module tbq (output logic o);\n mid u_mid ();\n assign o = u_mid.u_leaf.g_l[1].s;\nendmodule\n";
#[test]
fn a_two_instance_path_through_a_block_is_renamed_with_every_other_file_closed() {
let tree = Tree::new("qa_genlabel_two_hops");
tree.write("leaf.sv", LEAF);
tree.write("mid.sv", MID);
tree.write("tbq.sv", TB);
let mut session = Session::wide(vec![tree.path.clone()], false);
let leaf = session.open(&tree.path.join("leaf.sv"), LEAF);
let found = places(&session.result(References::METHOD, position(&leaf, LEAF, 1, "g_l")));
let at = |f: &str, l| (f.to_string(), l);
assert_eq!(found, vec![at("leaf.sv", 1), at("leaf.sv", 3), at("tbq.sv", 2)]);
let mut params = position(&leaf, LEAF, 2, "s;");
params["newName"] = serde_json::json!("s_q");
let answer = session.request(Rename::METHOD, params).response_result.expect("renames");
let changes = answer["changes"].as_object().expect("changes");
let tb = path_to_uri(&tree.path.join("tbq.sv")).expect("a uri");
assert_eq!(changes.get(tb.as_str()).and_then(Value::as_array).map_or(0, Vec::len), 1);
}
@@ -0,0 +1,150 @@
//! A generate block label over the wire (TODO §65.1, topo §2.9-43).
//!
//! `references`, `prepareRename` and `rename` at a block label reach the
//! closing label and every path through the block — the same-file
//! `g_lane[0].sig` and another file's `u_x.g_lane[1].sig` — through the
//! engine and the index's hierarchical surface, whether the other file is
//! open or closed.
use super::*;
const SUB: &str = "module sub (input logic clk, output logic o);\n for (genvar i = 0; i < 2; i++) begin : g_lane\n logic sig;\n assign sig = clk;\n end : g_lane\n assign o = g_lane[0].sig;\nendmodule\n";
const TOP: &str = "module top (input logic clk, output logic o);\n sub u_x (.clk, .o());\n assign o = u_x.g_lane[1].sig;\nendmodule\n";
/// The LSP position of the `g_lane` on 0-based `line` of `text`.
fn at_label(uri: &Uri, text: &str, line: usize) -> Value {
let row = text.lines().nth(line).expect("the line");
let character = row.find("g_lane").expect("the label on that line");
serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": line, "character": character },
})
}
/// `(file name, line)` of every location in a `references` answer.
fn places(found: &Value) -> Vec<(String, u64)> {
let mut out: Vec<(String, u64)> = found
.as_array()
.expect("an array")
.iter()
.map(|l| {
let uri = l["uri"].as_str().unwrap_or("?");
let name = uri.rsplit('/').next().unwrap_or("?").to_string();
(name, l["range"]["start"]["line"].as_u64().unwrap_or(0))
})
.collect();
out.sort();
out
}
/// The two-file tree, with `sub.sv` and/or `top.sv` open.
fn session_with(tag: &str, open_sub: bool, open_top: bool) -> (Tree, Session, Uri, Uri) {
let tree = Tree::new(tag);
tree.write("sub.sv", SUB);
tree.write("top.sv", TOP);
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = |name: &str| path_to_uri(&tree.path.join(name)).expect("a uri");
let (sub, top) = (uri("sub.sv"), uri("top.sv"));
if open_sub {
session.open(&tree.path.join("sub.sv"), SUB);
}
if open_top {
session.open(&tree.path.join("top.sv"), TOP);
}
(tree, session, sub, top)
}
fn expected() -> Vec<(String, u64)> {
let sub = |line| ("sub.sv".to_string(), line);
vec![sub(1), sub(4), sub(5), ("top.sv".to_string(), 2)]
}
#[test]
fn references_at_the_label_reach_the_closing_label_and_every_path_with_the_user_closed() {
let (_tree, mut session, sub, _) = session_with("genlabel_refs_closed", true, false);
let mut params = at_label(&sub, SUB, 1);
params["context"] = serde_json::json!({ "includeDeclaration": true });
assert_eq!(places(&session.result(References::METHOD, params)), expected());
}
#[test]
fn references_from_the_other_files_segment_are_the_same_set_with_the_declarer_closed() {
// The declaring file is closed, so its own uses (the closing label and
// `g_lane[0].sig`) come from §64.1's one-file re-analysis: a block is a
// hierarchical-only declaration.
let (_tree, mut session, _, top) = session_with("genlabel_refs_open", false, true);
let mut params = at_label(&top, TOP, 2);
params["context"] = serde_json::json!({ "includeDeclaration": true });
assert_eq!(places(&session.result(References::METHOD, params)), expected());
}
#[test]
fn references_with_both_files_open_are_the_same_set() {
let (_tree, mut session, _, top) = session_with("genlabel_refs_both", true, true);
let mut params = at_label(&top, TOP, 2);
params["context"] = serde_json::json!({ "includeDeclaration": true });
assert_eq!(places(&session.result(References::METHOD, params)), expected());
}
#[test]
fn prepare_rename_and_rename_rewrite_every_site_in_both_files() {
let (tree, mut session, sub, _) = session_with("genlabel_rename", true, false);
let prepared = session.result(PrepareRenameRequest::METHOD, at_label(&sub, SUB, 4));
assert_eq!(prepared["placeholder"], "g_lane", "{prepared:#}");
let mut params = at_label(&sub, SUB, 4);
params["newName"] = serde_json::json!("g_ln");
let answer = session.request(Rename::METHOD, params).response_result.expect("renames");
let changes = answer["changes"].as_object().expect("changes");
let count = |path: &str| {
let uri = path_to_uri(&tree.path.join(path)).expect("a uri");
changes.get(uri.as_str()).and_then(Value::as_array).map_or(0, Vec::len)
};
assert_eq!((count("sub.sv"), count("top.sv")), (3, 1), "{answer:#}");
let mut texts = changes.values().flat_map(|e| e.as_array().into_iter().flatten());
assert!(texts.all(|e| e["newText"] == "g_ln"), "{answer:#}");
}
/// A member of a **nested** block is found on the index's `sub.g_a.g_b` key
/// (`Semantics::member_key`), so the reference list from its declaration in
/// an open buffer reaches the closed file's path to it.
#[test]
fn references_at_a_nested_blocks_member_reach_the_path_from_another_file() {
const NSUB: &str = "module nsub;\n if (1) begin : g_a\n for (genvar j = 0; j < 2; j++) begin : g_b\n logic deep;\n end\n end\nendmodule\n";
const NTOP: &str = "module ntop (output logic o);\n nsub u_n ();\n assign o = u_n.g_a.g_b[1].deep;\nendmodule\n";
let tree = Tree::new("genlabel_nested");
tree.write("nsub.sv", NSUB);
tree.write("ntop.sv", NTOP);
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("nsub.sv"), NSUB);
let params = serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": 3, "character": NSUB.lines().nth(3).and_then(|l| l.find("deep")) },
"context": { "includeDeclaration": true },
});
let found = places(&session.result(References::METHOD, params));
assert_eq!(found, vec![("nsub.sv".to_string(), 3), ("ntop.sv".to_string(), 2)]);
}
/// QA F1 over the wire: an open buffer is always in the rename's set, so its
/// path through the label that resolves to nothing (`tb.u_x.…`, rooted at a
/// top module this server cannot resolve) is shown as a warning, unedited.
#[test]
fn an_unresolved_path_in_an_open_buffer_is_shown_as_a_rename_warning() {
const PROBE: &str =
"module probe (output logic o);\n assign o = tb.u_x.g_lane[0].sig;\nendmodule\n";
let (tree, mut session, sub, _) = session_with("genlabel_unresolved", true, false);
tree.write("probe.sv", PROBE);
session.open(&tree.path.join("probe.sv"), PROBE);
let _ = session.drain();
let mut params = at_label(&sub, SUB, 1);
params["newName"] = serde_json::json!("g_ln");
let answer = session.request(Rename::METHOD, params).response_result.expect("renames");
let probe = path_to_uri(&tree.path.join("probe.sv")).expect("a uri");
assert!(answer["changes"].get(probe.as_str()).is_none(), "probe.sv is not edited: {answer:#}");
let shown = session.shown();
assert!(
shown.iter().any(|(_, m)| m.contains("probe.sv:2:") && m.contains("`g_lane`")),
"{shown:?}"
);
}
@@ -4,7 +4,7 @@ use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_semantic::{ScopeKind, SymbolKind};
use vlog_semantic::{ScopeKind, Symbol, SymbolKind};
/// See [`Rule::doc`].
pub struct DuplicateDeclaration;
@@ -60,7 +60,7 @@ impl Rule for DuplicateDeclaration {
let mut out = Vec::new();
for duplicate in semantics.duplicates() {
let Some(first) = semantics.symbol(duplicate.first) else { continue };
if !plain(duplicate.kind) || !plain(first.kind) {
if !collides(semantics, duplicate.kind, first) {
continue;
}
let scope = semantics.scope(duplicate.scope).map(|scope| scope.kind);
@@ -85,6 +85,29 @@ impl Rule for DuplicateDeclaration {
}
}
/// Whether a declaration of kind `kind` written after `first`, of one name in
/// one scope, is an error: both of a kind written once and once only
/// ([`plain`]); or a **block label** beside any other kind of declaration —
/// a net, a variable, a parameter, an instance, a port, a genvar, a typedef,
/// a function or task (a label and those share one namespace, IEEE 1800
/// §3.13); or two labels of named **procedural** blocks (generate-label-rename
/// F3, R4). Two *generate* arms carrying one label are not: only one arm of
/// an `if`/`case` elaborates (§27.5).
fn collides(semantics: &vlog_semantic::Semantics, kind: SymbolKind, first: &Symbol) -> bool {
match (kind == SymbolKind::Block, first.kind == SymbolKind::Block) {
(false, false) => plain(kind) && plain(first.kind),
(true, true) => !opens_a_generate_scope(semantics, first),
_ => true,
}
}
/// Whether a block label names a generate block — its scope is a generate
/// scope — rather than a procedural `begin`/`fork` or a statement label.
fn opens_a_generate_scope(semantics: &vlog_semantic::Semantics, label: &Symbol) -> bool {
let child = label.child_scope.and_then(|id| semantics.scope(id));
child.is_some_and(|scope| scope.kind == ScopeKind::Generate)
}
/// True for the declaration kinds that may be written **once** and once only.
///
/// Everything left out has a legal shape in which the same name is written
@@ -122,6 +145,41 @@ mod tests {
DuplicateDeclaration.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_block_label_beside_a_net_of_its_name_either_way_round() {
let label_second = "module m;\n logic g;\n if (1) begin : g\n end\nendmodule\n";
let label_first = "module m;\n if (1) begin : g\n end\n logic g;\nendmodule\n";
for src in [label_second, label_first] {
let found = violations(src);
assert_eq!(found.len(), 1, "{src}: {found:?}");
assert!(found[0].message.contains("`g`"), "{}", found[0].message);
}
}
#[test]
fn flags_a_block_label_beside_any_declaration_and_two_procedural_labels() {
for src in [
"module m (input logic g);\n if (1) begin : g\n end\nendmodule\n",
"module m (g);\n input g;\n if (1) begin : g\n end\nendmodule\n",
"module m;\n genvar g;\n if (1) begin : g\n end\nendmodule\n",
"module m;\n typedef logic g;\n if (1) begin : g\n end\nendmodule\n",
"module m;\n function void g();\n endfunction\n if (1) begin : g\n end\nendmodule\n",
"module m;\n task g();\n endtask\n if (1) begin : g\n end\nendmodule\n",
"module m;\n initial begin : g\n end\n initial begin : g\n end\nendmodule\n",
] {
let found = violations(src);
assert_eq!(found.len(), 1, "{src}: {found:?}");
}
}
#[test]
fn two_arms_carrying_one_label_are_not_a_duplicate() {
let src = "module m;\n if (1) begin : g\n end else begin : g\n end\nendmodule\n";
assert!(violations(src).is_empty());
let case = "module m;\n case (1)\n 0: begin : g\n end\n default: begin : g\n end\n endcase\nendmodule\n";
assert!(violations(case).is_empty());
}
#[test]
fn flags_two_signals_of_one_name() {
let src = "module m;\n logic a;\n logic a;\nendmodule\n";
@@ -190,6 +190,14 @@ mod tests {
assert_eq!(names_in_a_project(src, &[]), names(src), "an empty project changes nothing");
}
#[test]
fn a_block_label_spelled_like_a_net_is_not_a_read_of_it() {
// generate-label-rename F3: the colliding label is a
// `duplicate-declaration`, never a use of the net.
let src = "module m;\n wire g;\n if (1) begin : g\n end\nendmodule\n";
assert!(names(src).is_empty(), "{:?}", names(src));
}
#[test]
fn a_read_but_undriven_signal_is_reported() {
let src = "module m (output logic q);\n wire a;\n assign q = a;\nendmodule\n";
+6 -7
View File
@@ -41,7 +41,7 @@ use vlog_semantic::{
use super::ledger::{pieces_match, Split};
use super::{anchor_of, Anchor, Shifts};
use crate::rename::sites::{binds_implicitly, may_connect_implicitly, nearest, sites, Site};
use crate::rename::{display, Scope};
use crate::rename::Scope;
use crate::TextEdit;
/// The rename's lexical contract for a file whose edits insert connection
@@ -53,10 +53,9 @@ pub(super) fn insertions_match(
after: &str,
edits: &[TextEdit],
names: [&str; 2],
path: &Path,
shown: &str,
) -> Result<(), String> {
let refusal =
|what: &str| format!("the rename would {what} in {}; no edits were made.", display(path));
let refusal = |what: &str| format!("the rename would {what} in {shown}; no edits were made.");
let Ok(old_tokens) = tokenize(before) else {
return Err(refusal("edit a file lucisv cannot lex"));
};
@@ -74,8 +73,8 @@ pub(super) fn insertions_match(
return Err(refusal(&outside));
}
}
let split = Split::read(before, after, edits, path, "the rename")?;
pieces_match(&split, edits, path, "the rename")?;
let split = Split::read(before, after, edits, shown, "the rename")?;
pieces_match(&split, edits, shown, "the rename")?;
let grew = parse_source_tolerant(after).1.len() > parse_source_tolerant(before).1.len();
match grew {
true => Err(refusal("leave a connection list that does not parse")),
@@ -340,7 +339,7 @@ pub(super) fn bindings_match(
let [old, new] = names;
return Err(format!(
"renaming `{old}` to `{new}` would change what an implicit connection of `{instance}` binds in {}; the rename was abandoned.",
display(path)
scope.name_of(path)
));
}
}
+22 -41
View File
@@ -9,13 +9,11 @@
//! the whole of it.
use std::collections::HashMap;
use std::path::Path;
use vlog_parser::span::TextRange;
use vlog_parser::token::TokenKind;
use vlog_parser::tokenize;
use crate::rename::display;
use crate::TextEdit;
use super::{Moving, Origin};
@@ -77,14 +75,11 @@ impl Split {
before: &str,
after: &str,
edits: &[TextEdit],
path: &Path,
shown: &str,
what: &str,
) -> Result<Split, String> {
let (Some(old), Some(new)) = (pieces(before), pieces(after)) else {
return Err(format!(
"{} would no longer lex after {what}; no edits were made.",
display(path)
));
return Err(format!("{} would no longer lex after {what}; no edits were made.", shown));
};
let mut written: Vec<Vec<(TextRange, Piece)>> = Vec::new();
for edit in edits {
@@ -103,7 +98,7 @@ impl Split {
pub(super) fn positions_match(
&self,
edits: &[TextEdit],
path: &Path,
shown: &str,
what: &str,
) -> Result<(), String> {
let clone = |pieces: &[(TextRange, Piece)]| -> Vec<Piece> {
@@ -144,14 +139,14 @@ impl Split {
"{what} would write {} where {} belongs in {}; no edits were made.",
actual.describe(),
expected.describe(),
display(path)
shown
))
}
None => {
return Err(format!(
"{what} would lose {} in {}; no edits were made.",
expected.describe(),
display(path)
shown
))
}
}
@@ -160,7 +155,7 @@ impl Split {
let extra = actual.get(expected.len()).map_or_else(String::new, Piece::describe);
return Err(format!(
"{what} would add {extra} to {}, which is not part of the edit; no edits were made.",
display(path)
shown
));
}
Ok(())
@@ -174,12 +169,12 @@ impl Split {
pub(super) fn pieces_match(
split: &Split,
edits: &[TextEdit],
path: &Path,
shown: &str,
what: &str,
) -> Result<(), String> {
let ledger = Ledger::of(split, edits, TextRange::empty(0));
ledger.check(&display(path), what, &Tally::new())?;
split.positions_match(edits, path, what)
ledger.check(shown, what, &Tally::new())?;
split.positions_match(edits, shown, what)
}
/// The range the move takes text out of file `i`, if it names that file as one
@@ -545,7 +540,7 @@ fn and_list(names: &[String]) -> String {
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use super::*;
use crate::apply;
@@ -556,11 +551,11 @@ mod tests {
before: &str,
after: &str,
edits: &[TextEdit],
path: &Path,
shown: &str,
what: &str,
) -> Result<(), String> {
let split = Split::read(before, after, edits, path, what)?;
super::pieces_match(&split, edits, path, what)
let split = Split::read(before, after, edits, shown, what)?;
super::pieces_match(&split, edits, shown, what)
}
// ------------------------------------------------------------------
@@ -587,7 +582,7 @@ mod tests {
}
fn splice_attack(corrupted: &str) -> Result<(), String> {
pieces_match(PORTS, corrupted, &add_edits(), Path::new("/rtl/m.sv"), "adding port `cfg`")
pieces_match(PORTS, corrupted, &add_edits(), "m.sv", "adding port `cfg`")
}
#[test]
@@ -642,7 +637,7 @@ mod tests {
let at = text.find("hello").expect("string") as u32;
let edits = vec![TextEdit { range: TextRange::empty(at), new_text: "x".into() }];
let corrupted = apply(text, &edits);
let outcome = pieces_match(text, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit");
let outcome = pieces_match(text, &corrupted, &edits, "m.sv", "an edit");
assert!(outcome.is_err(), "the string's own text is not a token lucisv may write");
}
@@ -654,8 +649,7 @@ mod tests {
let end = PORTS.find("*/").expect("comment") as u32 + 2;
let edits = vec![TextEdit { range: TextRange::new(start, end), new_text: String::new() }];
let corrupted = apply(PORTS, &edits);
let outcome =
pieces_match(PORTS, &corrupted, &edits, Path::new("/rtl/m.sv"), "removing port `rst`");
let outcome = pieces_match(PORTS, &corrupted, &edits, "m.sv", "removing port `rst`");
let message = outcome.expect_err("a deleted comment is a refusal");
assert!(message.contains("comments are never dropped"), "{message}");
}
@@ -690,13 +684,7 @@ mod tests {
}
fn move_attack(corrupted: &str) -> Result<(), String> {
pieces_match(
MOVED,
corrupted,
&move_edits(),
Path::new("/rtl/m.sv"),
"converting `m`'s ports to ANSI",
)
pieces_match(MOVED, corrupted, &move_edits(), "m.sv", "converting `m`'s ports to ANSI")
}
#[test]
@@ -773,7 +761,7 @@ mod tests {
];
let corrupted = apply(SHARED, &edits);
assert_eq!(corrupted.matches("// both").count(), 2, "the attack really doubles it");
let message = pieces_match(SHARED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit")
let message = pieces_match(SHARED, &corrupted, &edits, "m.sv", "an edit")
.expect_err("a doubled comment is a refusal");
assert!(message.contains("would write the comment"), "{message}");
}
@@ -786,7 +774,7 @@ mod tests {
let end = MOVED.find("\n output").expect("output") as u32;
let edits = vec![TextEdit { range: TextRange::new(start, end), new_text: String::new() }];
let corrupted = apply(MOVED, &edits);
let message = pieces_match(MOVED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit")
let message = pieces_match(MOVED, &corrupted, &edits, "m.sv", "an edit")
.expect_err("a deleted comment nothing writes back is a refusal");
assert!(message.contains("comments are never dropped"), "{message}");
}
@@ -812,7 +800,7 @@ mod tests {
];
let corrupted = apply(SHARED, &edits);
assert_eq!(corrupted.matches("// shared").count(), 3, "the attack really triples it");
let message = pieces_match(SHARED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit")
let message = pieces_match(SHARED, &corrupted, &edits, "m.sv", "an edit")
.expect_err("a duplicated comment is a refusal");
assert!(message.contains("comments are never duplicated"), "{message}");
}
@@ -832,8 +820,7 @@ mod tests {
}];
let spliced = apply(source, &edits);
assert_eq!(spliced.matches("TODO").count(), 2, "{spliced}");
let outcome =
pieces_match(source, &spliced, &edits, Path::new("/rtl/top.sv"), "adding port `b`");
let outcome = pieces_match(source, &spliced, &edits, "top.sv", "adding port `b`");
assert_eq!(outcome, Ok(()), "a generated placeholder is the engine's own text");
}
@@ -889,13 +876,7 @@ mod tests {
fn attribute_attack(edits: &[TextEdit]) -> Result<(), String> {
let corrupted = apply(ATTRIBUTED, edits);
pieces_match(
ATTRIBUTED,
&corrupted,
edits,
Path::new("/rtl/m.sv"),
"converting `m`'s ports to ANSI",
)
pieces_match(ATTRIBUTED, &corrupted, edits, "m.sv", "converting `m`'s ports to ANSI")
}
#[test]
+23 -21
View File
@@ -21,6 +21,10 @@ mod after;
mod implicit;
mod ledger;
#[cfg(test)]
mod qa_block_attacks;
#[cfg(test)]
mod qa_block_paths;
#[cfg(test)]
mod qa_implicit;
use std::collections::HashMap;
@@ -33,7 +37,7 @@ use vlog_semantic::{
ExternalResolutions, ExternalTarget, ReferenceId, Semantics, SymbolKind, WorkspaceIndex,
};
use crate::rename::{contains_word, display, Scope};
use crate::rename::{contains_word, Scope};
use crate::trace::VerifyTrace;
use crate::{apply, Shift, TextEdit};
@@ -108,7 +112,7 @@ pub(crate) fn verify(
if let Some(what) = before.first_difference(&after) {
return Err(format!(
"renaming `{old_name}` to `{new_name}` would change what {what} means in {}; the rename was abandoned.",
display(path)
scope.name_of(path)
));
}
}
@@ -134,9 +138,10 @@ fn tokens_verified(
) -> Result<(), String> {
for ((i, edits), (path, text)) in edits.iter().zip(edited) {
let Some(before) = scope.text(*i) else { return Err(ABANDONED.to_string()) };
let shown = scope.name_of(path);
stage.measure(|| match edits.iter().any(|e| e.range.is_empty()) {
true => implicit::insertions_match(before, text, edits, names, path),
false => tokens_match(before, text, &Shift::new(edits), names[1], path),
true => implicit::insertions_match(before, text, edits, names, &shown),
false => tokens_match(before, text, &Shift::new(edits), names[1], &shown),
})?;
}
Ok(())
@@ -295,23 +300,24 @@ pub(crate) fn verify_move(
if edits.iter().any(|(i, _)| *i == copied.file) {
return Err(format!(
"{what} would edit {}, which it only copies out of; no edits were made.",
display(path)
scope.name_of(path)
));
}
transit.copy(&display(path), text, copied.region, what)?;
transit.copy(&scope.name_of(path), text, copied.region, what)?;
}
for ((i, edits), (path, text)) in edits.iter().zip(&edited) {
let Some(before) = scope.text(*i) else { return Err(abandoned) };
let split = Split::read(before, text, edits, path, what)?;
let shown = scope.name_of(path);
let split = Split::read(before, text, edits, &shown, what)?;
match region_of(moving, *i) {
// A file the move names balances against the pieces in transit
// rather than on its own; its positional comparison is unchanged.
Some(region) => {
transit.add(&display(path), region, &split, edits);
split.positions_match(edits, path, what)?;
transit.add(&scope.name_of(path), region, &split, edits);
split.positions_match(edits, &shown, what)?;
}
None => pieces_match(&split, edits, path, what)?,
None => pieces_match(&split, edits, &shown, what)?,
}
// A tolerant parse of a file that was already broken still reports its
// old diagnostics, so the bar is "no *new* one", not "none".
@@ -320,7 +326,7 @@ pub(crate) fn verify_move(
if after_count > before_count {
return Err(format!(
"{what} would leave {} unparseable; no edits were made.",
display(path)
scope.name_of(path)
));
}
}
@@ -360,7 +366,7 @@ pub(crate) fn verify_move(
if let Some(what_moved) = before.first_difference(&after) {
return Err(format!(
"{what} would change what {what_moved} means in {}; no edits were made.",
display(path)
scope.name_of(path)
));
}
}
@@ -437,16 +443,12 @@ fn tokens_match(
after: &str,
shift: &Shift,
new_name: &str,
path: &Path,
shown: &str,
) -> Result<(), String> {
let refusal = |what: &str| {
format!("the rename would change {what} in {}; no edits were made.", display(path))
};
let refusal =
|what: &str| format!("the rename would change {what} in {shown}; no edits were made.");
let (Ok(old), Ok(new)) = (tokenize(before), tokenize(after)) else {
return Err(format!(
"{} would no longer lex after the rename; no edits were made.",
display(path)
));
return Err(format!("{shown} would no longer lex after the rename; no edits were made."));
};
if old.len() != new.len() {
return Err(refusal("the token stream's shape"));
@@ -651,7 +653,7 @@ mod tests {
fn attack(corrupted: &str) -> Result<(), String> {
let edits = rename_edits();
tokens_match(SOURCE, corrupted, &Shift::new(&edits), "sig", Path::new("/rtl/m.sv"))
tokens_match(SOURCE, corrupted, &Shift::new(&edits), "sig", "m.sv")
}
#[test]
@@ -0,0 +1,175 @@
//! QA re-attack (TODO §65.1, CLAUDE.md invariant 4) on the rename verifier
//! over block labels, beyond the dev's `qa_block_paths`: corrupted outputs
//! that rename an unrelated block of the same name, rebind a path to another
//! module's block, split a same-label pair of arms, or let a genvar capture
//! a path written inside the loop. Each lexes and parses; each must be
//! refused. `docs/features/generate-label-rename/README.md`, QA log.
use std::path::{Path, PathBuf};
use vlog_parser::span::TextRange;
use super::verify;
use crate::rename::Scope;
use crate::trace::VerifyTrace;
use crate::TextEdit;
/// Two modules, each with its own `g_lane`, both instantiated in `top`.
const SUB: &str = "module sub (input logic clk);
for (genvar i = 0; i < 2; i++) begin : g_lane
logic sig;
assign sig = clk;
end : g_lane
endmodule
";
const OTHER: &str = "module other (input logic clk);
for (genvar i = 0; i < 2; i++) begin : g_lane
logic sig;
assign sig = clk;
end : g_lane
endmodule
";
const TOP: &str = "module top (input logic clk, output logic o, output logic p);
sub u_x (.clk);
other u_y (.clk);
assign o = u_x.g_lane[1].sig;
assign p = u_y.g_lane[0].sig;
endmodule
";
/// Both arms of a generate `if` carry one label, each closed by it.
const ARMS: &str = "module arms #(parameter bit P = 0) (output logic o);
if (P) begin : g_arm
logic q;
end : g_arm
else begin : g_arm
logic q;
end : g_arm
assign o = g_arm.q;
endmodule
";
/// A path to the loop's own block written inside the loop's body.
const INSIDE: &str = "module inside (output logic o);
for (genvar gi = 0; gi < 2; gi++) begin : g_lane
logic sig;
assign sig = g_lane[0].sig;
end
assign o = g_lane[1].sig;
endmodule
";
/// A rename's edit at the `n`th (0-based) whole-word `name` in `text`.
fn at_word(text: &str, name: &str, n: usize, new: &str) -> TextEdit {
let is_word = |b: Option<&u8>| b.is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_');
let bytes = text.as_bytes();
let start = text
.match_indices(name)
.map(|(i, _)| i)
.filter(|&i| {
!is_word(i.checked_sub(1).and_then(|p| bytes.get(p)))
&& !is_word(bytes.get(i + name.len()))
})
.nth(n)
.expect("occurrence");
TextEdit {
range: TextRange::new(start as u32, (start + name.len()) as u32),
new_text: new.into(),
}
}
/// `verify` over `files` with the given edits, keyed by file name.
fn verdict(
files: &[(&str, &str)],
edits: &[(&str, Vec<TextEdit>)],
old: &str,
new: &str,
) -> Result<(), String> {
let sources: Vec<(PathBuf, String)> =
files.iter().map(|(name, text)| (Path::new("/rtl").join(name), text.to_string())).collect();
let mut scope = Scope::build(&sources);
let mut keyed: Vec<(usize, Vec<TextEdit>)> = edits
.iter()
.map(|(name, edits)| {
let i = scope.index_of(&Path::new("/rtl").join(name)).expect("in scope");
(i, edits.clone())
})
.collect();
keyed.sort_by_key(|(i, _)| *i);
verify(&mut scope, &keyed, old, new, &mut VerifyTrace::default())
}
fn three() -> Vec<(&'static str, &'static str)> {
vec![("sub.sv", SUB), ("other.sv", OTHER), ("top.sv", TOP)]
}
/// The honest rename of `sub`'s `g_lane`: its label, its closing label and
/// `u_x`'s path — never `other`'s block or `u_y`'s path.
fn honest() -> Vec<(&'static str, Vec<TextEdit>)> {
vec![
("sub.sv", (0..2).map(|n| at_word(SUB, "g_lane", n, "g_ln")).collect()),
("top.sv", vec![at_word(TOP, "g_lane", 0, "g_ln")]),
]
}
#[test]
fn the_honest_rename_of_one_modules_block_verifies() {
assert_eq!(verdict(&three(), &honest(), "g_lane", "g_ln"), Ok(()));
}
/// Not a corruption, and pinned as such: a rename that *also* moves an
/// unrelated same-named block together with every use of it changes no
/// meaning, and the verifier is a meaning check — it accepts it exactly as it
/// accepts the same shape for a net (`sig` in both modules). That the engine
/// never produces this edit is pinned by `tests/qa_generate_label.rs`
/// (`a_same_named_block_in_another_module_is_never_touched`).
#[test]
fn a_rename_that_also_moved_the_other_modules_block_consistently_is_meaning_preserving() {
let mut edits = honest();
edits.push(("other.sv", (0..2).map(|n| at_word(OTHER, "g_lane", n, "g_ln")).collect()));
edits[1].1.push(at_word(TOP, "g_lane", 1, "g_ln"));
assert_eq!(verdict(&three(), &edits, "g_lane", "g_ln"), Ok(()));
let mut nets = vec![
("sub.sv", (0..2).map(|n| at_word(SUB, "sig", n, "sg")).collect::<Vec<_>>()),
("top.sv", vec![at_word(TOP, "sig", 0, "sg")]),
];
nets.push(("other.sv", (0..2).map(|n| at_word(OTHER, "sig", n, "sg")).collect()));
nets[1].1.push(at_word(TOP, "sig", 1, "sg"));
assert_eq!(verdict(&three(), &nets, "sig", "sg"), Ok(()), "the same for a net");
}
#[test]
fn a_rename_that_moved_the_other_instances_path_instead_is_rejected() {
let edits = vec![
("sub.sv", (0..2).map(|n| at_word(SUB, "g_lane", n, "g_ln")).collect()),
("top.sv", vec![at_word(TOP, "g_lane", 1, "g_ln")]),
];
assert!(verdict(&three(), &edits, "g_lane", "g_ln").is_err(), "`u_y.g_ln` names nothing");
}
#[test]
fn a_rename_of_one_arm_of_a_same_label_pair_is_rejected() {
// The first arm's labels and the path move; the second arm keeps
// `g_arm`, so the pair no longer names one block.
let edits = vec![(
"arms.sv",
vec![0, 1, 4].into_iter().map(|n| at_word(ARMS, "g_arm", n, "g_x")).collect(),
)];
assert!(verdict(&[("arms.sv", ARMS)], &edits, "g_arm", "g_x").is_err());
// …and the second arm's closing label alone left behind.
let edits =
vec![("arms.sv", (0..3).chain([4]).map(|n| at_word(ARMS, "g_arm", n, "g_x")).collect())];
assert!(verdict(&[("arms.sv", ARMS)], &edits, "g_arm", "g_x").is_err());
// The honest one: all five.
let edits = vec![("arms.sv", (0..5).map(|n| at_word(ARMS, "g_arm", n, "g_x")).collect())];
assert_eq!(verdict(&[("arms.sv", ARMS)], &edits, "g_arm", "g_x"), Ok(()));
}
#[test]
fn a_rename_to_the_genvar_that_captures_the_path_inside_the_loop_is_rejected() {
// `g_lane` → `gi`: inside the body `gi[0].sig` would name the genvar.
let edits = vec![("inside.sv", (0..3).map(|n| at_word(INSIDE, "g_lane", n, "gi")).collect())];
assert!(verdict(&[("inside.sv", INSIDE)], &edits, "g_lane", "gi").is_err());
}
@@ -0,0 +1,140 @@
//! TODO §65.1: masked-corruption attacks on the rename verifier over paths
//! through a block label (CLAUDE.md invariant 4).
//!
//! The verifier gained **no** normalization for block labels: a closing label
//! and a path segment are ordinary references now (`vlog_semantic` binds them
//! — `docs/features/generate-label-rename/README.md`), so the unchanged
//! resolution print compares them like any other use. These attacks pin that
//! it does: each hands `verify` a rename of `g_lane` → `g_ln` with one site
//! left out, rewritten wrongly or rewritten where no reference is, every one
//! of which lexes, parses and — before §65.1 — verified clean.
//!
//! Crate-internal because `verify` is.
use std::path::{Path, PathBuf};
use vlog_parser::span::TextRange;
use super::verify;
use crate::rename::Scope;
use crate::trace::VerifyTrace;
use crate::TextEdit;
const SUB: &str = "module sub (input logic clk, output logic o);
for (genvar i = 0; i < 2; i++) begin : g_lane
logic sig;
assign sig = clk;
end : g_lane
assign o = g_lane[0].sig;
// g_lane in a comment
endmodule
";
const TOP: &str = "module top (input logic clk, output logic o);
sub u_x (.clk, .o());
assign o = u_x.g_lane[1].sig;
endmodule
";
/// A rename's edit at the `n`th (0-based) whole-word `name` in `text`.
fn at_word(text: &str, name: &str, n: usize, new: &str) -> TextEdit {
let is_word = |b: Option<&u8>| b.is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_');
let bytes = text.as_bytes();
let start = text
.match_indices(name)
.map(|(i, _)| i)
.filter(|&i| {
!is_word(i.checked_sub(1).and_then(|p| bytes.get(p)))
&& !is_word(bytes.get(i + name.len()))
})
.nth(n)
.expect("occurrence");
TextEdit {
range: TextRange::new(start as u32, (start + name.len()) as u32),
new_text: new.into(),
}
}
/// `verify` over SUB and TOP with the given edits, keyed by file name.
fn verdict(edits: &[(&str, Vec<TextEdit>)]) -> Result<(), String> {
let files = vec![
(PathBuf::from("/rtl/sub.sv"), SUB.to_string()),
(PathBuf::from("/rtl/top.sv"), TOP.to_string()),
];
let mut scope = Scope::build(&files);
let mut keyed: Vec<(usize, Vec<TextEdit>)> = edits
.iter()
.map(|(name, edits)| {
let i = scope.index_of(&Path::new("/rtl").join(name)).expect("in scope");
(i, edits.clone())
})
.collect();
keyed.sort_by_key(|(i, _)| *i);
verify(&mut scope, &keyed, "g_lane", "g_ln", &mut VerifyTrace::default())
}
/// The honest edits: the label, its closing label and both path segments —
/// SUB's first, second and third `g_lane` (the fourth is the comment).
fn honest() -> Vec<(&'static str, Vec<TextEdit>)> {
vec![
("sub.sv", (0..3).map(|n| at_word(SUB, "g_lane", n, "g_ln")).collect()),
("top.sv", vec![at_word(TOP, "g_lane", 0, "g_ln")]),
]
}
#[test]
fn the_honest_rename_verifies() {
assert_eq!(verdict(&honest()), Ok(()));
}
#[test]
fn a_rename_that_left_the_same_file_path_segment_is_rejected() {
let mut edits = honest();
edits[0].1.remove(2);
assert!(verdict(&edits).is_err(), "`g_lane[0].sig` would name nothing");
}
#[test]
fn a_rename_that_left_the_closing_label_is_rejected() {
let mut edits = honest();
edits[0].1.remove(1);
assert!(verdict(&edits).is_err(), "`end : g_lane` would close `begin : g_ln`");
}
#[test]
fn a_rename_that_left_the_other_files_path_is_rejected() {
let mut edits = honest();
edits.remove(1);
assert!(verdict(&edits).is_err(), "`u_x.g_lane[1].sig` would name nothing");
}
#[test]
fn a_rename_of_the_paths_alone_is_rejected() {
let edits = vec![
("sub.sv", vec![at_word(SUB, "g_lane", 2, "g_ln")]),
("top.sv", vec![at_word(TOP, "g_lane", 0, "g_ln")]),
];
assert!(verdict(&edits).is_err(), "the paths would name a block that does not exist");
}
#[test]
fn a_rename_that_also_rewrote_the_comment_is_rejected() {
let mut edits = honest();
edits[0].1.push(at_word(SUB, "g_lane", 3, "g_ln"));
assert!(verdict(&edits).is_err(), "a comment never changes");
}
#[test]
fn a_rename_that_rewrote_a_segment_to_a_different_name_is_rejected() {
let mut edits = honest();
edits[1].1 = vec![at_word(TOP, "g_lane", 0, "g_other")];
assert!(verdict(&edits).is_err(), "every edited token spells the new name");
}
#[test]
fn a_rename_that_also_rewrote_the_member_after_the_segment_is_rejected() {
let mut edits = honest();
let sig = at_word(TOP, "sig", 0, "g_ln");
edits[1].1.push(sig);
assert!(verdict(&edits).is_err(), "`.sig` is another declaration's reference");
}
+1 -1
View File
@@ -285,7 +285,7 @@ fn confirm(
if ports != wanted_ports || params != wanted_params {
return Err(format!(
"{what} would not leave `{new_name}` with the header lucisv intended in {}; no edits were made.",
display(path)
scope.name_of(path)
));
}
return Ok(());
+1 -1
View File
@@ -292,7 +292,7 @@ fn no_hierarchy(scope: &Scope<'_>, site: &Site<'_>) -> Result<(), String> {
return Err(format!(
"`{}` is named as a scope of the design hierarchy in {}, and inlining it dissolves the scope that path walks through; no edits were made.",
site.instance,
display(path)
scope.name_of(path)
));
}
}
+2 -2
View File
@@ -59,8 +59,8 @@ pub use ports::{
PortOfferKind,
};
pub use rename::{
contains_word, prepare_rename, prepare_rename_here, rename, rename_name_at, rename_preflight,
rename_traced, rename_traced_with, KnownFacts, RenameTarget,
contains_word, home_set, prepare_rename, prepare_rename_here, rename, rename_name_at,
rename_preflight, rename_traced, rename_traced_with, KnownFacts, RenameTarget,
};
pub use trace::{IndexTrace, RenameTrace, Stage, VerifyTrace, WarnTrace};
+23 -23
View File
@@ -3,14 +3,12 @@
//! non-ANSI, empty, or none), guarded against landing inside an `` `ifdef``
//! arm; and the connection every instantiation in scope gains.
use std::path::Path;
use vlog_parser::ast::{Connections, Instance, ItemKind, ListElem, Module, PortList};
use vlog_parser::span::TextRange;
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::{parse_source_tolerant, tokenize, LineIndex};
use crate::rename::{display, Scope};
use crate::rename::Scope;
use crate::TextEdit;
use super::find::{
@@ -96,8 +94,9 @@ pub(super) fn plan_add(
return Err(format!("`{}` already has a port named `{}`.", site.name, port.name));
}
let Some(path) = scope.path(site.file) else { return Err(not_indexed(&site.name)) };
let tokens = tokenize(text).map_err(|_| lex_failed(Some(path)))?;
let file = File { text, path, tokens };
let shown = scope.name_of(path);
let tokens = tokenize(text).map_err(|_| lex_failed(&shown))?;
let file = File { text, shown, tokens };
let mut plan = Plan::default();
let header = header_edits(&file, module, item_span, port, &existing, &mut plan.warnings)?;
@@ -143,15 +142,15 @@ pub(super) fn not_indexed(name: &str) -> String {
format!("lucisv can no longer find the declaration of `{name}`.")
}
fn lex_failed(path: Option<&Path>) -> String {
format!("{} does not lex, so lucisv will not edit it.", display(path.unwrap_or(Path::new("?"))))
fn lex_failed(shown: &str) -> String {
format!("{shown} does not lex, so lucisv will not edit it.")
}
/// The file a module is written in, as the planners read it: its text, its
/// name for a message, and its tokens.
struct File<'a> {
text: &'a str,
path: &'a Path,
shown: String,
tokens: Vec<Token>,
}
@@ -164,7 +163,7 @@ fn header_edits(
existing: &[DeclaredPort],
warnings: &mut Vec<String>,
) -> Result<Vec<TextEdit>, String> {
let (text, path, tokens) = (file.text, file.path, file.tokens.as_slice());
let (text, path, tokens) = (file.text, file.shown.as_str(), file.tokens.as_slice());
let name_end = module.name_span.end;
let list = list_directives(module);
let header = format!("`{}`'s port list", module.name);
@@ -290,14 +289,14 @@ fn guard_conditionals(
at: u32,
region: &str,
text: &str,
path: &Path,
shown: &str,
warnings: &mut Vec<String>,
) -> Result<(), String> {
if directives.is_empty() {
return Ok(());
}
let lines = LineIndex::new(text);
let where_ = |span: TextRange| format!("{}:{}", display(path), lines.line_col(span.start).0);
let where_ = |span: TextRange| format!("{shown}:{}", lines.line_col(span.start).0);
let mut depth = 0i32;
let mut opened: Option<&Directive> = None;
for directive in directives.iter().filter(|d| d.span.start < at) {
@@ -389,6 +388,7 @@ fn instantiation_edits(
if !text.contains(&site.name) {
return Ok((Vec::new(), 0));
}
let shown = scope.name_of(path);
let (tree, _) = parse_source_tolerant(text);
let mut instantiations = Vec::new();
collect_instantiations(&tree.items, &mut instantiations);
@@ -421,7 +421,7 @@ fn instantiation_edits(
warnings.push(format!(
"`{}` at {}:{} writes an empty connection list, so `{}` is left unconnected there.",
instance.name,
display(path),
shown,
lines.line_col(instance.name_span.start).0,
port.name
));
@@ -431,7 +431,7 @@ fn instantiation_edits(
return Err(format!(
"`{}` in {} connects {} of `{}`'s {ports_before} port(s) by position, so lucisv cannot tell where a new one goes; give it named connections first.",
instance.name,
display(path),
shown,
conns.len(),
site.name
));
@@ -448,9 +448,9 @@ fn instantiation_edits(
warnings.push(format!(
"`{}` at {}:{} connects with `.*` and {} has no signal named `{}`, so the new port will not bind; connect it by hand.",
instance.name,
display(path),
shown,
lines.line_col(instance.name_span.start).0,
display(path),
shown,
port.name
));
}
@@ -465,13 +465,13 @@ fn instantiation_edits(
let expr = if visible {
port.name.clone()
} else {
todo.push(at_site(&instance.name, path, &lines, instance.name_span.start));
todo.push(at_site(&instance.name, &shown, &lines, instance.name_span.start));
"/* TODO: connect */".to_string()
};
let element = format!(".{}({expr})", port.name);
let open = match open {
Some(open) => open,
None => return Err(missing_parens(&instance.name, path)),
None => return Err(missing_parens(&instance.name, &shown)),
};
edits.extend(append_to_list(text, Some(open), &spans, &element));
}
@@ -484,11 +484,11 @@ fn instantiation_edits(
let expr = if visible {
port.name.clone()
} else {
empty.push(at_site(&instance.name, path, &lines, instance.name_span.start));
empty.push(at_site(&instance.name, &shown, &lines, instance.name_span.start));
String::new()
};
let Some(open) = conn_list_open(text, instance, spans.first().copied()) else {
return Err(missing_parens(&instance.name, path));
return Err(missing_parens(&instance.name, &shown));
};
edits.extend(append_to_list(text, Some(open), &spans, &expr));
}
@@ -510,14 +510,14 @@ fn instantiation_edits(
}
/// How one instantiation site is named in a warning: `` `u_sub` (top.sv:12) ``.
fn at_site(instance: &str, path: &Path, lines: &LineIndex, offset: u32) -> String {
format!("`{instance}` ({}:{})", display(path), lines.line_col(offset).0)
fn at_site(instance: &str, shown: &str, lines: &LineIndex, offset: u32) -> String {
format!("`{instance}` ({shown}:{})", lines.line_col(offset).0)
}
pub(super) fn missing_parens(instance: &str, path: &Path) -> String {
pub(super) fn missing_parens(instance: &str, shown: &str) -> String {
format!(
"lucisv cannot find the connection list of `{instance}` in {}; no edits were made.",
display(path)
shown
)
}
+2 -2
View File
@@ -39,7 +39,7 @@ use std::path::{Path, PathBuf};
use vlog_parser::ast::{Connections, ItemKind, Module, PortList, SourceFile};
use vlog_parser::parse_source_tolerant;
use crate::rename::{display, Scope};
use crate::rename::Scope;
use crate::{check, RefactorEdit, TextEdit};
use add::{parse_port_decl, plan_add};
@@ -504,7 +504,7 @@ fn confirm(scope: &Scope, plan: &Plan, module: &str, what: &str) -> Result<(), S
if &actual != expected {
return Err(format!(
"{what} would not leave {} with the signature lucisv intended; no edits were made.",
display(path)
scope.name_of(path)
));
}
}
+8 -3
View File
@@ -47,6 +47,7 @@ use super::list::{append_to_list, conn_list_open, elem_spans};
use super::propagate::{connections_of, instance_at, missing_ports};
use super::remove::{body_uses_in, disconnections_in, header_removal, port_at};
use super::{port_action_modules_in, sites_phrase, Plan};
use crate::scope::BaseNames;
/// Which of the four port refactorings an offer names.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -148,6 +149,8 @@ struct Files<'a> {
/// Index of the buffer the cursor is in.
here: usize,
parsed: Vec<Option<Parsed>>,
/// How many sources share each file name, for naming them in messages.
base_names: BaseNames,
}
impl<'a> Files<'a> {
@@ -160,7 +163,8 @@ impl<'a> Files<'a> {
sources.dedup_by(|a, b| a.0 == b.0);
let here = sources.iter().position(|(path, _)| *path == file)?;
let parsed = sources.iter().map(|_| None).collect();
Some(Files { sources, here, parsed })
let base_names = BaseNames::of(sources.iter().map(|(p, _)| *p));
Some(Files { sources, here, parsed, base_names })
}
fn len(&self) -> usize {
@@ -247,11 +251,12 @@ impl<'a> Files<'a> {
if !text.contains(module) {
return Ok((Vec::new(), 0));
}
let shown = self.base_names.name(path);
if i == self.here {
return disconnections_in(text, path, buffer.tree, module, port, warnings);
return disconnections_in(text, &shown, buffer.tree, module, port, warnings);
}
match self.parsed(i) {
Some(parsed) => disconnections_in(text, path, &parsed.tree, module, port, warnings),
Some(parsed) => disconnections_in(text, &shown, &parsed.tree, module, port, warnings),
None => Ok((Vec::new(), 0)),
}
}
+3 -3
View File
@@ -11,7 +11,7 @@ use vlog_parser::ast::{
use vlog_parser::span::TextRange;
use vlog_parser::{parse_source_tolerant, LineIndex};
use crate::rename::{display, Scope};
use crate::rename::Scope;
use super::add::{missing_parens, not_indexed};
use super::find::{
@@ -115,7 +115,7 @@ pub(super) fn plan_propagate(
let spans: Vec<TextRange> = elem_spans(conns, |c| c.span);
let Some(open) = conn_list_open(text, instance, spans.first().copied()) else {
return Err(missing_parens(&instance.name, file));
return Err(missing_parens(&instance.name, &scope.name_of(file)));
};
let lines = LineIndex::new(text);
let at = instance.name_span.start;
@@ -147,7 +147,7 @@ pub(super) fn plan_propagate(
plan.warnings.push(format!(
"no signal named {} is in scope at {}:{}, so those connections were left as `/* TODO: connect */`.",
todo.iter().map(|n| format!("`{n}`")).collect::<Vec<_>>().join(", "),
display(file),
scope.name_of(file),
lines.line_col(at).0
));
}
Loaded 100 of 186 files, more files were not shown because too many files have changed in this diff. Show more