Compare commits

...
11 Commits
Author SHA1 Message Date
lucioandClaude Fable 5.2 ea586d29bc Release smoke: the ranges probe expects a block laid out at its own indentation (TODO §66.2)
ci / checks (push) Successful in 1m54s
ci / corpus (push) Successful in 36s
release / build-and-publish (push) Successful in 7m18s
The v0.63.0 release build failed at tools/release.sh's server smoke test:
smoke.js still expected rangesFormatting to re-indent a named line to the
configured depth. Selection formatting keeps a block's written leading
whitespace, so the probe now checks that the named fork is re-laid from
its own two spaces, the named wire stays put and the unnamed block keeps
its bytes. Checked against a local release lucisv-server (smoke: OK).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-09 19:50:52 -08:00
lucioandClaude Fable 5.2 e115f9fc8f Release 0.63.0: Format Selection that fits where it stands, comment toggling in VS Code
ci / checks (push) Successful in 1m43s
ci / corpus (push) Successful in 35s
release / build-and-publish (push) Failing after 7m5s
Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.63.0) and
editors/vscode/CHANGELOG.md. TODO §66.1, §66.2.
Gates: the local tools/gates.sh run was not green — vlog_semantic and
vlog_refactor were killed on the 300 s wall clock (a stuck syspolicyd made
each new test binary take up to 40 s to launch); every test that ran
passed, and both suites passed in full when re-run piecewise on d8119aa.
By the owner's call the release relies on the Gitea CI run.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-09 19:34:10 -08:00
lucioandClaude Fable 5.2 d8119aa9c6 CLAUDE.md: dev and QA both Opus 5.5; refactor devs Fable 5.2; second QA failure escalates to Fable 5.2
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-09 18:53:04 -08:00
lucioandClaude Fable 5.2 2854bcaa2f TODO §66.2: the server's range, ranges and on-type formatting run on format_selection
textDocument/rangeFormatting, rangesFormatting and the on-type ';' now
format the selected block in place of the enclosing module-level item;
the reply is still one whole-document edit. On-type ';' now answers in a
buffer whose error is elsewhere and adds no final newline. topo: the
server → formatter edge and the selection-formatting row.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-09 18:53:04 -08:00
lucioandClaude Fable 5.2 3598a9145e TODO §66.2: format_selection lays out only the selected block, at the indentation it already has
A splice: the smallest run of sibling items/statements the selected lines
cover is laid out alone (Printer::print_at with the written leading
whitespace as the base) and replaces its own bytes; the parent is not
re-laid. Whole-file verify_equivalence and convergence still gate the
result; verify.rs is unchanged. A file that does not parse is formatted
when the error lies outside the target. Descent stops only on a unit's
first line; the closing end line alone names its unit. CRLF kept,
including after a trailing // comment. Module-level targets defer to
format_range, which the CLI's --lines still uses.
36 tests in tests/selection.rs; docs/features/selection-formatting.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-09 18:53:04 -08:00
lucioandClaude Fable 5.2 a8c4a2ecf8 TODO §66.1: the VS Code extension declares the language's comments and brackets (Ctrl+/ toggles comments)
editors/vscode/language-configuration.json for both verilog and
systemverilog: // and /* */, bracket pairs, auto-closing and surrounding
pairs. TODO §66 planned (66.1 here, 66.2 selection formatting).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-09 18:53:04 -08:00
lucioandClaude Opus 5.5 66bf27617e Release 0.62.0: paths rooted at a top-level module, the release gate script, guard memory at every depth
ci / checks (push) Successful in 1m50s
ci / corpus (push) Successful in 38s
release / build-and-publish (push) Successful in 6m59s
Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.62.0) and
editors/vscode/CHANGELOG.md. TODO §65.2 (closed by ruling), §65.3, §65.4.
Gates: tools/gates.sh PASS on 9dc567c (15 steps, 5 180 tests, corpus
814/820); CI green on 9dc567c.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 19:45:28 -07:00
lucioandClaude Opus 5.5 9dc567c72a TODO §65.4: a hierarchical path rooted at a top-level module resolves through the workspace (conservative)
ci / checks (push) Successful in 1m42s
ci / corpus (push) Successful in 32s
`tb.dut.g_sw[0].buf_q` written in a file that does not declare `tb` now
resolves like an instance path: the binder marks a dotted path's head
(Target::PathHead), resolve/root.rs answers a plain lexical miss with a
hierarchical external candidate, head_site roots the spine there, and
fold_path walks it — every hop a module/interface surface. find_references,
LSP references and rename see every segment; $root.tb works; a local `tb`
shadows. FACTS_FORMAT 22.

Rooted only when the root is provable (owner's ruling: conservative): not
when the head has an import candidate (so `import uvm_pkg::*` with uvm_pkg
outside the project stays warned — opentitan's DV force paths behave as
before), not from inside a class, not beside a macro that stands where a
declaration could (item, statement, port list), not when the root name is
also a package or ambiguous. The LSP rename set adds the files of the
path's root and middle hops (sources.rs, WorkspaceIndex::path_units_to).
An unresolved path is warned once.

QA (Opus) x2: F1-F4 and R1 silent-wrong-rename shapes fixed with tests;
QA's attack cases 1-6 each warned or correctly renamed; lucisv check hw
byte-identical to master. Completion after `tb.` deferred (TODO §65.8).
tools/gates.sh: PASS, 15 steps, 5 180 tests, corpus 814/820.
docs/features/top-rooted-paths.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 15:34:45 -07:00
lucioandClaude Opus 5.5 92875e6c6d TODO §65.3: tools/gates.sh, the release gate; guard.sh enforces memory at every depth and runs with a closed stdin
ci / checks (push) Successful in 1m34s
ci / corpus (push) Successful in 38s
guard.sh fixes (both ours): the memory sum never saw a process three or
more levels down the tree (a doubled space became an empty entry in the
`ps -p` list, which macOS rejects whole), so cargo -> rustc -> linker and
test-spawned servers were never memory-limited — QA re-proved 1.5 GB at
depth 3/4 missed by master, killed in 2-4 s now; a closed stdin skipped
the command silently, now /dev/null. The stall itself is the host's
(syspolicyd on fresh unsigned binaries).

tools/gates.sh runs fmt, clippy, the test build, one suite per workspace
crate, the doc-tests, the corpus gate and the node tests as separate
guarded steps with kept logs and per-step limits; a guard-killed step is
retried once and shown as KILLED -> retried; usage errors exit 2 (lead
fixes after QA: comments/one-line/glob members, an empty crate list, a
missing option value, an empty selection). RELEASING.md step 3, CLAUDE.md
and the README's Building section point at it.

Ten consecutive green runs recorded (healthy host); full gate on master:
PASS, 15 steps, 5 127 tests, corpus 814/820. QA (Sonnet): PASS.
docs/features/release-gates.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 06:13:28 -07:00
lucioandClaude Opus 5.5 51b975bf68 TODO §65.2 closed by ruling: LSP references are scope-relative by design; tests pin both scopes
ci / checks (push) Successful in 1m40s
ci / corpus (push) Successful in 32s
Root cause (lane A): not the fan-out. The default index scope (`folder`,
depth 2) opened from hw/ip/aes/dv/tb/tb.sv indexes hw/ip/aes only, so the
three *_pd_main.sv tops are never walked; with index.scope "workspace" the
LSP answers 14/12, equal to the whole-set engine. Ruled out: the 1 MiB cap,
autogen/ignore rules, the multi-line instantiation. The owner kept the
design; the index.scope setting now says a rename of a module instantiated
outside the scope leaves those sites unchanged.

Tests: server/tests/references_scope.rs (3: the LSP equals the engine over
the same file set in both scopes, a module rename reaches the top under
`workspace`), tests/opentitan_references.rs (2, ignored: 14/12 workspace,
11/9 default). lucisv_server 1 865 passed, 0 failed; node 8/8.
docs/features/references-fanout-pd-main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 05:48:40 -07:00
lucioandClaude Opus 5.5 ec492cdd86 TODO §65: correct the release targets (65.1 shipped in 0.60.0; 65.2-65.4 target 0.62.0) and plan the 0.62.0 wave (§65.7)
ci / checks (push) Successful in 2m3s
ci / corpus (push) Successful in 34s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 05:32:31 -07:00
61 changed files with 5647 additions and 146 deletions

No files matched your search

+72
View File
@@ -4,6 +4,78 @@ 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.63.0 — 2026-11-09
### Format Selection that fits where it stands; comment toggling in VS Code
(`docs/features/selection-formatting`; TODO §66.)
- **Format Selection lays out only the block you selected.** Selecting an
`always` block, a `case` statement or a few statements used to re-lay the
whole enclosing module-level item — at the formatter's own depth, so a
block in a 4-space or tab-indented file moved, and the blank lines at the
selection's edges were eaten. The new engine
(`vlog_formatter::format_selection`) finds the smallest run of sibling
items or statements the selected lines cover, lays out that run alone and
puts it back starting at the leading whitespace it already has (tabs
kept). The parent is not touched. `textDocument/rangeFormatting`,
`rangesFormatting` and the on-type `;` all run on it.
- **A parse error elsewhere in the file no longer refuses the request.** The
selection is formatted when the error lies outside it, and refused only
when it lies inside.
- **How a selection picks its block.** Touching a block's first line takes
the whole block; a selection that starts inside it takes only the
statements it covers, even when it reaches the closing `end`; the `end`
line alone takes the block it closes. A selection of whole module-level
items behaves as before.
- **Still verified.** Every result passes the whole-file equivalence check
and a convergence replay, or the buffer is left unchanged; the verifier
itself is unchanged. CRLF files keep every line ending.
- The on-type `;` now tidies its statement in a buffer whose error is
elsewhere, and no longer adds a final newline to a file without one.
- The reply is still one whole-document edit; the CLI's `--lines` is
unchanged (whole module-level items).
- **VS Code: `Ctrl+/` toggles comments.** The extension now declares the
language's `//` and `/* */` comments, bracket pairs and auto-closing
pairs for Verilog and SystemVerilog, so Toggle Line Comment and Toggle
Block Comment work on one line or a selection.
## 0.62.0 — 2026-10-19
### Paths rooted at a top-level module; a dependable release gate
(`docs/features/top-rooted-paths`, `docs/features/release-gates`,
`docs/features/references-fanout-pd-main`.)
- **A hierarchical path that starts at a top-level module now resolves.**
`tb.dut.u_core.sig` written in a file that does not declare `tb` used to
stop at `tb`; now every segment is a reference — `find_references` and LSP
references list it, and a rename of `dut`, `u_core`, `sig` or a generate
label on the way rewrites the path. `$root.tb…` works; a local `tb`
shadows. The LSP's rename also reads the files of the path's root and the
modules it passes through. **Rooted only when lucisv can prove the head is
a top-level module**: not when the name could come from a wildcard import
(including `import uvm_pkg::*` with `uvm_pkg` outside the project), not
inside a class, not beside a macro that stands where a declaration could,
and not when the name is also a package or several modules share it —
those paths are left unchanged and warned about exactly as before. The
index cache format moves to 22, so a 0.61.0 cache is rebuilt once.
- An unresolved path through the renamed name is warned about once (it was
sometimes named twice).
- **Find All References across blocks is relative to the index scope, by
design.** On a default `folder` scope a module's references and rename
reach only the folders the index covers; the `lucisv.index.scope` setting
now says that a rename of a module instantiated outside the scope leaves
those instantiations unchanged (use `workspace`, or open the file first).
- **`tools/gates.sh`** is the release gate: fmt, clippy, the test build,
each crate's suites, the doc-tests, the corpus gate and the extension
tests, each a separately guarded step with its own log and a summary; a
step the guard kills is retried once and reported as `KILLED → retried`.
- **`tools/guard.sh` fixes:** its memory limit now sees every process in the
tree (a pid-list bug hid everything three or more levels down, so builds
and test-spawned servers were never capped), and a closed stdin no longer
makes the command silently not run.
## 0.61.0 — 2026-10-14
### Call hierarchy from anywhere, functions and tasks as nodes; full-line references in VS Code
+23 -3
View File
@@ -93,7 +93,10 @@ files over 600 workspace-wide: `lucisv_server/src/perf.rs` 907 (reasoned),
- `cargo fmt` clean, `cargo clippy --all-targets` clean (no `#[allow]`
without a comment explaining why), `cargo test` green — all three
before declaring any work finished.
before declaring any work finished. **Before a release, and whenever
the whole workspace is gated, run `tools/gates.sh`** (every gate as a
separate guarded step with kept logs; `--only`/`--skip` for a subset)
instead of a bare `cargo test --workspace`.
- No `unwrap()`/`expect()`/`panic!` in library code paths; return
`Result`. Tests and `main.rs` argument handling may use them.
- Public items get a one-line doc comment. Doc comments say what/why,
@@ -136,6 +139,19 @@ Rules:
## Workflow
- **Agent models**: the lead plans and reviews; coding goes to one dev
agent and verification to one QA agent, **both Claude Opus 5.5**
(`model: "opus"`). This holds for a single lane and for each of two
parallel lanes.
- **Refactor lanes** (pure moves, decompositions): the dev is **Claude
Fable 5.2 at high reasoning effort** — the `refactor-dev` agent in
`.claude/agents/`. Its brief says: no new tests beyond what the move
forces, the gates are the proof, spend the effort on module
boundaries, naming and readability. QA is unchanged (Opus 5.5).
- **Escalation**: a first QA failure gets a normal Opus 5.5 fix round.
When a fix round fails QA a **second** time on the same feature, redo
the round with **Claude Fable 5.2 as both dev and QA**
(`model: "fable"`).
- Do **not** run `git commit` or `git push` — the lead reviews and
commits all work.
- Do not touch files outside your feature's stated scope. If you need a
@@ -160,6 +176,9 @@ process tree when its resident set or wall clock exceeds the limits
`tools/guard.sh`** — dev, QA and lead alike, foreground or background.
- A guard kill is a finding: report the command and the limit it hit;
do not raise the limit to make it pass.
- The release gate is `tools/gates.sh`, which guards each step with its
own limits and retries a killed step once (shown as `KILLED → retried`);
do not wrap it in another `guard.sh`.
## Parallel lanes (the 2-agent loop)
@@ -181,8 +200,9 @@ proven independent and run serially. Rules for a parallel wave:
while lanes are in flight; the lead merges each lane back only after
that lane's QA verdict and lead review, and re-runs the full gates on
the merged tree before pushing.
- **Roles per lane are unchanged**: one dev (Opus), then one QA
(Sonnet) in the same worktree, then the lead's review — so at most
- **Roles per lane are unchanged**: one dev, then one QA — **both
Claude Opus 5.5** (owner, 2026-11-09; QA was Sonnet before) — in the
same worktree, then the lead's review — so at most
2 devs + 2 QA agents exist at once, and a lane's QA starts only when
its own dev is done. A QA rework loops inside its lane without
blocking the other lane.
Generated
+9 -9
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.61.0"
version = "0.63.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.61.0"
version = "0.63.0"
[[package]]
name = "lucisv_mcp"
version = "0.61.0"
version = "0.63.0"
dependencies = [
"lucisv_core",
"serde",
@@ -126,7 +126,7 @@ dependencies = [
[[package]]
name = "lucisv_server"
version = "0.61.0"
version = "0.63.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.61.0"
version = "0.63.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.61.0"
version = "0.63.0"
dependencies = [
"lucisv_core",
"vlog_formatter",
@@ -279,11 +279,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.61.0"
version = "0.63.0"
[[package]]
name = "vlog_refactor"
version = "0.61.0"
version = "0.63.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -292,7 +292,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.61.0"
version = "0.63.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -13,7 +13,7 @@ members = [
]
[workspace.package]
version = "0.61.0"
version = "0.63.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+5 -3
View File
@@ -1037,11 +1037,13 @@ expected; no PRs or review required.
```bash
cargo build --release # binaries at target/release/{lucisv,lucisv-server}
cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
tools/guard.sh -- cargo test --workspace # unit, integration, snapshots, doc tests
tools/gates.sh # every gate: fmt, clippy, build, each crate's suites, doc tests, corpus, node
tools/gates.sh --only suites # just the per-crate test suites
```
`tools/gates.sh` runs each gate as its own guarded step with a kept log and
prints a summary (`docs/features/release-gates/README.md`).
Snapshot tests live in `crates/vlog_formatter/tests/fixtures/`; regenerate
expected outputs only for intentional formatting changes with
`UPDATE_SNAPSHOTS=1 tools/guard.sh -- cargo test -p vlog_formatter`.
+97 -12
View File
@@ -6950,7 +6950,10 @@ 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.
restored with `git -C … checkout -- <file>`). ~~Ships as 0.60.0.~~
**Release targets (corrected 2026-10-19):** 65.1 shipped in **0.60.0**
(2026-10-08); 65.2, 65.3 and 65.4 are open and target **0.62.0** (wave
below, §65.7); 65.6 is unscheduled.
### 65.1 Rename and references through a generate block label (topo §2.9-43, MCP-14)
@@ -7007,18 +7010,18 @@ top-level instantiations in
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` —
- [x] 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
- [x] ~~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`)
test with a fixture that reproduces the cause (not only opentitan)~~ — **closed by the owner's ruling 2026-10-19: scope-relative by design.** The LSP answer equals the engine over the same file set (pinned for both scopes in `server/tests/references_scope.rs`); the default `folder` scope does not reach the three tops, `workspace` does (14/12).
- [x] 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
- [x] ~~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?)
three sites?)~~ — not run: no production code changed under the ruling
### 65.3 The combined test command stalls entering the doc-tests
@@ -7028,16 +7031,16 @@ 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
- [x] 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
- [x] 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
- [x] 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)
@@ -7061,8 +7064,8 @@ 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
- [x] root lookup in `head_site`, the head recorded as a module use
- [x] 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)
@@ -7087,3 +7090,85 @@ modules is two bindings and must agree or be refused. QA's repro:
binding agrees
- [ ] QA's repro renames the fragment's use; the §65.1 warning remains for
what cannot be bound
### 65.7 Wave for 0.62.0 (planned 2026-10-19, owner's order: "fix those that are true")
Two parallel lanes first (disjoint files; neither touches `vlog_semantic`),
then 65.4 serially (it changes `vlog_semantic` resolution, which §65.2's
lane might also need — run after it merges).
**Lane A — §65.2 references fan-out** (Opus dev → QA → lead), files:
`crates/lucisv_server/src/state/sources.rs`, `crates/lucisv_server/src/nav.rs`,
new test files under `crates/lucisv_server/src/server/tests/`, a new
ignored-by-default `crates/lucisv_server/tests/opentitan_references.rs`,
`docs/features/references-fanout-pd-main/README.md`.
- [x] §65.2's checklist above (closed by ruling: scope-relative by design)
**Lane B — §65.3 gate script** (Opus dev → QA → lead), files:
`tools/gates.sh` (new), `tools/guard.sh` (only if the cause is there),
`tools/RELEASING.md`, `docs/features/release-gates/README.md` (new);
CLAUDE.md's pointer is the lead's at merge.
- [x] §65.3's checklist above
**Then — §65.4 top-module-rooted paths** (serial, after lane A merges).
- [x] §65.4's checklist above (conservative by the owner's ruling: a head with an import candidate, inside a class, or beside a macro that could declare it is not rooted)
### 65.8 Completion after a top-rooted path head (deferred from §65.4 H2, 2026-10-19)
`tb.` offers nothing in completion: the completion walk keeps "an unknown
head answers nothing" (two `lucisv_server` completion tests pin it), while
resolution now roots an unknown head at a top module. Decide whether
completion should offer `tb.`'s hierarchical members, answering `None` when
the index has no unit of that name. `docs/features/top-rooted-paths`.
- [ ] owner/lead decision; if yes, `completion/member.rs` + tests
## 66. Format Selection that fits where it stands (planned 2026-11-09, owner's order)
Owner's report: *Format Selection* "fails more than half of the time". The
usual selection is one whole `always` block or one whole `case` statement,
often nested inside blocks the selection does not cover. Reproduced on trunk
(`lucisv --lines`, the engine `textDocument/rangeFormatting` shares): selecting
a `case` re-lays the whole `always` around it; the block is re-indented to the
formatter's own depth × width, so in a file indented any other way it no
longer lines up with its neighbours; a selection inside `generate` re-lays the
whole region; and a file with a parse error anywhere is refused outright.
Owner's rule: do not worry about the parent — the selected block keeps the
indentation level it starts at, and stays functionally the same.
### 66.1 VS Code language configuration (lead, done 2026-11-09)
- [x] `editors/vscode/language-configuration.json` (comment tokens, brackets,
auto-closing and surrounding pairs) wired to both language ids in
`editors/vscode/package.json` — Toggle Line/Block Comment (Ctrl+/) works
without another Verilog extension installed.
### 66.2 Selection formatting (one lane: dev, then QA)
Feature README: `docs/features/selection-formatting/README.md`. Files:
`crates/vlog_formatter/src/selection.rs` (+ a `selection/` split if it nears
600 lines), `crates/vlog_formatter/src/{lib.rs,printer.rs,format/mod.rs}`,
`crates/vlog_formatter/tests/selection.rs`, `crates/lucisv_server/src/format.rs`,
`crates/lucisv_server/src/server/tests/formatting.rs`,
`crates/lucisv_server/tests/e2e.rs`. `verify.rs`, `range.rs`, `fence.rs`, the
parser and the CLI's `--lines` are not touched.
- [x] `format_selection`: the smallest run of sibling items/statements the
selected lines cover, laid out alone at the indentation it was written
at, spliced into otherwise untouched bytes.
- [x] Verified whole-file (`verify_equivalence`, unchanged) and converged by
replaying the located target, not the line numbers.
- [x] Fences outrank the selection; a module/package-level target defers to
`format_range` (header/footer splitting).
- [x] A file that does not parse: the target is located in the tolerant tree
and refused when a diagnostic falls inside it.
- [x] `textDocument/rangeFormatting` / `rangesFormatting` call it.
- [x] Tests: the owner's shapes (whole `always`, whole `case`, inside
`generate`, inside a function), off-grid and tab indentation, partial
selections, comments, fences, broken files, masked-corruption attacks on
the splice.
+46 -8
View File
@@ -6,13 +6,16 @@
//! output, or no edit at all and an error for the user to read. That holds for
//! the range requests too — their output is verified over the whole buffer,
//! and what makes a request a *range* format is which constructs it laid out,
//! not which bytes it was allowed to replace.
//! not which bytes it was allowed to replace. The range requests go through
//! `format_selection`: the smallest run of sibling items or statements the
//! selection covers, laid out at the indentation it was written at — see
//! `docs/features/selection-formatting/README.md`.
use std::path::Path;
use lsp_types::{FormattingOptions, Range, TextDocumentIdentifier, TextEdit};
use lucisv_core::config::{Discovery, FileConfig};
use vlog_formatter::{format_range, format_source, Config, LineRanges};
use vlog_formatter::{format_selection, format_source, Config, LineRanges};
use crate::settings::ClientSettings;
use crate::state::Document;
@@ -122,10 +125,12 @@ pub fn range_formatting(
///
/// The ranges are a *set*: they are sorted and merged by `LineRanges::new`
/// before the engine sees them, so overlapping, adjacent, repeated and
/// unsorted input from the client all reach the same answer. No range is
/// formatted on its own — one `format_range` call lays out the union, which is
/// what keeps the all-or-nothing contract (CLAUDE.md invariant #1) whole
/// rather than making it a promise per range.
/// unsorted input from the client all reach the same answer. Each merged span
/// selects its own target (targets that overlap are re-selected from the hull
/// of their spans), but no range is formatted on its own — one
/// `format_selection` call lays out and verifies them all, which is what keeps
/// the all-or-nothing contract (CLAUDE.md invariant #1) whole rather than
/// making it a promise per range.
///
/// The reply is still one whole-document edit: the engine's contract is
/// all-or-nothing over the file, and a partial run's output differs from the
@@ -140,7 +145,7 @@ pub fn ranges_formatting(
return Ok(None);
}
let lines = LineRanges::new(ranges.iter().copied().map(lines_of))?;
let formatted = format_range(&doc.text, config, &lines).map_err(|e| e.to_string())?;
let formatted = format_selection(&doc.text, config, &lines).map_err(|e| e.to_string())?;
if formatted == doc.text {
return Ok(None);
}
@@ -700,6 +705,39 @@ mod tests {
assert!(edit.new_text.contains("é ✓ 🎉"), "comments are never dropped");
}
/// A file indented four spaces with a `case` nested in an `always`: the
/// shape VS Code's "Format Selection" most often sends.
const NESTED: &str = "module m;\n always @* begin\n case (s)\n 0: y=a;\n default:y=b;\n endcase\n z = 1;\n end\nendmodule\n";
#[test]
fn a_selected_case_is_laid_out_alone_at_the_indentation_it_starts_at() {
let edit = ranged(NESTED, at(2, 0, 6, 0)).expect("formats").expect("changed");
assert_eq!(
edit.new_text,
"module m;\n always @* begin\n case (s)\n 0: y = a;\n default: y = b;\n endcase\n z = 1;\n end\nendmodule\n"
);
}
#[test]
fn a_tab_indented_selection_keeps_its_tabs() {
let text = "module m;\n\talways @* begin\n\t\tx=1;\n\tend\nendmodule\n";
let edit = ranged(text, at(2, 0, 2, 4)).expect("formats").expect("changed");
assert_eq!(edit.new_text, "module m;\n\talways @* begin\n\t\tx = 1;\n\tend\nendmodule\n");
}
#[test]
fn a_parse_error_outside_the_selection_does_not_block_it() {
let text = "module m;\n always @* begin\n x=1;\n end\n assign y = ;\nendmodule\n";
let edit = ranged(text, at(2, 0, 2, 4)).expect("formats").expect("changed");
assert_eq!(
edit.new_text,
"module m;\n always @* begin\n x = 1;\n end\n assign y = ;\nendmodule\n"
);
// Inside it, the request is refused with a message to read.
let message = ranged(text, at(4, 0, 4, 4)).expect_err("must refuse");
assert!(message.contains("syntax error"), "{message}");
}
#[test]
fn an_unparsable_buffer_produces_no_range_edit_either() {
// Range formatting cannot rescue broken input; the strict parse still
@@ -802,7 +840,7 @@ mod tests {
#[test]
fn a_refused_buffer_is_refused_identically_whichever_range_request_asked() {
// No partial output on either path (CLAUDE.md invariant #1), and the
// same message: both are one `format_range` call away from the engine.
// same message: both are one `format_selection` call away from the engine.
let broken = "module m;\n wire ;\nendmodule\n";
let one = ranged(broken, at(0, 0, 0, 9));
let many = multi(broken, &[at(0, 0, 0, 9), at(2, 0, 2, 9)]);
+20 -8
View File
@@ -61,9 +61,9 @@ pub fn on_type_formatting(
/// Lay out the statement the `;` just ended, through the range engine.
///
/// The range asked for is the `;`'s **own line** and nothing else. That is not
/// a narrower request than "the statement's lines": `format_range` selects by
/// *unit*, so any line of a statement selects the whole statement (see
/// `docs/features/range-formatting/README.md`). It is, however, a much safer
/// a narrower request than "the statement's lines": `format_selection` selects
/// by *unit*, so any line of a statement selects the whole statement (see
/// `docs/features/selection-formatting/README.md`). It is, however, a much safer
/// one — the `;` closing `module m (\n input a\n);` ends no statement at all,
/// and naming its enclosing node's lines there would ask for the whole module
/// back on a keystroke.
@@ -1174,7 +1174,19 @@ mod tests {
#[test]
fn a_semicolon_in_a_buffer_the_engine_refuses_answers_nothing_at_all() {
// Half-typed code is the normal case on this trigger, not a failure.
assert_eq!(semicolon("module m;\n wire a;\n wire ;\nendmodule\n", 1), Vec::new());
// The error is on the keystroke's own line: one elsewhere in the
// buffer no longer refuses (selection-formatting, TODO §66.2).
let text = "module m;\n wire a = ;\nendmodule\n";
let at = Position { line: 1, character: 13 };
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
assert_eq!(edits, Vec::new());
}
#[test]
fn a_semicolon_still_lays_out_its_statement_when_the_error_is_elsewhere() {
let edits = semicolon("module m;\n wire a;\n wire ;\nendmodule\n", 1);
assert_eq!(edits.len(), 1, "{edits:#?}");
assert_eq!(edits[0].new_text, "module m;\n wire a;\n wire ;\nendmodule\n");
}
#[test]
@@ -1204,10 +1216,10 @@ mod tests {
let at = Position { line: 1, character: 11 };
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
assert_eq!(edits.len(), 1, "{edits:#?}");
// The engine's own canonicalization adds the missing final newline —
// exactly what `textDocument/rangeFormatting` would also do here, and
// not a moved byte this path invented on its own.
assert_eq!(edits[0].new_text, "module m;\n wire a;\nendmodule\n");
// Only the statement moves: the file's tail is outside the splice, so
// the missing final newline stays missing — exactly what
// `textDocument/rangeFormatting` answers here too.
assert_eq!(edits[0].new_text, "module m;\n wire a;\nendmodule");
}
#[test]
@@ -135,6 +135,27 @@ fn a_ranges_request_lays_out_every_range_it_names_in_one_answer() {
assert!(session.shown().is_empty(), "a clean config says nothing");
}
#[test]
fn a_selection_inside_a_nested_block_lays_out_only_that_block() {
// The owner's report (TODO §66.2): a `case` selected inside an `always`
// in a four-space file. Only the `case` moves, and it stays where it
// starts; the statement after it and the parent keep their bytes.
let tree = Tree::new("rangesnested");
let mut session = Session::new(vec![tree.path.clone()], false);
let text = "module m;\n always @* begin\n case (s)\n 0: y=a;\n endcase\n z = 1;\n end\nendmodule\n";
let uri = session.open(&tree.path.join("m.sv"), text);
let one = range_result(&mut session, &uri, json_range(2, 0, 5, 0));
assert_eq!(
one[0]["newText"],
"module m;\n always @* begin\n case (s)\n 0: y = a;\n endcase\n z = 1;\n end\nendmodule\n",
"{one:#?}"
);
// The multi-range method gives the same answer for the same selection.
assert_eq!(ranges_result(&mut session, &uri, vec![json_range(2, 0, 5, 0)]), one);
assert!(session.shown().is_empty());
}
#[test]
fn one_range_through_the_new_method_answers_what_the_old_method_answers() {
// The two requests are the same engine, and a client must never have
@@ -250,9 +271,11 @@ fn a_keystroke_the_engine_refuses_is_answered_with_silence_and_not_a_popup() {
// user cannot type past would arrive on every semicolon.
let tree = Tree::new("ontypequiet");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\n wire ;\n");
// The error sits on the keystroke's own line: since selection formatting
// (TODO §66.2) an error on *another* line no longer refuses the request.
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a = ;\n");
assert_eq!(on_type(&mut session, &uri, ";", 1, 11), serde_json::json!([]));
assert_eq!(on_type(&mut session, &uri, ";", 1, 13), serde_json::json!([]));
assert!(session.shown().is_empty(), "not one word: {:?}", session.shown());
// ...and the whole-document request on the same buffer still does say
// something, so the silence is this path's decision and not a
@@ -61,8 +61,11 @@ mod progress;
mod pull_diagnostics;
mod qa_generate_label;
mod qa_rename_implicit;
mod references_scope;
mod references_top_rooted;
mod rename_generate_label;
mod rename_implicit;
mod rename_top_rooted_scope;
mod requests;
mod scan;
mod scan_trace;
@@ -0,0 +1,170 @@
//! TODO §65.2 over the wire: `references` from a testbench answers within
//! the active index scope, and within an equal file set it answers exactly
//! what the whole-set engine (`vlog_refactor::find_references`) answers.
//! `docs/features/references-fanout-pd-main/README.md`.
//!
//! The fixture is opentitan's shape in miniature: an IP block with `rtl/`
//! and `dv/tb/`, and a generated top two directories away that instantiates
//! the block with a multi-line `blk #( … ) u_blk (`.
use std::path::Path;
use super::*;
const BLK: &str = "module blk #(\n parameter int W = 1\n) (\n input logic clk_i,\n input logic rst_ni\n);\nendmodule\n";
const TB: &str = "module tb;\n logic clk, rst_n;\n blk #(\n .W ( 2 )\n ) dut (\n .clk_i ( clk ),\n .rst_ni ( rst_n )\n );\nendmodule\n";
const PD_MAIN: &str = "module top_pd_main (\n input logic clk_main_i,\n input logic rst_main_ni\n);\n blk #(\n .W ( 4 )\n ) u_blk (\n // Clock and reset connections\n .clk_i ( clk_main_i ),\n .rst_ni ( rst_main_ni )\n );\nendmodule\n";
/// The three files, at their opentitan-shaped paths.
fn fixture(tag: &str) -> Tree {
let tree = Tree::new(tag);
tree.write("ip/blk/rtl/blk.sv", BLK);
tree.write("ip/blk/dv/tb/tb.sv", TB);
tree.write("top/rtl/autogen/top_pd_main.sv", PD_MAIN);
tree
}
/// `(path relative to the root, line)` of every location in an answer.
fn answered(root: &Path, 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 path =
crate::uri::uri_to_path(&Uri::from_str(uri).expect("a uri")).expect("a path");
let rel = path.strip_prefix(root).unwrap_or(&path).display().to_string();
(rel, l["range"]["start"]["line"].as_u64().unwrap_or(0))
})
.collect();
out.sort();
out
}
/// What the whole-set engine answers over `files`, as [`answered`] spells it.
fn engine(
root: &Path,
files: &[(PathBuf, String)],
file: &Path,
offset: u32,
) -> Vec<(String, u64)> {
let found =
vlog_refactor::find_references(files, file, offset, true).expect("the engine answers");
let mut out: Vec<(String, u64)> = found
.into_iter()
.map(|(path, range)| {
let text = &files.iter().find(|(p, _)| *p == path).expect("a read file").1;
let line = text[..range.start as usize].matches('\n').count() as u64;
let rel = path.strip_prefix(root).unwrap_or(&path).display().to_string();
(rel, line)
})
.collect();
out.sort();
out
}
/// Every file under the tree — the set the MCP's `references` hands the engine.
fn every_file(tree: &Tree) -> Vec<(PathBuf, String)> {
["ip/blk/rtl/blk.sv", "ip/blk/dv/tb/tb.sv", "top/rtl/autogen/top_pd_main.sv"]
.iter()
.map(|rel| {
let path = tree.path.join(rel);
let text = std::fs::read_to_string(&path).expect("read");
(path, text)
})
.collect()
}
/// A references request at the first `needle` on line `line` of `text`, and
/// the byte offset the engine is asked at.
fn at(uri: &Uri, text: &str, line: usize, needle: &str) -> (Value, u32) {
let row = text.lines().nth(line).expect("the line");
let character = row.find(needle).expect("the needle on that line");
let before: usize = text.lines().take(line).map(|l| l.len() + 1).sum();
let params = serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": line, "character": character },
"context": { "includeDeclaration": true },
});
(params, (before + character) as u32)
}
/// The four positions the §65.2 checklist names: the module name and one of
/// its ports, each from its declaration and from a use.
fn positions(tree: &Tree) -> [(PathBuf, &'static str, usize, &'static str); 4] {
let blk = tree.path.join("ip/blk/rtl/blk.sv");
let tb = tree.path.join("ip/blk/dv/tb/tb.sv");
[
(blk.clone(), BLK, 0, "blk"),
(tb.clone(), TB, 2, "blk"),
(blk, BLK, 3, "clk_i"),
(tb, TB, 5, "clk_i"),
]
}
#[test]
fn over_the_whole_workspace_references_equal_the_whole_set_engine() {
let tree = fixture("refscope_wide");
let mut session = Session::wide(vec![tree.path.clone()], false);
let all = every_file(&tree);
for (path, text, line, needle) in positions(&tree) {
let uri = session.open(&path, text);
let (params, offset) = at(&uri, text, line, needle);
let lsp = answered(&tree.path, &session.result(References::METHOD, params));
let whole = engine(&tree.path, &all, &path, offset);
assert_eq!(lsp, whole, "{needle} at {}:{line}", path.display());
assert!(
lsp.iter().any(|(file, _)| file.ends_with("top_pd_main.sv")),
"the generated top is listed: {lsp:?}"
);
}
}
/// The cause, pinned: under the shipped folder scope a testbench in
/// `ip/blk/dv/tb/` raises to `ip/blk/`, the generated top is not in the
/// index, and `references` answers what the engine answers over the scope —
/// not over every file. Opening the top widens the scope, and the answer
/// becomes the whole set's.
#[test]
fn under_the_folder_scope_references_equal_the_engine_over_the_scope() {
let tree = fixture("refscope_folder");
let mut session = Session::new(vec![tree.path.clone()], false);
let top = tree.path.join("top/rtl/autogen/top_pd_main.sv");
for (path, text, line, needle) in positions(&tree) {
let uri = session.open(&path, text);
let in_index = session.server.workspace.index().files().contains(&top);
assert!(!in_index, "the top is outside the folder scope");
let (params, offset) = at(&uri, text, line, needle);
let lsp = answered(&tree.path, &session.result(References::METHOD, params));
let scoped = engine(&tree.path, &session.server.workspace.sources(), &path, offset);
assert_eq!(lsp, scoped, "{needle} at {}:{line}", path.display());
assert!(!lsp.iter().any(|(file, _)| file.ends_with("top_pd_main.sv")), "{lsp:?}");
}
let _ = session.open(&top, PD_MAIN);
let all = every_file(&tree);
for (path, text, line, needle) in positions(&tree) {
let uri = path_to_uri(&path).expect("uri");
let (params, offset) = at(&uri, text, line, needle);
let lsp = answered(&tree.path, &session.result(References::METHOD, params));
assert_eq!(lsp, engine(&tree.path, &all, &path, offset), "{needle}, widened");
}
}
/// `rename`'s fan-out has no gap of its own: over the whole workspace a
/// module rename from the testbench edits the generated top too.
#[test]
fn over_the_whole_workspace_a_module_rename_edits_the_generated_top() {
let tree = fixture("refscope_rename");
let mut session = Session::wide(vec![tree.path.clone()], false);
let tb = tree.path.join("ip/blk/dv/tb/tb.sv");
let uri = session.open(&tb, TB);
let (mut params, _) = at(&uri, TB, 2, "blk");
params["newName"] = serde_json::json!("blk2");
let answer = session.request(Rename::METHOD, params).response_result.expect("renames");
let changes = answer["changes"].as_object().expect("changes");
let top = path_to_uri(&tree.path.join("top/rtl/autogen/top_pd_main.sv")).expect("uri");
assert_eq!(changes.get(top.as_str()).and_then(Value::as_array).map_or(0, Vec::len), 1);
assert_eq!(changes.len(), 3, "blk.sv, tb.sv and the top: {answer:#}");
}
@@ -0,0 +1,106 @@
//! A hierarchical path rooted at a top module another file declares, over
//! the wire (TODO §65.4): `references` at a member of the DUT lists every
//! segment of `tb.dut.g_sw[0].buf_q` in a DV file, whichever side is open,
//! and `rename` rewrites them. `docs/features/top-rooted-paths/README.md`.
use super::*;
const DUT: &str = "module dut_a;\n for (genvar i = 0; i < 2; i++) begin : g_sw\n logic buf_q;\n end\nendmodule\n";
const TB: &str = "module tb;\n dut_a dut ();\nendmodule\n";
const PROBE: &str = "module probe (output logic o);\n assign o = tb.dut.g_sw[0].buf_q;\n initial force tb.dut.g_sw[1].buf_q = 1'b0;\nendmodule\n";
/// The LSP position of the first `name` on 0-based `line` of `text`.
fn at(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 },
})
}
/// `(file name, 0-based 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 three-file tree with the named files open; the uris of `dut_a.sv`
/// and `probe.sv`.
fn session_with(tag: &str, open: &[&str]) -> (Tree, Session, Uri, Uri) {
let tree = Tree::new(tag);
let files = [("dut_a.sv", DUT), ("tb.sv", TB), ("probe.sv", PROBE)];
for (name, text) in files {
tree.write(name, text);
}
let mut session = Session::wide(vec![tree.path.clone()], false);
for (name, text) in files.into_iter().filter(|(name, _)| open.contains(name)) {
session.open(&tree.path.join(name), text);
}
let uri = |name: &str| path_to_uri(&tree.path.join(name)).expect("a uri");
let (dut, probe) = (uri("dut_a.sv"), uri("probe.sv"));
(tree, session, dut, probe)
}
fn expected() -> Vec<(String, u64)> {
let place = |file: &str, line| (file.to_string(), line);
vec![place("dut_a.sv", 2), place("probe.sv", 1), place("probe.sv", 2)]
}
fn references(session: &mut Session, mut params: Value) -> Vec<(String, u64)> {
params["context"] = serde_json::json!({ "includeDeclaration": true });
places(&session.result(References::METHOD, params))
}
#[test]
fn references_at_the_member_list_the_path_in_the_closed_dv_file() {
let (_tree, mut session, dut, _) = session_with("toproot_refs_decl", &["dut_a.sv"]);
assert_eq!(references(&mut session, at(&dut, DUT, 2, "buf_q")), expected());
}
#[test]
fn references_at_the_paths_segment_reach_the_closed_declaration() {
let (_tree, mut session, _, probe) = session_with("toproot_refs_path", &["probe.sv"]);
assert_eq!(references(&mut session, at(&probe, PROBE, 2, "buf_q")), expected());
}
#[test]
fn references_with_both_files_open_are_the_same_set() {
let (_tree, mut session, _, probe) =
session_with("toproot_refs_both", &["dut_a.sv", "probe.sv"]);
assert_eq!(references(&mut session, at(&probe, PROBE, 1, "buf_q")), expected());
}
#[test]
fn references_at_the_root_list_every_path_it_heads() {
let (_tree, mut session, _, probe) = session_with("toproot_refs_root", &["probe.sv"]);
let found = references(&mut session, at(&probe, PROBE, 1, "tb"));
let tb = ("tb.sv".to_string(), 0);
assert_eq!(found, vec![("probe.sv".to_string(), 1), ("probe.sv".to_string(), 2), tb]);
}
#[test]
fn rename_at_the_block_label_rewrites_the_paths_in_the_dv_file() {
let (tree, mut session, dut, _) = session_with("toproot_rename", &["dut_a.sv"]);
let mut params = at(&dut, DUT, 1, "g_sw");
params["newName"] = serde_json::json!("g_hw");
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("dut_a.sv"), count("probe.sv"), count("tb.sv")), (1, 2, 0), "{answer:#}");
let mut texts = changes.values().flat_map(|e| e.as_array().into_iter().flatten());
assert!(texts.all(|e| e["newText"] == "g_hw"), "{answer:#}");
}
@@ -128,7 +128,8 @@ fn references_at_a_nested_blocks_member_reach_the_path_from_another_file() {
/// 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.
/// top module no file in the tree declares — TODO §65.4 resolves the root
/// when one does) is shown as a warning, unedited.
#[test]
fn an_unresolved_path_in_an_open_buffer_is_shown_as_a_rename_warning() {
const PROBE: &str =
@@ -147,4 +148,5 @@ fn an_unresolved_path_in_an_open_buffer_is_shown_as_a_rename_warning() {
shown.iter().any(|(_, m)| m.contains("probe.sv:2:") && m.contains("`g_lane`")),
"{shown:?}"
);
assert!(!shown.iter().any(|(_, m)| m.contains("more")), "said once: {shown:?}");
}
@@ -0,0 +1,121 @@
//! A rename through a hierarchical path rooted at a top module, under the
//! shipped **folder** scope (top-rooted-paths QA F3): the rename's file set
//! holds the files declaring every unit the path walks through — the root
//! `tb` and each hop's type — so a three-hop `tb.dut.u_core.sig` is renamed
//! exactly as the whole-set engine renames it, from the declaration or from
//! the segment. A hop outside the scope leaves the path warned about, and a
//! rename from its segment is refused with the accurate reason.
use super::*;
const CORE: &str = "module core;\n logic sig;\nendmodule\n";
const DUT: &str = "module dut_a;\n core u_core ();\n logic top_sig;\n for (genvar i = 0; i < 2; i++) begin : g_sw\n logic buf_q;\n end\nendmodule\n";
const TB: &str = "module tb;\n dut_a dut ();\nendmodule\n";
const PROBE: &str = "module probe;\n initial force tb.dut.u_core.sig = 1'b0;\n initial force tb.dut.top_sig = 1'b0;\n initial force tb.dut.g_sw[1].buf_q = 1'b0;\nendmodule\n";
/// The opentitan shape: `ip/blk/{rtl,dv}`, with `tb.sv` at `tb_at`.
fn fixture(tag: &str, tb_at: &str) -> Tree {
let tree = Tree::new(tag);
tree.write("ip/blk/rtl/core.sv", CORE);
tree.write("ip/blk/rtl/dut_a.sv", DUT);
tree.write(tb_at, TB);
tree.write("ip/blk/dv/probe.sv", PROBE);
tree
}
/// The LSP position of the first `name` on 0-based `line` of `text`.
fn at(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 },
})
}
/// The number of edits a rename answer makes in each of `files`.
fn edits(tree: &Tree, answer: &Value, files: &[&str]) -> Vec<usize> {
let changes = answer["changes"].as_object().expect("changes");
files
.iter()
.map(|rel| {
let uri = path_to_uri(&tree.path.join(rel)).expect("a uri");
changes.get(uri.as_str()).and_then(Value::as_array).map_or(0, Vec::len)
})
.collect()
}
fn rename(session: &mut Session, mut params: Value, new: &str) -> Result<Value, String> {
params["newName"] = serde_json::json!(new);
session.request(Rename::METHOD, params).response_result.map_err(|e| format!("{e:?}"))
}
const FILES: [&str; 2] = ["ip/blk/rtl/core.sv", "ip/blk/dv/probe.sv"];
#[test]
fn a_three_hop_path_is_renamed_from_the_declaration() {
let tree = fixture("toproot_scope_decl", "ip/blk/dv/tb.sv");
let mut session = Session::new(vec![tree.path.clone()], false);
let core = session.open(&tree.path.join(FILES[0]), CORE);
let answer = rename(&mut session, at(&core, CORE, 1, "sig"), "sig2").expect("renames");
assert_eq!(edits(&tree, &answer, &FILES), vec![1, 1], "{answer:#}");
assert!(session.shown().is_empty(), "nothing to warn about: {:?}", session.shown());
}
#[test]
fn a_three_hop_path_is_renamed_from_its_segment() {
let tree = fixture("toproot_scope_seg", "ip/blk/dv/tb.sv");
let mut session = Session::new(vec![tree.path.clone()], false);
let probe = session.open(&tree.path.join(FILES[1]), PROBE);
let answer = rename(&mut session, at(&probe, PROBE, 1, "sig"), "sig2").expect("renames");
assert_eq!(edits(&tree, &answer, &FILES), vec![1, 1], "{answer:#}");
}
#[test]
fn a_member_of_a_generate_block_is_renamed_through_the_path() {
let tree = fixture("toproot_scope_block", "ip/blk/dv/tb.sv");
let mut session = Session::new(vec![tree.path.clone()], false);
let dut = session.open(&tree.path.join("ip/blk/rtl/dut_a.sv"), DUT);
let answer = rename(&mut session, at(&dut, DUT, 4, "buf_q"), "buf_r").expect("renames");
let files = ["ip/blk/rtl/dut_a.sv", "ip/blk/dv/probe.sv"];
assert_eq!(edits(&tree, &answer, &files), vec![1, 1], "{answer:#}");
}
/// The LSP rename equals the engine's over the scope's files.
#[test]
fn the_lsp_rename_equals_the_engine_over_the_scope() {
let tree = fixture("toproot_scope_engine", "ip/blk/dv/tb.sv");
let mut session = Session::new(vec![tree.path.clone()], false);
let core = session.open(&tree.path.join(FILES[0]), CORE);
let answer = rename(&mut session, at(&core, CORE, 1, "sig"), "sig2").expect("renames");
let sources = session.server.workspace.sources();
let path = tree.path.join(FILES[0]);
let offset = CORE.find("sig").expect("sig") as u32;
let engine = vlog_refactor::rename(&sources, &path, offset, "sig2").expect("engine renames");
let lsp = edits(&tree, &answer, &FILES);
let whole: Vec<usize> =
FILES.iter().map(|rel| engine.edits_for(&tree.path.join(rel)).len()).collect();
assert_eq!(lsp, whole);
}
/// `tb.sv` outside the folder scope: the index cannot resolve the root, so
/// the open probe's path is left and warned about, and a rename asked from
/// its segment is refused for what it is — an unresolved path.
#[test]
fn a_root_outside_the_scope_is_warned_and_refused_accurately() {
let tree = fixture("toproot_scope_out", "top/dv/tb.sv");
let mut session = Session::new(vec![tree.path.clone()], false);
let probe = session.open(&tree.path.join(FILES[1]), PROBE);
let core = session.open(&tree.path.join(FILES[0]), CORE);
let in_index =
session.server.workspace.index().files().contains(&tree.path.join("top/dv/tb.sv"));
assert!(!in_index, "premise: the root's file is outside the scope");
let _ = session.drain();
let answer = rename(&mut session, at(&core, CORE, 1, "sig"), "sig2").expect("renames");
assert_eq!(edits(&tree, &answer, &FILES), vec![1, 0], "{answer:#}");
let shown = session.shown();
assert!(shown.iter().any(|(_, m)| m.contains("probe.sv:2:")), "{shown:?}");
let why = rename(&mut session, at(&probe, PROBE, 1, "sig"), "sig3").expect_err("refused");
assert!(why.contains("hierarchical path"), "{why}");
assert!(!why.contains("declared outside"), "{why}");
}
+12
View File
@@ -281,6 +281,18 @@ impl Workspace {
for site in self.index.references_to(def) {
wanted.extend(self.index.path(site.file).map(Path::to_path_buf));
}
// A use written as a hierarchical path (`tb.dut.u_core.sig`) resolves
// inside the engine's set only if the set declares every unit the
// path walks through — the top module it is rooted at and each hop's
// type — so their declaring files come too (top-rooted-paths QA F3).
// Only files the index has: a unit outside the scope is not in it,
// and the path stays unresolved and warned about.
wanted.on(Rung::Declaration);
for unit in self.index.path_units_to(def) {
for unit_def in self.index.units(&unit) {
wanted.extend(self.index.path(unit_def.file).map(Path::to_path_buf));
}
}
}
/// Every file that instantiates a name — the census the reference postings
+51
View File
@@ -278,6 +278,57 @@ fn range_formatting_is_advertised_and_formats_only_the_selection() {
let _ = std::fs::remove_dir_all(&dir);
}
/// Tab-indented, with a parse error after the block: the shape of a buffer
/// mid-edit that "Format Selection" (TODO §66.2) must still serve.
const TABBED_BROKEN: &str = "module m;\n\talways @* begin\n\t\tif (a) x=1;\n\t\telse x=2;\n\tend\n\tassign y = ;\nendmodule\n";
#[test]
fn range_formatting_lays_out_a_nested_selection_in_place_over_the_wire() {
let dir = temp_dir("selectionfmt");
let file = dir.join("m.sv");
std::fs::write(&file, TABBED_BROKEN).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
let request = |id: u32, sl: u32, el: u32| {
frame(&format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/rangeFormatting","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":{sl},"character":0}},"end":{{"line":{el},"character":0}}}},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"#
))
};
let session = [
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(TABBED_BROKEN).expect("json")
)),
// The two statement lines inside the `always`.
request(2, 2, 4),
// The broken line itself: refused, no edit.
request(3, 5, 6),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let messages = talk(&session);
assert_eq!(
new_text(&messages, 2),
"module m;\n\talways @* begin\n\t\tif (a) x = 1;\n\t\telse x = 2;\n\tend\n\tassign y = ;\nendmodule\n",
"only the selected statement moves, tabs kept, error elsewhere ignored"
);
let refused = messages.iter().find(|m| m["id"] == 3).expect("response");
assert!(
refused.get("error").is_some()
|| refused["result"].is_null()
|| refused["result"] == serde_json::json!([]),
"{refused}"
);
let _ = std::fs::remove_dir_all(&dir);
}
/// Four items on four lines, so two ranges can straddle one they leave alone.
const FOUR_ITEMS: &str = "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n";
@@ -0,0 +1,283 @@
//! TODO §65.2 on a real checkout: `textDocument/references` at the `aes`
//! instantiation in `hw/ip/aes/dv/tb/tb.sv` and at its `.clk_i` connection.
//!
//! Over the whole workspace (`lucisv.index.scope: "workspace"`) the server
//! answers what the whole-set engine answers — 14 and 12, the three generated
//! `*_pd_main.sv` tops included. Under the shipped folder scope it answers 11
//! and 9: the testbench's folder raises two levels to `hw/ip/aes`, and the
//! tops are not in the index. Both are pinned, because the difference *is*
//! the finding (`docs/features/references-fanout-pd-main/README.md`).
//!
//! `#[ignore]`: it needs the checkout, which it only reads. Run with
//! `LUCISV_OPENTITAN=/path/to/opentitan tools/guard.sh -- cargo test -p
//! lucisv_server --test opentitan_references -- --ignored --nocapture`;
//! without the variable it looks in `~/.cache/lucisv-eval/ot`, and it skips
//! (passing, with a line on stderr) when neither holds the testbench.
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::mpsc::{self, Receiver};
use std::time::{Duration, Instant};
use serde_json::{json, Value};
/// The testbench, relative to the checkout.
const TB: &str = "hw/ip/aes/dv/tb/tb.sv";
/// The three generated tops the folder scope does not reach.
const TOPS: [&str; 3] = [
"hw/top_darjeeling/rtl/autogen/darjeeling_pd_main.sv",
"hw/top_earlgrey/rtl/autogen/earlgrey_pd_main.sv",
"hw/top_englishbreakfast/rtl/autogen/englishbreakfast_pd_main.sv",
];
/// The checkout: `LUCISV_OPENTITAN`, else the eval clone; `None` when the
/// testbench is not there.
fn checkout() -> Option<PathBuf> {
let root = std::env::var_os("LUCISV_OPENTITAN").map(PathBuf::from).or_else(|| {
std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".cache/lucisv-eval/ot"))
})?;
root.join(TB).is_file().then_some(root)
}
/// One language server over `root/hw`, with `settings` as its `lucisv`
/// section.
struct Server {
child: Child,
stdin: ChildStdin,
inbox: Receiver<Value>,
settings: Value,
next_id: i64,
}
impl Server {
fn over(hw: &Path, settings: Value) -> Server {
// The persistent cache falls back to the OS cache directory; point it
// somewhere a test may write, as `tests/e2e.rs` does.
let sandbox =
std::env::temp_dir().join(format!("lucisv_server_ot_refs_{}", std::process::id()));
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-server"))
.env("HOME", &sandbox)
.env("XDG_CACHE_HOME", sandbox.join("cache"))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.expect("the server binary starts");
let stdin = child.stdin.take().expect("stdin");
let stdout = BufReader::new(child.stdout.take().expect("stdout"));
let (sender, inbox) = mpsc::channel();
std::thread::spawn(move || {
let mut stdout = stdout;
while let Some(message) = read_message(&mut stdout) {
if sender.send(message).is_err() {
break;
}
}
});
let mut server = Server { child, stdin, inbox, settings, next_id: 0 };
let root = uri(hw);
server.request(
"initialize",
json!({
"processId": null, "rootUri": root,
"workspaceFolders": [{ "uri": root, "name": "hw" }],
"capabilities": {
"window": { "workDoneProgress": true },
"workspace": { "configuration": true },
},
}),
);
server.notify("initialized", json!({}));
let lucisv = server.settings.clone();
server.notify(
"workspace/didChangeConfiguration",
json!({ "settings": { "lucisv": lucisv } }),
);
server
}
fn send(&mut self, message: Value) {
let payload = message.to_string();
write!(self.stdin, "Content-Length: {}\r\n\r\n{payload}", payload.len()).expect("write");
self.stdin.flush().expect("flush");
}
fn notify(&mut self, method: &str, params: Value) {
self.send(json!({ "jsonrpc": "2.0", "method": method, "params": params }));
}
/// The next message within `wait`, with every request the server makes
/// of us answered on the way (`workspace/configuration` with our
/// settings, everything else with `null`).
fn next(&mut self, wait: Duration) -> Option<Value> {
let message = self.inbox.recv_timeout(wait).ok()?;
if let (Some(id), Some(method)) = (message.get("id"), message["method"].as_str()) {
let result = if method == "workspace/configuration" {
let items = message["params"]["items"].as_array().map_or(1, Vec::len);
Value::Array(vec![self.settings.clone(); items])
} else {
Value::Null
};
let id = id.clone();
self.send(json!({ "jsonrpc": "2.0", "id": id, "result": result }));
}
Some(message)
}
fn request(&mut self, method: &str, params: Value) -> Value {
self.next_id += 1;
let id = self.next_id;
self.send(json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }));
let deadline = Instant::now() + Duration::from_secs(600);
while Instant::now() < deadline {
let Some(message) = self.next(Duration::from_secs(1)) else { continue };
if message["id"] == id && message.get("method").is_none() {
return message["result"].clone();
}
}
panic!("{method} was not answered");
}
/// Open the testbench and wait until every scan has ended: at least one
/// progress `end` after the open, then five quiet seconds with no bar in
/// flight (the startup scan, the settings push and the open's widen may
/// each run one).
fn open_and_settle(&mut self, path: &Path) {
let text = std::fs::read_to_string(path).expect("read the testbench");
self.notify(
"textDocument/didOpen",
json!({ "textDocument": {
"uri": uri(path), "languageId": "systemverilog", "version": 1, "text": text,
}}),
);
let deadline = Instant::now() + Duration::from_secs(600);
let (mut ended, mut in_flight, mut quiet_since) = (false, 0i32, Instant::now());
while Instant::now() < deadline {
if ended && in_flight <= 0 && quiet_since.elapsed() > Duration::from_secs(5) {
return;
}
let Some(message) = self.next(Duration::from_secs(1)) else { continue };
if message["method"] != "$/progress" {
continue;
}
quiet_since = Instant::now();
match message["params"]["value"]["kind"].as_str() {
Some("begin") => in_flight += 1,
Some("end") => {
in_flight -= 1;
ended = true;
}
_ => {}
}
}
panic!("the scan never settled");
}
/// `references` at the first `needle` on 1-based `line` of `path`, as
/// `file:line` relative to `root`, sorted.
fn references(&mut self, root: &Path, path: &Path, line: usize, needle: &str) -> Vec<String> {
let text = std::fs::read_to_string(path).expect("read");
let row = text.lines().nth(line - 1).expect("the line");
let character = row.find(needle).expect("the needle on that line");
let found = self.request(
"textDocument/references",
json!({
"textDocument": { "uri": uri(path) },
"position": { "line": line - 1, "character": character },
"context": { "includeDeclaration": true },
}),
);
let prefix = format!("{}/", uri(root));
let mut out: Vec<String> = found
.as_array()
.expect("an array")
.iter()
.map(|l| {
let file = l["uri"].as_str().unwrap_or("?").replace(&prefix, "");
format!("{file}:{}", l["range"]["start"]["line"].as_u64().unwrap_or(0) + 1)
})
.collect();
out.sort();
out
}
}
impl Drop for Server {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
fn uri(path: &Path) -> String {
format!("file://{}", path.display())
}
/// One framed message, or `None` when the stream ends.
fn read_message(input: &mut impl BufRead) -> Option<Value> {
let mut length = None;
loop {
let mut line = String::new();
if input.read_line(&mut line).unwrap_or(0) == 0 {
return None;
}
let trimmed = line.trim_end_matches(['\r', '\n']);
if trimmed.is_empty() {
break;
}
if let Some(value) = trimmed.strip_prefix("Content-Length: ") {
length = value.parse::<usize>().ok();
}
}
let mut body = vec![0u8; length?];
input.read_exact(&mut body).ok()?;
serde_json::from_slice(&body).ok()
}
/// The `aes` and `.clk_i` answers of one server over `root/hw`.
fn answers(root: &Path, settings: Value) -> (Vec<String>, Vec<String>) {
let hw = root.join("hw");
let tb = root.join(TB);
let mut server = Server::over(&hw, settings);
server.open_and_settle(&tb);
let module = server.references(root, &tb, 45, "aes");
let port = server.references(root, &tb, 50, "clk_i");
println!("aes: {} {module:#?}\n.clk_i: {} {port:#?}", module.len(), port.len());
(module, port)
}
fn names_a_top(found: &[String], top: &str) -> bool {
found.iter().any(|hit| hit.starts_with(&format!("{top}:")))
}
#[test]
#[ignore = "needs an opentitan checkout (LUCISV_OPENTITAN or ~/.cache/lucisv-eval/ot)"]
fn over_the_whole_workspace_references_list_the_three_generated_tops() {
let Some(root) = checkout() else {
eprintln!("skipped: no opentitan checkout holding {TB}");
return;
};
let (module, port) = answers(&root, json!({ "index": { "scope": "workspace" } }));
assert_eq!(module.len(), 14, "aes: {module:#?}");
assert_eq!(port.len(), 12, ".clk_i: {port:#?}");
for top in TOPS {
assert!(names_a_top(&module, top), "aes misses {top}");
assert!(names_a_top(&port, top), ".clk_i misses {top}");
}
}
#[test]
#[ignore = "needs an opentitan checkout (LUCISV_OPENTITAN or ~/.cache/lucisv-eval/ot)"]
fn under_the_folder_scope_references_stop_at_the_ip_block() {
let Some(root) = checkout() else {
eprintln!("skipped: no opentitan checkout holding {TB}");
return;
};
let (module, port) = answers(&root, json!({}));
assert_eq!(module.len(), 11, "aes: {module:#?}");
assert_eq!(port.len(), 9, ".clk_i: {port:#?}");
let in_block = |found: &[String]| found.iter().all(|hit| hit.starts_with("hw/ip/aes/"));
assert!(in_block(&module) && in_block(&port), "only hw/ip/aes is in scope");
}
+41 -1
View File
@@ -28,7 +28,7 @@ mod stmt;
mod sva;
mod verbatim;
use crate::doc::{text, Doc};
use crate::doc::{concat, text, Doc};
use crate::fence::{self, Region};
use crate::printer::Printer;
use crate::range::{self, Split};
@@ -62,6 +62,10 @@ pub enum FormatError {
Source(vlog_parser::Error),
/// A safety check failed; the formatted text was discarded.
Verification(VerificationError),
/// A selection could not be laid out on its own — it reaches a parse
/// error, or its target could not be found again in the output. Nothing
/// was changed.
Selection(String),
}
impl std::fmt::Display for FormatError {
@@ -69,6 +73,7 @@ impl std::fmt::Display for FormatError {
match self {
FormatError::Source(e) => write!(f, "{e}"),
FormatError::Verification(e) => write!(f, "{e}"),
FormatError::Selection(e) => write!(f, "{e}"),
}
}
}
@@ -130,6 +135,41 @@ pub fn format_range(
Ok(output)
}
/// A sibling run a selection lays out on its own: items at their AST depth,
/// or statements.
pub(crate) enum Run<'t> {
Items(&'t [Item], usize),
Stmts(&'t [Stmt]),
}
/// Lay out one run of `file` (parsed from `source`) exactly as the
/// whole-file printers would, every line starting with `base`.
///
/// No final-newline normalization and no trailing whitespace: the result
/// replaces the run's own bytes and nothing else. Fenced regions inside the
/// run are emitted as written, as in a whole-file run.
pub(crate) fn print_run(
source: &str,
file: &SourceFile,
config: &Config,
run: Run<'_>,
base: &str,
) -> String {
let regions = fence::collect(source, file);
let fmt = Fmt { cfg: config, src: source, regions, splits: Vec::new() };
let docs = match run {
Run::Items(items, depth) => fmt.item_seq(items, depth),
Run::Stmts(stmts) => fmt.stmt_seq(stmts),
};
let printer = Printer { max_width: config.max_width, indent_width: config.indent_width };
let mut out = printer.print_at(&concat(docs), base);
// Spaces and newlines only, exactly what `render` trims.
while out.ends_with('\n') || out.ends_with(' ') {
out.pop();
}
out
}
/// A single unverified formatting pass: parse, lay out, print.
fn format_once(source: &str, config: &Config) -> Result<String, vlog_parser::Error> {
let file = vlog_parser::parse_source(source)?;
+2
View File
@@ -6,8 +6,10 @@ pub mod fence;
pub mod format;
pub mod printer;
pub mod range;
mod selection;
pub mod verify;
pub use format::{format_range, format_source, Config, FormatError};
pub use range::LineRanges;
pub use selection::format_selection;
pub use verify::{verify_convergence, verify_equivalence, VerificationError};
+49 -17
View File
@@ -18,9 +18,22 @@ pub struct Printer {
}
impl Printer {
/// Render `doc` starting at column 0.
pub fn print(&self, doc: &Doc) -> String {
let mut out = String::new();
let mut col = 0usize;
self.print_at(doc, "")
}
/// Render `doc` as if every line began with `base`: the text starts with
/// `base`, every line break the printer writes repeats it before the
/// indentation, and the width budget shrinks by it.
///
/// `base` is copied as written, tabs included, which is what lets a
/// selection keep the indentation it was written at. Text that carries
/// its own absolute indentation (`Doc::Verbatim`, `Doc::Inline`) is not
/// shifted. With an empty `base` this is exactly [`Printer::print`].
pub fn print_at(&self, doc: &Doc, base: &str) -> String {
let mut out = base.to_string();
let mut col = self.base_width(base);
// Stack of (indent_level, mode, doc).
let mut stack: Vec<(usize, Mode, &Doc)> = vec![(0, Mode::Break, doc)];
@@ -61,24 +74,22 @@ impl Printer {
out.push(' ');
col += 1;
} else {
self.newline(&mut out, &mut col, ind);
self.newline(&mut out, &mut col, ind, base);
}
}
Doc::SoftLine => {
if mode == Mode::Break {
self.newline(&mut out, &mut col, ind);
self.newline(&mut out, &mut col, ind, base);
}
}
Doc::HardLine => {
self.newline(&mut out, &mut col, ind);
self.newline(&mut out, &mut col, ind, base);
}
Doc::BlankLine => {
// Trim trailing spaces from the current line, add a blank.
while out.ends_with(' ') {
out.pop();
}
trim_line_end(&mut out, base);
out.push('\n');
self.newline(&mut out, &mut col, ind);
self.newline(&mut out, &mut col, ind, base);
}
Doc::IfBreak(s) => {
if mode == Mode::Break {
@@ -89,9 +100,7 @@ impl Printer {
Doc::Verbatim(s) => {
// Undo the indent the preceding line break wrote: these
// bytes carry their own.
while out.ends_with(' ') {
out.pop();
}
trim_line_end(&mut out, base);
out.push_str(s);
col = s.rsplit('\n').next().map_or(0, |last| last.chars().count());
}
@@ -100,14 +109,20 @@ impl Printer {
out
}
fn newline(&self, out: &mut String, col: &mut usize, ind: usize) {
while out.ends_with(' ') {
out.pop();
}
fn newline(&self, out: &mut String, col: &mut usize, ind: usize, base: &str) {
trim_line_end(out, base);
out.push('\n');
out.push_str(base);
let spaces = ind * self.indent_width;
out.extend(std::iter::repeat_n(' ', spaces));
*col = spaces;
*col = self.base_width(base) + spaces;
}
/// The columns `base` occupies. A tab counts as one indent level: the
/// printer cannot know the reader's tab stop, and the width only steers
/// which groups break.
fn base_width(&self, base: &str) -> usize {
base.chars().map(|c| if c == '\t' { self.indent_width } else { 1 }).sum()
}
/// Would `items` (flat) followed by the rest of the work stack fit on
@@ -194,6 +209,23 @@ impl Printer {
}
}
/// Drop the trailing spaces of the line being written. Under a non-empty
/// `base` a line holding nothing but indentation is emptied entirely, so a
/// blank line never keeps the base's tabs; with no base this is exactly the
/// space trim the printer always did.
fn trim_line_end(out: &mut String, base: &str) {
while out.ends_with(' ') {
out.pop();
}
if base.is_empty() {
return;
}
let bol = out.rfind('\n').map_or(0, |i| i + 1);
if out[bol..].chars().all(|c| c == ' ' || c == '\t') {
out.truncate(bol);
}
}
pub(crate) fn contains_hard_line(items: &[Doc]) -> bool {
items.iter().any(|d| match d {
Doc::HardLine | Doc::BlankLine | Doc::Verbatim(_) => true,
@@ -0,0 +1,262 @@
//! Finding the run of sibling units one selected line span names.
//!
//! The walk starts at the file scope and goes down while the selection sits
//! inside a single unit below its first line and reaches into exactly one of
//! its nested scopes; it then settles on the units met there. A run that cannot be cut
//! out of its lines cleanly, or whose ends a fenced region covers, is trimmed
//! or given up one level at a time. The result is a [`Target`]: a path of
//! child indices plus a run, which is what lets the same units be found again
//! in the formatted output.
use crate::fence::Region;
use vlog_parser::LineIndex;
use super::scope::{Scope, Unit};
/// The units a selection lays out, by position in the tree.
///
/// `path` holds one `(unit index, child scope index)` step per scope the walk
/// descended into; the run is `start..start + count` of the scope it ends in.
/// Positions, not bytes, so the target can be replayed on a reformatted text
/// whose tree is the same.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Target {
pub path: Vec<(usize, usize)>,
pub start: usize,
pub count: usize,
}
/// What one selected line span comes to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum Found {
/// No unit to lay out: blank lines, or everything met is fenced.
Nothing,
/// The run holds a module or package, or no run is line-clean: the
/// request goes to `format_range` whole.
Defer,
Target(Target),
}
/// The finder over one text and the tree parsed from it.
pub(super) struct Locator<'s> {
src: &'s str,
index: LineIndex,
regions: Vec<Region>,
}
impl<'s> Locator<'s> {
pub(super) fn new(src: &'s str, regions: Vec<Region>) -> Locator<'s> {
Locator { src, index: LineIndex::new(src), regions }
}
/// Locate the run the 1-based inclusive lines `first..=last` select.
pub(super) fn locate(&self, root: Scope<'_>, (first, last): (u32, u32)) -> Found {
let mut trail = vec![root];
let mut path = Vec::new();
let mut scope = root;
let Some((mut a, mut b)) = self.met(scope, first, last) else { return Found::Nothing };
while a == b {
let Some((k, child)) = self.descend(scope, a, first, last) else { break };
let Some(run) = self.met(child, first, last) else { break };
path.push((a, k));
trail.push(child);
scope = child;
(a, b) = run;
}
loop {
let Some((a2, b2)) = self.trim_fences(scope, a, b) else { return Found::Nothing };
if self.clean(scope, a2, b2) {
return self.target(scope, path, a2, b2);
}
// Not cut cleanly at its lines: the enclosing unit is.
trail.pop();
let (Some((i, _)), Some(&parent)) = (path.pop(), trail.last()) else {
return Found::Defer;
};
(scope, a, b) = (parent, i, i);
}
}
fn target(&self, scope: Scope<'_>, path: Vec<(usize, usize)>, a: usize, b: usize) -> Found {
let contains_container =
(a..=b).filter_map(|i| scope.unit(i)).any(|unit| unit.is_container());
if contains_container {
return Found::Defer;
}
Found::Target(Target { path, start: a, count: b - a + 1 })
}
/// The first and last units of `scope` whose lines meet `first..=last`.
fn met(&self, scope: Scope<'_>, first: u32, last: u32) -> Option<(usize, usize)> {
let mut hit: Option<(usize, usize)> = None;
for i in 0..scope.len() {
let Some(unit) = scope.unit(i) else { continue };
let (l0, l1) = self.lines(unit);
if l0 <= last && first <= l1 {
hit = Some(hit.map_or((i, i), |(a, _)| (a, i)));
}
}
hit
}
/// The nested scope to descend into from unit `i`: only when the
/// selection does not touch the unit's first line, and reaches into
/// exactly one of its scopes.
///
/// The last line is deliberately not asked about. A selection dragged
/// over the final statements of a block and its closing `end` means those
/// statements; taking the whole enclosing unit for it re-laid hundreds of
/// unselected lines (QA note 2, lead ruling 2026-11-09). The closing line
/// alone meets no nested unit, so it still names the unit it closes.
fn descend<'t>(
&self,
scope: Scope<'t>,
i: usize,
first: u32,
last: u32,
) -> Option<(usize, Scope<'t>)> {
let unit = scope.unit(i)?;
let (l0, _) = self.lines(unit);
if first <= l0 {
return None;
}
let mut reached = unit
.children()
.into_iter()
.enumerate()
.filter(|(_, child)| self.met(*child, first, last).is_some());
let only = reached.next()?;
reached.next().is_none().then_some(only)
}
/// The 1-based first and last lines of a unit's extent.
fn lines(&self, unit: Unit<'_>) -> (u32, u32) {
let (start, end) = unit.extent(self.src);
let first = self.index.line_col(start as u32).0;
let last = self.index.line_col(end.saturating_sub(1).max(start) as u32).0;
(first, last)
}
/// Drop units a fenced region of this scope reaches from both ends of the
/// run, so no region is ever half inside the splice. `None` when nothing
/// is left.
fn trim_fences(&self, scope: Scope<'_>, mut a: usize, mut b: usize) -> Option<(usize, usize)> {
while a <= b && self.fenced(scope, a) {
a += 1;
}
while b > a && self.fenced(scope, b) {
b -= 1;
}
(a <= b).then_some((a, b))
}
/// Whether a region opened in this scope — not one nested inside the
/// unit's own code — overlaps unit `i`'s extent.
fn fenced(&self, scope: Scope<'_>, i: usize) -> bool {
let Some(unit) = scope.unit(i) else { return true };
let (start, end) = unit.extent(self.src);
let span = unit.span();
let (code_start, code_end) = (span.start as usize, span.end as usize);
self.regions.iter().any(|r| {
let overlaps = r.start < end && start < r.end;
let nested = r.start >= code_start && r.end <= code_end;
overlaps && !nested
})
}
/// Whether units `a..=b` can be replaced by whole lines: only indentation
/// before the first, nothing after the last on its line, and no sibling
/// or dangling comment of the scope inside the bytes between.
fn clean(&self, scope: Scope<'_>, a: usize, b: usize) -> bool {
let (Some(first), Some(last)) = (scope.unit(a), scope.unit(b)) else { return false };
let (start, _) = first.extent(self.src);
let (_, end) = last.extent(self.src);
let bol = line_start(self.src, start);
let indent_only = self.src.get(bol..start).is_some_and(|s| s.chars().all(is_indent));
let eol =
self.src.get(end..).map_or(end, |rest| end + rest.find('\n').unwrap_or(rest.len()));
let rest_blank = self.src.get(end..eol).is_some_and(|s| s.chars().all(char::is_whitespace));
let prev_clear = a == 0 || scope.unit(a - 1).is_some_and(|u| u.extent(self.src).1 <= start);
let next_clear = scope.unit(b + 1).is_none_or(|u| u.extent(self.src).0 >= end);
let dangling_clear = scope
.dangling()
.iter()
.all(|c| c.span.end as usize <= start || c.span.start as usize >= end);
indent_only && rest_blank && prev_clear && next_clear && dangling_clear
}
}
/// The bytes a resolved target replaces, and the run that replaces them.
pub(super) struct Placed<'t> {
pub run: crate::format::Run<'t>,
/// Start of the first unit's line: where the splice begins.
pub bol: usize,
/// The base indentation every line of the layout starts with, as a byte
/// range of the source: the leading whitespace of the run's first unit
/// that is not a directive (see [`base_indent`]).
pub base: (usize, usize),
/// One past the last unit's last byte.
pub end: usize,
}
/// Find `target` again in a tree, and the bytes of `src` it occupies.
pub(super) fn resolve<'t>(src: &str, root: Scope<'t>, target: &Target) -> Option<Placed<'t>> {
let mut scope = root;
for &(i, k) in &target.path {
scope = scope.unit(i)?.children().into_iter().nth(k)?;
}
let first = scope.unit(target.start)?;
let last = scope.unit(target.start + target.count.checked_sub(1)?)?;
let start = first.extent(src).0;
let end = last.extent(src).1;
let run = scope.run(target.start, target.count)?;
let base = base_indent(src, scope, target, start);
Some(Placed { run, bol: line_start(src, start), base, end })
}
/// The indentation the run is laid out at: that of its first unit, unless
/// that unit is a compiler directive and a later one is not. Directives are
/// commonly written at column 0 while the code they guard is indented, and
/// the code is what says where the block stands; the directive is then
/// indented with it, as a whole-file run would.
fn base_indent(src: &str, scope: Scope<'_>, target: &Target, start: usize) -> (usize, usize) {
let code = (target.start..target.start + target.count)
.filter_map(|i| scope.unit(i))
.find(|u| !u.is_directive())
.map(|u| u.extent(src).0);
let own_line = |at: usize| {
let bol = line_start(src, at);
src.get(bol..at).is_some_and(|s| s.chars().all(is_indent)).then_some((bol, at))
};
code.and_then(own_line).unwrap_or((line_start(src, start), start))
}
/// Every unit of a resolved target and everything nested in it, for the
/// error-node check of a tolerant parse.
pub(super) fn any_error(root: Scope<'_>, target: &Target) -> bool {
let mut scope = root;
for &(i, k) in &target.path {
let Some(next) = scope.unit(i).and_then(|u| u.children().into_iter().nth(k)) else {
return true;
};
scope = next;
}
(target.start..target.start + target.count).any(|i| scope.unit(i).is_none_or(unit_has_error))
}
fn unit_has_error(unit: Unit<'_>) -> bool {
unit.is_error()
|| unit
.children()
.into_iter()
.any(|s| (0..s.len()).any(|i| s.unit(i).is_none_or(unit_has_error)))
}
/// The start of the line `at` is on.
pub(super) fn line_start(src: &str, at: usize) -> usize {
src.get(..at).and_then(|s| s.rfind('\n')).map_or(0, |i| i + 1)
}
fn is_indent(c: char) -> bool {
c == ' ' || c == '\t'
}
+238
View File
@@ -0,0 +1,238 @@
//! Selection formatting: lay out the smallest run of sibling items or
//! statements the selected lines cover, at the indentation it was written
//! at, and splice it into otherwise untouched bytes.
//!
//! This is what an editor's "Format Selection" wants. `format_range` (the
//! CLI's `--lines`) re-lays whole module-level items at formatter depth;
//! here the unit is whatever sibling list the selection lands in — a `case`
//! inside an `always`, two statements of a function — and the parent is not
//! touched at all. The run keeps the leading whitespace of its first line,
//! tabs and off-grid indentation included. Every other byte of the file stays
//! as written, the file tail included.
//!
//! The safety net is the usual one over the whole file: equivalence of the
//! token streams, then convergence by replaying the located *target* (a path
//! in the tree, not line numbers) on the output. Full spec:
//! `docs/features/selection-formatting/README.md`.
mod locate;
mod scope;
use crate::fence;
use crate::format::{format_range, print_run, Config, FormatError};
use crate::range::LineRanges;
use crate::verify::{verify_convergence, verify_equivalence, VerificationError};
use locate::{any_error, resolve, Found, Locator, Target};
use scope::Scope;
use vlog_parser::ast::SourceFile;
use vlog_parser::ParseDiagnostic;
/// Format the smallest runs of sibling items or statements `lines` covers,
/// each at the indentation its first line was written at, leaving every other
/// byte of `source` as it is.
///
/// A selection reaching a module or package item as a whole is handed to
/// [`format_range`] unchanged. A file that does not parse is formatted only
/// where the selection is clear of every parse error; otherwise, as on any
/// failed check, the caller gets an error and must keep the original text.
///
/// Same stack requirement as [`crate::format_source`].
pub fn format_selection(
source: &str,
config: &Config,
lines: &LineRanges,
) -> Result<String, FormatError> {
let tree = Tree::parse(source).map_err(FormatError::Source)?;
let Some(root) = Scope::root(&tree.file) else {
return format_range(source, config, lines);
};
let locator = Locator::new(source, fence::collect(source, &tree.file));
let Ok(targets) = select(&locator, root, source, lines) else {
return format_range(source, config, lines);
};
if targets.is_empty() {
return Ok(source.to_string());
}
tree.check_clear(source, root, &targets)?;
let output = splice(source, &tree.file, root, config, &targets)
.ok_or_else(|| lost("the selection could not be cut out of its lines"))?;
verify_equivalence(source, &output)?;
let again = replay(&output, config, &targets)?;
verify_convergence(&output, &again)?;
Ok(output)
}
/// Format the output a second time with the same targets, found again by
/// their position in its tree.
fn replay(output: &str, config: &Config, targets: &[Target]) -> Result<String, FormatError> {
let tree = Tree::parse(output).map_err(VerificationError::Reparse)?;
let root = Scope::root(&tree.file).ok_or_else(|| lost("the output is not the same kind"))?;
tree.check_clear(output, root, targets)?;
splice(output, &tree.file, root, config, targets)
.ok_or_else(|| lost("the selection could not be found again in the output"))
}
fn lost(why: &str) -> FormatError {
FormatError::Selection(format!("cannot format the selection: {why}"))
}
/// A parsed text: strictly when it parses, tolerantly when it does not.
struct Tree {
file: SourceFile,
/// The tolerant parse's diagnostics; empty for a strict parse.
diagnostics: Vec<ParseDiagnostic>,
}
impl Tree {
fn parse(src: &str) -> Result<Tree, vlog_parser::Error> {
match vlog_parser::parse_source(src) {
Ok(file) => Ok(Tree { file, diagnostics: Vec::new() }),
Err(e) => {
let (file, diagnostics) = vlog_parser::parse_source_tolerant(src);
// A tolerant parse that finds nothing wrong where the strict
// one failed is not a tree to trust.
if diagnostics.is_empty() {
return Err(e);
}
Ok(Tree { file, diagnostics })
}
}
}
/// Refuse when a parse error lies inside any target: its layout would
/// rest on error recovery's guess.
fn check_clear(
&self,
src: &str,
root: Scope<'_>,
targets: &[Target],
) -> Result<(), FormatError> {
if self.diagnostics.is_empty() {
return Ok(());
}
for target in targets {
let placed = resolve(src, root, target).ok_or_else(|| lost("internal: lost target"))?;
let (lo, hi) = (placed.bol, placed.end);
let hit = self
.diagnostics
.iter()
.find(|d| (d.span.start as usize) <= hi && lo <= d.span.end as usize);
if let Some(d) = hit {
return Err(FormatError::Selection(format!(
"cannot format the selection: it contains a syntax error at {}:{}: {}",
d.line, d.col, d.message
)));
}
if any_error(root, target) {
return Err(lost("it contains text that does not parse"));
}
}
Ok(())
}
}
/// The request goes to `format_range` whole.
struct Defer;
/// Locate one target per selected span; targets whose bytes overlap are
/// re-selected from the hull of their spans.
fn select(
locator: &Locator<'_>,
root: Scope<'_>,
src: &str,
lines: &LineRanges,
) -> Result<Vec<Target>, Defer> {
let mut picked: Vec<Picked> = Vec::new();
for &span in lines.spans() {
picked.extend(pick(locator, root, src, span)?);
}
loop {
picked.sort_by_key(|p| p.bytes.0);
let Some(i) = (1..picked.len()).find(|&i| picked[i].bytes.0 < picked[i - 1].bytes.1) else {
break;
};
let (a, b) = (picked.remove(i), picked.remove(i - 1));
let hull = (a.span.0.min(b.span.0), a.span.1.max(b.span.1));
picked.extend(pick(locator, root, src, hull)?);
}
Ok(picked.into_iter().map(|p| p.target).collect())
}
/// One located target, with the line span that chose it and the bytes it
/// replaces.
struct Picked {
span: (u32, u32),
target: Target,
bytes: (usize, usize),
}
/// The target one span selects, if any.
fn pick(
locator: &Locator<'_>,
root: Scope<'_>,
src: &str,
span: (u32, u32),
) -> Result<Option<Picked>, Defer> {
match locator.locate(root, span) {
Found::Nothing => Ok(None),
Found::Defer => Err(Defer),
Found::Target(target) => {
// Resolving a target in the tree it was found in cannot fail; if
// it ever did, the conservative answer is the old engine.
let placed = resolve(src, root, &target).ok_or(Defer)?;
Ok(Some(Picked { span, target, bytes: (placed.bol, placed.end) }))
}
}
}
/// Replace every target's bytes with its layout, bottom-up so the earlier
/// offsets stay valid. `None` when a target cannot be found or cut.
fn splice(
src: &str,
file: &SourceFile,
root: Scope<'_>,
config: &Config,
targets: &[Target],
) -> Option<String> {
let mut placed = targets.iter().map(|t| resolve(src, root, t)).collect::<Option<Vec<_>>>()?;
placed.sort_by_key(|p| std::cmp::Reverse(p.bol));
let mut out = src.to_string();
let mut floor = src.len();
for p in placed {
let base = src.get(p.base.0..p.base.1)?;
if p.end > floor || !base.chars().all(|c| c == ' ' || c == '\t') {
return None;
}
let mut text = print_run(src, file, config, p.run, base);
if uses_crlf(src, p.bol, p.end) {
text = to_crlf(&text);
}
out = format!("{}{}{}", out.get(..p.bol)?, text, out.get(p.end..)?);
floor = p.bol;
}
Some(out)
}
/// Whether the lines around a target end in `\r\n`: the line ending after
/// it, or before it when it ends the file.
fn uses_crlf(src: &str, bol: usize, end: usize) -> bool {
match src.get(end..).and_then(|rest| rest.find('\n')) {
Some(i) => src.get(..end + i).is_some_and(|s| s.ends_with('\r')),
None => src.get(..bol).is_some_and(|s| s.ends_with("\r\n")),
}
}
/// Turn every bare `\n` into `\r\n`; text copied from the source keeps the
/// `\r\n` it already had.
fn to_crlf(text: &str) -> String {
let mut out = String::with_capacity(text.len() + text.len() / 16);
let mut prev = '\0';
for c in text.chars() {
if c == '\n' && prev != '\r' {
out.push('\r');
}
out.push(c);
prev = c;
}
out
}
@@ -0,0 +1,234 @@
//! The sibling lists a selection can land in, and the units they hold.
//!
//! A *scope* is a sibling list exactly as `fence.rs` defines one — an item
//! list (file, module, package, generate region, generate `begin`…`end`,
//! class) or a statement list (`begin`…`end`, `fork`…`join`, a function or
//! task body). A *unit* is one item or statement of such a list. The match
//! arms below mirror `fence::scan_nested` / `scan_nested_stmt` /
//! `scan_gen_block`: a single-statement body or a block-less generate item is
//! not a scope, so it is walked *through* to the scopes it reaches. An arm
//! missing here only makes a selection coarser, never wrong.
use crate::fence;
use crate::format::Run;
use vlog_parser::ast::{
GenBlock, GenElse, GenIf, Item, ItemKind, Meta, SourceFile, Stmt, StmtKind,
};
use vlog_parser::span::TextRange;
use vlog_parser::token::Comment;
/// One sibling list. Items carry the AST depth `item_seq` lays them out at.
#[derive(Clone, Copy)]
pub(super) enum Scope<'t> {
Items(&'t [Item], &'t [Comment], usize),
Stmts(&'t [Stmt], &'t [Comment]),
}
/// One member of a scope.
#[derive(Clone, Copy)]
pub(super) enum Unit<'t> {
Item(&'t Item, usize),
Stmt(&'t Stmt),
}
impl<'t> Scope<'t> {
/// The scope a whole file is, or `None` for a fragment whose elements
/// are not items or statements (enum members, cover items).
pub(super) fn root(file: &'t SourceFile) -> Option<Scope<'t>> {
match &file.fragment {
None => Some(Scope::Items(&file.items, &file.dangling, 0)),
Some(vlog_parser::ast::Fragment::Statements(stmts)) => {
Some(Scope::Stmts(stmts, &file.dangling))
}
Some(_) => None,
}
}
pub(super) fn len(&self) -> usize {
match self {
Scope::Items(items, ..) => items.len(),
Scope::Stmts(stmts, _) => stmts.len(),
}
}
pub(super) fn unit(&self, i: usize) -> Option<Unit<'t>> {
match *self {
Scope::Items(items, _, depth) => items.get(i).map(|item| Unit::Item(item, depth)),
Scope::Stmts(stmts, _) => stmts.get(i).map(Unit::Stmt),
}
}
pub(super) fn dangling(&self) -> &'t [Comment] {
match *self {
Scope::Items(_, dangling, _) | Scope::Stmts(_, dangling) => dangling,
}
}
/// The units `start..start + count` as something the printers take.
pub(super) fn run(&self, start: usize, count: usize) -> Option<Run<'t>> {
let end = start.checked_add(count)?;
match *self {
Scope::Items(items, _, depth) => items.get(start..end).map(|s| Run::Items(s, depth)),
Scope::Stmts(stmts, _) => stmts.get(start..end).map(Run::Stmts),
}
}
}
impl<'t> Unit<'t> {
fn meta(&self) -> &'t Meta {
match self {
Unit::Item(item, _) => &item.meta,
Unit::Stmt(stmt) => &stmt.meta,
}
}
pub(super) fn span(&self) -> TextRange {
match self {
Unit::Item(item, _) => item.span,
Unit::Stmt(stmt) => stmt.span,
}
}
/// The unit's bytes: its first leading comment or attribute through the
/// comments written after it on the same line.
pub(super) fn extent(&self, src: &str) -> (usize, usize) {
let meta = self.meta();
let span = self.span();
let mut start = span.start;
if let Some(c) = meta.leading.first() {
start = start.min(c.span.start);
}
if let Some(a) = meta.attrs.first() {
start = start.min(a.span.start);
}
// In a CRLF file a trailing `//` comment's line ends `\r\n`, and the
// scan above stops at the `\n`. The `\r` is the line ending, not the
// unit: the layout does not write it, so the splice must not eat it.
let mut end = fence::with_trailing_comments(src, span.end as usize);
while end > span.end as usize && src.as_bytes().get(end - 1) == Some(&b'\r') {
end -= 1;
}
(start as usize, end)
}
/// Whether the unit is a construct `format_range` splits (a module or a
/// package), which a selection defers to it.
pub(super) fn is_container(&self) -> bool {
matches!(
self,
Unit::Item(Item { kind: ItemKind::Module(_) | ItemKind::Package { .. }, .. }, _)
)
}
/// Whether the unit is a compiler directive (`` `ifdef `` and kin),
/// which is often written at column 0 whatever the code around it does.
pub(super) fn is_directive(&self) -> bool {
match self {
Unit::Item(item, _) => matches!(item.kind, ItemKind::Directive(_)),
Unit::Stmt(stmt) => matches!(stmt.kind, StmtKind::Directive(_)),
}
}
/// Whether the unit is a node error recovery made of unparsable text.
pub(super) fn is_error(&self) -> bool {
match self {
Unit::Item(item, _) => matches!(item.kind, ItemKind::Error(_)),
Unit::Stmt(stmt) => matches!(stmt.kind, StmtKind::Error(_)),
}
}
/// The scopes directly nested in this unit, in source order.
pub(super) fn children(&self) -> Vec<Scope<'t>> {
let mut out = Vec::new();
match *self {
Unit::Item(item, depth) => item_scopes(item, depth, &mut out),
Unit::Stmt(stmt) => stmt_scopes(stmt, &mut out),
}
out
}
}
/// The scopes nested in one item at `depth`, at the depth `item_kind` lays
/// their items out at.
fn item_scopes<'t>(item: &'t Item, depth: usize, out: &mut Vec<Scope<'t>>) {
match &item.kind {
ItemKind::Module(m) => out.push(Scope::Items(&m.items, &m.dangling, depth + 1)),
ItemKind::Package { items, dangling, .. }
| ItemKind::GenerateRegion { items, dangling } => {
out.push(Scope::Items(items, dangling, depth + 1))
}
ItemKind::GenBlock(b) => gen_block_scopes(b, depth, out),
ItemKind::GenIf(g) => gen_if_scopes(g, depth, out),
ItemKind::GenFor(g) => gen_block_scopes(&g.body, depth, out),
ItemKind::GenCase(g) => {
for i in &g.items {
gen_block_scopes(&i.body, depth + 1, out);
}
}
ItemKind::Class(c) => out.push(Scope::Items(&c.items, &c.dangling, depth + 1)),
ItemKind::Function(f) => out.push(Scope::Stmts(&f.stmts, &f.dangling)),
ItemKind::Task(t) => out.push(Scope::Stmts(&t.stmts, &t.dangling)),
ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => {
stmt_scopes(stmt, out)
}
_ => {}
}
}
fn gen_if_scopes<'t>(g: &'t GenIf, depth: usize, out: &mut Vec<Scope<'t>>) {
gen_block_scopes(&g.then, depth, out);
match g.els.as_deref() {
Some(GenElse::If(_, inner)) => gen_if_scopes(inner, depth, out),
Some(GenElse::Block(b)) => gen_block_scopes(b, depth, out),
None => {}
}
}
/// A generate `begin`…`end` is a scope one level in; a block-less body's
/// one item is laid out one level in too, and walked through.
fn gen_block_scopes<'t>(b: &'t GenBlock, depth: usize, out: &mut Vec<Scope<'t>>) {
if b.is_block {
out.push(Scope::Items(&b.items, &b.dangling, depth + 1));
} else {
for item in &b.items {
item_scopes(item, depth + 1, out);
}
}
}
/// The statement lists one statement holds, walking through every
/// single-statement body.
fn stmt_scopes<'t>(stmt: &'t Stmt, out: &mut Vec<Scope<'t>>) {
match &stmt.kind {
StmtKind::Block { stmts, dangling, .. } | StmtKind::ForkJoin { stmts, dangling, .. } => {
out.push(Scope::Stmts(stmts, dangling))
}
StmtKind::If { then, els, .. } => {
stmt_scopes(then, out);
if let Some(e) = els {
stmt_scopes(e, out);
}
}
StmtKind::Assert { then, els, .. } => {
for s in then.iter().chain(els.iter()) {
stmt_scopes(s, out);
}
}
StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => {
for i in items {
stmt_scopes(&i.stmt, out);
}
}
StmtKind::For { body, .. }
| StmtKind::While { body, .. }
| StmtKind::DoWhile { body, .. }
| StmtKind::Repeat { body, .. }
| StmtKind::Forever { body }
| StmtKind::Foreach { body, .. }
| StmtKind::Labeled { stmt: body, .. } => stmt_scopes(body, out),
StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => {
stmt_scopes(inner, out)
}
_ => {}
}
}
+451
View File
@@ -0,0 +1,451 @@
//! Selection formatting (`format_selection`): the smallest run of sibling
//! items or statements a selection covers is laid out at the indentation it
//! was written at, and every other byte of the file stays as written.
//!
//! Spec: `docs/features/selection-formatting/README.md`.
use vlog_formatter::{format_range, format_selection, verify_equivalence, Config, LineRanges};
fn select_with(src: &str, spec: &str, config: &Config) -> Result<String, String> {
let lines = LineRanges::parse(spec).expect("line spec");
format_selection(src, config, &lines).map_err(|e| e.to_string())
}
fn select(src: &str, spec: &str) -> String {
select_with(src, spec, &Config::default()).expect("formats")
}
/// Format, then format the result again with the same lines: the second run
/// must change nothing.
fn fixed(src: &str, spec: &str) -> String {
let out = select(src, spec);
assert_eq!(select(&out, spec), out, "a second run must change nothing");
out
}
/// Lines `first..=last` (1-based) of `src` are the target: everything before
/// and after must come back byte for byte, and the returned middle is what
/// replaced them.
fn middle<'a>(src: &str, out: &'a str, first: usize, last: usize) -> &'a str {
let lines: Vec<&str> = src.split_inclusive('\n').collect();
let head: String = lines[..first - 1].concat();
let tail: String = lines[last..].concat();
assert!(out.starts_with(&head), "bytes before the target changed:\n{out}");
assert!(out.ends_with(&tail), "bytes after the target changed:\n{out}");
assert!(out.len() >= head.len() + tail.len(), "target overlaps the kept bytes:\n{out}");
&out[head.len()..out.len() - tail.len()]
}
// ------------------------------------------------------------------
// The owner's shapes
// ------------------------------------------------------------------
/// A file indented four spaces, as many hand-written files are.
const FOUR: &str = "\
module m;
reg [3:0] q;
always @(posedge clk) begin
if (rst) q<=0;
else begin
case (sel)
2'b00: q<=a;
2'b01 : q <= b;
default:q<=c;
endcase
end
end
assign y=q;
endmodule
";
#[test]
fn a_whole_always_keeps_its_indentation_in_a_four_space_file() {
let out = fixed(FOUR, "3-12");
let mid = middle(FOUR, &out, 3, 12);
assert_eq!(
mid,
" always @(posedge clk) begin
if (rst) q <= 0;
else begin
case (sel)
2'b00: q <= a;
2'b01: q <= b;
default: q <= c;
endcase
end
end
"
);
}
#[test]
fn a_whole_case_inside_an_always_is_the_only_thing_laid_out() {
let out = fixed(FOUR, "6-10");
let mid = middle(FOUR, &out, 6, 10);
assert_eq!(
mid,
" case (sel)
2'b00: q <= a;
2'b01: q <= b;
default: q <= c;
endcase
"
);
}
#[test]
fn an_always_inside_a_generate_for_is_laid_out_alone() {
let src = "\
module m;
generate
for (genvar i=0;i<4;i++) begin : g
always @(posedge clk) q[i]<=d[i];
assign w[i]=q[i];
end
endgenerate
endmodule
";
let out = fixed(src, "4");
let mid = middle(src, &out, 4, 4);
assert_eq!(mid, " always @(posedge clk) q[i] <= d[i];\n");
}
#[test]
fn statements_inside_a_function_are_laid_out_without_the_function() {
let src = "\
module m;
function automatic int f(input int a);
int r;
r=a+1;
return r;
endfunction
endmodule
";
let out = fixed(src, "4-5");
let mid = middle(src, &out, 4, 5);
assert_eq!(mid, " r = a + 1;\n return r;\n");
assert!(out.contains(" int r;\n"), "the unselected statement stays: {out}");
}
#[test]
fn a_block_inside_an_else_branch_is_laid_out_alone() {
let src = "\
module m;
always @* begin
if (a) x = 1;
else begin
y=2;
z = 3;
end
end
endmodule
";
let out = fixed(src, "5-6");
let mid = middle(src, &out, 5, 6);
assert_eq!(mid, " y = 2;\n z = 3;\n");
}
// ------------------------------------------------------------------
// Indentation
// ------------------------------------------------------------------
#[test]
fn tab_indentation_is_reproduced_as_written() {
let src = "module m;\n\talways @* begin\n\t\tx=1;\n\t\tif (a) begin\n\t\t\ty=2;\n\t\tend\n\tend\nendmodule\n";
let out = fixed(src, "2-7");
let mid = middle(src, &out, 2, 7);
assert_eq!(
mid,
"\talways @(*) begin\n\t x = 1;\n\t if (a) begin\n\t y = 2;\n\t end\n\tend\n"
);
}
#[test]
fn off_grid_indentation_is_kept() {
let src = "module m;\n always @* begin\n x=1;\n end\nendmodule\n";
let out = fixed(src, "2-4");
assert_eq!(middle(src, &out, 2, 4), " always @(*) begin\n x = 1;\n end\n");
}
#[test]
fn a_misindented_parent_does_not_move_the_selection() {
let src = "module m;\nalways @* begin\n x=1;\n y = 2;\n end\nendmodule\n";
let out = fixed(src, "3");
assert_eq!(middle(src, &out, 3, 3), " x = 1;\n");
assert!(out.contains("\n y = 2;\n"), "the sibling is untouched: {out}");
}
// ------------------------------------------------------------------
// Partial selections
// ------------------------------------------------------------------
#[test]
fn one_line_inside_a_case_lays_out_the_case() {
let out = fixed(FOUR, "8");
let mid = middle(FOUR, &out, 6, 10);
assert!(mid.starts_with(" case (sel)\n"), "{mid}");
assert!(mid.contains(" 2'b01: q <= b;\n"), "{mid}");
}
#[test]
fn a_cursor_only_range_formats_the_statement_under_it() {
let src = "module m;\n always @* begin\n x=1;\n y=2;\n end\nendmodule\n";
let out = fixed(src, "4");
assert_eq!(out, "module m;\n always @* begin\n x=1;\n y = 2;\n end\nendmodule\n");
}
#[test]
fn a_selection_ending_on_the_end_line_takes_only_the_statements_it_covers() {
let src = "module m;\n always @* begin\n x=1;\n y=2;\n end\n assign a=b;\nendmodule\n";
let out = fixed(src, "4-5");
assert_eq!(middle(src, &out, 4, 4), " y = 2;\n");
}
#[test]
fn the_end_line_alone_takes_the_unit_it_closes() {
let src = "module m;\n always @* begin\n x=1;\n y=2;\n end\n assign a=b;\nendmodule\n";
let out = fixed(src, "5");
assert_eq!(middle(src, &out, 2, 5), " always @(*) begin\n x = 1;\n y = 2;\n end\n");
}
#[test]
fn a_selection_starting_on_the_first_line_takes_the_whole_unit() {
let src = "module m;\n always @* begin\n x=1;\n y=2;\n end\n assign a=b;\nendmodule\n";
let out = fixed(src, "2-3");
assert_eq!(middle(src, &out, 2, 5), " always @(*) begin\n x = 1;\n y = 2;\n end\n");
}
#[test]
fn blank_lines_alone_change_nothing() {
let src = "module m;\n wire a;\n\n\n wire b;\nendmodule\n";
assert_eq!(select(src, "3-4"), src);
}
#[test]
fn leading_and_trailing_comments_travel_with_their_unit() {
let src = "module m;\n always @* begin\n // why\n x=1; // what\n y=2;\n end\nendmodule\n";
let out = fixed(src, "4");
assert_eq!(middle(src, &out, 3, 4), " // why\n x = 1; // what\n");
}
#[test]
fn a_comment_after_begin_is_not_line_clean_and_the_parent_is_taken() {
let src = "module m;\n always @* begin // note\n x=1;\n end\nendmodule\n";
let out = fixed(src, "3");
assert_eq!(middle(src, &out, 2, 4), " always @(*) begin\n // note\n x = 1;\n end\n");
}
#[test]
fn two_statements_on_one_line_are_taken_together() {
let src = "module m;\n always @* begin\n x=1; y=2;\n z=3;\n end\nendmodule\n";
let out = fixed(src, "3");
assert_eq!(middle(src, &out, 3, 3), " x = 1;\n y = 2;\n");
assert!(out.contains(" z=3;\n"), "{out}");
}
#[test]
fn a_selection_across_two_branches_takes_the_whole_if() {
let src = "module m;\n always @* begin\n if (a) begin\n x=1;\n end else begin\n y=2;\n end\n end\nendmodule\n";
let out = fixed(src, "4-6");
let mid = middle(src, &out, 3, 7);
assert_eq!(mid, " if (a) begin\n x = 1;\n end else begin\n y = 2;\n end\n");
}
// ------------------------------------------------------------------
// Fences
// ------------------------------------------------------------------
#[test]
fn a_fence_inside_the_target_is_emitted_as_written() {
let src = "module m;\n always @* begin\n x=1;\n // lucisv: off\n y = 2;\n // lucisv: on\n z=3;\n end\nendmodule\n";
let out = fixed(src, "2-8");
assert!(out.contains(" y = 2;\n"), "{out}");
assert!(out.contains(" x = 1;\n") && out.contains(" z = 3;\n"), "{out}");
}
#[test]
fn a_fence_around_the_target_wins() {
let src = "module m;\n // lucisv: off\n always @* begin\n x=1;\n end\n // lucisv: on\nendmodule\n";
assert_eq!(select(src, "4"), src);
assert_eq!(select(src, "3-5"), src);
}
#[test]
fn a_fence_straddling_the_target_trims_the_fenced_units() {
let src = "module m;\n always @* begin\n a=1;\n b=2;\n // lucisv: off\n c = 3;\n // lucisv: on\n d=4;\n end\nendmodule\n";
// Lines 3-6 meet a, b, and c (fenced): c is trimmed off the end.
let out = fixed(src, "3-6");
assert_eq!(middle(src, &out, 3, 4), " a = 1;\n b = 2;\n");
assert!(out.ends_with(
" // lucisv: off\n c = 3;\n // lucisv: on\n d=4;\n end\nendmodule\n"
));
// Lines 6-8 meet c (fenced) and d — whose extent starts at `on`: both go.
assert_eq!(select(src, "6-8"), src);
}
// ------------------------------------------------------------------
// Deferral to `format_range`
// ------------------------------------------------------------------
#[test]
fn a_module_header_or_whole_module_selection_is_format_range() {
let src = "module m(input a,output b);\n wire x;\n assign x=a;\nendmodule\nmodule n;\nendmodule\n";
for spec in ["1", "1-4", "1-6", "4", "2-5"] {
let lines = LineRanges::parse(spec).expect("spec");
let range = format_range(src, &Config::default(), &lines).expect("range formats");
assert_eq!(select(src, spec), range, "spec {spec}");
}
}
// ------------------------------------------------------------------
// Files that do not parse
// ------------------------------------------------------------------
const BROKEN: &str = "\
module m;
always @* begin
x=1;
end
assign y = ;
endmodule
";
#[test]
fn an_error_outside_the_target_does_not_stop_it() {
let out = fixed(BROKEN, "3");
assert_eq!(middle(BROKEN, &out, 3, 3), " x = 1;\n");
}
#[test]
fn an_error_inside_the_target_refuses() {
let err = select_with(BROKEN, "5", &Config::default()).expect_err("refused");
assert!(err.contains("syntax error") || err.contains("parse"), "{err}");
}
// ------------------------------------------------------------------
// Idempotence and multiple ranges
// ------------------------------------------------------------------
#[test]
fn formatting_the_same_target_twice_changes_nothing() {
for spec in ["3-12", "6-10", "4", "8", "13"] {
fixed(FOUR, spec);
}
}
#[test]
fn two_ranges_lay_out_two_targets_and_nothing_between() {
let src = "module m;\n always @* begin\n x=1;\n y=2;\n z=3;\n end\nendmodule\n";
let out = fixed(src, "3,5");
assert_eq!(
out,
"module m;\n always @* begin\n x = 1;\n y=2;\n z = 3;\n end\nendmodule\n"
);
}
#[test]
fn overlapping_targets_are_reselected_from_their_hull() {
// `4` selects the inner statement, `2` the always holding it.
let src = "module m;\n always @* begin\n x=1;\n y=2;\n end\nendmodule\n";
let out = fixed(src, "2,4");
assert_eq!(out, "module m;\n always @(*) begin\n x = 1;\n y = 2;\n end\nendmodule\n");
}
// ------------------------------------------------------------------
// Masked-corruption attacks on the splice
// ------------------------------------------------------------------
/// Either a correct result (equivalent to the input, a fixed point) or a
/// refusal — never silently wrong.
fn correct_or_refused(src: &str, spec: &str) -> Option<String> {
let out = select_with(src, spec, &Config::default()).ok()?;
verify_equivalence(src, &out).expect("the result is equivalent to the input");
assert_eq!(select(&out, spec), out, "and a fixed point");
Some(out)
}
#[test]
fn a_trailing_comment_on_the_last_line_survives() {
let src = "module m;\n always @* begin\n x=1; /* a */ /* b */\n end\nendmodule\n";
let out = correct_or_refused(src, "3").expect("formats");
assert!(out.contains("/* a */") && out.contains("/* b */"), "{out}");
}
#[test]
fn crlf_line_endings_are_kept() {
let src = "module m;\r\n always @* begin\r\n x=1;\r\n y=2;\r\n end\r\nendmodule\r\n";
let out = correct_or_refused(src, "3-4").expect("formats");
assert_eq!(
out,
"module m;\r\n always @* begin\r\n x = 1;\r\n y = 2;\r\n end\r\nendmodule\r\n"
);
}
#[test]
fn crlf_with_a_trailing_comment_on_the_last_line_keeps_every_line_ending() {
// QA finding 1: the `\r` after a trailing `//` comment is the line
// ending, not part of the unit, so the splice leaves it in place.
let src = "module m;\r\n initial begin\r\n a = 1; // c\r\n b = 2; // d\r\n end\r\nendmodule\r\n";
let out = correct_or_refused(src, "3-4").expect("formats");
assert_eq!(out, src.replace("b = 2", "b = 2"));
let out = correct_or_refused(src, "4").expect("formats");
assert_eq!(out, src.replace("b = 2", "b = 2"));
}
#[test]
fn a_multi_line_block_comment_inside_the_target_survives() {
let src =
"module m;\n always @* begin\n /* one\n two */\n x=1;\n end\nendmodule\n";
let out = correct_or_refused(src, "2-6").expect("formats");
assert!(out.contains("/* one\n two */"), "{out}");
}
#[test]
fn a_multi_line_string_inside_the_target_is_kept_or_refused() {
let src =
"module m;\n initial begin\n $display(\"a\\\n b\");\n x=1;\n end\nendmodule\n";
if let Some(out) = correct_or_refused(src, "2-6") {
assert!(out.contains("\"a\\\n b\""), "{out}");
}
}
#[test]
fn a_target_at_the_end_of_a_file_without_a_final_newline() {
let src = "always @* begin\n x=1;\nend";
let out = correct_or_refused(src, "2").expect("formats");
assert_eq!(out, "always @* begin\n x = 1;\nend");
let src = "wire a;\nassign b=a;";
let out = correct_or_refused(src, "2").expect("formats");
assert_eq!(out, "wire a;\nassign b = a;");
}
#[test]
fn multi_byte_characters_before_the_target_do_not_shift_it() {
let src = "module m;\n // café — ünïcode\n wire a; // ß\n assign b=a;\nendmodule\n";
let out = correct_or_refused(src, "4").expect("formats");
assert_eq!(middle(src, &out, 4, 4), " assign b = a;\n");
}
#[test]
fn the_safety_net_rejects_a_mis_spliced_output() {
// An off-by-one at the end of the splice duplicates the `;`; at the
// start it drops the trailing comment's first byte. Both must be caught.
let src = "module m;\n always @* begin\n x=1; // c\n end\nendmodule\n";
let duplicated = "module m;\n always @* begin\n x = 1;; // c\n end\nendmodule\n";
assert!(verify_equivalence(src, duplicated).is_err());
let dropped = "module m;\n always @* begin\n x = 1; c\n end\nendmodule\n";
assert!(verify_equivalence(src, dropped).is_err());
let crlf = "module m;\r\n always @* begin\r\n /* one\r\n two */\r\n x=1;\r\n end\r\nendmodule\r\n";
let lost_comment_line =
"module m;\r\n always @* begin\r\n /* one */\r\n x = 1;\r\n end\r\nendmodule\r\n";
assert!(verify_equivalence(crlf, lost_comment_line).is_err());
}
#[test]
fn a_column_zero_directive_does_not_set_the_indentation_of_the_code_it_guards() {
let src = "module m;\n`ifdef A\n wire a;\n`endif\n wire b;\nendmodule\n";
let out = fixed(src, "2-4");
// The code says where the block stands; the directives are indented with
// it, as a whole-file run indents them.
assert_eq!(middle(src, &out, 2, 4), " `ifdef A\n wire a;\n `endif\n");
}
+28 -3
View File
@@ -49,8 +49,8 @@ use vlog_parser::span::TextRange;
use vlog_parser::token::{is_keyword, TokenKind};
use vlog_parser::tokenize;
use vlog_semantic::{
Def, ExternalResolutions, ExternalTarget, ReferenceId, Resolution, Semantics, Symbol, SymbolId,
WorkspaceIndex,
Def, ExternalResolutions, ExternalTarget, ReferenceId, Resolution, Semantics, Surface, Symbol,
SymbolId, WorkspaceIndex,
};
use crate::trace::RenameTrace;
@@ -130,6 +130,7 @@ pub fn prepare_rename_here(
Ok(RenameTarget { range: cursor, name: reference.name.clone() })
}
Some(ExternalTarget::Ambiguous(_)) => Err(ambiguous(&reference.name)),
_ if hierarchical(&reference.resolution) => Err(unresolved_path(&reference.name)),
_ => Err(declared_outside(&reference.name)),
},
}
@@ -366,7 +367,15 @@ impl<'a> Scope<'a> {
return Err(from_base(&name, base))
}
Resolution::ExternalCandidate { .. } => {
Found::Elsewhere(name, cursor, analysis.external.get(id).cloned())
let answer = analysis.external.get(id).cloned();
let answered = matches!(
answer,
Some(ExternalTarget::Resolved(_) | ExternalTarget::Ambiguous(_))
);
if !answered && hierarchical(&reference.resolution) {
return Err(unresolved_path(&name));
}
Found::Elsewhere(name, cursor, answer)
}
}
}
@@ -594,6 +603,22 @@ fn from_base(name: &str, base: &str) -> String {
)
}
/// Whether a use is a segment of a hierarchical path (its candidate reads a
/// module's hierarchical surface) — the one external candidate whose miss is
/// not "declared outside the indexed files" but "the path did not resolve".
fn hierarchical(resolution: &Resolution) -> bool {
matches!(resolution, Resolution::ExternalCandidate { surface: Surface::Hierarchical, .. })
}
/// The refusal for a path segment the workspace could not walk to a
/// declaration (top-rooted-paths QA F3): a unit the path passes through is
/// not in the files lucisv reads, or several files declare it.
fn unresolved_path(name: &str) -> String {
format!(
"`{name}` is a segment of a hierarchical path lucisv could not resolve to one declaration (a unit the path passes through is not among the files lucisv indexes, or is declared more than once); rename the declaration itself."
)
}
fn declared_outside(name: &str) -> String {
format!(
"`{name}` is declared outside the files lucisv indexes, so a rename here would only be half a rename."
+103 -14
View File
@@ -2,12 +2,20 @@
//! 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`.)
//! in *any* file of the set, that resolved to no declaration at all — no
//! reference, or `NotFound` (`tb.dut.g_sw[0].q` where a local `logic tb`
//! shadows the top module, so the spine stops at a net). 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`.)
//!
//! Since TODO §65.4 a path rooted at a top module another file declares
//! (`tb.dut.g_sw[0].q`, `$root.tb.…`) resolves when the workspace can walk
//! it, and every segment of it is renamed with its declaration. When the
//! workspace cannot — the root is declared nowhere, or by several files
//! (`tb` in seventy opentitan testbenches) — the segment is an external
//! candidate the index left unanswered, and it is named here too: such a
//! path is exactly what this scan was written for.
//!
//! 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
@@ -16,9 +24,9 @@
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::tokenize;
use vlog_semantic::{Resolution, Semantics};
use vlog_semantic::{ExternalResolutions, ExternalTarget, Resolution, Semantics, Surface};
use crate::scope::Scope;
use crate::scope::{Analysis, Scope};
impl<'a> Scope<'a> {
/// One warning per file listing the lines where a path segment spelling
@@ -42,8 +50,7 @@ impl<'a> Scope<'a> {
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));
let lines = unresolved_segments(analysis, &tokens, name, edited.contains(&i));
if lines.is_empty() {
continue;
}
@@ -58,9 +65,16 @@ impl<'a> Scope<'a> {
}
/// 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> {
/// nothing: no reference at all (unless `edited`, see the caller), a
/// reference whose resolution is `NotFound`, or a segment of a top-rooted
/// path the workspace left unanswered ([`top_rooted_miss`]).
fn unresolved_segments(
analysis: &Analysis,
tokens: &[Token],
name: &str,
edited: bool,
) -> Vec<u32> {
let sem = &analysis.semantics;
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) {
@@ -70,7 +84,13 @@ fn unresolved_segments(sem: &Semantics, tokens: &[Token], name: &str, edited: bo
continue;
}
let unresolved = match sem.reference_at(token.span.start) {
Some(r) if r.name_span == token.span => matches!(r.resolution, Resolution::NotFound),
Some(r) if r.name_span == token.span => match r.resolution {
Resolution::NotFound => true,
Resolution::ExternalCandidate { surface: Surface::Hierarchical, .. } => {
top_rooted_miss(sem, &analysis.external, tokens, i)
}
_ => false,
},
_ => !edited,
};
if unresolved && lines.last() != Some(&token.line) {
@@ -80,6 +100,75 @@ fn unresolved_segments(sem: &Semantics, tokens: &[Token], name: &str, edited: bo
lines
}
/// Whether this scan names the use whose name starts at `offset`: a path
/// segment of a top-rooted path the workspace left unanswered. Asked by
/// `warnings.rs`'s unresolved-candidate scan, which skips such a use so each
/// line is said once, in this scan's words (Handshake H1, lead-granted).
pub(super) fn names_top_rooted_miss(analysis: &Analysis, tokens: &[Token], offset: u32) -> bool {
let Ok(i) = tokens.binary_search_by_key(&offset, |t| t.span.start) else { return false };
is_segment(tokens, i) && top_rooted_miss(&analysis.semantics, &analysis.external, tokens, i)
}
/// Whether the segment at `i` is part of a path rooted at a top-level module
/// — its head is `$root`, or a name this file does not declare, which the
/// semantic layer records as a candidate for the unit table on the
/// hierarchical surface — **and** the workspace answered the segment with
/// nothing. An ambiguous answer is not this scan's: when it can name the
/// renamed declaration the rename is refused outright, and when it cannot,
/// the path is another declaration's.
fn top_rooted_miss(
sem: &Semantics,
external: &ExternalResolutions,
tokens: &[Token],
i: usize,
) -> bool {
let answered = sem.reference_id_at(tokens[i].span.start).and_then(|id| external.get(id));
if !matches!(answered, Some(ExternalTarget::StillUnresolved)) {
return false;
}
let Some(head) = path_head(tokens, i) else { return false };
if head.text == "$root" {
return true;
}
match sem.reference_at(head.span.start) {
Some(r) if r.name_span == head.span => matches!(
&r.resolution,
Resolution::ExternalCandidate { surface: Surface::Hierarchical, paths }
if paths.last().is_some_and(|last| *last == head.text)
),
_ => false,
}
}
/// The first token of the dotted path the identifier at `i` is a segment of:
/// back over each `.` and the element selects before it (`g[0][k].x`).
fn path_head(tokens: &[Token], mut i: usize) -> Option<&Token> {
while i >= 2 && tokens[i - 1].is_sym(".") {
let mut j = i - 2;
while tokens[j].is_sym("]") {
j = matching_open(tokens, j)?.checked_sub(1)?;
}
i = j;
}
tokens.get(i)
}
/// The `[` that opens the `]` at `close`.
fn matching_open(tokens: &[Token], close: usize) -> Option<usize> {
let mut depth = 0usize;
for j in (0..=close).rev() {
if tokens[j].is_sym("]") {
depth += 1;
} else if tokens[j].is_sym("[") {
depth -= 1;
if depth == 0 {
return Some(j);
}
}
}
None
}
/// 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 {
+27 -5
View File
@@ -21,11 +21,12 @@ use vlog_parser::defines::DefineKind;
use vlog_parser::span::TextRange;
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::{tokenize, LineIndex};
use vlog_semantic::{ExternalTarget, ReferenceId, Resolution};
use vlog_semantic::{ExternalTarget, ReferenceId, Resolution, Surface};
use crate::TextEdit;
use super::carry::argument_position;
use super::paths;
use super::scoped::{binds_into, spellings, Scoping};
use super::Target;
use crate::scope::Scope;
@@ -524,10 +525,9 @@ impl<'a> Scope<'a> {
return Vec::new();
}
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.
let mut groups: Vec<(String, Vec<u32>)> = Vec::new();
// The unanswered candidates: (unit, offset, on the hierarchical surface).
let mut hits: Vec<(String, u32, bool)> = Vec::new();
for (i, reference) in analysis.semantics.references().iter().enumerate() {
if reference.name != name {
continue;
@@ -542,7 +542,29 @@ impl<'a> Scope<'a> {
) {
continue;
}
let line = lines.line_col(reference.name_span.start).0;
let hierarchical = matches!(
reference.resolution,
Resolution::ExternalCandidate { surface: Surface::Hierarchical, .. }
);
hits.push((unit, reference.name_span.start, hierarchical));
}
// A segment of a top-rooted path is the §65.1 path scan's to name
// (`paths.rs`); naming it here too would say the line twice. Lexed
// only when a hierarchical candidate could be one.
let (tokens, lines) = if hits.iter().any(|(_, _, h)| *h) {
scan.tokens_and_lines(text)
} else {
(None, scan.lines(text))
};
// Unit that could not be found → the lines it was named on.
let mut groups: Vec<(String, Vec<u32>)> = Vec::new();
for (unit, offset, hierarchical) in hits {
let path_line = hierarchical
&& tokens.is_some_and(|t| paths::names_top_rooted_miss(analysis, t, offset));
if path_line {
continue;
}
let line = lines.line_col(offset).0;
match groups.iter_mut().find(|(u, _)| *u == unit) {
Some((_, at)) => at.push(line),
None => groups.push((unit, vec![line])),
@@ -0,0 +1,155 @@
//! TODO §65.4 on a real checkout: `rename keymgr_dpe.gen_sw_assigns`, whose
//! DV interface writes `force tb.dut.gen_sw_assigns[i]…` (a path rooted at a
//! top module another file declares, IEEE 1800 §23.6).
//!
//! Two file sets, because the answer depends on how many `module tb` the set
//! holds (`docs/features/top-rooted-paths/README.md`):
//!
//! * **the IP folder** `hw/ip/keymgr_dpe` — what the language server indexes
//! under its shipped folder scope for a file there. One `tb`; but the
//! interface imports `uvm_pkg::*` and `keymgr_dpe_env_pkg::*`, either of
//! which could supply `tb` by the LRM (and `uvm_pkg` is not in the tree),
//! so the head is not provably the top module and the path is left and
//! named (the rework after QA, F2).
//! * **the whole `hw` tree** — what `lucisv-mcp` hands the engine. Seventy
//! files declare `module tb`, so `tb.dut` names seventy instances and the
//! path resolves to nothing; the rename leaves it and says so.
//!
//! `#[ignore]`: it needs the checkout, which it only reads — the edit is
//! computed, never applied. Run with `LUCISV_OPENTITAN=/path/to/opentitan
//! tools/guard.sh -- cargo test -p vlog_refactor --test opentitan_top_rooted
//! -- --ignored --nocapture`; without the variable it looks in
//! `~/.cache/lucisv-eval/ot`, and it skips (passing, with a line on stderr)
//! when neither holds the IP.
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Instant;
use vlog_refactor::rename;
const RTL: &str = "hw/ip/keymgr_dpe/rtl/keymgr_dpe.sv";
const IF: &str = "hw/ip/keymgr_dpe/dv/env/keymgr_dpe_if.sv";
fn checkout() -> Option<PathBuf> {
let root = std::env::var_os("LUCISV_OPENTITAN").map(PathBuf::from).or_else(|| {
std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".cache/lucisv-eval/ot"))
})?;
root.join(RTL).is_file().then_some(root)
}
/// Every `.sv`/`.svh`/`.v` file under `dir`, with its text, path-sorted.
fn sources(dir: &Path) -> Vec<(PathBuf, String)> {
let mut out = Vec::new();
let mut stack = vec![dir.to_path_buf()];
while let Some(d) = stack.pop() {
let Ok(entries) = fs::read_dir(&d) else { continue };
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
stack.push(path);
} else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "svh" | "v"))
{
if let Ok(text) = fs::read_to_string(&path) {
out.push((path, text));
}
}
}
}
out.sort();
out
}
/// The rename over one set: the 1-based lines it edits in the interface file,
/// how many sites in how many files, and the warnings naming the interface.
fn probe(root: &Path, set: &str) -> (Vec<usize>, usize, usize, Vec<String>) {
let files = sources(&root.join(set));
let rtl = root.join(RTL);
let text = &files.iter().find(|(p, _)| *p == rtl).expect("the rtl is in the set").1;
let offset = text.find("begin : gen_sw_assigns").expect("the label") + "begin : ".len();
let started = Instant::now();
let edit = rename(&files, &rtl, offset as u32, "gen_sw_asg").expect("renames");
let took = started.elapsed();
let iface = root.join(IF);
let if_text = &files.iter().find(|(p, _)| *p == iface).expect("the interface").1;
let lines: Vec<usize> = edit
.edits_for(&iface)
.iter()
.map(|e| if_text[..e.range.start as usize].matches('\n').count() + 1)
.collect();
let touched: Vec<&PathBuf> =
files.iter().map(|(p, _)| p).filter(|p| !edit.edits_for(p).is_empty()).collect();
let sites: usize = touched.iter().map(|p| edit.edits_for(p).len()).sum();
let warned: Vec<String> =
edit.warnings.iter().filter(|w| w.contains("keymgr_dpe_if.sv")).cloned().collect();
eprintln!(
"{set}: {} files, {sites} sites in {} files, {} warnings ({} naming the interface), {took:.2?}",
files.len(),
touched.len(),
edit.warnings.len(),
warned.len()
);
for w in &edit.warnings {
eprintln!(" warning: {w}");
}
(lines, sites, touched.len(), warned)
}
#[test]
#[ignore = "needs an opentitan checkout"]
fn the_ip_folder_leaves_the_imported_head_and_says_so() {
let Some(root) = checkout() else {
eprintln!("skipped: no opentitan checkout");
return;
};
let (lines, _, _, warned) = probe(&root, "hw/ip/keymgr_dpe");
assert!(lines.is_empty(), "an import could supply `tb`: {lines:?}");
let said: Vec<&String> = warned.iter().filter(|w| w.contains("514")).collect();
assert_eq!(said.len(), 1, "the force lines are said once: {warned:?}");
}
#[test]
#[ignore = "needs an opentitan checkout"]
fn the_whole_tree_leaves_the_ambiguous_root_and_says_so() {
let Some(root) = checkout() else {
eprintln!("skipped: no opentitan checkout");
return;
};
let (lines, _, _, warned) = probe(&root, "hw");
assert!(lines.is_empty(), "seventy `tb`s: the path names nothing: {lines:?}");
let said: Vec<&String> = warned.iter().filter(|w| w.contains("514")).collect();
assert_eq!(said.len(), 1, "the force lines are said once: {warned:?}");
}
/// The index cost of the extra external references: the facts every file
/// records (encoded bytes — the persistent store's size), the reference
/// postings the merge resolves them into, and the wall time of the build,
/// best of three. Prints only; the before/after is the feature README's.
#[test]
#[ignore = "needs an opentitan checkout"]
fn index_cost_over_the_whole_tree() {
let Some(root) = checkout() else {
eprintln!("skipped: no opentitan checkout");
return;
};
let files = sources(&root.join("hw"));
let bytes: usize = files
.iter()
.map(|(p, t)| vlog_semantic::FileFacts::of(p.clone(), t).encode().map_or(0, |s| s.len()))
.sum();
let mut best: Option<std::time::Duration> = None;
let mut sizes = None;
for _ in 0..3 {
let started = Instant::now();
let index = vlog_semantic::WorkspaceIndex::build(
files.iter().map(|(p, t)| (p.clone(), t.as_str())),
);
let took = started.elapsed();
best = Some(best.map_or(took, |b| b.min(took)));
sizes = Some(index.table_sizes());
}
eprintln!(
"index over {} files: facts {bytes} bytes, {sizes:?}, build best of 3 {best:.2?}",
files.len()
);
}
+54 -10
View File
@@ -529,15 +529,15 @@ 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.
// TODO §65.4 (superseding the lead's F1 ruling, which warned): the root
// `tb` is the top module `tb.sv` declares (IEEE 1800 §23.6), so the path
// resolves and is renamed with the declaration — and nothing is warned.
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:?}");
assert_eq!(texts[1], tb, "the testbench does not spell the name");
assert_eq!(texts[2], probe.replace(old, new), "the path moves with it");
assert!(warnings.is_empty(), "{warnings:?}");
}
}
@@ -619,16 +619,48 @@ 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)]
}
/// The set without `tb.sv`: nothing declares the root `tb`, so no path
/// rooted at it can resolve (TODO §65.4 — with `tb.sv` in the set they do).
fn rc_files_without_the_root() -> Vec<(&'static str, &'static str)> {
rc_files().into_iter().filter(|(name, _)| *name != "tb.sv").collect()
}
#[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");
renamed(&rc_files_without_the_root(), "dut_a.sv", "begin : ", "g_sw", "g_hw")
.expect("renames");
assert_eq!(texts[2], 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:?}");
}
/// TODO §65.4: with the root declared, every path shape is renamed and the
/// comment, the string and the connection to an unknown module are not.
#[test]
fn every_path_shape_rooted_at_a_declared_top_module_is_renamed() {
let (texts, warnings) =
renamed(&rc_files(), "dut_a.sv", "begin : ", "g_sw", "g_hw").expect("renames");
let code: Vec<&str> = RC_PROBE.lines().collect();
let want: Vec<String> = code
.iter()
.enumerate()
.map(
|(i, l)| {
if [1, 2, 3, 5].contains(&i) {
l.replace("g_sw", "g_hw")
} else {
l.to_string()
}
},
)
.collect();
assert_eq!(texts[3], want.join("\n") + "\n");
assert_eq!(texts[1], RC_OTHER, "`dut_b`'s block is another declaration");
assert!(warnings.is_empty(), "{warnings:?}");
}
#[test]
fn recheck_a_path_that_resolves_to_another_declaration_is_not_warned_about() {
let user = "module user (output logic o);
@@ -646,11 +678,17 @@ endmodule
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();
let mut files = rc_files_without_the_root();
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:?}");
// TODO §65.4: with the root declared, the fragment's path is renamed.
let mut files = rc_files();
files.push(("frag.svh", frag));
files.push(("host.sv", host));
let (texts, _) = renamed(&files, "dut_a.sv", "begin : ", "g_sw", "g_hw").expect("renames");
assert_eq!(texts[4], frag.replace("g_sw", "g_hw"));
}
/// The word census holds no escaped identifier (`words.rs`: "an escaped
@@ -660,11 +698,17 @@ 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)];
// Without `tbe.sv` nothing declares the root, and the path is named.
let files = [("dut_e.sv", dut), ("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:?}");
// TODO §65.4: with it, the escaped segment is renamed.
let files = [("dut_e.sv", dut), ("tbe.sv", tb), ("pe.sv", probe)];
let (texts, warnings) =
renamed(&files, "dut_e.sv", "begin : ", "\\g$sw", "g_hw").expect("renames");
assert_eq!(texts[2], probe.replace("\\g$sw", "g_hw"), "{warnings:?}");
}
#[test]
@@ -175,17 +175,16 @@ endmodule
}
/// Rework 2, R1: three files named `probe.sv` at different depths, each with
/// an unresolved path — each warning must name a findable file.
/// an unresolved path — each warning must name a findable file. (Since TODO
/// §65.4 a root some file declares resolves, so the set declares no `tb`.)
#[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()),
@@ -250,17 +249,22 @@ endmodule
}
}
/// Rework 2, R2: an escaped net and an escaped label behind an unresolved root.
/// Rework 2, R2: an escaped net and an escaped label behind an unresolved root
/// — no file declares `tbe` — and, since TODO §65.4, renamed behind one that
/// is declared.
#[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 files = [("dut_e.sv", dut), ("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:#?}");
let files = [("dut_e.sv", dut), ("tbe.sv", tb), ("pe.sv", probe)];
let (texts, warnings) = run(&files, "dut_e.sv", "logic ", "\\n$q", "n_q").expect("net");
assert_eq!(texts[2], probe.replace("\\n$q", "n_q"), "{warnings:#?}");
}
// ---------------------------------------------------------------------------
@@ -258,7 +258,9 @@ 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}");
// Since TODO §65.4 `genblk1.` heads a path rooted at a top module no
// file declares — refused all the same, never this file's unnamed block.
assert!(why.contains("not resolved") || why.contains("hierarchical path"), "{why}");
assert!(prepare_rename(&files, &path("m.sv"), at(text, "o = ", "genblk1")).is_err());
}
@@ -351,6 +353,7 @@ fn an_unresolved_path_through_the_name_warns_and_a_path_to_another_declaration_d
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));
// `tb` is declared nowhere (TODO §65.4 resolves it when it is).
assert_eq!(warnings.len(), 1, "{warnings:?}");
assert!(warnings[0].starts_with("probe.sv:2,3,4: "), "{warnings:?}");
}
@@ -0,0 +1,343 @@
//! TODO §65.4: `find_references` and `rename` through a hierarchical path
//! rooted at a top-level module another file declares (`tb.dut.g_sw[0].q`,
//! the opentitan DV `force` shape; IEEE 1800 §23.6), and `$root.tb.…`.
//! `docs/features/top-rooted-paths/README.md`.
use std::path::{Path, PathBuf};
use vlog_refactor::{find_references, rename, RefactorEdit};
const DUT: &str = "module dut_a;
for (genvar i = 0; i < 2; i++) begin : g_sw
logic buf_q;
end
endmodule
";
const TB: &str = "module tb;
dut_a dut ();
endmodule
";
const PROBE: &str = "module probe (output logic o);
assign o = tb.dut.g_sw[0].buf_q;
initial force tb.dut.g_sw[1].buf_q = 1'b0;
initial release $root.tb.dut.g_sw[1].buf_q;
endmodule
";
fn path(name: &str) -> PathBuf {
PathBuf::from("/rtl").join(name)
}
fn workspace(files: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
files.iter().map(|(name, text)| (path(name), text.to_string())).collect()
}
/// The offset of the first `name` 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"));
let from = from + prefix.len();
(from + text[from..].find(name).expect("the name after the prefix")) as u32
}
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
}
/// Every file's text after renaming the `name` after `prefix` in `file`, and
/// the warnings.
fn renamed(
files: &[(&str, &str)],
file: &str,
prefix: &str,
name: &str,
new: &str,
) -> (Vec<String>, Vec<String>) {
let text = files.iter().find(|(n, _)| *n == file).map(|(_, t)| *t).expect("the file");
let edit = rename(&workspace(files), &path(file), at(text, prefix, name), new)
.unwrap_or_else(|why| panic!("rename refused: {why}"));
let texts = files.iter().map(|(n, t)| apply(t, &edit, &path(n))).collect();
(texts, edit.warnings)
}
/// `file:line` of every reference to the `name` after `prefix`, sorted.
fn references(files: &[(&str, &str)], file: &str, prefix: &str, name: &str) -> Vec<String> {
let text = files.iter().find(|(n, _)| *n == file).map(|(_, t)| *t).expect("the file");
let found = find_references(&workspace(files), &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");
assert_eq!(&text[span.as_range()], ident_at(text, span.start));
format!("{name}:{}", text[..span.start as usize].matches('\n').count() + 1)
})
.collect();
out.sort();
out
}
/// The identifier starting at `start` — what a reference span must slice.
fn ident_at(text: &str, start: u32) -> &str {
let rest = &text[start as usize..];
let end = rest.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).unwrap_or(rest.len());
&rest[..end]
}
fn files() -> Vec<(&'static str, &'static str)> {
vec![("dut_a.sv", DUT), ("tb.sv", TB), ("probe.sv", PROBE)]
}
#[test]
fn find_references_lists_every_segment_of_a_top_rooted_path() {
let files = files();
let want = ["dut_a.sv:2", "probe.sv:2", "probe.sv:3", "probe.sv:4"];
assert_eq!(references(&files, "dut_a.sv", "begin : ", "g_sw"), want);
let want = ["dut_a.sv:3", "probe.sv:2", "probe.sv:3", "probe.sv:4"];
assert_eq!(references(&files, "dut_a.sv", "logic ", "buf_q"), want);
let want = ["probe.sv:2", "probe.sv:3", "probe.sv:4", "tb.sv:2"];
assert_eq!(references(&files, "tb.sv", "dut_a ", "dut"), want);
let want = ["probe.sv:2", "probe.sv:3", "probe.sv:4", "tb.sv:1"];
assert_eq!(references(&files, "tb.sv", "module ", "tb"), want, "the root itself");
}
#[test]
fn renaming_a_member_rewrites_the_path_and_warns_about_nothing() {
let files = files();
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);
assert_eq!(texts[0], DUT.replace(old, new));
assert_eq!(texts[1], TB);
assert_eq!(texts[2], PROBE.replace(old, new));
assert!(warnings.is_empty(), "{warnings:?}");
}
}
#[test]
fn renaming_the_instance_or_the_top_module_rewrites_its_segment() {
let files = files();
let (texts, warnings) = renamed(&files, "tb.sv", "dut_a ", "dut", "u_dut");
assert_eq!(texts[1], TB.replace(" dut ", " u_dut "));
assert_eq!(texts[2], PROBE.replace("tb.dut.", "tb.u_dut."));
assert!(warnings.is_empty(), "{warnings:?}");
let (texts, warnings) = renamed(&files, "tb.sv", "module ", "tb", "top_tb");
assert_eq!(texts[1], TB.replace("module tb", "module top_tb"));
assert_eq!(texts[2], PROBE.replace("tb.dut.", "top_tb.dut."));
assert!(warnings.is_empty(), "{warnings:?}");
}
/// The rename can be asked from the path itself, at any segment.
#[test]
fn a_rename_requested_on_a_segment_of_the_path_renames_the_declaration() {
let files = files();
let (texts, warnings) = renamed(&files, "probe.sv", "force tb.dut.", "g_sw", "g_hw");
assert_eq!(texts[0], DUT.replace("g_sw", "g_hw"));
assert_eq!(texts[2], PROBE.replace("g_sw", "g_hw"));
assert!(warnings.is_empty(), "{warnings:?}");
}
/// A local of the head's name wins (IEEE 1800 §23.8's upward search finds it
/// first): the path is that net's, nothing is rewritten, and the segment no
/// declaration answers is named — the §65.1 path warning, as before.
#[test]
fn a_local_that_shadows_the_top_module_is_not_renamed_through() {
let shadow = "module probe2 (output logic o);
logic tb;
assign o = tb.dut.g_sw[0].buf_q;
endmodule
";
let mut files = files();
files.push(("probe2.sv", shadow));
let (texts, warnings) = renamed(&files, "dut_a.sv", "begin : ", "g_sw", "g_hw");
assert_eq!(texts[2], PROBE.replace("g_sw", "g_hw"), "the unshadowed paths move");
assert_eq!(texts[3], shadow, "the shadowed path does not");
let said: Vec<&String> = warnings.iter().filter(|w| w.contains("probe2.sv")).collect();
assert_eq!(said.len(), 1, "{warnings:?}");
assert!(said[0].starts_with("probe2.sv:3:"), "{said:?}");
}
/// A root no file declares: the path is left and named, with its lines.
#[test]
fn a_root_the_workspace_does_not_declare_is_left_and_warned_about() {
let files = [("dut_a.sv", DUT), ("probe.sv", PROBE)];
let (texts, warnings) = renamed(&files, "dut_a.sv", "begin : ", "g_sw", "g_hw");
assert_eq!(texts[1], PROBE, "nothing reaches `dut_a` from an unknown root");
// Exactly one warning names these sites — the §65.1 path line; the
// unresolved-candidate scan leaves them to it (Handshake H1).
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:") && said[0].contains("`g_sw`"), "{said:?}");
}
/// Two `module tb`: `tb.dut` names two instances, so nothing after it is
/// renamed, and it is said.
#[test]
fn an_ambiguous_root_is_left_and_warned_about() {
let dut_b = "module dut_b;\n logic x;\nendmodule\n";
let tb2 = "module tb;\n dut_b dut ();\nendmodule\n";
let mut files = files();
files.push(("dut_b.sv", dut_b));
files.push(("tb2.sv", tb2));
let (texts, warnings) = renamed(&files, "dut_a.sv", "begin : ", "g_sw", "g_hw");
assert_eq!(texts[2], PROBE);
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:"), "{warnings:?}");
}
/// With two `module tb`, each `tb.` head could name either, so renaming one
/// of them is refused rather than rewriting heads that may be the other's.
#[test]
fn renaming_one_of_two_same_named_tops_is_refused() {
let tb2 = "module tb;\n dut_a dut ();\nendmodule\n";
let mut files = files();
files.push(("tb2.sv", tb2));
let text = TB;
let why = rename(&workspace(&files), &path("tb.sv"), at(text, "module ", "tb"), "top_tb")
.expect_err("refused");
assert!(why.contains("tb"), "{why}");
}
/// Handshake H1: QA's repro (`probe.sv: assign o = tb.dut.g_sw[0].buf_q;`)
/// with the root undeclared, and with three `module tb` (the opentitan
/// shape): exactly one warning names the probe's line, the §65.1 path line,
/// and the unresolved-candidate scan does not repeat it.
#[test]
fn an_unresolved_top_rooted_path_is_named_by_exactly_one_warning() {
let probe = "module probe (output logic o);\n assign o = tb.dut.g_sw[0].buf_q;\nendmodule\n";
let tb_b = "module tb;\n dut_b dut ();\nendmodule\n";
let tb_c = "module tb;\n dut_c dut ();\nendmodule\n";
let undeclared = vec![("dut_a.sv", DUT), ("probe.sv", probe)];
let mut three = vec![("dut_a.sv", DUT), ("tb.sv", TB), ("probe.sv", probe)];
three.extend([("tb_b.sv", tb_b), ("tb_c.sv", tb_c)]);
for files in [undeclared, three] {
for (prefix, old) in [("begin : ", "g_sw"), ("logic ", "buf_q")] {
let (texts, warnings) = renamed(&files, "dut_a.sv", prefix, old, "renamed_x");
let at_probe = files.iter().position(|(n, _)| *n == "probe.sv").expect("probe");
assert_eq!(texts[at_probe], probe, "left unchanged");
let said: Vec<&String> = warnings.iter().filter(|w| w.contains("probe.sv")).collect();
assert_eq!(said.len(), 1, "{old}: {warnings:?}");
assert!(said[0].starts_with("probe.sv:2:"), "{old}: {said:?}");
}
}
}
// ---------------------------------------------------------------------------
// Rework after QA (2026-10-19): rooting only when the head is provably a top
// module or interface. Each case is QA's repro (`scratchpad/qa654/attack`);
// each asserts the path is left unchanged and named, never silently renamed.
// ---------------------------------------------------------------------------
/// Rename the `name` after `prefix` in `file`; assert `left` is unchanged and
/// a warning names `left`'s `line`.
fn left_and_named(files: &[(&str, &str)], at_: (&str, &str, &str), left: &str, line: u32) {
let (file, prefix, name) = at_;
let (texts, warnings) = renamed(files, file, prefix, name, "renamed_x");
let i = files.iter().position(|(n, _)| *n == left).expect("the left file");
assert_eq!(texts[i], files[i].1, "{name}: `{left}` is not edited");
let named = format!("{left}:{line}:");
assert!(warnings.iter().any(|w| w.starts_with(&named)), "{name}: {warnings:?}");
}
/// QA F1 (B12): a package `tb` beside the module `tb`. Renaming the package's
/// `dut` used to rewrite `tb.dut.x`; renaming the module's instance used to
/// miss it. Neither touches it now, and both name it.
#[test]
fn qa_f1_a_package_sharing_the_roots_name_lends_the_path_nothing() {
let dut = "module dut_a;\n logic x;\nendmodule\n";
let pkg = "package tb;\n logic dut;\nendpackage\n";
let other = "module other;\n initial force tb.dut.x = 0;\nendmodule\n";
let files = [("dut_a.sv", dut), ("tb.sv", TB), ("tb_pkg.sv", pkg), ("other.sv", other)];
left_and_named(&files, ("tb_pkg.sv", "logic ", "dut"), "other.sv", 2);
left_and_named(&files, ("tb.sv", "dut_a ", "dut"), "other.sv", 2);
left_and_named(&files, ("dut_a.sv", "logic ", "x"), "other.sv", 2);
}
/// QA A3/A4: `pk.x` (illegal) with a package `pk`, with and without a module
/// `pk`: renaming the package's `x` leaves it.
#[test]
fn qa_f1_a_package_is_never_a_root() {
let pkg = "package pk;\n logic x;\nendpackage\n";
let module = "module pk;\n logic x;\nendmodule\n";
let user = "module user (output logic o);\n assign o = pk.x;\nendmodule\n";
let alone = [("p.sv", pkg), ("user.sv", user)];
let (texts, _) = renamed(&alone, "p.sv", "logic ", "x", "y");
assert_eq!(texts[1], user);
let both = [("p.sv", pkg), ("m.sv", module), ("user.sv", user)];
left_and_named(&both, ("p.sv", "logic ", "x"), "user.sv", 2);
left_and_named(&both, ("m.sv", "logic ", "x"), "user.sv", 2);
}
/// QA F2 (A1): `import p::*` supplies `cfg`, a package variable, and a module
/// `cfg` exists too. The imported name is the head; renaming the module's
/// `field` used to rewrite `cfg.field`.
#[test]
fn qa_f2_an_imported_head_is_never_rooted_at_a_same_named_module() {
let pkg = "package p;\n typedef struct packed { logic field; } s_t;\n s_t cfg;\nendpackage\n";
let module = "module cfg;\n logic field;\nendmodule\n";
let user =
"module user (output logic o);\n import p::*;\n assign o = cfg.field;\nendmodule\n";
let files = [("p.sv", pkg), ("cfgm.sv", module), ("user.sv", user)];
left_and_named(&files, ("cfgm.sv", "logic ", "field"), "user.sv", 3);
}
/// QA F4: three heads the binder cannot see — a macro-declared member in a
/// class (A11), a macro-declared struct in a module (A12) and a class in a
/// package writing `tb.dut.x` (D2) — each used to be renamed through a
/// same-named module.
#[test]
fn qa_f4_a_head_this_crate_cannot_see_is_never_rooted() {
let cfg = "module cfg;\n logic en;\nendmodule\n";
let class = "class env;\n `DECLARE_CFG\n task run(); if (cfg.en) $display(\"x\"); endtask\nendclass\n";
left_and_named(&[("cm.sv", cfg), ("cls.sv", class)], ("cm.sv", "logic ", "en"), "cls.sv", 3);
let st = "module st;\n logic a;\nendmodule\n";
let user = "module user (output logic o);\n `DECL_STRUCT(st)\n assign o = st.a;\nendmodule\n";
left_and_named(&[("cm.sv", st), ("user.sv", user)], ("cm.sv", "logic ", "a"), "user.sv", 3);
let dut = "module dut_a;\n logic x;\nendmodule\n";
let pkg = "package env_pkg;\n class seq;\n task body(); tb.dut.x = 1; endtask\n endclass\nendpackage\n";
let files = [("dut_a.sv", dut), ("tb.sv", TB), ("pkg.sv", pkg)];
left_and_named(&files, ("dut_a.sv", "logic ", "x"), "pkg.sv", 3);
}
/// QA R1 (E1, E2, E6, E3): a macro statement in a `begin` block, a task or a
/// function body, or a macro in the ANSI port list, may declare `st`/`bus`;
/// renaming the same-named module's member leaves the path and names it.
#[test]
fn qa_r1_a_macro_where_a_declaration_could_stand_blocks_rooting() {
let st = "module st;\n logic a;\nendmodule\n";
for (user, line) in [
("module user;\n initial begin\n `DECL_LOCAL(st)\n st.a = 1;\n end\nendmodule\n", 4),
("module user;\n task automatic t();\n `DECL_LOCAL(st)\n st.a = 1;\n endtask\nendmodule\n", 4),
("module user;\n function automatic void f();\n `DECL_LOCAL(st)\n begin st.a = 1; end\n endfunction\nendmodule\n", 4),
] {
left_and_named(&[("st.sv", st), ("user.sv", user)], ("st.sv", "logic ", "a"), "user.sv", line);
}
let bus = "module bus;\n logic data;\nendmodule\n";
let user = "module user (`MY_PORTS, output logic o);\n assign o = bus.data;\nendmodule\n";
let files = [("bus.sv", bus), ("user.sv", user)];
let (texts, _) = renamed(&files, "bus.sv", "logic ", "data", "d2");
assert_eq!(texts[1], user, "the macro port may declare `bus`");
}
/// The held shapes (E7, E8): a macro in a sibling generate block, or used as
/// a data type, declares no head on the path's scope chain — renamed.
#[test]
fn qa_r1_a_macro_off_the_scope_chain_or_as_a_type_still_renames() {
let st = "module st;\n logic a;\nendmodule\n";
for user in [
"module user;\n if (1) begin : g1\n `DECL_LOCAL(st)\n end\n if (1) begin : g2\n initial st.a = 1;\n end\nendmodule\n",
"module user;\n `MY_STRUCT_T other;\n initial st.a = 1;\nendmodule\n",
] {
let files = [("st.sv", st), ("user.sv", user)];
let (texts, warnings) = renamed(&files, "st.sv", "logic ", "a", "b");
assert_eq!(texts[1], user.replace("st.a", "st.b"), "{warnings:?}");
}
}
+12 -3
View File
@@ -74,8 +74,9 @@ impl<'a> Binder<'a> {
self.bind_expr(lsb, scope);
}
// `a.b`, `a.b.c`, `tb.dut.u_core.sig`: every link is bound —
// the head as an ordinary use, each `.name` as a tail against the
// type of what precedes it (`Target::MemberOf`) — because the
// the head as a path root (`Target::PathHead`), each `.name` as a
// tail against the type of what precedes it (`Target::MemberOf`) —
// because the
// recursion below meets each `Member` node in turn. `this.b` and
// `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
@@ -92,7 +93,15 @@ impl<'a> Binder<'a> {
self.use_member(scope, name, member_tail(e.span, name), Target::SuperMember)
}
_ => {
self.bind_expr(base, scope);
// A bare head is a path's root: a miss there names a
// top-level module (`Target::PathHead`), where any other
// bare identifier's miss names nothing.
match &base.kind {
ExprKind::Ident(head) => {
self.use_name(scope, head, base.span, Target::PathHead)
}
_ => self.bind_expr(base, scope),
}
if let Some((head, mids)) = spine(base) {
// The tail's range is derived from the whole
// expression's, so it is verified before use: a
+21 -1
View File
@@ -183,9 +183,11 @@ impl<'a> Binder<'a> {
// `Verbatim` is a constraint or covergroup body — no symbol is
// bound for its name and nothing inside it is scanned, the same
// contract macro invocations have.
// A macro invocation standing as an item may declare names this
// crate never sees (`Binder::mark_macro_declarations`).
ItemKind::MacroItem(_) => self.mark_macro_declarations(scope),
ItemKind::Export(ExportDecl::Dpi(_))
| ItemKind::Directive(_)
| ItemKind::MacroItem(_)
| ItemKind::Timeunit(_)
| ItemKind::Error(_)
// A null item (`;`) declares nothing and references nothing.
@@ -212,6 +214,9 @@ impl<'a> Binder<'a> {
}
}
self.bind_param_ports(m.param_ports.iter().flatten(), inner);
if port_list_may_hide_declarations(&m.ports) {
self.mark_macro_declarations(inner);
}
match &m.ports {
// An error element — a port a tolerant parse could not read —
// declares nothing, exactly as an `ItemKind::Error` does.
@@ -568,3 +573,18 @@ fn bind_target_path(b: &BindDirective) -> Option<String> {
}
(!out.is_empty()).then_some(out)
}
/// Whether a header's port list holds an entry this crate cannot read as a
/// port: a macro invocation standing as one (`` module m (`MY_PORTS, …) ``,
/// which the parser keeps as a port spelled `` `MY_PORTS ``) or an element a
/// tolerant parse gave up on. Either may declare names this crate never sees.
fn port_list_may_hide_declarations(ports: &PortList) -> bool {
let macro_name = |name: &str| name.starts_with('`');
match ports {
PortList::Ansi(ports) => ports.iter().any(|p| p.ok().is_none_or(|p| macro_name(&p.name))),
PortList::NonAnsi(ports) => {
ports.iter().any(|p| p.ok().is_none_or(|p| macro_name(&p.name)))
}
PortList::None | PortList::Empty => false,
}
}
+24 -2
View File
@@ -113,6 +113,13 @@ pub(crate) enum Target {
/// of `mids` walks one link further — the [`Target::MemberOf`] walk, with
/// its start moved from the writing scope to the target's.
BindMember { target: String, head: String, mids: Vec<String> },
/// The **head** of a dotted path — the `tb` of `tb.dut.sig`: looked up
/// exactly like [`Target::Lexical`], but a miss is a top-level module's
/// name (IEEE 1800 §23.6: a top-level module name is the root of a
/// hierarchical name), so it is handed to the workspace's unit table as
/// [`Target::Module`] hands an instantiation's type. A local of the name
/// still wins. `docs/features/top-rooted-paths/README.md`.
PathHead,
/// The `x` of `this.x`: the enclosing class's scope only.
ThisMember,
/// The `x` of `super.x`: always the base class's business.
@@ -166,6 +173,7 @@ impl<'a> Binder<'a> {
imports: Vec::new(),
extends: None,
names: HashMap::new(),
macro_items: false,
};
Binder {
src,
@@ -183,6 +191,17 @@ impl<'a> Binder<'a> {
ScopeId(0)
}
/// Record that an unexpanded macro invocation stands in `scope` where a
/// declaration could stand — an item, a statement or block item, a port —
/// so it may declare names this crate never sees. A path head missing
/// from `scope`, or from a scope inside it, is then not proven a top
/// module (`resolve/root.rs`, top-rooted-paths QA F4 and R1).
pub(super) fn mark_macro_declarations(&mut self, scope: ScopeId) {
if let Some(s) = self.scopes.get_mut(scope.0 as usize) {
s.macro_items = true;
}
}
fn new_scope(&mut self, kind: ScopeKind, parent: ScopeId, span: TextRange) -> ScopeId {
let id = ScopeId(self.scopes.len() as u32);
self.scopes.push(Scope {
@@ -195,6 +214,7 @@ impl<'a> Binder<'a> {
imports: Vec::new(),
extends: None,
names: HashMap::new(),
macro_items: false,
});
self.scopes[parent.0 as usize].children.push(id);
id
@@ -322,14 +342,16 @@ impl<'a> Binder<'a> {
// with a head of its own already carries the right target and is left
// alone.
let target = match (&self.with_head, &self.bind_target, &target) {
(Some((head, mids)), _, Target::Lexical) => {
(Some((head, mids)), _, Target::Lexical | Target::PathHead) => {
Target::InlineConstraint { head: head.clone(), mids: mids.clone() }
}
// Same funnel, same rule, for a `bind`'s connection expressions:
// a bare name there is the target scope's before it is anything
// else. A name written with a head of its own already carries the
// right target and is left alone.
(None, Some(scope), Target::Lexical) => Target::BindScope { target: scope.clone() },
(None, Some(scope), Target::Lexical | Target::PathHead) => {
Target::BindScope { target: scope.clone() }
}
// And the same rule for a hierarchical path in one: its head is a
// name in the target's scope, so the whole spine is rooted there
// rather than in the scope the directive is written in.
+3 -1
View File
@@ -277,13 +277,15 @@ impl<'a> Binder<'a> {
| StmtKind::Continue
| StmtKind::WaitFork
| StmtKind::Directive(_)
| StmtKind::MacroStmt(_)
| StmtKind::Null
// Verbatim source: opaque to name resolution, exactly as the
// item-level `ItemKind::Verbatim` is.
| StmtKind::Verbatim(_)
| StmtKind::Error(_) => {}
StmtKind::Assertion(a) => self.bind_assertion(a, scope),
// A macro standing as a statement may be a block-item declaration
// (`Binder::mark_macro_declarations`, top-rooted-paths QA R1).
StmtKind::MacroStmt(_) => self.mark_macro_declarations(scope),
}
}
+9 -1
View File
@@ -164,7 +164,15 @@ use crate::workspace::{
/// 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;
/// 21 → 22 (2026-10-19, top-rooted-paths): no new field, but new records — a
/// dotted path whose head this file does not declare (`tb.dut.sig`, rooted at
/// a top module another file declares) records its head as a candidate for
/// the unit table and every segment after it as an external reference on the
/// hierarchical surface, where it recorded nothing. A 0.61.0 store would
/// answer find-references and the rename of `dut`'s members as though no DV
/// file's `force tb.dut.…` named them. See
/// `docs/features/top-rooted-paths/README.md`.
pub const FACTS_FORMAT: u32 = 22;
impl FileFacts {
/// These facts as one line's worth of fields, tab-separated.
+7
View File
@@ -239,6 +239,10 @@ pub enum Resolution {
/// which is a hierarchical path and reads the module's hierarchical
/// surface. Carried here rather than worked out again at lookup time
/// because only the file that wrote the path knows what its head was.
/// A path rooted at a **top module** another file declares (`tb` of
/// `tb.dut.sig`, TODO §65.4) reads the hierarchical surface too — its
/// head as well, whose bare path the index then accepts only as a module
/// or an interface.
ExternalCandidate { paths: Vec<String>, surface: Surface },
/// A use inside a class that nothing lexical binds, where the class's
/// `extends` could: `base` is the base-class path as written
@@ -420,6 +424,9 @@ pub struct Scope {
/// rules). Kept separate from `symbols` so a redeclaration is still
/// visible in the outline.
pub(crate) names: HashMap<String, SymbolId>,
/// Whether an unexpanded macro invocation stands as an item here — text
/// that may declare names this crate cannot see.
pub(crate) macro_items: bool,
}
impl Scope {
+64 -9
View File
@@ -7,6 +7,8 @@
use crate::bind::{Pending, Target};
use crate::model::{MemberSite, Resolution, Scope, ScopeId, Surface, Symbol, SymbolId, SymbolKind};
mod root;
/// Resolve one pending use against the finished scope tree.
///
/// `None` means **record no reference at all**: the targets that can arrive
@@ -21,6 +23,7 @@ pub(crate) fn resolve(scopes: &[Scope], symbols: &[Symbol], p: &Pending) -> Opti
// which symbol that is, so there is nothing to look up.
Target::Declaration(id) => Resolution::Resolved(*id),
Target::Lexical => lexical(scopes, p.scope, &p.name, false),
Target::PathHead => root::path_head(scopes, p.scope, &p.name),
Target::Type => lexical(scopes, p.scope, &p.name, true),
Target::Package => named_at_file_scope(scopes, symbols, &p.name, is_package),
// An interface is instantiated, connected and hierarchically named
@@ -222,7 +225,11 @@ fn member_of(
mids: &[String],
name: &str,
) -> Option<Resolution> {
let site = member_site(scopes, symbols, from, head, mids)?;
if head == root::ROOT && mids.is_empty() {
// `$root.tb`: the tail is the top module itself.
return Some(root::top_module(scopes, symbols, name));
}
let site = spine_site(scopes, symbols, from, head, mids, HeadMiss::TopModule)?;
member_at(scopes, symbols, site, name, mids.is_empty())
}
@@ -288,6 +295,17 @@ fn member_at(
/// keeps the two from drifting. `super` names the first hop of the `extends`
/// chain — the base's scope when this file declares it, the base's *name*
/// when it does not, which is the unit the overlay's own chase starts at.
///
/// **One difference from the resolution walk**, and only one: a head this
/// file does not declare is *not* rooted at a top-level module here
/// ([`HeadMiss::Nothing`]), where [`member_of`] roots it at one
/// ([`HeadMiss::TopModule`], TODO §65.4). A popup after `no_such_handle.` has
/// always answered nothing so the ordinary completion tiers run, and a
/// workspace unit list after every unknown head would replace them with an
/// empty one; offering a top module's members after `tb.` is a completion
/// change the language server's member list must make knowingly
/// (`docs/features/top-rooted-paths/README.md`, Handshakes). `$root.tb.` is
/// rooted in both: it says what it is.
pub(crate) fn member_site(
scopes: &[Scope],
symbols: &[Symbol],
@@ -295,7 +313,31 @@ pub(crate) fn member_site(
head: &str,
mids: &[String],
) -> Option<MemberSite> {
let mut here = head_site(scopes, symbols, from, head)?;
spine_site(scopes, symbols, from, head, mids, HeadMiss::Nothing)
}
/// What a spine's head that this file does not declare roots the spine at.
#[derive(Clone, Copy)]
enum HeadMiss {
/// Nothing: the spine stops (the completion walk).
Nothing,
/// The top-level module of that name (the resolution walk).
TopModule,
}
/// [`member_site`]'s walk, with what a head miss means said by the caller.
fn spine_site(
scopes: &[Scope],
symbols: &[Symbol],
from: ScopeId,
head: &str,
mids: &[String],
miss: HeadMiss,
) -> Option<MemberSite> {
let (mut here, mids) = match (head, mids.split_first()) {
(root::ROOT, Some((top, rest))) => (root::top_site(scopes, symbols, top), rest),
_ => (head_site(scopes, symbols, from, head, miss)?, mids),
};
for mid in mids {
here = descend(scopes, symbols, here, mid)?;
}
@@ -338,6 +380,7 @@ fn head_site(
symbols: &[Symbol],
from: ScopeId,
head: &str,
miss: HeadMiss,
) -> Option<MemberSite> {
match head {
// Neither is a name this crate binds, so neither goes through
@@ -354,12 +397,22 @@ fn head_site(
}),
}
}
_ => {
let Resolution::Resolved(id) = lexical(scopes, from, head, false) else {
return None;
};
link_type(scopes, symbols, id)
}
// `$root` alone, a system name, a macro: no unit to root a path at.
_ if head.starts_with(['$', '`']) => None,
_ => match lexical(scopes, from, head, false) {
Resolution::Resolved(id) => link_type(scopes, symbols, id),
// A plain miss where nothing unseen could declare the name is a
// top-level module's name — the very rule `Target::PathHead`
// applies to the head's own reference (`root::roots_at_top`), so
// the head and the segments after it agree. Anything else is
// doubt, and doubt roots nothing.
Resolution::NotFound
if matches!(miss, HeadMiss::TopModule) && root::roots_at_top(scopes, from) =>
{
Some(root::unit_root(head))
}
_ => None,
},
}
}
@@ -684,7 +737,9 @@ fn last_segment(path: &str) -> &str {
/// in a *value* position: a name a `` `define`` would have produced, a typo, a
/// signal declared somewhere this crate does not model. Nothing about it says
/// "file-scope declaration", so it is not swept through the unit table, where a
/// mere name collision would make `rename` rewrite an unrelated file.
/// mere name collision would make `rename` rewrite an unrelated file. The one
/// value position that does say it is the head of a dotted path, which is
/// [`Target::PathHead`]'s and `root::path_head`'s, not this function's.
fn lexical(scopes: &[Scope], from: ScopeId, name: &str, promote: bool) -> Resolution {
let mut external = Vec::new();
let mut current = Some(from);
+85
View File
@@ -0,0 +1,85 @@
//! A hierarchical path rooted at a **top-level module** (IEEE 1800 §23.6: a
//! top-level module name is the root of a hierarchical name) — `tb.dut.sig`
//! written in a file that does not declare `tb`, and `$root.tb.dut.sig`.
//!
//! The head's own reference ([`path_head`]) and the walk the segments after it
//! take ([`unit_root`], via `head_site`) fall back to the same unit, so `tb`
//! and `tb.dut` cannot name different modules.
//!
//! **A path is rooted only when this file shows the head can be nothing but a
//! top-level module** ([`roots_at_top`]); in doubt it is not, and the path
//! stays unresolved and warned about, as before §65.4. A local of the name
//! wins (the LRM's upward search finds it first); so does a name an import
//! could supply, whether or not the workspace can say it does; and a head
//! written inside a class, or where an unexpanded macro stands as an item,
//! may be a name this crate never sees. `docs/features/top-rooted-paths/README.md`.
use crate::model::{MemberSite, Resolution, Scope, ScopeId, ScopeKind, Surface, Symbol};
use super::{file_symbol, is_instantiable, lexical, owning_scope};
/// The system name that spells the root of the design hierarchy.
pub(super) const ROOT: &str = "$root";
/// The head of a dotted path: the lexical answer, and on a plain miss that
/// [`roots_at_top`] allows, the top-level module of that name. An import
/// candidate stays exactly what `lexical` said (the imported name is the
/// head, by the LRM), and so does every other answer.
pub(super) fn path_head(scopes: &[Scope], from: ScopeId, name: &str) -> Resolution {
match lexical(scopes, from, name, false) {
Resolution::NotFound if roots_at_top(scopes, from) => top_candidate(name),
found => found,
}
}
/// Whether a head missing from the lexical chain of `from` may be taken for a
/// top-level module: no scope on the chain, up to the file, is a class (a
/// class member, inherited or macro-declared, is never a path into the design
/// hierarchy lucisv could prove) or holds an unexpanded macro invocation as
/// an item (it may declare the very name).
pub(super) fn roots_at_top(scopes: &[Scope], from: ScopeId) -> bool {
let mut current = Some(from);
while let Some(id) = current {
let Some(scope) = scopes.get(id.0 as usize) else { return false };
if scope.kind == ScopeKind::Class || scope.macro_items {
return false;
}
current = scope.parent;
}
true
}
/// Where a path whose head this file does not declare is rooted: the
/// workspace unit of that name, read on its hierarchical surface — the
/// surface an instance path reads, because the segments after a root are the
/// same kind of names (`tb.dut` is an instance of `tb`).
pub(super) fn unit_root(head: &str) -> MemberSite {
MemberSite::Unit { path: head.to_string(), surface: Surface::Hierarchical }
}
/// The `tb` of `$root.tb.…` as a site: the module this file declares at file
/// scope, else the workspace unit. `$root` skips the lexical walk entirely —
/// that is what it is for.
pub(super) fn top_site(scopes: &[Scope], symbols: &[Symbol], top: &str) -> MemberSite {
match owning_scope(scopes, symbols, top, is_instantiable) {
Some(scope) => MemberSite::Scope(scope),
None => unit_root(top),
}
}
/// The `tb` of `$root.tb` as a reference: the file-scope module this file
/// declares, else a candidate for the workspace's unit table.
pub(super) fn top_module(scopes: &[Scope], symbols: &[Symbol], top: &str) -> Resolution {
match file_symbol(scopes, symbols, top, is_instantiable) {
Some(id) => Resolution::Resolved(id),
None => top_candidate(top),
}
}
/// The bare name on the hierarchical surface — which is also what tells the
/// workspace layer to accept only a module or an interface for it
/// (`external::follow_one`): a package or class sharing a top module's name
/// is not a root a `.` can follow.
fn top_candidate(name: &str) -> Resolution {
Resolution::ExternalCandidate { paths: vec![name.to_string()], surface: Surface::Hierarchical }
}
+46 -1
View File
@@ -246,15 +246,46 @@ pub(super) fn base_chain<'i>(index: &'i WorkspaceIndex, unit: &str) -> Vec<&'i s
///
/// The same fold [`follow_one`] runs before its own lookup — shared, so a
/// list and a lookup of the same path cannot land in different units.
///
/// On the **hierarchical** surface every unit the fold stands in is checked
/// ([`design_unit`]): a path through the design hierarchy starts at a module
/// or an interface and never passes through a package, so a package sharing a
/// module's name cannot lend the path its members (top-rooted-paths QA F1).
pub(super) fn fold_path(index: &WorkspaceIndex, path: &str, surface: Surface) -> Option<String> {
let mut segments = path.split("::");
let mut unit = segments.next()?.to_string();
let hierarchical = surface == Surface::Hierarchical;
if hierarchical && !design_unit(index, &unit, true) {
return None;
}
for segment in segments {
unit = index.member_unit_in(&unit, segment, surface)?;
if hierarchical && !design_unit(index, &unit, false) {
return None;
}
}
Some(unit)
}
/// Whether a hierarchical path may stand in `unit`. Its **first** unit must be
/// declared, and only as modules or interfaces — the type of an instance, the
/// target of a `bind`, or the top module a path is rooted at. A **later** unit
/// (an instance's type, a block's synthesized key, a struct or class type a
/// variable is declared with) may be any kind, but not a module and something
/// else at once: the member table is keyed by name, so such a name's members
/// are the two declarations' merged — which is how a package sharing a
/// module's name would reach a later hop. A later unit that is *only* a
/// package would need a declaration typed with a package's name, which is
/// not code; no separate rule is kept for it (QA M7).
fn design_unit(index: &WorkspaceIndex, unit: &str, first: bool) -> bool {
let defs = index.units(unit);
let modules = defs.iter().filter(|def| def.kind.is_instantiable()).count();
if first {
return !defs.is_empty() && modules == defs.len();
}
modules == 0 || modules == defs.len()
}
/// The type a file-scope `typedef` names, when the workspace declares the name
/// exactly once and as a typedef. Two declarations of the name are two
/// answers, and this layer picks between candidates nowhere else either.
@@ -327,7 +358,7 @@ fn follow_one<'i>(
}
if segments.len() < 2 {
return if path == name {
index.units(name)
root_units(index.units(name), surface)
} else {
member_chain(index, path, name, surface)
};
@@ -342,6 +373,20 @@ fn follow_one<'i>(
member_chain(index, &unit, name, surface)
}
/// The units a bare name answers with. On the connection surface — an
/// instantiation's type, an imported package, a type name — every unit of the
/// name, as always. On the **hierarchical** surface the name is the root of a
/// path (`tb` of `tb.dut.sig`, TODO §65.4), which only a module or an
/// interface can be: units of any other kind answer nothing, and so does a
/// name some file declares as a module and another as something else, rather
/// than an answer with the stranger left in or quietly dropped.
fn root_units(units: &[Def], surface: Surface) -> &[Def] {
match surface {
Surface::Hierarchical if !units.iter().all(|def| def.kind.is_instantiable()) => &[],
_ => units,
}
}
impl ExternalResolutions {
/// The answer for one reference, or `None` if it was not an external
/// candidate.
@@ -27,6 +27,7 @@
mod external;
mod hierarchy;
mod index;
mod path_units;
mod record;
mod reexport;
mod update;
@@ -0,0 +1,72 @@
//! The design units a hierarchical path to a declaration walks through —
//! what a caller handing the refactoring engine a *subset* of the workspace
//! must include for that path to resolve inside the subset as it does in the
//! whole (top-rooted-paths QA F3).
//!
//! `tb.dut.u_core.sig` in a DV file names `sig` through `tb` (the top module
//! it is rooted at), `dut_a` (the type of `tb.dut`) and `core` (the type of
//! `u_core`). The index resolved it, so the use is in `sig`'s postings; but a
//! rename handed only `sig`'s declaring file and that DV file cannot resolve
//! the root, and would leave the path behind. The answer is read off the
//! records the index already holds: no file is read.
use std::collections::{BTreeSet, HashMap, HashSet};
use crate::model::Surface;
use super::record::ReferenceFact;
use super::{Def, FileId, WorkspaceIndex};
impl WorkspaceIndex {
/// Every unit an indexed use of `def` written as a hierarchical path
/// passes through before its last segment: the path's first unit (an
/// instance's type, a `bind` target, a top module) and the unit of each
/// hop after it. Empty when no use of `def` is such a path.
pub fn path_units_to(&self, def: &Def) -> BTreeSet<String> {
let mut by_file: HashMap<FileId, HashSet<(u32, u32)>> = HashMap::new();
for site in self.references_to(def) {
let span = (site.name_span.start, site.name_span.end);
by_file.entry(site.file).or_default().insert(span);
}
let mut out = BTreeSet::new();
for (file, spans) in by_file {
let Some(facts) = self.facts.get(file.0 as usize) else { continue };
for fact in &facts.references {
let ReferenceFact::External {
paths,
surface: Surface::Hierarchical,
occurrence,
..
} = fact
else {
continue;
};
if spans.contains(&(occurrence.start, occurrence.end)) {
for path in paths {
self.collect_hops(path, &mut out);
}
}
}
}
out
}
/// The units `path`'s segments before its last stand in, folded as
/// `external::fold_path` folds them, as far as the fold goes.
fn collect_hops(&self, path: &str, out: &mut BTreeSet<String>) {
let mut segments: Vec<&str> = path.split("::").collect();
segments.pop();
let Some((first, hops)) = segments.split_first() else { return };
let mut unit = first.to_string();
out.insert(unit.clone());
for hop in hops {
match self.member_unit_in(&unit, hop, Surface::Hierarchical) {
Some(next) => {
unit = next;
out.insert(unit.clone());
}
None => return,
}
}
}
}
+14 -2
View File
@@ -229,8 +229,20 @@ fn a_block_and_its_members_are_hierarchical_only_under_the_dotted_key() {
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());
// Nothing here declares `genblk1`, so — as the head of a dotted path — it
// can only be a top-level module some other file declares (TODO §65.4),
// and `w` a member of that module: candidates for the workspace, which
// holds no such module. Never this file's unnamed block.
let top = Resolution::ExternalCandidate {
paths: vec!["genblk1".to_string()],
surface: Surface::Hierarchical,
};
assert_eq!(resolution(&s, at(src, "genblk1", 0, 0)), top);
let member = Resolution::ExternalCandidate {
paths: vec!["genblk1::w".to_string()],
surface: Surface::Hierarchical,
};
assert_eq!(resolution(&s, at(src, "genblk1.w", 0, 8)), member);
assert!(s.symbols_named("genblk1").next().is_none(), "no symbol is invented for it");
}
+11 -1
View File
@@ -196,11 +196,21 @@ endmodule
let s = sem(src);
for (spelling, why) in [
("x.bit_field", "a built-in type names no declaration"),
("stranger.thing", "the head is not declared here"),
("h.absent", "the class is known whole and has no such member"),
] {
assert!(s.reference_at(tail(src, spelling, 0)).is_none(), "{spelling}: {why}");
}
// `stranger.thing` was on the list above until TODO §65.4: a head nothing
// here declares is the root of a hierarchical name — a top-level module
// another file declares (IEEE 1800 §23.6) — so its tail is a candidate
// for the workspace (`docs/features/top-rooted-paths/README.md`).
assert_eq!(
resolution_at(&s, tail(src, "stranger.thing", 0)),
Resolution::ExternalCandidate {
paths: vec!["stranger::thing".to_string()],
surface: vlog_semantic::Surface::Hierarchical,
}
);
// The one that does resolve, so the test is not vacuous.
assert_eq!(
resolution_at(&s, tail(src, "h.known", 0)),
@@ -0,0 +1,338 @@
//! Hierarchical paths rooted at a top-level module (TODO §65.4, IEEE 1800
//! §23.6): `tb.dut.g_sw[0].buf_q` written in a file that does not declare
//! `tb`, and `$root.tb.…`. The head is a candidate for the workspace's unit
//! table, every segment after it a candidate on the hierarchical surface of
//! the unit before it — and a local of the head's name still wins.
//! `docs/features/top-rooted-paths/README.md`.
use std::path::PathBuf;
use vlog_parser::parse_source_tolerant;
use vlog_semantic::{
analyze, resolve_external, ExternalTarget, MemberSite, Resolution, Semantics, Surface,
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 candidate(paths: &[&str]) -> Resolution {
Resolution::ExternalCandidate {
paths: paths.iter().map(|p| p.to_string()).collect(),
surface: Surface::Hierarchical,
}
}
const DUT: &str = "module dut_a;
for (genvar i = 0; i < 2; i++) begin : g_sw
logic buf_q;
end
endmodule
";
const TB: &str = "module tb;
dut_a dut ();
endmodule
";
const PROBE: &str = "module probe (output logic o);
assign o = tb.dut.g_sw[0].buf_q;
endmodule
";
fn index(extra: &[(&str, &str)]) -> WorkspaceIndex {
let mut files = vec![("dut_a.sv", DUT), ("tb.sv", TB), ("probe.sv", PROBE)];
files.extend_from_slice(extra);
WorkspaceIndex::build(files.into_iter().map(|(n, t)| (PathBuf::from("/rtl").join(n), t)))
}
/// What the workspace answers for the reference at `offset`: the kind and
/// name of the one declaration, or a description of a non-answer.
fn external(s: &Semantics, ws: &WorkspaceIndex, offset: u32) -> String {
let id = s.reference_id_at(offset).expect("a reference there");
match resolve_external(s, ws).get(id) {
Some(ExternalTarget::Resolved(def)) => format!("{:?}", def.kind),
Some(ExternalTarget::Ambiguous(defs)) => format!("ambiguous {}", defs.len()),
Some(ExternalTarget::StillUnresolved) => "unresolved".to_string(),
None => "not a candidate".to_string(),
}
}
#[test]
fn the_head_and_every_segment_are_candidates_rooted_at_the_head() {
let s = sem(PROBE);
assert_eq!(resolution(&s, at(PROBE, "tb.", 0, 0)), candidate(&["tb"]));
assert_eq!(resolution(&s, at(PROBE, "dut.", 0, 0)), candidate(&["tb::dut"]));
assert_eq!(resolution(&s, at(PROBE, "g_sw", 0, 0)), candidate(&["tb::dut::g_sw"]));
assert_eq!(resolution(&s, at(PROBE, "buf_q", 0, 0)), candidate(&["tb::dut::g_sw::buf_q"]));
}
#[test]
fn the_workspace_walks_the_path_from_the_top_module() {
let (ws, s) = (index(&[]), sem(PROBE));
assert_eq!(external(&s, &ws, at(PROBE, "tb.", 0, 0)), "Module");
assert_eq!(external(&s, &ws, at(PROBE, "dut.", 0, 0)), "Instance");
assert_eq!(external(&s, &ws, at(PROBE, "g_sw", 0, 0)), "Block");
assert_eq!(external(&s, &ws, at(PROBE, "buf_q", 0, 0)), "Var");
}
#[test]
fn a_root_the_workspace_does_not_declare_stays_unresolved() {
let ws = WorkspaceIndex::build(
[("dut_a.sv", DUT), ("probe.sv", PROBE)]
.into_iter()
.map(|(n, t)| (PathBuf::from("/rtl").join(n), t)),
);
let s = sem(PROBE);
assert_eq!(external(&s, &ws, at(PROBE, "tb.", 0, 0)), "unresolved");
assert_eq!(external(&s, &ws, at(PROBE, "g_sw", 0, 0)), "unresolved");
assert_eq!(external(&s, &ws, at(PROBE, "buf_q", 0, 0)), "unresolved");
}
/// Seventy opentitan testbenches are each `module tb`: `tb.dut` then names
/// as many instances, and nothing after it can be told apart.
#[test]
fn two_top_modules_of_one_name_leave_the_path_unresolved() {
let other_tb = "module tb;\n dut_b dut ();\nendmodule\n";
let ws = index(&[("tb2.sv", other_tb)]);
let s = sem(PROBE);
assert_eq!(external(&s, &ws, at(PROBE, "tb.", 0, 0)), "ambiguous 2");
assert_eq!(external(&s, &ws, at(PROBE, "dut.", 0, 0)), "ambiguous 2");
assert_eq!(external(&s, &ws, at(PROBE, "g_sw", 0, 0)), "unresolved");
}
/// A package or class is not a root a `.` can follow, and a name declared as
/// a module in one file and a package in another is no root either.
#[test]
fn only_a_module_or_an_interface_is_a_root() {
let pkg = "package tb;\n logic dut;\nendpackage\n";
let ws = WorkspaceIndex::build(
[("dut_a.sv", DUT), ("tb_pkg.sv", pkg), ("probe.sv", PROBE)]
.into_iter()
.map(|(n, t)| (PathBuf::from("/rtl").join(n), t)),
);
let s = sem(PROBE);
assert_eq!(external(&s, &ws, at(PROBE, "tb.", 0, 0)), "unresolved");
let ws = index(&[("tb_pkg.sv", pkg)]);
assert_eq!(external(&s, &ws, at(PROBE, "tb.", 0, 0)), "unresolved", "module and package");
let iface = "interface tb;\n dut_a dut ();\nendinterface\n";
let ws = WorkspaceIndex::build(
[("dut_a.sv", DUT), ("tb_if.sv", iface), ("probe.sv", PROBE)]
.into_iter()
.map(|(n, t)| (PathBuf::from("/rtl").join(n), t)),
);
assert_eq!(external(&s, &ws, at(PROBE, "tb.", 0, 0)), "Interface");
assert_eq!(external(&s, &ws, at(PROBE, "buf_q", 0, 0)), "Var");
}
/// The LRM's upward name resolution finds a local first: a `logic tb` makes
/// `tb.dut` a select of a net this crate models no members of, and an
/// instance named `tb` roots the path in *its* module.
#[test]
fn a_local_of_the_heads_name_wins() {
let net = "module probe (output logic o);\n logic tb;\n assign o = tb.dut.g_sw[0].buf_q;\nendmodule\n";
let s = sem(net);
let local = s.symbol_at(at(net, "logic tb", 0, 6)).expect("the net");
assert_eq!(resolution(&s, at(net, "tb.", 0, 0)), Resolution::Resolved(local));
assert!(s.reference_at(at(net, "dut.", 0, 0)).is_none(), "a net has no members");
let inst =
"module probe (output logic o);\n other tb ();\n assign o = tb.dut.x;\nendmodule\n";
let s = sem(inst);
let local = s.symbol_at(at(inst, "other tb", 0, 6)).expect("the instance");
assert_eq!(resolution(&s, at(inst, "tb.", 0, 0)), Resolution::Resolved(local));
assert_eq!(resolution(&s, at(inst, "dut.", 0, 0)), candidate(&["other::dut"]));
}
/// A module this file declares is found lexically, as it always was.
#[test]
fn a_top_module_declared_in_the_same_file_resolves_in_the_file() {
let src = "module tb;\n logic sig;\nendmodule\nmodule probe (output logic o);\n assign o = tb.sig;\nendmodule\n";
let s = sem(src);
let tb = s.symbol_at(at(src, "module tb", 0, 7)).expect("tb");
let sig = s.symbol_at(at(src, "logic sig", 0, 6)).expect("sig");
assert_eq!(resolution(&s, at(src, "tb.sig", 0, 0)), Resolution::Resolved(tb));
assert_eq!(resolution(&s, at(src, "tb.sig", 0, 3)), Resolution::Resolved(sig));
}
/// QA F2: an import that could supply the head makes it the imported name
/// (a local, by the LRM) whether or not the workspace can say so — doubt, so
/// nothing is rooted: the head keeps the import's candidate and no segment
/// after it is a reference.
#[test]
fn an_import_in_scope_wins_and_roots_nothing() {
let src = "module probe (output logic o);\n import p::*;\n assign o = tb.dut.x;\nendmodule\n";
let s = sem(src);
let imported = Resolution::ExternalCandidate {
paths: vec!["p::*".to_string()],
surface: Surface::Connection,
};
assert_eq!(resolution(&s, at(src, "tb.", 0, 0)), imported);
assert!(s.reference_at(at(src, "dut.", 0, 0)).is_none());
}
/// QA F4: a head written inside a class (any class: a member, inherited or
/// macro-declared, is never a path lucisv can prove), or in a scope where an
/// unexpanded macro stands as an item, roots nothing.
#[test]
fn a_head_inside_a_class_or_beside_a_macro_item_roots_nothing() {
for (src, head) in [
// A11: a class with no base, `cfg` declared by a macro.
("class env;\n `DECLARE_CFG\n task run(); if (cfg.en) $display(\"x\"); endtask\nendclass\n", "cfg."),
// D2: a class in a package writing a hierarchical path (illegal).
("package env_pkg;\n class seq;\n task body(); tb.dut.x = 1; endtask\n endclass\nendpackage\n", "tb."),
// A12: a module whose `st` comes from a macro.
("module user (output logic o);\n `DECL_STRUCT(st)\n assign o = st.a;\nendmodule\n", "st."),
// The macro one scope out still casts its doubt inward.
("module user (output logic o);\n `DECL_STRUCT(st)\n initial begin : b\n o = st.a;\n end\nendmodule\n", "st."),
] {
let s = sem(src);
assert_eq!(resolution(&s, at(src, head, 0, 0)), Resolution::NotFound, "{src}");
let tail = at(src, head, 0, head.len());
assert!(s.reference_at(tail).is_none(), "{src}");
}
}
/// QA F1: a package sharing the root's name lends the path nothing — neither
/// the head nor any segment after it answers — and a package alone is never
/// a root (`pk.x` is illegal).
#[test]
fn a_package_never_lends_a_top_rooted_path_its_members() {
let pkg = "package tb;\n logic dut;\nendpackage\n";
let other = "module other;\n initial force tb.dut.x = 0;\nendmodule\n";
let dut = "module dut_a;\n logic x;\nendmodule\n";
let both = WorkspaceIndex::build(
[("dut_a.sv", dut), ("tb.sv", TB), ("tb_pkg.sv", pkg), ("other.sv", other)]
.into_iter()
.map(|(n, t)| (PathBuf::from("/rtl").join(n), t)),
);
let s = sem(other);
for needle in ["tb.", "dut.", ".x"] {
let skip = usize::from(needle.starts_with('.'));
assert_eq!(external(&s, &both, at(other, needle, 0, skip)), "unresolved", "{needle}");
}
let user = "module user (output logic o);\n assign o = pk.x;\nendmodule\n";
let only = WorkspaceIndex::build(
[("pk.sv", "package pk;\n logic x;\nendpackage\n"), ("user.sv", user)]
.into_iter()
.map(|(n, t)| (PathBuf::from("/rtl").join(n), t)),
);
let s = sem(user);
assert_eq!(external(&s, &only, at(user, "pk.", 0, 0)), "unresolved");
assert_eq!(external(&s, &only, at(user, ".x", 0, 1)), "unresolved");
}
/// Inside an extending class the base could supply the head, so it stays the
/// base's candidate and no path is rooted at a module.
#[test]
fn inside_an_extending_class_the_head_is_the_bases() {
let src = "class c extends base;\n function void f();\n cfg.dut.x = 1;\n endfunction\nendclass\n";
let s = sem(src);
assert!(matches!(resolution(&s, at(src, "cfg.", 0, 0)), Resolution::InheritedCandidate { .. }));
assert!(s.reference_at(at(src, "dut.", 0, 0)).is_none());
}
#[test]
fn dollar_root_names_the_top_module_and_skips_the_lexical_walk() {
let src = "module probe (output logic o);\n logic tb;\n assign o = $root.tb.dut.g_sw[0].buf_q;\nendmodule\n";
let s = sem(src);
// The local `tb` is not what `$root.tb` names.
assert_eq!(resolution(&s, at(src, "tb.dut", 0, 0)), candidate(&["tb"]));
assert_eq!(resolution(&s, at(src, "dut.", 0, 0)), candidate(&["tb::dut"]));
assert_eq!(resolution(&s, at(src, "buf_q", 0, 0)), candidate(&["tb::dut::g_sw::buf_q"]));
let ws = WorkspaceIndex::build(
[("dut_a.sv", DUT), ("tb.sv", TB), ("p.sv", src)]
.into_iter()
.map(|(n, t)| (PathBuf::from("/rtl").join(n), t)),
);
assert_eq!(external(&s, &ws, at(src, "tb.dut", 0, 0)), "Module");
assert_eq!(external(&s, &ws, at(src, "buf_q", 0, 0)), "Var");
}
#[test]
fn dollar_root_reaches_a_top_module_this_file_declares() {
let src = "module tb;\n logic sig;\nendmodule\nmodule probe (output logic o);\n logic tb;\n assign o = $root.tb.sig;\nendmodule\n";
let s = sem(src);
let tb = s.symbol_at(at(src, "module tb", 0, 7)).expect("tb");
let sig = s.symbol_at(at(src, "logic sig", 0, 6)).expect("sig");
assert_eq!(resolution(&s, at(src, "tb.sig", 0, 0)), Resolution::Resolved(tb));
assert_eq!(resolution(&s, at(src, "tb.sig", 0, 3)), Resolution::Resolved(sig));
}
/// The completion walk (`Semantics::member_site`) does not root an unknown
/// head at a top module — a popup after an unknown head answers nothing, so
/// the ordinary tiers run, until the language server's member list takes the
/// change knowingly (README, Handshakes). `$root.tb.` says what it is and is
/// rooted in both walks.
#[test]
fn the_completion_walk_roots_only_an_explicit_dollar_root() {
let s = sem(PROBE);
let scope = s.reference_at(at(PROBE, "tb.", 0, 0)).expect("tb").scope;
assert_eq!(s.member_site(scope, "tb", &["dut".to_string()]), None);
let rooted = s.member_site(scope, "$root", &["tb".to_string(), "dut".to_string()]);
assert_eq!(
rooted,
Some(MemberSite::Unit { path: "tb::dut".to_string(), surface: Surface::Hierarchical })
);
assert_eq!(s.member_site(scope, "$root", &[]), None);
assert_eq!(s.member_site(scope, "`MACRO", &[]), None);
}
#[test]
fn a_system_name_or_a_macro_roots_nothing() {
let src = "module probe (output logic o);\n assign o = `TOP.dut.x;\n assign o = $unit.x;\nendmodule\n";
let s = sem(src);
assert!(s.reference_at(at(src, "dut.", 0, 0)).is_none());
assert!(s.reference_at(at(src, ".x;", 1, 1)).is_none());
}
/// QA R1: a macro standing where a declaration could stand — a statement in
/// a `begin`/`end`, a task or a function body, or an entry of the port list —
/// may declare the head, so nothing is rooted from that scope (or one inside
/// it).
#[test]
fn a_macro_where_a_declaration_could_stand_roots_nothing() {
for src in [
// E1
"module user;\n initial begin\n `DECL_LOCAL(st)\n st.a = 1;\n end\nendmodule\n",
// E2
"module user;\n task automatic t();\n `DECL_LOCAL(st)\n st.a = 1;\n endtask\nendmodule\n",
// E6
"module user;\n function automatic void f();\n `DECL_LOCAL(st)\n begin st.a = 1; end\n endfunction\nendmodule\n",
// E3, the parse is tolerant of the macro port
"module user (`MY_PORTS, output logic o);\n assign o = st.a;\nendmodule\n",
// E3, the macro after a port
"module user (input logic i, `MY_PORTS);\n initial st.a = i;\nendmodule\n",
] {
let s = sem(src);
let head = at(src, "st.a", 0, 0);
assert!(
matches!(s.reference_at(head).map(|r| &r.resolution), Some(Resolution::NotFound) | None),
"{src}"
);
assert!(s.reference_at(at(src, "st.a", 0, 3)).is_none(), "{src}");
}
}
/// …and the shapes that cannot declare the head keep rooting: a macro used
/// as a data type, and a macro in a *sibling* generate block (E7, E8).
#[test]
fn a_macro_that_cannot_declare_the_head_still_roots() {
for src in [
"module user;\n `MY_STRUCT_T other;\n initial st.a = 1;\nendmodule\n",
"module user;\n if (1) begin : g1\n `DECL_LOCAL(st)\n end\n if (1) begin : g2\n initial st.a = 1;\n end\nendmodule\n",
"module user;\n initial st.a = $bits(`WIDTH);\nendmodule\n",
] {
let s = sem(src);
assert_eq!(resolution(&s, at(src, "st.a", 0, 0)), candidate(&["st"]), "{src}");
assert_eq!(resolution(&s, at(src, "st.a", 0, 3)), candidate(&["st::a"]), "{src}");
}
}
+5
View File
@@ -364,6 +364,11 @@ is a leaf, as it was for fences.
## Status / TODO
- Editors' "Format Selection" no longer uses this engine: since TODO §66.2
the LSP range requests call `format_selection`, which lays out the smallest
sibling run in place — see `docs/features/selection-formatting/README.md`.
The CLI's `--lines` still runs here, unchanged.
- [x] `range.rs`: `LineRanges` (`parse`/`new`, sorted+merged, reversed and
zero refused, past-EOF clamped) with unit tests for every spelling.
- [x] `range.rs`: `Pick`/`Selection`/`Plan`/`Split`, the `Planner` walk in
@@ -0,0 +1,140 @@
# references-fanout-pd-main
## Goal
TODO §65.2 (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 answered 11 and 9 locations, while the whole-set engine
(`vlog_refactor::find_references` over every file, as `lucisv-mcp`'s
`references` runs it) answered 14 and 12 — the same plus the three generated
tops `hw/top_{earlgrey,darjeeling,englishbreakfast}/rtl/autogen/*_pd_main.sv`.
Find the cause, fix it at the cause, and pin the answer.
## Root cause
**It is the index scope, not the fan-out.** The language server runs on the
shipped default `lucisv.index.scope: "folder"` with `scopeDepth: 2`
(`settings.rs` `DEFAULT_SCOPE_DEPTH`, ladder in `state/scope.rs`). Opening
`hw/ip/aes/dv/tb/tb.sv` raises its folder two levels to **`hw/ip/aes`**, and
that is the whole index: the three `*_pd_main.sv` tops are never walked, so
no index table (units, instantiations, reference postings, words) knows them.
`lucisv-mcp` hands the engine every file under the root, which is the
`"workspace"` rung's set. The two answers are over different file sets; over
the same set they are identical.
This is the documented behaviour of `docs/features/index-scope` ("cross-file
answers are scope-relative … `find_references` and a workspace rename all
answer within the active scope"; migration line `"lucisv.index.scope":
"workspace"`), chosen 2026-08-27/28 for scan cost.
Evidence (release `lucisv-server` built at ec492cd, LSP client driving it over
stdio, root `ot/hw`, `tb.sv` opened, positions `45:3` `aes` and `50:6`
`clk_i`, after the scan's progress end plus 5 s):
| scope | `aes` | `.clk_i` | files listed |
|---|---|---|---|
| default (`folder`, depth 2) | 11 | 9 | all under `hw/ip/aes/` |
| `index.scope: "workspace"` | **14** | **12** | the 11/9 + `darjeeling_pd_main.sv:1521/1538`, `earlgrey_pd_main.sv:2069/2086`, `englishbreakfast_pd_main.sv:933/950` |
The workspace-scope answer is exactly MCP-6's 14/12 list. Ruled out, as the
lead's pre-investigation suggested: the 1 MiB size cap (the tops are
62–141 kB and are indexed under the workspace scope), `.gitignore`/the walk
(`autogen` is walked under the workspace scope), and the multi-line
`aes #( … ) u_aes (` shape (indexed and answered under the workspace scope).
`state/sources.rs` (`module_sources`, `rename_sources_traced`, `fan_out_of`)
and `nav.rs`'s indexed-references path are correct: within the scope they
equal the engine over `Workspace::sources()`.
**Rename has the same scope relation and no gap of its own.** Probe over the
same checkout: a rename of `aes` from `tb.sv:45` edits 14 sites in 9 files
under the workspace scope (the three tops included) and 11 sites in 6 files
under the folder scope. The latter is the sharper consequence: under the
default scope a module rename from the testbench would leave the three tops
instantiating a module that no longer exists. That is the index-scope
README's stated trade-off, but it is a correctness hazard for a write, not
only an incomplete read — flagged for the lead below.
## Assumptions
- "The whole-set engine" means `vlog_refactor::find_references` over every
file the client's root holds, as `lucisv-mcp` runs it; the server's answer
is compared to it over the same file set.
- The folder scope's documented behaviour stands until the lead rules
(Handshakes); nothing in this lane changes which files are indexed.
## Handshakes
- **Ruling request → lead (the fix is outside this lane's files).** The
cause is the shipped default scope, which lives in
`crates/lucisv_server/src/settings.rs` (`IndexScope::default`,
`DEFAULT_SCOPE_DEPTH`) and `state/scope.rs`, and is a product decision
recorded in `docs/features/index-scope`. Not edited. Options:
1. **Keep the design; close §65.2 as scope-relative by design.** The tests
below pin both halves. Optionally document it where users meet it (the
VS Code setting's description, the README's LSP section).
2. **Widen only for writes.** A cross-file rename (and port refactorings)
on a unit whose instantiations may exist outside the folder scope runs
against the workspace walk, or refuses with "outside the index scope —
set `lucisv.index.scope: workspace`". Closes the hazard above without
changing read latency. Touches `state/sources.rs` (`fan_out_of` /
`rename_sources_traced`) and the rename handler.
3. **Change the default to `"workspace"` when the client has roots.**
Restores pre-2026-08-27 behaviour; costs the full scan the index-scope
round removed (opentitan: ~4 000 files; the persistent cache and the
interleaved scan now bound it). `settings.rs`, the index-scope README,
release notes.
- Consumed, unchanged: `Workspace::sources()`, `WorkspaceIndex::files()`,
`vlog_refactor::find_references`. No handshake changed.
## Status / TODO
- [x] Reproduce at the LSP level (11/9 default scope; 14/12 workspace scope)
- [x] Root cause named: the folder index scope (`hw/ip/aes`), not the fan-out
- [x] Rename's fan-out checked: same scope relation, no separate gap
- [x] Fixture regression tests (`server/tests/references_scope.rs`, 3 tests)
- [x] Ignored opentitan test (`tests/opentitan_references.rs`, 2 tests)
- [ ] Fix — pending the lead's ruling (Handshakes); no code fix was needed in
`sources.rs`/`nav.rs`
- [ ] QA
## Work log
- **2026-10-19 (dev).** Fast-forwarded the lane worktree from 75d2d37 to the
wave's base ec492cd (TODO-only commit). Built release `lucisv-server` and
drove it with a scratch stdio LSP client: default scope 11/9, all locations
under `hw/ip/aes/`; `index.scope: "workspace"` 14/12, exactly MCP-6's list.
So the gap is the scope, and the fan-out code is correct — nothing in
`sources.rs` or `nav.rs` changed. Rename probe: 9 files/14 edits (workspace)
vs 6 files/11 edits (folder) for `aes`; the `.clk_i` rename under the
workspace scope refuses over an unrelated implicit `.clk_i` binding in
`hw/ip/keymgr_dpe/dv/tb.sv` (the existing safety refusal), under the folder
scope it edits 16 sites in 6 files.
Tests: `server/tests/references_scope.rs` — opentitan's shape in miniature
(`ip/blk/rtl/blk.sv`, `ip/blk/dv/tb/tb.sv`, `top/rtl/autogen/top_pd_main.sv`
with a multi-line `blk #( … ) u_blk (`): (1) whole workspace: LSP ==
engine over every file, for the module name and `clk_i`, each from its
declaration and from a use, and the top is listed; (2) folder scope: the top
is not in the index, LSP == engine over `Workspace::sources()` at the same
four positions, the top absent; opening the top widens the scope and the
answer becomes the whole set's; (3) whole workspace: a module rename from
the testbench edits the top. `tests/opentitan_references.rs` (ignored, skips
without the checkout): pins 14/12 with the three tops under the workspace
scope, and 11/9 all-in-`hw/ip/aes` under the default. Ran both ignored tests
against `~/.cache/lucisv-eval/ot`: pass (17.8 s, debug); with
`LUCISV_OPENTITAN=/nonexistent` both skip and pass.
## QA log
## Review
**2026-10-19 — lead (owner's ruling).** The owner chose **keep as
designed**: cross-file answers stay relative to the index scope, and §65.2
is closed as scope-relative by design rather than as a defect. The lane's
tests are merged as the pin of both halves (the workspace scope equals the
whole-set engine, the folder scope equals the engine over the scope, the
opentitan 14/12 vs 11/9). The rename consequence is now said in the
`lucisv.index.scope` setting's description (a rename of a module
instantiated outside the scope leaves those instantiations unchanged). No
production code changed, so no QA lane was run; the lead reviewed the
tests.
+366
View File
@@ -0,0 +1,366 @@
# release-gates — TODO §65.3: a dependable release gate script
## Goal
`cargo test --workspace` under `tools/guard.sh` kept hitting the guard's
wall clock (2026-09-29 in `Doc-tests vlog_linter`, 2026-09-30 at the start
of `tests/rename_implicit.rs`, 2026-10-07 launching
`vlog_semantic/tests/struct_members`, 2026-10-14 in
`vlog_refactor/tests/corpus.rs`), while every per-crate run passed. Name
the cause, fix whatever part of it is ours, and replace the three-command
gate in `tools/RELEASING.md` with `tools/gates.sh`: fmt, clippy, the test
build, each crate's suites, the doc-tests, the corpus gate and the node
tests as **separate guarded steps**, each with its own log, a kill retried
once and shown as such, and a summary table — so a stall names the step it
happened in instead of eating a 30-minute guard.
## Assumptions
- The gates run on the release Mac (Apple Silicon, 10 cores, 64 GB), the
same host the Gitea runner uses. The `-t`/`-m` limits are sized for it;
a slower machine may need larger clocks (edit `limits()`).
- No gate reads stdin; `gates.sh` gives every step `/dev/null`.
- The corpus lives at `~/.cache/lucisv-corpus` as in CI
(`.gitea/workflows/ci.yml`); `-c` points elsewhere. Absent → the step is
skipped with a note, which does not fail the run (CI is where the corpus
gate is mandatory).
- The workspace `members` in the root `Cargo.toml` are all under
`crates/`, one per line, and each member's first `name =` line is its
package name. `gates.sh` reads the crate list from there.
- A guard kill is identified by exit 137 **and** guard.sh's `killing` line
in the step log; a 137 without that line (a test binary SIGKILLed by
something else) is an ordinary failure and is not retried.
## Handshakes
- **Consumes** `tools/guard.sh` (`-t`, `-m`, exit 137 + `guard.sh: …
killing: …` on stderr), `scripts/corpus_gate.sh <dir>` (needs
`target/release/lucisv`, so the corpus step builds it first, as CI does),
`node --test`, cargo.
- **Changes `tools/guard.sh`** (two fixes, both ours, see Work log):
a closed stdin no longer makes the command silently not run, and the
memory limit now sees processes three or more levels down the tree.
The second is a **behaviour change for every guarded command**: memory
that was invisible (rustc/linker processes under cargo, binaries a test
spawns, the corpus scorer's `lucisv` processes) is now summed, so a
command whose real tree exceeded its `-m` and used to pass will now be
killed. Measured peaks are below; a guard kill after this change is a
finding, per CLAUDE.md, not a reason to raise the limit silently.
- **Promises** `tools/gates.sh` exit 0 only if every selected step passed
(or was the corpus step skipped for a missing corpus); logs kept under
the log dir: `<step>.log`, `<step>.killed.log` for a first attempt the
guard killed, `summary.txt`, `steps.tsv` (step, start, end epoch, result).
- **CLAUDE.md request (the lead's file):** under "Rust standards", replace
the first bullet's tail so it reads:
> - `cargo fmt` clean, `cargo clippy --all-targets` clean (no `#[allow]`
> without a comment explaining why), `cargo test` green — all three
> before declaring any work finished. **Before a release, and whenever
> the whole workspace is gated, run `tools/gates.sh`** (every gate as a
> separate guarded step with kept logs; `--only`/`--skip` for a subset)
> instead of a bare `cargo test --workspace`.
and in "Runaway guard", after the first bullet:
> - The release gate is `tools/gates.sh`, which guards each step with
> its own limits; do not wrap it in another `guard.sh`.
- **Request (root `README.md`, not this lane's file):** its build section
(line ~1042) still shows `tools/guard.sh -- cargo test --workspace`; a
pointer to `tools/gates.sh` there would match RELEASING.md.
- **Request (lane A / `lucisv_server`, not this lane's file):** the
wall-clock assertion in `crates/lucisv_server/src/large.rs:884`
(`LOCATE_BUDGET_MS = 150`) flaked once under load (Work log); make it
relative or widen it so the gate stays deterministic.
## Status / TODO
- [x] investigate: stall reproduction attempt, syspolicyd, stuck tree
- [x] doc-test stdin question: closed / `/dev/null` / pipe / tty / tty with
job control, under the guard, in the background
- [x] fix what is ours: guard.sh closed-stdin, guard.sh deep-tree memory
- [x] `tools/gates.sh` with `--only`, `--skip`, `--list`, `-o`, `-c`, `--help`
- [x] kill → retry path exercised (killed → pass, killed → killed, plain
failure not retried, corpus skipped)
- [x] two full runs recorded
- [x] ten consecutive green runs (runs 3–12; thirteen green in all, no kills)
- [x] `tools/RELEASING.md` step 3 points at `tools/gates.sh`
- [ ] CLAUDE.md pointer (lead, at merge)
## Work log
### 2026-10-19 — investigation
Base: master ec492cd (the worktree was created one commit behind it, at
75d2d37; fast-forwarded before any work). Lane A (§65.2) ran its own
`lucisv_server` tests in another worktree throughout: load average 6–10 on
10 cores for the whole session, so every timing below was taken under a
second, unrelated workload — the 2026-10-14 condition.
**The stall did not reproduce.** The host had been up 1 h 13 min (rebooted
that morning). `syspolicyd` sat at 0.0 % CPU at the start, never above 0.3 %
in any 1 s sample across the twelve full gate runs, and showed nothing over
1 % in 0.2 s samples during a freshly-linked suite's first run. Five freshly
linked unique binaries (`rustc` of a one-line `main`, each with a distinct
constant, i.e. a distinct cdhash as a doc-test's `rust_out` has) launched in
10 ms the first time and 10 ms the second. `cargo clean -p lucisv_server`
then a first and second run of its suites: 2.2 s and 2.2 s. So there was no
stuck tree to inspect; the cause recorded on 2026-09-30 (syspolicyd stuck at
~100 % CPU on notarization lookups, `-67062`, for hours, each first launch of
a new unsigned executable waiting on it) stands unrefuted and unreproduced,
and it fits every recorded stall: each one sat at the **first launch of a
freshly linked binary** — a test binary just rebuilt
(`rename_implicit`, `struct_members`, `corpus.rs`) or the doc-test phase,
where `vlog_linter`'s `lib.rs` example is the **only runnable doc-test in the
workspace** (`cargo test --workspace --doc`: 1 test), and rustdoc links it
into a new `rust_out` with a new hash on every run, so it can never hit
syspolicyd's cache. That is why "Doc-tests vlog_linter" is where 2026-09-29
sat. Healthy after a reboot, sick after hours of uptime: the host fix (System
Settings → Privacy & Security → Developer Tools: allow the terminal / Claude
app, or restart syspolicyd) is the owner's, not the repo's. `DevToolsSecurity
-status` reports developer mode disabled; `spctl --status`: assessments
enabled.
**The doc-test stdin question — not the cause.** `cargo test --workspace
--doc` under `tools/guard.sh`, backgrounded, with each kind of stdin (script
kept in the session scratchpad; results):
| stdin | result |
|---|---|
| closed (`<&-`) | **exit 1 in 0 s, nothing ran** — `guard.sh: line 34: 0: Bad file descriptor`, then `3: Bad file descriptor` (a guard bug, fixed below) |
| `/dev/null` | exit 0, 1 s, 1 passed |
| a pipe whose writer never closes | exit 0, 1 s, 1 passed |
| a pty (`script`), no job control | exit 0, 1 s, 1 passed |
| a pty with job control (`set -m`: the job in a background process group, as `guard.sh … &` typed at a prompt) | exit 0, 1 s, 1 passed — no SIGTTIN stop |
The harness never reads stdin: rustdoc feeds each doc-test to `rustc` over a
pipe of its own and runs `rust_out` with `Command::output()`, which gives it
`/dev/null`. No test in the workspace spawns a child that inherits stdin and
reads it (every `spawn()` in `crates/*/tests` pipes stdin; the one inherited
`status()`, `lucisv_server/tests/e2e.rs:571`, runs `lucisv check --fix
<file>`, which does not read it).
**Fixed — ours, both in `tools/guard.sh`:**
1. *Closed stdin*: `exec 3<&0` failed, then `"$@" <&3` failed, so the
command silently never ran (exit 1). Now `{ exec 3<&0; } 2>/dev/null ||
exec 3</dev/null`. `lucisv -` still reads stdin through the guard,
foreground and backgrounded (checked: formatted output both ways); with a
closed stdin it now reads an empty `/dev/null` instead of not running.
2. *The memory limit was blind three levels down.* `tree()` appended
`"$all $next"` where `next` ended in a space, so from the second level of
descendants on the list had a doubled space, `tr ' ' ,` made `a,,b`, and
macOS `ps -p` rejects the whole list on an empty element ("Invalid
(zero-length) process id") — RSS summed to 0 and the limit could never
fire. Every real guarded command is that deep: cargo → rustc → ld, cargo →
test binary → spawned `lucisv-server`/`lucisv-mcp`, the corpus scorer's
`lucisv` processes. Reproduction (a perl process holding 1.5 GB for 8 s,
`-m 1`): at depth 1 and 2 killed in 3 s; at depth 3 **ran to completion,
exit 0** before the fix; killed in 3 s after it. The awk now prints
`" %s"` and the loop appends without a separator, so the list is single-
spaced; the kill path uses the same list and was re-checked (depth-3 hog
killed, nothing left behind). Not related to the stalls (it can only
cause *fewer* kills), but it is the runaway guard CLAUDE.md relies on.
**Also observed, not ours to fix (lane A owns the crate):**
`lucisv_server` `large::tests::references_on_one_giant_line_locate_their_hits_in_linear_time`
failed once, on the first run after `cargo clean -p lucisv_server`, under
lane A's load: "locating 800 hits on one line cost 185.450583ms" against
`LOCATE_BUDGET_MS = 150` (`crates/lucisv_server/src/large.rs:884`, budget at
:896); the 400-hit pass on the same run took 17 ms, so it was a scheduling
hiccup, not the quadratic rescan. The immediate rerun passed and so did all
thirteen gate runs. A wall-clock budget in a debug-build unit test is a
flake source for any gate; filed here as a request for the lead (widen the
budget or compare the 800-hit time against the 400-hit time instead of an
absolute).
**Also observed: feature unification rebuilds.** `cargo test -p <crate>`
after `cargo test --workspace --all-targets --no-run` recompiles a few crates
(`crossbeam-utils`, `lsp-server`, `lucisv_server`: 16 s in run 1) because
resolver 2 unifies features per selected package set; both variants are
cached afterwards. The per-crate clocks allow for it.
### 2026-10-19 — `tools/gates.sh`
Steps, logs, retry and summary as in the header comment and Handshakes.
Design points: the command for each step is a bash array (no `eval`); the
crate list comes from the root `members`, each member's `name`; a guard
kill is exit 137 *and* the guard's line, retried once with the first log
kept as `<step>.killed.log`; every step gets `/dev/null` as stdin; node 22+
prints `ℹ pass N` rather than TAP's `# pass N` and both are counted; the
corpus step builds `target/release/lucisv` first, as CI does; unknown step
names are a usage error (exit 2).
Exercised paths (a throwaway copy of the script with a 2 s clock on a
`sleep 30`, deleted after): killed → retried → KILLED (exit 1), killed →
retried → pass (a command that sleeps only on its first call; exit 0, first
log kept), a plain failure (`node -e 'process.exit(3)'`) reported `fail` and
not retried, the corpus step `SKIPPED (no corpus)` with `-c /nonexistent`
and the run still green.
Limits (`limits()`; measured 2026-10-19 from a cold `target/`, peak tree RSS
sampled each second over the whole step tree):
| step | measured cold | warm (runs 3–12) | peak RSS | `-t` / `-m` |
|---|---|---|---|---|
| fmt | 3 s | 2 s | 0.1 GB | 120 s / 2 GB |
| clippy | 20 s | 1–2 s | 1.6 GB | 900 s / 6 GB |
| build | 31 s | 1–2 s | 2.6 GB | 900 s / 8 GB |
| suite: each small crate | ≤ 3 s | 1–4 s | ≤ 0.15 GB | 300 s / 4 GB |
| suite:lucisv_server | 17–19 s (rebuild) | 2–4 s | 1.1 GB | 600 s / 4 GB |
| suite:lucisv_mcp | 20–22 s | 12–15 s | 1.4 GB | 600 s / 4 GB |
| docs | 1 s | 1 s | 0.1 GB | 300 s / 2 GB |
| corpus (release build + score) | 30 s | 3–4 s | 1.2 GB | 900 s / 6 GB |
| node | 1 s | 1 s | 0.3 GB | 120 s / 2 GB |
The clocks are the cold time times twelve (the CPU-bound slowdown a sick
syspolicyd was measured to cost) rounded up, with a two-minute floor: a
real hang costs at most that step's clock twice, not 30 minutes; a stall
that clears on the retry shows as `KILLED → retried → pass`.
### 2026-10-19 — runs
Thirteen full runs, all `gates: PASS`, **zero kills, zero retries, zero
failures**: run 1 (warm, before the deep-tree guard fix and with the first
draft limits), run 2 (after `cargo clean`, limits as drafted), runs 3–12
(final limits, back to back: 33–38 s each), run 13 (the final script, after
a summary-alignment change; default log dir). Runs 3–12 are §65.3's ten
consecutive green runs. Honest caveat: the host was healthy all session
(syspolicyd ≤ 0.3 %), so these runs prove the script and the gates, not
immunity to the host fault — that would show as a `KILLED → retried` row.
Run 2 (cold):
```
step result seconds passed/failed
fmt pass 3 -
clippy pass 20 -
build pass 31 -
suite:vlog_parser pass 3 505/0
suite:vlog_semantic pass 1 401/0
suite:vlog_refactor pass 1 727/0
suite:vlog_formatter pass 1 314/0
suite:vlog_linter pass 1 672/0
suite:lucisv_core pass 1 117/0
suite:lucisv pass 2 143/0
suite:lucisv_server pass 17 1862/0
suite:lucisv_mcp pass 22 383/0
docs pass 1 1/0
corpus pass 30 814/6
node pass 1 8/0
gates: PASS
```
Run 13 (final script, warm except clippy/build after `cargo clean -p
lucisv_server`): fmt 2, clippy 9, build 14, suites 3/1/1/1/1/2/1/2/12,
docs 1, corpus 3, node 1 s — the same counts, `gates: PASS`. The corpus
"failed" column is total − passing (6 of 820, the documented ceiling).
## QA log
### 2026-10-19 — QA agent (Sonnet)
**Verdict: PASS, no blocking findings; no files fixed (log only).** Host load
average 5 to 19 (lane A running suites) throughout. Bash: only `/bin/bash`
3.2.57 exists (`which -a bash`), so `#!/usr/bin/env bash` runs 3.2; no
bash-4 feature in either script (grep for `declare -A`, `mapfile`,
`${v,,}`, `[[`, `+=`, `|&`: none).
**guard.sh** (diff read line by line: three changes, stdin fallback,
awk `" %s"`, `all="$all$next"`; nothing else touched).
- Memory depth proof (`nest.sh N`: N nested bash layers, python holding
1.5 GB at the bottom, `-m 1 -t 40`; scratch `qaB65/nest.sh`):
| depth | master guard | new guard |
|---|---|---|
| 1 | 137, killed in 3 s | 137, 3 s |
| 2 | 137, 3 s | 137, 3 s |
| 3 | **exit 0 after 31 s, no guard line (missed)** | 137, 4 s, guard line |
| 4 | **exit 0 after 31 s (missed)** | 137, 2 s, guard line |
No `nest.sh` survivors after any run.
- Wall clock: `-t 3 -- sleep 30` gives 137 with the guard line in 6 s. TERM
escalation: a script and a child both with `trap '' TERM`, `-t 3`: 137 in
6 s (3 s + 2 s grace + KILL), no survivors.
- Stdin: `echo ... | guard.sh -- lucisv -` formats (foreground); formatted in
the background with stdin from a file, from a pipe in a subshell, and from
a pipe inside `bash -c '... &'`. Closed stdin (`<&-`): new guard runs the
command (`echo` ran, `cat` exits 0); master guard prints "Bad file
descriptor" twice and exits 1 without running it (confirmed).
- `exit 3` passes through as 3. A 400-subshell fork storm of short-lived
children (exiting mid-poll) under `-m 2`: exit 0, stderr empty.
macOS pids are at most 99999, so the awk `index()` token match has no
prefix-collision risk.
- Cosmetic (info): on a kill the shell prints `tools/guard.sh: line 57:
<pid> Terminated: 15 "$@" 0<&3` to stderr (seen in the retry logs). It
is harmless and gates.sh matches the `guard.sh: ... killing` line instead.
**gates.sh**
- `--help` exit 0; `--list` prints the 15 steps; unknown flag exit 2;
`--only nope`, `--skip suite:nope` exit 2 with "unknown step". `--only
fmt,node`, `--only docs --skip corpus`, `--only corpus -c /nonexistent`
(SKIPPED (no corpus), exit 0, note in corpus.log) all as documented.
`-o "dir with space"` works (logs, summary.txt, steps.tsv created).
- Scratch copies of the script: a failing node test gives `fail`, summary
`gates: FAIL`, exit 1, and a single attempt (no `.killed.log`); a step
killed twice (2 s clock on `sleep 30`) gives `KILLED → retried → KILLED`,
exit 1, `node.killed.log` kept, `steps.tsv` row written; killed once then
passing gives `KILLED → retried → pass`, exit 0, `.killed.log` kept.
- Crate list: the real `members` (nine, one per line, no comments, no glob)
parses to all nine and matches `--list`.
- **Full gate, run once, not wrapped:** `tools/gates.sh` printed
`gates: PASS`, 36 s wall, zero kills. Warm cache: fmt 2, clippy 1, build 1,
suites 3/1/2/1/1/1/1/2/14 (parser, semantic, refactor, formatter, linter,
core, lucisv, server, mcp), docs 1, corpus 3 (814/6), node 1 (8/0);
counts identical to the dev's run 2 (505, 401, 727, 314, 672, 117, 143,
1862, 383, 1 doc-test).
**Findings** (all low; none block)
1. **Low-medium, silent shrink of coverage.** `crates()` at
`tools/gates.sh:74-79` drops members it cannot parse and still reports
PASS. Reproduced in a scratch workspace: a trailing comment on a member
line (`"crates/a", # note`) loses that crate (plus one `sed: ...
No such file` on stderr); `members = ["crates/a", "crates/b"]` on one
line yields no crates; `"crates/*"` yields no crates. In the last two
cases the whole suite phase vanishes and the run is green. The README
assumption names the layout, but nothing enforces it. Suggest: fail
(exit 2) when `crates` is empty or its count differs from
`cargo metadata --no-deps` members. Not a risk with today's Cargo.toml.
2. **Low.** `gates.sh:55-57` (`-o`, `-c`, `--only`, `--skip` as the last
argument): `$2: unbound variable` under `set -u`, exit 1, not the
documented usage error 2. Repro: `tools/gates.sh --only`.
3. **Low.** `--only ''` means no filter (all steps run), and a selection
that matches nothing (`--only suites --skip suites`) prints an empty
table and `gates: PASS`, exit 0. A zero-step run being green is
misleading; suggest exit 2 or a "no steps selected" line.
4. **Info.** The corpus step is skipped green when `~/.cache/lucisv-corpus`
is absent; documented, but a release run on a fresh host would pass
without the corpus gate. `RELEASING.md` step 3 says so, which suffices.
5. **Info / behaviour change (already in Handshakes).** After the guard fix,
memory is now enforced for deep trees. The full gate's peaks stayed under
all `-m` limits in this run (no kills), so the limits are sound at
least on this host.
**Review of docs.** `tools/RELEASING.md` step 3 reads correctly and matches
the script (steps, log names, retry wording, `--only`/`--skip`/`--list`).
Minor: "a line in the release notes' working log" is vague (the repo has a
CHANGELOG and README work logs). The proposed CLAUDE.md lines are sensible
and consistent: `gates.sh` guards each step itself, so "do not wrap it in
another guard.sh" is right (a nested guard would also hide per-step kills).
## Review
**2026-10-19 — lead.** Accepted. The two `guard.sh` bugs were the real
find: the memory limit never saw a process three or more levels down the
tree (every cargo → rustc → linker chain), and a closed stdin skipped the
command; QA re-proved both against master's guard. The stall itself is the
host's (syspolicyd on fresh unsigned binaries; the owner's Developer Tools
setting), and `gates.sh` now survives it by retrying a killed step once and
saying so. QA's three lows are fixed by the lead in the worktree before
merge: the crate list drops comments and handles a one-line list and a
glob, and an empty list is a usage error (exit 2) instead of a green run
with no suites; a missing or empty option value is exit 2; a selection that
runs no step is exit 2. Granted: the CLAUDE.md lines (Rust standards and
Runaway guard) and the root README's Building section now point at
`tools/gates.sh`. The ten green runs were on a healthy host — the first
`KILLED → retried` row on a stalled one is the evidence still to come.
@@ -0,0 +1,348 @@
# selection-formatting
## Goal
VS Code's "Format Selection" (`textDocument/rangeFormatting`) failed more than
half the time on the selections people actually make — one whole `always`
block, one whole `case`, usually nested in blocks the selection does not
cover. The request went to `format_range` (the CLI's `--lines`), whose unit is
a whole module-level item laid out at formatter depth: selecting a `case`
re-laid the whole `always`, a block in a four-space or tab-indented file came
back re-indented to two spaces, a selection inside `generate` or a function
re-laid the whole region, and any parse error anywhere refused the request.
`format_selection` lays out **only the smallest run of sibling items or
statements the selection covers**, at the indentation its first line was
written at, and splices it into otherwise untouched bytes. The owner's rule:
don't worry about the parent; the selected block keeps the indentation level
it starts at; the result must be functionally the same.
## Semantics
### Scopes and units
A *scope* is a sibling list exactly as `fence.rs` defines one: item lists
(file, module, package, generate region, generate `begin`…`end`, class) and
statement lists (`begin`…`end`, `fork`…`join*`, function and task bodies). A
single-statement body (`if (a) x = 1;`, `always @* x = 1;`) or a block-less
generate item is not a scope; it is walked *through* to the scopes it reaches.
A *unit* is one item or statement with its whole extent: first leading comment
or attribute through the comments written after it on the same line.
### Locating the target (`selection/locate.rs`)
For one selected line span, starting at the file scope:
1. Take the units whose lines meet the span. Blank lines select nothing; a
span meeting no unit changes nothing.
2. If exactly one unit is met, the span touches neither its first line nor its
last, and exactly **one** of its nested scopes has a unit the span meets,
descend into that scope and repeat.
*(Lead ruling 2026-11-09, QA note 2: only the unit's **first** line is
asked about. A selection over a block's last statements and its closing
`end` descends and lays out those statements; the closing line alone
meets no nested unit and still names the unit it closes.)*
3. Otherwise the target is the run of consecutive units met — a partial
selection expands to whole units.
4. **Fences outrank the selection.** Units a fenced region *of this scope*
reaches (a region nested inside a unit's own code does not count) are
trimmed from both ends of the run; an empty run changes nothing. A region is
never half inside the splice.
5. **Line-clean or one level up.** The run must be replaceable by whole lines:
only spaces/tabs before its first byte on that line, only whitespace after
its last byte on that line, no sibling unit's extent and no dangling comment
of the scope inside it. If not (`begin // note` makes the first statement's
leading comment start on the `begin` line; `x = 1; y = 2;` with only `x`
selected is fine because both are met), the enclosing unit is the target,
checked the same way. At the file scope there is nowhere to go up to, and
the request is deferred.
6. **Big containers defer.** A run holding a `module`/`interface`/`program`
or `package` item goes to `format_range(source, config, lines)` unchanged —
header/footer splitting and whole-file selections behave exactly as before.
The located target is recorded as a **path** — `(unit index, child scope
index)` per descent, plus the run's start and length — not as bytes or lines.
### Layout and splice (`selection/mod.rs`, `format::print_run`)
- `print_run` builds the ordinary `Fmt` over the whole source (fenced regions
from `fence::collect`, no range splits) and calls `item_seq(run, depth)` or
`stmt_seq(run)` on the sub-slice. `depth` is the AST depth `item_kind`
would pass down (it only feeds the alignment width budget).
- The **base indentation** is the leading whitespace of the run's first unit's
line, as written (tabs included) — or, when that unit is a compiler directive
and a later unit is not, the later unit's: directives are commonly written at
column 0 while the code they guard is indented, and the code says where the
block stands. The directive is then indented with the block, as a whole-file
run indents it.
- `Printer::print_at(doc, base)` starts the text with `base`, writes it after
every line break before the indentation, and charges its width against the
line budget (a tab counts as one indent width). `Doc::Verbatim` and
`Doc::Inline` keep their own absolute indentation, and a line holding nothing
but indentation is emptied so blank lines never keep the base's tabs.
`print` is `print_at(doc, "")`, byte for byte the old printer.
- The splice replaces `line start of the first unit .. end of the last unit's
extent` with the printed text and nothing else: blank lines at the boundary,
the rest of the last line and the file tail (final newline or not) are
untouched. In a file whose lines end in `\r\n` (judged at the target), every
line break the printer wrote becomes `\r\n`; source text copied through
keeps the `\r\n` it had.
### Several ranges
Each merged span of `LineRanges` selects its own target. Targets whose byte
ranges overlap are replaced by the target of the hull of their spans, until
none overlap. They are spliced bottom-up and verified together, so the
all-or-nothing contract covers the whole request. If any span defers, the
whole request goes to `format_range`.
### Safety net (unchanged)
`verify_equivalence(source, output)` over the whole file, then convergence by
**replaying the targets**: the output is parsed the same way, each path is
resolved in its tree, laid out and spliced again, and `verify_convergence`
must find nothing to change. `verify.rs` is not touched. Any failure — a target
that cannot be found again or cut cleanly in the output included — is an error
and no edit (`FormatError::Selection` for the selection's own refusals).
### A file that does not parse
`parse_source` first. If it fails, `parse_source_tolerant` builds the tree and
the target is located in it the same way. The request is refused when any
parse diagnostic lies inside `line start .. end` of a target, or any unit of
the target (at any depth reachable through the scope walk) is an `Error` node.
The replay parses the output the same way and applies the same check.
**Verdict:** sound and useful. Sound because the layout is token-verified over
the whole file like every other path: recovery can only mis-guess the *nesting*
around a target (an `assign` after a missing `end` becomes a statement), which
changes at most how a clean run is laid out, never its tokens — and the target
itself is required to be free of diagnostics and error nodes. Useful because
in the corpus sweep below, with a broken line injected in every file, 75 % of
selections still answered.
## Assumptions
- A tab in the base indentation is worth one indent width for the line budget.
The printer cannot know the reader's tab stop; only group breaking depends
on it, and the replay uses the same rule, so it cannot break convergence.
- Comment `col` is a byte column with a tab counting 1, so `raw_lines`'
dedent-by-column cancels a base containing tabs exactly as it cancels
spaces (exercised by the tab tests).
- A parse diagnostic's span is the token the parser gave up on, not the extent
of what it swallowed; the `Error`-node walk covers the latter at list level.
An error node nested in an expression or header list is assumed to come with
a diagnostic inside it. The safety net backs both.
- The alignment of a sub-slice is planned over the sub-slice only (a run
holding half of an alignment group aligns that half). Stable under replay.
- With `uvm-utils-indent` on, a run holding a `` `uvm_*_utils_begin `` without
its `_end` indents what follows it inside the run, as a whole-file run would.
## Handshakes
- **Consumes** `fence::collect`, `fence::region_at`-shaped regions,
`fence::with_trailing_comments` (already `pub(crate)`), `Fmt::item_seq` /
`Fmt::stmt_seq` (already `pub(super)` within `format`), `format_range`,
`verify_equivalence`, `verify_convergence`, `vlog_parser::parse_source`,
`parse_source_tolerant`.
- **Provides** `vlog_formatter::format_selection(source, config, lines)` and
`Printer::print_at(doc, base)`; `format::print_run` / `format::Run`
(`pub(crate)`); a new `FormatError::Selection(String)` variant (every match
on `FormatError` in the workspace already has a catch-all arm).
- **Changed for the server:** `lucisv_server::format::{range_formatting,
ranges_formatting}` now call `format_selection`. `on_type.rs`'s
semicolon trigger calls `format::range_formatting`, so it changes too.
- **Request (not done — outside this lane's files): `crates/lucisv_server/src/on_type.rs`.**
Two of its unit tests pin behaviour this design changes on purpose, and fail:
1. `a_semicolon_in_a_buffer_the_engine_refuses_answers_nothing_at_all`
(line ~1175) — its buffer's error (`wire ;`, line 3) is *outside* the
keystroke's statement (line 2), so the request now formats line 2 (design
step 7). Proposed fix: put the error on the keystroke's own line, e.g.
`"module m;\n wire a = ;\nendmodule\n"` with the `;` at line 1,
char 13 — the change made to the twin test in
`server/tests/formatting.rs`.
2. `a_semicolon_at_eof_with_no_trailing_newline_still_lays_out_its_line`
(line ~1210) — the splice no longer adds a final newline (design step 5);
the expected text becomes `"module m;\n wire a;\nendmodule"` and the
comment above it should say the file tail is untouched.
The module doc at line ~64 ("`format_range` selects by …") is also stale.
- The CLI `--lines` keeps calling `format_range`; `range.rs` is unchanged.
## Status / TODO
- [x] `printer.rs`: `print_at(doc, base)`; `print` delegates with `""`.
Whole-file output byte-identical (snapshot + idempotency suite green
before any selection test existed).
- [x] `format/mod.rs`: `Run`, `print_run`, `FormatError::Selection`.
- [x] `selection/scope.rs`: scopes, units, extents, the nested-scope walk.
- [x] `selection/locate.rs`: locate (descend, fences, line-clean, defer),
path resolution, error-node walk, base indentation.
- [x] `selection/mod.rs`: `format_selection`, multi-target hull merging,
bottom-up splice, CRLF, tolerant path, replay.
- [x] `tests/selection.rs` — 33 tests (incl. the directive-base test).
- [x] Server: `ranges_formatting` → `format_selection`; 3 handler tests in
`format.rs`, 1 dispatch test + 1 updated in `server/tests/formatting.rs`,
1 e2e leg.
- [x] `on_type.rs` test updates — Handshake request above (applied by the lead, 2026-11-09).
## Work log
### 2026-11-09 — dev
- Built as designed, as a directory module (`selection/{mod,scope,locate}.rs`,
each well under 300 production lines) rather than one file.
- **Deviation 1 — multi-range lives in the engine.** The design put the
per-span targets and hull re-selection in the LSP handler; `format_selection`
takes a `LineRanges` anyway, so it does that itself and verifies all targets
in one pass. The server only swaps `format_range` for `format_selection`.
- **Deviation 2 — descent needs exactly one reached child scope.** A span
covering both branches of an `if` reaches two scopes; it takes the `if`
rather than one branch.
- **Deviation 3 — directive base.** The base indentation is taken from the
first non-directive unit of the run; found by a scratch run where a run
starting at a column-0 `` `ifdef `` pulled the guarded code to column 0.
- **Fence check** counts only regions opened in the run's own scope; a region
nested in a unit's code is laid out verbatim by the printer as in a
whole-file run, so it does not trim the unit.
- **`FormatError::Selection(String)`** added for refusals that are neither a
parse error nor a verification failure (a parse error inside the target, a
target that cannot be found again).
- **Server tests updated:** `a_keystroke_the_engine_refuses_is_answered_with_
silence_and_not_a_popup` (`server/tests/formatting.rs`) — its buffer's error
was on another line, which no longer refuses; the error now sits on the
keystroke's own line. No `format.rs` test pinned over-reach: the existing
range tests select whole module items and come out identical.
- **Corpus sweep** (scratch test, release, under `tools/guard.sh`, not
committed): 428 formattable files of `corpus/{common_cells,ibex,picorv32,
opentitan/hw/ip}` (every ~2nd file), windows of 1, 2, 4 and 8 lines at a
stride of 5+w: **33 438 calls, 21 473 changed, 11 965 unchanged, 0
verification errors, 0 selection refusals, 0 source errors.** Same files
with ` @@ broken = ;` injected at the middle line: 33 626 calls, 14 159
changed, 10 954 unchanged, 4 281 refused because the target holds the
error (or recovery swallowed the rest of the file into an error node), 4 232
source errors (the span reached a module-level unit and was deferred to
`format_range`, which parses strictly), 0 verification errors.
## QA log
### 2026-11-09 — QA
**Gates (main checkout, all guarded, no guard kills):** `cargo fmt --all --check` clean;
`cargo clippy --workspace --all-targets` 0 warnings; `cargo test`: `-p vlog_formatter`
347 passed / 0 failed, `-p lucisv_server` 1881 passed / 0 failed / 40 ignored, `-p lucisv`
143 passed / 0 failed. `verify.rs`, `range.rs`, `fence.rs`, `crates/lucisv` untouched
(`git diff --stat`). No source or test files edited by QA; all experiments in a throwaway copy
(deleted).
**Hand-written attack set:** 221 (source, selection) cases in 2/3/4-space and tab files
(nested `generate for` / `always_ff` / `case`, mis-indented parents, `if`/`else` chains, `for`,
`fork`/`join`, function and task bodies, case-item blocks, class methods, gen-if/gen-case),
comments everywhere, `` `define `` with `\` continuations, `` `ifdef `` at run boundaries,
escaped identifiers, attributes, labels, fences (enclosing / unmatched / straddling), CRLF, no
final newline, multibyte, mixed whitespace, tabs, empty file, past-EOF, one-line/cursor-only,
statements sharing a line, multi-range hulls, files with parse errors. Every window of each
case was then run (24 719 calls): **0 panics, 0 token-nonequivalent outputs (independent
`verify_equivalence`), 0 non-idempotent results, 0 verification errors except the CRLF finding
below.** A "far" detector (changed lines not touching the selection) fired 573 times; every
one inspected was the target growing to its whole unit (selection touching a unit's first/last
line, a leading `///` comment line, or the module header deferral) as the spec says.
**Corpus sweep** (release, 409 files of `corpus/`, 12 random windows of 1-12 lines each,
fixed seed): clean 4 908 calls: 3 611 changed / 1 265 unchanged / 32 refused / 0 verification
errors / 0 panics / 0 non-equivalent. One random line replaced by ` @@ broken ( ;` (4 908
calls): 1 005 changed / 617 unchanged / 3 286 refused (error inside target or swallowed by
recovery) / 0 verification errors / 0 panics / 0 non-equivalent. CRLF-converted (818 calls): 594
changed / 212 unchanged / 7 refused / **5 verification errors** and 1 mixed-EOL output (finding 1).
(A shifted-window re-run flagged 18 "non-idempotent" calls; all were artifacts of the shifted
window landing on the module header, i.e. a different target — not a defect.)
**Sabotage (copy only):** (A) splice tail skips the line after the target: 27 of 33
`tests/selection.rs` tests fail; runtime net alone rejected 14 294 of 24 719 calls, 0 corrupted
outputs returned. (B) base indentation prefixed onto every `Doc::Verbatim`: 1 test fails
(`a_fence_inside_the_target_is_emitted_as_written`); runtime net (replay convergence)
rejected 283 calls, 0 corrupted outputs returned; the whole-file suite cannot see it (empty
base) — so one test is all that pins it. (C) fence trimming removed: 2 tests fail
(`a_fence_around_the_target_wins`, `a_fence_straddling_the_target_trims_the_fenced_units`);
net rejected 241 calls.
**Findings**
- SHOULD-FIX 1 — CRLF file + target whose last line ends in a `//` comment loses its `\r`.
`print_run`'s `out.trim_end()` (`format/mod.rs`, `print_run`) strips the `\r` that the trailing
comment's text carries while `Unit::extent` (`scope.rs`) includes it in the replaced
bytes, so the line ends in a bare `\n`; the replay then often disagrees and the request is
*refused* ("formatting is not idempotent; line N changed from "" to """), otherwise the file
comes back with one bare-`\n` line. Repro: `"module m;\r\n initial begin\r\n a = 1; // c\r\n
b = 2; // d\r\n end\r\nendmodule\r\n"`, lines `3-4` -> Err; `3-3` of a one-statement
variant -> Err; corpus `opentitan/.../uart_tx_rx_vseq.sv` as CRLF, line `215-215` -> Ok with a
bare `\n` on line 215. The LF twin of each is fine. Safe (no corruption) but Windows files
with trailing comments cannot be range-formatted.
- NOTE 2 — selecting interior statements together with the parent's closing `end` (e.g. the
last statements of a generate `begin`…`end` plus its `end`) takes the whole parent: corpus
`common_cells/src/rr_arb_tree.sv` lines `310-319` re-lays 116..292. By design (step 2/3)
but it is the most common sloppy selection; consider whether the owner wants it.
- NOTE 3 — inner indentation comes from `Config::indent_width` (2 for the library default),
so the engine alone on a 4-space file gives a 4-space block with 2-space nesting inside
(`gen-4sp` cases); the server passes the editor `tabSize`, so with `indent_width = 4` the
owner's case comes out right (demo below). For tab files the nested levels are `\t…\t` plus
spaces (`\t\t\t\t case`), same as the whole-file printer's no-tab model.
- NOTE 4 — a selection spanning module-header ports and body items formats only the body
items (the header lines are not units); header-only selections defer to `format_range`.
- NOTE 5 — a column-0 directive in a run together with indented code is moved to the block's
indentation (`` `endif `` + next statement selected -> `` `endif `` indented while `` `ifdef ``
stays at column 0). Token-equivalent; cosmetic.
- NOTE 6 — with a missing `end` the tolerant tree nests later statements into the open block, so
they get laid out one level deeper than the (misplaced) `end` implies. Tokens identical.
I could not construct a counterexample where a wrong parse changes meaning: only whitespace
is chosen by layout, the token/comment stream is compared exactly, and line-sensitive
tokens (`` `define ``, directives, line comments) are tokens whose text includes their line.
**Usability (owner's complaint)**, 4-space file, `generate for` -> `always_ff` -> `case`,
`indent_width = 4`: selecting exactly the `case` lines (6-10), exactly the `always_ff` lines
(5-11), one middle line (8) and the three case items (7-9) all yield the same correct result,
and every byte outside the `case` is unchanged:
before after (selection 8-8)
always_ff @(posedge clk) begin always_ff @(posedge clk) begin
case (sel[i]) case (sel[i])
2'b00: q[i]<=a; 2'b00: q[i] <= a;
2'b01 : q[i] <= b; 2'b01: q[i] <= b;
default:q[i]<=c; default: q[i] <= c;
endcase endcase
end end
**Not verified:** the editor (VS Code / Vim) end to end; opentitan sweep and the byte-identity
corpus gates (the 347-test formatter suite incl. snapshots is green, which is the evidence for
`print_at("")` == old `print`); files over 120 KB; non-ASCII-heavy corpora beyond the
hand-written multibyte cases; `--release` gate script `tools/gates.sh`.
## Review
**2026-11-09 — lead. Verdict: accepted, with two fixes of mine after QA.**
1. **The design is a splice, not a second inverted fence**, and that is what
answers the owner's complaint: the target keeps the indentation it was
written at because nothing above it is laid out at all. The safety
argument is the old one, unchanged — whole-file `verify_equivalence`
(`verify.rs` untouched, so invariant #4 does not apply) plus a replay of
the located target. QA's three sabotages were each caught, with zero
corrupted outputs returned in 24,719 hand-case calls and 10,634 corpus
calls; no panic.
2. **QA SHOULD-FIX 1 (CRLF), fixed by the lead.** `Unit::extent` counted the
`\r` after a trailing `//` comment as part of the unit, so the splice ate
it. The extent now stops before it (`selection/scope.rs`); `print_run`
trims spaces and newlines only, as `render` does. Pinned by
`crlf_with_a_trailing_comment_on_the_last_line_keeps_every_line_ending`.
3. **QA NOTE 2, ruled: only the first line stops the descent.** A selection
over a block's last statements and its `end` re-laid 177 unselected lines
of `rr_arb_tree.sv`. It now lays out the statements it covers; the `end`
line alone still names the unit it closes. Three tests pin the three
cases.
4. **`on_type.rs`** (the dev's Handshake request): accepted. The `;` trigger
shares the engine, so an error elsewhere in the buffer no longer silences
it and the file tail is not normalized; two tests updated, one added.
5. **Accepted as they are**: the dev's four deviations; NOTE 3 (nested levels
use `indent_width`, which the server takes from the editor's `tabSize`);
NOTE 4 and NOTE 5 (cosmetic, token-equivalent).
6. **Open**: the LSP reply is still one whole-document edit; the engine now
knows the exact bytes it replaced, so a minimal edit is possible. Not
verified in a running editor.
+683
View File
@@ -0,0 +1,683 @@
# top-rooted-paths
TODO §65.4 (from §65.1 QA F1). Wave 0.62.0 (§65.7), serial after lane A.
## Goal
A hierarchical path whose head is a top-level module declared in another
file — `tb.dut.u_x.sig`, the shape every opentitan DV `force`, `$deposit`
and `uvm_hdl_*` path takes (IEEE 1800 §23.6: a top-level module name is the
root of a hierarchical name) — resolved nothing: `tb` was a `Target::Lexical`
use that missed in the writing file, `resolve::head_site` stopped the spine
there, no segment after it was a reference, and a rename of `dut`'s
declarations left the path behind (since §65.1 with a warning). The goal is
that such a path resolves through the workspace exactly as an instance path
does, so `find_references` and LSP references list its segments and `rename`
rewrites them, while a root the workspace does not declare stays unchanged
and is warned about.
## Design
- **The head is its own target.** `bind/expr.rs`: the bare identifier that
heads a dotted path (`ExprKind::Member` whose base is an `Ident`) is bound
as `Target::PathHead` instead of `Target::Lexical`. Only the head of a dotted
path: a bare identifier anywhere else is unchanged, so a value-position miss
is still never swept through the unit table (the reason `lexical`'s doc
gives). The `with`/`bind` funnel in `bind/mod.rs::use_member` treats
`PathHead` exactly as `Lexical`.
- **`resolve/root.rs` (new)** holds the root rules. **The governing rule
(lead, after QA): a path is rooted only when this file shows the head can
be nothing but a top-level module or interface; in doubt it is not, and the
path stays unresolved and warned about.**
- `roots_at_top(scopes, from)`: false when any scope from the use up to
the file is a class (a member, inherited or macro-declared, is never a
provable path into the hierarchy; a class in a package may not reference
it at all) or holds an unexpanded macro invocation where a declaration
could stand (`Scope::macro_items`, set by `Binder::mark_macro_declarations`
for an item, a statement or block item in any `begin`/`end`, `fork`, task
or function body, and a port-list entry or an unreadable port element;
it may declare the name). A macro inside an expression or used as a data
type cannot declare a name and does not block.
- `path_head`: the lexical answer; on a plain `NotFound` that
`roots_at_top` allows, the candidate `ExternalCandidate { paths: [head],
surface: Hierarchical }`. An import candidate (`import p::*` in scope,
which by the LRM could supply the name) is left exactly as `lexical`
gave it, whether or not the workspace can answer it; so is an
`InheritedCandidate`.
- `unit_root`: the site `MemberSite::Unit { path: head, surface:
Hierarchical }`.
- `$root.tb.…`: `top_site`/`top_module` look `tb` up at file scope only
(an in-file module or interface), else the workspace unit. `$root` skips
the lexical walk, so a local `tb` does not capture `$root.tb`.
- **`resolve.rs::head_site`**: on a plain `NotFound` that `roots_at_top`
allows (the same rule as the head's own reference) the resolution walk
answers `root::unit_root(head)`, so the head reference and the segments
after it are rooted in one unit; anything else roots nothing. The workspace's
`fold_path` then walks `tb` → `dut`'s type → … exactly as for an instance
path. A system name or a macro (`$unit`, `` `TOP``) roots nothing.
- **The completion walk is unchanged.** `member_site` (what
`Semantics::member_site` and the completion popup call) and the resolution
walk share `spine_site`, parameterised by `HeadMiss`: `member_of` passes
`TopModule`, `member_site` passes `Nothing`. A popup after an unknown head
keeps answering `None` (so the ordinary tiers run), which the server's
completion tests pin; offering `tb.`'s members is a server-side change
(Handshake H2). `$root.tb.` is rooted in both walks.
- **Only a module or an interface is a root, and a package is never a
hop.** `workspace/external.rs`: a bare path equal to the name on the
*hierarchical* surface (only a path head produces one) answers through
`root_units` — all instantiable, else nothing. And `fold_path`, on the
hierarchical surface, checks every unit it stands in (`design_unit`): the
first must be declared and only as modules/interfaces; a later one may not
be a module and something else at once (the member table is keyed by name
and would merge the two). A later unit that is only a package would need a
declaration typed with a package's name, which is not code; the separate
"never a package" clause was dropped as unreachable (QA M7). So with a
module and a package both named `tb` the head *and* every segment answer
nothing, and `pk.x` with only a package `pk` resolves to nothing (QA F1).
- **The rename's file set (LSP)**: `WorkspaceIndex::path_units_to(def)`
(new, `workspace/path_units.rs`) lists every unit an indexed hierarchical
use of `def` walks through — the root and each hop's type — read off the
facts the index holds. `lucisv_server/src/state/sources.rs::
want_declaration` adds those units' declaring files, so a three-hop
`tb.dut.u_core.sig` resolves inside the rename's set as in the whole (QA
F3; lead-granted). A unit outside the index scope adds nothing, and the
path stays warned about.
- **An accurate refusal** (`vlog_refactor/src/rename/mod.rs`): a rename asked
at a path segment the workspace could not walk is refused with "`x` is a
segment of a hierarchical path lucisv could not resolve to one
declaration …", not "declared outside the files lucisv indexes".
- **`FACTS_FORMAT` 21 → 22** (`facts.rs`, reason written there): no new
field, but new records — a 0.61.0 store would answer as though no DV file's
`force tb.dut.…` named anything.
- **The §65.1 path warning** (`vlog_refactor/src/rename/paths.rs`): a segment
of a top-rooted path (head is `$root`, or the head's reference is a root
candidate) whose overlay answer is `StillUnresolved` counts as unresolved,
so the warning still fires for a root the workspace does not declare, or
declares several times. An `Ambiguous` answer is not flagged: when it can
name the renamed declaration `collect_occurrences` already refuses the
rename.
- **Said once** (Handshake H1, lead-granted): `warnings.rs`'s
`unresolved_candidate_warnings` skips a candidate that
`paths::names_top_rooted_miss` says the path scan names, so such a line
carries only the §65.1 path warning. The file is lexed for that check only
when an unanswered candidate is on the hierarchical surface.
## What resolves now
- `tb.dut.g_sw[0].buf_q` in a file that does not declare `tb`, with exactly
one `module tb` (or `interface tb`) in the set: `tb` → the module, `dut` →
the instance, `g_sw` → the block, `buf_q` → the variable. Every segment is
a reference: `find_references` lists it, `rename` of any of the four
declarations (or from the segment itself) rewrites it, verified as usual.
- `$root.tb.dut.…`, the same, and `$root.tb.x` against an in-file `tb`.
- Not rooted, by the rule above, and left warned exactly as before §65.4: a
head an import could supply, a head inside any class, a head in (or under)
a scope holding an item-level macro invocation, a head named both a
module and a package, and a package alone.
## Limits
- **Several `module tb` in the set** (opentitan: 70 files under `hw/`):
`tb` is `Ambiguous`, `tb.dut` names 70 instances, and `member_unit_in`
refuses an ambiguous hop, so nothing after the head resolves; the rename
leaves the path and warns. Choosing the
`tb` whose branch has the next member was considered and rejected: the
whole-tree `gen_sw_assigns` case is ambiguous between `keymgr` and
`keymgr_dpe` anyway, and an `Ambiguous` answer that can name the renamed
declaration makes `collect_occurrences` refuse the whole rename — so
branching would turn today's warnings into refusals for every common
member name.
- **A renamed top module's `tb` heads are references** to it. With several
same-named tops a rename of one is refused as ambiguous (pinned:
`renaming_one_of_two_same_named_tops_is_refused`); before, the heads were
`NotFound` and only the declaration was renamed.
- **Any wildcard import in scope stops rooting** — including the
`import uvm_pkg::*;` nearly every opentitan DV interface starts with. By
the LRM such an import could supply the head, and `uvm_pkg` is not in the
tree for the index to rule it out, so the path is doubt. Measured: on
opentitan `hw` (and in `hw/ip/keymgr_dpe`) the reference postings are
exactly master's — no DV force path roots. Rooting when every supplying
import is indexed and shown not to hold the head is possible future work;
it would not change opentitan while `uvm_pkg` is outside the tree.
- **Any macro where a declaration could stand blocks rooting** from its
scope down (lead's R1 ruling): a `` `uvm_info `` statement in the block
beside a `force` blocks it too, since the binder cannot tell a logging
macro from a declaring one. A macro statement in an unnamed `begin` whose
statements bind in the enclosing scope blocks that whole scope.
- **Completion after `tb.`** answers nothing (H2, deferred by the lead).
- `undeclared-identifier` no longer sees an unknown path head as `NotFound`
(it is a root candidate now). Measured on opentitan `hw`: 7 findings
before and after, identical.
## Assumptions
- A bare identifier followed by `.` whose lexical lookup misses plainly —
no import could supply it, no class or item-level macro on the scope
chain — is a top-level module name (§23.6); a typo there is an unresolved
candidate, not `NotFound`.
- Only the head of a dotted path is a root; `tb[0].x` (an indexed head) is
not modelled as one.
- The surface tag on the head candidate is the only signal that a bare path
must be instantiable; nothing else produces a bare hierarchical path.
## Handshakes
- **Consumes**: `WorkspaceIndex::member_unit_in` / `fold_path` (unchanged),
`hierarchy::member` (unchanged), `Scope::analysis().external`.
- **Promises (changed)**: `Resolution::ExternalCandidate` with
`surface: Hierarchical` and a bare path is now produced for a path head;
`follow_one` answers it with modules and interfaces only. `Semantics::
member_site` is unchanged for every head except `$root`.
- **H1 (granted by the lead 2026-10-19, done)**: `warnings.rs`
`unresolved_candidate_warnings` skips a segment `paths.rs` names
(`paths::names_top_rooted_miss`, `pub(super)`), so an unresolved
top-rooted path is said once, in the §65.1 wording.
- **F3 (granted by the lead, done)**: `lucisv_server/src/state/sources.rs`
`want_declaration` adds the files of `WorkspaceIndex::path_units_to(def)`.
**Promised to the server**: `path_units_to` is a pure read of the index's
facts (no file is read); its cost is one pass over the reference records
of each file holding a use of `def`.
- **Outside the listed files, flagged**: `vlog_refactor/src/rename/mod.rs`
gained `hierarchical`/`unresolved_path` so the refusal at an unresolved
segment is the accurate one the lead's F3 ruling asks for (two call
sites, the message only; no rename decision changes).
- **H2 (deferred by lead → TODO; `lucisv_server/src/completion/member.rs` untouched)**: to offer
`tb.`'s members, call a root-aware member site and answer `None` when the
index holds no unit for the root (the server's
`an_unresolvable_head_answers_nothing_at_all` must keep passing).
## Status / TODO
- [x] root lookup in `head_site`, the head recorded as a module use
- [x] QA's repro renames the path instead of warning
- [x] the §65.1 warning stays for an undeclared (or ambiguous) root
- [x] `find_references` and LSP references list the path segments
- [x] the local-shadows-top case
- [x] `$root.` (cheap: done)
- [x] opentitan index/scan cost before and after; `FACTS_FORMAT` bump reasoned
- [x] H1: an unresolved top-rooted path is said once (lead-granted)
- [x] rework after QA: F1 (no package root or hop), F2 (an import wins),
F3 (LSP rename set holds the path's units; accurate refusal), F4 (no
root in a class or beside an item-level macro)
- [ ] H2: completion after `tb.` — deferred by lead → TODO
## Work log
**2026-10-19 (dev, Opus).** Worktree fast-forwarded ec492cd → 51b975b.
- Implemented as designed above. `resolve.rs` 559 → 586 production lines
(the walk split `spine_site`/`HeadMiss`); the root rules are the new
`resolve/root.rs` (29).
- Deviation: the planned single walk would have changed completion after an
unknown head (two server tests), so completion keeps its walk (H2).
- Deviation: rooting a head on an import miss as well as on `NotFound` —
opentitan's DV interfaces import packages, so `NotFound`-only would leave
the target shape unresolved.
- QA's repro `a_path_rooted_at_another_files_top_module_is_never_silently_left_behind`
flipped to assert the rename (granted). Other §65.1 tests that used a
declared `tb` as the vehicle for an *unresolved* root now drop `tb.sv` from
their set (so the root is genuinely undeclared) and gained the declared
counterpart asserting the rename: `qa_generate_label.rs` (three rechecks),
`qa_warning_scope.rs` (two), `rename_generate_label.rs` (two, wording),
`generate_blocks.rs` / `member_access.rs` (an unknown head's tail is now a
candidate, not absent), server `rename_generate_label.rs` (shown wording).
- Invariant 4: `vlog_refactor/src/check/` untouched.
- Tests: `vlog_semantic/tests/top_rooted_paths.rs` (13),
`vlog_refactor/tests/top_rooted_paths.rs` (8), one declared-root
counterpart in `qa_generate_label.rs`, `vlog_refactor/tests/
opentitan_top_rooted.rs` (3, ignored), `lucisv_server/src/server/tests/
references_top_rooted.rs` (5). Counts before → after: `vlog_semantic`
401 → 414 (4 ignored), `vlog_refactor` 727 → 736 (3 → 6 ignored),
`lucisv_server` 1 865 → 1 870 (40 ignored), `lucisv_mcp` 383 → 383;
`vlog_linter` 673 → 673. Gates: fmt, clippy `-D warnings`, the four suites
green. One `lucisv_server` run lost two `large::` linear-time tests to host
load (load average 14–16, another lane's suites); the re-run was green.
*Opentitan* (eval clone `~/.cache/lucisv-eval/ot`, read-only; release;
engine API, nothing written — `vlog_refactor/tests/opentitan_top_rooted.rs`,
ignored by default):
| | before (51b975b) | after |
|---|---|---|
| `rename gen_sw_assigns`, set `hw/ip/keymgr_dpe` (23 files, the LSP folder scope) | 1 site in 1 file; warnings: `uvm_info` macro arg :523, path :514,515,517 | **4 sites in 2 files** (label + `keymgr_dpe_if.sv:514,515,517`); warning: `uvm_info` :523 only |
| same, set `hw` (3 979 files, 70 `module tb`) | 1 site; 4 warnings (2 macro args, 2 path lines `keymgr_if.sv:468,469,471`, `keymgr_dpe_if.sv:514,515,517`) | 1 site; 4 warnings, the same 4 (6 before H1: the 2 candidate lines for the same sites) |
| rename time, `hw` | 2.16 s | 2.23 s |
| facts, `hw` (encoded) | 54 297 047 B | 54 465 816 B (+0.31 %) |
| index postings `reference_sites` / keys | 528 532 / 60 559 | 528 719 / 60 573 |
| `WorkspaceIndex::build`, `hw`, best of 3 | 1.65 s | 1.69 s |
| `lucisv check hw` wall, two runs each | 1.050 / 1.051 s (re-run 1.059 / 1.063) | 1.064 / 1.065 s |
| `lucisv check hw` findings | 1 158 | 1 158, byte-identical output |
| `check --select undeclared-identifier hw` | 7 | 7, identical |
The host was shared with another lane's suites (load average 14–16), so the
sub-2 % time deltas are within noise.
**2026-10-19 (dev, Opus) — H1.** Lead granted H1, deferred H2.
`paths::names_top_rooted_miss` (`pub(super)`, wraps `is_segment` +
`top_rooted_miss`) is asked by `warnings.rs::unresolved_candidate_warnings`
for each unanswered hierarchical candidate; a hit is skipped. The tests that
tolerated the duplicate now assert exactly one line again
(`qa_generate_label.rs` recheck, `rename_generate_label.rs` back to
`warnings.len() == 1`, `top_rooted_paths.rs` two, server
`an_unresolved_path_in_an_open_buffer_is_shown_as_a_rename_warning` back to
`probe.sv:2:` with no "more"), plus a new
`an_unresolved_top_rooted_path_is_named_by_exactly_one_warning` (QA's repro
undeclared, and with three `module tb`), and the opentitan whole-tree probe
asserts the force lines are said once. Opentitan `rename gen_sw_assigns`
over `hw`: **6 → 4 warnings** (2 macro arguments, 2 path lines), 1 site,
2.16 s; IP folder unchanged (4 sites in 2 files, 1 warning). Counts:
`vlog_refactor` 737 (6 ignored), `lucisv_server` 1 870 (40), `lucisv_mcp`
383 (4) — its `a_rename_names_each_same_named_file_by_its_root_relative_path_once`
passes with the two path lines and no candidate lines. fmt and clippy clean.
**2026-10-19 (dev, Opus) — rework after QA.** Governing rule (lead): root
only when the engine can show the head is a top module or interface.
- **F1** (`workspace/external.rs`): `fold_path` checks every unit on the
hierarchical surface (`design_unit`): first unit declared and all
modules/interfaces; later units never a package nor mixed. Tests:
semantic `a_package_never_lends_a_top_rooted_path_its_members`; refactor
`qa_f1_a_package_sharing_the_roots_name_lends_the_path_nothing` (QA's
B12: renaming the package's `dut`, the module's instance `dut`, or `x`
leaves `tb.dut.x` and names it), `qa_f1_a_package_is_never_a_root`
(A3/A4).
- **F2** (`resolve/root.rs`, `resolve.rs::head_site`): an import candidate
is never rooted, and the "bare name last" fallback is gone. Tests:
semantic `an_import_in_scope_wins_and_roots_nothing` (replaces
`an_import_in_scope_is_tried_before_the_top_module`); refactor
`qa_f2_an_imported_head_is_never_rooted_at_a_same_named_module` (A1).
- **F3** (`workspace/path_units.rs` new, `lucisv_server/src/state/sources.rs`,
`vlog_refactor/src/rename/mod.rs` message): server tests
`rename_top_rooted_scope.rs` (5, folder scope): three-hop rename from the
declaration and from the segment, the generate-block `buf_q`, LSP equals
engine over the scope, and a root outside the scope (warned; segment
rename refused with "hierarchical path", not "declared outside"). With
the `sources.rs` rung disabled four of the five fail.
- **F4** (`Scope::macro_items`, `roots_at_top`): semantic
`a_head_inside_a_class_or_beside_a_macro_item_roots_nothing` (A11, D2,
A12, and a macro one scope out); refactor
`qa_f4_a_head_this_crate_cannot_see_is_never_rooted`.
- Mutations: `design_unit` and `roots_at_top` both forced true → both F1
refactor tests and the F4 test fail; `head_site` rooting an import
candidate again → the F2 test fails.
- Changed tests: `rename_generate_label.rs` genblk1 refusal accepts the new
message; the opentitan probe's IP-folder test is now
`the_ip_folder_leaves_the_imported_head_and_says_so`.
- Counts: `vlog_semantic` 416 (4 ignored), `vlog_refactor` 741 (6),
`lucisv_server` 1 875 (40), `lucisv_mcp` 383 (4), `vlog_linter` 673 (0);
fmt and clippy `-D warnings` clean; every suite through the guard, exit 0.
- Opentitan: `lucisv check hw` stdout and stderr byte-identical to master's
binary (1 158 lines); `--select undeclared-identifier` identical (7).
`rename gen_sw_assigns`: IP folder 1 site, 2 warnings (`uvm_info` :523,
path :514,515,517 — `keymgr_dpe_if.sv` imports `uvm_pkg::*`); whole `hw`
1 site, 4 warnings, 2.13 s — both exactly master's. Index over `hw`:
`reference_sites` 528 532 / keys 60 559, equal to master; facts
54 333 266 B (+36 KB, the head candidates).
**2026-10-19 (dev, Opus) — rework 2 (R1, M7).**
- **R1**: `Binder::mark_macro_declarations(scope)` (`bind/mod.rs`) is now
called for an item-level macro (`bind/item.rs`), a macro statement
(`bind/stmt.rs`, `StmtKind::MacroStmt`, on the scope the statement binds
in) and a header port list holding a `` ` ``-spelled port or an error
element (`bind/item.rs::port_list_may_hide_declarations`, on the module's
scope). Tests: semantic
`a_macro_where_a_declaration_could_stand_roots_nothing` (E1, E2, E6, E3
twice) and `a_macro_that_cannot_declare_the_head_still_roots` (data-type
macro, sibling generate block E7, a macro inside an expression); refactor
`qa_r1_a_macro_where_a_declaration_could_stand_blocks_rooting` (E1, E2,
E6 left and named; E3 left) and
`qa_r1_a_macro_off_the_scope_chain_or_as_a_type_still_renames` (E7, E8
shape). With both new flag sites disabled the refactor R1 test fails.
- **M7**: the later-hop "never a package" clause in `design_unit` dropped
as unreachable (argued in its doc comment); the mixed module+package rule
still refuses QA's B12, pinned by the F1 tests.
- **QA's cases1–6 re-run** against this build (QA's harness
`scratchpad/qa654/attack`, outputs in `scratchpad/p654/cases{1..6}.out`).
Every rename either rewrites the correct sites or leaves the path and
warns:
- A1, A3, A4, A7, A8, A10, A11, A12: left and warned. A2: the package
variable renamed with its use (correct). A5, A6, A9: the head is a local
(clocking block, interface port, virtual interface handle), the path is
another declaration, nothing to warn (correct).
- B1, B7, B8, B10: renamed correctly (local `tb` elsewhere warned in B1).
B2, B3: `$root` paths renamed; the local-`tb` line warned; two `tb`
refused. B4: five colliding renames refused. B5: the instance-array
path warned, the unpacked array and the instance array name renamed.
B6 (bind) and B9 (forward local) warned. B11: warned. B12: both renames
leave `tb.dut.x` and warn.
- C1: renamed from the declaration, the segment and the label; refs list
all three sites.
- D1: the unshadowed module's path renamed, the shadowed one warned. D2,
D3 (struct field), D6 (typo head): warned; D3's `acc` renamed. D4, D5:
renamed correctly.
- E1, E2, E3, E4, E5, E6: left and warned. E7 (sibling block) and E9
(modport macro): renamed, correctly. E8 (data-type macro): the head is
the local `st`, warned as an unresolved candidate.
- F3 (`cases6`): each `sig` rename edits exactly its own references.
- Counts: `vlog_semantic` 418 (4 ignored), `vlog_refactor` 743 (6),
`lucisv_server` 1 875 (40), `lucisv_mcp` 383 (4), `vlog_linter` 673 (0);
fmt and clippy `-D warnings` clean; every suite through the guard, exit 0.
- Opentitan `lucisv check hw`: stdout and stderr byte-identical to master's
binary (1 158 lines); `--select undeclared-identifier` identical (7).
## QA log
**2026-10-19 — QA agent (Opus).**
**Verdict: conditional pass. F1 needs a fix before release, and the lead
should rule on F2–F4.** Everything else held: the
verifier, the shadow and `$root` rules, the cache bump, opentitan byte
identity, and every guard mutated.
*Gates* (worktree as handed over, 51b975b + dev diff; every suite through
`tools/guard.sh`, guard exit 0 each, logs kept):
- `cargo fmt --all --check` clean, and `clippy --workspace --all-targets -D
warnings` clean.
- Suites: `vlog_semantic` 414 passed (4 ignored), `vlog_refactor` 737 (6),
`lucisv_server` 1 870 (40), `lucisv_mcp` 383 (4), `vlog_linter` 673 (0).
All 0 failed, and every count matches the work log. No host stall.
*Tests read.* The new semantic, refactor and server tests assert what their
names say: exact `file:line` sets, the exact texts after the edit, and
warning counts. Flipped tests:
- `qa_generate_label.rs` and `qa_warning_scope.rs` now drop `tb.sv`, so the
root is really undeclared, and each gained a declared counterpart. That is
sound.
- The server rename test covers only the block label `g_sw`, which is one hop
below the root's child. That is exactly the case F3 does not hit.
*Mutations.* Each was applied in a scratch copy of the workspace
(`scratchpad/qa654/ws`), never in this tree, and each ran the semantic,
refactor and server suites:
- M1: remove the module/interface-only rule in `root_units`. Caught by 1
semantic test (`only_a_module_or_an_interface_is_a_root`); 0 refactor or
server failures.
- M2: a local of the head's name no longer shadows, in both `path_head` and
`head_site`. Caught by 70 semantic and 37 refactor failures.
- M3: `$root.tb` ignores an in-file `tb`, in `top_site` and `top_module`.
Caught by 1 semantic test (`dollar_root_reaches_a_top_module_this_file_declares`).
- M4: `$root.tb` goes through the lexical walk, so a local `tb` captures it.
Caught by 2 semantic tests (`dollar_root_names_the_top_module_and_skips_the_lexical_walk`
and the previous one).
- All four are caught. M1 and M3 are each pinned by a single unit test, and
nothing at the rename level pins them.
*Verifier (invariant 4; `check/` untouched).* 8 masked-corruption attacks
went into a scratch-only `check/qa_top_rooted.rs` over `dut_a` / `tb` /
`probe` (`tb.dut.buf_q` ×2 and `$root.tb.dut.buf_q`). All 8 behaved: three
honest edit sets verify, and every corrupt one is refused:
- a leaf rename missing each one of the 3 path segments, or missing the
declaration;
- a top-module rename missing each one of the 3 heads, or also renaming a
local `logic tb`;
- an instance rename missing each segment.
*Opentitan* (`~/.cache/lucisv-eval/ot`, read-only, `git status` clean before
and after):
- **`lucisv check --no-cache hw`.** Master 51b975b, built in a scratch `git
worktree` that has since been removed, and this branch both print 1 158
lines. stdout and stderr are byte-identical.
- **`--select undeclared-identifier`.** Identical, 7 findings.
- **`find_references` at 48 seeded random positions.** Half of them follow a
`.`, over `hw/ip/{keymgr_dpe,aes,uart,i2c}`. Before and after are
byte-identical.
- **Targeted top-rooted positions.** These were `pwrmgr_if.sv:191`
`tb.dut.u_slow_fsm…`, and `otp_ctrl_if.sv:169/287` and `tb.sv:248` under
`top_earlgrey/ip_autogen/{pwrmgr,otp_ctrl}`. Every difference is a segment
of a top-rooted path that now has references where it had none. For
example, `gen_partitions` went from no symbol to 12 references (10 force
and release lines, `tb.sv` and the RTL label), and `u_slow_fsm` went from
none to 4.
- **No other names changed.**
*`FACTS_FORMAT` 22.* The server ran over one fixture first with master's
binary (format 21), then with this branch. The new server analysed every
file afresh, with no `cached:` lines, and answered with the new references.
A second run of the new server read its own cache. The unit tests
`index_cache.rs:846` and `qa_m6.rs:367` already reject every older format.
*Code.*
- No new `unwrap`, `expect` or `panic`. The index arithmetic in `paths.rs`
`path_head` and `matching_open` is guarded.
- Production lines: `resolve.rs` 586, which is under 600 but at the mark, so
the next arm goes in a module. `resolve/root.rs` is 29, `paths.rs` 158,
`warnings.rs` 555, `external.rs` 224.
- `warnings.rs::unresolved_candidate_warnings` is now about 79 lines,
including its doc comment. That is just under the 80-line investigate mark
(Info).
*Findings*
- **F1 (High): silent wrong rename and silent miss when a module and a
package share the root's name.** Location: `vlog_semantic/src/workspace/external.rs:337-342`
(`follow_one`, the multi-segment branch).
- What `root_units` guards: only the bare head path `tb`.
- What it misses: the next segment's path `tb::dut` folds `tb` and asks
`member_chain` on the hierarchical surface, which answers from the
package.
- Repro: `module tb; dut_a dut (); endmodule`, `package tb; logic dut;
endpackage`, and `other.sv`: `initial force tb.dut.x = 0;`.
- Renaming the package's `dut` to `d2` rewrites the path to
`tb.d2.x`, which is wrong because the path names the module's
instance. No warning.
- Renaming the module's instance `dut` to `u_dut` leaves the path, also
with no warning, because it resolved to a different declaration.
- Before §65.4 neither edit touched the path, and the path was warned
about.
- The same root cause makes `pk.x`, with a package `pk` and no module
(illegal code), resolve into the package, and renaming the package
member rewrites it (A3/A4, Low on their own).
- This contradicts the Design bullet "Only a module or an interface is a
root".
- Suggested direction, the dev's to choose: apply the instantiable check
to the first hop of a hierarchical candidate rooted at a top. Then add a
rename-level test, because M1 is caught only by the semantic suite.
- **F2 (Medium, a documented limit, but a silent wrong rename): an imported
package variable used as a head, next to a same-named module.** Location:
`vlog_semantic/src/resolve.rs:408` (`head_site` roots on
`ExternalCandidate` as well as on `NotFound`).
- Repro: `package p; typedef struct packed {logic field;} s_t; s_t cfg;
endpackage`, `module cfg; logic field; endmodule`, and
`user.sv`: `import p::*; assign o = cfg.field;`.
- The head `cfg` resolves to `p::cfg`, the package variable, but the tail
`field` resolves to the module's `field`.
- Renaming the module's `field` to `fld2` rewrites `cfg.field` to
`cfg.fld2` with no warning. Before, the tail had no reference.
- The head and its tail disagree about the root, which is detectable. The
tail could carry the head's import paths first (`p::cfg::field`, then
`cfg::field`), or rooting could be refused when the head's own answer is
not a unit.
- **F3 (Medium, loud): LSP rename misses the files of the path's middle
hops.** Location: `lucisv_server/src/state/sources.rs:235-285`
(`fan_out_of` / `want_declaration`; outside this lane's files, so this is a
Handshake request).
- The rename set holds the declaration, the reference postings and the
instantiation sites of the container. It does not hold the root's file
(`tb.sv`) or a middle hop's file. Inside the rename, the root is then
undeclared.
- Repro, fixture `ip/rtl/{core,dut_a}.sv`, `ip/dv/{tb,probe}.sv`, where
`probe.sv` has `force tb.dut.u_core.sig = 1'b0;`, under the default
folder scope:
- LSP references on `core.sv`'s `sig` list `probe.sv:2`.
- LSP rename of `sig` edits `core.sv` only and warns "probe.sv:2: a
hierarchical path through `sig` was not resolved…".
- Rename from the segment in `probe.sv` is refused with "`sig` is
declared outside the files lucisv indexes", which is misleading.
- The same happens for `buf_q` inside `g_sw`: references list
`probe.sv:2,3`, and rename edits the declaration only.
- `top_sig` (one hop) and `g_sw` (the label) rename fine.
- The Goal's own shape `tb.dut.u_x.sig` is the failing one, and most
opentitan force paths are deeper than one hop. The engine API (and so
`lucisv-mcp`) renames them correctly over the whole set.
- Not silent, because it is warned, but references and rename disagree
over LSP.
- **F4 (Low–Medium, by the §23.6 assumption): a head the binder cannot see
now roots silently.** Location: `vlog_semantic/src/resolve/root.rs:24`
(`path_head`) with `resolve.rs:408`.
- Before, these were the §65.1 path warning. Now each is renamed silently
through a same-named module:
- a class without `extends` whose `cfg` comes from a macro (A11:
`` `DECLARE_CFG `` then `cfg.en`);
- a module whose struct `st` comes from `` `DECL_STRUCT(st) `` (A12);
- a class in a package writing `tb.dut.x` (D2). That is illegal (a
package may not reference the hierarchy), but it is renamed anyway.
- A cheap narrowing: do not root inside a class scope. Opentitan's DV
classes all live in packages, where no head can legally be a top module.
- **F5 (Low, documented).** `undeclared-identifier` no longer reports an
unknown path head (`tbb.dut.x`), which is now an unresolved candidate. The
rename still warns, and the opentitan count is unchanged (7).
*Held (no finding).*
- **Locals shadow.** A local `tb` net (same file or another) shadows and is
warned. A forward-declared local instance `tb` shadows.
- **Labels and other heads.** A named block `blk` beats `module blk`. A
clocking block `cb.data`, a modport / interface port head and a `virtual
bus_if vif` head all stay local. A genvar or parameter head, and `f().x`,
are warned.
- **Classes.** An extending class leaves the head alone and warns.
- **`bind` and `$root`.** A `bind` head is warned (the BindScope funnel).
`$root.tb` with a local `tb` reaches the top, and `$unit::` is unaffected.
- **Renaming the root and its instance.** Renaming `tb` rewrites every head
and `$root.tb`, and skips local `tb`s. Two `module tb` is refused. A
colliding rename of a leaf, the instance or the top is refused (5 cases).
`tb.dut.x = y` renamed `x` → `y` correctly.
- **Arrays.** An instance array `u[2].x` is not descended and is warned.
`mem[3]` and the instance array name itself rename. A struct field through
`acc[1].rl` is warned.
- **Interfaces and upward names.** An interface top works, and so does an
upward module-name reference (`par.sig` from a child).
- **LSP references.** Correct with the declaring file open or closed. Under
`workspace` with two `tb`, they answer nothing and rename is refused.
- **H1.** The dedupe predicate is equivalent to the path scan's, and the
path scan's text prefilter trims newlines, so a multi-line path is not
lost.
*Fixes made by QA:* none. Scratch harnesses: `scratchpad/qa654/attack`
(case files `cases1–4.txt`), `refs_{new,base}`, `lspfx*`, `probe2.py`.
**2026-10-19 — QA agent (Opus), re-check after "rework after QA".**
**Verdict: pass for F1–F4 as reworked.** One new Medium finding needs the
lead's ruling (R1: a macro that is not item-level can declare the head), and
there are two Info notes. No QA fixes were made.
*Gates.* Every suite ran through the guard with exit 0.
- `cargo fmt --all --check` and `clippy --workspace --all-targets -D
warnings` are clean.
- Suites: `vlog_semantic` 416 (4 ignored), `vlog_refactor` 741 (6),
`lucisv_server` 1 875 (40), `lucisv_mcp` 383 (4), `vlog_linter` 673 (0).
All 0 failed, and every count matches the work log.
*The old attacks, re-run against the new build* (`cases1–4`, plus LSP
`lspfx`, `lspfx2`).
- **F1 is fixed.** B12 (a module `tb` beside a package `tb`): renaming the
package's `dut` or the module's instance `dut` now leaves `tb.dut.x` and
warns about it, both ways. A3 and A4 (`pk.x` through a package) now warn,
and the segment refuses.
- **F2 is fixed.** A1: the imported `cfg` keeps its head. Renaming the
module's `field` leaves `cfg.field` and warns, and the segment has no
reference.
- **F4 is fixed.** A11 (a class with a macro member), A12 (a macro item in a
module) and D2 (a package class) are all warned again, as before §65.4.
- **F3 is fixed.** The three-hop `tb.dut.u_core.sig` renames over LSP from
the declaration and from the segment: 2 edits in 2 files, equal to the
references. So does the generate-block `buf_q` (3 edits in 2 files). Under
`workspace` scope with two `tb`, the segment refusal now says "segment of
a hierarchical path…".
- **Every other round-1 case is byte-identical to round 1.** That covers
B1–B11, D1, D3–D6, `$root`, the shadows, the collisions and the arrays.
*New attacks.*
- **F3's wider set (`lspfx4`).**
- The fixture puts an unrelated `sig` in every hop file: `tb.sv` (a local
`sig`, plus `dut.sig` and `dut.u_core.sig`), and `dut_a.sv` (its own
`sig`, plus `module helper` with a `sig`).
- Renaming `core`'s, `dut_a`'s or `tb`'s `sig` over LSP edits exactly the
references, and the engine over the whole set gives the same edits.
- `helper` is never touched, and neither is the unrelated `sig` in any
hop file.
- **A macro beside a head that is not item-level** (`cases5.txt`). These
are the R1 cases:
- E1: `` initial begin `DECL_LOCAL(st) st.a = 1; end `` beside `module st;
logic a;`. Renaming `st.a`'s `a` to `b` rewrites `st.a` to `st.b`
silently.
- E2 and E6: the same inside a task body and a function body.
- E3: `` module user (`MY_PORTS, output logic o); … bus.data `` beside
`module bus`. The rename rewrites it silently.
- **Macro shapes that hold or are warned.**
- Held: a macro in a non-ANSI port region (E4), a macro at file scope
(E5), and a macro used as a data type (E8).
- Rooted, and correctly so: a macro in a *sibling* generate block (E7) is
not in the head's lexical chain.
- A macro inside a modport list (E9) still roots. A modport declares no
variables, so this is no finding.
*Mutations* (scratch copy, re-synced):
- M5: `roots_at_top` without its class check. Caught by 1 semantic test and
`qa_f4_…`.
- M6: `roots_at_top` without its macro check. Caught by the same two tests.
- M7: `design_unit`'s later-hop "never a package" clause removed. **Not
caught** by any of the three suites (Info). A later hop's unit is an
instance's or a variable's type, and a module and package sharing a name
is already refused by the mixed check. So the clause looks unreachable
short of an instance of a package (malformed code). Either pin it with
such a test or drop it.
*Opentitan* (read-only, `git status` clean):
- **`lucisv check --no-cache hw`.** Against master 51b975b (scratch
worktree, removed afterwards), stdout and stderr are byte-identical, 1 158
lines each. `--select undeclared-identifier` is identical.
- **`find_references` spot checks.** The 48 seeded positions are identical
to master. The round-1 top-rooted positions (`pwrmgr_if.sv:191`,
`otp_ctrl_if.sv:169/287`) now answer exactly as master, because those
interfaces import `uvm_pkg::*` and the owner's conservative ruling applies.
- **Info:** on opentitan's DV interfaces the feature is therefore dormant;
every one imports a package.
*Code.*
- No new `unwrap`, `expect` or `panic`.
- Production lines: `resolve.rs` 587 (at the mark), `resolve/root.rs` 38,
`external.rs` 240, `workspace/path_units.rs` 50, `state/sources.rs` 176.
*Findings*
- **R1 (Medium, silent wrong rename; the lead to rule): a macro that is not
item-level can declare the head.**
- Location: `vlog_semantic/src/resolve/root.rs:40` (`roots_at_top`) and
`bind/item.rs` (only `ItemKind::MacroItem` sets `macro_items`).
- What escapes it:
- a macro statement in a `begin`/`end`, task or function body, where a
block-item declaration is legal (E1, E2, E6);
- a macro in an ANSI port list (E3).
- These root the head at a same-named module and rename through it
silently. Before §65.4 they were warned about.
- Narrowing would follow the same rule as F4: a macro statement in any
enclosing procedural scope, and a macro in the port list, also count as
doubt.
- The coordinator's brief says statement macros were left out by design.
E1–E3 show that they can declare the head, so the trade-off is the
lead's call. It needs a module sharing the head's name, which is rare
in RTL.
## Review
**2026-10-19 — lead.** Accepted after two reworks. QA (Opus) found four
silent-wrong-rename shapes (F1 a package sharing the root's name; F2 an
imported head beside a same-named module; F4 heads the binder cannot see)
plus the LSP rename set missing the middle hops (F3); its re-check found R1
(a statement-level or port-list macro declaring the head). All fixed with
tests built from QA's repros; QA's cases1–6 re-run against the final build
are each warned or correctly renamed. Owner's ruling: stay conservative —
a head with an import candidate (e.g. `import uvm_pkg::*` with uvm_pkg not
in the project) is doubt and not rooted, so opentitan's DV force paths stay
warned exactly as before; the feature applies where the root is provable.
`lucisv check hw` byte-identical to master. Granted handshakes: `rename/
warnings.rs` (H1, said once), `lucisv_server/src/state/sources.rs` (F3),
the message in `rename/mod.rs`. H2 (completion after `tb.`) deferred as
TODO §65.8.
+2 -1
View File
@@ -151,7 +151,7 @@ what a change on the pointed-to side must not silently break.
| `lucisv_server ◀──▶ vlog_semantic` | handshake | Three later additive performance surfaces: **`DeclLines` / `Def::lines`** record declaration and detail lines at index time (`FACTS_FORMAT` 3 → 4); **`WorkspaceIndex::absorb`** folds a scan batch with one merge rather than one merge per file; and **`WorkspaceIndex::files_spelling`** finds external uses by spelling, resolved or not, for rename's dangling-use refusal. The first feeds hover-line-index, the second scan-interleave, and the third refactor-rename's six-rung fan-out. Changing the facts codec, reference-fact census or merge semantics breaks those consumers. |
| `lucisv_server ──▶ vlog_refactor` | depends | `prepare_rename`/`rename`, `find_references`, the port refactorings, `organize_imports`, `extract_module`, `inline_module`, `RefactorEdit::{edits,warnings,created}`, `rename_traced_with(files, known: &dyn KnownFacts, …)` (perf5r-scope-reuse, 2026-09-09: the engine may build its index from a caller's record for a file **only** when `known.facts_for(path, text)` answers for exactly these bytes — the server answers from the index cache's store entry, record and FNV-1a content hash read from one place, never from the workspace index's record; a reused file is parsed anyway if a later stage reads its `Semantics`; `rename_traced` is the door with nothing known), `rename_traced` + `RenameTrace`/`VerifyTrace`/`Stage` (perf5-p2: the rename with its stage timings and parse counts as an out parameter; `rename` is the same call with a trace nobody reads; the server logs one `timing: rename trace …` line under `--verbose` only), the parsed-input selectors `port_action_modules_in`/`imported_packages_in`/`extract_site_in`/`inline_site_in` (perf5-p1: the offer paths hand the document's own tolerant parse and diagnostics; the text forms are thin wrappers kept for standalone consumers and the every-offset parity test; a large-file buffer still takes the text form), `instantiation_plan`/`render_with`/`module_definition` (the inline instantiation ghost, signature help, inlay hints — the completion popup stopped consuming them 2026-08-30, names-only tier). Promise consumed: never a partial edit — `Ok` verified whole, `Err` is a sentence. |
| `lucisv_server ◀──▶ vlog_refactor` | handshake | Request-scope selectors added for the performance wave: `prepare_rename_here` must produce the same answer/refusal text as whole-scope `prepare_rename`; `rename_name_at` must name the target that the rename engine acts on; `port_action_modules` and `enclosing_module` must name every module the corresponding port action/command can edit. The server uses those names to choose an index-derived file set; `extract_site`, `inline_site` and `imported_packages` also name source requirements. **`rename_preflight(semantics, offset, new_name)` (perf5r-preflight, 2026-09-08)** owes whole-scope `rename` the same *refusal* text one-directionally — it may always stand aside with `Ok(())` and never invents a refusal — and deliberately reads no workspace index (unlike `prepare_rename_here`): only refusals that are a pure function of the request buffer's own text (the new-name check, no symbol here, an unresolved or inherited-candidate reference, an unspelled declaration, the same name at a non-file-scope declaration); every index-answered refusal stays on the slow road. The engine remains the authority, and every selector must supply a superset of files needed for edits and refusals (inline gap: §2.9-33). |
| `lucisv_server ──▶ vlog_formatter` | depends | `format_source`, `format_range`/`LineRanges` (range, ranges, on-type formatting), `Config`, `fence::protected_regions` (quick-fix filter). |
| `lucisv_server ──▶ vlog_formatter` | depends | `format_source`, `format_selection`/`LineRanges` (range, ranges, on-type formatting — since TODO §66.2, 2026-11-09; `format_range` is now the CLI's `--lines` and the engine's own fallback for module/package-level selections), `Config`, `fence::protected_regions` (quick-fix filter). |
| `lucisv_server ──▶ vlog_linter` | depends | `run`, `lint` + `LintContext::from_parse` (lints from the `Document`'s own parse — one-parse), `default_rules`, `apply_fixes`, `rule_by_name`. Same three promises the CLI relies on. |
| `lucisv_mcp ──▶ lucisv_core, vlog_parser, vlog_semantic, vlog_refactor, vlog_formatter, vlog_linter` | depends | The MCP block (2026-09-23, `docs/mcp/PLAN.md`, `TODO-MCP.md`): `lucisv-mcp` composes the six libraries through their public APIs only — `Discovery`/`filelist`/`walk`/`content_hash`/`write_atomic` (core); `tokenize`, `parse_tolerant`, `parse_source` (strict, the structural edits' rule 1), `LineIndex`, `defines`, the AST (`Item`/`ItemKind`, `Meta::leading`, `Connections`), `PARSE_STACK_SIZE` (parser); `analyze`, `IndexBuilder::{add_file, add_facts}`, `WorkspaceIndex::{absorb, fingerprint, units, members_of, member_in, instantiations, workspace_symbols, find_define, files_mentioning, …}`, `resolve_external`, `FileFacts::{of, decode}`, `FACTS_FORMAT` (semantic); `rename`, `add_port`, `remove_port`, `find_references`, `instantiation_plan`, `module_definition`, `enclosing_module` (refactor); `format_source`/`fence` (formatter); `LintContext::from_parse`, `lint_with`, `select_rules`, `apply_fixes`, `rules_markdown`, `MentionOracle` (linter). **Never `lucisv_server`** (bin-only) and never `lsp-types`. Feature READMEs `docs/features/mcp-*`. **M7 (2026-09-23, the lean catalogue):** nine tools; `diff::unified`, `format_range` and the cursor refactorings (`expand_wildcard`, `convert_to_ansi`, `organize_imports`, `inline_module`, `propagate_ports`, `extract_module`) are no longer called — they stay in the CLI and the server. |
| `lucisv_server ──▶ lsp-server / lsp-types` | depends | The transport (synchronous, no async runtime) and the protocol data model. Both pinned exactly. cancel-request additionally relies on `lsp-server 0.10.0`'s stdio transport being a **rendezvous channel** (its own forwarder queue exists because of it) — a version bump must re-read that crate's `stdio.rs`. |
@@ -429,6 +429,7 @@ graph LR
| `corpus-bugs ──▶ corpus-check` | depends | Fixes exactly the four root causes A–D the corpus check catalogued; measured back to 0 verification errors. |
| `range-formatting ──▶ format-fences` | depends | A range is "an inverted fence": reuses `Doc::Verbatim`, `fence::collect`/`region_at`, and two helpers widened to `pub(crate)` (`line_start`, `with_trailing_comments`) — the only fence.rs change. |
| `range-formatting ──▶ spans` | depends | The planner selects items by span/line. |
| `selection-formatting ──▶ range-formatting / format-fences / lucisv-server` | depends | (2026-11-09, TODO §66.2) `format_selection` lays out the smallest run of sibling items/statements a line span covers at its written indentation and splices it in; defers to `format_range` for a module/package-level target; consumes `fence::collect`/`with_trailing_comments` and `Fmt::item_seq`/`stmt_seq`; adds `Printer::print_at` and `FormatError::Selection`. `verify.rs`, `range.rs`, `fence.rs` untouched. The server's range, ranges and on-type `;` requests all go through it. |
| `alignment ──▶ spans` (+ name-spans) | depends | Anchor columns are derived from `name_span` byte offsets + the source text; deliberately **no** token-level representation of spacing. `doc.rs`/`printer.rs`/`verify.rs` untouched. |
| `alignment ──▶ format-fences` | depends | `fence::region_at` (via `Fmt::is_fenced`) keeps fenced items out of alignment groups. |
| `shared-fence-filter ◀──▶ linter-core / server-lint` | handshake | Closes server-lint Handshake 3: `fence::protected_regions` + `is_protected` become the **one** answer to "what may an automatic fix not touch"; CLI `--fix` and server quick fixes both call it; `vlog_linter` itself deliberately stays fence-blind. |
+24
View File
@@ -5,6 +5,30 @@ 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.63.0 — 2026-11-09
- **Format Selection formats just what you selected.** Select an `always`
block, a `case` statement or a few statements and only that block is laid
out, starting at the indentation it already has; the code around it is
left alone. It used to re-lay the whole enclosing module or top-level
block.
- **Format Selection works while another part of the file is broken.** A
syntax error outside the selection no longer stops it.
- **`Ctrl+/` (`Cmd+/`) toggles comments** on the current line or every
selected line, and brackets and quotes auto-close.
## 0.62.0 — 2026-10-19
- **Find All References and Rename follow paths from a top-level module.**
`tb.dut.u_core.sig` in a testbench file is now a reference to `sig`, and
renaming `dut`, `u_core` or `sig` updates the path — whenever lucisv can
tell for certain that `tb` is a top-level module. Where it can't (the
name might come from a package the project doesn't contain, such as
`uvm_pkg`), the path is left alone and the rename says so, as before.
- The `lucisv.index.scope` setting now explains that renaming a module that
is also instantiated outside the indexed folders leaves those
instantiations unchanged.
## 0.61.0 — 2026-10-14
- **Show Call Hierarchy works from where your cursor is.** It used to answer
+13 -1
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.61.0**. Its platform packages include
The current release is **0.63.0**. Its platform packages include
`lucisv-server`, the `lucisv` command-line tool and `lucisv-mcp` (see
[Agents (MCP)](#agents-mcp)):
@@ -406,6 +406,18 @@ Every nesting color is a proper VS Code theme color:
}
```
## Release 0.63.0 highlights
Version 0.63.0 makes **Format Selection** format just the block you selected,
at the indentation it already has, and makes `Ctrl+/` (`Cmd+/`) toggle
comments on the selected lines.
## Release 0.62.0 highlights
Version 0.62.0 lets references and rename follow a hierarchical path from a
top-level module (`tb.dut.u_core.sig`) whenever the root is certain, and
says so plainly where it is not.
## Release 0.61.0 highlights
Version 0.61.0 makes Show Call Hierarchy answer from wherever the cursor is
@@ -0,0 +1,24 @@
{
"comments": {
"lineComment": "//",
"blockComment": ["/*", "*/"]
},
"brackets": [
["(", ")"],
["[", "]"],
["{", "}"]
],
"autoClosingPairs": [
{ "open": "(", "close": ")" },
{ "open": "[", "close": "]" },
{ "open": "{", "close": "}" },
{ "open": "\"", "close": "\"", "notIn": ["string", "comment"] },
{ "open": "/*", "close": " */", "notIn": ["string"] }
],
"surroundingPairs": [
["(", ")"],
["[", "]"],
["{", "}"],
["\"", "\""]
]
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "lucisv",
"version": "0.61.0",
"version": "0.63.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "lucisv",
"version": "0.61.0",
"version": "0.63.0",
"license": "MIT",
"dependencies": {
"vscode-languageclient": "9.0.1"
+6 -4
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.61.0",
"version": "0.63.0",
"publisher": "guoliangchen",
"author": "Guoliang Chen",
"license": "MIT",
@@ -208,7 +208,8 @@
"extensions": [
".v",
".vh"
]
],
"configuration": "./language-configuration.json"
},
{
"id": "systemverilog",
@@ -219,7 +220,8 @@
"extensions": [
".sv",
".svh"
]
],
"configuration": "./language-configuration.json"
}
],
"grammars": [
@@ -432,7 +434,7 @@
"Index every folder in the workspace, whatever is open."
],
"default": "folder",
"markdownDescription": "How much of your project the workspace index scans. **`folder` (the default) indexes only the folders your open files live in** — plus everything under them — which is what keeps a huge project from costing minutes on every scan. Opening a file in another folder widens the index to that folder as well, so the scope grows as you work; it never shrinks while the editor is open. **Until it reaches a folder, symbols in that folder do not exist as far as the server is concerned**: go-to-definition, workspace symbol search, call and type hierarchy, find-references and rename all answer within the current scope only. Set to `workspace` to index every workspace folder up front, as lucisv always did before this setting existed — the right choice for a small project or a fast machine. A `#lucisv.filelist#` overrides this setting entirely: a project file defines the scope."
"markdownDescription": "How much of your project the workspace index scans. **`folder` (the default) indexes only the folders your open files live in** — plus everything under them — which is what keeps a huge project from costing minutes on every scan. Opening a file in another folder widens the index to that folder as well, so the scope grows as you work; it never shrinks while the editor is open. **Until it reaches a folder, symbols in that folder do not exist as far as the server is concerned**: go-to-definition, workspace symbol search, call and type hierarchy, find-references and rename all answer within the current scope only — so renaming a module that is also instantiated outside the scope (a top-level `*_top.sv` two blocks away) leaves those instantiations unchanged; open such a file first, or switch to `workspace`, before a rename across blocks. Set to `workspace` to index every workspace folder up front, as lucisv always did before this setting existed — the right choice for a small project or a fast machine. A `#lucisv.filelist#` overrides this setting entirely: a project file defines the scope."
},
"lucisv.index.scopeDepth": {
"type": "number",
+10 -5
View File
@@ -197,9 +197,11 @@ server.stdin.end(
params: { textDocument: { uri }, options: { tabSize: 2, insertSpaces: true } },
}),
// Multi-range formatting (LSP 3.18): two ranges, one round trip. Lines 2
// and 8 of SOURCE (0-based 1 and 7) are `wire a;` and `initial fork`; only
// the first moves under `indent = 4`, so the answer proves both that the
// request is served and that it left the range between them alone.
// and 8 of SOURCE (0-based 1 and 7) are `wire a;` and `initial fork`. Each
// named block is laid out where it stands (selection formatting keeps a
// block's own leading whitespace): the wire is already laid out, the fork
// is re-laid under `indent = 4` from its two written spaces, and the
// `initial begin` between them keeps its bytes.
frame({
jsonrpc: '2.0',
id: 7,
@@ -389,8 +391,11 @@ server.on('close', (code) => {
fail(`expected one edit from rangesFormatting, got ${JSON.stringify(ranged.result)}`);
}
const partial = ranged.result[0].newText;
if (!partial.includes('\n wire a;')) {
fail(`the named line was not laid out:\n${partial}`);
if (!partial.includes('\n initial\n fork\n c = 1;\n join\n')) {
fail(`the named block was not laid out at its own indentation:\n${partial}`);
}
if (!partial.includes('\n wire a;')) {
fail(`a named line must keep the indentation it was written at:\n${partial}`);
}
if (!partial.includes('\n initial begin')) {
fail(`a line no range named must keep its own bytes:\n${partial}`);
+24 -6
View File
@@ -105,16 +105,34 @@ under `docs/features/` that hold the detail. Not a commit log, not a round log.
## 3. Gate
All three must be clean before anything is built for distribution:
Every gate must be green before anything is built for distribution:
```bash
cargo fmt --check
cargo clippy --all-targets
cargo test --workspace
tools/gates.sh # logs in target/gates/<timestamp>/
```
Optionally re-run the real-world corpus check and quote the result in the
changelog (`tools/corpus_fetch.sh` once, then `tools/corpus_check.sh`); a
It runs each gate as a separate `tools/guard.sh` step with its own clock,
memory limit and log: `cargo fmt --all -- --check`, `cargo clippy
--workspace --all-targets -- -D warnings`, the test build (`cargo test
--workspace --all-targets --no-run`), `cargo test -p <crate> --all-targets`
for each workspace member in turn, the doc-tests (`cargo test --workspace
--doc`), the corpus gate (`scripts/corpus_gate.sh` over
`~/.cache/lucisv-corpus`, as CI runs it; skipped with a note when the corpus
is absent — fetch it once with `tools/corpus_fetch.sh ~/.cache/lucisv-corpus`)
and the extension's `node --test editors/vscode/*_test.js`. It prints one line
per step start and end, then a table (step, result, seconds, passed/failed,
log); it exits non-zero if any step failed. A step the guard killed is
retried once and reported as `KILLED → retried → pass|fail` — a kill that
passes on retry is still worth a line in the release notes' working log,
and one that does not is a release blocker like any failure. The first
attempt's log is kept as `<step>.killed.log`.
`tools/gates.sh --only suites,docs` or `--skip corpus` runs a subset
(`--list` names the steps, `--help` the options). Do not replace it with a
bare `cargo test --workspace`: that one command hid which binary stalled
(TODO §65.3, `docs/features/release-gates/README.md`).
Quote the corpus step's numbers in the changelog when they changed; a
verification error or a crash there is a release blocker by definition.
## 4. Build the artifacts
Executable
+237
View File
@@ -0,0 +1,237 @@
#!/usr/bin/env bash
# Run lucisv's release gates, each as a separate tools/guard.sh step.
#
# Steps, in order (names for --only/--skip):
# fmt cargo fmt --all -- --check
# clippy cargo clippy --workspace --all-targets -- -D warnings
# build cargo test --workspace --all-targets --no-run
# suite:<crate> cargo test -p <crate> --all-targets, one step per crate of
# the workspace Cargo.toml `members` ("suites" selects all)
# docs cargo test --workspace --doc
# corpus cargo build --release -p lucisv, then scripts/corpus_gate.sh
# over ~/.cache/lucisv-corpus as CI does (skipped, with a
# note, when that directory is absent; -c overrides it)
# node node --test editors/vscode/*_test.js
#
# Each step's output goes to its own log under the log dir (default
# target/gates/<timestamp>/, -o overrides); the terminal gets one line per
# step start and end, then a summary table. A step the GUARD killed (exit
# 137 plus guard.sh's "killing" line in its log) is retried once and shows
# as "KILLED → retried → pass|fail"; an ordinary failure is not retried.
# The per-step -t/-m limits are in limits() below, sized from measured runs
# (docs/features/release-gates/README.md has the numbers).
#
# Why separate steps: the combined `cargo test --workspace` hid where a stall
# was (TODO §65.3); a step per crate shows which binary hung, keeps its log,
# and a retry costs one crate, not the whole suite.
#
# Usage: tools/gates.sh [-o log-dir] [-c corpus-dir] [--only a,b] [--skip a,b]
# [--list] [--help]
# tools/gates.sh # everything
# tools/gates.sh --only suites,docs # the per-crate suites and doc-tests
# tools/gates.sh --skip corpus # all but the corpus gate
#
# Exit status: 0 if every selected step passed (or was skipped for a missing
# corpus), 1 if any failed or stayed killed, 2 on a usage error.
# Standard tooling only (bash, awk, date, sed).
set -u
repo_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$repo_root" || exit 2
log_dir=
corpus=$HOME/.cache/lucisv-corpus
only=
skip=
usage() {
sed -n '/^# Usage:/,/^# Exit status/p' "$0" | sed '$d; s/^# \{0,1\}//'
}
while [ $# -gt 0 ]; do
case $1 in
-o | -c | --only | --skip)
# A missing or empty value is a usage error, never "no filter".
if [ $# -lt 2 ] || [ -z "$2" ]; then usage >&2; exit 2; fi
case $1 in
-o) log_dir=$2 ;;
-c) corpus=$2 ;;
--only) only=$2 ;;
--skip) skip=$2 ;;
esac
shift 2 ;;
--list) list=1; shift ;;
-h|--help) usage; exit 0 ;;
*) usage >&2; exit 2 ;;
esac
done
# The workspace crates, from the root Cargo.toml `members` list: each
# member directory's package name. Comments are dropped, a one-line list
# and a glob member (`crates/*`) work; an empty answer is fatal below.
crates() {
local pattern dir
for pattern in $(awk '/^members *= *\[/ { f = 1 } f { print } f && /\]/ { exit }' Cargo.toml |
sed 's/#.*//; s/^members *= *//' | tr ',[]' '\n\n\n' | tr -d ' "'); do
for dir in $pattern; do
[ -f "$dir/Cargo.toml" ] || continue
sed -n 's/^name *= *"\(.*\)"/\1/p' "$dir/Cargo.toml" | head -1
done
done
}
all_steps() {
local c
echo fmt clippy build
for c in $(crates); do echo "suite:$c"; done
echo docs corpus node
}
# Does step $1 match the comma list $2? "suites" matches every suite:<crate>.
in_list() {
local item
for item in $(echo "$2" | tr ',' ' '); do
[ "$item" = "$1" ] && return 0
[ "$item" = suites ] && case $1 in suite:*) return 0 ;; esac
done
return 1
}
selected() {
[ -n "$only" ] && ! in_list "$1" "$only" && return 1
[ -n "$skip" ] && in_list "$1" "$skip" && return 1
return 0
}
# Guard limits per step: "<seconds> <GB>". Measured on the release Mac
# 2026-10-19 from a cold target/ (seconds, peak tree RSS): fmt 3 s; clippy
# 20 s, 1.6 GB; build 31 s, 2.6 GB; each small suite <= 3 s, <= 0.15 GB;
# lucisv_server 19 s, 1.1 GB; lucisv_mcp 22 s, 1.4 GB; docs 1 s; corpus
# (release build + score) 30 s, 1.2 GB; node 1 s. The clocks allow a 12x
# slowdown (what a busy syspolicyd costs, §65.3) on top, with a floor of
# two minutes; memory is the peak plus headroom. README has the runs.
limits() {
case $1 in
fmt | node) echo "120 2" ;;
clippy) echo "900 6" ;;
build) echo "900 8" ;;
suite:lucisv_server | suite:lucisv_mcp) echo "600 4" ;;
suite:*) echo "300 4" ;;
docs) echo "300 2" ;;
corpus) echo "900 6" ;;
esac
}
# The command for step $1, into the array `cmd`.
set_command() {
case $1 in
fmt) cmd=(cargo fmt --all -- --check) ;;
clippy) cmd=(cargo clippy --workspace --all-targets -- -D warnings) ;;
build) cmd=(cargo test --workspace --all-targets --no-run) ;;
suite:*) cmd=(cargo test -p "${1#suite:}" --all-targets) ;;
docs) cmd=(cargo test --workspace --doc) ;;
corpus) cmd=(bash -c 'cargo build --release -p lucisv && scripts/corpus_gate.sh "$1"'
corpus-gate "$corpus") ;;
node) cmd=(node --test editors/vscode/*_test.js) ;;
esac
}
# "passed N failed M" from a step log, where that is cheap to read off:
# libtest's "test result:" lines, node's "# pass"/"# fail" (TAP; node 22+
# prints "ℹ pass" instead), the corpus JSON.
counts() {
awk '
/^test result:/ { for (i = 1; i <= NF; i++) { if ($(i+1) ~ /^passed/) p += $i; if ($(i+1) ~ /^failed/) f += $i }; n = 1 }
($1 == "#" || $1 == "ℹ") && NF == 3 && $2 == "pass" { p += $3; n = 1 }
($1 == "#" || $1 == "ℹ") && NF == 3 && $2 == "fail" { f += $3; n = 1 }
/^\{"passing":/ { match($0, /"passing":[0-9]+/); pp = substr($0, RSTART + 10, RLENGTH - 10)
match($0, /"total":[0-9]+/); t = substr($0, RSTART + 8, RLENGTH - 8)
p += pp; f += t - pp; n = 1 }
END { if (n) printf "%d/%d", p, f; else printf "-" }' "$1"
}
# Run step $1 once under the guard into log $2, ending the log with a
# "gate exit N" line. No gate reads stdin, so it is /dev/null.
run_once() {
local step=$1 log=$2 lim secs gb
lim=$(limits "$step")
secs=${lim% *} gb=${lim#* }
set_command "$step"
{
echo "\$ tools/guard.sh -t $secs -m $gb -- ${cmd[*]}"
tools/guard.sh -t "$secs" -m "$gb" -- "${cmd[@]}" </dev/null
echo "gate exit $?"
} >"$log" 2>&1
}
status_of() { sed -n 's/^gate exit //p' "$1" | tail -1; }
was_killed() { [ "$(status_of "$1")" = 137 ] && grep -q '^guard.sh: .*killing' "$1"; }
if [ -z "$(crates)" ]; then
echo "gates.sh: no workspace crates found in Cargo.toml members" >&2
exit 2
fi
[ "${list:-0}" = 1 ] && { all_steps | tr ' ' '\n'; exit 0; }
steps=$(all_steps)
for s in $(echo "$only,$skip" | tr ',' ' '); do
[ "$s" = suites ] && continue
echo "$steps" | tr ' ' '\n' | grep -qx -- "$s" - || { echo "gates.sh: unknown step '$s' (see --list)" >&2; exit 2; }
done
picked=0
for step in $steps; do selected "$step" && picked=$((picked + 1)); done
if [ "$picked" = 0 ]; then
echo "gates.sh: the selection runs no step (see --list)" >&2
exit 2
fi
[ -n "$log_dir" ] || log_dir=target/gates/$(date +%Y%m%d-%H%M%S)
mkdir -p "$log_dir" || exit 2
summary=$log_dir/summary.txt
: >"$log_dir/steps.tsv"
echo "gates: logs in $log_dir"
failed=0
rows=
for step in $steps; do
selected "$step" || continue
log=$log_dir/$(echo "$step" | tr ':' '-').log
if [ "$step" = corpus ] && [ ! -d "$corpus" ]; then
echo "skipped: no corpus at $corpus (tools/corpus_fetch.sh \"$corpus\")" >"$log"
echo " skip $step (no corpus at $corpus)"
rows="$rows$step|SKIPPED (no corpus)|0|-|$log
"
continue
fi
echo " start $step ($(limits "$step" | sed 's/ / s, /') GB)"
t0=$(date +%s)
run_once "$step" "$log"
result=pass
[ "$(status_of "$log")" = 0 ] || result=fail
if was_killed "$log"; then
mv "$log" "${log%.log}.killed.log"
run_once "$step" "$log"
if [ "$(status_of "$log")" = 0 ]; then result="KILLED → retried → pass"
elif was_killed "$log"; then result="KILLED → retried → KILLED"
else result="KILLED → retried → fail"; fi
fi
t1=$(date +%s)
case $result in *pass) ;; *) failed=1 ;; esac
printf '%s\t%s\t%s\t%s\n' "$step" "$t0" "$t1" "$result" >>"$log_dir/steps.tsv"
echo " end $step: $result ($((t1 - t0)) s)"
rows="$rows$step|$result|$((t1 - t0))|$(counts "$log")|$log
"
done
{
printf '%-22s %-26s %6s %-13s %s\n' step result seconds passed/failed log
printf '%s' "$rows" | while IFS='|' read -r s r t c l; do
[ -n "$s" ] || continue
# printf pads by bytes; widen the column by what the arrows add.
w=$((26 + $(printf %s "$r" | LC_ALL=C wc -c) - $(printf %s "$r" | LC_ALL=en_US.UTF-8 wc -m)))
printf "%-22s %-${w}s %6s %-13s %s\n" "$s" "$r" "$t" "$c" "$l"
done
[ "$failed" = 0 ] && echo "gates: PASS" || echo "gates: FAIL"
} | tee "$summary"
exit "$failed"
+9 -3
View File
@@ -31,19 +31,25 @@ done
# Keep the command's stdin: a plain `cmd &` in a non-interactive shell
# gives the job /dev/null, which silently empties any stdin-fed `lucisv`.
exec 3<&0
# A CLOSED stdin (`<&-`, some launchers) would make both redirections fail
# and the command never run (exit 1, nothing executed); it gets /dev/null.
{ exec 3<&0; } 2>/dev/null || exec 3</dev/null
"$@" <&3 &
root=$!
start=$(date +%s)
# The command's process tree: descendants by parent pid, transitively.
# Single spaces only: the list becomes `ps -p a,b,c`, and macOS ps rejects
# the WHOLE list on an empty element ("a,,b") — which a doubled space made
# for any tree three levels deep (cargo → rustc → ld, a test spawning
# lucisv), summing 0 kB and silently disabling the memory limit (§65.3).
tree() {
local all="$1" next
while :; do
next=$(ps -axo pid=,ppid= | awk -v set=" $all " '
{ if (index(set, " " $2 " ") > 0 && index(set, " " $1 " ") == 0) printf "%s ", $1 }')
{ if (index(set, " " $2 " ") > 0 && index(set, " " $1 " ") == 0) printf " %s", $1 }')
[ -z "$next" ] && break
all="$all $next"
all="$all$next"
done
echo "$all"
}