Compare commits

...
12 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
91 changed files with 8871 additions and 406 deletions

No files matched your search

+121
View File
@@ -4,6 +4,127 @@ 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
Generated
+9 -9
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.58.0"
version = "0.60.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.58.0"
version = "0.60.0"
[[package]]
name = "lucisv_mcp"
version = "0.58.0"
version = "0.60.0"
dependencies = [
"lucisv_core",
"serde",
@@ -126,7 +126,7 @@ dependencies = [
[[package]]
name = "lucisv_server"
version = "0.58.0"
version = "0.60.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.58.0"
version = "0.60.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.58.0"
version = "0.60.0"
dependencies = [
"lucisv_core",
"vlog_formatter",
@@ -279,11 +279,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.58.0"
version = "0.60.0"
[[package]]
name = "vlog_refactor"
version = "0.58.0"
version = "0.60.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -292,7 +292,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.58.0"
version = "0.60.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -13,7 +13,7 @@ members = [
]
[workspace.package]
version = "0.58.0"
version = "0.60.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+34
View File
@@ -448,6 +448,40 @@ Feature README `docs/features/mcp-lean-catalogue`. One dev (Opus), one QA
(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)
1. **Engine bump** (M5): if `vsce` accepts the contribution point on
+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
+14 -2
View File
@@ -22,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)]
@@ -35,6 +34,8 @@ pub struct Options {
/// `--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,
}
@@ -88,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}")),
}
@@ -114,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 -1
View File
@@ -111,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));
+26 -5
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;
@@ -38,6 +38,17 @@ const RESOURCE_NOT_FOUND: i64 = -32002;
/// 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)]
pub struct RpcError {
@@ -195,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()),
@@ -217,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),
})
}
@@ -233,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(),
@@ -319,6 +330,15 @@ fn open_project(options: &Options) -> Project {
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 {
@@ -348,6 +368,7 @@ mod tests {
#[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]
+52 -12
View File
@@ -45,10 +45,14 @@ fn rename(project: &mut Project, args: &Args) -> Result<Answer, 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(project, &why))?;
.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);
let told = Told { name: &name, home: &path, unit: unit.as_deref() };
// 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}")];
@@ -62,6 +66,8 @@ struct Picked {
name: String,
path: PathBuf,
offset: u32,
/// The declaration's kind word (`module`, `var`, …).
kind: &'static str,
}
fn one_declaration(project: &mut Project, args: &Args) -> Result<Picked, String> {
@@ -87,16 +93,9 @@ fn one_declaration(project: &mut Project, args: &Args) -> Result<Picked, String>
[one] if one.is_macro() => {
Err(format!("`{name}` is a macro; lucisv does not rename macros."))
}
// The engine rewrites no hierarchical path through a block and
// reports none as a use, so the rename could not be complete
// (topo §2.9 MCP-14).
[one] if one.kind == "block" => Err(format!(
"`rename` does not rename generate block labels: paths through the block (`{}[0].…`) would not be rewritten; edit the file.",
names::qualified(name).1
)),
[one] => {
let name = names::qualified(name).1.to_string();
Ok(Picked { name, path: one.path.clone(), offset: one.offset })
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")),
}
@@ -129,6 +128,10 @@ 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,
@@ -151,21 +154,58 @@ pub(super) fn write_telling(
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()))
});
let focus = Focus { name: told.name, home: told.home, unit: told.unit, accounted: &accounted };
// 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();
let warnings: Vec<String> = plan.warnings.iter().map(|w| set.rooted(project, w)).collect();
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 })
}
/// 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)),
);
}
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.
+35 -2
View File
@@ -83,7 +83,7 @@ fn with_uses(project: &Project, name: &str, found: &[Declaration]) -> Vec<String
account(&mut accounted, hits);
}
Err(why) => {
let why = engine_refusal(&set.rooted(project, &why));
let why = engine_refusal(&set.rooted(&why));
lines.push(format!(" uses not listed: {why}"));
}
}
@@ -93,13 +93,46 @@ fn with_uses(project: &Project, name: &str, found: &[Declaration]) -> Vec<String
lines.push(format!("uses listed for {REFS_CAP} of {followed} declarations"));
}
let home = &found[0].path;
let focus = Focus { name, home, unit: None, accounted: &accounted };
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();
+18 -9
View File
@@ -32,9 +32,16 @@ const MAX_DEPTH: i64 = 20;
/// The most nodes one walk collects before it stops.
const NODE_CAP: usize = 50_000;
/// The most lines an answer holds before `… and N more`.
/// 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;
@@ -271,14 +278,21 @@ impl<'a> Walk<'a> {
}
/// The nodes as lines, two spaces per level (`up` starts at no indent),
/// each followed by its statement on `peek`; cut whole nodes at [`CAP`].
/// 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 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);
let mut block = vec![format!("{indent}{}", node_line(project, &mut texts, node, up))];
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.
@@ -286,13 +300,8 @@ fn render_nodes(project: &Project, nodes: &[Node], up: bool, peek: bool) -> Vec<
true => line,
false => format!("{indent} {line}"),
};
block.extend(source.into_iter().map(shown));
lines.extend(source.into_iter().map(shown));
}
if lines.len() + block.len() > CAP {
lines.push(render::more(nodes.len() - at));
return lines;
}
lines.extend(block);
}
lines
}
+20
View File
@@ -52,6 +52,17 @@ pub struct Focus<'a> {
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 {
@@ -93,7 +104,13 @@ pub fn find<'t>(
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;
@@ -109,6 +126,9 @@ pub fn find<'t>(
.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));
}
}
+43 -6
View File
@@ -105,14 +105,39 @@ const TOOLS: &[(Tool, Effect)] = &[
(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 })
}
@@ -253,8 +278,20 @@ 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 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}");
+6 -6
View File
@@ -63,18 +63,18 @@ fn add_port(
) -> 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(project, &why))?;
.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(project, &why))?
place::after(&set.files, &edit, &spec).map_err(|why| set.rooted(&why))?
}
None => edit,
};
let told = Told { name: &port, home: file, unit: Some(module) };
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));
@@ -89,9 +89,9 @@ fn remove_port(
) -> 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(project, &why))?;
let told = Told { name: port, home: file, unit: Some(module) };
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));
+44 -12
View File
@@ -76,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 {
@@ -85,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
}
@@ -105,18 +110,17 @@ impl WholeSet {
})
}
/// An engine sentence with each bare file name written root-relative
/// (`p1.sv:2` → `rtl/p1.sv:2`), where the name is the base name of
/// exactly one file of the set — the engines name files by base name,
/// and only an unambiguous one can be placed.
pub fn rooted(&self, project: &Project, sentence: &str) -> String {
/// 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 (path, _) in &self.files {
let Some(base) = path.file_name().and_then(|name| name.to_str()) else { continue };
let same = self.files.iter().filter(|(other, _)| other.file_name() == path.file_name());
let shown = project.relative(path);
if same.count() == 1 && shown != base {
out = replace_file_name(&out, base, &shown);
for (spelled, shown) in &self.names {
if out.contains(spelled.as_str()) {
out = replace_file_name(&out, spelled, shown);
}
}
out
@@ -140,6 +144,34 @@ 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 {
+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}");
}
+7 -2
View File
@@ -544,8 +544,11 @@ const SM: &str = "module main_sm (\n input logic clk_i,\n output logic busy_o
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 // state_q two\r\n string s = \"state_q\";\r\nendmodule\r\n";
"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() {
@@ -580,7 +583,9 @@ fn qa_mentions_find_every_kind_and_only_whole_words() {
#[test]
fn qa_mentions_are_capped_at_50_with_the_edited_file_first() {
let far: String = (0..60).map(|i| format!("// state_q far {i}\n")).collect::<String>()
// 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);
+7 -2
View File
@@ -277,7 +277,10 @@ 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"),
];
@@ -285,7 +288,9 @@ const MACRO_ARG: &[(&str, &str)] = &[
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`
// `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!(
+78 -16
View File
@@ -197,7 +197,7 @@ fn qa_every_cap_cuts_once_with_the_right_count_and_whole_lines() {
let expected = [
(300, 101), // the root line + 400 instances
(300, 100), // 400 instantiations
(299, 251), // root + 149 two-line blocks; the 150th block would pass 300
(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
@@ -220,9 +220,11 @@ fn qa_every_cap_cuts_once_with_the_right_count_and_whole_lines() {
assert_eq!(file, "rtl/big.sv");
number.parse::<u32>().unwrap();
}
// A peek block is never split: the last shown line is a statement.
// 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[298], " leaf u_148 (.a(a));");
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}");
}
@@ -715,17 +717,19 @@ fn qa_rework_every_local_kind_is_found_and_renamed_by_name_file_and_unit() {
#[test]
fn qa_rework_renaming_a_generate_label_never_leaves_a_path_through_it_behind() {
// `find g_lane refs` lists no use and `rename` answers `renamed 1 site`,
// leaving `g_lane[0].lane_q` naming a block that no longer exists —
// while `edit_item delete g_lane` sees the use (`rtl/fsm.sv:19:18`).
// `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)]);
// Lead's ruling R1: the MCP layer refuses the rename, and the source
// is untouched.
let said = session(&tree, &[("rename", json!({"name": "g_lane", "new_name": "g_ln"}))]);
assert!(said[0].refused, "{}", said[0].text);
let why = &said[0].text;
assert!(why.starts_with("`rename` does not rename generate block labels"), "{why}");
assert_eq!(tree.read("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]
@@ -745,10 +749,15 @@ fn qa_rework_a_shared_base_name_is_named_by_path_or_left_alone() {
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 it stays as said;
// `p1b.sv` is one, so it is named by its path.
// 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 p1.sv:4 connects with `.*` and p1.sv has"), "{added}");
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}");
}
@@ -805,3 +814,56 @@ fn qa_rework_an_escaped_local_outline_lists_is_found() {
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");
}
}
+10 -3
View File
@@ -795,7 +795,13 @@ fn rename_lists_the_old_names_unresolved_mentions() {
text.contains("\nwarning: `state_q` appears in the body of macro `SM_STATE`"),
"{text}"
);
assert!(text.ends_with("\nunresolved:\n rtl/sm.sv:1,8\n dv/probe_if.sv:2,4,6\n"), "{text}");
// Line 6 is `tb.…state_q`, a path nothing resolves: the engine's own
// warning names it (§65.1 F1), so it is not repeated as a mention.
assert!(
text.contains("\nwarning: dv/probe_if.sv:6: a hierarchical path through `state_q`"),
"{text}"
);
assert!(text.ends_with("\nunresolved:\n rtl/sm.sv:1,8\n dv/probe_if.sv:2,4\n"), "{text}");
// The hierarchical use in core.sv is renamed, so it is not a mention;
// the text the block names is left as it was.
assert!(read(&tree, "rtl/core.sv").contains("u_main_sm.main_state_q"));
@@ -894,12 +900,13 @@ fn engine_sentences_name_files_root_relative() {
assert_eq!(before, snapshot(&tree));
let added = server.text("port", json!({"module": "spare", "add": "input logic en"}));
assert!(added.contains("at `u_s` (rtl/spare_user.sv:5)"), "{added}");
// A base name two files share cannot be placed: left as the engine said.
// A base name two files share: the engine names it by its path (§65.1
// re-check R1), which the answer makes root-relative like any other.
let (tree, mut server) = served("edit");
fs::create_dir_all(tree.path("alt")).unwrap();
fs::write(tree.path("alt/cell.sv"), "module cell2; endmodule\n").unwrap();
let twice = refusal(&mut server, "port", json!({"module": "cell", "remove": "en"}));
assert!(twice.contains("inside `cell` at cell.sv:6"), "{twice}");
assert!(twice.contains("inside `cell` at rtl/cell.sv:6"), "{twice}");
}
#[test]
+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
));
}
+8 -8
View File
@@ -10,7 +10,7 @@ use vlog_parser::span::TextRange;
use vlog_parser::{parse_source_tolerant, LineIndex};
use vlog_semantic::SymbolKind;
use crate::rename::{display, Scope};
use crate::rename::Scope;
use crate::TextEdit;
use super::add::{element_spans, not_indexed};
@@ -113,7 +113,7 @@ pub(super) fn plan_remove(
return Err(format!(
"`{port}` is still used inside `{}` at {}:{}; remove those uses first.",
site.name,
display(path),
scope.name_of(path),
used.join(", ")
));
}
@@ -163,7 +163,7 @@ pub(super) fn plan_remove(
/// rename after QA found the same hole there (`Scope::macro_argument_sites`,
/// `Scope::define_sites`) answers it here, with news of its own.
fn preprocessor_warnings(scope: &Scope, file: usize, port: &str) -> Vec<String> {
let where_ = display(scope.path(file).unwrap_or(Path::new("?")));
let where_ = scope.name_at(file);
let mut out = Vec::new();
for site in scope.macro_argument_sites(file, port) {
out.push(format!(
@@ -283,7 +283,7 @@ fn disconnection_edits(
return Ok((Vec::new(), 0));
}
let (tree, _) = parse_source_tolerant(text);
disconnections_in(text, path, &tree, &site.name, port, warnings)
disconnections_in(text, &scope.name_of(path), &tree, &site.name, port, warnings)
}
/// [`disconnection_edits`] over a parse the caller already has, so the offer
@@ -291,7 +291,7 @@ fn disconnection_edits(
/// without building a workspace (take 5 §P1c).
pub(super) fn disconnections_in(
text: &str,
path: &Path,
shown: &str,
tree: &SourceFile,
module: &str,
port: &str,
@@ -311,7 +311,7 @@ pub(super) fn disconnections_in(
return Err(format!(
"`{}` in {} connects `{}`'s ports by position; dropping one would silently re-bind the rest, so lucisv made no edits — give it named connections first.",
instance.name,
display(path),
shown,
module
))
}
@@ -325,7 +325,7 @@ pub(super) fn disconnections_in(
warnings.push(format!(
"`{}` at {}:{} connects with `.*`, so nothing was removed there; the signal it bound `{port}` to may now be unused.",
instance.name,
display(path),
shown,
lines.line_col(instance.name_span.start).0
));
continue;
@@ -346,7 +346,7 @@ pub(super) fn disconnections_in(
if !trivial {
warnings.push(format!(
"`{written}` at {}:{} was deleted with the port.",
display(path),
shown,
lines.line_col(expr.span.start).0
));
}
+119
View File
@@ -0,0 +1,119 @@
//! The same-named members a rename leaves in the *other* arms of a generate
//! label, said out loud (generate-label-rename QA F2, re-check R3).
//!
//! Two arms of one generate `if`/`case` may carry one label (IEEE 1800
//! §27.5), and a path `g.x` names whichever arm elaborates. Renaming the `x`
//! of one arm rewrites `g.x` with it, so the `x` of every other arm reachable
//! by the same hierarchical name — through *every* enclosing same-label pair,
//! `g.h.x` with two `g` arms each holding an `h` — is named, not edited.
//!
//! Which arms carry a label is the binder's record: an arm's scope is owned by
//! its label, or — for an arm whose label repeats an earlier one — it is the
//! scope whose span is that redeclaration's (`Semantics::duplicates`).
use vlog_semantic::{ScopeId, ScopeKind, Semantics, SymbolId, SymbolKind};
use super::Target;
use crate::scope::Scope;
impl<'a> Scope<'a> {
/// One warning per other declaration of the renamed name that the same
/// hierarchical name reaches through another combination of arms.
pub(super) fn sibling_arm_warnings(&mut self, target: &Target) -> Vec<String> {
let where_ = self.name_at(target.file);
let text = self.text(target.file).unwrap_or("");
let Some(analysis) = self.analysis(target.file) else { return Vec::new() };
let sem = &analysis.semantics;
let Some(symbol) = sem.symbol(target.symbol) else { return Vec::new() };
let (root, labels) = label_chain(sem, symbol.scope);
if labels.is_empty() {
return Vec::new();
}
let dotted = labels.join(".");
reachable_arms(sem, root, &labels)
.into_iter()
.filter(|&arm| arm != symbol.scope)
.filter_map(|arm| sem.scope(arm)?.lookup_local(&target.name))
.filter_map(|other| sem.symbol(other))
.map(|other| {
let line = text[..other.name_span.start as usize].matches('\n').count() + 1;
format!(
"`{}` is also declared at {where_}:{line}, in another arm labelled `{dotted}`; a path `{dotted}.{}` now names only the renamed arm's declaration, and that one was left unchanged.",
target.name, target.name
)
})
.collect()
}
}
/// The labels of the arms enclosing `scope`, outermost first, and the scope
/// the outermost one is declared in. A scope that is no labelled arm ends the
/// chain.
fn label_chain(sem: &Semantics, scope: ScopeId) -> (ScopeId, Vec<String>) {
let mut labels = Vec::new();
let mut here = scope;
while let Some(label) = arm_label(sem, here).and_then(|id| sem.symbol(id)) {
labels.push(label.name.clone());
here = label.scope;
}
labels.reverse();
(here, labels)
}
/// Every arm the dotted `labels` reach from `root`: each label looked up in
/// the scope the previous level's arms open, and every arm carrying it.
fn reachable_arms(sem: &Semantics, root: ScopeId, labels: &[String]) -> Vec<ScopeId> {
let mut level = vec![root];
for label in labels {
level = level
.iter()
.filter_map(|&scope| sem.scope(scope)?.lookup_local(label))
.filter(|&id| sem.symbol(id).is_some_and(|s| s.kind == SymbolKind::Block))
.flat_map(|id| arms_of(sem, id))
.collect();
}
level
}
/// The arm scopes carrying block label `label`: the one it owns, and every
/// arm whose repeated label the binder recorded as a redeclaration of it.
fn arms_of(sem: &Semantics, label: SymbolId) -> Vec<ScopeId> {
let owned = sem.symbol(label).and_then(|s| s.child_scope);
let repeats =
sem.duplicates().iter().filter(|d| d.first == label && d.kind == SymbolKind::Block);
let mut out: Vec<ScopeId> = owned.into_iter().collect();
for repeat in repeats {
out.extend(arm_at(sem, repeat.scope, repeat.decl_span));
}
out
}
/// The label an arm scope carries: its owner, or the first declaration its
/// repeated label redeclares.
fn arm_label(sem: &Semantics, arm: ScopeId) -> Option<SymbolId> {
let scope = sem.scope(arm)?;
if scope.kind != ScopeKind::Generate {
return None;
}
if let Some(owner) = scope.owner {
return (sem.symbol(owner)?.kind == SymbolKind::Block).then_some(owner);
}
let parent = scope.parent?;
sem.duplicates()
.iter()
.find(|d| d.kind == SymbolKind::Block && d.scope == parent && d.decl_span == scope.span)
.map(|d| d.first)
}
/// The generate scope a repeated label's block opened: a child of the scope
/// the label is declared in, spanning exactly the block.
fn arm_at(
sem: &Semantics,
declared_in: ScopeId,
span: vlog_parser::span::TextRange,
) -> Option<ScopeId> {
let parent = sem.scope(declared_in)?;
parent.children.iter().copied().find(|&child| {
sem.scope(child).is_some_and(|c| c.kind == ScopeKind::Generate && c.span == span)
})
}
+324
View File
@@ -0,0 +1,324 @@
//! Which macro arguments can reach a module member from any file (TODO
//! §65.1, independent review H-1/H-2, 2026-10-06).
//!
//! A bare spelling in another file's macro argument is that file's own name
//! — unless the macro *carries* the argument somewhere a bare name is not:
//! after a `.` (`force u_m.sig`, a named connection `.x(x)`), after a `.`
//! through a `` `` `` paste (`` u_m.``sig ``), into a `bind` into the
//! declaring unit (whose connections are evaluated in that unit), or into
//! another macro's argument that is carried. Such an argument is news
//! wherever it is written. So is an argument of a macro the set does not
//! define, or one past the macro's formals: nothing shows it cannot reach.
//!
//! A `bind` is recognised where its keyword is spelled in a `` `define``
//! body of the set (directly, or in a macro that body invokes); a macro that
//! expands to one is a *binder*: every argument it takes is carried, its body
//! is news (as a `bind` statement's would be), and a file invoking it is home
//! (K2).
use std::collections::{HashMap, HashSet};
use super::contains_word;
use super::home::{macro_names, skip_string};
use super::scoped::{binds_into, spellings};
/// One `` `define`` of a macro: its formal names as written and its body.
pub(crate) struct MacroDef {
/// The formal arguments as written (`"a"`, `"b = 8"`); empty for an
/// object-like macro.
pub(crate) params: Vec<String>,
/// The replacement text, line continuations joined.
pub(crate) body: String,
}
/// Macro name → every `` `define`` of it in the set.
pub(crate) type Defs = HashMap<String, Vec<MacroDef>>;
/// Which arguments of which macros are carried, for one declaring unit.
#[derive(Default)]
pub(super) struct Carriers {
/// Macro → per formal position, whether it is carried; `None` when every
/// position is (a binder).
formals: HashMap<String, Option<Vec<bool>>>,
/// The macros that expand to a `bind` into the unit.
binders: HashSet<String>,
}
impl Carriers {
/// The carried arguments of every macro in `defs`, for members of `unit`.
pub(super) fn of(defs: &Defs, unit: &str) -> Carriers {
let mut walk = Walk { defs, unit, binder: HashMap::new(), formals: HashMap::new() };
let names: Vec<&String> = defs.keys().collect();
for name in names {
walk.formals_of(name, &mut HashSet::new());
}
let binders = walk.binder.into_iter().filter(|(_, b)| *b).map(|(n, _)| n).collect();
Carriers { formals: walk.formals, binders }
}
/// Whether argument `position` (0-based) of an invocation of
/// `macro_name` may reach the declaration from any file.
pub(super) fn carries(&self, macro_name: &str, position: usize) -> bool {
match self.formals.get(macro_name) {
Some(Some(formals)) => formals.get(position).copied().unwrap_or(true),
Some(None) | None => true,
}
}
/// Whether `macro_name` expands to a `bind` into the unit.
pub(super) fn binds(&self, macro_name: &str) -> bool {
self.binders.contains(macro_name)
}
/// Whether any macro of the set is a binder.
pub(super) fn any_binder(&self) -> bool {
!self.binders.is_empty()
}
}
/// The memoized recursion over the set's macros.
struct Walk<'a> {
defs: &'a Defs,
unit: &'a str,
binder: HashMap<String, bool>,
formals: HashMap<String, Option<Vec<bool>>>,
}
impl Walk<'_> {
/// Whether `name` expands to a `bind` into the unit, directly or through
/// a macro its body invokes. A cycle (an illegal macro) answers `false`.
fn is_binder(&mut self, name: &str, active: &mut HashSet<String>) -> bool {
if let Some(&known) = self.binder.get(name) {
return known;
}
let Some(defs) = self.defs.get(name) else { return false };
if !active.insert(name.to_string()) {
return false;
}
let mut found = defs.iter().any(|d| body_binds(&d.body, self.unit));
if !found {
let inner: Vec<String> = defs.iter().flat_map(|d| macro_names(&d.body)).collect();
found = inner.iter().any(|n| self.is_binder(n, active));
}
active.remove(name);
self.binder.insert(name.to_string(), found);
found
}
/// The carried formal positions of `name`; `None` when every position is
/// (a binder, an unknown macro, or a cycle — nothing shows otherwise).
fn formals_of(&mut self, name: &str, active: &mut HashSet<String>) -> Option<Vec<bool>> {
if let Some(known) = self.formals.get(name) {
return known.clone();
}
let defs = self.defs.get(name)?;
if active.contains(name) {
return None;
}
if self.is_binder(name, &mut HashSet::new()) {
self.formals.insert(name.to_string(), None);
return None;
}
active.insert(name.to_string());
let mut carried: Vec<bool> = Vec::new();
for def in defs {
for (position, formal) in def.params.iter().enumerate() {
let formal = formal.split('=').next().unwrap_or_default().trim();
if carried.len() <= position {
carried.resize(position + 1, false);
}
carried[position] |= self.formal_is_carried(&def.body, formal, active);
}
}
active.remove(name);
self.formals.insert(name.to_string(), Some(carried.clone()));
Some(carried)
}
/// Whether `body` spells `formal` after a `.`, or passes it to a macro
/// argument that is carried.
fn formal_is_carried(
&mut self,
body: &str,
formal: &str,
active: &mut HashSet<String>,
) -> bool {
if formal.is_empty() || !contains_word(body, formal) {
return false;
}
if spellings(body, formal).1 {
return true;
}
for (inner, arguments) in invocations(body) {
for (position, argument) in arguments.iter().enumerate() {
if !contains_word(argument, formal) {
continue;
}
let carried = match self.formals_of(&inner, active) {
Some(formals) => formals.get(position).copied().unwrap_or(true),
None => true,
};
if carried {
return true;
}
}
}
false
}
}
/// Whether a `` `define`` body holds a `bind` into `unit`; a body that
/// spells `bind` but does not lex is counted (doubt).
fn body_binds(body: &str, unit: &str) -> bool {
if !contains_word(body, "bind") {
return false;
}
match vlog_parser::tokenize(body) {
Ok(tokens) => !binds_into(&tokens, unit).is_empty(),
Err(_) => true,
}
}
/// Every function-like macro invocation in `text` (strings and comments
/// skipped): its name and its top-level argument texts. Invocations nested
/// in another's arguments are listed too.
fn invocations(text: &str) -> Vec<(String, Vec<&str>)> {
let bytes = text.as_bytes();
let mut out = Vec::new();
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'"' => i = skip_string(bytes, i + 1),
b'/' if bytes.get(i + 1) == Some(&b'/') => {
i = bytes[i..].iter().position(|&b| b == b'\n').map_or(bytes.len(), |n| i + n)
}
b'/' if bytes.get(i + 1) == Some(&b'*') => {
i = text[i + 2..].find("*/").map_or(bytes.len(), |n| i + 2 + n + 2)
}
// `` `" `` (stringify) and `` `` `` (paste) open nothing.
b'`' if matches!(bytes.get(i + 1), Some(b'"' | b'`')) => i += 2,
b'`' => {
let len = text[i + 1..]
.bytes()
.take_while(|b| b.is_ascii_alphanumeric() || *b == b'_' || *b == b'$')
.count();
let name = &text[i + 1..i + 1 + len];
i += 1 + len;
let open = i + text[i..].len() - text[i..].trim_start().len();
if !name.is_empty() && bytes.get(open) == Some(&b'(') {
out.push((name.to_string(), split_arguments(&text[open + 1..]).0));
}
}
_ => i += 1,
}
}
out
}
/// The top-level, comma-separated arguments of the list that starts right
/// after its `(`, up to the matching `)` (or the end of `text`), with the
/// byte offset of each argument's start.
fn split_arguments(text: &str) -> (Vec<&str>, Vec<usize>) {
let bytes = text.as_bytes();
let (mut arguments, mut starts) = (Vec::new(), vec![0]);
let (mut depth, mut start, mut i) = (0usize, 0usize, 0usize);
while i < bytes.len() {
match bytes[i] {
b'"' => {
i = skip_string(bytes, i + 1);
continue;
}
b'(' | b'[' | b'{' => depth += 1,
b')' | b']' | b'}' if depth == 0 => break,
b')' | b']' | b'}' => depth -= 1,
b',' if depth == 0 => {
arguments.push(&text[start..i]);
start = i + 1;
starts.push(start);
}
_ => {}
}
i += 1;
}
arguments.push(&text[start..i.min(text.len())]);
(arguments, starts)
}
/// The 0-based position of the argument holding byte `offset` of an
/// invocation's argument text (the text right after its `(`).
pub(super) fn argument_position(arguments: &str, offset: usize) -> usize {
let (_, starts) = split_arguments(arguments);
starts.iter().filter(|&&start| start <= offset).count().saturating_sub(1)
}
#[cfg(test)]
mod tests {
use super::*;
fn defs(entries: &[(&str, &[&str], &str)]) -> Defs {
let mut out = Defs::new();
for (name, params, body) in entries {
let params = params.iter().map(|p| p.to_string()).collect();
out.entry(name.to_string())
.or_default()
.push(MacroDef { params, body: body.to_string() });
}
out
}
#[test]
fn a_formal_after_a_dot_or_a_pasted_dot_is_carried_and_a_plain_one_is_not() {
let set = defs(&[
("CONN", &["x"], ".x(x)"),
("FORCE", &["sig"], "force u_m.sig = 1'b0;"),
("PEEK", &["sig"], "u_m.``sig"),
("ASSERT", &["n", "e"], "n: assert property (e);"),
("STR", &["s"], "`\"s`\""),
]);
let carriers = Carriers::of(&set, "m");
assert!(carriers.carries("CONN", 0));
assert!(carriers.carries("FORCE", 0));
assert!(carriers.carries("PEEK", 0));
assert!(!carriers.carries("ASSERT", 0) && !carriers.carries("ASSERT", 1));
assert!(!carriers.carries("STR", 0));
assert!(carriers.carries("ASSERT", 2), "past the formals");
assert!(carriers.carries("UNKNOWN", 0), "a macro the set does not define");
}
#[test]
fn a_formal_passed_on_is_carried_only_when_the_inner_position_is() {
let set = defs(&[
("OUTER", &["a", "b"], "`INNER(a, b)"),
("INNER", &["p", "q"], "p + top.q"),
("ELSEWHERE", &["a"], "`NOT_IN_SET(a)"),
("LOOP", &["a"], "`LOOP(a)"),
]);
let carriers = Carriers::of(&set, "m");
assert!(!carriers.carries("OUTER", 0));
assert!(carriers.carries("OUTER", 1));
assert!(carriers.carries("ELSEWHERE", 0));
assert!(carriers.carries("LOOP", 0), "a cycle is doubt");
}
#[test]
fn a_macro_expanding_to_a_bind_into_the_unit_is_a_binder_through_other_macros() {
let set = defs(&[
("BIND_CHK", &[], "bind m chk u_chk (.s(state_q));"),
("WRAP", &["x"], "`BIND_CHK x"),
("OTHER", &["x"], "bind n chk u (.s(x));"),
]);
let carriers = Carriers::of(&set, "m");
assert!(carriers.binds("BIND_CHK") && carriers.binds("WRAP"));
assert!(carriers.carries("WRAP", 0));
assert!(!carriers.binds("OTHER") && !carriers.carries("OTHER", 0));
}
#[test]
fn an_argument_position_counts_top_level_commas_only() {
let args = "a, f(b, c), {d, e}, \"x,y\", g)";
assert_eq!(argument_position(args, 0), 0);
assert_eq!(argument_position(args, args.find('c').unwrap_or(0)), 1);
assert_eq!(argument_position(args, args.find('e').unwrap_or(0)), 2);
assert_eq!(argument_position(args, args.find('g').unwrap_or(0)), 4);
}
}
@@ -30,7 +30,7 @@ use vlog_semantic::{ScopeKind, Surface, SymbolId, SymbolKind};
use super::layout::{append, connection, shorthand_tail};
use super::sites::{binds_implicitly, may_connect_implicitly, nearest, sites, Site};
use super::{contains_word, display, Scope, Target};
use super::{contains_word, Scope, Target};
use crate::TextEdit;
/// The insertions a rename's implicit connections need, and the sentences
@@ -451,7 +451,7 @@ impl<'a> Scope<'a> {
/// "`u_leaf` at top.sv:12", the way every sentence here names an instance.
fn describe(&self, file: usize, text: &str, site: &Site) -> String {
let path = self.path(file).map(display).unwrap_or_default();
let path = self.name_at(file);
let line = LineIndex::new(text).line_col(site.instance.name_span.start).0;
format!("`{}` at {path}:{line}", site.instance.name)
}
+326
View File
@@ -0,0 +1,326 @@
//! The **home set** of a declaration: the files whose text the preprocessor
//! pastes into, or out of, the scope the declaration is written in (TODO
//! §65.1, QA final H1–H4 and the lead's corrected ruling, 2026-09-30).
//!
//! The declaring file; every file it `` `include``s, transitively; every file
//! that includes the declaring file (a declaration in an included fragment),
//! and that file's own includes, transitively; and the files the rename
//! edits. An include is resolved against the set by path suffix (`"a/b.svh"`
//! matches `…/a/b.svh`), and when nothing ends that way, by base name — every
//! file of that base name is home.
//!
//! Text only: the include directives are read off the files' bytes, so a
//! commented-out include makes the set larger, never smaller.
use std::collections::{BTreeSet, HashMap, HashSet};
use std::path::{Path, PathBuf};
use super::carry::Defs;
/// The home set of the file at `declaring` in `files`, plus `edited`, as
/// paths — what `lucisv-mcp` scopes a member's mentions with. `None` when the
/// set cannot be known: some include of it names no file of the set, or is
/// not a plain `"…"`/`<…>` name (a macro builds it) — and then nothing may be
/// scoped.
pub fn home_set(
files: &[(PathBuf, String)],
declaring: &Path,
edited: &[PathBuf],
) -> Option<Vec<PathBuf>> {
let sources: Vec<(&Path, &str)> =
files.iter().map(|(p, t)| (p.as_path(), t.as_str())).collect();
let at = sources.iter().position(|(p, _)| *p == declaring)?;
let edited: Vec<usize> =
edited.iter().filter_map(|e| sources.iter().position(|(p, _)| p == e)).collect();
let home = home_of(&sources, at, &edited);
if home.unknown {
return None;
}
Some(home.all.into_iter().filter_map(|i| Some(sources.get(i)?.0.to_path_buf())).collect())
}
/// A home set by source index, with which of its files are include-related to
/// the declaring file (as opposed to edited only).
pub(crate) struct Home {
/// Every home file, the declaring one included.
pub(crate) all: BTreeSet<usize>,
/// The files the declaring file includes, transitively.
pub(crate) included: BTreeSet<usize>,
/// The files that include the declaring file, those that include them,
/// and so on, and everything any of them includes — minus the declaring
/// file and [`Home::included`].
pub(crate) around: BTreeSet<usize>,
/// Whether a file of the include-related set has an include the engine
/// cannot resolve (K3): the set is then not known.
pub(crate) unknown: bool,
}
/// [`home_set`] over a scope's `(path, text)` sources.
pub(crate) fn home_of(sources: &[(&Path, &str)], declaring: usize, edited: &[usize]) -> Home {
let graph = Graph::of(sources);
let included = graph.down(&[declaring], &BTreeSet::from([declaring]));
let mut up: BTreeSet<usize> = BTreeSet::new();
let mut todo = vec![declaring];
while let Some(i) = todo.pop() {
for &j in graph.included_by.get(&i).into_iter().flatten() {
if j != declaring && up.insert(j) {
todo.push(j);
}
}
}
let roots: Vec<usize> = up.iter().copied().collect();
let mut known = included.clone();
known.insert(declaring);
known.extend(roots.iter().copied());
let mut around = up;
around.extend(graph.down(&roots, &known));
around.retain(|i| *i != declaring && !included.contains(i));
let mut all: BTreeSet<usize> = [declaring].into();
all.extend(included.iter().copied());
all.extend(around.iter().copied());
let unknown = all.iter().any(|i| graph.unresolved.contains(i));
all.extend(edited.iter().copied());
Home { all, included, around, unknown }
}
/// Who includes whom in one set of files.
struct Graph {
/// File → the files its includes resolve to.
includes: HashMap<usize, Vec<usize>>,
/// File → the files that include it.
included_by: HashMap<usize, Vec<usize>>,
/// The files with an include that resolves to nothing, or that a macro
/// builds.
unresolved: HashSet<usize>,
}
impl Graph {
fn of(sources: &[(&Path, &str)]) -> Graph {
let mut by_base: HashMap<&std::ffi::OsStr, Vec<usize>> = HashMap::new();
for (i, (path, _)) in sources.iter().enumerate() {
if let Some(base) = path.file_name() {
by_base.entry(base).or_default().push(i);
}
}
let mut graph = Graph {
includes: HashMap::new(),
included_by: HashMap::new(),
unresolved: HashSet::new(),
};
for (i, (_, text)) in sources.iter().enumerate() {
if !text.contains("`include") {
continue;
}
for include in includes_in(text) {
let found = match include {
Some(spelled) => resolve(sources, &by_base, spelled),
None => Vec::new(),
};
if found.is_empty() {
graph.unresolved.insert(i);
}
for j in found {
graph.includes.entry(i).or_default().push(j);
graph.included_by.entry(j).or_default().push(i);
}
}
}
graph
}
/// Every file `roots` include, transitively, that is not in `known`.
fn down(&self, roots: &[usize], known: &BTreeSet<usize>) -> BTreeSet<usize> {
let mut out = BTreeSet::new();
let mut todo = roots.to_vec();
while let Some(i) = todo.pop() {
for &j in self.includes.get(&i).into_iter().flatten() {
if !known.contains(&j) && out.insert(j) {
todo.push(j);
}
}
}
out
}
}
/// Every `` `include`` of one text: `Some(name)` for a plain `"…"`/`<…>`
/// form, `None` for one whose name is built some other way (a macro).
fn includes_in(text: &str) -> Vec<Option<&str>> {
let mut out = Vec::new();
let mut from = 0;
while let Some(hit) = text.get(from..).and_then(|s| s.find("`include")) {
let after = from + hit + "`include".len();
from = after;
// `` `includes`` or `` `include_dir`` is another word.
if text[after..].starts_with(|c: char| c.is_ascii_alphanumeric() || c == '_') {
continue;
}
let rest = text[after..].trim_start();
let close = match rest.chars().next() {
Some('"') => '"',
Some('<') => '>',
_ => {
out.push(None);
continue;
}
};
match rest[1..].find(close) {
Some(end) => out.push(Some(&rest[1..1 + end])),
None => out.push(None),
}
}
out
}
/// The sources an include spelling names: every file of its base name whose
/// path ends in it, else every file of its base name.
fn resolve(
sources: &[(&Path, &str)],
by_base: &HashMap<&std::ffi::OsStr, Vec<usize>>,
spelled: &str,
) -> Vec<usize> {
let wanted = Path::new(spelled);
let Some(candidates) = wanted.file_name().and_then(|base| by_base.get(base)) else {
return Vec::new();
};
let suffix: Vec<usize> =
candidates.iter().copied().filter(|&i| sources[i].0.ends_with(wanted)).collect();
match suffix.is_empty() {
true => candidates.clone(),
false => suffix,
}
}
/// Every macro name invoked in `texts`, and — through the bodies in `defs` —
/// every macro those invoke, and so on: what can expand inside the home set.
pub(crate) fn invoked_from(texts: &[&str], defs: &Defs) -> HashSet<String> {
let mut invoked: HashSet<String> = HashSet::new();
let mut todo: Vec<String> = texts.iter().flat_map(|t| macro_names(t)).collect();
while let Some(name) = todo.pop() {
if !invoked.insert(name.clone()) {
continue;
}
for def in defs.get(&name).into_iter().flatten() {
todo.extend(macro_names(&def.body));
}
}
invoked
}
/// The names after every backtick in `text` that stands in code — not inside
/// a string literal or a comment, where a backtick invokes nothing (QA N2).
/// Directives are included; no `` `define`` can be named like one.
pub(super) fn macro_names(text: &str) -> Vec<String> {
let mut out = Vec::new();
let bytes = text.as_bytes();
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'"' => i = skip_string(bytes, i + 1),
b'/' if bytes.get(i + 1) == Some(&b'/') => {
i = bytes[i..].iter().position(|&b| b == b'\n').map_or(bytes.len(), |n| i + n)
}
b'/' if bytes.get(i + 1) == Some(&b'*') => {
i = text[i + 2..].find("*/").map_or(bytes.len(), |n| i + 2 + n + 2)
}
b'`' => {
let name: String = text[i + 1..]
.chars()
.take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '$')
.collect();
i += 1 + name.len();
if !name.is_empty() {
out.push(name);
}
}
_ => i += 1,
}
}
out
}
/// The offset just past the string literal whose body starts at `i`.
pub(super) fn skip_string(bytes: &[u8], mut i: usize) -> usize {
while i < bytes.len() {
match bytes[i] {
b'\\' => i += 2,
b'"' => return i + 1,
_ => i += 1,
}
}
bytes.len()
}
#[cfg(test)]
mod tests {
use super::super::carry::MacroDef;
use super::*;
fn set(files: &[&str]) -> Vec<(PathBuf, String)> {
files.iter().map(|f| (PathBuf::from(f), String::new())).collect()
}
#[test]
fn an_include_is_read_between_quotes_or_angle_brackets() {
let text = "`include \"a/b.svh\"\n `include <c.sv>\n`include MACRO\n`include_dirs x\n";
assert_eq!(includes_in(text), vec![Some("a/b.svh"), Some("c.sv"), None]);
}
#[test]
fn the_home_set_follows_includes_both_ways_and_takes_every_base_name_match() {
let mut files = set(&[
"/r/m.sv",
"/r/x/m_assert.svh",
"/r/top.sv",
"/r/a/defs.svh",
"/r/b/defs.svh",
"/r/far.sv",
]);
files[0].1 = "module m;\n`include \"m_assert.svh\"\nendmodule\n".into();
files[1].1 = "`include \"defs.svh\"\n".into();
files[2].1 = "`include \"m.sv\"\n".into();
let home = home_set(&files, Path::new("/r/m.sv"), &[]).expect("known");
let names: Vec<&str> = home.iter().filter_map(|p| p.to_str()).collect();
assert_eq!(
names,
vec!["/r/m.sv", "/r/x/m_assert.svh", "/r/top.sv", "/r/a/defs.svh", "/r/b/defs.svh"]
);
}
#[test]
fn the_upward_chain_is_followed_transitively_and_a_cycle_ends() {
let mut files = set(&["/r/frag.svh", "/r/mid.sv", "/r/outer.sv", "/r/side.svh"]);
files[1].1 = "`include \"frag.svh\"\n".into();
files[2].1 = "`include \"mid.sv\"\n`include \"side.svh\"\n".into();
files[3].1 = "`include \"outer.sv\"\n".into();
let home = home_set(&files, Path::new("/r/frag.svh"), &[]).expect("known");
assert_eq!(home.len(), 4, "{home:?}");
}
#[test]
fn an_include_a_macro_builds_or_that_names_no_file_makes_the_set_unknown() {
let mut files = set(&["/r/m.sv", "/r/paths.svh"]);
files[0].1 = "`include \"paths.svh\"\n`include `FRAG\n".into();
assert_eq!(home_set(&files, Path::new("/r/m.sv"), &[]), None);
files[0].1 = "`include \"nowhere.svh\"\n".into();
assert_eq!(home_set(&files, Path::new("/r/m.sv"), &[]), None);
files[0].1 = "// no includes\n".into();
assert!(home_set(&files, Path::new("/r/m.sv"), &[]).is_some());
}
#[test]
fn a_backtick_in_a_string_or_a_comment_invokes_nothing() {
let names = macro_names("x = `A; $display(\"`B \\\" `C\"); // `D\n/* `E */ `F");
assert_eq!(names, vec!["A", "F"]);
}
#[test]
fn invocations_are_followed_through_define_bodies() {
let def = |body: &str| vec![MacroDef { params: Vec::new(), body: body.to_string() }];
let defs: Defs = [("A".to_string(), def("`B(x)")), ("B".to_string(), def("clk_i"))]
.into_iter()
.collect();
let invoked = invoked_from(&[" `A\n"], &defs);
assert!(invoked.contains("A") && invoked.contains("B"));
}
}
+13 -2
View File
@@ -12,17 +12,28 @@
//! workspace every refactoring in this crate reads through, `warnings` is
//! what a finished rename says about the occurrences it could not edit, and
//! `connections` (with `sites` and `layout`) rewrites the `.name` and `.*`
//! connections that bind the renamed name implicitly.
//! connections that bind the renamed name implicitly; `paths` names the
//! hierarchical paths through the name that nothing resolved, and `arms` the
//! same-named members of the other arms of its generate labels; `scoped`
//! decides which text spellings a warning is about the renamed declaration,
//! over `home`'s include-derived home set and `carry`'s macro arguments that
//! reach the declaration from any file.
mod arms;
mod carry;
mod connections;
mod home;
use connections::{combine, fuse};
mod layout;
mod paths;
mod preflight;
mod scoped;
pub(crate) mod sites;
#[cfg(test)]
mod tests;
mod warnings;
pub use home::home_set;
pub use preflight::rename_preflight;
// The rename was the first refactoring, so most of the crate still spells the
@@ -537,7 +548,7 @@ impl<'a> Scope<'a> {
"lucisv found `{name}` recorded at bytes {}..{} of {}, which does not spell it; the rename was abandoned.",
span.start,
span.end,
display(self.path(file).unwrap_or(Path::new("?")))
self.name_at(file)
));
}
if n > 0 && span.start < last_end {
+159
View File
@@ -0,0 +1,159 @@
//! What a rename could not account for **in hierarchical paths**, said out
//! loud (generate-label-rename QA F1).
//!
//! [`Scope::unresolved_path_warnings`]: a segment spelling the renamed name,
//! in *any* file of the set, that resolved to no declaration at all
//! (`tb.dut.g_sw[0].q`, where `tb` is a top module another file declares and
//! nothing resolves the root — TODO §65.4). The rename cannot know whether
//! that path reaches the renamed declaration, so it is left unchanged and
//! named. A segment that resolved to a *different* declaration is not news
//! and is not reported. (The same-label arms are `arms.rs`.)
//!
//! Narrowed by the index's word census and then by a text test for a `.` or
//! `[` beside the name, so a file is analysed only when it could hold such a
//! segment; a name the census cannot hold (an escaped one) is narrowed by
//! text alone.
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::tokenize;
use vlog_semantic::{Resolution, Semantics};
use crate::scope::Scope;
impl<'a> Scope<'a> {
/// One warning per file listing the lines where a path segment spelling
/// `name` resolved to nothing. `edited` files skip a segment with no
/// reference at all: the edited-file stray scan (`unaccounted_warnings`)
/// already names it, and saying it twice is noise.
pub(super) fn unresolved_path_warnings(&mut self, name: &str, edited: &[usize]) -> Vec<String> {
// The census holds no escaped identifier (`words.rs`), so for one the
// text test below is the whole filter.
let escaped = name.starts_with('\\');
let mentioning: Vec<_> = self.index().files_mentioning(name).collect();
let mut out = Vec::new();
for i in 0..self.len() {
if !escaped && !self.file_id(i).is_some_and(|id| mentioning.contains(&id)) {
continue;
}
let Some(text) = self.text(i) else { continue };
if !spelled_beside_a_path(text, name) {
continue;
}
let Some(path) = self.path(i) else { continue };
let Ok(tokens) = tokenize(text) else { continue };
let Some(analysis) = self.analysis(i) else { continue };
let lines =
unresolved_segments(&analysis.semantics, &tokens, name, edited.contains(&i));
if lines.is_empty() {
continue;
}
let at = lines.iter().map(u32::to_string).collect::<Vec<_>>().join(",");
out.push(format!(
"{}:{at}: a hierarchical path through `{name}` was not resolved to any declaration, so it was left unchanged; check whether it reaches the renamed one.",
self.name_of(path)
));
}
out
}
}
/// The 1-based lines of `name` tokens that are a path segment and resolved to
/// nothing: no reference at all (unless `edited`, see the caller), or a
/// reference whose resolution is `NotFound`.
fn unresolved_segments(sem: &Semantics, tokens: &[Token], name: &str, edited: bool) -> Vec<u32> {
let mut lines: Vec<u32> = Vec::new();
for (i, token) in tokens.iter().enumerate() {
if token.kind != TokenKind::Ident || token.text != name || !is_segment(tokens, i) {
continue;
}
if sem.symbol_at(token.span.start).is_some() {
continue;
}
let unresolved = match sem.reference_at(token.span.start) {
Some(r) if r.name_span == token.span => matches!(r.resolution, Resolution::NotFound),
_ => !edited,
};
if unresolved && lines.last() != Some(&token.line) {
lines.push(token.line);
}
}
lines
}
/// Whether the identifier at `i` is one segment of a dotted path: a `.`
/// before it, or a `.` after it past any element selects (`g[0][1].x`).
fn is_segment(tokens: &[Token], i: usize) -> bool {
if i.checked_sub(1).and_then(|p| tokens.get(p)).is_some_and(|t| t.is_sym(".")) {
return true;
}
let mut next = i + 1;
while tokens.get(next).is_some_and(|t| t.is_sym("[")) {
let mut depth = 0usize;
loop {
let Some(t) = tokens.get(next) else { return false };
if t.is_sym("[") {
depth += 1;
} else if t.is_sym("]") {
depth -= 1;
if depth == 0 {
break;
}
}
next += 1;
}
next += 1;
}
tokens.get(next).is_some_and(|t| t.is_sym("."))
}
/// A cheap superset of "`name` is spelled as a path segment somewhere in
/// `text`": a whole-word occurrence with a `.` before it or a `.` or `[`
/// after it, past blanks. A comment between the name and its neighbour is not
/// looked through — it passes, which is what a superset promises.
fn spelled_beside_a_path(text: &str, name: &str) -> bool {
let bytes = text.as_bytes();
let word = |b: u8| b.is_ascii_alphanumeric() || b == b'_' || b == b'$';
let mut from = 0;
while let Some(hit) = text.get(from..).and_then(|s| s.find(name)) {
let start = from + hit;
let end = start + name.len();
from = start + 1;
let before = text[..start].trim_end().as_bytes().last().copied();
let after = text[end..].trim_start().as_bytes().first().copied();
let whole = !start.checked_sub(1).and_then(|p| bytes.get(p)).is_some_and(|&b| word(b))
&& !bytes.get(end).is_some_and(|&b| word(b));
let beside =
matches!(before, Some(b'.' | b'/')) || matches!(after, Some(b'.' | b'[' | b'/'));
if whole && beside {
return true;
}
}
false
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_text_prefilter_passes_every_segment_shape() {
for text in ["a.g.b", "g[0].x", "g [i] .x", "u.g", "u. g", "g /* c */ .x", "u./*c*/g"] {
assert!(spelled_beside_a_path(text, "g"), "{text}");
}
for text in ["assign g = 1;", "gg.x", "u.gg", "x = g + 1;"] {
assert!(!spelled_beside_a_path(text, "g"), "{text}");
}
}
#[test]
fn a_segment_is_a_dot_neighbour_past_element_selects() {
let tokens = tokenize("x = a.g; y = g[0][k[1]].z; w = g[0]; v = g;").expect("lexes");
let at: Vec<bool> = tokens
.iter()
.enumerate()
.filter(|(_, t)| t.text == "g")
.map(|(i, _)| is_segment(&tokens, i))
.collect();
assert_eq!(at, vec![true, true, false, false]);
}
}
+388
View File
@@ -0,0 +1,388 @@
//! Which of the rename's *text* warnings are about the renamed declaration
//! (TODO §65.1: the lead's inspection, QA's final pass H1–H4, rework 4's
//! K1–K3/N1–N3 and the corrected rulings, 2026-09-30).
//!
//! **The governing principle: scoping may drop a warning only when the
//! engine can show the spelling cannot reach the renamed declaration; any
//! doubt falls back to the unscoped behaviour — every spelling warned, as
//! before scoping existed.**
//!
//! Scoping applies only to a declaration that is a **member of a module or
//! interface** (a net, variable, parameter, port, instance, block, a
//! function- or task-local, an enum value written in a module) whose **home
//! set** (`home.rs`) is known. A declaration with no enclosing unit (a
//! fragment's or `$unit`'s own declaration — K1) and one whose home set holds
//! an include the engine cannot resolve (K3) are warned about unscoped.
//! When it applies:
//!
//! * a **bare** spelling (no `.` before it) in a macro argument or an
//! unstructured assertion is news in the declaring file and in a file the
//! rename edits when the scope lookup there (`sites::nearest`) finds the
//! declaration (N1 — another module's own `clk_i` is not); in a file pasted
//! into or around the declaring file always (no scope to look in — H1);
//! inside a `bind` into the declaring unit wherever it is written (H3);
//! in an argument the macro carries after a `.`, into a `bind` into the
//! unit or into a macro the set does not define, wherever it is written
//! (`carry.rs`, review H-1/H-2); elsewhere never;
//! * a **dotted** spelling (`… .state_q`) may be a hierarchical path and is
//! always news;
//! * a `` `define`` body is news when it is written in the home set, when its
//! macro is invoked from the home set — a file with a `bind` into the unit,
//! or invoking a macro that expands to one, counts (K2) — through other
//! bodies too (H2), when the macro itself expands to such a `bind`, or when
//! it spells the name dotted; a macro with a **parameter** named like the
//! declaration never is (N2: the body's spellings are the parameter);
//! * a bare use in the plain code of a pasted file is a use the engine
//! cannot edit, and is said (H4, `Scope::fragment_use_warnings`) — for
//! every renamed declaration, scoped or not.
//!
//! Anything else — a module, interface, package or class, a package's or
//! class's member — can be named bare from any file (an import, a `pkg::`, a
//! handle), and every spelling is reported as before.
use std::collections::HashSet;
use vlog_parser::span::TextRange;
use vlog_parser::token::{Token, TokenKind};
use vlog_semantic::{ScopeId, Semantics, SymbolId};
use super::carry::{Carriers, Defs, MacroDef};
use super::home::{home_of, invoked_from, macro_names, Home};
use super::sites::nearest;
use super::Target;
use crate::scope::Scope;
use crate::TextEdit;
/// What the text scans need to know about the renamed declaration.
pub(super) struct Scoping {
/// The module or interface the declaration is a member of.
unit: Option<String>,
/// Whether spellings may be dropped at all: a member (`unit`) whose home
/// set is known. `false` is the unscoped behaviour.
scoped: bool,
declaring: usize,
symbol: SymbolId,
name: String,
/// The home set (`home.rs`), plus the files holding a `bind` into the
/// unit (K2).
home: Home,
/// Every macro a home-set file invokes, through define bodies.
invoked: HashSet<String>,
/// The macros whose arguments reach the unit from any file, and those
/// expanding to a `bind` into it (`carry.rs`).
carriers: Carriers,
}
impl Scoping {
/// The rule for `target`, renamed by edits to `edited`.
pub(super) fn new(scope: &mut Scope, target: &Target, edited: Vec<usize>) -> Scoping {
let unit = scope
.analysis(target.file)
.and_then(|a| a.semantics.symbol(target.symbol).map(|s| (s.scope, &a.semantics)))
.and_then(|(declared_in, sem)| enclosing_unit(sem, declared_in));
let sources: Vec<_> =
(0..scope.len()).filter_map(|i| Some((scope.path(i)?, scope.text(i)?))).collect();
let mut home = home_of(&sources, target.file, &edited);
let scoped = unit.is_some() && !home.unknown;
let mut invoked = HashSet::new();
let mut carriers = Carriers::default();
if let (Some(unit), true) = (&unit, scoped) {
let defs = define_defs(scope);
carriers = Carriers::of(&defs, unit);
home.all.extend(files_binding_into(scope, unit, &carriers));
let texts: Vec<&str> = home.all.iter().filter_map(|&i| scope.text(i)).collect();
invoked = invoked_from(&texts, &defs);
}
Scoping {
unit,
scoped,
declaring: target.file,
symbol: target.symbol,
name: target.name.clone(),
home,
invoked,
carriers,
}
}
/// The module or interface the declaration is a member of, when spellings
/// are scoped to it.
pub(super) fn unit(&self) -> Option<&str> {
self.unit.as_deref().filter(|_| self.scoped)
}
/// The files the preprocessor pastes into or around the declaring file
/// (H4's fragments), each with whether the declaring file includes it
/// (`true`) or it is on the including side (`false`).
pub(super) fn pasted(&self) -> Vec<(usize, bool)> {
let included = self.home.included.iter().map(|&i| (i, true));
included.chain(self.home.around.iter().map(|&i| (i, false))).collect()
}
/// The declaring file's source index.
pub(super) fn declaring(&self) -> usize {
self.declaring
}
/// Whether a `` `define`` of macro `macro_name` in `file`, whose body
/// spells the name (`params`: its formal arguments), is news.
///
/// The unscoped fallback and a dotted spelling are news first; only then
/// may a parameter named like the declaration silence the body's bare
/// spellings (they are the parameter) — never a bare spelling in a
/// default argument (`default_bare`), which expands in the caller.
pub(super) fn keeps_define_body(
&self,
file: usize,
macro_name: &str,
params: &[String],
dotted: bool,
default_bare: bool,
) -> bool {
if !self.scoped || dotted {
return true;
}
let shadowed =
params.iter().any(|p| p.split('=').next().is_some_and(|p| p.trim() == self.name));
if shadowed && !default_bare {
return false;
}
self.home.all.contains(&file)
|| self.invoked.contains(macro_name)
|| self.carriers.binds(macro_name)
}
/// Whether argument `position` of an invocation of `macro_name` may
/// reach the declaration wherever it is written (`carry.rs`).
pub(super) fn carries(&self, macro_name: &str, position: usize) -> bool {
!self.scoped || self.carriers.carries(macro_name, position)
}
/// Whether a spelling in `file` — dotted or bare, at `offset` — is news.
pub(super) fn keeps(&self, scope: &Scope, file: usize, dotted: bool, offset: u32) -> bool {
!self.scoped || dotted || self.bare_is_news(scope, file, offset)
}
/// A bare spelling: in a pasted file always (no scope to look in); in the
/// declaring file and an edited file when the lookup there finds the
/// declaration — only the declaring file's own analysis can; elsewhere
/// never.
fn bare_is_news(&self, scope: &Scope, file: usize, offset: u32) -> bool {
if self.home.included.contains(&file) || self.home.around.contains(&file) {
return true;
}
if file != self.declaring {
return false;
}
let Some(analysis) = scope.cached(file) else { return true };
nearest(&analysis.semantics, offset, &self.name) == Some(self.symbol)
}
}
/// K2: every file holding a `bind` into `unit` (by name or by an instance
/// path), or invoking a macro that expands to one — home, so the macros it
/// invokes are followed.
fn files_binding_into(scope: &Scope, unit: &str, carriers: &Carriers) -> Vec<usize> {
(0..scope.len())
.filter(|&i| {
let Some(text) = scope.text(i) else { return false };
let invokes_binder = carriers.any_binder()
&& text.contains('`')
&& macro_names(text).iter().any(|m| carriers.binds(m));
if invokes_binder {
return true;
}
if !super::contains_word(text, "bind") {
return false;
}
vlog_parser::tokenize(text).is_ok_and(|tokens| !binds_into(&tokens, unit).is_empty())
})
.collect()
}
impl<'a> Scope<'a> {
/// H4: bare uses of the name in the plain code of a file the declaring
/// file includes (or that includes it). That text is analysed on its own,
/// outside the module's scope, so no reference there is the declaration's
/// and the rename cannot edit it: one warning per file, with its lines.
/// A use the rename does edit (`edits`: a cross-file reference the index
/// resolved, such as an instantiation of a renamed module) is not one.
pub(super) fn fragment_use_warnings(
&mut self,
scoping: &Scoping,
edits: &[(usize, Vec<TextEdit>)],
) -> Vec<String> {
let name = scoping.name.clone();
let declaring = self.name_at(scoping.declaring());
let mut out = Vec::new();
for (file, included) in scoping.pasted() {
let Some(text) = self.text(file) else { continue };
if !super::contains_word(text, &name) {
continue;
}
let Ok(tokens) = vlog_parser::tokenize(text) else { continue };
let Some(analysis) = self.analysis(file) else { continue };
let edited: Vec<TextRange> = edits
.iter()
.filter(|(i, _)| *i == file)
.flat_map(|(_, e)| e.iter().map(|e| e.range))
.collect();
let lines = bare_unbound_uses(&analysis.semantics, &tokens, &name, &edited);
if lines.is_empty() {
continue;
}
let at = lines.iter().map(u32::to_string).collect::<Vec<_>>().join(",");
let relation = match included {
true => format!("a file `{declaring}` includes"),
false => format!("a file that includes `{declaring}` or is included with it"),
};
out.push(format!(
"{}:{at}: `{name}` is used in {relation} and was left unchanged; lucisv does not rename inside `included text.",
self.name_of(self.path(file).unwrap_or(std::path::Path::new("?")))
));
}
out
}
}
/// The lines of `name` tokens in one fragment's plain code that are a use no
/// declaration of that fragment answers: not a declaration, not after a `.`,
/// not a reference resolved inside the fragment itself, and not covered by
/// one of the rename's `edited` ranges in it.
fn bare_unbound_uses(
sem: &Semantics,
tokens: &[Token],
name: &str,
edited: &[TextRange],
) -> Vec<u32> {
let mut lines: Vec<u32> = Vec::new();
for (i, token) in tokens.iter().enumerate() {
if token.kind != TokenKind::Ident || token.text != name {
continue;
}
if i.checked_sub(1).and_then(|p| tokens.get(p)).is_some_and(|t| t.is_sym(".")) {
continue;
}
if sem.symbol_at(token.span.start).is_some() {
continue;
}
if edited.iter().any(|e| e.start <= token.span.start && token.span.end <= e.end) {
continue;
}
let local = sem.reference_at(token.span.start).is_some_and(|r| r.resolved().is_some());
if !local && lines.last() != Some(&token.line) {
lines.push(token.line);
}
}
lines
}
/// H3: the byte ranges of the `bind` statements in one file whose target is
/// `unit` — by name, or by an instance path, which lucisv cannot follow to a
/// unit and so counts — from `bind` to its `;`.
pub(super) fn binds_into(tokens: &[Token], unit: &str) -> Vec<TextRange> {
let mut out = Vec::new();
for (i, token) in tokens.iter().enumerate() {
// `bind` lexes as an identifier (it is not a reserved word of every
// standard the lexer serves); a `bind` statement starts with it.
if !(token.kind == TokenKind::Ident && token.text == "bind") {
continue;
}
let Some(target) = tokens.get(i + 1) else { continue };
let path = tokens.get(i + 2).is_some_and(|t| t.is_sym(".") || t.is_sym("["));
if target.text != unit && !path {
continue;
}
let Some(end) = tokens[i..].iter().find(|t| t.is_sym(";")) else { continue };
out.push(TextRange::new(token.span.start, end.span.end));
}
out
}
/// Macro name → every `` `define`` of it in the set.
fn define_defs(scope: &Scope) -> Defs {
let mut out = Defs::new();
for i in 0..scope.len() {
let Some(defines) = scope.file_id(i).and_then(|id| scope.index().defines(id)) else {
continue;
};
for define in defines.entries() {
let params = define.params.clone().unwrap_or_default();
let def = MacroDef { params, body: define.body.clone() };
out.entry(define.name.clone()).or_default().push(def);
}
}
out
}
/// The module or interface a declaration written in `scope` is a member of:
/// the first owned scope outward that is an instantiable unit's (a block,
/// function or task in between does not end the walk). A package, a class or
/// the file scope ends it with `None`.
fn enclosing_unit(sem: &Semantics, scope: ScopeId) -> Option<String> {
let mut here = Some(scope);
while let Some(id) = here {
let current = sem.scope(id)?;
if let Some(owner) = current.owner.and_then(|o| sem.symbol(o)) {
if owner.kind.is_instantiable() {
return Some(owner.name.clone());
}
if matches!(
owner.kind,
vlog_semantic::SymbolKind::Package | vlog_semantic::SymbolKind::Class
) {
return None;
}
}
here = current.parent;
}
None
}
/// The whole-word spellings of `name` in `text`: the byte offsets of the bare
/// ones, and whether any is dotted (a `.` before it, past blanks).
pub(super) fn spellings(text: &str, name: &str) -> (Vec<usize>, bool) {
let bytes = text.as_bytes();
let word = |b: u8| b.is_ascii_alphanumeric() || b == b'_' || b == b'$';
let (mut bare, mut dotted) = (Vec::new(), false);
let mut from = 0;
while let Some(hit) = text.get(from..).and_then(|s| s.find(name)) {
let start = from + hit;
let end = start + name.len();
from = start + 1;
let glued = start.checked_sub(1).and_then(|p| bytes.get(p)).is_some_and(|&b| word(b))
|| bytes.get(end).is_some_and(|&b| word(b));
if glued {
continue;
}
match after_dot(&text[..start]) {
true => dotted = true,
false => bare.push(start),
}
}
(bare, dotted)
}
/// Whether `before` ends in a `.`, past blanks and `` `` `` pastes
/// (`` u_m.``sig `` pastes a path).
fn after_dot(before: &str) -> bool {
let mut rest = before.trim_end();
while let Some(shorter) = rest.strip_suffix("``") {
rest = shorter.trim_end();
}
rest.ends_with('.')
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_spelling_is_dotted_past_blanks_and_bare_otherwise() {
assert_eq!(spellings("x(state_q, a.state_q)", "state_q"), (vec![2], true));
assert_eq!(spellings("x(u . state_q)", "state_q"), (vec![], true));
assert_eq!(spellings("x(state_qq, my_state_q)", "state_q"), (vec![], false));
assert_eq!(spellings("u_m.``state_q", "state_q"), (vec![], true));
assert_eq!(spellings("pre``state_q", "state_q"), (vec![5], false));
}
}
+133 -19
View File
@@ -16,7 +16,6 @@
//! out in the order they always did.
use std::collections::HashMap;
use std::path::Path;
use vlog_parser::defines::DefineKind;
use vlog_parser::span::TextRange;
@@ -26,8 +25,10 @@ use vlog_semantic::{ExternalTarget, ReferenceId, Resolution};
use crate::TextEdit;
use super::carry::argument_position;
use super::scoped::{binds_into, spellings, Scoping};
use super::Target;
use crate::scope::{display, Scope};
use crate::scope::Scope;
use crate::trace::WarnTrace;
/// One file's token stream and its line index, built at most once per
@@ -93,6 +94,7 @@ impl<'a> Scope<'a> {
trace: &mut WarnTrace,
) -> Vec<String> {
let name = &target.name;
let scoping = Scoping::new(self, target, edits.iter().map(|(i, _)| *i).collect());
let (mut defines, mut macro_uses) = (Vec::new(), Vec::new());
let (mut fallbacks, mut unfinished) = (Vec::new(), Vec::new());
// The edited files' scans outlive the loop: the unaccounted scan runs
@@ -100,10 +102,15 @@ impl<'a> Scope<'a> {
let mut kept: HashMap<usize, FileScan> = HashMap::new();
for i in 0..self.len() {
let mut scan = FileScan::default();
defines.extend(trace.defines.measure(|| self.define_warnings(i, name, &mut scan)));
macro_uses
.extend(trace.macro_uses.measure(|| self.macro_use_warnings(i, name, &mut scan)));
fallbacks.extend(trace.sva.measure(|| self.sva_fallback_warnings(i, name, &mut scan)));
defines.extend(
trace.defines.measure(|| self.define_warnings(i, name, &scoping, &mut scan)),
);
macro_uses.extend(
trace.macro_uses.measure(|| self.macro_use_warnings(i, name, &scoping, &mut scan)),
);
fallbacks.extend(
trace.sva.measure(|| self.sva_fallback_warnings(i, name, &scoping, &mut scan)),
);
unfinished.extend(
trace.unfinished.measure(|| self.unresolved_candidate_warnings(i, name, &mut scan)),
);
@@ -118,6 +125,8 @@ impl<'a> Scope<'a> {
warnings.extend(macro_uses);
warnings.extend(fallbacks);
warnings.extend(unfinished);
warnings.extend(trace.paths.measure(|| self.path_warnings(target, edits)));
warnings.extend(trace.paths.measure(|| self.fragment_use_warnings(&scoping, edits)));
for (i, edits) in edits {
let mut scan = kept.remove(i).unwrap_or_default();
warnings.extend(
@@ -143,19 +152,27 @@ impl<'a> Scope<'a> {
edits: &[(usize, Vec<TextEdit>)],
) -> Vec<String> {
let name = &target.name;
let scoping = Scoping::new(self, target, edits.iter().map(|(i, _)| *i).collect());
let mut warnings = Vec::new();
for i in 0..self.len() {
warnings.extend(self.define_warnings(i, name, &mut FileScan::default()));
warnings.extend(self.define_warnings(i, name, &scoping, &mut FileScan::default()));
}
for i in 0..self.len() {
warnings.extend(self.macro_use_warnings(i, name, &mut FileScan::default()));
warnings.extend(self.macro_use_warnings(i, name, &scoping, &mut FileScan::default()));
}
for i in 0..self.len() {
warnings.extend(self.sva_fallback_warnings(i, name, &mut FileScan::default()));
warnings.extend(self.sva_fallback_warnings(
i,
name,
&scoping,
&mut FileScan::default(),
));
}
for i in 0..self.len() {
warnings.extend(self.unresolved_candidate_warnings(i, name, &mut FileScan::default()));
}
warnings.extend(self.path_warnings(target, edits));
warnings.extend(self.fragment_use_warnings(&scoping, edits));
for (i, edits) in edits {
warnings.extend(self.unaccounted_warnings(*i, name, edits, &mut FileScan::default()));
}
@@ -163,13 +180,39 @@ impl<'a> Scope<'a> {
warnings
}
/// The two hierarchical-path scans (`paths.rs`): segments in any file
/// that resolved to nothing, and the renamed member's same-named twins in
/// the other arms of its generate label.
fn path_warnings(&mut self, target: &Target, edits: &[(usize, Vec<TextEdit>)]) -> Vec<String> {
let edited: Vec<usize> = edits.iter().map(|(i, _)| *i).collect();
let mut out = self.unresolved_path_warnings(&target.name, &edited);
out.extend(self.sibling_arm_warnings(target));
out
}
/// lucisv does not preprocess, so a name that is also a macro name, or that
/// appears in a macro body, is left exactly as written — and said so.
fn define_warnings(&self, file: usize, name: &str, scan: &mut FileScan) -> Vec<String> {
let where_ = display(self.path(file).unwrap_or(Path::new("?")));
fn define_warnings(
&self,
file: usize,
name: &str,
scoping: &Scoping,
scan: &mut FileScan,
) -> Vec<String> {
let where_ = self.name_at(file);
let mut out = Vec::new();
for site in self.define_sites_with(file, name, scan) {
let line = site.line;
let body_news = scoping.keeps_define_body(
file,
&site.macro_name,
&site.params,
site.body_dotted,
site.default_bare,
);
if site.defines_the_name.is_none() && !body_news {
continue;
}
match site.defines_the_name {
Some(DefineKind::Define) => out.push(format!(
"`{name}` is also a macro defined at {where_}:{line}; macro names and macro uses are never renamed."
@@ -190,10 +233,39 @@ impl<'a> Scope<'a> {
/// so the name inside `` `BUMP(a) `` is invisible to the semantic layer and
/// cannot be edited. It can be seen, though — and silence would be worse
/// than a warning, because the expansion still spells the old name.
fn macro_use_warnings(&self, file: usize, name: &str, scan: &mut FileScan) -> Vec<String> {
let where_ = display(self.path(file).unwrap_or(Path::new("?")));
self.macro_argument_sites_with(file, name, scan)
fn macro_use_warnings(
&self,
file: usize,
name: &str,
scoping: &Scoping,
scan: &mut FileScan,
) -> Vec<String> {
let where_ = self.name_at(file);
let sites = self.macro_argument_sites_with(file, name, scan);
// H3: an argument inside a `bind` into the declaring unit is
// evaluated in that unit's scope, wherever the directive is written.
let binds = match (scoping.unit(), sites.is_empty()) {
(Some(unit), false) => {
let tokens = self.text(file).and_then(|text| scan.tokens(text));
tokens.map_or_else(Vec::new, |tokens| binds_into(tokens, unit))
}
_ => Vec::new(),
};
let bound = |at: u32| binds.iter().any(|r| r.start <= at && at < r.end);
// A bare argument the macro carries after a `.`, into a `bind` or into
// a macro the set does not define may reach the declaration from here
// (`carry.rs`, review H-1/H-2).
let news = |site: &ArgumentSite, at: u32, position: usize| {
bound(at)
|| scoping.carries(&site.macro_name, position)
|| scoping.keeps(self, file, false, at)
};
sites
.into_iter()
.filter(|site| {
site.dotted
|| site.bare.iter().zip(&site.positions).any(|(&at, &k)| news(site, at, k))
})
.map(|site| {
format!(
"`{name}` appears in the arguments of the macro invocation `{}` at {where_}:{} and was left unchanged; a macro invocation is one opaque token to lucisv, which does not expand macros.",
@@ -220,6 +292,7 @@ impl<'a> Scope<'a> {
&mut self,
file: usize,
name: &str,
scoping: &Scoping,
scan: &mut FileScan,
) -> Vec<String> {
let (Some(text), Some(path)) = (self.text(file), self.path(file)) else {
@@ -238,7 +311,7 @@ impl<'a> Scope<'a> {
covered.extend(analysis.semantics.references().iter().map(|r| r.name_span));
let (Some(tokens), lines) = scan.tokens_and_lines(text) else { return Vec::new() };
let mut at: Vec<u32> = Vec::new();
for token in tokens {
for (n, token) in tokens.iter().enumerate() {
if token.kind != TokenKind::Ident || token.text != name {
continue;
}
@@ -248,6 +321,11 @@ impl<'a> Scope<'a> {
if !regions.iter().any(|r| r.start <= token.span.start && token.span.end <= r.end) {
continue;
}
let dotted =
n.checked_sub(1).and_then(|p| tokens.get(p)).is_some_and(|t| t.is_sym("."));
if !scoping.keeps(self, file, dotted, token.span.start) {
continue;
}
at.push(lines.line_col(token.span.start).0);
}
at.dedup();
@@ -257,7 +335,7 @@ impl<'a> Scope<'a> {
let at = at.iter().map(u32::to_string).collect::<Vec<_>>().join(", ");
vec![format!(
"`{name}` is spelled inside an assertion lucisv could not structure in {} at line(s) {at} and was left unchanged; that property expression did not fit the SVA grammar, so it is kept as source text.",
display(path)
self.name_of(path)
)]
}
@@ -289,12 +367,29 @@ impl<'a> Scope<'a> {
macro_name: define.name.clone(),
line,
defines_the_name: Some(define.kind),
body_dotted: false,
default_bare: false,
params: Vec::new(),
});
} else if contains_word(&define.body, name) {
continue;
}
// A default argument (`(x = state_q)`) expands in the caller
// exactly as the body does, so it is scanned with it.
let params = define.params.clone().unwrap_or_default();
let defaults: String = params
.iter()
.filter_map(|p| p.split_once('=').map(|(_, d)| d))
.collect::<Vec<_>>()
.join(" ");
let (default_bare, default_dotted) = spellings(&defaults, name);
if contains_word(&define.body, name) || contains_word(&defaults, name) {
out.push(DefineSite {
macro_name: define.name.clone(),
line,
defines_the_name: None,
body_dotted: spellings(&define.body, name).1 || default_dotted,
default_bare: !default_bare.is_empty(),
params,
});
}
}
@@ -338,9 +433,15 @@ impl<'a> Scope<'a> {
if !contains_word(arguments, name) {
continue;
}
let opened = (token.text.len() - arguments.len()) as u32;
let (bare, dotted) = spellings(arguments, name);
let at = |offset: usize| token.span.start + opened + offset as u32;
out.push(ArgumentSite {
macro_name: macro_name_of(&token.text).to_string(),
line: lines.line_col(token.span.start).0,
dotted,
positions: bare.iter().map(|&b| argument_position(arguments, b)).collect(),
bare: bare.into_iter().map(at).collect(),
});
}
out
@@ -388,7 +489,7 @@ impl<'a> Scope<'a> {
let at = at.iter().map(u32::to_string).collect::<Vec<_>>().join(", ");
format!(
"`{name}` also occurs in {} at line(s) {at} as {reason}; lucisv records no reference there, so it was left unchanged.",
display(path)
self.name_of(path)
)
})
.collect()
@@ -422,7 +523,7 @@ impl<'a> Scope<'a> {
if !text.contains(name) {
return Vec::new();
}
let where_ = display(path).to_string();
let where_ = self.name_of(path);
let lines = scan.lines(text);
let Some(analysis) = self.analysis(file) else { return Vec::new() };
// Unit that could not be found → the lines it was named on.
@@ -485,6 +586,13 @@ pub(crate) struct DefineSite {
/// `Some` when the name *is* this macro's name; `None` when it only
/// appears in the macro's body.
pub(crate) defines_the_name: Option<DefineKind>,
/// Whether the body or a default argument spells the name after a `.`
/// (`scoped::spellings`).
pub(crate) body_dotted: bool,
/// Whether a default argument spells the name bare.
pub(crate) default_bare: bool,
/// The macro's formal arguments as written (`"a"`, `"b = 8"`).
pub(crate) params: Vec<String>,
}
/// A macro invocation whose arguments spell a name, found by
@@ -493,6 +601,12 @@ pub(crate) struct ArgumentSite {
pub(crate) macro_name: String,
/// 1-based line the invocation starts on.
pub(crate) line: u32,
/// Whether an argument spells the name after a `.`.
pub(crate) dotted: bool,
/// The file offsets of the argument spellings with no `.` before them.
pub(crate) bare: Vec<u32>,
/// For each of `bare`, the 0-based position of the argument holding it.
pub(crate) positions: Vec<usize>,
}
/// Why an identifier spelling the name is not a reference lucisv can edit,
+58 -1
View File
@@ -25,6 +25,7 @@
//! [`KnownFacts`]; `docs/features/perf5r-scope-reuse/README.md` has the rest.
use std::collections::HashMap;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use vlog_parser::parse_source_tolerant;
@@ -170,6 +171,8 @@ pub(crate) struct Scope<'a> {
/// [`Analysis`] that does not depend on the finished index. Moved into
/// `cache` the first time that file's analysis is asked for.
kept: HashMap<usize, Semantics>,
/// How many sources share each file name, for [`Scope::name_of`].
base_names: BaseNames,
}
impl<'a> Scope<'a> {
@@ -262,7 +265,8 @@ impl<'a> Scope<'a> {
.map(|(i, path)| (path.as_path(), FileId(i as u32)))
.collect();
let file_ids = sources.iter().map(|(path, _)| ids.get(path).copied()).collect();
Scope { sources, index, file_ids, cache: HashMap::new(), kept }
let base_names = BaseNames::of(sources.iter().map(|(p, _)| *p));
Scope { sources, index, file_ids, cache: HashMap::new(), kept, base_names }
}
pub(crate) fn len(&self) -> usize {
@@ -333,6 +337,19 @@ impl<'a> Scope<'a> {
pub(crate) fn index(&self) -> &WorkspaceIndex {
&self.index
}
/// How a file of this set is named in a message: its file name when no
/// other file in the set shares it, else the path the caller gave — two
/// `pwrmgr_if.sv` in one answer must name two findable files (§65.1
/// re-check R1). A front end makes the path relative as it does any other.
pub(crate) fn name_of(&self, path: &Path) -> String {
self.base_names.name(path)
}
/// [`Scope::name_of`] for the file at source index `i`.
pub(crate) fn name_at(&self, i: usize) -> String {
self.path(i).map_or_else(|| "?".to_string(), |path| self.name_of(path))
}
}
/// How a file is named in a message: its file name, because an absolute path
@@ -341,6 +358,36 @@ pub(crate) fn display(path: &Path) -> String {
path.file_name().and_then(|n| n.to_str()).unwrap_or("?").to_string()
}
/// How many files of a set share each file name, counted once so that
/// naming every file of a large set is linear, not quadratic (review M-2).
pub(crate) struct BaseNames(HashMap<OsString, usize>);
impl BaseNames {
/// The counts for the files at `all`.
pub(crate) fn of<'p>(all: impl IntoIterator<Item = &'p Path>) -> BaseNames {
let mut counts: HashMap<OsString, usize> = HashMap::new();
for path in all {
if let Some(base) = path.file_name() {
*counts.entry(base.to_os_string()).or_default() += 1;
}
}
BaseNames(counts)
}
/// [`display`] made unambiguous within the counted set: the file name
/// when no other path shares it, else the path as given. The one rule
/// [`Scope::name_of`] and a buffer-level planner (the port offers) both
/// name files by, so an offer and the refactoring it offers say the same
/// thing.
pub(crate) fn name(&self, path: &Path) -> String {
let shared = path.file_name().and_then(|b| self.0.get(b)).is_some_and(|&n| n > 1);
match shared {
true => path.display().to_string(),
false => display(path),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -548,4 +595,14 @@ mod tests {
assert_eq!(scope.index().fingerprint(), built.fingerprint());
assert!(scope.analysis(0).is_some(), "and every file still analyses on demand");
}
#[test]
fn a_file_name_another_file_shares_is_named_by_its_path() {
let paths = [Path::new("/a/x/if.sv"), Path::new("/a/y/if.sv"), Path::new("/a/top.sv")];
let names = BaseNames::of(paths);
assert_eq!(names.name(Path::new("/a/x/if.sv")), "/a/x/if.sv");
assert_eq!(names.name(Path::new("/a/y/if.sv")), "/a/y/if.sv");
assert_eq!(names.name(Path::new("/a/top.sv")), "top.sv");
assert_eq!(names.name(Path::new("/elsewhere/new.sv")), "new.sv", "outside the set");
}
}
+4 -1
View File
@@ -123,6 +123,8 @@ pub struct WarnTrace {
pub sva: Stage,
/// The unresolved-candidate scan.
pub unfinished: Stage,
/// The hierarchical-path scans: unresolved segments and same-label arms.
pub paths: Stage,
/// The edited files' unaccounted-occurrence scan.
pub unaccounted: Stage,
/// Files whose text spelled the name, and which were therefore lexed.
@@ -134,11 +136,12 @@ impl WarnTrace {
fn line(&self) -> String {
format!(
"warnings{{defines={:.1}ms macro_uses={:.1} sva={:.1} unfinished={:.1} \
unaccounted={:.1} scanned={}}}",
paths={:.1} unaccounted={:.1} scanned={}}}",
self.defines.ms,
self.macro_uses.ms,
self.sva.ms,
self.unfinished.ms,
self.paths.ms,
self.unaccounted.ms,
self.scanned,
)
@@ -0,0 +1,757 @@
//! QA attacks on TODO §65.1 (rename and references through a block label).
//!
//! Every test drives the public `rename` / `find_references` over a small
//! in-memory workspace. The contract under attack: every site is rewritten,
//! or the rename is refused or warns — never a silent partial rename.
//! `docs/features/generate-label-rename/README.md`, QA log 2026-09-30.
use std::path::{Path, PathBuf};
use vlog_refactor::{find_references, rename, RefactorEdit};
fn workspace(files: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
files.iter().map(|(name, text)| (path(name), text.to_string())).collect()
}
fn path(name: &str) -> PathBuf {
PathBuf::from("/rtl").join(name)
}
/// The offset of the first whole-word `name` at or after `prefix`.
fn at(text: &str, prefix: &str, name: &str) -> u32 {
let from =
text.find(prefix).unwrap_or_else(|| panic!("`{prefix}` is not in the text")) + prefix.len();
let is_word = |b: Option<&u8>| {
b.is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_' || *b == b'$' || *b == b'\\')
};
let bytes = text.as_bytes();
let mut search = from;
while let Some(hit) = text.get(search..).and_then(|s| s.find(name)) {
let start = search + hit;
let end = start + name.len();
let before = start.checked_sub(1).and_then(|i| bytes.get(i));
if (name.starts_with('\\') || !is_word(before)) && !is_word(bytes.get(end)) {
return start as u32;
}
search = start + 1;
}
panic!("`{name}` does not occur after `{prefix}`");
}
fn apply(text: &str, edit: &RefactorEdit, file: &Path) -> String {
let mut out = String::new();
let mut cursor = 0usize;
for e in edit.edits_for(file) {
out.push_str(&text[cursor..e.range.start as usize]);
out.push_str(&e.new_text);
cursor = e.range.end as usize;
}
out.push_str(&text[cursor..]);
out
}
type Renamed = Result<(Vec<String>, Vec<String>), String>;
/// Rename the `name` after `prefix` in `file`; every file's text afterwards,
/// and the warnings.
fn renamed(files: &[(&str, &str)], file: &str, prefix: &str, name: &str, new: &str) -> Renamed {
let sources = workspace(files);
let text = files.iter().find(|(n, _)| *n == file).map(|(_, t)| *t).expect("the file");
let edit = rename(&sources, &path(file), at(text, prefix, name), new)?;
let texts = files.iter().map(|(n, t)| apply(t, &edit, &path(n))).collect();
Ok((texts, edit.warnings))
}
/// `file:line:text` of every reference to the `name` after `prefix`.
fn references(files: &[(&str, &str)], file: &str, prefix: &str, name: &str) -> Vec<String> {
let sources = workspace(files);
let text = files.iter().find(|(n, _)| *n == file).map(|(_, t)| *t).expect("the file");
let found = find_references(&sources, &path(file), at(text, prefix, name), true)
.unwrap_or_else(|why| panic!("find_references refused: {why}"));
let mut out: Vec<String> = found
.iter()
.map(|(p, span)| {
let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("?");
let text = files.iter().find(|(n, _)| *n == name).map(|(_, t)| *t).expect("file");
let line = text[..span.start as usize].matches('\n').count() + 1;
format!("{name}:{line}:{}", &text[span.as_range()])
})
.collect();
out.sort();
out
}
/// A rename either rewrote every spelling of `old` in code (not comments) in
/// every file — edited or not — or said something: never a silent partial.
/// Callers keep unrelated declarations of `old` out of the workspace.
fn complete_or_loud(result: &Renamed, old: &str) {
let Ok((texts, warnings)) = result else { return };
if !warnings.is_empty() {
return;
}
for text in texts {
let code: String =
text.lines().map(|l| l.split("//").next().unwrap_or("")).collect::<Vec<_>>().join("\n");
let is_word = |b: u8| b.is_ascii_alphanumeric() || b == b'_';
let left = code.match_indices(old).any(|(i, _)| {
let b = code.as_bytes();
!(i > 0 && is_word(b[i - 1])) && !b.get(i + old.len()).is_some_and(|&c| is_word(c))
});
assert!(!left, "silent partial rename, `{old}` left behind:\n{text}");
}
}
// ---------------------------------------------------------------------------
// B. Scope semantics seen through references and rename
// ---------------------------------------------------------------------------
/// Two sibling `for` loops carrying one label (illegal, seen in the wild):
/// no crash, and a rename of the label is all or nothing.
const SIBLINGS: &str = "module sib (output logic o);
for (genvar i = 0; i < 2; i++) begin : g
logic a;
end
for (genvar j = 0; j < 2; j++) begin : g
logic b;
end
assign o = g[0].a;
endmodule
";
#[test]
fn sibling_loops_with_one_label_rename_as_one_label_without_a_crash() {
let result = renamed(&[("s.sv", SIBLINGS)], "s.sv", "begin : ", "g", "gg");
let (texts, _) = result.clone().expect("renames");
assert_eq!(texts[0], SIBLINGS.replace(": g\n", ": gg\n").replace("g[0]", "gg[0]"));
complete_or_loud(&result, "g");
let found = references(&[("s.sv", SIBLINGS)], "s.sv", "o = ", "g");
assert_eq!(found, vec!["s.sv:2:g", "s.sv:5:g", "s.sv:8:g"]);
}
/// A label that shadows an outer net of the same name: inside the outer
/// block the path's head is the inner block, outside it is the net.
const SHADOW: &str = "module sh (output logic o, output logic p);
logic g_a;
assign g_a = 1'b0;
if (1) begin : outer
if (1) begin : g_a
logic q;
end
assign o = g_a.q;
end
assign p = g_a;
endmodule
";
#[test]
fn a_label_shadowing_an_outer_net_takes_only_its_own_path() {
let (texts, warnings) =
renamed(&[("sh.sv", SHADOW)], "sh.sv", "begin : ", "g_a", "g_b").expect("renames");
assert!(warnings.is_empty(), "{warnings:?}");
assert_eq!(
texts[0],
SHADOW.replace("begin : g_a", "begin : g_b").replace("o = g_a.q", "o = g_b.q")
);
let (texts, _) =
renamed(&[("sh.sv", SHADOW)], "sh.sv", "logic ", "g_a", "n_a").expect("the net renames");
assert_eq!(
texts[0],
SHADOW
.replace("logic g_a;", "logic n_a;")
.replace("assign g_a", "assign n_a")
.replace("p = g_a;", "p = n_a;")
);
}
/// A declaration inside an **unnamed** generate `if` stays invisible outside
/// it; one inside `generate … endgenerate` is a name of the module.
#[test]
fn an_unnamed_generate_if_still_hides_its_declarations() {
let text = "module u (output logic o, output logic p);
generate
wire in_region;
if (1) begin
wire hidden;
end
endgenerate
assign o = in_region;
assign p = hidden;
endmodule
";
let found = references(&[("u.sv", text)], "u.sv", "wire ", "in_region");
assert_eq!(found, vec!["u.sv:3:in_region", "u.sv:8:in_region"]);
let found = references(&[("u.sv", text)], "u.sv", "wire ", "hidden");
assert_eq!(found, vec!["u.sv:5:hidden"], "the outer `hidden` is an implicit net, not this one");
}
/// Escaped labels: the label, its closing label and a path through it.
#[test]
fn an_escaped_label_is_renamed_with_its_path() {
let text = "module e (output logic o);
for (genvar i = 0; i < 2; i++) begin : \\g$lane
logic q;
end : \\g$lane
assign o = \\g$lane [0].q;
endmodule
";
let result = renamed(&[("e.sv", text)], "e.sv", "begin : ", "\\g$lane", "g_ln");
match &result {
Ok((texts, _)) => {
assert!(!texts[0].contains("\\g$lane"), "every escaped spelling moves:\n{}", texts[0]);
}
Err(why) => assert!(!why.is_empty()),
}
}
/// A label written in both arms of an `ifdef`: one name, all or nothing.
const IFDEF: &str = "module d (output logic o);
`ifdef WIDE
for (genvar i = 0; i < 4; i++) begin : g_w
logic q;
end : g_w
`else
for (genvar i = 0; i < 2; i++) begin : g_w
logic q;
end : g_w
`endif
assign o = g_w[0].q;
endmodule
";
#[test]
fn a_label_inside_an_ifdef_is_renamed_in_every_arm_or_the_rename_says_so() {
let result = renamed(&[("d.sv", IFDEF)], "d.sv", "o = ", "g_w", "g_v");
complete_or_loud(&result, "g_w");
if let Ok((texts, _)) = &result {
assert_eq!(texts[0], IFDEF.replace("g_w", "g_v"));
}
}
/// A label that is used only by its closing label.
#[test]
fn a_label_used_only_by_its_closing_label_moves_with_it() {
let text = "module c (input logic clk);
if (1) begin : g_only
logic q;
end : g_only
always_ff @(posedge clk) begin : p_only
end : p_only
endmodule
";
let (texts, _) = renamed(&[("c.sv", text)], "c.sv", "end : ", "g_only", "g_x").expect("g");
assert_eq!(texts[0], text.replace("g_only", "g_x"));
let (texts, _) = renamed(&[("c.sv", text)], "c.sv", "begin : ", "p_only", "p_x").expect("p");
assert_eq!(texts[0], text.replace("p_only", "p_x"));
}
/// Named blocks inside a function and a task, with `disable`.
#[test]
fn named_blocks_in_functions_and_tasks_rename_with_disable_and_closing_label() {
let text = "module f;
function automatic int ff(int a);
begin : fblk
if (a == 0) disable fblk;
ff = a;
end : fblk
endfunction
task automatic tt();
begin : tblk
disable tblk;
end : tblk
endtask
endmodule
";
let (texts, _) = renamed(&[("f.sv", text)], "f.sv", "disable ", "fblk", "f2").expect("f");
assert_eq!(texts[0], text.replace("fblk", "f2"));
let (texts, _) = renamed(&[("f.sv", text)], "f.sv", "end : ", "tblk", "t2").expect("t");
assert_eq!(texts[0], text.replace("tblk", "t2"));
}
/// Nested `g_a.g_b[2].x` from another file: every level renames.
const NSUB: &str = "module nsub;
if (1) begin : g_a
for (genvar j = 0; j < 4; j++) begin : g_b
logic x;
end : g_b
end : g_a
endmodule
";
const NTOP: &str = "module ntop (output logic o);
nsub u_n ();
assign o = u_n.g_a.g_b[2].x;
endmodule
";
#[test]
fn every_level_of_a_nested_cross_file_path_renames() {
let files = [("nsub.sv", NSUB), ("ntop.sv", NTOP)];
for (prefix, name, new) in
[("begin : ", "g_a", "g_top"), ("g_a\n for", "g_b", "g_bit"), ("logic ", "x", "xx")]
{
let (texts, warnings) = renamed(&files, "nsub.sv", prefix, name, new).expect(name);
assert!(warnings.is_empty(), "{name}: {warnings:?}");
let word = |t: &str| {
t.replace(&format!(": {name}\n"), &format!(": {new}\n"))
.replace(&format!(".{name}"), &format!(".{new}"))
.replace(&format!("logic {name};"), &format!("logic {new};"))
};
assert_eq!(texts[1], word(NTOP), "{name}");
assert!(!texts[0].contains(&format!(" {name}\n")), "{name}:\n{}", texts[0]);
// Started from the other file, the same edit.
let other = renamed(&files, "ntop.sv", "u_n.", name, new).expect(name);
assert_eq!(other.0, texts, "{name}");
}
}
/// A generate `case` with the same label in several arms, each with a
/// closing label.
#[test]
fn a_case_label_in_three_arms_renames_all_arms_and_the_path() {
let text = "module k #(parameter int P = 0) (output logic o);
case (P)
0: begin : g_c
logic z;
end : g_c
1: begin : g_c
logic z;
end : g_c
default: begin : g_c
logic z;
end : g_c
endcase
assign o = g_c.z;
endmodule
";
for start in ["0: begin : ", "1: begin : ", "default: begin : ", "o = "] {
let (texts, _) = renamed(&[("k.sv", text)], "k.sv", start, "g_c", "g_d").expect(start);
assert_eq!(texts[0], text.replace("g_c", "g_d"), "from `{start}`");
}
}
/// Legal SystemVerilog: both arms of a generate `if` are labelled `g`, and a
/// member exists only in the second one (IEEE 1800 §27.5 — only one arm is
/// elaborated, so `g.b` is valid whenever the `else` arm is).
const ARMS: &str = "module a #(parameter bit P = 0) (output logic o, output logic p);
if (P) begin : g
logic a;
end else begin : g
logic b;
end
assign o = g.a;
assign p = g.b;
endmodule
";
#[test]
fn a_member_only_the_second_arm_declares_is_never_silently_left_behind() {
let result = renamed(&[("a.sv", ARMS)], "a.sv", "logic ", "b", "b2");
complete_or_loud(&result, "b");
}
#[test]
fn a_member_both_arms_declare_is_never_silently_split() {
// `g.x` means the first arm's `x` or the second's depending on `P`:
// renaming one arm's `x` and the path leaves the other arm without it.
let text = "module b2 #(parameter bit P = 0) (output logic o);
if (P) begin : g
logic x;
end else begin : g
logic x;
end
assign o = g.x;
endmodule
";
let result = renamed(&[("b.sv", text)], "b.sv", "logic ", "x", "y");
complete_or_loud(&result, "x");
// Lead's ruling on F2: a warning naming the other arm's declaration; no
// refusal and no extra rewrite.
let (texts, warnings) = result.expect("renames");
assert_eq!(texts[0], text.replacen("logic x;", "logic y;", 1).replace("g.x", "g.y"));
assert!(
warnings.iter().any(|w| w.contains("b.sv:5") && w.contains("another arm labelled `g`")),
"{warnings:?}"
);
}
// ---------------------------------------------------------------------------
// Element selects on things that are not generate arrays
// ---------------------------------------------------------------------------
const PKG: &str = "package pk;
typedef struct packed { logic f; logic g; } pkt_t;
typedef pkt_t arr_t [2];
endpackage
";
#[test]
fn an_element_select_resolves_only_where_the_element_type_is_the_recorded_type() {
let text = "module s import pk::*; (output logic o, output logic p, output logic q);
pkt_t [1:0] packed_arr;
pkt_t unpacked_arr [2];
logic [3:0] vec;
assign o = packed_arr[0].f;
assign p = unpacked_arr[1].f;
assign q = vec[0].f;
endmodule
";
let files = [("pk.sv", PKG), ("s.sv", text)];
let found = references(&files, "pk.sv", "packed { logic ", "f");
// The packed array's element is a `pkt_t`: a reference. The others must
// never resolve to the struct's `f` through a type they do not have.
assert!(found.contains(&"s.sv:5:f".to_string()), "{found:?}");
assert!(
!found.contains(&"s.sv:7:f".to_string()),
"`vec[0].f` is not a struct field: {found:?}"
);
// Renaming the field is complete or loud about the unpacked array.
let result = renamed(&files, "pk.sv", "packed { logic ", "f", "ff");
complete_or_loud(&result, "f");
}
#[test]
fn an_instance_array_and_an_interface_array_path_is_not_a_wrong_answer() {
let leaf = "module leaf (output logic sig);
assign sig = 1'b0;
endmodule
interface bus_if;
logic sig;
endinterface
";
let top = "module top (output logic o, output logic p);
leaf u_arr [2] (.sig());
bus_if b_arr [2] ();
assign o = u_arr[1].sig;
assign p = b_arr[0].sig;
endmodule
";
let files = [("leaf.sv", leaf), ("top.sv", top)];
let found = references(&files, "leaf.sv", "interface bus_if;\n logic ", "sig");
for f in &found {
assert!(!f.starts_with("top.sv:4"), "`u_arr[1].sig` is leaf's port, not bus_if's: {f}");
}
let found = references(&files, "leaf.sv", "output logic ", "sig");
for f in &found {
assert!(!f.starts_with("top.sv:5"), "`b_arr[0].sig` is bus_if's, not leaf's: {f}");
}
}
// ---------------------------------------------------------------------------
// C. Rename attacks
// ---------------------------------------------------------------------------
#[test]
fn renaming_a_label_to_a_name_the_enclosing_scope_declares_is_refused() {
let text = "module r (output logic o);
logic taken;
if (1) begin : g_x
logic q;
end
for (genvar i = 0; i < 2; i++) begin : g_y
logic q;
end
assign o = taken;
endmodule
";
for (prefix, label) in [("begin : ", "g_x"), ("begin : g_x", "g_y")] {
let why = renamed(&[("r.sv", text)], "r.sv", prefix, label, "taken");
assert!(why.is_err(), "`{label}` → `taken` collides in the module: {why:?}");
// and to a sibling block's label
let other = if label == "g_x" { "g_y" } else { "g_x" };
let why = renamed(&[("r.sv", text)], "r.sv", prefix, label, other);
assert!(why.is_err(), "`{label}` → `{other}` collides with the other block: {why:?}");
}
// A net renamed to a block's label collides too.
let why = renamed(&[("r.sv", text)], "r.sv", "logic ", "taken", "g_x");
assert!(why.is_err(), "`taken` → `g_x` collides with the block label: {why:?}");
}
#[test]
fn a_label_renamed_there_and_back_restores_every_byte() {
let files = [("nsub.sv", NSUB), ("ntop.sv", NTOP)];
let (once, _) = renamed(&files, "nsub.sv", "g_a\n for", "g_b", "g_q").expect("there");
let back_files = [("nsub.sv", once[0].as_str()), ("ntop.sv", once[1].as_str())];
let (twice, _) = renamed(&back_files, "ntop.sv", "u_n.g_a.", "g_q", "g_b").expect("back");
assert_eq!(twice, vec![NSUB.to_string(), NTOP.to_string()]);
}
#[test]
fn a_net_inside_a_block_renamed_through_a_bind_and_a_path_from_two_files() {
let sub = "module sub (input logic clk);
for (genvar i = 0; i < 2; i++) begin : g_lane
logic sig;
assign sig = clk;
end
endmodule
";
let top = "module top (input logic clk, output logic o);
sub u_x (.clk);
assign o = u_x.g_lane[1].sig;
endmodule
";
let tb = "module tb;
logic clk, o;
top dut (.clk, .o);
initial $display(\"%b\", dut.u_x.g_lane[0].sig);
endmodule
";
let files = [("sub.sv", sub), ("top.sv", top), ("tb.sv", tb)];
let (texts, warnings) = renamed(&files, "tb.sv", "g_lane[0].", "sig", "sig_q").expect("ok");
assert!(warnings.is_empty(), "{warnings:?}");
assert_eq!(
texts[0],
sub.replace("logic sig;", "logic sig_q;").replace("assign sig ", "assign sig_q ")
);
assert_eq!(texts[1], top.replace(".sig", ".sig_q"));
assert_eq!(texts[2], tb.replace(".sig)", ".sig_q)"));
}
/// The opentitan DV shape (`keymgr_dpe_if.sv:514`, `force
/// tb.dut.gen_sw_assigns[i].hw_key_sel_buf[0] = …`): a path rooted at a
/// top-level module declared in another file. lucisv records nothing for it
/// (0.59.0 neither, for a net), and the file is not edited, so the stray
/// scan never looks at it either — the rename is silently partial.
#[test]
fn a_path_rooted_at_another_files_top_module_is_never_silently_left_behind() {
let dut = "module dut_a;
for (genvar i = 0; i < 2; i++) begin : g_sw
logic buf_q;
end
endmodule
";
let tb = "module tb;
dut_a dut ();
endmodule
";
let probe = "module probe (output logic o);
assign o = tb.dut.g_sw[0].buf_q;
endmodule
";
let files = [("dut_a.sv", dut), ("tb.sv", tb), ("probe.sv", probe)];
complete_or_loud(&renamed(&files, "dut_a.sv", "begin : ", "g_sw", "g_hw"), "g_sw");
complete_or_loud(&renamed(&files, "dut_a.sv", "logic ", "buf_q", "buf_r"), "buf_q");
// Lead's ruling on F1: the path rooted at another file's top module does
// not resolve, so it is left unchanged — and said so, with its line.
for (prefix, old, new) in [("begin : ", "g_sw", "g_hw"), ("logic ", "buf_q", "buf_r")] {
let (texts, warnings) = renamed(&files, "dut_a.sv", prefix, old, new).expect("renames");
assert_eq!(texts[0], dut.replace(old, new), "the declaration moves");
assert_eq!((texts[1].as_str(), texts[2].as_str()), (tb, probe), "nothing else is edited");
let said: Vec<&String> = warnings.iter().filter(|w| w.contains("probe.sv:2:")).collect();
assert_eq!(said.len(), 1, "one warning for the unresolved path: {warnings:?}");
assert!(said[0].contains(&format!("`{old}`")), "{said:?}");
}
}
#[test]
fn a_same_named_block_in_another_module_is_never_touched() {
let sub = "module sub (input logic clk);
for (genvar i = 0; i < 2; i++) begin : g_lane
logic sig;
end : g_lane
endmodule
";
let other = sub.replace("module sub", "module other");
let top = "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
";
let files = [("sub.sv", sub), ("other.sv", other.as_str()), ("top.sv", top)];
let (texts, warnings) = renamed(&files, "top.sv", "u_x.", "g_lane", "g_ln").expect("renames");
assert!(warnings.is_empty(), "{warnings:?}");
assert_eq!(texts[0], sub.replace("g_lane", "g_ln"));
assert_eq!(texts[1], other, "`other`'s block is another declaration");
assert_eq!(texts[2], top.replace("u_x.g_lane", "u_x.g_ln"));
}
#[test]
fn renaming_a_label_to_its_loops_genvar_is_refused_when_a_path_inside_would_be_captured() {
let text = "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
";
let why = renamed(&[("i.sv", text)], "i.sv", "begin : ", "g_lane", "gi");
assert!(why.is_err(), "`gi[0].sig` inside the body would name the genvar: {why:?}");
}
// ---------------------------------------------------------------------------
// Re-check 2026-09-30: the rework's unresolved-path and sibling-arm warnings
// ---------------------------------------------------------------------------
const RC_DUT: &str = "module dut_a;
for (genvar i = 0; i < 2; i++) begin : g_sw
logic buf_q;
end
endmodule
";
const RC_OTHER: &str = "module dut_b;
for (genvar i = 0; i < 2; i++) begin : g_sw
logic buf_q;
end
endmodule
";
const RC_TB: &str = "module tb;
dut_a dut ();
dut_b other ();
endmodule
";
/// Every shape a path through `g_sw` rooted at another file's `tb` takes.
const RC_PROBE: &str = "module probe (output logic o);
initial force tb.dut.g_sw[0].buf_q = 1'b0;
initial release tb.dut.g_sw[0].buf_q;
initial $assertoff(0, tb.dut.g_sw[1]);
assign o = tb.dut
.g_sw[1]
.buf_q;
// tb.dut.g_sw[0].buf_q in a comment
initial $display(\"tb.dut.g_sw[0]\");
unknown_mod u_unk (.g_sw(1'b0));
endmodule
";
fn rc_files() -> Vec<(&'static str, &'static str)> {
vec![("dut_a.sv", RC_DUT), ("dut_b.sv", RC_OTHER), ("tb.sv", RC_TB), ("probe.sv", RC_PROBE)]
}
#[test]
fn recheck_every_unresolved_path_shape_is_named_once_with_its_lines() {
let (texts, warnings) =
renamed(&rc_files(), "dut_a.sv", "begin : ", "g_sw", "g_hw").expect("renames");
assert_eq!(texts[3], RC_PROBE, "the probe is never edited");
let said: Vec<&String> = warnings.iter().filter(|w| w.contains("probe.sv")).collect();
assert_eq!(said.len(), 1, "one line for the file: {warnings:?}");
assert!(said[0].starts_with("probe.sv:2,3,4,6:"), "{said:?}");
}
#[test]
fn recheck_a_path_that_resolves_to_another_declaration_is_not_warned_about() {
let user = "module user (output logic o);
dut_b u_b ();
assign o = u_b.g_sw[0].buf_q;
endmodule
";
let mut files = rc_files();
files.push(("user.sv", user));
let (_, warnings) = renamed(&files, "dut_a.sv", "begin : ", "g_sw", "g_hw").expect("renames");
assert!(!warnings.iter().any(|w| w.contains("user.sv")), "{warnings:?}");
}
#[test]
fn recheck_an_included_fragment_is_scanned_like_any_file() {
let frag = " initial force tb.dut.g_sw[0].buf_q = 1'b1;\n";
let host = "module host;\n`include \"frag.svh\"\nendmodule\n";
let mut files = rc_files();
files.push(("frag.svh", frag));
files.push(("host.sv", host));
let (_, warnings) = renamed(&files, "dut_a.sv", "begin : ", "g_sw", "g_hw").expect("renames");
assert!(warnings.iter().any(|w| w.starts_with("frag.svh:1:")), "{warnings:?}");
}
/// The word census holds no escaped identifier (`words.rs`: "an escaped
/// identifier is not a word"), so `paths.rs`'s census filter drops the file.
#[test]
fn recheck_an_escaped_label_behind_an_unresolved_root_is_named() {
let dut = "module dut_e;\n if (1) begin : \\g$sw \n logic q;\n end\nendmodule\n";
let tb = "module tbe;\n dut_e dut ();\nendmodule\n";
let probe = "module pe (output logic o);\n assign o = tbe.dut.\\g$sw .q;\nendmodule\n";
let files = [("dut_e.sv", dut), ("tbe.sv", tb), ("pe.sv", probe)];
let result = renamed(&files, "dut_e.sv", "begin : ", "\\g$sw", "g_hw");
complete_or_loud(&result, "\\g$sw");
let (_, warnings) = result.expect("renames");
assert!(warnings.iter().any(|w| w.starts_with("pe.sv:2:")), "{warnings:?}");
}
#[test]
fn recheck_sibling_arm_warnings_in_every_arm_shape() {
let three = "module t3 #(parameter int P = 0) (output logic o);
if (P == 0) begin : g
logic x;
end else if (P == 1) begin : g
logic x;
end else begin : g
logic x;
end
assign o = g.x;
endmodule
";
let case = "module tc #(parameter int P = 0) (output logic o);
case (P)
0: begin : g
logic x;
end
1: begin : g
logic x;
end
default: begin : g
logic x;
end
endcase
assign o = g.x;
endmodule
";
let ifdef = "module td (output logic o);
`ifdef A
if (1) begin : g
logic x;
end
`else
if (1) begin : g
logic x;
end
`endif
assign o = g.x;
endmodule
";
for (name, text, prefix, others) in [
("t3.sv", three, "P == 0) begin : g\n logic ", vec![5, 7]),
("t3.sv", three, "P == 1) begin : g\n logic ", vec![3, 7]),
("tc.sv", case, "0: begin : g\n logic ", vec![7, 10]),
("tc.sv", case, "default: begin : g\n logic ", vec![4, 7]),
("td.sv", ifdef, "`ifdef A\n if (1) begin : g\n logic ", vec![8]),
] {
let (_, warnings) = renamed(&[(name, text)], name, prefix, "x", "y").expect(name);
for line in others {
let at = format!("{name}:{line},");
assert!(
warnings.iter().any(|w| w.contains(&at) && w.contains("another arm")),
"{name} {prefix:?}: no warning for line {line}: {warnings:?}"
);
}
}
}
/// Nested arms: `g.h.x` reaches the `h` inside *either* arm of `g`. The
/// sibling scan looks only at the arms of the innermost label, so renaming
/// the `x` under `g`'s `else` arm leaves `g.h.x` (which resolves to the first
/// arm's) and says nothing — and renaming the first one warns about its
/// `h`-sibling at line 6 but not about line 10.
#[test]
fn recheck_sibling_arms_of_an_enclosing_label_are_warned_about() {
let nested = "module tn #(parameter bit P = 0, parameter bit Q = 0) (output logic o);
if (P) begin : g
if (Q) begin : h
logic x;
end else begin : h
logic x;
end
end else begin : g
if (1) begin : h
logic x;
end
end
assign o = g.h.x;
endmodule
";
let result = renamed(&[("tn.sv", nested)], "tn.sv", "if (1) begin : h\n logic ", "x", "y");
complete_or_loud(&result, "x");
let (_, warnings) =
renamed(&[("tn.sv", nested)], "tn.sv", "if (Q) begin : h\n logic ", "x", "y")
.expect("renames");
assert!(warnings.iter().any(|w| w.contains("tn.sv:10,")), "{warnings:?}");
}
@@ -0,0 +1,521 @@
//! QA attacks on TODO §65.1 rework 3 (`rename/scoped.rs`): a module member's
//! bare spelling in another file's macro argument, `` `define`` body or
//! unstructured assertion is no longer warned about. The danger is a HIDDEN
//! real use — text that expands into the declaring module's scope from
//! another file. `docs/features/generate-label-rename/README.md`, QA log.
use std::path::PathBuf;
use vlog_refactor::rename;
fn workspace(files: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
files.iter().map(|(name, text)| (PathBuf::from("/rtl").join(name), text.to_string())).collect()
}
/// Rename the first `logic <name>` (or `<prefix>` then `name`) in `file`;
/// the rewritten texts and the warnings, or the refusal.
fn run(
files: &[(&str, &str)],
file: &str,
prefix: &str,
name: &str,
new: &str,
) -> Result<(Vec<String>, Vec<String>), String> {
let sources = workspace(files);
let text = files.iter().find(|(n, _)| *n == file).map(|(_, t)| *t).expect("file");
let at = (text.find(prefix).expect("prefix") + prefix.len()) as u32;
let at = at + text[at as usize..].find(name).expect("name") as u32;
let edit = rename(&sources, &PathBuf::from("/rtl").join(file), at, new)?;
let texts = files
.iter()
.map(|(n, t)| {
let mut out = String::new();
let mut cursor = 0usize;
for e in edit.edits_for(&PathBuf::from("/rtl").join(n)) {
out.push_str(&t[cursor..e.range.start as usize]);
out.push_str(&e.new_text);
cursor = e.range.end as usize;
}
out.push_str(&t[cursor..]);
out
})
.collect();
Ok((texts, edit.warnings))
}
/// Whether some warning mentions `file` at `line` (`file:line` or `file at
/// line(s) … line`).
fn said(warnings: &[String], file: &str, line: u32) -> bool {
warnings.iter().any(|w| {
w.contains(&format!("{file}:{line}"))
|| (w.contains(file) && w.contains(&format!(" {line}")))
})
}
const ASSERT_DEFS: &str = "`define ASSERT(n, e) n: assert property (@(posedge clk) e);\n";
/// The opentitan `*_assert.svh` shape: the module includes a fragment whose
/// assertions name the module's own signals bare.
#[test]
fn a_bare_use_in_an_included_fragments_macro_argument_is_said() {
let module = "module m (input logic clk);
logic state_q;
always_ff @(posedge clk) state_q <= ~state_q;
`include \"m_assert.svh\"
endmodule
";
let frag = " `ASSERT(StateKnown_A, !$isunknown(state_q))\n";
let files = [("defs.svh", ASSERT_DEFS), ("m.sv", module), ("m_assert.svh", frag)];
let (_, warnings) = run(&files, "m.sv", "logic ", "state_q", "state_r").expect("renames");
assert!(said(&warnings, "m_assert.svh", 1), "HIDDEN USE: {warnings:#?}");
}
/// The same fragment with the use in plain code, not a macro.
#[test]
fn a_bare_use_in_plain_included_code_is_renamed_or_said() {
let module = "module m (input logic clk, output logic o);
logic state_q;
`include \"m_body.svh\"
endmodule
";
let frag = " assign o = state_q;\n";
let files = [("m.sv", module), ("m_body.svh", frag)];
let (texts, warnings) = run(&files, "m.sv", "logic ", "state_q", "state_r").expect("renames");
// Lead's ruling on H4: said, not renamed (renaming inside included
// fragments is TODO §65.6).
assert_eq!(texts[1], frag, "the fragment is not edited");
assert!(said(&warnings, "m_body.svh", 1), "{warnings:#?}");
}
/// A header's `` `define`` whose body spells the net bare, invoked in the
/// declaring module: the expansion is a real use.
#[test]
fn a_bare_use_in_a_header_macro_body_invoked_in_the_module_is_said() {
let defs = "`define CHK assert property (@(posedge clk) state_q != 0);\n";
let module = "module m (input logic clk);
logic state_q;
always_ff @(posedge clk) state_q <= ~state_q;
`CHK
endmodule
";
let files = [("chk.svh", defs), ("m.sv", module)];
let (_, warnings) = run(&files, "m.sv", "logic ", "state_q", "state_r").expect("renames");
assert!(said(&warnings, "chk.svh", 1), "HIDDEN USE: {warnings:#?}");
}
/// A bind file's connection names the target's net bare inside a macro
/// argument — evaluated in the bound scope.
#[test]
fn a_bare_use_in_a_bind_connection_macro_argument_is_said() {
let defs = "`define Q(x) x\n";
let module = "module m (input logic clk);
logic state_q;
always_ff @(posedge clk) state_q <= ~state_q;
endmodule
";
let chk = "module chk (input logic s);
endmodule
";
let bind = "module m_bind;
bind m chk u_chk (.s(`Q(state_q)));
endmodule
";
let files = [("defs.svh", defs), ("m.sv", module), ("chk.sv", chk), ("m_bind.sv", bind)];
let (texts, warnings) = run(&files, "m.sv", "logic ", "state_q", "state_r").expect("renames");
assert!(texts[3].contains("state_r") || said(&warnings, "m_bind.sv", 2), "{warnings:#?}");
}
/// Same file, several scopes: a function, a generate block and a nested
/// module see the net; an inner declaration of the same name shadows it.
#[test]
fn inside_the_declaring_file_the_lookup_respects_scopes_and_shadowing() {
let module = "module m (input logic clk);
logic state_q;
function automatic logic f();
return `Q(state_q);
endfunction
if (1) begin : g
assign x = `Q(state_q);
end
if (1) begin : h
logic state_q;
assign y = `Q(state_q);
end
endmodule
module other;
logic state_q;
assign z = `Q(state_q);
endmodule
";
let files = [("defs.svh", "`define Q(x) x\n"), ("m.sv", module)];
let (_, warnings) = run(&files, "m.sv", "logic ", "state_q", "state_r").expect("renames");
assert!(said(&warnings, "m.sv", 4), "the function's use: {warnings:#?}");
assert!(said(&warnings, "m.sv", 7), "the generate block's use: {warnings:#?}");
assert!(!said(&warnings, "m.sv", 11), "shadowed by h's own state_q: {warnings:#?}");
assert!(!said(&warnings, "m.sv", 16), "the other module's own: {warnings:#?}");
}
/// Unstructured assertion text and `ifdef`-disabled text in the declaring
/// file.
#[test]
fn unparsed_assertion_and_ifdef_text_in_the_declaring_file_is_said() {
let module = "module m (input logic clk);
logic state_q;
always_ff @(posedge clk) state_q <= ~state_q;
a_weird: assert property (@(posedge clk) state_q |-> ##[1:$] $$$ state_q);
`ifdef NEVER
`Q(state_q)
`endif
endmodule
";
let files = [("defs.svh", "`define Q(x) x\n"), ("m.sv", module)];
let (texts, warnings) = run(&files, "m.sv", "logic ", "state_q", "state_r").expect("renames");
assert!(texts[1].contains("$$$ state_r") || said(&warnings, "m.sv", 4), "{warnings:#?}");
assert!(said(&warnings, "m.sv", 6), "the ifdef'd macro argument: {warnings:#?}");
}
/// Rework 2, R1: three files named `probe.sv` at different depths, each with
/// an unresolved path — each warning must name a findable file.
#[test]
fn recheck_three_same_named_files_are_each_named_by_their_path() {
let dut = "module dut_a;\n for (genvar i = 0; i < 2; i++) begin : g_sw\n logic q;\n end\nendmodule\n";
let tb = "module tb;\n dut_a dut ();\nendmodule\n";
let probe = "module PROBE (output logic o);\n assign o = tb.dut.g_sw[0].q;\nendmodule\n";
let (p1, p2, p3) =
(probe.replace("PROBE", "p1"), probe.replace("PROBE", "p2"), probe.replace("PROBE", "p3"));
let files = [
("dut_a.sv", dut),
("tb.sv", tb),
("probe.sv", p1.as_str()),
("x/probe.sv", p2.as_str()),
("x/y/z/probe.sv", p3.as_str()),
];
let (_, warnings) = run(&files, "dut_a.sv", "begin : ", "g_sw", "g_hw").expect("renames");
let paths: Vec<&String> = warnings.iter().filter(|w| w.contains("hierarchical path")).collect();
assert_eq!(paths.len(), 3, "{warnings:#?}");
for w in &paths {
let named = w.split(':').next().unwrap_or("");
assert!(named.ends_with("probe.sv") && named.contains('/'), "unfindable: {w}");
}
let mut named: Vec<&str> = paths.iter().map(|w| w.split(':').next().unwrap_or("")).collect();
named.dedup();
assert_eq!(named.len(), 3, "three distinct names: {warnings:#?}");
}
/// Rework 2, R3: three levels of same-label arms.
#[test]
fn recheck_three_level_same_label_arms_are_all_warned_about() {
let text = "module t (output logic o);
if (1) begin : a
if (1) begin : b
if (1) begin : c
logic x;
end
end
end else begin : a
if (1) begin : b
if (1) begin : c
logic x;
end
end else begin : b
if (1) begin : c
logic x;
end
end
end
assign o = a.b.c.x;
endmodule
";
let (_, warnings) = run(&[("t.sv", text)], "t.sv", "logic ", "x", "y").expect("renames");
for line in [11, 15] {
assert!(
warnings.iter().any(|w| w.contains(&format!("t.sv:{line}"))),
"{line}: {warnings:#?}"
);
}
// …and from the deepest-else arm.
let (_, warnings) = run(
&[("t.sv", text)],
"t.sv",
"end else begin : b\n if (1) begin : c\n logic ",
"x",
"y",
)
.expect("renames");
for line in [5, 11] {
assert!(
warnings.iter().any(|w| w.contains(&format!("t.sv:{line}"))),
"{line}: {warnings:#?}"
);
}
}
/// Rework 2, R2: an escaped net and an escaped label behind an unresolved root.
#[test]
fn recheck_escaped_net_and_label_paths_are_named() {
let dut = "module dut_e;\n logic \\n$q ;\n if (1) begin : \\g$sw \n logic q;\n end\nendmodule\n";
let tb = "module tbe;\n dut_e dut ();\nendmodule\n";
let probe = "module pe (output logic o, output logic p);\n assign o = tbe.dut.\\g$sw .q;\n assign p = tbe.dut.\\n$q ;\nendmodule\n";
let files = [("dut_e.sv", dut), ("tbe.sv", tb), ("pe.sv", probe)];
let (_, warnings) = run(&files, "dut_e.sv", "begin : ", "\\g$sw", "g_hw").expect("label");
assert!(warnings.iter().any(|w| w.starts_with("pe.sv:2:")), "{warnings:#?}");
let (_, warnings) = run(&files, "dut_e.sv", "logic ", "\\n$q", "n_q").expect("net");
assert!(warnings.iter().any(|w| w.starts_with("pe.sv:3:")), "{warnings:#?}");
}
// ---------------------------------------------------------------------------
// Rework 4 (home set) attacks, 2026-09-30
// ---------------------------------------------------------------------------
const Q_DEFS: &str = "`define Q(x) x\n";
/// A module and a fragment it includes by `spelled`, the fragment naming
/// `state_q` bare in a macro argument; whether renaming `m.state_q` says so.
fn fragment_said(spelled: &str, frag_path: &str, extra: &[(&str, &str)]) -> (bool, Vec<String>) {
let module = format!(
"module m (input logic clk);\n logic state_q;\n always_ff @(posedge clk) state_q <= ~state_q;\n{spelled}\nendmodule\n"
);
let frag = " initial $display(\"%b\", `Q(state_q));\n";
let mut files: Vec<(&str, &str)> =
vec![("defs.svh", Q_DEFS), ("rtl/m.sv", &module), (frag_path, frag)];
files.extend_from_slice(extra);
let (_, warnings) = run(&files, "rtl/m.sv", "logic ", "state_q", "state_r").expect("renames");
let base = frag_path.rsplit('/').next().unwrap_or(frag_path);
(warnings.iter().any(|w| w.contains(base) && w.contains("macro invocation")), warnings)
}
#[test]
fn rework4_include_spellings_all_reach_the_fragment() {
for (spelled, path) in [
("`include \"../inc/m_assert.svh\"", "inc/m_assert.svh"),
("`include \"m_assert.svh\"", "deep/inc/dir/m_assert.svh"),
("`ifdef FOO\n`include \"m_assert.svh\"\n`endif", "rtl/m_assert.svh"),
("`include \"m_assert.svh\" // the assertions", "rtl/m_assert.svh"),
("`include \"m_assert.svh\"\r", "rtl/m_assert.svh"),
] {
let (ok, warnings) = fragment_said(spelled, path, &[]);
assert!(ok, "HIDDEN USE via {spelled:?} → {path}: {warnings:#?}");
}
}
#[test]
fn rework4_a_base_name_matching_two_files_takes_both() {
let other = ("other/m_assert.svh", " initial $display(\"%b\", `Q(state_q));\n");
let (ok, warnings) = fragment_said("`include \"m_assert.svh\"", "inc/m_assert.svh", &[other]);
assert!(ok, "{warnings:#?}");
let both =
warnings.iter().filter(|w| w.contains("m_assert.svh") && w.contains("macro")).count();
assert_eq!(both, 2, "both candidates are home: {warnings:#?}");
}
#[test]
fn rework4_three_level_includes_and_a_cycle_terminate_and_reach() {
let a = ("inc/a.svh", "`include \"b.svh\"\n");
let b = ("inc/b.svh", "`include \"m_assert.svh\"\n`include \"a.svh\"\n");
let (ok, warnings) = fragment_said("`include \"a.svh\"", "inc/m_assert.svh", &[a, b]);
assert!(ok, "three levels, with a cycle a → b → a: {warnings:#?}");
}
/// `` `include `FRAG `` — an include whose file name a macro builds.
#[test]
fn rework4_an_include_built_by_a_macro_is_followed_or_said() {
let defs = ("inc/paths.svh", "`define FRAG \"m_assert.svh\"\n");
let (ok, warnings) =
fragment_said("`include \"paths.svh\"\n`include `FRAG", "inc/m_assert.svh", &[defs]);
assert!(ok, "HIDDEN USE via `include `FRAG: {warnings:#?}");
}
/// The declaration sits in a fragment included by two modules: both
/// includers are home, and a bare use in either's macro argument is said.
#[test]
fn rework4_a_declaration_in_a_fragment_shared_by_two_modules() {
let decl = " logic shared_q;\n";
let m1 =
"module m1;\n`include \"decl.svh\"\n initial $display(\"%b\", `Q(shared_q));\nendmodule\n";
let m2 = "module m2;\n`include \"decl.svh\"\n assign o = shared_q;\nendmodule\n";
let files = [("defs.svh", Q_DEFS), ("decl.svh", decl), ("m1.sv", m1), ("m2.sv", m2)];
let result = run(&files, "decl.svh", "logic ", "shared_q", "shared_r");
let (_, warnings) = result.expect("renames");
assert!(said(&warnings, "m1.sv", 3), "m1's macro argument: {warnings:#?}");
assert!(said(&warnings, "m2.sv", 3), "m2's plain use: {warnings:#?}");
}
/// H2 closure and noise.
#[test]
fn rework4_define_bodies_reached_through_two_other_bodies() {
let hdr = "`define INNER state_q\n`define MID `INNER\n`define OUTER `MID\n";
let module = "module m (input logic clk, output logic [1:0] o);
logic state_q;
assign o = `OUTER;
endmodule
";
let files = [("hdr.svh", hdr), ("m.sv", module)];
let (_, warnings) = run(&files, "m.sv", "logic ", "state_q", "state_r").expect("renames");
let bodies: Vec<&String> = warnings.iter().filter(|w| w.contains("body of macro")).collect();
assert!(
bodies.iter().any(|w| w.contains("`INNER`")),
"HIDDEN USE through two bodies: {warnings:#?}"
);
}
/// Noise, not a hidden use: a macro whose parameter is named like the net,
/// and a macro "invoked" only inside a string.
#[test]
fn rework4_a_parameter_named_like_the_net_and_a_string_invocation_are_not_news() {
let hdr = "`define PARAM(state_q) (state_q + 1)\n`define UNUSED state_q\n";
let module = "module m (input logic clk, output logic [1:0] o);
logic state_q;
assign o = `PARAM(clk);
initial $display(\"`UNUSED\");
endmodule
";
let files = [("hdr.svh", hdr), ("m.sv", module)];
let (_, warnings) = run(&files, "m.sv", "logic ", "state_q", "state_r").expect("renames");
assert!(
!warnings.iter().any(|w| w.contains("`PARAM`") || w.contains("`UNUSED`")),
"{warnings:#?}"
);
}
/// H2 × H3: a bind file into the declaring module invokes a header macro
/// whose body spells the net bare.
#[test]
fn rework4_a_macro_invoked_inside_a_bind_into_the_unit_is_followed() {
let hdr = "`define SIG state_q\n";
let module = "module m (input logic clk);\n logic state_q;\nendmodule\n";
let chk = "module chk (input logic s);\nendmodule\n";
let bind = "module m_bind;\n bind m chk u_chk (.s(`SIG));\nendmodule\n";
let files = [("hdr.svh", hdr), ("m.sv", module), ("chk.sv", chk), ("m_bind.sv", bind)];
let (_, warnings) = run(&files, "m.sv", "logic ", "state_q", "state_r").expect("renames");
assert!(
warnings.iter().any(|w| w.contains("hdr.svh") || w.contains("m_bind.sv")),
"HIDDEN USE: {warnings:#?}"
);
}
/// H3 shapes: an instance path, an interface target, inside a generate.
#[test]
fn rework4_bind_by_path_to_an_interface_and_inside_a_generate() {
let ifc = "interface bus_if (input logic clk);\n logic state_q;\nendinterface\n";
let chk = "module chk (input logic s);\nendmodule\n";
let binds = "module binds;
bind bus_if chk u_a (.s(`Q(state_q)));
bind tb.u_bus chk u_b (.s(`Q(state_q)));
if (1) begin : g
bind bus_if chk u_c (.s(`Q(state_q)));
end
endmodule
";
let files = [("defs.svh", Q_DEFS), ("bus_if.sv", ifc), ("chk.sv", chk), ("binds.sv", binds)];
let (_, warnings) = run(&files, "bus_if.sv", "logic ", "state_q", "state_r").expect("renames");
for line in [2, 3, 5] {
assert!(said(&warnings, "binds.sv", line), "line {line}: {warnings:#?}");
}
}
/// H4: a fragment that declares its own `mem` is never rewritten; a fragment
/// only an unrelated module includes stays silent.
#[test]
fn rework4_fragment_uses_of_a_different_declaration_are_not_rewritten() {
let module = "module m;\n logic [7:0] mem;\n`include \"own.svh\"\nendmodule\n";
let own =
" function automatic int peek();\n logic [7:0] mem;\n return mem;\n endfunction\n";
let unrelated = "module u;\n logic [7:0] mem;\n`include \"far.svh\"\nendmodule\n";
let far = " initial mem = '0;\n";
let files = [("m.sv", module), ("own.svh", own), ("u.sv", unrelated), ("far.svh", far)];
let (texts, warnings) = run(&files, "m.sv", "logic [7:0] ", "mem", "mem_q").expect("renames");
assert_eq!(texts[1], own, "the fragment's own `mem` is never rewritten");
assert_eq!((texts[2].as_str(), texts[3].as_str()), (unrelated, far));
assert!(!warnings.iter().any(|w| w.contains("far.svh")), "{warnings:#?}");
}
// ---------------------------------------------------------------------------
// Rework 5 closing check, 2026-09-30
// ---------------------------------------------------------------------------
/// N1: renaming `sub.clk_i` edits `top` (its connection). `top` has no
/// `clk_i` of its own and spells one in a macro argument of the connection.
/// The bare spelling cannot name `sub`'s port; whatever is said, the port's
/// own module must still warn its own macro argument.
#[test]
fn rework5_an_edited_instantiator_without_its_own_name() {
let sub =
"module sub (input logic clk_i);\n initial $display(\"%b\", `Q(clk_i));\nendmodule\n";
let top = "module top (input logic c);\n sub u (.clk_i(`Q(clk_i)));\nendmodule\n";
let files = [("defs.svh", Q_DEFS), ("sub.sv", sub), ("top.sv", top)];
let (texts, warnings) = run(&files, "sub.sv", "logic ", "clk_i", "clk").expect("renames");
assert!(said(&warnings, "sub.sv", 2), "{warnings:#?}");
assert!(texts[2].contains(".clk("), "the connection's port name moves: {}", texts[2]);
}
/// N1: an edited file that also includes a fragment the declaring module
/// includes, and a nested module that re-declares the name.
#[test]
fn rework5_an_edited_file_sharing_a_fragment_or_nesting_a_redeclaration() {
let sub = "module sub (input logic clk_i);\n`include \"frag.svh\"\nendmodule\n";
let frag = " initial $display(\"%b\", `Q(clk_i));\n";
let top = "module top (input logic clk_i);\n`include \"frag.svh\"\n sub u (.clk_i);\n module inner;\n logic clk_i;\n initial $display(\"%b\", `Q(clk_i));\n endmodule\nendmodule\n";
let files = [("defs.svh", Q_DEFS), ("sub.sv", sub), ("frag.svh", frag), ("top.sv", top)];
let (_, warnings) = run(&files, "sub.sv", "logic ", "clk_i", "clk").expect("renames");
assert!(said(&warnings, "frag.svh", 1), "the shared fragment pastes into sub: {warnings:#?}");
assert!(!said(&warnings, "top.sv", 6), "inner's own clk_i: {warnings:#?}");
}
/// N2: a parameter named like the net silences only a body that has no
/// other way to the net. A path through the name in the body (`u_m.state_q`)
/// can reach it; 0.59.0 warned, rework 5 did not (QA P1: the parameter check
/// ran before `body_dotted` and the unscoped fallback). Fixed: both now come
/// first in `keeps_define_body`.
#[test]
fn rework5_a_shadowing_parameter_does_not_hide_a_dotted_body_spelling() {
let hdr = "`define PATHY(state_q) (state_q + u_m.state_q)\n";
let module = "module m (input logic clk, output logic [1:0] o);
logic state_q;
assign o = `PATHY(clk);
endmodule
";
let files = [("hdr.svh", hdr), ("m.sv", module)];
let (_, warnings) = run(&files, "m.sv", "logic ", "state_q", "state_r").expect("renames");
assert!(warnings.iter().any(|w| w.contains("`PATHY`")), "the dotted path: {warnings:#?}");
}
/// A default argument spelling the name expands into the module when the
/// macro is invoked without it. Silent in 0.59.0 too (QA P2: default
/// arguments were never scanned); now scanned with the body.
#[test]
fn rework5_a_default_argument_spelling_the_name_is_said() {
let hdr = "`define DFLT(x = state_q) (x)\n";
let module = "module m (input logic clk, output logic [1:0] o);
logic state_q;
assign o = `DFLT();
endmodule
";
let files = [("hdr.svh", hdr), ("m.sv", module)];
let (_, warnings) = run(&files, "m.sv", "logic ", "state_q", "state_r").expect("renames");
assert!(
warnings.iter().any(|w| w.contains("`DFLT`") || w.contains("hdr.svh:1")),
"{warnings:#?}"
);
}
/// K2 through a two-level instance path, and N3 three include levels up.
#[test]
fn rework5_bind_by_two_level_path_and_three_levels_of_includers() {
let hdr = "`define SIG state_q\n";
let m = "module m;\n logic state_q;\nendmodule\n";
let chk = "module chk (input logic s);\nendmodule\n";
let bind = "module b;\n bind tb.u_top.u_m chk u_chk (.s(`SIG));\nendmodule\n";
let files = [("hdr.svh", hdr), ("m.sv", m), ("chk.sv", chk), ("b.sv", bind)];
let (_, warnings) = run(&files, "m.sv", "logic ", "state_q", "state_r").expect("renames");
assert!(warnings.iter().any(|w| w.contains("hdr.svh") || w.contains("b.sv")), "{warnings:#?}");
let body = " logic deep_q;\n initial $display(\"%b\", `Q(deep_q));\n";
let l1 = "`include \"body.svh\"\n";
let l2 = "`include \"l1.svh\"\n";
let l3 = "module top;\n`include \"l2.svh\"\n initial $display(\"%b\", `Q(deep_q));\n assign o = deep_q;\nendmodule\n";
let files =
[("defs.svh", Q_DEFS), ("body.svh", body), ("l1.svh", l1), ("l2.svh", l2), ("top.sv", l3)];
let (_, warnings) = run(&files, "body.svh", "logic ", "deep_q", "deep_r").expect("renames");
assert!(said(&warnings, "top.sv", 3), "three levels up, macro argument: {warnings:#?}");
assert!(said(&warnings, "top.sv", 4), "three levels up, plain use: {warnings:#?}");
}
+10 -10
View File
@@ -963,15 +963,15 @@ fn a_tail_naming_a_parameter_is_renamed_across_files() {
);
}
/// The honest refusal, pinned. A net declared inside a **generate block** is
/// not a member of the module: its scope is the block's, and the member table
/// records a unit's own scope only. `u_x.gen_b.sig` therefore does not
/// resolve, the tail is left as written, and the rename says so rather than
/// editing half a design. Widening this means teaching the index about
/// generate scopes and their loop indices (`u_x.gen[0].sig`), which §49
/// deliberately did not do.
/// A net declared inside a **generate block**, named through an instance from
/// another file. Until TODO §65.1 this was the honest refusal pinned here: the
/// member table recorded a unit's own scope only, so `u_x.gen_b.sig` did not
/// resolve and the tail was left as written. A module's named blocks are now
/// on its hierarchical surface and their members under `sub.gen_b`, so the
/// tail is a reference and the rename rewrites it
/// (`docs/features/generate-label-rename/README.md`).
#[test]
fn a_generate_block_scoped_net_named_through_an_instance_is_refused_honestly() {
fn a_generate_block_scoped_net_named_through_an_instance_is_renamed_with_its_path() {
const SUB: &str = concat!(
"module sub;\n",
" if (1) begin : gen_b\n",
@@ -987,8 +987,8 @@ fn a_generate_block_scoped_net_named_through_an_instance_is_refused_honestly() {
assert!(apply(SUB, &edit, &path("sub.sv")).contains("wire signal;"), "the declaration moves");
assert_eq!(
apply(TOP, &edit, &path("top.sv")),
TOP,
"a generate-scoped name is not on either surface, so the tail is left alone"
TOP.replace("gen_b.sig", "gen_b.signal"),
"the tail through the block is a reference, so it moves with the declaration"
);
}
+14 -9
View File
@@ -535,12 +535,13 @@ endmodule
}
#[test]
fn a_bind_target_reached_through_a_generate_block_is_warned_about_never_guessed() {
// `bind tb.gen[0].u_aes …`: the middle hop is a generate block, which the
// index has no record of at all (an indexed segment "keeps only its
// name", per `bind_target_path`'s doc comment) — so the path is one the
// index cannot walk, and the contract is a warning, never a silent miss
// and never a guess at which `u_aes` is meant.
fn a_bind_target_reached_through_a_generate_block_is_followed_and_a_broken_one_warned_about() {
// `bind tb.gen[0].u_aes …`: the middle hop is a generate block. Until
// TODO §65.1 the index had no record of one and this path warned; a
// module's named blocks are now on its hierarchical surface, so the hop
// is walked (`tb` → `tb.gen` → `u_aes`'s `aes`) and the connection is
// renamed. A path naming a block `tb` does not have is still the
// warning, never a silent miss and never a guess.
let tb = "\
module tb;
if (1) begin : gen
@@ -555,23 +556,27 @@ module aes_bind;
);
endmodule
";
let broken = bind.replace("tb.gen[0]", "tb.nogen[0]").replace("aes_bind", "aes_bind2");
let mut files = rtl(bind);
files.push((path("tb.sv"), tb.to_string()));
files.push((path("aes_bind2.sv"), broken.clone()));
let edit =
rename(&files, &path("aes.sv"), at(AES, "logic", "entropy_masking_req"), "masking_req")
.expect("the rename over the rest of the design still succeeds");
assert_eq!(
apply(bind, &edit, &path("aes_bind.sv")),
bind,
"a path through a generate block is never guessed at: {edit:?}"
bind.replace("(entropy_masking_req)", "(masking_req)"),
"a path through a generate block is walked: {edit:?}"
);
assert_eq!(apply(&broken, &edit, &path("aes_bind2.sv")), broken, "never guessed at");
assert!(
edit.warnings
.iter()
.any(|w| w.contains("aes_bind.sv") && w.contains("could not be resolved")),
.any(|w| w.contains("aes_bind2.sv") && w.contains("could not be resolved")),
"the miss is said out loud rather than silently dropped: {:?}",
edit.warnings
);
assert!(!edit.warnings.iter().any(|w| w.contains("aes_bind.sv")), "{:?}", edit.warnings);
}
// ----------------------------------------------------------------------
@@ -0,0 +1,377 @@
//! A rename and a reference list through a block label (TODO §65.1, topo
//! §2.9-43, MCP-14).
//!
//! `rename` of `g_lane` in `for (…) begin : g_lane` used to rewrite the label
//! alone: the loop's label was bound inside the loop header's scope, so
//! `g_lane[0].lane_q` written beside the loop resolved to nothing, and a path
//! from another file (`u_x.g_lane[1].sig`) never reached the block at all.
//! Every test drives the public `rename` / `find_references` over a little
//! in-memory workspace and asserts the whole text of each file afterwards,
//! the reference list, or the refusal's sentence.
use std::path::{Path, PathBuf};
use vlog_refactor::{find_references, prepare_rename, rename, RefactorEdit};
fn workspace(files: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
files.iter().map(|(name, text)| (path(name), text.to_string())).collect()
}
fn path(name: &str) -> PathBuf {
PathBuf::from("/rtl").join(name)
}
/// The offset of the first whole-word `name` at or after `prefix`.
fn at(text: &str, prefix: &str, name: &str) -> u32 {
let from =
text.find(prefix).unwrap_or_else(|| panic!("`{prefix}` is not in the text")) + prefix.len();
let is_word = |b: Option<&u8>| b.is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_');
let bytes = text.as_bytes();
let mut search = from;
while let Some(hit) = text.get(search..).and_then(|s| s.find(name)) {
let start = search + hit;
let end = start + name.len();
if !is_word(start.checked_sub(1).and_then(|i| bytes.get(i))) && !is_word(bytes.get(end)) {
return start as u32;
}
search = start + 1;
}
panic!("`{name}` does not occur after `{prefix}`");
}
fn apply(text: &str, edit: &RefactorEdit, file: &Path) -> String {
let mut out = String::new();
let mut cursor = 0usize;
for e in edit.edits_for(file) {
out.push_str(&text[cursor..e.range.start as usize]);
out.push_str(&e.new_text);
cursor = e.range.end as usize;
}
out.push_str(&text[cursor..]);
out
}
/// Rename the `name` after `prefix` in `file`; every file's text afterwards,
/// and the warnings.
fn renamed(
files: &[(&str, &str)],
file: &str,
prefix: &str,
name: &str,
new_name: &str,
) -> Result<(Vec<String>, Vec<String>), String> {
let sources = workspace(files);
let text = files.iter().find(|(n, _)| *n == file).map(|(_, t)| *t).expect("the file");
let edit = rename(&sources, &path(file), at(text, prefix, name), new_name)?;
let texts = files.iter().map(|(n, t)| apply(t, &edit, &path(n))).collect();
Ok((texts, edit.warnings))
}
/// `(file, line text)` of every reference to the `name` after `prefix`.
fn references(files: &[(&str, &str)], file: &str, prefix: &str, name: &str) -> Vec<String> {
let sources = workspace(files);
let text = files.iter().find(|(n, _)| *n == file).map(|(_, t)| *t).expect("the file");
let found = find_references(&sources, &path(file), at(text, prefix, name), true)
.unwrap_or_else(|why| panic!("find_references refused: {why}"));
found
.iter()
.map(|(p, span)| {
let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("?");
let text = files.iter().find(|(n, _)| *n == name).map(|(_, t)| *t).expect("file");
let line = text[..span.start as usize].matches('\n').count() + 1;
format!("{name}:{line}:{}", &text[span.as_range()])
})
.collect()
}
/// The QA reproduction (MCP-14), with a closing label added.
const FSM: &str = "module fsm (input logic clk, output logic busy);
for (genvar gi = 0; gi < 2; gi++) begin : g_lane
logic lane_q;
assign lane_q = gi[0];
end : g_lane
always_comb begin
automatic logic tmp;
tmp = clk;
busy = tmp | g_lane[0].lane_q | g_lane[gi_top].lane_q;
end
localparam int gi_top = 1;
endmodule
";
#[test]
fn renaming_a_for_generate_label_rewrites_the_closing_label_and_every_indexed_path() {
let (texts, warnings) =
renamed(&[("fsm.sv", FSM)], "fsm.sv", "begin : ", "g_lane", "g_ln").expect("renames");
assert_eq!(texts[0], FSM.replace("g_lane", "g_ln"));
assert!(warnings.is_empty(), "{warnings:?}");
}
#[test]
fn the_rename_is_the_same_from_a_path_segment_and_from_the_closing_label() {
let from_decl = renamed(&[("fsm.sv", FSM)], "fsm.sv", "begin : ", "g_lane", "g_ln");
let from_use = renamed(&[("fsm.sv", FSM)], "fsm.sv", "tmp | ", "g_lane", "g_ln");
let from_end = renamed(&[("fsm.sv", FSM)], "fsm.sv", "end : ", "g_lane", "g_ln");
assert_eq!(from_decl, from_use);
assert_eq!(from_decl, from_end);
}
#[test]
fn find_references_on_the_label_lists_the_declaration_the_closing_label_and_every_segment() {
let found = references(&[("fsm.sv", FSM)], "fsm.sv", "tmp | ", "g_lane");
assert_eq!(
found,
vec!["fsm.sv:2:g_lane", "fsm.sv:5:g_lane", "fsm.sv:9:g_lane", "fsm.sv:9:g_lane"]
);
}
#[test]
fn a_variable_inside_the_block_is_renamed_through_the_path_too() {
let (texts, _) =
renamed(&[("fsm.sv", FSM)], "fsm.sv", "logic ", "lane_q", "lane_r").expect("renames");
assert_eq!(texts[0], FSM.replace("lane_q", "lane_r"));
}
const NESTED: &str = "module n (output logic o, output logic p);
if (1) begin : g_a
for (genvar j = 0; j < 4; j++) begin : g_b
logic x;
assign x = j[0];
end
logic y;
end
generate
case (2)
2: begin : g_c
logic z;
end
default: begin : g_c
logic z;
end : g_c
endcase
endgenerate
assign o = g_a.g_b[2].x ^ g_a.y;
assign p = g_c.z;
endmodule
";
#[test]
fn a_bare_a_nested_and_an_indexed_segment_are_all_references_to_their_labels() {
let (texts, _) = renamed(&[("n.sv", NESTED)], "n.sv", "begin : ", "g_a", "g_top").expect("a");
assert_eq!(texts[0], NESTED.replace("g_a", "g_top"));
let (texts, _) = renamed(&[("n.sv", NESTED)], "n.sv", "g_a.", "g_b", "g_bit").expect("b");
assert_eq!(texts[0], NESTED.replace("g_b", "g_bit"));
}
#[test]
fn a_label_both_arms_of_a_generate_case_carry_is_renamed_as_one_with_both_closing_labels() {
let (texts, _) = renamed(&[("n.sv", NESTED)], "n.sv", "p = ", "g_c", "g_d").expect("renames");
assert_eq!(texts[0], NESTED.replace("g_c", "g_d"));
}
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
logic plain;
endmodule
";
const TOP: &str = "module top (input logic clk, output logic o);
sub u_x (.clk);
assign o = u_x.g_lane[1].sig | u_x.g_lane[0].sig;
// g_lane is only a comment here
endmodule
";
fn cross() -> Vec<(&'static str, &'static str)> {
vec![("sub.sv", SUB), ("top.sv", TOP)]
}
#[test]
fn a_path_from_another_file_through_an_instance_is_rewritten_with_the_label() {
let (texts, _) = renamed(&cross(), "sub.sv", "begin : ", "g_lane", "g_ln").expect("renames");
assert_eq!(texts[0], SUB.replace("g_lane", "g_ln"));
assert_eq!(
texts[1],
TOP.replace("u_x.g_lane", "u_x.g_ln"),
"the comment is not a reference and stays"
);
}
#[test]
fn the_cross_file_rename_is_the_same_started_from_the_other_file() {
let from_decl = renamed(&cross(), "sub.sv", "begin : ", "g_lane", "g_ln");
let from_use = renamed(&cross(), "top.sv", "u_x.", "g_lane", "g_ln");
assert_eq!(from_decl, from_use);
}
#[test]
fn find_references_reaches_the_other_files_segments() {
let found = references(&cross(), "top.sv", "u_x.", "g_lane");
assert_eq!(
found,
vec!["sub.sv:2:g_lane", "sub.sv:5:g_lane", "top.sv:3:g_lane", "top.sv:3:g_lane"]
);
}
#[test]
fn a_signal_in_the_block_is_renamed_through_the_cross_file_path() {
let (texts, _) = renamed(&cross(), "sub.sv", "logic ", "sig", "sig_q").expect("renames");
assert_eq!(
texts[0],
SUB.replace("logic sig;", "logic sig_q;").replace("assign sig", "assign sig_q")
);
assert_eq!(texts[1], TOP.replace(".sig", ".sig_q"));
}
#[test]
fn a_spelling_in_a_macro_or_a_string_is_a_warning_and_the_rest_is_renamed() {
let text = "`define LANE(n) g_lane[n].lane_q
module m (output logic o, output logic p);
for (genvar i = 0; i < 2; i++) begin : g_lane
logic lane_q;
end
assign o = g_lane[0].lane_q;
assign p = `LANE(1);
initial $display(\"g_lane\");
endmodule
";
let (texts, warnings) =
renamed(&[("m.sv", text)], "m.sv", "begin : ", "g_lane", "g_ln").expect("renames");
assert!(texts[0].contains("begin : g_ln\n") && texts[0].contains("o = g_ln[0].lane_q;"));
assert!(texts[0].contains("`define LANE(n) g_lane[n]"), "macro text is not edited");
assert!(texts[0].contains("$display(\"g_lane\")"), "a string is not edited");
assert!(warnings.iter().any(|w| w.contains("LANE")), "{warnings:?}");
}
#[test]
fn an_unnamed_generate_block_has_no_label_to_rename() {
let text = "module m (output logic o);
if (1) begin
logic w;
end
assign o = genblk1.w;
endmodule
";
let files = workspace(&[("m.sv", text)]);
let why =
rename(&files, &path("m.sv"), at(text, "o = ", "genblk1"), "g_x").expect_err("refused");
assert!(why.contains("not resolved"), "{why}");
assert!(prepare_rename(&files, &path("m.sv"), at(text, "o = ", "genblk1")).is_err());
}
const PROCEDURAL: &str = "module p (input logic clk, output logic o);
always_ff @(posedge clk) begin : blk
logic t;
t = ~o;
if (t) disable blk;
o <= t;
end : blk
task automatic poke();
fork : fk
begin end
join : fk
disable fk;
endtask
initial lbl: begin
disable lbl;
end : lbl
endmodule
";
#[test]
fn a_named_procedural_block_its_closing_label_and_disable_are_one_reference_set() {
let (texts, _) =
renamed(&[("p.sv", PROCEDURAL)], "p.sv", "disable ", "blk", "b2").expect("renames");
assert_eq!(texts[0], PROCEDURAL.replace("blk", "b2"));
let (texts, _) = renamed(&[("p.sv", PROCEDURAL)], "p.sv", "join : ", "fk", "f2").expect("fk");
assert_eq!(texts[0], PROCEDURAL.replace("fk", "f2"));
let (texts, _) = renamed(&[("p.sv", PROCEDURAL)], "p.sv", "end : ", "lbl", "l2").expect("l");
assert_eq!(texts[0], PROCEDURAL.replace("lbl", "l2"));
}
#[test]
fn a_net_and_a_block_of_the_same_name_in_different_scopes_are_two_declarations() {
let text = "module s (output logic o);
if (1) begin : g
logic x;
end
if (1) begin : h
logic g;
assign g = 1'b1;
end
assign o = g.x | h.g;
endmodule
";
let (texts, _) = renamed(&[("s.sv", text)], "s.sv", "begin : ", "g", "gg").expect("block");
assert_eq!(
texts[0],
text.replace("begin : g\n", "begin : gg\n").replace("o = g.x", "o = gg.x")
);
let (texts, _) =
renamed(&[("s.sv", text)], "s.sv", "begin : h\n logic ", "g", "n").expect("net");
assert_eq!(
texts[0],
text.replace("logic g;", "logic n;")
.replace("assign g =", "assign n =")
.replace("h.g;", "h.n;")
);
}
#[test]
fn a_new_name_that_a_path_would_then_capture_is_refused() {
// `g_ln` already names a net beside the loop: the path's head would
// rebind to it, so the whole rename is refused.
let text = "module c (output logic o);
logic g_ln;
for (genvar i = 0; i < 2; i++) begin : g_lane
logic q;
end
assign o = g_lane[0].q;
endmodule
";
let why =
renamed(&[("c.sv", text)], "c.sv", "begin : ", "g_lane", "g_ln").expect_err("refused");
assert!(why.contains("g_ln") || why.contains("abandoned"), "{why}");
}
/// QA F1, the lead's rule: a path segment spelling the old name that resolved
/// to *no* declaration, in any file of the set, is a warning with its lines;
/// one that resolved to a *different* declaration is not news.
#[test]
fn an_unresolved_path_through_the_name_warns_and_a_path_to_another_declaration_does_not() {
let sub = "module sub;\n logic state_q;\nendmodule\n";
let other = "module other;\n logic state_q;\nendmodule\n";
let top = "module top (output logic o, output logic p);\n sub u_x ();\n other u_y ();\n assign o = u_x.state_q;\n assign p = u_y.state_q;\nendmodule\n";
let probe = "module probe (output logic o);\n assign o = tb.u_x.state_q;\n assign o = tb.u_x.state_q\n | tb.u_x.state_q;\nendmodule\n";
let files = [("sub.sv", sub), ("other.sv", other), ("top.sv", top), ("probe.sv", probe)];
let (texts, warnings) =
renamed(&files, "sub.sv", "logic ", "state_q", "state_r").expect("renames");
assert_eq!(texts[2], top.replace("u_x.state_q", "u_x.state_r"));
assert_eq!((texts[1].as_str(), texts[3].as_str()), (other, probe));
assert_eq!(warnings.len(), 1, "{warnings:?}");
assert!(warnings[0].starts_with("probe.sv:2,3,4: "), "{warnings:?}");
}
/// Re-check R1: two files of one base name in the set are named by the path
/// the caller gave, so each warning names a findable file; a unique base
/// name stays bare.
#[test]
fn warnings_name_a_shared_base_name_by_its_path_and_a_unique_one_bare() {
let dut = "module dut_x;\n if (1) begin : g_sw\n logic q;\n end\nendmodule\n";
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 files = [("dut_x.sv", dut), ("a/x_if.sv", a.as_str()), ("b/x_if.sv", b.as_str())];
let (_, warnings) = renamed(&files, "dut_x.sv", "begin : ", "g_sw", "g_hw").expect("renames");
let lines: Vec<&str> = warnings
.iter()
.filter_map(|w| w.split_once(": a hierarchical path"))
.map(|(h, _)| h)
.collect();
assert_eq!(lines, vec!["/rtl/a/x_if.sv:2", "/rtl/b/x_if.sv:2"], "{warnings:?}");
let unique = [("dut_x.sv", dut), ("a/x_if.sv", a.as_str())];
let (_, warnings) = renamed(&unique, "dut_x.sv", "begin : ", "g_sw", "g_hw").expect("renames");
assert!(warnings.iter().any(|w| w.starts_with("x_if.sv:2: ")), "{warnings:?}");
}
@@ -0,0 +1,138 @@
//! A bare macro argument in another module is that module's own name —
//! unless the macro carries it to the renamed declaration: after a `.`
//! (`force u_m.sig`, a named connection `.x(x)`), through a pasted path
//! (`` u_m.``sig ``), into a `bind` into the declaring module, or into a
//! macro the set does not define (TODO §65.1, independent review H-1/H-2,
//! 2026-10-06). Each of these was warned about in 0.59.0, silent after the
//! scoping rework, and is warned about again.
use std::path::PathBuf;
use vlog_refactor::rename;
/// `m`'s `state_q` is an input port; every test renames it.
const M: &str = "module m (input logic clk, input logic state_q);
logic r;
always_ff @(posedge clk) r <= state_q;
endmodule
";
/// The warnings of renaming `m.state_q` to `state_r` among `files` (plus
/// `m.sv`).
fn warnings_of(files: &[(&str, &str)]) -> Vec<String> {
let mut sources = vec![(PathBuf::from("/rtl/m.sv"), M.to_string())];
sources.extend(files.iter().map(|(n, t)| (PathBuf::from("/rtl").join(n), t.to_string())));
let at = M.find("logic state_q").expect("declaration") as u32 + 6;
rename(&sources, &PathBuf::from("/rtl/m.sv"), at, "state_r").expect("renames").warnings
}
/// Whether some warning names `file:line`.
fn said(warnings: &[String], file: &str, line: u32) -> bool {
warnings.iter().any(|w| w.contains(&format!("{file}:{line}")))
}
/// PC: the instantiation is broken by the rename and must not be silent.
#[test]
fn a_named_connection_a_macro_builds_from_a_bare_argument_is_said() {
let top = "module top (input logic clk, input logic state_q);
m u_m (.clk(clk), `CONN(state_q));
endmodule
";
let warnings = warnings_of(&[("defs.svh", "`define CONN(x) .x(x)\n"), ("top.sv", top)]);
assert!(said(&warnings, "top.sv", 2), "{warnings:#?}");
}
/// PA: a testbench forcing a path the macro builds from its argument.
#[test]
fn a_bare_argument_the_macro_puts_after_a_dot_is_said() {
let tb = "module tb;
logic clk;
m u_m (.clk(clk), .state_q(1'b0));
initial begin
`FORCE(state_q)
end
endmodule
";
let defs = "`define FORCE(sig) force u_m.sig = 1'b0;\n";
let warnings = warnings_of(&[("defs.svh", defs), ("tb.sv", tb)]);
assert!(said(&warnings, "tb.sv", 5), "{warnings:#?}");
}
/// PA2: the same path through a `` `` `` paste.
#[test]
fn a_bare_argument_pasted_after_a_dot_is_said() {
let tb = "module tb;
logic clk, o;
m u_m (.clk(clk), .state_q(1'b0));
assign o = `PEEK(state_q);
endmodule
";
let warnings = warnings_of(&[("defs.svh", "`define PEEK(sig) u_m.``sig\n"), ("tb.sv", tb)]);
assert!(said(&warnings, "tb.sv", 4), "{warnings:#?}");
}
/// A macro passing its argument on to one that carries it carries it too;
/// the position it passes on is the one that counts.
#[test]
fn an_argument_passed_on_to_a_carrying_macro_is_said_and_another_is_not() {
let defs =
"`define FORCE(sig) force u_m.sig = 1'b0;\n`define BOTH(v, sig) v = 1'b1; `FORCE(sig)\n";
let tb = "module tb;
logic clk, state_q;
m u_m (.clk(clk), .state_q(1'b0));
initial `BOTH(state_q, r);
initial `BOTH(x, state_q);
endmodule
";
let warnings = warnings_of(&[("defs.svh", defs), ("tb.sv", tb)]);
assert!(!said(&warnings, "tb.sv", 4), "tb's own state_q: {warnings:#?}");
assert!(said(&warnings, "tb.sv", 5), "{warnings:#?}");
}
/// PD: a macro whose body is a `bind` into `m`, invoked from a file that is
/// not home — the body's `state_q` is evaluated in `m`.
#[test]
fn a_define_body_that_binds_into_the_module_is_said_wherever_it_is_invoked() {
let defs = "`define BIND_CHK bind m chk u_chk (.s(state_q));\n";
let chk = "module chk (input logic s);\nendmodule\n";
let binds = "module binds;\n `BIND_CHK\nendmodule\n";
let warnings = warnings_of(&[("defs.svh", defs), ("chk.sv", chk), ("binds.sv", binds)]);
assert!(said(&warnings, "defs.svh", 1), "{warnings:#?}");
}
/// PD with the name passed in: every argument of a binder is carried.
#[test]
fn a_bare_argument_of_a_macro_that_binds_into_the_module_is_said() {
let defs = "`define BIND_S(sig) bind m chk u_chk (.s(sig));\n";
let chk = "module chk (input logic s);\nendmodule\n";
let binds = "module binds;\n `BIND_S(state_q)\nendmodule\n";
let warnings = warnings_of(&[("defs.svh", defs), ("chk.sv", chk), ("binds.sv", binds)]);
assert!(said(&warnings, "binds.sv", 2), "{warnings:#?}");
}
/// Nothing shows what an undefined macro does with its argument.
#[test]
fn a_bare_argument_of_a_macro_the_set_does_not_define_is_said() {
let tb = "module tb;
logic state_q;
initial `NOWHERE(state_q)
endmodule
";
let warnings = warnings_of(&[("tb.sv", tb)]);
assert!(said(&warnings, "tb.sv", 3), "{warnings:#?}");
}
/// The scoping is kept where it is provable: a macro that uses its argument
/// as a plain expression, in a module with its own `state_q`, is silent.
#[test]
fn a_plain_expression_macro_in_another_module_stays_silent() {
let defs =
"`define ASSERT(n, e) n: assert property (@(posedge clk) e);\n`define CONN(x) .x(x)\n";
let other = "module other (input logic clk);
logic state_q;
`ASSERT(Own, state_q)
endmodule
";
let warnings = warnings_of(&[("defs.svh", defs), ("other.sv", other)]);
assert!(!said(&warnings, "other.sv", 3), "{warnings:#?}");
}
@@ -0,0 +1,126 @@
//! A rename's text warnings are about the renamed declaration (TODO §65.1,
//! lead's inspection 2026-09-30): a module member's bare spelling in another
//! module's macro argument, `` `define`` body or unstructured assertion is
//! that module's own signal, not news; a dotted spelling may be a path to it
//! and is still said; a package-level name is still warned about everywhere.
use std::path::PathBuf;
use vlog_refactor::rename;
fn workspace(files: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
files.iter().map(|(name, text)| (PathBuf::from("/rtl").join(name), text.to_string())).collect()
}
const DEFS: &str = "`define ASSERT(n, e) n: assert property (e);\n`define PEEK_A tb.u_a.state_q\n`define LOCAL_B state_q\n";
const A: &str = "module a (input logic clk);
logic state_q;
always_ff @(posedge clk) state_q <= ~state_q;
`ASSERT(A_Toggles, state_q)
// state_q is a's register
initial $display(\"state_q\");
endmodule
";
const B: &str = "module b (input logic clk);
logic state_q;
a u_a (.clk);
always_ff @(posedge clk) state_q <= ~state_q;
`ASSERT(B_Own, state_q)
`ASSERT(B_Peek, u_a.state_q)
// state_q is b's register
initial $display(\"state_q\");
endmodule
";
/// The warnings of renaming `a`'s `state_q`.
fn warnings_of_renaming_a() -> Vec<String> {
let files = workspace(&[("defs.svh", DEFS), ("a.sv", A), ("b.sv", B)]);
let at = A.find("logic state_q").expect("decl") as u32 + 6;
rename(&files, &PathBuf::from("/rtl/a.sv"), at, "state_r").expect("renames").warnings
}
#[test]
fn only_the_renamed_modules_bare_macro_argument_is_warned_about() {
let warnings = warnings_of_renaming_a();
let macro_args: Vec<&String> =
warnings.iter().filter(|w| w.contains("arguments of the macro invocation")).collect();
assert_eq!(macro_args.len(), 2, "{warnings:#?}");
assert!(macro_args[0].contains("a.sv:4"), "a's own `ASSERT: {warnings:#?}");
assert!(macro_args[1].contains("b.sv:6"), "b's dotted `u_a.state_q`: {warnings:#?}");
}
#[test]
fn a_foreign_define_body_is_said_only_when_it_spells_the_name_dotted() {
let warnings = warnings_of_renaming_a();
let bodies: Vec<&String> = warnings.iter().filter(|w| w.contains("body of macro")).collect();
assert_eq!(bodies.len(), 1, "{warnings:#?}");
assert!(bodies[0].contains("`PEEK_A`"), "{warnings:#?}");
}
#[test]
fn a_package_level_name_is_still_warned_about_in_every_module() {
let pkg = "package p;\n localparam int W = 1;\nendpackage\n";
let user = "module u import p::*; (input logic clk);\n `ASSERT(U_W, W > 0)\nendmodule\n";
let other =
"module v (input logic clk);\n localparam int W = 2;\n `ASSERT(V_W, W > 0)\nendmodule\n";
let files = workspace(&[("defs.svh", DEFS), ("p.sv", pkg), ("u.sv", user), ("v.sv", other)]);
let at = pkg.find("W =").expect("decl") as u32;
let edit = rename(&files, &PathBuf::from("/rtl/p.sv"), at, "WIDTH").expect("renames");
let macro_args: Vec<&String> =
edit.warnings.iter().filter(|w| w.contains("arguments of the macro invocation")).collect();
assert_eq!(macro_args.len(), 2, "both, as before: {:#?}", edit.warnings);
}
/// Rework 5, N1: a port rename edits every instantiating file, and each of
/// those asserts on its *own* `clk_i` — the scope lookup in an edited file
/// says those are not the renamed port. The declaring module's own
/// assertion still warns.
#[test]
fn an_instantiating_modules_own_bare_spelling_is_not_news() {
let flop = "module flop (input logic clk_i, input logic d, output logic q);
always_ff @(posedge clk_i) q <= d;
`ASSERT(FlopKnown_A, !$isunknown(clk_i))
endmodule
";
let user = |n: u32| {
format!(
"module user{n} (input logic clk_i, input logic d, output logic q);
flop u_flop (.clk_i(clk_i), .d, .q);
`ASSERT(User{n}Clk_A, clk_i)
endmodule
"
)
};
let (u1, u2, u3) = (user(1), user(2), user(3));
let files = workspace(&[
("defs.svh", DEFS),
("flop.sv", flop),
("user1.sv", &u1),
("user2.sv", &u2),
("user3.sv", &u3),
]);
let at = flop.find("clk_i").expect("port") as u32;
let edit = rename(&files, &PathBuf::from("/rtl/flop.sv"), at, "clk_x").expect("renames");
assert_eq!(edit.edits.len(), 4, "the port and the three connections");
let macro_args: Vec<&String> =
edit.warnings.iter().filter(|w| w.contains("arguments of the macro invocation")).collect();
assert_eq!(macro_args.len(), 1, "{:#?}", edit.warnings);
assert!(macro_args[0].contains("flop.sv:3"), "{:#?}", edit.warnings);
}
/// Review M-1: a use in an include-related file that the rename *did* edit
/// is not reported as "left unchanged". `all.sv` includes `m.sv` and `n.sv`,
/// so `n.sv` is pasted around `m.sv`; its instantiation of `m` is a
/// cross-file reference the rename rewrites.
#[test]
fn an_edited_use_in_an_include_related_file_is_not_said_to_be_left_unchanged() {
let m = "module m (input logic clk);\nendmodule\n";
let n = "module n (input logic clk);\n m u_m (.clk(clk));\nendmodule\n";
let all = "`include \"m.sv\"\n`include \"n.sv\"\n";
let files = workspace(&[("m.sv", m), ("n.sv", n), ("all.sv", all)]);
let at = m.find("module m").expect("decl") as u32 + 7;
let edit = rename(&files, &PathBuf::from("/rtl/m.sv"), at, "m2").expect("renames");
assert_eq!(edit.edits_for(&PathBuf::from("/rtl/n.sv")).len(), 1, "the instantiation moves");
let left = edit.warnings.iter().any(|w| w.contains("n.sv:2") && w.contains("left unchanged"));
assert!(!left, "{:#?}", edit.warnings);
}
+16 -6
View File
@@ -80,10 +80,10 @@ impl<'a> Binder<'a> {
// `super.b` go to the enclosing class instead, and a spine that
// starts at one of them stops there: `this.a.b` records `a` and
// nothing more (`this` is not a name this crate binds, so there
// is no head to walk from). An indexed or called head
// (`a[i].b`, `f().b`) still resolves its own head and stops:
// chasing those needs the element type of a container, which
// this crate does not model (TODO.md §15).
// is no head to walk from). A called head (`f().b`) still
// resolves its own head and stops. An **indexed** link
// (`g_lane[0].lane_q`, `u_x.g[1].sig`) is walked as the name it
// indexes — see [`spine`] for why that is never a wrong answer.
ExprKind::Member { base, name, .. } => match &base.kind {
ExprKind::Ident(head) if head == "this" => {
self.use_member(scope, name, member_tail(e.span, name), Target::ThisMember)
@@ -240,8 +240,17 @@ impl<'a> Binder<'a> {
/// identifier it starts at, and the members already selected from it, in the
/// order they are written (`a.b.c`'s tail `c` gives `("a", ["b"])`).
///
/// `None` for a spine this crate cannot start walking — an index, a call, a
/// cast, or `this`/`super`, which name no declaration to take a type from.
/// An element select is transparent: `g[0].x` walks as `g.x`. Every link the
/// walk can continue from is one an index selects *another of the same* from
/// — a generate block (an element of a `for` generate is an instance of the
/// same block, IEEE 1800 §27.4), or a declaration whose recorded type is the
/// element's (a packed array of a struct). An unpacked declarator records no
/// type at all (`declare_typed`), and an instance array none either, so
/// `q[i].m` and `u[0].sig` still stop at their head exactly as before.
///
/// `None` for a spine this crate cannot start walking — a call, a cast, a
/// part select, or `this`/`super`, which name no declaration to take a type
/// from.
fn spine(base: &Expr) -> Option<(String, Vec<String>)> {
let mut mids = Vec::new();
let mut current = base;
@@ -256,6 +265,7 @@ fn spine(base: &Expr) -> Option<(String, Vec<String>)> {
mids.push(name.clone());
current = base;
}
ExprKind::Index { base, .. } => current = base,
_ => return None,
}
}
+78
View File
@@ -0,0 +1,78 @@
//! Generate constructs: `if`/`case`/`for` generate and the blocks they own.
//!
//! A generate block's **label is declared in the scope the construct is
//! written in** (IEEE 1800 §27.3–27.5): `g_lane` of `for (…) begin : g_lane`
//! is a name of the enclosing module, which is what lets `g_lane[0].lane_q`
//! written beside the loop resolve its head at all. The loop's genvar is
//! not — it lives in a header scope of its own, and the block's body sees it
//! because the body's scope is opened *inside* that header. So a labelled
//! `for` block is the one declaration whose name and whose body sit in two
//! different scopes (`docs/features/generate-label-rename/README.md`).
use vlog_parser::ast::*;
use vlog_parser::span::TextRange;
use crate::model::{ScopeId, ScopeKind, SymbolKind};
use super::Binder;
impl<'a> Binder<'a> {
pub(super) fn bind_gen_if(&mut self, g: &'a GenIf, scope: ScopeId) {
self.bind_expr(&g.cond, scope);
self.bind_gen_block(&g.then, scope);
match g.els.as_deref() {
Some(GenElse::If(_, inner)) => self.bind_gen_if(inner, scope),
Some(GenElse::Block(b)) => self.bind_gen_block(b, scope),
None => {}
}
}
pub(super) fn bind_gen_for(&mut self, g: &'a GenFor, span: TextRange, scope: ScopeId) {
// The loop header opens a scope of its own so that `for (genvar i...)`
// does not leak `i` into the enclosing module.
let header = self.new_scope(ScopeKind::Generate, scope, span);
match (g.init_genvar, &g.init.lhs.kind) {
// `for (genvar i = 0; ...)` declares; `for (i = 0; ...)` uses a
// `genvar i;` written outside the loop.
(true, ExprKind::Ident(name)) => {
self.declare(header, name, SymbolKind::Genvar, g.init.lhs.span, g.init.lhs.span);
}
_ => self.bind_expr(&g.init.lhs, header),
}
self.bind_expr(&g.init.rhs, header);
self.bind_expr(&g.cond, header);
match &g.step {
ForStep::Assign(a) => {
self.bind_expr(&a.lhs, header);
self.bind_expr(&a.rhs, header);
}
ForStep::Expr(e) => self.bind_expr(e, header),
}
self.bind_gen_body(&g.body, scope, header);
}
/// A generate block whose label, if any, is declared in `scope` and whose
/// body is opened there too — every generate block but a `for` loop's.
pub(super) fn bind_gen_block(&mut self, b: &'a GenBlock, scope: ScopeId) {
self.bind_gen_body(b, scope, scope);
}
/// One generate block: the label declared in `declared_in`, the body's
/// scope opened inside `parent`. The two differ only for a `for` loop,
/// whose body must see the header's genvar.
fn bind_gen_body(&mut self, b: &'a GenBlock, declared_in: ScopeId, parent: ScopeId) {
let label = match (&b.label, b.label_span) {
(Some(label), Some(ls)) => {
self.declare(declared_in, label, SymbolKind::Block, ls, b.span)
}
_ => None,
};
let inner = self.new_scope(ScopeKind::Generate, parent, b.span);
if let Some(sym) = label {
self.symbols[sym.0 as usize].child_scope = Some(inner);
self.scopes[inner.0 as usize].owner = Some(sym);
}
self.bind_items(&b.items, inner);
self.use_end_label(declared_in, inner, b.end_label.as_ref(), b.end_label_span);
}
}
+9 -59
View File
@@ -1,7 +1,7 @@
//! The item-level walk: a file or fragment, the `ItemKind` dispatch, modules
//! and interfaces (header, ports, modports, clocking blocks), packages and
//! imports, instantiations and `bind`, generate constructs, functions and
//! tasks. Every item that declares a typed name hands the name to `decl` and
//! imports, instantiations and `bind`, functions and tasks (generate
//! constructs are `generate`'s). Every item that declares a typed name hands the name to `decl` and
//! every body to `stmt`; what stays here is the shape of the item and the
//! scope it opens.
@@ -124,10 +124,10 @@ impl<'a> Binder<'a> {
self.declare(scope, &name.text, SymbolKind::Genvar, name.span, item.span);
}
}
ItemKind::GenerateRegion { items, .. } => {
let inner = self.new_scope(ScopeKind::Generate, scope, item.span);
self.bind_items(items, inner);
}
// `generate … endgenerate` is not a scope (IEEE 1800 §27.3): what
// it holds is declared in the enclosing module, which is where a
// block label written inside it must be found from.
ItemKind::GenerateRegion { items, .. } => self.bind_items(items, scope),
// A bare `begin … end` where an item belongs: bound as the
// unnamed generate scope an unlabeled `if` arm's block gets.
ItemKind::GenBlock(b) => self.bind_gen_block(b, scope),
@@ -396,56 +396,6 @@ impl<'a> Binder<'a> {
self.bind_opt_expr(c.expr.as_ref(), scope);
}
fn bind_gen_if(&mut self, g: &'a GenIf, scope: ScopeId) {
self.bind_expr(&g.cond, scope);
self.bind_gen_block(&g.then, scope);
match g.els.as_deref() {
Some(GenElse::If(_, inner)) => self.bind_gen_if(inner, scope),
Some(GenElse::Block(b)) => self.bind_gen_block(b, scope),
None => {}
}
}
fn bind_gen_for(&mut self, g: &'a GenFor, span: TextRange, scope: ScopeId) {
// The loop header opens a scope of its own so that `for (genvar i...)`
// does not leak `i` into the enclosing module.
let header = self.new_scope(ScopeKind::Generate, scope, span);
match (g.init_genvar, &g.init.lhs.kind) {
// `for (genvar i = 0; ...)` declares; `for (i = 0; ...)` uses a
// `genvar i;` written outside the loop.
(true, ExprKind::Ident(name)) => {
self.declare(header, name, SymbolKind::Genvar, g.init.lhs.span, g.init.lhs.span);
}
_ => self.bind_expr(&g.init.lhs, header),
}
self.bind_expr(&g.init.rhs, header);
self.bind_expr(&g.cond, header);
match &g.step {
ForStep::Assign(a) => {
self.bind_expr(&a.lhs, header);
self.bind_expr(&a.rhs, header);
}
ForStep::Expr(e) => self.bind_expr(e, header),
}
self.bind_gen_block(&g.body, header);
}
fn bind_gen_block(&mut self, b: &'a GenBlock, scope: ScopeId) {
let inner = match (&b.label, b.label_span) {
(Some(label), Some(ls)) => self.declare_with_scope(
scope,
label,
SymbolKind::Block,
ls,
b.span,
ScopeKind::Generate,
),
_ => self.new_scope(ScopeKind::Generate, scope, b.span),
};
self.bind_items(&b.items, inner);
self.use_end_label(scope, inner, b.end_label.as_ref(), b.end_label_span);
}
fn bind_function(&mut self, f: &'a FunctionDecl, span: TextRange, scope: ScopeId) {
if !f.scope.is_empty() {
// An out-of-body definition binds into its class's scope, which
@@ -605,9 +555,9 @@ impl<'a> Binder<'a> {
/// connection in the scope the directive is written in, which is not the
/// scope it elaborates in.
///
/// An indexed segment (`gen[0]`) keeps only its name: the index has no record
/// of a generate block, so such a path answers nothing either way, and a
/// spelling the user can recognize is what the warning needs.
/// An indexed segment (`gen[0]`) keeps only its name: a generate block is on
/// its module's hierarchical surface, and an index into a generate array
/// selects an instance of the same block, so the name is the whole hop.
fn bind_target_path(b: &BindDirective) -> Option<String> {
let mut out = String::new();
for seg in &b.target {
+25 -6
View File
@@ -7,14 +7,16 @@
//! plumbing — opening a scope, declaring a name, recording a use, an end
//! label, a derived span checked against the source. The walk itself is one
//! sibling per grammar domain, each an `impl Binder` block: `item` (the
//! item-level walk), `decl` (declared names and their types), `class`
//! (classes, constraints, out-of-body definitions), `cover` (covergroups),
//! `stmt`, `sva` (assertions) and `expr`.
//! item-level walk), `generate` (generate constructs and their blocks),
//! `decl` (declared names and their types), `class` (classes, constraints,
//! out-of-body definitions), `cover` (covergroups), `stmt`, `sva`
//! (assertions) and `expr`.
mod class;
mod cover;
mod decl;
mod expr;
mod generate;
mod item;
mod stmt;
mod sva;
@@ -222,7 +224,15 @@ impl<'a> Binder<'a> {
first,
scope,
});
self.use_name(scope, name, name_span, Target::Lexical);
// A redeclaration names the first declaration — unless exactly one
// of the two is a block label. Two arms of one generate `if`
// carrying one label are one label; a label spelled like a net of
// the same scope is a collision (`duplicate-declaration`), and
// counting it as a *use* of the net would call the net read.
let first_is_block = self.symbols[first.0 as usize].kind == SymbolKind::Block;
if first_is_block == (kind == SymbolKind::Block) {
self.use_name(scope, name, name_span, Target::Lexical);
}
return None;
}
let id = SymbolId(self.symbols.len() as u32);
@@ -347,8 +357,17 @@ impl<'a> Binder<'a> {
return;
};
// `None` when the declaration was a redeclaration and bound no symbol
// of its own; the label is then left unrecorded, as it was before.
let Some(sym) = self.scopes[body.0 as usize].owner else {
// of its own; the label is then left unrecorded, as it was before —
// except for a block. Two arms of one generate `if`/`case` may carry
// the same label (IEEE 1800 §27.5), and the second arm's opening label
// is already a use of the first declaration; its closing label is the
// same name and must be the same use, or a rename rewrites one of the
// pair and leaves `end : old` closing `begin : new`.
let owner = self.scopes[body.0 as usize].owner.or_else(|| {
let first = *self.scopes[scope.0 as usize].names.get(label)?;
(self.symbols[first.0 as usize].kind == SymbolKind::Block).then_some(first)
});
let Some(sym) = owner else {
return;
};
if self.symbols[sym.0 as usize].name != *label {
+9 -1
View File
@@ -156,7 +156,15 @@ use crate::workspace::{
/// though the `bind` file did not mention it — for exactly the files it had
/// cached, which is the half-right answer every one of these bumps exists to
/// prevent. See `docs/features/rename-bind-occurrences/README.md`.
pub const FACTS_FORMAT: u32 = 20;
/// 20 → 21 (2026-09-30, generate-label-rename): no new field, but new records
/// and different answers in the old fields — a named block is a member on its
/// module's hierarchical surface, its own members are recorded under the
/// synthesized `module.label` key, and a path through a block
/// (`u_x.g_lane[0].lane_q`) is an external reference where it recorded
/// nothing. A 0.59.0 store would answer find-references and the rename of a
/// block label as though no other file named it. See
/// `docs/features/generate-label-rename/README.md`.
pub const FACTS_FORMAT: u32 = 21;
impl FileFacts {
/// These facts as one line's worth of fields, tab-separated.
+34
View File
@@ -282,6 +282,40 @@ impl Semantics {
out
}
/// The key the workspace index files the members of `scope` under: the
/// name of the declaration that owns it, or — for a named block — the key
/// of the scope the block is declared in and the label, joined by a `.`
/// (`sub.g_lane`, `sub.g_a.g_b`).
///
/// How a caller holding one file's analysis asks the index about one of
/// its members: `member_in(key, name, …)`. `None` for a scope nobody owns
/// (an unnamed `begin`), whose members the index does not hold.
///
/// A block inside a function or task is on no cross-file surface — the
/// index never files it — and its key is qualified by the enclosing unit
/// and marked as the subroutine's (`m.ff().fb`), so it can never be the
/// key a module `ff`'s block `fb` is filed under (QA F4).
pub fn member_key(&self, scope: ScopeId) -> Option<String> {
let owner = self.scope(scope)?.owner.and_then(|id| self.symbol(id))?;
if owner.kind != SymbolKind::Block {
return Some(owner.name.clone());
}
Some(format!("{}.{}", self.block_parent_key(owner.scope)?, owner.name))
}
/// The key part a block declared in `scope` hangs off: the enclosing
/// block's or unit's key, or — inside a function or task — the unit's key
/// and the subroutine's name with `()`, which no index key spells.
fn block_parent_key(&self, scope: ScopeId) -> Option<String> {
let owner = self.scope(scope)?.owner.and_then(|id| self.symbol(id))?;
match owner.kind {
SymbolKind::Function | SymbolKind::Task => {
Some(format!("{}.{}()", self.member_key(owner.scope)?, owner.name))
}
_ => self.member_key(scope),
}
}
/// How many uses resolved to a declaration in this file, out of how many
/// were recorded. The corpus test reports the ratio as an honest baseline.
pub fn resolution_counts(&self) -> (usize, usize) {
+9 -5
View File
@@ -199,7 +199,7 @@ fn type_member(
/// `None` — no reference recorded at all — whenever this crate has nothing to
/// say, which is the shape every pre-2026-09-01 hierarchical name had: a head
/// nothing in this file declares, a head that is neither typed nor a unit a
/// hierarchical name may start at (a `logic [3:0]`, a block label, a
/// hierarchical name may start at (a `logic [3:0]`, a genvar, a
/// built-in), a type **this file declares** as something with no members to
/// search (a struct or enum typedef — see [`TypeHere::NotAUnit`]), or a
/// member genuinely absent from a class this file declares whole. Recording a
@@ -428,8 +428,9 @@ fn unit_scope(scopes: &[Scope], symbols: &[Symbol], from: ScopeId, unit: &str) -
/// which is how `tb.dut.u_core.sig` reaches into `tb` (IEEE 1800 §23.6: a
/// top-level module name is the root of a hierarchical path), or a class,
/// where the answer can only ever be that very class's own member. Everything
/// else — a `logic` net, a genvar, a block label, a package — answers `None`,
/// which stops the chain.
/// else — a `logic` net, a genvar, a package — answers `None`, which stops
/// the chain. A block label has no type either, and opens its own scope the
/// way a module does.
fn link_type(scopes: &[Scope], symbols: &[Symbol], id: SymbolId) -> Option<MemberSite> {
let symbol = symbols.get(id.0 as usize)?;
let Some(type_name) = symbol.type_name.as_deref() else {
@@ -638,8 +639,10 @@ fn container_scope(symbols: &[Symbol], id: SymbolId) -> Option<ScopeId> {
/// The scope a symbol opens when a `.` may name its members: a class, a
/// module, or an interface — which is what makes `vif.sig` and `u.internal`
/// reach into one — **or** a `struct`/`union` body, whoever names it. A
/// package is a container to pass through, never a thing a handle can be.
/// reach into one — a named block, which is what `g_lane[0].lane_q` and
/// `blk.tmp` reach into (IEEE 1800 §23.6), **or** a `struct`/`union` body,
/// whoever names it. A package is a container to pass through, never a thing
/// a handle can be.
///
/// The struct half is deliberately written as "any symbol whose child scope is
/// a struct body", not "a `Typedef` whose child scope is one": the same rule
@@ -651,6 +654,7 @@ fn member_scope(scopes: &[Scope], symbols: &[Symbol], id: SymbolId) -> Option<Sc
let symbol = symbols.get(id.0 as usize)?;
if symbol.kind == SymbolKind::Class
|| symbol.kind == SymbolKind::Covergroup
|| symbol.kind == SymbolKind::Block
|| symbol.kind.is_instantiable()
{
return symbol.child_scope;
@@ -49,6 +49,14 @@ use super::{Def, WorkspaceIndex};
/// It gains its instances hierarchically for the same hop reason, and nothing
/// else moves.
///
/// A **named generate block** (and a named procedural block) is on its
/// module's or interface's hierarchical surface, and has only that surface
/// itself: `u_x.g_lane[0].lane_q` names the block and then its variable
/// (§23.6, §27.4), and no connection list can name either. What a block
/// exports is what a path may select from it — its nets, variables, instances,
/// parameters and nested blocks — under the synthesized key
/// `record::block_key` gives it.
///
/// A `typedef struct`/`union` exports its fields, and a field that is itself
/// an inline aggregate exports its own — which is what a generated register
/// package is: `reg2hw_t` → `ctrl` → `q`. A covergroup's surface is its
@@ -80,7 +88,9 @@ pub(super) fn surface_of(unit: SymbolKind, member: SymbolKind) -> Option<Surface
| SymbolKind::LocalParam
| SymbolKind::Property
| SymbolKind::Sequence => Some(Surface::Connection),
SymbolKind::Net | SymbolKind::Var | SymbolKind::Instance => Some(Surface::Hierarchical),
SymbolKind::Net | SymbolKind::Var | SymbolKind::Instance | SymbolKind::Block => {
Some(Surface::Hierarchical)
}
_ => None,
},
SymbolKind::Typedef | SymbolKind::StructMember => {
@@ -101,7 +111,16 @@ pub(super) fn surface_of(unit: SymbolKind, member: SymbolKind) -> Option<Surface
| SymbolKind::Task
| SymbolKind::Modport
| SymbolKind::Clocking => Some(Surface::Connection),
SymbolKind::Instance => Some(Surface::Hierarchical),
SymbolKind::Instance | SymbolKind::Block => Some(Surface::Hierarchical),
_ => None,
},
SymbolKind::Block => match member {
SymbolKind::Net
| SymbolKind::Var
| SymbolKind::Instance
| SymbolKind::Block
| SymbolKind::Param
| SymbolKind::LocalParam => Some(Surface::Hierarchical),
_ => None,
},
_ => None,
+19 -3
View File
@@ -501,7 +501,7 @@ fn collect_members(
continue;
}
let mut decl = Decl::member(member, lines, surface);
let nested = nested_key(key, member);
let nested = nested_key(key, member).or_else(|| block_key(key, member));
if let Some(nested) = &nested {
decl.type_name = Some(nested.clone());
}
@@ -511,8 +511,9 @@ fn collect_members(
// *class's* name — register them there too. A struct `typedef` nested
// in a package is the same shape, an inline aggregate member is the
// same shape under its synthesized key, and so is a covergroup, whose
// labelled coverpoints `cg_inst.cp` reaches. The scope tree is
// acyclic, so this recursion terminates.
// labelled coverpoints `cg_inst.cp` reaches. A named block is the
// inline-aggregate shape: no type name, so a synthesized key. The
// scope tree is acyclic, so this recursion terminates.
if matches!(member.kind, SymbolKind::Class | SymbolKind::Typedef | SymbolKind::Covergroup) {
collect_members(sem, &member.name, member, lines, out);
} else if let Some(nested) = nested {
@@ -543,6 +544,21 @@ fn nested_key(key: &str, member: &Symbol) -> Option<String> {
.then(|| format!("{key}.{}", member.name))
}
/// The member-table key a **named block**'s own members are registered under,
/// and the `type_name` the block's [`Def`] carries so that a path's next hop
/// finds them: the container's key and the label, joined by a `.` —
/// [`nested_key`]'s spelling, for [`nested_key`]'s reasons. A block's label is
/// no type name, and the bare label would collide across every module that
/// writes a `gen_generic` or a `g_lane`; the dotted one is unwritable as a
/// unit name and unique per module (`docs/features/generate-label-rename`).
///
/// Shared with [`crate::Semantics::member_key`], which is how a caller holding
/// one file's analysis names the same table.
fn block_key(key: &str, member: &Symbol) -> Option<String> {
(member.kind == SymbolKind::Block && member.child_scope.is_some())
.then(|| format!("{key}.{}", member.name))
}
/// Parse one file and read its `` `define`` table off the same token stream.
fn parse_and_collect(src: &str) -> (vlog_parser::ast::SourceFile, DefineTable, Census) {
match tokenize(src) {
@@ -0,0 +1,231 @@
//! Named blocks as places a path reaches through (TODO §65.1): a generate
//! block's label is declared where the construct is written, an index into a
//! generate array is walked as the block itself, and a module's blocks and
//! their members are on its hierarchical surface in the workspace index.
//! `docs/features/generate-label-rename/README.md`.
use std::path::PathBuf;
use vlog_parser::parse_source_tolerant;
use vlog_semantic::{
analyze, resolve_external, ExternalTarget, Resolution, Semantics, Surface, SymbolKind,
WorkspaceIndex,
};
fn sem(src: &str) -> Semantics {
let (file, _) = parse_source_tolerant(src);
analyze(&file, src)
}
/// Offset of the `n`th (0-based) occurrence of `needle`, plus `skip` bytes.
fn at(src: &str, needle: &str, n: usize, skip: usize) -> u32 {
(src.match_indices(needle).nth(n).expect("occurrence must exist").0 + skip) as u32
}
fn resolution(s: &Semantics, offset: u32) -> Resolution {
s.reference_at(offset).unwrap_or_else(|| panic!("no reference at {offset}")).resolution.clone()
}
fn declared(s: &Semantics, src: &str, needle: &str, skip: usize) -> Resolution {
let id = s.symbol_at(at(src, needle, 0, skip)).expect("a declaration there");
Resolution::Resolved(id)
}
const LOOP: &str = "module fsm (output logic busy);
for (genvar gi = 0; gi < 2; gi++) begin : g_lane
logic lane_q;
end : g_lane
assign busy = g_lane[0].lane_q | g_lane[gi].lane_q;
endmodule
";
#[test]
fn a_for_generate_label_is_a_name_of_the_enclosing_module_and_its_genvar_is_not() {
let s = sem(LOOP);
let label = declared(&s, LOOP, "begin : g_lane", 8);
assert_eq!(resolution(&s, at(LOOP, "g_lane[0]", 0, 0)), label);
assert_eq!(resolution(&s, at(LOOP, "end : g_lane", 0, 6)), label, "the closing label");
assert_eq!(resolution(&s, at(LOOP, "g_lane[gi]", 0, 0)), label);
assert_eq!(resolution(&s, at(LOOP, "[gi]", 0, 1)), Resolution::NotFound, "no genvar leak");
let lane_q = declared(&s, LOOP, "logic lane_q", 6);
assert_eq!(resolution(&s, at(LOOP, ".lane_q", 0, 1)), lane_q, "through the index");
assert_eq!(resolution(&s, at(LOOP, ".lane_q", 1, 1)), lane_q);
}
#[test]
fn a_nested_block_is_reached_through_its_parent_and_an_index() {
let src = "module n (output logic o);
if (1) begin : g_a
for (genvar j = 0; j < 4; j++) begin : g_b
logic x;
end
end
assign o = g_a.g_b[2].x;
endmodule
";
let s = sem(src);
assert_eq!(resolution(&s, at(src, "g_a.g_b", 0, 4)), declared(&s, src, "begin : g_b", 8));
assert_eq!(resolution(&s, at(src, "[2].x", 0, 4)), declared(&s, src, "logic x", 6));
}
#[test]
fn a_generate_region_is_not_a_scope() {
let src = "module r (output logic o);
generate
if (1) begin : g_in
logic q;
end
wire w;
endgenerate
assign o = g_in.q | w;
endmodule
";
let s = sem(src);
assert_eq!(resolution(&s, at(src, "g_in.q", 0, 0)), declared(&s, src, "begin : g_in", 8));
assert_eq!(resolution(&s, at(src, "| w", 0, 2)), declared(&s, src, "wire w", 5));
}
#[test]
fn both_arms_of_a_generate_if_are_one_label_closing_labels_included() {
let src = "module d (output logic o);
if (1) begin : g
logic q;
end : g
else begin : g
logic q;
end : g
assign o = g.q;
endmodule
";
let s = sem(src);
let first = declared(&s, src, "begin : g", 8);
for (needle, n) in [("begin : g", 1), ("end : g", 0), ("end : g", 1)] {
let skip = needle.len() - 1;
assert_eq!(resolution(&s, at(src, needle, n, skip)), first, "{needle} #{n}");
}
}
#[test]
fn a_prefix_statement_label_owns_its_closing_label() {
let src = "module p;\n initial lbl: begin\n disable lbl;\n end : lbl\nendmodule\n";
let s = sem(src);
let label = declared(&s, src, "lbl:", 0);
assert_eq!(resolution(&s, at(src, "disable lbl", 0, 8)), label);
assert_eq!(resolution(&s, at(src, "end : lbl", 0, 6)), label);
}
#[test]
fn an_index_is_walked_only_where_the_link_has_members_of_its_own() {
let src = "module t (output logic o);
typedef struct packed { logic f; } pkt_t;
pkt_t [1:0] packed_arr;
pkt_t unpacked_arr [2];
assign o = packed_arr[0].f | unpacked_arr[1].f;
endmodule
";
let s = sem(src);
assert_eq!(resolution(&s, at(src, "[0].f", 0, 4)), declared(&s, src, "logic f", 6));
assert!(s.reference_at(at(src, "[1].f", 0, 4)).is_none(), "an unpacked element is untyped");
}
#[test]
fn a_blocks_member_key_is_its_modules_and_its_labels() {
let src = "module sub;\n if (1) begin : g_a\n if (1) begin : g_b\n logic x;\n end\n end\nendmodule\n";
let s = sem(src);
let key_of = |name: &str| {
let id = s.symbols_named(name).next().expect("declared");
s.symbol(id).and_then(|sym| s.member_key(sym.scope))
};
assert_eq!(key_of("g_a").as_deref(), Some("sub"));
assert_eq!(key_of("g_b").as_deref(), Some("sub.g_a"));
assert_eq!(key_of("x").as_deref(), Some("sub.g_a.g_b"));
}
const SUB: &str = "module sub (input logic clk);
for (genvar i = 0; i < 2; i++) begin : g_lane
logic sig;
if (1) begin : g_in
logic deep;
end
end
endmodule
";
const TOP: &str = "module top (output logic o);
sub u_x (.clk(1'b0));
assign o = u_x.g_lane[1].sig | u_x.g_lane[0].g_in.deep;
endmodule
";
fn index() -> WorkspaceIndex {
WorkspaceIndex::build([("sub.sv", SUB), ("top.sv", TOP)].map(|(p, s)| (PathBuf::from(p), s)))
}
/// The one declaration the overlay answers the reference at `offset` with,
/// as `(kind, the name it spells in SUB)`.
fn external(s: &Semantics, ws: &WorkspaceIndex, offset: u32) -> (SymbolKind, String) {
let overlay = resolve_external(s, ws);
let id = s.reference_id_at(offset).expect("a reference there");
match overlay.get(id) {
Some(ExternalTarget::Resolved(def)) => {
(def.kind, SUB[def.name_span.as_range()].to_string())
}
other => panic!("not resolved: {other:?}"),
}
}
#[test]
fn a_path_from_another_file_reaches_the_block_and_its_members() {
let ws = index();
let s = sem(TOP);
let block = (SymbolKind::Block, "g_lane".to_string());
assert_eq!(external(&s, &ws, at(TOP, "u_x.g_lane", 0, 4)), block);
assert_eq!(external(&s, &ws, at(TOP, "u_x.g_lane", 1, 4)), block);
assert_eq!(external(&s, &ws, at(TOP, ".sig", 0, 1)), (SymbolKind::Var, "sig".to_string()));
assert_eq!(external(&s, &ws, at(TOP, ".g_in", 0, 1)), (SymbolKind::Block, "g_in".into()));
assert_eq!(external(&s, &ws, at(TOP, ".deep", 0, 1)), (SymbolKind::Var, "deep".into()));
}
#[test]
fn a_block_and_its_members_are_hierarchical_only_under_the_dotted_key() {
let ws = index();
assert!(ws.member("sub", "g_lane").is_empty(), "no connection list can name a block");
assert_eq!(ws.member_in("sub", "g_lane", Surface::Hierarchical).len(), 1);
assert_eq!(ws.member_in("sub.g_lane", "sig", Surface::Hierarchical).len(), 1);
assert_eq!(ws.member_in("sub.g_lane.g_in", "deep", Surface::Hierarchical).len(), 1);
assert!(
ws.member_in("g_lane", "sig", Surface::Hierarchical).is_empty(),
"never the bare label"
);
let held: Vec<&str> = ws.hierarchical_declarations("g_lane").map(|(unit, _)| unit).collect();
assert_eq!(held, vec!["sub"]);
}
#[test]
fn an_unnamed_block_declares_nothing_a_path_can_name() {
let src = "module u (output logic o);\n if (1) begin\n logic w;\n end\n assign o = genblk1.w;\nendmodule\n";
let s = sem(src);
assert_eq!(resolution(&s, at(src, "genblk1", 0, 0)), Resolution::NotFound);
assert!(s.reference_at(at(src, "genblk1.w", 0, 8)).is_none());
assert!(s.symbols_named("genblk1").next().is_none(), "no symbol is invented for it");
}
/// QA F3: a block label that collides with a net of its scope is a duplicate
/// and **not** a use of the first declaration, either way round; two arms
/// sharing a label still are one label.
#[test]
fn a_block_label_beside_a_same_named_net_is_a_duplicate_and_not_a_use() {
let net_first = "module c;\n wire g;\n if (1) begin : g\n end : g\nendmodule\n";
let s = sem(net_first);
assert_eq!(s.duplicates().len(), 1);
let net = s.symbols_named("g").next().expect("the net");
assert_eq!(s.symbol(net).map(|x| x.kind), Some(SymbolKind::Net));
assert!(s.references_of(net).is_empty(), "the label is not a read of the net");
let block_first = "module c;\n if (1) begin : g\n end : g\n wire g;\nendmodule\n";
let s = sem(block_first);
assert_eq!(s.duplicates().len(), 1);
let block = s.symbols_named("g").next().expect("the block");
let uses: Vec<u32> = s.references_of(block).iter().map(|r| r.name_span.start).collect();
assert_eq!(uses, vec![at(block_first, "end : g", 0, 6)], "only its closing label");
}
+7 -1
View File
@@ -197,7 +197,6 @@ endmodule
for (spelling, why) in [
("x.bit_field", "a built-in type names no declaration"),
("stranger.thing", "the head is not declared here"),
("blk.inner", "a generate block label is not a type this crate models"),
("h.absent", "the class is known whole and has no such member"),
] {
assert!(s.reference_at(tail(src, spelling, 0)).is_none(), "{spelling}: {why}");
@@ -207,6 +206,13 @@ endmodule
resolution_at(&s, tail(src, "h.known", 0)),
Resolution::Resolved(symbol_named(&s, "known"))
);
// A generate block label was on the list above until TODO §65.1: a named
// block opens a scope a path may select from (IEEE 1800 §23.6), so its
// member resolves (`docs/features/generate-label-rename/README.md`).
assert_eq!(
resolution_at(&s, tail(src, "blk.inner", 0)),
Resolution::Resolved(symbol_named(&s, "inner"))
);
}
/// `this.x` walks the `extends` chain as far as this file declares it.
@@ -0,0 +1,300 @@
//! QA attacks on TODO §65.1's scope rules (a generate label declared in the
//! enclosing scope, `generate … endgenerate` not a scope, a block's member
//! scope, an index transparent in a path's spine).
//! `docs/features/generate-label-rename/README.md`, QA log 2026-09-30.
use vlog_parser::parse_source_tolerant;
use vlog_semantic::{analyze, Resolution, Semantics};
fn sem(src: &str) -> Semantics {
let (file, _) = parse_source_tolerant(src);
analyze(&file, src)
}
/// Offset of the `n`th (0-based) occurrence of `needle`, plus `skip` bytes.
fn at(src: &str, needle: &str, n: usize, skip: usize) -> u32 {
(src.match_indices(needle).nth(n).expect("occurrence must exist").0 + skip) as u32
}
fn resolution(s: &Semantics, offset: u32) -> Option<Resolution> {
s.reference_at(offset).map(|r| r.resolution.clone())
}
fn declared(s: &Semantics, src: &str, needle: &str, n: usize, skip: usize) -> Option<Resolution> {
let id = s.symbol_at(at(src, needle, n, skip)).expect("a declaration there");
Some(Resolution::Resolved(id))
}
#[test]
fn a_genvar_never_leaks_even_past_a_module_signal_of_its_name() {
let src = "module g (output logic o, output logic p);
logic i;
for (genvar i = 0; i < 2; i++) begin : g_l
logic q;
assign q = i[0];
end
assign o = i;
assign p = g_l[1].q;
endmodule
";
let s = sem(src);
assert_eq!(resolution(&s, at(src, "o = i", 0, 4)), declared(&s, src, "logic i", 0, 6));
assert_eq!(resolution(&s, at(src, "q = i", 0, 4)), declared(&s, src, "genvar i", 0, 7));
assert_eq!(resolution(&s, at(src, "g_l[1]", 0, 0)), declared(&s, src, ": g_l", 0, 2));
}
#[test]
fn a_member_lookup_through_a_block_never_climbs_to_the_enclosing_scope() {
// `g_l[0].clk` names a `clk` *inside* the block; there is none, so the
// module's port must never be the answer (a rename of `clk` would then
// rewrite a path that meant something else).
let src = "module m (input logic clk, output logic o, output logic p);
for (genvar i = 0; i < 2; i++) begin : g_l
logic q;
end
if (1) begin : g_b
logic r;
end
assign o = g_l[0].clk;
assign p = g_b.clk;
endmodule
";
let s = sem(src);
let port = declared(&s, src, "logic clk", 0, 6);
for (needle, n) in [(".clk", 0), (".clk", 1)] {
let got = resolution(&s, at(src, needle, n, 1));
assert_ne!(got, port, "{needle} #{n} climbed to the module port: {got:?}");
}
}
#[test]
fn an_unnamed_generate_if_hides_its_declarations_and_a_region_does_not() {
let src = "module u (output logic o, output logic p);
generate
wire in_region;
if (1) begin
wire hidden;
end
begin
wire in_bare;
end
endgenerate
assign o = in_region;
assign p = hidden | in_bare;
endmodule
";
let s = sem(src);
assert_eq!(
resolution(&s, at(src, "o = in_region", 0, 4)),
declared(&s, src, "wire in_r", 0, 5)
);
for (needle, decl) in [("p = hidden", "wire hidden"), ("| in_bare", "wire in_bare")] {
let got = resolution(&s, at(src, needle, 0, needle.find(' ').unwrap_or(0) + 3));
assert_ne!(got, declared(&s, src, decl, 0, 5), "{needle} saw into an unnamed block");
}
}
#[test]
fn a_block_label_named_like_a_module_is_the_lexical_answer() {
// IEEE 1800 §23.8: a name is looked up in the enclosing scopes before it
// is taken as a top-level module name.
let src = "module sub;
logic x;
endmodule
module m (output logic o);
if (1) begin : sub
logic x;
end
assign o = sub.x;
endmodule
";
let s = sem(src);
assert_eq!(resolution(&s, at(src, "sub.x", 0, 0)), declared(&s, src, ": sub", 0, 2));
assert_eq!(resolution(&s, at(src, "sub.x", 0, 4)), declared(&s, src, "logic x", 1, 6));
}
#[test]
fn an_element_select_never_resolves_to_a_declaration_of_another_type() {
let src = "module t (output logic o);
typedef struct packed { logic f; } pkt_t;
typedef struct packed { logic f; } other_t;
typedef pkt_t [1:0] vec_t;
pkt_t [1:0][1:0] two_d;
vec_t v;
logic [3:0] bits;
other_t f;
assign o = two_d[0][1].f | v[1].f | bits[0].f;
endmodule
";
let s = sem(src);
let pkt_f = declared(&s, src, "logic f", 0, 6);
assert_eq!(resolution(&s, at(src, "[1].f |", 0, 4)), pkt_f, "a 2-D packed array of pkt_t");
assert_eq!(resolution(&s, at(src, "v[1].f", 0, 5)), pkt_f, "through a packed-array typedef");
let got = resolution(&s, at(src, "bits[0].f", 0, 8));
assert!(
!matches!(got, Some(Resolution::Resolved(_))),
"`bits[0].f` has no field to name: {got:?}"
);
}
#[test]
fn an_index_through_a_class_queue_or_an_instance_array_is_not_a_wrong_answer() {
let src = "class item;
int m;
endclass
module leaf (output logic sig);
endmodule
module t (output logic o);
int m;
logic sig;
item q[$];
leaf u_arr [2] (.sig());
initial o = q[0].m == 0;
assign o = u_arr[1].sig;
endmodule
";
let s = sem(src);
let got = resolution(&s, at(src, "q[0].m", 0, 5));
assert_ne!(got, declared(&s, src, "int m", 1, 4), "the module's `m`: {got:?}");
let got = resolution(&s, at(src, "u_arr[1].sig", 0, 9));
assert_ne!(got, declared(&s, src, "logic sig", 1, 6), "the module's `sig`: {got:?}");
}
#[test]
fn a_procedural_block_in_a_function_is_one_label_with_disable_and_end() {
let src = "module f;
function automatic int ff(int a);
begin : fb
if (a == 0) disable fb;
ff = a;
end : fb
endfunction
task automatic tt();
fork : fk
join_none : fk
disable fk;
endtask
endmodule
";
let s = sem(src);
let fb = declared(&s, src, ": fb", 0, 2);
assert_eq!(resolution(&s, at(src, "disable fb", 0, 8)), fb);
assert_eq!(resolution(&s, at(src, "end : fb", 0, 6)), fb);
let fk = declared(&s, src, ": fk", 0, 2);
assert_eq!(resolution(&s, at(src, "join_none : fk", 0, 12)), fk);
assert_eq!(resolution(&s, at(src, "disable fk", 0, 8)), fk);
}
#[test]
fn sibling_loops_with_one_label_neither_crash_nor_resolve_into_the_wrong_body() {
let src = "module s (output logic o, output logic p);
for (genvar i = 0; i < 2; i++) begin : g
logic a;
end : g
for (genvar j = 0; j < 2; j++) begin : g
logic b;
end : g
assign o = g[0].a;
assign p = g[1].b;
endmodule
";
let s = sem(src);
let first = declared(&s, src, ": g", 0, 2);
for (needle, n) in [(": g", 1), (": g", 2), (": g", 3), ("g[0]", 0), ("g[1]", 0)] {
let skip = if needle.starts_with(':') { 2 } else { 0 };
assert_eq!(resolution(&s, at(src, needle, n, skip)), first, "{needle} #{n}");
}
assert_eq!(resolution(&s, at(src, ".a", 0, 1)), declared(&s, src, "logic a", 0, 6));
let got = resolution(&s, at(src, ".b", 0, 1));
assert_ne!(got, declared(&s, src, "logic a", 0, 6), "{got:?}");
}
#[test]
fn a_label_in_both_arms_of_an_ifdef_is_one_label() {
let src = "module d (output logic o);
`ifdef WIDE
for (genvar i = 0; i < 4; i++) begin : g_w
logic q;
end : g_w
`else
for (genvar i = 0; i < 2; i++) begin : g_w
logic q;
end : g_w
`endif
assign o = g_w[0].q;
endmodule
";
let s = sem(src);
let first = declared(&s, src, ": g_w", 0, 2);
for n in 1..4 {
assert_eq!(resolution(&s, at(src, ": g_w", n, 2)), first, "label #{n}");
}
assert_eq!(resolution(&s, at(src, "g_w[0]", 0, 0)), first);
}
#[test]
fn a_blocks_member_key_is_none_or_dotted_never_a_bare_colliding_name() {
// A named block inside a function: the function's own name is not a key
// the index files anything under, and `ff.fb` is exactly the key a
// module `ff`'s block `fb` is filed under.
let src = "module m;
function automatic void ff();
begin : fb
logic t;
t = 1'b0;
end
endfunction
endmodule
";
let s = sem(src);
let t = s.symbols_named("t").next().expect("t");
let key = s.symbol(t).and_then(|sym| s.member_key(sym.scope));
assert_ne!(key.as_deref(), Some("ff.fb"), "collides with module `ff`'s block `fb`");
// Fixed (F4): qualified by the enclosing unit, marked as the function's.
assert_eq!(key.as_deref(), Some("m.ff().fb"));
}
/// Re-check of F4: a named block in a package function, a class method, an
/// out-of-body class method and an interface task — never a key the index
/// files a module's block under.
#[test]
fn recheck_a_block_in_a_subroutine_anywhere_keys_by_its_unit_and_subroutine() {
let src = "package pk;
function automatic void pf();
begin : pb
logic pt;
end
endfunction
class cls;
function void cm();
begin : cb
logic ct;
end
endfunction
extern function void ext();
endclass
function void cls::ext();
begin : eb
logic et;
end
endfunction
endpackage
interface ifc;
task automatic it();
begin : ib
logic itv;
end
endtask
endinterface
";
let s = sem(src);
let key = |name: &str| {
let id = s.symbols_named(name).next().expect("declared");
s.symbol(id).and_then(|sym| s.member_key(sym.scope))
};
assert_eq!(key("pt").as_deref(), Some("pk.pf().pb"));
assert_eq!(key("ct").as_deref(), Some("cls.cm().cb"));
assert_eq!(key("itv").as_deref(), Some("ifc.it().ib"));
let et = key("et");
assert!(et.as_deref().is_none_or(|k| k.contains("()")), "{et:?}");
}
File diff suppressed because it is too large. Load diff
+37 -2
View File
@@ -76,8 +76,10 @@ Decisions where PLAN §10 is silent (the simplest thing, recorded):
module to the end of the line holding its `;`, the common indentation
removed, indented four spaces past the node's line, at most 12 lines then
`…`. Nothing is shown when the file no longer spells the module there.
- The 300-line cap cuts whole nodes (a node's peek block is never split);
`… and N more` counts the nodes left. The 50 000-node walk cap stays, so
- The cap is 300 nodes (instance lines, a root line included) without
`peek` and 100 nodes with it, down and up alike; `peek` lines never count
toward it, and a peek block is never split. `… and N more` counts the nodes not shown. (Was a 300-*line* cap
until 2026-09-29, which with `peek` showed as few as 23 instances.) The 50 000-node walk cap stays, so
on a cut walk `N` is a lower bound.
- Unknown root: up to 10 module/interface names containing it, any case.
@@ -142,6 +144,11 @@ Decisions where PLAN §10 is silent (the simplest thing, recorded):
- **`rename`** refuses every `block`-kind declaration (the symbol table's
kind for a generate block label, and for a named `begin : label` too):
no engine rewrites or reports a hierarchical path through a block.
**2026-09-30 (TODO §65.1):** lifted. The engine now treats a path segment
naming a block as a reference to its label (`g_lane[0].lane_q`,
`u_x.g_lane[1].sig`, the closing `end : g_lane`), so `rename` of a
`block` declaration is complete and is performed like any other;
`qa_m7.rs` asserts it (`docs/features/generate-label-rename`).
- **`port`**: the module is found by `module_definition` (exactly one
declaring file). `remove` finds the port by name in the module's own
scope in that file. `N instantiations in K files` is the index's census
@@ -199,6 +206,8 @@ Requests (not edits):
(`g_lane[0].lane_q`) unrewritten, and `find_references` does not report
them; the MCP layer refuses the rename (any `block`-kind declaration);
the LSP still allows it.
**Closed 2026-09-30 by TODO §65.1** (`docs/features/generate-label-rename`);
the MCP refusal is removed from `tools/edit.rs`.
- **MCP-13 → release/docs owners (outside this lane's files):**
`tools/release.sh` (comments at lines 134 and 257), `tools/RELEASING.md:129`
("at least 26 tools, one `project_overview`") and
@@ -348,6 +357,32 @@ for `down`. `verify.rs` lost its dead forced path.
exact; the pinned test stays ignored with its reason. **R3:** no change.
- Catalogue 3 440 bytes, instructions 398 (unchanged).
### 2026-09-29 — dev (M8 rework 2: the hierarchy cap counts instances)
- Census round 5 found `hierarchy {"root":"prim_fifo_sync","up":true,
"peek":true}` on the OpenTitan clone cut to 20 of 77 instantiations by
the 300-line cap. Lead ruling: the cap counts nodes, never peek lines.
`hierarchy.rs` `render_nodes` now stops at the 300th node; without
`peek` the answer is byte-identical (one line per node). `qa_m7.rs`'s
caps test updated (root + 400 with peek: 599 lines shown, `… and 101
more`); new `tests/hierarchy_cap.rs` (30 fourteen-line instantiations,
up + peek: all 30; 350 instantiations with peek: 300 shown, `… and 50
more` up, `… and 51 more` down). Descriptions and byte budgets unchanged.
PLAN §10.1's row amended.
### 2026-09-29 — dev (M8 rework 3: 100 instances with peek)
- QA finding 6 (M8): with the node cap alone a peeked answer reached
150 kB (`top_earlgrey` depth 3, 3 759 lines). Lead ruling: 300 nodes
without `peek`, 100 with it (`CAP`, `PEEK_CAP` in `hierarchy.rs`);
everything else from rework 2 stands. Tests: `hierarchy_cap.rs` (350
instantiations with peek: 100 shown, `… and 250 more` up, `… and 251
more` down; without peek 300 and 50/51), `qa_m7.rs` caps test (root +
400 with peek: 199 lines, then `… and 301 more`), QA's
`qa_m8.rs` boundary test renamed
`qa_the_node_cap_is_exact_at_300_and_301_plain_and_100_and_101_with_peek`
with 100/101-node fixtures added. PLAN §10.1's row amended again.
## QA log
### 2026-09-24 — QA (M7)
+359
View File
@@ -0,0 +1,359 @@
# mcp-read-only
Lane **M8** of the MCP block (`TODO-MCP.md`, `docs/mcp/PLAN.md` §11).
## Goal
One binary, two modes. `lucisv-mcp --read-only` offers only the five read
tools (`hierarchy`, `find`, `outline`, `read`, `check`) and shorter
instructions, so an agent that only needs to *understand* a design reads a
catalogue half the size and talks to a server that cannot change it: no file
inside a root is created, written, renamed or removed, whatever is called.
Without the flag nothing changes — full mode is byte-identical to 0.58.0 on
the wire. The VS Code extension chooses the mode by a setting
(`lucisv.mcp.mode`), and its copy-config command keys a read-only server
`lucisv-ro` so a host can carry both side by side.
## Assumptions
Where §11 is silent, the simplest thing, recorded:
- **The mode is a registry filter.** `tools::Mode { Full, ReadOnly }` lives
in `tools/mod.rs`; `Mode::offers(Effect)` admits `Read` tools in read-only
mode and every tool in full mode. `tools::list(mode)` and
`tools::find(name, mode)` both go through the one filter, so the listed
set and the callable set cannot disagree. No handler checks the mode.
- **`Options.mode`** carries the mode (default `Full`); `--read-only` sets
it. The flag takes no value and may be repeated harmlessly.
- **Resources** run their read tools through `tools::find(name,
Mode::ReadOnly)` — the strictest registry that has them — so a resource
can never reach an edit tool in either mode and answers the same in both.
- **The unknown-tool message** carries the ` (the server runs --read-only)`
suffix for *any* unknown name in read-only mode, not only the four edit
names: the sentence is true either way and the rule is one line. Full mode
keeps `unknown tool: NAME` exactly.
- **`check`'s description is shared.** The shipped description ("Parse
errors and lint findings of `file` or the whole design, …") never said
"after edits" — only the full-mode *instructions* do — so it reads right
in both modes and there is one description (§11.1 allows this). The read
tools' descriptions, schemas and annotations are identical in both modes
(pinned by test).
- **The instructions text deviates from §11.1 by one phrase.** The quoted
text is 302 bytes, over its own 300-byte budget; "check for diagnostics"
became "check for issues" (297 bytes). Nothing else changed.
- **The promise covers the roots.** The index store under `--index-cache`
is still written on exit. The extension passes VS Code's workspace
storage, which is outside the folder. A user who points `--index-cache`
at a directory *inside* a root gets that directory written (the store,
its `.gitignore`); that is the user's own choice of store location, not a
tool call, and is not guarded against.
- **Extension:** only an unset `lucisv.mcp.mode` or exactly `"full"` is
full mode; exactly `"read-only"` is read-only, and any other value fails
safe to read-only with one line in the lucisv output channel (lead
ruling on QA finding 2; was: anything but `"read-only"` is full). The change event already fires for every `lucisv.mcp.*`
change (`affectsConfiguration('lucisv.mcp')`), so the mode needed no new
listener — only a test. `--read-only` is appended *last* in the
definition's args (after `--index-cache`) and in the snippet's args. The
copy-config message names the mode in both modes (`(full mode)` /
`(read-only mode)`), a wording change for full mode too.
- **`mcp_smoke.js --read-only`** additionally checks the tiny project's two
files are byte-identical after the session; with `--tool-table` it prints
whatever the mode lists (the full-mode table is unchanged, compared
byte for byte against the 0.58.0 script).
## Handshakes
- **Consumes** from the tool registry (M7): the `Effect` per tool in
`TOOLS`. A new tool must be given the right `Effect` — an `Edit` tool
marked `Read` would be offered in read-only mode. The five-name tests in
`tools/mod.rs` and `tests/read_only.rs` pin the current set.
- **Promises** to hosts: `--read-only` → exactly `hierarchy, find, outline,
read, check` in that order, catalogue ≤ 1 800 model-visible bytes (1 797
shipped), instructions ≤ 300 (297 shipped); `tools/call` of an edit name
→ JSON-RPC `-32602` `unknown tool: NAME (the server runs --read-only)`;
no write inside a root. Full mode: `initialize` and `tools/list`
byte-identical to 0.58.0 (checked against the 0.58.0 release binary; the
full catalogue stays 3 440 bytes, instructions 398).
- **Promises** to the extension's users and to `release.sh`: setting
`lucisv.mcp.mode` (`"full"` / `"read-only"`), label `lucisv read-only
(<folder>)`, args `[…, "--read-only"]`, copy-config key `lucisv-ro`;
`mcp_smoke.js <binary> --read-only` as the second MCP gate at both
`release.sh` sites. Recorded in `docs/topo.md` §2.8.
- **Requests:** none. Every file touched is on the lane's list.
## Status / TODO
- [x] server: `--read-only` parsed and in the usage line; `Mode` filters
the registry (`tools/list`, `tools/call`); read-only instructions;
the unknown-tool message
- [x] tests: `tests/read_only.rs` (names and order, both budgets, the five
identical to full mode's, the four edit names unknown, full mode's
nine names and 0.58.0 instructions, the no-write snapshot with every
tool name and every resource, the full-mode control that the edit
arguments do write); unit tests in `tools/mod.rs`, `rpc.rs`,
`main.rs`
- [x] extension: `lucisv.mcp.mode` in `package.json`; `mcp.js` args,
label, copy-config key/args/message; `mcp_test.js`
- [x] `mcp_smoke.js --read-only`; `tools/release.sh` runs both smokes at
both sites; `tools/RELEASING.md`
- [x] docs: Agents guide "Read-only mode" section, settings table and
arguments line; extension README and CHANGELOG; `CHANGELOG.md`
0.59.0 (unreleased); `docs/topo.md` §2.8; manual-acceptance rows
26–27
## Work log
### 2026-09-29 — dev (Opus)
- Captured the 0.58.0 wire (`initialize` + `tools/list` over
`tests/fixtures/design`) from a release build of HEAD before any change;
after the change the full-mode output is `cmp`-identical to it.
- `tools/mod.rs`: `Mode`, `Mode::offers`, `offered(mode)`; `list` and
`find` take the mode. `rpc.rs`: `INSTRUCTIONS_READ_ONLY`,
`instructions(mode)`, `unknown_tool(name, mode)`. `main.rs`:
`Options.mode`, `--read-only`, the usage line. `resources.rs`: reads
through `Mode::ReadOnly`.
- Deviation: §11.1's instructions text measured 302 bytes against its own
≤ 300 budget; "check for diagnostics" → "check for issues" (297).
- Figures (release build): read-only catalogue 1 797 bytes, instructions
297; full catalogue 3 440, instructions 398 (unchanged). The read-only
catalogue is 3 bytes under its ceiling: any growth of the five read
tools' descriptions or schemas now needs a trim elsewhere.
- `tests/read_only.rs` copies the small `Tree`/`Session` helpers from
`wire.rs` rather than sharing them (brief). The no-write test snapshots
path → (size, mtime) for files and mtime for directories (so a temp file
created and removed is caught), runs with `--index-cache` outside the
tree, closes stdin and waits for exit before the second snapshot, and
asserts the cache directory did get the store.
- Extension: setting, provider args/label, copy-config snippet key and
message; `mcp_smoke.js --read-only` (five tools, `hierarchy`, `rename`
→ the exact `-32602` error, files untouched). Against the 0.58.0 binary
`--read-only` fails as it should (`unknown option`).
- Gates: `cargo fmt --all`; `cargo clippy --all-targets -- -D warnings`
clean (guard exit 0); `cargo test -p lucisv_mcp` 14 suites, 373 passed,
0 failed, 4 ignored (guard exit 0); `node --test editors/vscode/*_test.js`
6/6; `mcp_smoke.js target/release/lucisv-mcp` OK in both modes.
### 2026-09-29 — dev (Opus), QA rework
- QA finding 2 (lead ruling 1): `mcp.js` `readOnlyMode(log)` — unset or
exactly `"full"` → full; exactly `"read-only"` → read-only; anything else
(`"Read-Only"`, `"readonly"`, `"Full"`, `null`, `true`, a number) →
read-only plus one line, `lucisv: lucisv.mcp.mode is "<value>", not
"full" or "read-only"; using read-only.`, through `activate`'s `log`
(now passed to `serverDefinitions` and `copyConfig`, which share the
rule). `mcp_test.js` `anUnknownModeFailsSafeToReadOnly` covers the three
cases and the line; `theReadOnlySnippets` covers copy-config with
`"readonly"`. One clause ("any other value is treated as read-only") in
the `package.json` description, the extension README settings table and
the Agents guide settings table.
- QA finding 4 (lead ruling 2): `mcp_smoke.js --read-only` now checks the
tool list (count and names) before the `rename` refusal; against a
wrapper that drops `--read-only` it fails with `tools/list is 9 tools
[…], expected 5 […]`.
- No Rust changed. `node --test editors/vscode/*_test.js` 6/6; both smokes
OK against `target/release/lucisv-mcp`.
### 2026-09-29 — dev (Opus), rework 2
- The `hierarchy` cap now counts instances, not peek lines (census round
5 finding on `prim_fifo_sync` up + peek). The change and its tests are
logged in `docs/features/mcp-lean-catalogue/README.md` (work log,
2026-09-29); tool descriptions and both modes' byte figures unchanged.
### 2026-09-29 — dev (Opus), rework 3
- QA finding 6: the `hierarchy` cap is 300 instances without `peek`, 100
with it (lead ruling). Logged in the M7 README (work log, rework 3).
QA's boundary test in `qa_m8.rs` is renamed
`qa_the_node_cap_is_exact_at_300_and_301_plain_and_100_and_101_with_peek`
(the QA log below still names it by its old name). Descriptions and both
modes' byte figures unchanged.
## QA log
### 2026-09-29 — QA (Opus)
**Verdict: PASS with findings** (two low, three informational; no
corruption, no write, no reachable edit handler).
What was verified, and how:
- **No-write promise, fixture.** `tests/qa_m8.rs`
`qa_read_only_never_changes_a_byte_whatever_arrives`: snapshot of every
entry under a copy of `fixtures/edit` (file size + mtime + **bytes**,
directory mtime so a temp file created and removed is caught), then one
session with: 13 edit shapes (rename ×2, port add / add-after / remove,
edit_item replace / insert_before / insert_after / delete, format with and
without `fix`, `**/*.sv`, `rtl`) sent before `initialize` (all `-32002`),
after it as requests (all `-32602` with the exact message), as
notifications (`tools/call` with no id) and as `notifications/<name>`;
12 near-miss names (`Rename`, `" rename"`, `"rename "`, `rename\n`,
`rename\0`, `edit-item`, `editItem`, fullwidth `rename`, `format\t`, …);
`name` as number / array / object / null / bool (`-32602` "need a string
`name`"); edit names with null / array / string / smuggled `mode` arguments
and a `_meta`/`mode` in params; a batch array (`-32600`); a duplicate
`name` key (`check` then `format`: last key wins → refused); a second
`initialize` asking for `experimental.mode: full` followed by `format`
(still refused); eight resource URIs (the four real ones plus
`lucisv://format/…`, `lucisv://unit/..%2F..%2Fetc`); three stray
notifications. Snapshot identical after exit. Control
`qa_every_edit_shape_writes_in_full_mode`: each of the 13 shapes writes in
full mode. Mutation `Mode::offers` → `(Mode::ReadOnly, _)`: three QA tests
fail; reverted, `cmp`-identical.
- **No-write promise, opentitan** (`~/.cache/lucisv-eval/ot/hw`, release
binary, `--read-only`, no `--index-cache`): `format **/*.sv fix` before
`initialize`, then rename `uart_rx`, port add/remove on `uart_rx`,
edit_item insert/delete in `ip/uart/rtl/uart_rx.sv`, format `**/*.sv`
and `ip/uart/rtl`, `Format `, a notification-form format, the five reads
and three resources (3 944 files indexed). Every edit answered `-32602`;
`git status --short` empty before and after, `--ignored` set unchanged,
no file newer than the run outside `.git`. `/Users/…/repo/opentitan`
not touched.
- **Reachability.** `tools::find` is the only way from a name to a handler;
callers: `rpc.rs:247` (`self.options.mode`) and `resources.rs:116`
(`Mode::ReadOnly`, and only `hierarchy`/`outline` are named). No cached
`Tool` reference; `apply::run` is called only from `edit.rs`, `format.rs`,
`item.rs` (and `port` through them). `Options` is built only by
`Options::default()` in `parse_args` (`main.rs:82`) and in `rpc.rs`'s unit
tests; `Server.options` is never reassigned.
- **Arguments** (`qa_argument_order_and_repetition_cannot_undo_read_only`):
flag first, last, repeated, mixed with `--verbose` → five tools;
`--read-only=false`, `--read-only false`, `--read-only=true`,
`--readonly`, `--no-read-only` → exit 2, `unknown option`, usage line
naming `[--read-only]`, no server.
- **Budgets, recomputed in Python** from the wire (compact JSON of name +
description + inputSchema): read-only 1 797 bytes, 5 tools, all
`readOnlyHint: true`, instructions 297; full 3 440, instructions 398. Sum
of name + description + schema alone: 1 576 / 3 043. Mutation: 4 bytes
appended to `hierarchy`'s description → `read_only.rs` fails ("the
read-only catalogue is 1801 bytes"); reverted, `cmp`-identical.
- **Full-mode identity.** `initialize` + `notifications/initialized` +
`tools/list` + `resources/list` + `resources/templates/list` + an unknown
tool, over `fixtures/design`: current release binary vs
`~/.cache/lucisv-eval/bin/lucisv-mcp-r5` — identical except
`serverInfo.version` (finding 3).
- **Read answers across modes**
(`qa_the_read_tools_and_resources_answer_identically_in_both_modes`): 12
read calls (incl. a refusal) + 4 resource reads (incl. not-found) + the
three list methods on `design` and `edit`: identical text in both modes.
- **Extension.** `node --test editors/vscode/*_test.js` 6/6. The change
event: `mcp.js:176-177` fires on `affectsConfiguration('lucisv.mcp')`,
which VS Code answers true for `lucisv.mcp.mode` (pinned by the dev's
test). Copy-config per host per mode pinned by `theThreeSnippets` /
`theReadOnlySnippets`. `mcp_smoke.js` against the release binary: OK in
both modes; `--read-only` against r5 (refuses the flag, exit 2) → smoke
exit 1; against a wrapper that drops `--read-only` (a server listing nine
tools) → smoke exit 1 (finding 4).
- **Release script.** `bash -n tools/release.sh` OK; `set -eu` (line 32);
both new invocations (host `$dist/lucisv-mcp-$version-$host`, embedded
`$unpacked/$inner/lucisv-mcp`) are plain statements, so a failing smoke
aborts the script.
- **Docs.** The guide's two-key example parses as JSON and each entry has
the shape copy-config emits for Claude Code / Cursor (`command`, `args`;
`lucisv-ro` args end `--read-only`). Arguments line and usage line name
the same five flags in the same order.
- **Gates.** `cargo fmt --all` clean; `cargo clippy --all-targets -- -D
warnings` clean (guard exit 0); `cargo test -p lucisv_mcp` 15 suites,
378 passed, 0 failed, 4 ignored (guard exit 0, no `guard.sh:` line).
Findings, by severity:
1. **Low (docs, fixed).** The Agents guide
(`docs/site/src/content/docs/guides/agents.md`, "Read-only mode", last
paragraph) and `CHANGELOG.md` 0.59.0 said the index store "is outside
the roots" — true only as the extension passes it. Repro:
`lucisv-mcp --root R --index-cache R/.cache --read-only`, call `check`,
close stdin → `R/.cache/.gitignore` and `R/.cache/index-cache-mcp`
appear (the dev's recorded deviation). Reworded both to say the store is
written where `--index-cache` points. PLAN §11.1 carries the same
sentence; left for the lead.
2. **Low (design, recorded).** `editors/vscode/mcp.js:57`: any
`lucisv.mcp.mode` other than exactly `"read-only"` — `"Read-Only"`,
`"readonly"`, `null`, `true` — is full mode, silently. That is the brief's
rule and nothing dangerous is said, but a typo lands on the *permissive*
mode; VS Code's only hint is the enum warning in `settings.json`. No
change made.
3. **Info.** `~/.cache/lucisv-eval/bin/lucisv-mcp-r5` reports
`serverInfo.version` `0.57.0` (built before the 0.58.0 bump); the wire is
otherwise byte-identical to the current full mode.
4. **Info.** `mcp_smoke.js --read-only` against a server that ignores the
flag fails on the `rename` check (`rename in read-only mode answered
undefined`) before the tool-list check — it fails, but the message does
not say "nine tools". Against r5 it fails the same way (the server
exited 2 with its usage line on stderr).
5. **Info.** `tools/release.sh` `smoke_embedded_mcp`: a failing smoke
aborts before `rm -rf "$unpacked"`, leaving `target/vsix-check`
(pre-existing pattern; the next run removes it first).
Tests added: `crates/lucisv_mcp/tests/qa_m8.rs` (5 tests, all green).
### 2026-09-29 — QA (Opus), re-check: `hierarchy` cap counts nodes
Rework under test: `tools/hierarchy.rs` `render_nodes` caps at 300 nodes
(the down root line included), peek lines never count. **Verdict: PASS with
one finding.**
- **No-peek identity with b757e82** (`lucisv-mcp-r6` vs a fresh release
build): 43 calls on `fixtures/design` and 85 on `fixtures/edit` (every
unit down / down depth 20 / up / up depth 20, with and without peek) —
0 differ. Eval clone, 9 calls — `top_earlgrey` depth 2 (50 lines) and
depth 3 (`… and 165 more`), `prim_fifo_sync` up (77) and up depth 3
(`… and 1421 more`), `top_darjeeling` depth 3 (`… and 174 more`),
`prim_flop` up (`… and 176 more`) and up depth 4 (`… and 45166 more`),
`uart` depth 20, the overview (`… and 69 more`) — byte-identical, and
identical again under `--read-only`.
- **`prim_fifo_sync` up + peek** (eval clone): 1 078 lines, no cut. Its
lines that are neither statement lines (4-space indent) nor blank are
exactly the 77 lines of the no-peek answer, in order; every node is
followed by at least one statement line; no block exceeds 12 lines + `…`
(69 blocks end in `…`). r6 gave 21 of them then `… and 56 more`.
- **`qa_m7.rs` diff vs HEAD:** one expected tuple `(299, 251)` → `(599,
101)` (root + 299 two-line blocks, 401 − 300 = 101 — what the rule
requires) and the peek assertion now pins *two* lines (`peek[597]` the
299th instance's node line, `peek[598]` its statement) where it pinned
one; no other assertion touched.
- **Boundaries** (`qa_m8.rs`
`qa_the_node_cap_is_exact_at_300_and_301_down_and_up_with_and_without_peek`,
14-line statements so every block is cut to 12 + `…`): down 299
instances (300 nodes) → 300 lines, no cut; down 300 → root + 299 and
`… and 1 more`; up 300 → 300, no cut; up 301 → 300 and `… and 1 more`.
With peek: the same node lines and cut line in the same order, exactly
14 lines per instance node, the line before the cut is the last block's
`…` (never split). The down count counts the root as a node consistently:
401 nodes → `… and 101 more` = the 101 instances not shown.
- **Modes:** every text above is identical in full and `--read-only` mode
(asserted in the test, and on the eval clone with and without peek).
- **Gates:** `cargo test -p lucisv_mcp` 16 suites, 381 passed, 0 failed, 4
ignored (guard exit 0, no `guard.sh:` line); clippy `-p lucisv_mcp
--all-targets -D warnings` clean. Eval clone `git status` empty.
Finding:
6. **Medium (answer size, design consequence).** A peeked answer is no
longer bounded by ~300 lines but by 300 × 14 lines. Repro on the eval
clone: `hierarchy {"root":"top_earlgrey","depth":3,"peek":true}` → 3 759
lines, 151 224 bytes (r6: 295 lines, 10 152 bytes);
`{"root":"prim_fifo_sync","up":true,"depth":3,"peek":true}` → 4 154
lines, 152 356 bytes (r6: 10 457); `prim_flop` up peek → 2 984 lines,
89 972 bytes. That is roughly 40 k tokens in one answer, against the
lean catalogue's short-answer goal (PLAN §10). The fix the brief asked for
(77 of 77) needs only ~31 KB; whether a byte ceiling on peek belongs
beside the node cap is the lead's call. Not changed.
Tests added: `qa_m8.rs` `qa_the_node_cap_is_exact_at_300_and_301_down_and_up_with_and_without_peek`.
## Review
2026-09-29 (lead). Examined the diff, the registry filter, the QA log and
the live wire in both modes. Accepted. `--read-only` lists five tools in
1 797 model-visible bytes with 297-byte instructions; full mode is
byte-identical to 0.58.0. QA could not make the read-only server write
inside a root or reach an edit handler. Rulings: the dev's deviations 1–5
stand (instructions say "check for issues"; any unknown tool name carries
the read-only suffix); an unknown `lucisv.mcp.mode` value selects
read-only and is logged (QA finding 2); the smoke checks the tool list
first (finding 4); PLAN §11 now says the index store is written wherever
`--index-cache` points. Gates at commit: lucisv_mcp 378 passed / 4
ignored (15 suites), node tests 6/6, both smokes OK. Census round 5
follows on this binary.
@@ -248,6 +248,11 @@ bind; a package only in a file. The parser accepts `always_comb` after
(rule 6).
- A hierarchical use in **another file** that `find_references` does not
follow (`u_h.gen_l[0].z` into a generate loop; MCP-12).
**2026-09-30 (TODO §65.1):** `find_references` now follows it — a path
segment through a block is a reference to its label and the tail resolves
(`docs/features/generate-label-rename`), so such a use is listed like any
other; the in-file "resolves to the declaration or to nothing" rule is
unchanged.
- A name reached only through a macro that pastes it together
(`` `a``_b ``): no byte spells it, and no lucisv engine follows it.
+20
View File
@@ -1369,6 +1369,26 @@ un-ignored, and QA's own pin of the old behaviour in
through `tools/guard.sh`: fmt, clippy, vlog_refactor 616 passed, workspace
4 761 passed.
**2026-09-30 — dev agent (TODO §65.1, generate-label-rename).** A rename of
a generate block label now rewrites every path through it — `g[0].x`,
`g_a.g_b[2].x`, `u_x.g[1].sig` from another file — with the label and its
closing label, and `find_references` lists them; named procedural blocks'
`end : lbl` and `disable lbl` are the same set. The engine and the verifier
are unchanged in code: the fix is in `vlog_semantic` (a `for` block's label
declared in the enclosing scope, `generate` regions transparent, blocks as
member scopes, index-transparent spines, blocks on the index's hierarchical
surface under `module.label`), after which a missed segment is a reference
that stops resolving and the existing resolution print refuses it — pinned by
eight attacks in `check/qa_block_paths.rs`. `docs/features/generate-label-rename`.
**2026-10-07 — correction (independent review M-3).** The 2026-09-30 entry
above says the engine and the verifier are "unchanged in code"; that held
for the first pass only. The §65.1 reworks added rename-warning modules
(`rename/paths.rs`, `arms.rs`, `home.rs`, `scoped.rs`, later `carry.rs`) and
path-qualified file names in every refactoring's messages, the verifier's
included (`Scope::name_of`). What a rename rewrites, and what the verifier
forgives, did not change. `docs/features/generate-label-rename`.
## QA log
**2026-08-24 — QA agent.**
+2
View File
@@ -32,6 +32,8 @@ hour. Record the release, the date and any failure in the table at the end.
| 23 | Universal `lucisv-<v>.vsix` with no `lucisv-mcp` on PATH; start the server. | Same as 22 with `"lucisv-mcp" not found`; the language server (steps 1–5) unaffected. |
| 24 | **lucisv: Copy MCP server config** → Claude Code; paste into `.mcp.json` of a scratch copy of a project; in a terminal there run `claude`, `/mcp`. Repeat for VS Code → `.vscode/mcp.json` in another window. | The info message names `.mcp.json` and warns the bundled path moves on update; Claude Code lists `lucisv` connected and answers `hierarchy` (no arguments); the `.vscode/mcp.json` server (`"type": "stdio"`) starts too. |
| 25 | Optional, if a VS Code older than 1.101 is at hand: install the platform `.vsix` there. | Extension activates normally; Output → lucisv has one "no MCP server API (needs 1.101+)" line; the copy-config command still works. |
| 26 | Set `lucisv.mcp.mode` to `read-only` (Settings UI, workspace scope); open **MCP: List Servers**; start the server and list its tools in agent mode. Reset the setting afterwards. | Without a reload the server is listed as `lucisv read-only (opentitan)`; it offers exactly five tools (`hierarchy`, `find`, `outline`, `read`, `check`); asking the agent to rename something gets no edit (the tool is not there). Back to `full`: `lucisv (opentitan)` with nine tools. |
| 27 | With `lucisv.mcp.mode` = `read-only`, **lucisv: Copy MCP server config** → Claude Code; paste into a scratch `.mcp.json`. | The info message says `(read-only mode)`; the snippet's server key is `lucisv-ro` and its `args` end with `--read-only`; Claude Code's `/mcp` lists `lucisv-ro` connected with five tools. |
## Runs
+68 -1
View File
@@ -504,7 +504,7 @@ its text. The `annotations` stay (`readOnlyHint`, `destructiveHint: false`)
| tool | arguments | answers |
|---|---|---|
| `hierarchy` | `root?`, `up?` (bool), `depth?` (1–20, default 1), `peek?` (bool) | Without `root`: one line `N files, M modules, K top` then the top modules as `name file:line`. With `root`, down: the instance tree, one line per instance, two spaces per level: `instance: module file:line` where `file:line` is the **instantiation site**. `up`: every instantiation of `root`, `parent.instance file:line`, all levels up to `depth`. `peek: true` appends each instantiation statement's source under its line (indented, as written, at most 12 lines each then `…`). Cap 300 lines then `… and N more`. Unknown `root`: a refusal that lists up to 10 contains-matches. |
| `hierarchy` | `root?`, `up?` (bool), `depth?` (1–20, default 1), `peek?` (bool) | Without `root`: one line `N files, M modules, K top` then the top modules as `name file:line`. With `root`, down: the instance tree, one line per instance, two spaces per level: `instance: module file:line` where `file:line` is the **instantiation site**. `up`: every instantiation of `root`, `parent.instance file:line`, all levels up to `depth`. `peek: true` appends each instantiation statement's source under its line (indented, as written, at most 12 lines each then `…`). Cap 300 instances, 100 with `peek`; peek lines do not count; then `… and N more`. Unknown `root`: a refusal that lists up to 10 contains-matches. |
| `find` | `name`, `refs?` (bool) | Every declaration of `name` (whole-name, any case-exact): `kind name file:line`, then, with `refs`, per declaration its uses as `file:line` (one file per line, lines joined with `,` when several are in one file: `ip/uart/rtl/uart.sv:120,133,140`), then `unresolved:` and the textual mentions (strings, comments, macro text) the same way. No declaration: up to 20 contains-matches of declarations as a refusal (`no declaration named X; similar: …`). Cap 300 lines. |
| `outline` | `file?` **or** `unit?` (exactly one) | `file`: its declarations as a tree with line ranges, two spaces per level: `kind name start–end`, parse errors first as `error line: message`. `unit`: its `file:line`, then parameters `param name = default` and ports `dir type[range] name` in declaration order, one per line; interfaces add modports, packages their exports. No template, no counts. Cap 300 lines. |
| `read` | `item`, `file?` | The item's source, exact bytes, preceded by one line `file:start–end`. Selector as today's `read_item` (`name`, `kind:name`, `name@LINE`, `always@LINE`). Without `file` the item is looked up design-wide; several matches → a refusal listing them as `file:line`. |
@@ -568,3 +568,70 @@ Agents guide's table.
- The M4 attack suite green unchanged; `check` on the fixtures identical to
the old `diagnostics` line set; `hierarchy` on opentitan's `top_earlgrey`
identical instance set to the old tool.
## 11. Read-only mode (0.59 — the owner's request of 2026-09-29)
One binary, two modes. `lucisv-mcp --read-only` offers only the five read
tools and shorter instructions; without the flag nothing changes (the nine
tools of §10). The two co-exist: a host may configure both side by side
under two names, and the extension chooses by a setting.
### 11.1 The server
- **Flag** `--read-only` (no value). Usage line:
`usage: lucisv-mcp [--root DIR]... [--filelist FILE] [--index-cache DIR] [--read-only] [--verbose]`.
- **`tools/list`** in read-only mode: exactly `hierarchy, find, outline,
read, check`, in that order, the same descriptions and schemas as in full
mode except `check`, whose words "after edits" do not apply (one
description for both modes if it reads right in both; otherwise a
read-only wording). Model-visible bytes (compact JSON of name +
description + inputSchema) **≤ 1 800**, pinned by test.
- **`tools/call`** of `rename`, `port`, `edit_item` or `format` in
read-only mode is the unknown-tool error (`-32602`), message
`unknown tool: rename (the server runs --read-only)`. The edit handlers
are not reachable: the mode filters the registry, it does not flag
inside each handler.
- **Instructions** in read-only mode, **≤ 300 bytes**, pinned by test:
> 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 promise:** in read-only mode no file inside a root is created,
written, renamed or removed by a tool, whatever is called. The server's
own index store under `--index-cache` is still written (it is what makes
the next start warm); the extension passes VS Code's workspace storage,
which is outside the folder — a user who points `--index-cache` inside a
root gets that directory written there. A test walks the fixture tree's
sizes, mtimes and names before and after calling every tool name of the
full catalogue.
- Resources, transport, freshness, annotations: unchanged.
### 11.2 The extension
- Setting **`lucisv.mcp.mode`**: `"full"` (default) or `"read-only"`; any
other value is treated as read-only and logged (a typo must not land on
the mode that can write). In
read-only mode the definition's args gain `--read-only` and its label is
`lucisv read-only (<folder>)`; a change of the setting fires the
provider's change event, like `lucisv.mcp.enabled`.
- **lucisv: Copy MCP server config** follows the setting: in read-only
mode the snippet's args end with `--read-only`, the server key is
`lucisv-ro`, and the message says which mode was copied. (Two keys, so a
user can paste both.)
- `mcp_smoke.js <binary> --read-only` smokes that mode (five tools in
order, one `hierarchy`, and `rename` answered with the unknown-tool
error); `tools/release.sh` runs both smokes on the host binary and on
the embedded one.
### 11.3 Acceptance
- Full mode byte-identical on the wire to 0.58.0 (`tools/list`,
`instructions`), except the usage line.
- Read-only budgets met and pinned; the no-write test green; the
extension's node tests cover the setting, the label, the args and the
snippet.
- Census round 5 (lead): tasks a and d on the read-only mode, against
round 4's full-mode figures.
+9
View File
@@ -25,3 +25,12 @@ r4 d mcp sonnet tokens=104897 calls=22 wall=278s outcome=correct 71/20, all coun
r4 c mcp sonnet tokens=101137 calls=45 wall=403s outcome=correct 8/8 sites in 4 files (rename wrote 2 files + listed the macro arg, chip_if path and the DV string path as unresolved; agent fixed those by hand); +16% vs r1 base, +9% vs r2 base rerun; agent lost time waiting on its own background rename (interim stop, nudged)
r4 d mcp sonnet (re-run) tokens=99525 calls=24 wall=302s outcome=correct 71/20, all counts; mean of the two r4 runs 102 211 vs base 102 579
r4 c mcp OPUS: tokens=68948 tool_calls=10 wall_s=214 outcome=correct 8/8 in 4 files (−1% vs r3 Opus mcp, +13% vs r3 Opus base)
# Round 5 — server b757e82 (M8 read-only mode, bin/lucisv-mcp-r6 --read-only, shim mcpc6ro, prompt_mcp_r5_ro.txt)
r5 a read-only sonnet tokens=67230 calls=7 wall=41s outcome=correct 47/47 table, all values (prose first said 55 then corrected itself to 47); hierarchy up hit the 300-line cap (… and 56 more), agent fell back to grep over hw/ip
r5 d read-only sonnet tokens=80487 calls=10 wall=121s outcome=correct 71/20, all counts (same content as the graded r4 answer); hierarchy depth 1 + outline unit per module
r5 a read-only sonnet (re-run) tokens=72361 calls=7 wall=56s outcome=correct 47/47 (same table); hierarchy up truncated again, agent scanned the RTL sources; mean of the two r5 runs 69 796 vs base 91 094
r5 d read-only sonnet (re-run) tokens=67104 calls=8 wall=151s outcome=correct 71/20, all counts; mean of the two r5 runs 73 796 vs base 102 579
r5 a BASE control sonnet (same day, 2026-09-29) tokens=64817 calls=3 wall=40s outcome=correct 47/47 — the base arm is 29% cheaper than on 2026-09-23 (91 094): the sub-agent environment changed; earlier rounds are not comparable with round 5
r5 d BASE control sonnet (same day) tokens=80194 calls=10 wall=78s outcome=correct 71/20, all counts (2026-09-23 base was 102 579)
r5b a read-only sonnet (cap fix, bin r7) tokens=72247 calls=8 wall=50s outcome=correct 47/47; hierarchy up+peek now complete (77 instantiations, 31 kB); agent still cross-checked with grep; +11% vs same-day base 64 817
+39 -2
View File
@@ -32,12 +32,13 @@ agent mode can call its tools. The extension starts it as
lucisv-mcp --root <folder> --index-cache <the extension's workspace storage>
```
Two settings govern it:
Three settings govern it:
| setting | default | what it does |
|---|---|---|
| `lucisv.mcp.enabled` | `true` | `false` withdraws the server from agent mode (takes effect without a reload) |
| `lucisv.mcp.path` | `""` | a `lucisv-mcp` to use instead of the bundled one; empty means the bundled one, else `lucisv-mcp` on `PATH` |
| `lucisv.mcp.mode` | `"full"` | `"read-only"` starts it with `--read-only`, listed as `lucisv read-only (<folder>)`; any other value is treated as read-only — see [Read-only mode](#read-only-mode) (takes effect without a reload) |
The universal `.vsix` carries no binaries: it looks `lucisv-mcp` up on
`PATH`, and when there is none it says so in the **lucisv** output channel
@@ -88,7 +89,8 @@ cargo build --release -p lucisv_mcp # target/release/lucisv-mcp
Arguments: `--root DIR` (repeatable; default the current directory),
`--filelist FILE` (index exactly the files an EDA filelist names),
`--index-cache DIR`, `--verbose` (per-call timing on stderr). Anything else is
`--index-cache DIR`, `--read-only` (the five read tools only — see
[Read-only mode](#read-only-mode)), `--verbose` (per-call timing on stderr). Anything else is
refused with a usage line and exit status 2.
## Tools
@@ -109,6 +111,41 @@ description. The agent sees the full description and input schema.
| `edit_item` | yes | 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. |
| `format` | yes | Format `files` (a path, directory or glob like `rtl/**/*.sv`) as lucisv format; `fix: true` applies safe lint fixes first. |
## Read-only mode
`lucisv-mcp --read-only` offers only the five read tools — `hierarchy`,
`find`, `outline`, `read`, `check`, the rows without **writes** above — and
shorter instructions: a smaller catalogue for the agent to read every
session, and a server that cannot change the design. Without the flag
nothing changes.
- **In VS Code**, set `lucisv.mcp.mode` to `"read-only"`: the extension
hands agent mode a server started with `--read-only`, listed as
`lucisv read-only (<folder>)` with five tools (no reload needed).
**lucisv: Copy MCP server config** follows the setting: in read-only mode
the snippet's args end with `--read-only` and its server key is
`lucisv-ro`, so it can sit beside a full one.
- **By hand**, both modes side by side under two names — the agent (or you)
picks the one to enable:
```json
{
"mcpServers": {
"lucisv": { "command": "lucisv-mcp", "args": ["--root", "/path/to/project"] },
"lucisv-ro": { "command": "lucisv-mcp", "args": ["--root", "/path/to/project", "--read-only"] }
}
}
```
What it promises: **no file inside a root is created, written, renamed or
removed, whatever is called.** An edit tool is not there to call — `tools/list`
does not offer it and `tools/call` answers its name with the unknown-tool
error, `unknown tool: rename (the server runs --read-only)`. The server's own
index store under `--index-cache` is still written on exit (it is what makes
the next start warm): the extension keeps it outside the workspace, but a
directory you name inside a root is written like any other. Resources answer
as in full mode.
## What it promises
- **Answers come from the disk.** Every call first re-checks the files it
+3 -2
View File
@@ -662,6 +662,7 @@ engine-lane features are listed above; this table is the server-internal web.
| `editor-packaging ◀──▶ lucisv-mcp` (mcp-packaging) | handshake | The MCP spawn contract (2026-09-23): the binary `lucisv-mcp[.exe]` found by the same three-rung ladder as the server (`lucisv.mcp.path` → `bin/` → `PATH`), spawned by VS Code from `McpStdioServerDefinition(label, command, ["--root", folder, "--index-cache", storage], env, version)` — the constructor is positional — one per workspace folder; `serverInfo.name == "lucisv-mcp"`, exactly the nine lean tools in order — `hierarchy, find, outline, read, check, rename, port, edit_item, format` (`mcp_smoke.js` `TOOLS`; **amended by M7, 2026-09-23**, was ≥ 26); `mcp_smoke.js --tool-table` regenerates the Agents guide's table. Provider id `lucisv.mcp`; settings `lucisv.mcp.enabled`/`.path`; command `lucisv.mcp.copyConfig`. |
| `release-prep / editor-platform-vsix ──▶ lucisv-mcp` (mcp-packaging) | depends | `release.sh` builds `-p lucisv_mcp` for every triple and stages it as the THIRD `bin/` entry (fifteen in the `all` package); `expect_vsix_bins` and `audit_artifacts.sh` pin the name; the seven `.vsix` names are unchanged. `mcp_smoke.js` is the gate beside `smoke.js`. |
| `lucisv-mcp ──▶ lucisv-server` (index cache, M6) | depends (read-only) | MCP reads the server's `index-cache` store read-only when `--index-cache DIR` names it (header `CACHE_FORMAT`/`FACTS_FORMAT`/version must match, else ignored) and writes its own `index-cache-mcp` beside it; it never writes the server's file. A codec change on the server side costs MCP its warm start, never its correctness. |
| `editor-packaging ◀──▶ lucisv-mcp` (mcp-read-only, M8) | handshake | The read-only mode (2026-09-29, PLAN §11): setting `lucisv.mcp.mode` (`"full"` default / `"read-only"`) appends `--read-only` to the spawn args and labels the definition `lucisv read-only (<folder>)`; copy-config keys it `lucisv-ro`. The binary then lists exactly `hierarchy, find, outline, read, check` (≤ 1 800 model-visible bytes, instructions ≤ 300), answers the four edit names with `-32602` `unknown tool: NAME (the server runs --read-only)`, and writes nothing inside a root (`tests/read_only.rs`); full mode is byte-identical to 0.58.0. `mcp_smoke.js --read-only` is the second MCP gate in `release.sh`, host and embedded. |
### 2.9 Open handshakes (filed, not yet delivered — claim before working)
@@ -709,10 +710,10 @@ update the filing README(s) and this file.
| 37 | **MCP-7 → `vlog_refactor`:** a `find_references` variant taking `&dyn KnownFacts` (like `rename_traced_with`) so whole-set callers feed cached records instead of re-parsing 3 944 files (≈2 s per opentitan call today) | mcp-navigation | vlog_refactor |
| 38 | **MCP-8 → `vlog_refactor`:** false `remove_port` refusal when the only "use" of the port is a named connection from another module in the same file (`ports/remove.rs::body_uses_in`) | mcp-edit-tools | vlog_refactor |
| 39 | **MCP-10 → `vlog_refactor`:** `extract_module` writes LF into a CRLF file (`extract/render.rs`) | mcp-edit-tools | vlog_refactor |
| 40 | **MCP-11/12 → `vlog_refactor`/`vlog_semantic`:** a batched `find_references` for several declarations; `find_references` misses a hierarchical use into a generate loop (`gen_l[0].z`) | mcp-structural-edits | vlog_refactor, vlog_semantic |
| 40 | **MCP-11/12 → `vlog_refactor`/`vlog_semantic`:** a batched `find_references` for several declarations; ~~`find_references` misses a hierarchical use into a generate loop (`gen_l[0].z`)~~ — **second half answered 2026-09-30 by generate-label-rename (TODO §65.1, row 43)**; the batched `find_references` stays open | mcp-structural-edits | vlog_refactor, vlog_semantic |
| 41 | **MCP-13 → `vlog_linter`:** a forced deletion of a non-ANSI body port leaves a header port with no direction and no lint reports it | mcp-structural-edits | vlog_linter |
| 42 | **Parser leniency → `vlog_parser`:** a trailing `,` in a named connection list, an empty concatenation element `{d,, d}`, and `type(x)'(y)` in a connection parse without a diagnostic (the rename verifier's position rule covers the rename; every other splice contract is exposed) | refactor-rename (M3.5) | vlog_parser |
| 43 | **MCP-14 → `vlog_refactor`/`vlog_semantic`:** rename of a generate block label leaves hierarchical paths through it unrewritten and `find_references` does not report them — vlog_refactor/vlog_semantic; the MCP layer refuses the rename; the LSP still allows it | mcp-lean-catalogue | vlog_refactor, vlog_semantic |
| ~~43~~ | ~~**MCP-14 → `vlog_refactor`/`vlog_semantic`:** rename of a generate block label leaves hierarchical paths through it unrewritten and `find_references` does not report them — vlog_refactor/vlog_semantic; the MCP layer refuses the rename; the LSP still allows it~~ — **closed 2026-09-30 by generate-label-rename (TODO §65.1, 0.60.0):** the gap was resolution, not the rename — `vlog_semantic` now declares a `for` block's label in the enclosing scope (the genvar stays in the header), treats `generate … endgenerate` as no scope, gives a named block a member scope, walks an index in a path as the name it indexes, and puts blocks on a module's hierarchical surface with their members under the synthesized key `module.label` (`FACTS_FORMAT` 21; `Semantics::member_key`, which `lucisv_server/src/nav.rs` now asks with). Every segment — bare, indexed, nested, cross-file — and the closing label are ordinary references, so `find_references`, `rename` (LSP, CLI engine, MCP) and the verifier's unchanged resolution print all see them; no verifier normalization was added, eight attacks pin that (`check/qa_block_paths.rs`). `lucisv-mcp`'s `block` refusal is lifted. Also answers row 40's second half (`gen_l[0].z` is found). | mcp-lean-catalogue | vlog_refactor, vlog_semantic |
---
+25
View File
@@ -5,6 +5,31 @@ for you. The extension and its bundled language server share one version
number; the full engineering notes live in the
[project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md).
## 0.60.0 — 2026-10-08
- **Rename a generate block label and every path through it moves.**
Renaming `g_lane` in `for (…) begin : g_lane` now also rewrites
`end : g_lane` and every hierarchical path through the block —
`g_lane[0].lane_q` beside the loop, `u_x.g_lane[1].sig` in another file —
all or nothing. **Find All References** on the label lists them too. Named
`begin : lbl` blocks rename with their `end : lbl` and `disable lbl;`.
- Rename warnings are about the signal you renamed: another module's own
`state_q` inside a macro or an assertion is no longer listed, while a
spelling that can still reach yours — a hierarchical path, a macro that
builds `.state_q(state_q)` or a `bind` — always is.
- `duplicate-declaration` reports a block label that collides with a
signal, port, parameter, function or another block of the same scope.
## 0.59.0 — 2026-09-29
- New setting `lucisv.mcp.mode`: `"read-only"` offers agent mode a
`lucisv read-only (<folder>)` server with only the five read tools —
`hierarchy`, `find`, `outline`, `read`, `check` — that never writes a file
in the workspace (`lucisv-mcp --read-only`). `"full"`, the default,
changes nothing. **lucisv: Copy MCP server config** follows the setting:
in read-only mode the snippet is keyed `lucisv-ro` and ends with
`--read-only`, so a full and a read-only server can be pasted side by side.
## 0.58.0 — 2026-09-24
- `lucisv-mcp`, the agent server, now offers nine tools instead of 26 —
+21 -2
View File
@@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view,
then open a Verilog or SystemVerilog file. There is no separate server or CLI
setup.
The current release is **0.58.0**. Its platform packages include
The current release is **0.60.0**. Its platform packages include
`lucisv-server`, the `lucisv` command-line tool and `lucisv-mcp` (see
[Agents (MCP)](#agents-mcp)):
@@ -197,11 +197,12 @@ edit is verified and written whole, with no dry run.
|---|---|
| VS Code agent mode | On VS Code 1.101+, one `lucisv (<folder>)` server per workspace folder, listed under **MCP: List Servers**; trust it once and agent mode can call its tools (the full list is in the Agents guide). Folders added or removed update the list |
| Other agents | **lucisv: Copy MCP server config** copies the snippet for Claude Code (`.mcp.json`), Cursor (`.cursor/mcp.json`) or VS Code (`.vscode/mcp.json`), naming the binary this extension runs |
| Read-only mode | Set `lucisv.mcp.mode` to `read-only` and the server is `lucisv read-only (<folder>)`, started with `--read-only`: the five read tools only (`hierarchy`, `find`, `outline`, `read`, `check`), and no file in the workspace is ever written. The copied config follows the setting (server key `lucisv-ro`, so both can sit in one file) |
| No binary, no error | With the universal package and no `lucisv-mcp` on `PATH`, one line in the lucisv output channel says so; nothing else changes |
The server reads files from disk, never unsaved buffers — save before asking
an agent about a file. The extension starts it as `lucisv-mcp --root <folder>
--index-cache <workspace storage>`. On VS Code older than 1.101 nothing is
--index-cache <workspace storage>` (plus `--read-only` in read-only mode). On VS Code older than 1.101 nothing is
registered (the engine requirement stays `^1.82.0`; `vsce` accepts the
contribution point there). The tool list and the snippets are in the
[Agents (MCP) guide](https://git.luci.ooo/lucio/lucisv/src/branch/master/docs/site/src/content/docs/guides/agents.md).
@@ -328,6 +329,7 @@ Server-side templates add `if`, `if/else`, `else if`, `case`, `for`, `while`,
| `lucisv.serverPath` | bundled | Explicit server override for advanced use; an unchanged setting uses the bundled server |
| `lucisv.mcp.enabled` | `true` | Offer `lucisv-mcp` to VS Code's agent mode (1.101+), one server per workspace folder; `false` withdraws it without a reload |
| `lucisv.mcp.path` | `""` | A `lucisv-mcp` to use instead of the bundled one (empty: bundled, else `PATH`); also what **lucisv: Copy MCP server config** names |
| `lucisv.mcp.mode` | `"full"` | `"read-only"`: offer agent mode only the five read tools (`lucisv-mcp --read-only`, listed as `lucisv read-only (<folder>)`), without a reload; any other value is treated as read-only; also the mode **lucisv: Copy MCP server config** copies (key `lucisv-ro`) |
| `lucisv.verbose` | `false` | Print how long every operation took in the lucisv output channel — one `timing:` line per request, notification, scan, widen, buffer flush, and per request that had to wait behind a rescan. **Restarts the language server when changed**, because it is an argument the server is started with |
The six `lucisv.index.*` settings and `lucisv.largeFile.threshold` arrive with
@@ -402,6 +404,23 @@ Every nesting color is a proper VS Code theme color:
}
```
## Release 0.60.0 highlights
Version 0.60.0 makes a generate block label a real name: renaming it
rewrites its closing label and every hierarchical path through the block,
in the same file or any other, and Find All References lists them. Rename
warnings now name only the spellings that can reach the renamed
declaration — another module's same-named signal is left out, a path or a
macro that carries the name onward is not.
## Release 0.59.0 highlights
Version 0.59.0 adds a read-only mode to `lucisv-mcp`: with
`lucisv.mcp.mode` set to `read-only` (or `--read-only` on the command
line) the agent sees five tools — hierarchy, find, outline, read, check —
in under 1.8 kB, and the server never writes inside the project. The full
nine-tool mode is unchanged and stays the default.
## Release 0.58.0 highlights
Version 0.58.0 slims `lucisv-mcp` to nine tools whose whole catalogue is
+34 -12
View File
@@ -52,26 +52,43 @@ function mcpEnabled() {
return vscode.workspace.getConfiguration('lucisv').get('mcp.enabled') !== false;
}
/**
* Whether the server runs `--read-only`. Only unset or exactly `"full"` is full
* mode: a value that is neither setting (`"readonly"`, `null`, a number) fails
* safe to read-only, and says so in one line through `log`.
*/
function readOnlyMode(log = () => {}) {
const mode = vscode.workspace.getConfiguration('lucisv').get('mcp.mode');
if (mode === undefined || mode === 'full') return false;
if (mode !== 'read-only') {
log(`lucisv: lucisv.mcp.mode is "${String(mode)}", not "full" or "read-only"; using read-only.`);
}
return true;
}
/** The workspace folders' paths, in order. */
function folderPaths() {
return (vscode.workspace.workspaceFolders || []).map((folder) => folder.uri.fsPath);
}
/**
* One stdio definition per workspace folder, or none while the setting is off.
* One stdio definition per workspace folder, or none while the setting is off;
* in read-only mode each gets `--read-only` and says so in its label.
* The constructor is positional (label, command, args, env, version) in
* vscode.d.ts — an object argument would become the label — and `cwd` is a
* plain property set afterwards.
*/
function serverDefinitions(context, bundledBinary, version) {
function serverDefinitions(context, bundledBinary, version, log) {
if (!mcpEnabled()) return [];
const command = resolveBinary(context, bundledBinary);
const storage = (context.storageUri || context.globalStorageUri || {}).fsPath;
const readOnly = readOnlyMode(log);
return (vscode.workspace.workspaceFolders || []).map((folder) => {
const args = ['--root', folder.uri.fsPath];
if (storage) args.push('--index-cache', storage);
if (readOnly) args.push('--read-only');
const definition = new vscode.McpStdioServerDefinition(
`lucisv (${folder.name})`,
readOnly ? `lucisv read-only (${folder.name})` : `lucisv (${folder.name})`,
command,
args,
{},
@@ -82,28 +99,33 @@ function serverDefinitions(context, bundledBinary, version) {
});
}
/** The JSON a host's config file wants for this server, pretty-printed. */
function configSnippet(host, command, roots) {
/**
* The JSON a host's config file wants for this server, pretty-printed. A
* read-only server is keyed `lucisv-ro`, so both snippets can be pasted side by side.
*/
function configSnippet(host, command, roots, readOnly = false) {
const args = roots.flatMap((root) => ['--root', root]);
if (readOnly) args.push('--read-only');
const server = host.stdioType ? { type: 'stdio', command, args } : { command, args };
return JSON.stringify({ [host.key]: { lucisv: server } }, null, 2);
return JSON.stringify({ [host.key]: { [readOnly ? 'lucisv-ro' : 'lucisv']: server } }, null, 2);
}
/** Ask which host, copy its snippet, and say which file it goes in. */
async function copyConfig(context, bundledBinary) {
/** Ask which host, copy its snippet in the configured mode, and say which mode and file. */
async function copyConfig(context, bundledBinary, log) {
const picked = await vscode.window.showQuickPick(
HOSTS.map((host) => ({ label: host.label, description: host.file, host })),
{ placeHolder: 'Copy the lucisv MCP server config for…' },
);
if (!picked) return;
const command = resolveBinary(context, bundledBinary);
await vscode.env.clipboard.writeText(configSnippet(picked.host, command, folderPaths()));
const readOnly = readOnlyMode(log);
await vscode.env.clipboard.writeText(configSnippet(picked.host, command, folderPaths(), readOnly));
const bundled = bundledBinary && bundledBinary(context, BINARY);
const moving = command === bundled
? ' The binary path points into this extension and changes when it updates.'
: '';
vscode.window.showInformationMessage(
`lucisv: copied the ${picked.host.label} MCP config — paste it into ${picked.host.file}.${moving}`,
`lucisv: copied the ${picked.host.label} MCP config (${readOnly ? 'read-only' : 'full'} mode) — paste it into ${picked.host.file}.${moving}`,
);
}
@@ -143,7 +165,7 @@ function activate(context, helpers = {}) {
const { bundledBinary, outputChannel } = helpers;
const log = (line) => outputChannel && outputChannel.appendLine(line);
context.subscriptions.push(
vscode.commands.registerCommand('lucisv.mcp.copyConfig', () => copyConfig(context, bundledBinary)),
vscode.commands.registerCommand('lucisv.mcp.copyConfig', () => copyConfig(context, bundledBinary, log)),
);
if (!hasMcpApi()) {
log('lucisv: this VS Code has no MCP server API (needs 1.101+); use "lucisv: Copy MCP server config" for other agents.');
@@ -156,7 +178,7 @@ function activate(context, helpers = {}) {
changed,
vscode.lm.registerMcpServerDefinitionProvider(PROVIDER_ID, {
onDidChangeMcpServerDefinitions: changed.event,
provideMcpServerDefinitions: () => serverDefinitions(context, bundledBinary, version),
provideMcpServerDefinitions: () => serverDefinitions(context, bundledBinary, version, log),
resolveMcpServerDefinition: (definition) => resolveDefinition(definition, log),
}),
vscode.workspace.onDidChangeWorkspaceFolders(() => changed.fire()),
+48 -14
View File
@@ -2,11 +2,13 @@
// provider does (`--root <folder> --index-cache <dir>`, the folder as cwd) over
// a tiny temporary project and drive one MCP session at it over stdio —
// initialize, notifications/initialized, tools/list, one `hierarchy` without a
// root (the project overview).
// root (the project overview). With `--read-only` the server is started in that
// mode and the smoke expects the five read tools, then one `rename` answered
// with the unknown-tool error, and the project's files untouched (PLAN §11).
// Plain node, no dependencies, hand-rolled newline-delimited JSON-RPC, like
// `smoke.js` does for the language server.
//
// node mcp_smoke.js [path-to-lucisv-mcp] [--tool-table]
// node mcp_smoke.js [path-to-lucisv-mcp] [--read-only] [--tool-table]
//
// `--tool-table` also prints the tools as the Markdown table checked into
// docs/site/src/content/docs/guides/agents.md, so that page is regenerated
@@ -19,13 +21,20 @@ const path = require('path');
const args = process.argv.slice(2);
const toolTable = args.includes('--tool-table');
const named = args.find((arg) => arg !== '--tool-table') || 'lucisv-mcp';
const readOnly = args.includes('--read-only');
const named = args.find((arg) => arg !== '--tool-table' && arg !== '--read-only') || 'lucisv-mcp';
// Resolved now: the server runs with the temporary project as its cwd, where a
// relative path would no longer point at the binary. A bare name stays a PATH lookup.
const binary = /[\\/]/.test(named) ? path.resolve(named) : named;
/** The lean catalogue, in order (PLAN §10.1, TODO-MCP M7). */
const TOOLS = ['hierarchy', 'find', 'outline', 'read', 'check', 'rename', 'port', 'edit_item', 'format'];
const FULL_TOOLS = ['hierarchy', 'find', 'outline', 'read', 'check', 'rename', 'port', 'edit_item', 'format'];
/** What this run expects `tools/list` to be: `--read-only` offers the five reads (PLAN §11.1). */
const TOOLS = readOnly ? FULL_TOOLS.slice(0, 5) : FULL_TOOLS;
/** The error a read-only server answers an edit tool with. */
const READ_ONLY_RENAME = { code: -32602, message: 'unknown tool: rename (the server runs --read-only)' };
/** Give up on a server that has not answered and exited by then. */
const TIMEOUT_MS = 30000;
@@ -35,14 +44,15 @@ function fail(message) {
throw new Error(message);
}
/** Two files, one instantiating the other: enough for a non-trivial overview. */
/** The project's two files: one instantiating the other, enough for a non-trivial overview. */
const SOURCES = {
'top.sv': 'module top (input logic clk);\n sub u_sub (.clk(clk));\nendmodule\n',
'sub.sv': 'module sub (input logic clk);\nendmodule\n',
};
function makeProject() {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'lucisv-mcp-smoke-'));
fs.writeFileSync(
path.join(root, 'top.sv'),
'module top (input logic clk);\n sub u_sub (.clk(clk));\nendmodule\n',
);
fs.writeFileSync(path.join(root, 'sub.sv'), 'module sub (input logic clk);\nendmodule\n');
for (const [name, text] of Object.entries(SOURCES)) fs.writeFileSync(path.join(root, name), text);
fs.mkdirSync(path.join(root, '.cache'));
return root;
}
@@ -62,11 +72,17 @@ const REQUESTS = [
{ jsonrpc: '2.0', id: 2, method: 'tools/list' },
{ jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: 'hierarchy', arguments: {} } },
];
if (readOnly) {
const rename = { name: 'rename', arguments: { name: 'sub', new_name: 'sub2' } };
REQUESTS.push({ jsonrpc: '2.0', id: 4, method: 'tools/call', params: rename });
}
/** Every request is written up front and stdin closed: the server answers in order and exits on EOF. */
function session(root) {
return new Promise((resolve, reject) => {
const server = spawn(binary, ['--root', root, '--index-cache', path.join(root, '.cache')], {
const flags = ['--root', root, '--index-cache', path.join(root, '.cache')];
if (readOnly) flags.push('--read-only');
const server = spawn(binary, flags, {
cwd: root,
stdio: 'pipe',
});
@@ -91,7 +107,10 @@ function session(root) {
});
}
/** Parse stdout, which must be JSON-RPC lines and nothing else. */
/**
* Parse stdout, which must be JSON-RPC lines and nothing else; only the
* read-only `rename` may be an error, kept under the key `'rename'` for `check`.
*/
function answers(stdout) {
const byId = new Map();
for (const line of stdout.split('\n').filter((l) => l.trim() !== '')) {
@@ -101,6 +120,10 @@ function answers(stdout) {
} catch {
fail(`stdout carried a line that is not JSON: ${line.slice(0, 200)}`);
}
if (readOnly && message.id === 4) {
byId.set('rename', message.error);
continue;
}
if (message.error) fail(`request ${message.id} failed: ${JSON.stringify(message.error)}`);
byId.set(message.id, message.result);
}
@@ -116,7 +139,14 @@ function check(byId) {
const listed = byId.get(2);
const tools = (listed && listed.tools) || [];
const names = tools.map((tool) => tool.name).join(', ');
if (names !== TOOLS.join(', ')) fail(`tools/list is [${names}], expected [${TOOLS.join(', ')}]`);
if (names !== TOOLS.join(', ')) {
fail(`tools/list is ${tools.length} tools [${names}], expected ${TOOLS.length} [${TOOLS.join(', ')}]`);
}
// Checked after the tool list, so a server ignoring --read-only fails on its nine tools.
const renameError = byId.get('rename');
if (readOnly && JSON.stringify(renameError) !== JSON.stringify(READ_ONLY_RENAME)) {
fail(`rename in read-only mode answered ${JSON.stringify(renameError)}, expected ${JSON.stringify(READ_ONLY_RENAME)}`);
}
const overview = byId.get(3);
if (!overview) fail('no hierarchy answer');
if (overview.isError) fail(`hierarchy is an error: ${JSON.stringify(overview.content)}`);
@@ -146,8 +176,12 @@ async function main() {
const { code, stdout } = await session(root);
const { init, tools } = check(answers(stdout));
if (code !== 0) fail(`the server exited with status ${code} after stdin closed`);
for (const [name, text] of Object.entries(SOURCES)) {
if (fs.readFileSync(path.join(root, name), 'utf8') !== text) fail(`${name} was written`);
}
const mode = readOnly ? ' (--read-only), rename refused' : '';
console.log(
`mcp smoke: OK — "${binary}" ${init.serverInfo.version}: initialize, ${tools.length} tools, hierarchy`,
`mcp smoke: OK — "${binary}" ${init.serverInfo.version}: initialize, ${tools.length} tools, hierarchy${mode}`,
);
if (toolTable) console.log(markdownTable(tools));
} finally {
+89 -2
View File
@@ -1,5 +1,6 @@
// Checks for `mcp.js`: the binary ladder, the provider registration and its
// guard on a VS Code without the MCP API, and the copy-config snippets.
// guard on a VS Code without the MCP API, the copy-config snippets, and the
// read-only mode (`lucisv.mcp.mode`).
//
// node mcp_test.js
//
@@ -156,6 +157,54 @@ function changesAreAnnounced() {
configListener({ affectsConfiguration: (section) => section === 'lucisv.mcp' });
configListener({ affectsConfiguration: () => false });
assert.equal(emitter.fired, 2, 'folder change and lucisv.mcp change fire; other settings do not');
// VS Code answers a section prefix of the changed key: `lucisv.mcp.mode` affects `lucisv.mcp`.
configListener({ affectsConfiguration: (section) => 'lucisv.mcp.mode'.startsWith(section) });
assert.equal(emitter.fired, 3, 'a change of lucisv.mcp.mode fires');
}
function readOnlyModeDefinitions() {
const contributed = require('./package.json').contributes.configuration.properties['lucisv.mcp.mode'];
assert.equal(contributed.default, 'full');
assert.deepEqual(contributed.enum, ['full', 'read-only']);
reset();
folders = [folder('alpha'), folder('beta')];
settings['mcp.mode'] = 'read-only';
mcp.activate(context(), { bundledBinary: bundled(true) });
const provider = registered[0].provider;
const definitions = provider.provideMcpServerDefinitions();
assert.deepEqual(definitions.map((d) => d.label), ['lucisv read-only (alpha)', 'lucisv read-only (beta)']);
assert.deepEqual(definitions[0].args, ['--root', '/work/alpha', '--index-cache', '/storage/ws', '--read-only']);
settings['mcp.mode'] = 'full';
const full = provider.provideMcpServerDefinitions()[0];
assert.equal(full.label, 'lucisv (alpha)', 'back to full: the plain label');
assert.ok(!full.args.includes('--read-only'), 'back to full: no flag');
}
function anUnknownModeFailsSafeToReadOnly() {
reset();
const log = [];
mcp.activate(context(), { bundledBinary: bundled(true), outputChannel: { appendLine: (l) => log.push(l) } });
const provider = registered[0].provider;
const first = () => provider.provideMcpServerDefinitions()[0];
// Unset and exactly "full": full mode, nothing logged.
for (const value of [undefined, 'full']) {
settings['mcp.mode'] = value;
assert.equal(first().label, 'lucisv (alpha)', `${value}: full`);
assert.ok(!first().args.includes('--read-only'), `${value}: no flag`);
}
// Exactly "read-only": read-only, nothing logged.
settings['mcp.mode'] = 'read-only';
assert.equal(first().label, 'lucisv read-only (alpha)');
assert.deepEqual(log, [], 'a valid setting logs nothing');
// Anything else: read-only, one line naming the value.
for (const value of ['Read-Only', 'readonly', 'Full', null, true, 3]) {
settings['mcp.mode'] = value;
log.length = 0;
const definition = first();
assert.equal(definition.label, 'lucisv read-only (alpha)', `${value}: read-only`);
assert.equal(definition.args[definition.args.length - 1], '--read-only', `${value}: flag`);
assert.deepEqual(log, [`lucisv: lucisv.mcp.mode is "${String(value)}", not "full" or "read-only"; using read-only.`]);
}
}
function disabledOffersNothing() {
@@ -221,6 +270,7 @@ async function theThreeSnippets() {
assert.equal(informed.length, 1);
assert.ok(informed[0].includes(file), `${label}: names ${file}`);
assert.ok(informed[0].includes('changes when it updates'), `${label}: warns the bundled path moves`);
assert.ok(informed[0].includes('(full mode)'), `${label}: names the mode`);
}
reset();
settings.inspectPath = { globalValue: '/usr/local/bin/lucisv-mcp' };
@@ -236,15 +286,52 @@ async function theThreeSnippets() {
assert.deepEqual(copied, [], 'a dismissed pick copies nothing');
}
async function theReadOnlySnippets() {
const args = ['--root', '/work/alpha', '--read-only'];
const want = {
'Claude Code': { mcpServers: { 'lucisv-ro': { command: '/ext/bin/lucisv-mcp', args } } },
Cursor: { mcpServers: { 'lucisv-ro': { command: '/ext/bin/lucisv-mcp', args } } },
'VS Code': { servers: { 'lucisv-ro': { type: 'stdio', command: '/ext/bin/lucisv-mcp', args } } },
};
for (const [label, json] of Object.entries(want)) {
reset();
settings['mcp.mode'] = 'read-only';
pickLabel = label;
mcp.activate(context(), { bundledBinary: bundled(true) });
await commands.get('lucisv.mcp.copyConfig')();
assert.equal(copied[0], JSON.stringify(json, null, 2), `${label}: exact read-only JSON`);
assert.ok(informed[0].includes('(read-only mode)'), `${label}: names the mode`);
}
// An unknown value copies the read-only server too, and says why.
reset();
settings['mcp.mode'] = 'readonly';
pickLabel = 'Claude Code';
const log = [];
mcp.activate(context(), { bundledBinary: bundled(true), outputChannel: { appendLine: (l) => log.push(l) } });
await commands.get('lucisv.mcp.copyConfig')();
assert.equal(copied[0], JSON.stringify(want['Claude Code'], null, 2), 'readonly: the lucisv-ro snippet');
assert.ok(informed[0].includes('(read-only mode)'));
assert.deepEqual(log, ['lucisv: lucisv.mcp.mode is "readonly", not "full" or "read-only"; using read-only.']);
// Two keys: the full and the read-only server fit in one config file.
const host = mcp.HOSTS[0];
const full = JSON.parse(mcp.configSnippet(host, 'b', ['/r']));
const readOnly = JSON.parse(mcp.configSnippet(host, 'b', ['/r'], true));
const both = { mcpServers: { ...full.mcpServers, ...readOnly.mcpServers } };
assert.deepEqual(Object.keys(both.mcpServers), ['lucisv', 'lucisv-ro']);
}
async function run() {
theLadder();
oneDefinitionPerFolder();
changesAreAnnounced();
readOnlyModeDefinitions();
anUnknownModeFailsSafeToReadOnly();
disabledOffersNothing();
anOldVsCodeRegistersNothing();
aMissingBinaryIsNotStarted();
await theThreeSnippets();
console.log('mcp: OK — binary ladder, one definition per folder, change events, enabled:false, old-VS Code guard, missing binary, three config snippets');
await theReadOnlySnippets();
console.log('mcp: OK — binary ladder, one definition per folder, change events, read-only definitions, unknown mode fails safe to read-only, enabled:false, old-VS Code guard, missing binary, three config snippets in both modes');
}
run().catch((error) => {
+14 -1
View File
@@ -2,7 +2,7 @@
"name": "lucisv",
"displayName": "lucisv — Verilog/SystemVerilog",
"description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.",
"version": "0.58.0",
"version": "0.60.0",
"publisher": "guoliangchen",
"author": "Guoliang Chen",
"license": "MIT",
@@ -291,6 +291,19 @@
"default": "",
"markdownDescription": "Path to the `lucisv-mcp` executable. Empty (the default) uses the one bundled with the extension, else `lucisv-mcp` on PATH. Also the binary **lucisv: Copy MCP server config** names."
},
"lucisv.mcp.mode": {
"type": "string",
"enum": [
"full",
"read-only"
],
"enumDescriptions": [
"All nine tools: the five reads and the four verified edits (rename, port, edit_item, format).",
"The five read tools only (hierarchy, find, outline, read, check): the server never writes a file in the workspace."
],
"default": "full",
"markdownDescription": "Which tools `lucisv-mcp` offers agent mode. `read-only` starts it with `--read-only` (listed as **lucisv read-only (folder)**): the five read tools, never a write inside the workspace. Any other value is treated as read-only. Also the mode **lucisv: Copy MCP server config** copies (server key `lucisv-ro`)."
},
"lucisv.verbose": {
"type": "boolean",
"default": false,
+67
View File
@@ -303,6 +303,63 @@ nothing where the old one cost 15–25 %; the small edit tasks now sit at
server's answers. The remaining gap is bounded by how the agent works, not
by what the server sends.
## Round 5 — server at b757e82 (M8, read-only mode)
`lucisv-mcp --read-only`: five tools (`hierarchy, find, outline, read,
check`), a 1 797-byte catalogue, 297-byte instructions, and no way to
write. Only the two read tasks apply. Each arm ran twice; **the base arm
was re-run the same day as a control**, and that control is the finding.
| task | arm | model | tokens | tool calls | wall | outcome |
|---|---|---|---|---|---|---|
| a | read-only | Sonnet 5 | 67 230 | 7 | 41 s | correct, 47/47 |
| a | read-only (re-run) | Sonnet 5 | 72 361 | 7 | 56 s | correct, 47/47 |
| a | base (same day) | Sonnet 5 | 64 817 | 3 | 40 s | correct, 47/47 |
| a | read-only, cap fixed | Sonnet 5 | 72 247 | 8 | 50 s | correct, 47/47 |
| d | read-only | Sonnet 5 | 80 487 | 10 | 121 s | correct, 71/20, all counts |
| d | read-only (re-run) | Sonnet 5 | 67 104 | 8 | 151 s | correct, 71/20, all counts |
| d | base (same day) | Sonnet 5 | 80 194 | 10 | 78 s | correct, 71/20, all counts |
### Observations
**Against the old base figures the read-only mode looks 23–28 % cheaper;
against a same-day base it is at parity** (a: mean 69.8 k vs 64.8 k, +8 %;
d: mean 73.8 k vs 80.2 k, −8 %). The base arm itself fell from 91.1 k to
64.8 k on task a and from 102.6 k to 80.2 k on task d between 2026-09-23
and 2026-09-29 with no change to the task, the clone or the prompt: the
sub-agent environment changed under the census. Two consequences. Rounds
1–4 compared each mcp arm with a base arm measured the same day or within
a day, so their deltas stand; round 5 must not be compared with them, and
no figure in this file should be read as an absolute. And every future
round needs its base arm re-run alongside.
- **a: the server's own answer was cut short.** Both read-only runs asked
`hierarchy up` with `peek` (they needed the `#(…)` values), and the
300-line cap, which counted peek lines, showed 20 of 77 instantiations
and `… and 56 more`. Both agents then scanned the RTL sources themselves
— which is what the base arm does, in 3 calls. Without `peek` the same
call lists all 77 in 77 lines. Fixed after the round: the cap counts
instances (300, or 100 with `peek`, which bounds a peeked answer near
40 kB), peek lines do not count (0.59.0). Re-measured on the fixed
binary: the one call now returns all 77 with their source (31 kB), the
agent reported the server and its own search agreed — and still ran the
search, so the cost did not move (72.2 k). A complete answer removes the
need for the fallback; it does not remove the agent's habit of checking.
- **d: the server answered.** `hierarchy` at depth 1 gave the 71 instances
in one call and `outline unit:` the port counts; 8–10 calls, the same as
the base arm's 10, with a wider spread in wall time (the shim re-indexes
on every call).
- **Catalogue.** Through the shim the read-only `--list` is 1.1 kB
(≈ 300 tokens) against 2.1 kB for the nine tools; a native host sends
1.8 kB of schemas against 3.4 kB. The saving is real and small: a few
hundred tokens per session, below the run-to-run noise of any task here.
**What the round says.** Read-only mode does what it is for: a smaller
surface that cannot write, with the same answers. It does not change the
token picture, and nothing at the catalogue level will: on these tasks
the model's own reading and answer dominate, and a current Sonnet with
plain file tools is already efficient at both.
## Verdict, and what to do next
**Helpful, not a toy — for the questions an engine answers better than
@@ -334,6 +391,16 @@ them as file writes"), not the server. For scoped edits (b) a design-wide
`port add` is the wrong tool and the agent should edit the two files; for
renames (c) the `unresolved:` list is what makes 8/8 repeatable.
**After round 5 (read-only mode, 0.59.0).** Six more runs, all correct.
With a same-day base control the read-only server is at parity with file
tools on both read tasks (+8 %, −8 %), and the control showed the base arm
itself had become 22–29 % cheaper in six days — so no round here supports
an absolute claim, only same-day comparisons. The round also found a real
defect (the `peek` cap cutting `hierarchy up` to a quarter of its answer),
fixed in 0.59.0. The honest summary of five rounds: the server is correct
and safe, it matches file tools on cost, and it does not beat them on
these tasks with these models.
**Superseded by the ruling above — kept for the record.** (feedback-3 and
after, as planned before round 4): the instantiation template opt-in
on `unit_interface`; a terser `hierarchy` line (overrides only on request);
+240
View File
@@ -0,0 +1,240 @@
# Independent review: uncommitted TODO §65.1 work (2026-10-06)
## Scope
This review covers the uncommitted working tree on `master`, on top of `b9ee399`. That is 47 modified files and 16 new ones, about 4.8k lines including tests:
- §65.1, generate-label rename and references;
- rename warnings and mentions scoped to the renamed declaration (the "home set", reworks 3–5);
- the MCP `block` refusal lifted;
- `duplicate-declaration` extensions;
- R1, path-qualified file names in messages.
It is a read-only review. The only file written is this one.
**Method:**
- I checked the gates and the docs myself.
- Two Opus reviewers took a slice each:
- A: `vlog_semantic`, `vlog_refactor/src/check`, `vlog_linter`;
- B: `vlog_refactor/src/rename`, `ports`, `lucisv_server`, `lucisv_mcp`.
- The reviewers reproduced their findings with scratch probe crates in the scratchpad, not in the repo.
- I re-read the code for each high finding and for the confirmed bug.
## Gates (run by me, all through `tools/guard.sh`)
| Gate | Result |
|---|---|
| `cargo fmt --all --check` | clean |
| `cargo clippy --workspace --all-targets` | exit 0, 0 warnings |
| `cargo test --workspace --all-targets` | guard exit 0 (no kill); 79 suites, **5 064 passed, 0 failed, 51 ignored** |
| doc-tests | **not run**. Excluded on purpose because of the open §65.3 stall, so this gate is still open for the release. |
| corpus / opentitan byte-identity | not run (no formatter change in the diff) |
| File size | Every touched production file is under 600 lines. Largest: `resolve.rs` 559, `rename/warnings.rs` 529, `rename/connections.rs` 477. Functions are all under 50 lines (reviewer A). |
**Verdict:** the generate-label part (§65.1 proper) is sound. Two high findings are in the newer warning-scoping work: it silently drops warnings that 0.59.0 gave. That breaks the feature's own rule that scoping may drop a warning only when the spelling provably cannot reach the declaration. **I would not ship 0.60.0 until H-1 and H-2 are fixed or the scoping is reverted to unscoped for those shapes.**
---
## HIGH
> **H-1 and H-2 fixed 2026-10-06:** new `vlog_refactor/src/rename/carry.rs` (carried macro arguments, binder macros); tests `vlog_refactor/tests/rename_macro_carry.rs` (8) and 4 unit tests in `carry.rs`; work log in `docs/features/generate-label-rename/README.md`. OpenTitan warnings unchanged on the renames measured (no added noise).
### H-1. A bare macro argument that the macro body turns into a path or a named connection is silently dropped (regression vs 0.59.0) — **FIXED 2026-10-06**
- **Where:**
- `crates/vlog_refactor/src/rename/scoped.rs:149-158` (`bare_is_news`)
- `crates/vlog_refactor/src/rename/warnings.rs:255-259` (the filter in `macro_use_warnings`)
- **The cause:** in a file that is not the declaring file and not an included or including fragment, `bare_is_news` returns `false` unconditionally. Edited instantiators and testbenches are such files. I confirmed this in the code. That is only safe if the macro uses its formal as a plain expression. It is wrong whenever the body puts the formal after a `.`, after a `` `` `` paste, or into a `.x(x)` connection.
- **Repros** (reviewer B; rename `m.state_q`, where `state_q` is a port of `m`). Each one renames with **no warning**; at HEAD each one warned:
- **PC (realistic):** `` `define CONN(x) .x(x) `` with `m u_m (.clk(clk), `CONN(state_q));` in `top.sv`.
- The port is renamed and the instantiation breaks.
- The MCP also drops the mention (`mentions.rs`: no `.` right before it).
- **PA:** `` `define FORCE(sig) force u_m.sig = 1'b0; `` invoked as `` `FORCE(state_q) `` in `tb.sv`. The result is the same when `tb.sv` is edited.
- **PA2:** `` `define PEEK(sig) u_m.``sig ``.
- **Suggested fix:** drop a bare argument only when every definition of the invoked macro in the set uses that formal nowhere after `.`, after `` `` ``, or as `.formal(`. If the macro is unknown or ambiguous, keep the warning. The bodies are already collected (`define_bodies`).
- **Missing tests:** PC, PA and PA2 in `qa_warning_scope.rs`. The existing tests only use `` `Q(x) x `` and `ASSERT`.
### H-2. A `bind` produced by a macro expansion is invisible to K2 and H3 — **FIXED 2026-10-06**
- **Where:** `scoped.rs:162-174` (`files_binding_into`) and `scoped.rs:~236` (`binds_into`).
- **The cause:** both functions look only at literal `bind` tokens.
- **Effect:** take a `` `define`` whose body is `bind m chk u (.s(state_q));`, invoked from a file outside the home set. That file is never added to the home set, so the bare `state_q` in the body is silenced (reviewer B, repro PD).
- **Related:** this has the same root cause as H-1: macro expansion moves text into `m`'s scope. One "macro body may carry the name into the unit" rule would cover both.
---
## MEDIUM
### M-1. The H4 fragment warning reports uses the rename *did* edit as "left unchanged" — **FIXED 2026-10-07**
- **Where:** `scoped.rs:~181-231` (`fragment_use_warnings` / `bare_unbound_uses`). It ignores the rename's edit ranges.
- **Repro** (reviewer B, PI):
- `all.sv` includes `m.sv` and `n.sv`;
- `n.sv` has `m u_m(...)`;
- renaming module `m` edits `n.sv:2`, yet the engine warns "`n.sv:2`: `m` is used in a file that includes `m.sv` or is included with it and was left unchanged".
- **Effect:** it misleads users and agents, and it fires for modules, packages (`p::X`) and every include-wrapper layout.
- **Suggested fix:** skip tokens covered by this rename's edits.
### M-2. Naming files in warnings is quadratic: about 0.5 s per rename on opentitan — **FIXED 2026-10-07**
- **Where:**
- `vlog_refactor/src/scope.rs:~341-345` (`name_of`) scans every source on each call.
- `define_warnings` (`warnings.rs:~202`) and `macro_use_warnings` (`warnings.rs:242`) compute `name_at(file)` for every file of the set **before** checking for sites.
- **Measured** (reviewer B):
- One pass over the 3 979 files takes 245 ms, and there are two passes.
- That is about 490 ms of a 2.93 s `entropy_src_main_sm.state_q` rename.
- **Suggested fix:** compute the name only when sites exist, or build base-name counts once per `Scope`.
- **Same pattern, smaller cost:** `ports/offer.rs:251` (`name_among` per mentioning file, on the code-action path).
### M-3. The docs contradict the code and leave out the last fix — **FIXED 2026-10-07**
- **README says engine and verifier are unchanged.** `docs/features/generate-label-rename/README.md:68-69` says "The rename engine (`vlog_refactor/src/rename/`) and the verifier (`check/`) are unchanged in code". `refactor-rename/README.md` (the 2026-09-30 work log) and topo row 43 say the same. All three are stale:
- reworks 2–5 added `rename/{arms,home,paths,scoped}.rs` and rewrote `warnings.rs`;
- `check/{implicit,ledger,mod}.rs` changed for R1 message naming.
- Reviewer A confirmed the `check/` change is message-only and widens no forgiveness, so invariant 4 is not triggered. The sentence is still false as written.
- **"What changed" stops at the first pass.** Reworks 1–5 are only in the work log.
- **Status / TODO does not list reworks 2–5 or the §65.6 filing** (it ends at "§65.4 filed").
- **The P1/P2 fix after QA's closing check is undocumented:**
- The QA log (line ~984) records 2 ignored tests (P1, P2) as open findings.
- The code now handles both (`keeps_define_body` checks `dotted` first and takes `default_bare`), and both tests run un-ignored and pass.
- There is no dev work-log entry for this fix, and no QA re-check.
- The doc comment of `rework5_a_shadowing_parameter_does_not_hide_a_dotted_body_spelling` (`tests/qa_warning_scope.rs:463-467`) still says "rework 5 does not".
- **Topo row 40 not amended.** Topo row 43 says the fix "also answers row 40's second half", but row 40 itself is not amended.
- **CHANGELOG 0.60.0 has two scoping bullets that disagree.**
- The first ("only … in the declaring module … or in a file the rename edits") is superseded by the second (the home set). They should be merged.
- The text says "a macro whose parameter is named like the declaration … [is] not" reported, without the dotted-body exception that now applies.
---
## LOW
### L-1. The closing-label fallback attaches a mismatched label to the wrong block (confirmed bug)
- **Where:** `vlog_semantic/src/bind/mod.rs:366-369` (`use_end_label`).
- **The cause:** when the body has no owner, the fallback takes the first same-scope symbol named like the *closing* label, if it is a `Block`. It never compares against the opening label of the construct being closed. The later `name != label` check is then trivially true. I confirmed this in the code.
- **Repro 1** (reviewer A):
```
initial begin : a … end : a
initial b: begin … end : a
```
- The mismatched `end : a` resolves to block `a`.
- `rename a → z` rewrites it.
- This contradicts the function's own doc ("a label that does not spell the declared name … records nothing").
- **Repro 2:**
```
if (1) begin : g … end : g
function … g(); … endfunction : g
```
- The `endfunction : g` becomes a use of block `g`, contrary to the README's F3 assumption ("neither is a use of the other").
- The verifier refuses the rename here, so nothing is corrupted.
- **Effect:** only already-invalid code reaches this.
- **Suggested fix:** limit the fallback to block constructs. For the `lbl: begin` form, compare against the statement's own label.
### L-2. `duplicate-declaration` misses repeated generate labels, and the result depends on order
- **Where:** `vlog_linter/src/rules/duplicate_declaration.rs:97-103` (`collides`, the `(true,true)` arm).
- **The cause:** the arm skips any pair whose first label opens a generate scope. That is meant for the arms of one `if`/`case`, but it also hides two sibling `for … begin : g` loops. Both elaborate, so that is a compile error.
- **Order dependence:** `initial begin : g` followed by `if (1) begin : g` is flagged; the reverse order is not.
- This is not a regression.
### L-3. Dotted detection skips only whitespace
- **Where:** `scoped.rs:~309` (`spellings`).
- **Missed shapes:** `u_m.``state_q`, `u_m./*x*/state_q`, and a macro argument `` `Q(u_m. /* c */ state_q) `` are all treated as bare and silenced in non-home files (reviewer B, repros PL, PM, PE).
### L-4. A file that fails to lex drops its warnings without saying so
- `files_binding_into` (`scoped.rs:171`) treats a lex failure as "no bind", so the macros invoked there are not followed (repro PH: an unterminated string in `binds.sv`).
- `fragment_use_warnings` (`scoped.rs:~190`) silently skips a fragment that fails to lex or analyse.
- By the feature's own rule, any doubt should fall back to unscoped.
### L-5. Paths through an interface port or virtual interface into an interface's generate block stay unresolved
- **Where:** `vlog_semantic/src/workspace/hierarchy.rs:~114`. `Block` is only on the interface's *hierarchical* surface, but `bus.g_mon.seen` and `vif.g_mon.seen` are looked up on the connection surface.
- **Effect:** the rename leaves them unchanged. It does warn ("could not be resolved"), so the rename is not silently partial. But the Goal and CHANGELOG read as if every path through a block is covered.
- **Suggested fix:** document this shape, or add `Block` to the interface's connection surface.
### L-6. `binds_into` misses a bind whose target is a bare instance name
- **Where:** `scoped.rs:~244-248`.
- **Missed shape:** `bind u_m chk …` written inside the parent, which the LRM allows. Rare.
### L-7. Macro names passed as arguments are not followed
- **Where:** `home.rs:~215` (`macro_names`).
- **Missed shape:** with `` `define APPLY(m) `m ``, the call `` `APPLY(CHK) `` never follows `CHK`'s body. Contrived.
### L-8. A child module's bare call to a parent function is not covered
- Upward name resolution (IEEE 1800 §23.8) lets a child call a module function `f()` bare.
- A macro-argument spelling of `f` in the child is now dropped. The plain-code case was never handled.
- Rare.
### L-9. The MCP and the engine disagree on what counts as dotted, and on the home set
- `mentions.rs:109-113`: the MCP counts a mention as dotted only when the byte right before it is a `.`. The engine skips blanks first.
- `edit.rs:169` and `find.rs:130`: `Focus::local` uses `home_set`, which does not include the K2 bind files.
- **Effect:** in both cases the engine still warns and only the MCP mention is dropped. Not silent, just inconsistent.
### L-10. `Semantics::member_key` disagrees with its doc for inline nested struct members
- **Where:** `vlog_semantic/src/lib.rs:298-304`. It returns the bare `owner.name`, but the index files these members under `nested_key` (`reg2hw_t.ctrl`, `record.rs:541-544`).
- Not a regression (it matches the old `nav.rs` behaviour), but the new public API's doc promises the index key.
### L-11. `generate … endgenerate` stopping being a scope is a visible behaviour change
- Two regions that each declare `genvar i;` now give `duplicate-declaration`. This is correct per IEEE 1800 §27.3, and the opentitan differential shows no change.
- Older Verilog-2001-style code will see new findings. The CHANGELOG mentions the scope change but not this lint consequence.
### L-12. Unchecked slice in library code
- **Where:** `vlog_refactor/src/rename/arms.rs:39`, `text[..other.name_span.start as usize]` with a `""` fallback for `text`.
- It panics only if the analysis and the text disagree. `.get(..)` would follow the no-panic rule.
### L-13. R1 is incomplete
- These multi-file messages still use bare `display()` instead of `name_of`:
- `inline/mod.rs:225` and `:313`;
- `ports/expand.rs:103` and `:320`;
- `extract/boundary.rs:158`.
---
## NIT
- **The index-transparency assumption is worded too broadly.** The README and `bind/expr.rs:241-249` claim it holds for every link the walk continues from. It is false for a scalar struct (`s[0].f` resolves) and for multi-dimensional packed struct arrays. Both are illegal SystemVerilog, so this is harmless. The cases that matter are fine: unpacked arrays, instance arrays and interface arrays still stop at the head.
- **Doc line too long.** `vlog_semantic/src/bind/item.rs:4`: a module doc line of 100 characters, not reflowed.
---
## Checked and found sound
- **Verifier (`check/`):** the only change is how files are named in messages. These names are never map keys, so no balancing can merge two files, and no normalization was added. The attack files `check/qa_block_paths.rs` (8 tests) and `check/qa_block_attacks.rs` (5) pin left-out, misplaced and extra edits on labels, closing labels, same-file and cross-file paths, split arms and genvar capture. Invariant 4 is not triggered.
- **Scoping:**
- A `for` label is declared in the enclosing scope, and the genvar does not leak.
- `g.x` looks only in the block's own scope.
- The outline is unchanged.
- Completion after `blk.` works.
- **Index:**
- `block_key` and `member_key` agree, including for function-local blocks (`m.ff().fb`).
- Block members go only into `hier_members`, so the port checks, the implicit-connection checks and the linter's interface checks are unaffected.
- `FACTS_FORMAT` is bumped to 21.
- **`home.rs`:**
- Include cycles end, and the upward closure is transitive.
- An include resolves by path suffix, then falls back to base name, taking every match.
- A macro-built include or an include of a file outside the set falls back to unscoped.
- `home_set` costs about 0.17 s in MCP `find refs` on opentitan.
- **`nav.rs`:** `member_key` equals `owner.name` for every non-block owner, so non-block references are unchanged.
- **MCP:**
- The `block` refusal is lifted, and `qa_m7` asserts the full rename.
- `path_warned` de-duplication is asserted in `wire.rs` and `qa_m7`.
- `rooted` builds its name table once per set.
- **Code rules:** no `unwrap`/`expect`/`panic` in new library code (L-12 is the one slice risk).
## Recommended before commit
1. Fix H-1 and H-2, or fall back to unscoped for a bare macro argument whose macro body carries it after `.`, `` `` `` or into a connection, or expands to a `bind`. Add tests PC, PA, PA2 and PD.
2. Fix M-1 by skipping edited ranges. Fix M-2 by computing names lazily.
3. Make L-4 conservative: fall back to unscoped when a file fails to lex.
4. Bring the docs up to date (M-3): the README's "What changed" and Status sections, a dev work-log entry for the P1/P2 fix plus a QA re-check, the stale test comment, topo rows 40 and 43, and the CHANGELOG bullets.
5. Run the doc-tests gate (§65.3) before release.
+4 -2
View File
@@ -127,8 +127,10 @@ It builds `--release`, copies the three binaries into `dist/` under
version-and-host names, smoke-tests the server binary with
`editors/vscode/smoke.js` and the MCP server with `editors/vscode/mcp_smoke.js`
(initialize, `tools/list` with exactly the nine tools in order, one `hierarchy`
over a tiny temporary project), packages the extension into `dist/lucisv-<version>.vsix`
and into the host's platform package, runs both smoke tests again against the
over a tiny temporary project; then again with `--read-only`: the five read
tools in order, one `hierarchy`, `rename` answered with the unknown-tool error
and the project's files untouched), packages the extension into `dist/lucisv-<version>.vsix`
and into the host's platform package, runs the smoke tests (the MCP one in both modes) again against the
binaries *unzipped out of* that package (and, with `--cross`, out of the `all`
package), and writes `dist/SHA256SUMS`. `dist/` is gitignored and is
deleted and recreated on every run.
+5 -2
View File
@@ -132,12 +132,14 @@ fi
# `smoke.js` is plain node with no dependencies, so this runs before `npm ci`.
# The MCP server gets the same treatment from `mcp_smoke.js`: initialize,
# tools/list (the nine tools, in order) and one `hierarchy` over stdio against a
# tiny temp project.
# tiny temp project; then again with `--read-only` (the five read tools, and
# `rename` answered with the unknown-tool error).
if command -v node >/dev/null 2>&1; then
echo "==> smoke-testing the server binary"
node "$repo_root/editors/vscode/smoke.js" "$dist/lucisv-server-$version-$host"
echo "==> smoke-testing the MCP server binary"
node "$repo_root/editors/vscode/mcp_smoke.js" "$dist/lucisv-mcp-$version-$host"
node "$repo_root/editors/vscode/mcp_smoke.js" "$dist/lucisv-mcp-$version-$host" --read-only
else
echo " note: no node on PATH, skipping the server and MCP smoke tests" >&2
fi
@@ -255,7 +257,7 @@ smoke_embedded_server() { # vsix file name, the bin/ path inside the package
}
# The same for the MCP server the package carries: unzipped, then driven through
# initialize, tools/list and one `hierarchy` by `mcp_smoke.js`.
# initialize, tools/list and one `hierarchy` by `mcp_smoke.js`, in both modes.
smoke_embedded_mcp() { # vsix file name, the bin/ path inside the package
vsix=$1
inner=$2
@@ -265,6 +267,7 @@ smoke_embedded_mcp() { # vsix file name, the bin/ path inside the package
unzip -q "$dist/$vsix" -d "$unpacked"
chmod +x "$unpacked/$inner/lucisv-mcp"
node "$repo_root/editors/vscode/mcp_smoke.js" "$unpacked/$inner/lucisv-mcp"
node "$repo_root/editors/vscode/mcp_smoke.js" "$unpacked/$inner/lucisv-mcp" --read-only
rm -rf "$unpacked"
}