Compare commits

...
14 Commits
Author SHA1 Message Date
lucioandClaude Opus 5.5 75d2d376cf Release 0.61.0: call hierarchy from anywhere with function/task nodes, type hierarchy inside classes, full-line references view in VS Code
ci / checks (push) Successful in 1m38s
ci / corpus (push) Successful in 31s
release / build-and-publish (push) Successful in 8m24s
Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); the notes are in CHANGELOG.md (## 0.61.0) and
editors/vscode/CHANGELOG.md. Gates on the tree: fmt and clippy -D warnings
clean, lucisv_server 1 862 passed 0 failed, per-crate suites green at
ca83f6f, node tests 8/8; CI checks green on 31b7db1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 14:56:33 -07:00
lucioandClaude Opus 5.5 31b7db16a3 LSP: call and type hierarchy answer from anywhere in a body; functions and tasks are call-hierarchy nodes
ci / checks (push) Successful in 1m38s
ci / corpus (push) Successful in 32s
Show Call Hierarchy was empty in VS Code unless the cursor sat on a module
name. prepareCallHierarchy now answers on an instance name (its module),
on a function/task declaration, call or end label (a FUNCTION/METHOD item
with data {kind,name,offset}), inside a function/task body (that one), and
inside a module/interface/program (the enclosing module). Function/task
items: incomingCalls = call sites grouped by the enclosing function/task or
unit, over the same files references reads; outgoingCalls = resolved
callees (system tasks and unresolved names skipped). A function's bare name
in its own body is its result variable, not recursion. Module items keep
instantiation edges, byte-identical. prepareTypeHierarchy answers the
enclosing class inside a class body and the base on `super`.

QA (Opus): old module answers identical at 3 137 positions; outline,
definition, references, hover unchanged at 1 340 queries; findings fixed in
a rework (outgoing over a closed 300-function package 3.0 s -> 18 ms). Two
e2e assertions that pinned the old null flipped (lead's handshake).
lucisv_server 1 862 passed, 0 failed; fmt, clippy -D warnings clean.
docs/features/call-hierarchy-everywhere.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 14:53:38 -07:00
lucioandClaude Opus 5.5 5e4af0be3d VS Code: Find All References with whole source lines (lucisv References view)
VS Code's built-in references pane cuts each preview to ~8 characters
before the match. lucisv.references.show runs the same reference and
definition providers and fills a tree view in the lucisv sidebar: one row
per file (current file first), one row per reference with the trimmed full
line and the identifier highlighted, the declaration marked; a click
selects the exact range. The setting lucisv.references.fullLineView
(default true) binds Shift+Alt+F12 to it in verilog/systemverilog editors
only; Shift+F12 peek is untouched. Closed files are read with
workspace.fs, so no didOpen reaches the server.

QA (Sonnet): PASS with 4 lows (recorded). Node tests 8/8. tools/RELEASING.md
must-ship list names every runtime module (lane handshake).
docs/features/vscode-references-view.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 14:14:11 -07:00
lucioandClaude Opus 5.5 41a90917bb Housekeeping: package-lock version follows the release and release.sh checks it; repository analysis refreshed to 0.60.0
ci / checks (push) Successful in 1m33s
ci / corpus (push) Successful in 33s
editors/vscode/package-lock.json said 0.10.2 since 0.10.2; it is 0.60.0
now, and tools/release.sh refuses to build when package.json or either
package-lock.json version differs from `lucisv --version`.
docs/repository-analysis.md: refreshed against 58520e5 (v0.60.0) — a status
row per release 0.50.0-0.60.0, nine MCP tools (five read-only), codec 21,
the generate-block and home-set contracts, the §55 split, and the current
open limits (§65.2-§65.6, review L-5-L-11, handshakes 31/32).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 13:38:04 -07:00
lucioandClaude Opus 5.5 4fae8fb63a TODO §55: split lucisv_server state/mod.rs by responsibility (pure move)
state/mod.rs 986 -> 63 production lines: document.rs (one analyzed
buffer), buffers.rs (open buffers), views.rs (closed-file view cache),
scope.rs (roots, settings, scope ladder), rescan.rs (scan and widen
protocol, 411), incremental.rs (one saved file re-indexed), sources.rs
(file sets for refactorings, 170). The 3 944-line inline test module moved
to state/tests/ (14 topic files). No function body changed; only forced
pub(super) widenings. Lead's line-multiset check: no code line lost or
added. CLAUDE.md measurement refreshed (2026-10-14); a stale test path in
server/tests/folders.rs corrected.

Gates on the merged tree: fmt and clippy -D warnings clean; lucisv_server
1 823 passed, 0 failed, 38 ignored (= before); the lane's workspace run 80
suites, 5 078 passed. Refactor dev Claude Fable 5.1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 13:38:04 -07:00
lucioandClaude Opus 5.5 ca83f6f99f Review lows L-1–L-4, L-12, L-13: end labels, duplicate generate labels, dotted comments, lex-failure fallbacks, file naming
- L-1: an unowned block's closing label is a use of a same-named block only
  for block constructs and only when it spells the construct's own opening
  label (use_block_end_label); a mismatched `end : a` or an `endfunction : g`
  beside block `g` records nothing.
- L-2: duplicate-declaration stays silent for two block labels only when
  both may be arms of one generate if/case; sibling `for` blocks and a
  procedural block beside a generate one are reported in either order.
  OpenTitan check: 1 158 findings, identical to 0.60.0.
- L-3: a block comment between `.` and the name is still dotted.
- L-4: a bind file that does not lex counts as binding (K2); a pasted
  fragment that does not lex is said, not skipped.
- L-12: no unchecked slice in rename/arms.rs.
- L-13: expand/ansi/inline/extract messages name files by Scope::name_of.

7 tests (L-3/L-4's fail with the fixes disabled). Per-crate suites under the
guard: 80 suites, 5 085 passed, 0 failed, 51 ignored (one combined run was
cut at 1 800 s in vlog_refactor/tests/corpus.rs with syspolicyd at 95 % —
the §65.3 stall).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 13:33:27 -07:00
lucioandClaude Opus 5.5 58520e586e Release 0.60.0: rename and references through generate block labels; rename warnings scoped to the renamed declaration
ci / checks (push) Successful in 1m37s
ci / corpus (push) Successful in 36s
release / build-and-publish (push) Successful in 8m2s
Version bump; the notes are in CHANGELOG.md (## 0.60.0) and
editors/vscode/CHANGELOG.md. TODO §65.1 plus the independent review's
H-1/H-2 and M-1/M-2 fixes. Gates on the tree: fmt and clippy -D warnings
clean, workspace lib/bins/tests 80 suites 5 078 passed 0 failed, node tests
6/6; doc-tests and the corpus gate run in CI.

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-07 01:01:23 -07:00
lucioandClaude Fable 5.1 b9ee399ac6 TODO §65: stabilization round 1 — generate-label rename/references, LSP references fan-out to the pd_main tops, the doc-test stall
ci / checks (push) Successful in 1m39s
ci / corpus (push) Successful in 35s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-30 01:44:39 -07:00
122 changed files with 17023 additions and 6312 deletions

No files matched your search

+128
View File
@@ -4,6 +4,134 @@ 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.61.0 — 2026-10-14
### Call hierarchy from anywhere, functions and tasks as nodes; full-line references in VS Code
(`docs/features/call-hierarchy-everywhere`, `docs/features/vscode-references-view`.)
- **`textDocument/prepareCallHierarchy` answers from any position in a
body.** It answered only on a module name, so Show Call Hierarchy was empty
almost everywhere. Now: an instance name prepares the instantiated module;
a function or task's declaration, call or end label prepares a
`Function`/`Method` item; a position inside a function or task body
prepares that function or task; one inside a module, interface or program
prepares the enclosing module. Module items answer exactly as before.
- **Functions and tasks are call-hierarchy nodes.** `incomingCalls` lists
every call site, grouped by the enclosing function or task (else the
module, interface, program, package or class), over the same files
`references` reads; `outgoingCalls` lists the resolved callees, skipping
system tasks and unresolved names. A function's own name read inside its
body (`clog2 = clog2 + 1`) is its result variable, not recursion. Calls
through `this.`, `super.`, a typed handle and an `import` resolve; virtual
dispatch and calls inside macro bodies are not modelled.
- **`textDocument/prepareTypeHierarchy`** answers the enclosing class
anywhere inside a class body, and the base class on `super`.
- **VS Code: Find All References with whole lines.** VS Code's references
pane starts each preview a few characters before the match. The extension's
new **References** view (lucisv sidebar) lists every reference's full line
with the identifier highlighted, grouped by file, the declaration marked;
`Shift+Alt+F12` opens it in Verilog/SystemVerilog editors while
`lucisv.references.fullLineView` is on (the default). Closed files are read
without opening them on the server.
### Review fixes and housekeeping
- The closing-label fallback of an unnamed block no longer attaches a
mismatched `end : a` (or an `endfunction : g` beside block `g`) to a
same-named block.
- `duplicate-declaration` reports sibling `for` generate blocks of one label,
and a procedural block beside a generate block in either order.
- Rename warnings: a comment between `.` and the name is still a path; a file
that fails to lex is warned about instead of skipped.
- Refactoring messages name a file by its path wherever another file shares
its base name (the `.*` expansion, ANSI conversion, inline and extract too).
- `lucisv_server`'s workspace state is split into seven modules (a pure
move); `tools/release.sh` refuses to build when the extension's
`package.json` / `package-lock.json` versions disagree with the binaries.
## 0.60.0 — 2026-10-08
### Rename and references through a generate block label
TODO §65.1, topo §2.9 row 43 (MCP-14). (`docs/features/generate-label-rename`.)
- **`rename` of a block label rewrites every path through it.** Renaming
`g_lane` in `for (…) begin : g_lane` used to rewrite the label alone,
leaving `g_lane[0].lane_q` (and `u_x.g_lane[1].sig` in another file)
naming a block that no longer existed, with no warning. The label, its
closing `end : g_lane`, and every path segment naming the block — bare,
indexed (`g[0].x`, `g[i].x`), nested (`g_a.g_b[2].x`), behind an instance
path from another file — are now one reference set, renamed all or
nothing; a spelling inside macro text or a string is a warning. A name
declared *inside* a block is likewise renamed through such a path. Named
procedural blocks: `begin : lbl`, `end : lbl` and `disable lbl;` (and the
`lbl: begin … end : lbl` form) are one set.
- **`find_references`** (LSP `textDocument/references`, `lucisv-mcp find
refs`) lists the declaration, the closing label and every segment, same
file and cross-file, with the declaring file open or closed.
- **`lucisv-mcp rename`** no longer refuses a `block`-kind declaration.
- Resolution changes every consumer sees: a `for` generate block's label is a
name of the enclosing module (its genvar is not); `generate … endgenerate`
is not a scope; `blk.x` and `arr[0].field` (a packed struct array) resolve
their tails; an unnamed `genblk1` still names nothing. The index cache
format moves to 21, so a 0.59.0 cache is rebuilt once.
- **A rename says so when a path it cannot resolve spells the name**: a
hierarchical path segment in any file of the rename's set that resolved to
no declaration (`tb.dut.gen_x[0].q`, rooted at a top module) is left
unchanged and warned about with its lines, for every kind of declaration;
and renaming a member one arm of a generate `if`/`case` declares warns
about the same-named member of the arm sharing its label.
- `duplicate-declaration` now also reports a block label beside a net,
variable, parameter or instance of the same name, and such a label is no
longer counted as a read of the net.
- Rename and port warnings name a file by its path whenever another file of
the set shares its base name (two `pwrmgr_if.sv` are two findable lines,
root-relative in `lucisv-mcp`), and a line a path warning names is not
repeated under `unresolved:`. Same-named members are warned about through
every enclosing same-label generate arm (`g.h.x`), and an escaped name's
unresolved paths are found too.
- **Rename warnings and mentions are about the renamed declaration.** For a
member of a module or interface (a net, variable, port, parameter, block,
…), a bare spelling of its name in a macro argument, a `` `define`` body, an
unstructured assertion, a comment or a string is reported only where it can
mean it: in the declaration's **home set** — the declaring file,
everything it `` `include``s, whatever includes it (transitively), and the
files the rename edits. In code, a spelling in the declaring file is
reported after a scope lookup finds the declaration there (an instantiating
module's own same-named signal is not); one in an included fragment always;
a `` `define`` body when the macro is invoked from the home set (through
other macros too — `ASSERT_DEFAULT_CLK`'s `clk_i`); a macro argument inside
a `bind` into the declaring module; and a bare use in the plain code of an
included fragment (`prim_util_memload.svh`'s `mem`) is named as a use the
rename could not edit. Reported wherever they are written: a dotted
spelling (`.state_q`, a possible hierarchical path); a bare macro argument
the macro carries to the declaration — after a `.` (`` `CONN(state_q)``
building `.state_q(state_q)`, `` `FORCE(state_q)`` building
`force u_m.state_q`), into a `bind` into the declaring module, or into a
macro lucisv has no definition of; and the body of a macro that expands to
such a `bind`. Not reported: a body whose spellings are only its own
parameter named like the declaration (unless the body also spells the name
after a `.`, or a default argument spells it), and a backtick inside a
string. Any doubt means no scoping: a module, interface, package or
package member, a declaration outside a module, or one whose home set holds
an include lucisv cannot resolve (a macro-built name, a file outside the
project such as `uvm_macros.svh`) is reported everywhere as before. On
opentitan the `state_q` rename's answer went from 274 lines (61 kB, 230
macro warnings, 229 about other modules) to about 72 lines (12 kB),
`hmac_core.StIdle`'s from 48 lines to 3.
- `duplicate-declaration` also reports a block label beside a port, genvar,
typedef, function or task, and two named procedural blocks of one label in
one scope.
- `lucisv-mcp rename` with many warnings is fast again: rooting the warning
paths was quadratic per warning (a `state_q` rename on opentitan: 125 s →
3.3 s). Naming the files in warnings no longer scans the whole set once per
file either: the engine's part of that rename went from 2.9 s to 2.2 s.
- A use in a file that includes the declaring file (or that it includes) is
no longer reported as "left unchanged" when the rename did rewrite it —
renaming a module whose instantiation sits in a file included beside it
said so wrongly.
## 0.59.0 — 2026-09-29
### MCP read-only mode
+5
View File
@@ -84,6 +84,11 @@ now): largest files `tools/read.rs` 405, `tools/item.rs` 379, `tools/item/verify
`vlog_refactor/src/rename/connections.rs` at 477 and `check/mod.rs` at 426,
and `lucisv_server/src/state/mod.rs` at 985 (already over; TODO §55).
Re-measured 2026-10-14 after TODO §55 (pure move, `docs/features/decomposition-state`):
`state/mod.rs` 63, the largest `state/` file `discover.rs` 412 (`rescan.rs` 411);
files over 600 workspace-wide: `lucisv_server/src/perf.rs` 907 (reasoned),
`vlog_parser/src/lexer.rs` 771, `vlog_formatter/src/format/stmt.rs` 604.
## Rust standards
- `cargo fmt` clean, `cargo clippy --all-targets` clean (no `#[allow]`
Generated
+9 -9
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.59.0"
version = "0.61.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.59.0"
version = "0.61.0"
[[package]]
name = "lucisv_mcp"
version = "0.59.0"
version = "0.61.0"
dependencies = [
"lucisv_core",
"serde",
@@ -126,7 +126,7 @@ dependencies = [
[[package]]
name = "lucisv_server"
version = "0.59.0"
version = "0.61.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.59.0"
version = "0.61.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.59.0"
version = "0.61.0"
dependencies = [
"lucisv_core",
"vlog_formatter",
@@ -279,11 +279,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.59.0"
version = "0.61.0"
[[package]]
name = "vlog_refactor"
version = "0.59.0"
version = "0.61.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -292,7 +292,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.59.0"
version = "0.61.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -13,7 +13,7 @@ members = [
]
[workspace.package]
version = "0.59.0"
version = "0.61.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+150 -2
View File
@@ -5084,11 +5084,14 @@ scope/widen logic, the document store, and the source selectors
(`module_sources`, `rename_sources`) are three sentences. Not planned; the
owner decides where it goes in loop 2.
- [ ] `state.rs` decomposition (pure move, byte-identical output, test
- [x] `state.rs` decomposition (pure move, byte-identical output, test
count unchanged); CLAUDE.md's measurement line refreshed —
**deferred to loop 3 by the lead, 2026-09-07** (958 lines at 0.49.0;
the measurement line already says so); a Fable refactor lane when
the owner schedules it
the owner schedules it — **done 2026-10-14**
(`docs/features/decomposition-state/README.md`: `state/` is ten
modules, largest 412 production lines; the CLAUDE.md measurement
line is the lead's, requested in that README's Handshakes)
## 50. `.*` expansion (planned 2026-09-05) — the first §8 refactoring
@@ -6939,3 +6942,148 @@ Nothing else.
(23e2e4b, v0.55.0), CI green on the release commit, 8 assets, the
darwin-arm64 vsix at 0.55.0 with both binaries,
`hierarchySections.js`, `extract.js`, no `*_test.js`.
## 65. Stabilization round 1 (planned 2026-09-30, owner's order) — two correctness gaps, then the doc-test stall
Three lanes, one at a time on trunk, dev (Opus) → QA (Opus) → lead review →
commit. Rules as §63/§64: every suite and sweep through `tools/guard.sh`,
never piped (log to a file, check `guard exit` and the suite count); no
`sleep` over 60 s; never `grep` without a path; opentitan read-only (the
eval clone `~/.cache/lucisv-eval/ot` may be read and, for an edit test,
restored with `git -C … checkout -- <file>`). Ships as 0.60.0.
### 65.1 Rename and references through a generate block label (topo §2.9-43, MCP-14)
`rename` of a generate block label (`for (…) begin : g_lane … end`) rewrites
the label and nothing else: a hierarchical path through it
(`g_lane[0].lane_q`, `u_x.g_lane[1].sig` from another file) keeps the old
name and no longer resolves, with no warning; `find_references` on the label
reports no use. The MCP layer refuses the rename (any `block`-kind
declaration); the LSP and the CLI still perform it. Feature README
`docs/features/generate-label-rename`.
The contract to reach, in `vlog_semantic` (resolution) and `vlog_refactor`
(`find_references`, `rename`, the verifier):
- [x] a path segment that names a generate block — bare (`g.x`), indexed
(`g[0].x`, `g[i].x`), nested (`g_a.g_b[2].x`), and behind an instance
path from another file (`u_x.g[0].x`) — resolves to the block's label
and is a reference to it
- [x] `find_references` on the label lists the declaration, the closing
`end : label` and every such segment, same-file and cross-file, through
the same fan-out §64.1 uses for hierarchical-surface declarations
- [x] `rename` rewrites all of them, all-or-nothing; a closing label is
rewritten with its opening one; a segment it cannot resolve (macro
text, a string) is a warning, as for any other declaration; an
unnamed block (`genblk1`) is not renameable
- [x] named procedural blocks (`begin : lbl` in `always`/`initial`/
functions/tasks): the label, its closing label and `disable lbl;` are
one reference set
- [x] the verifier accepts exactly these rewrites and nothing more:
masked-corruption attack tests for any normalization it gains
(CLAUDE.md invariant 4)
- [x] the LSP (`textDocument/references`, `rename`, `prepareRename`) and
the CLI get it through the engine; `lucisv-mcp`'s refusal of a
`block`-kind rename (`crates/lucisv_mcp/src/tools/edit.rs`) is lifted
and its tests (`tests/qa_m7.rs`) assert the rename instead
- [x] opentitan: a generate label with cross-file uses renamed on the eval
clone — every site rewritten, the files still parse, clone restored
- [x] rename warnings and mentions are scoped to the renamed declaration
(lead's inspection 2026-09-30: a module member's bare spelling
elsewhere is not news; a dotted one and a unit/package name's every
spelling still are)
- [x] QA: attack the index forms, nesting, shadowing (a net and a block of
the same name in different scopes), a label used only in a closing
label, `disable`, an escaped label, a label inside an `ifdef`
### 65.2 LSP `references` omits three `aes` instantiations (topo §2.9-36, MCP-6)
On opentitan, `textDocument/references` at the `aes` instantiation in
`hw/ip/aes/dv/tb/tb.sv` (and at its `.clk_i` connection) answers 11 and 9
locations; the whole-set engine answers 14 and 12 — the same plus the three
top-level instantiations in
`hw/top_{earlgrey,darjeeling,englishbreakfast}/rtl/autogen/*_pd_main.sv`
(`aes #(` and `.clk_i(clkmgr_clocks_i.clk_main_aes)`). Stable after a 30 s
settle, so not an indexing race. Feature README
`docs/features/references-fanout-pd-main`.
- [ ] root cause named (the fan-out/scope selection in `lucisv_server` —
`module_select`, `state/` scope widening, or the index's
instantiation facts for those three files; they are large generated
files, check the 1 MiB cap and the word census)
- [ ] the LSP answer equals the whole-set engine's for the module name and
for a port of it, from the declaration and from a use; a regression
test with a fixture that reproduces the cause (not only opentitan)
- [ ] an opentitan test (ignored by default, like `tests/opentitan.rs`)
pinning the 14 and 12
- [ ] QA: the same comparison for five other modules instantiated from a
`*_pd_main.sv` top, and for `rename`'s fan-out (does rename see the
three sites?)
### 65.3 The combined test command stalls entering the doc-tests
`cargo test --workspace` under `tools/guard.sh`: on 2026-09-29 (0.59.0 gate)
every suite finished in about two minutes and the run then sat 25 minutes
in `Doc-tests vlog_linter` until the guard cut it; on 2026-09-30 an
independent session's run hit its 600 s guard "entering the final doc-test
harness". `cargo test --workspace --doc` alone passes in under a minute.
- [ ] reproduce (how often, which doc-test, what the stuck process tree
is — `rustdoc`, `rust_out`, stdin?) and name the cause; `guard.sh`
runs the command with `0<&3` — check what the doc-test harness
inherits as stdin when the gate runs in the background
- [ ] fix at the cause (the harness, the doc-test, or the guard), and make
the release gate a script (`tools/gates.sh`) that runs fmt, clippy,
the test build, the suites, the doc-tests, the corpus gate and the
node tests as separate guarded steps with logs kept and a summary
that shows a kill — `tools/RELEASING.md` and CLAUDE.md point at it
- [ ] ten consecutive green runs of the gate script recorded
### 65.4 Resolve a hierarchical path rooted at a top-level module name (lead to schedule; from §65.1 QA F1)
A path whose head is a top module declared in another file — `tb.dut.u_x.sig`,
the shape every opentitan DV `force`/`$deposit`/`uvm_hdl_*` path takes
(IEEE 1800 §23.6: a top-level module name is the root of a hierarchical
name) — resolves nothing today: `tb` is bound as a `Target::Lexical` use,
misses in the writing file, and `resolve::member_site`'s `head_site` stops
the spine, so no segment after it is a reference and a rename of `dut`'s
declarations leaves the path behind (since §65.1 with a warning, not
silently). The root lookup belongs in `vlog_semantic/src/resolve.rs`
`head_site`: when the lexical walk misses **and** the head is followed by a
`.`, answer `MemberSite::Unit { path: head, surface: Hierarchical }` so the
workspace's `fold_path` walks `tb` → `dut`'s type → … exactly as it walks an
instance path today — with the head itself recorded as a `Target::Module`-like
use so `tb` stops being `NotFound`. QA's repro: `vlog_refactor/tests/
qa_generate_label.rs` `a_path_rooted_at_another_files_top_module_is_never_silently_left_behind`
(`probe.sv`: `assign o = tb.dut.g_sw[0].buf_q;`), and on opentitan
`hw/ip/keymgr_dpe/dv/env/keymgr_dpe_if.sv:514,515,517` (`force
tb.dut.gen_sw_assigns[i]…`) under `rename gen_sw_assigns`. Watch: a name
that is both a local and a top module (the local wins), `$root.tb…`, and the
index cost of the extra external candidates on every DV path.
- [ ] root lookup in `head_site`, the head recorded as a module use
- [ ] QA's repro renames the path instead of warning; the §65.1 warning
still fires for a root the workspace does not declare
### 65.6 Rename inside included fragments (lead to schedule; from §65.1 QA final H4)
A module that `` `include``s a fragment of its own body (`prim_ram_1p.sv`
including `prim_util_memload.svh`, every opentitan `*_assert.svh`) has that
fragment's text pasted into its scope, but lucisv analyses the fragment as a
file of its own: a bare `mem` there resolves to nothing, so `rename
prim_ram_1p.mem` edits the module and — since §65.1 — only *warns*
(`prim_util_memload.svh:12,24,32,43: `mem` is used in a file `prim_ram_1p.sv`
includes and was left unchanged`). Renaming there means binding a fragment
in the scope of the file that includes it (the include site's scope chain as
the fragment's outer scope, as `fragment-mode` does for a bare body) and
verifying the edit against that binding; a fragment included from two
modules is two bindings and must agree or be refused. QA's repro:
`vlog_refactor/tests/qa_warning_scope.rs`
`a_bare_use_in_plain_included_code_is_renamed_or_said` (`m_body.svh`:
`assign o = state_q;` included by `m.sv`).
- [ ] a fragment included by exactly one unit is bound in that unit's scope
and renamed with it; one included by several is refused unless every
binding agrees
- [ ] QA's repro renames the fragment's use; the §65.1 warning remains for
what cannot be bound
+52 -12
View File
@@ -45,10 +45,14 @@ fn rename(project: &mut Project, args: &Args) -> Result<Answer, String> {
}
let set = whole_set(project, Some(&path), std::slice::from_ref(&name))?;
let edit = vlog_refactor::rename(&set.files, &path, declaration.offset, new_name)
.map_err(|why| set.rooted(project, &why))?;
.map_err(|why| set.rooted(&why))?;
let sites: usize = edit.edits.iter().map(|(_, edits)| edits.len()).sum();
let unit = vlog_refactor::enclosing_module(&project.analysis(&path)?.text, declaration.offset);
let told = Told { name: &name, home: &path, unit: unit.as_deref() };
// A member of a module is named bare only where it is declared or used;
// the module (or interface, program) itself is named anywhere.
let unit_itself = matches!(declaration.kind, "module" | "interface" | "program");
let member = unit.is_some() && !unit_itself;
let told = Told { name: &name, home: &path, unit: unit.as_deref(), member };
let done = write_telling(project, edit, &set, &told)?;
let (sites, files) = (render::count(sites, "site"), render::count(done.files, "file"));
let mut lines = vec![format!("renamed {sites} in {files}")];
@@ -62,6 +66,8 @@ struct Picked {
name: String,
path: PathBuf,
offset: u32,
/// The declaration's kind word (`module`, `var`, …).
kind: &'static str,
}
fn one_declaration(project: &mut Project, args: &Args) -> Result<Picked, String> {
@@ -87,16 +93,9 @@ fn one_declaration(project: &mut Project, args: &Args) -> Result<Picked, String>
[one] if one.is_macro() => {
Err(format!("`{name}` is a macro; lucisv does not rename macros."))
}
// The engine rewrites no hierarchical path through a block and
// reports none as a use, so the rename could not be complete
// (topo §2.9 MCP-14).
[one] if one.kind == "block" => Err(format!(
"`rename` does not rename generate block labels: paths through the block (`{}[0].…`) would not be rewritten; edit the file.",
names::qualified(name).1
)),
[one] => {
let name = names::qualified(name).1.to_string();
Ok(Picked { name, path: one.path.clone(), offset: one.offset })
Ok(Picked { name, path: one.path.clone(), offset: one.offset, kind: one.kind })
}
many => Err(names::ambiguous(name, many, "pass `file`, and `name@LINE` within one file")),
}
@@ -129,6 +128,10 @@ pub(super) struct Told<'a> {
pub name: &'a str,
pub home: &'a Path,
pub unit: Option<&'a str>,
/// Whether the name is a member of a module or interface: its bare
/// mentions outside its home set (`vlog_refactor::home_set`) are not
/// listed.
pub member: bool,
}
/// What a written edit says after its first line: how many files it wrote,
@@ -151,21 +154,58 @@ pub(super) fn write_telling(
let accounted: Vec<(PathBuf, Vec<TextRange>)> =
edit.edits.iter().map(|(path, edits)| (path.clone(), written_ranges(edits))).collect();
let plan = Plan::from_refactor(edit, &set.files)?;
let warnings: Vec<String> = plan.warnings.iter().map(|w| set.rooted(w)).collect();
let named = path_warned(&warnings);
let written = set.files.iter().map(|(path, text)| {
let change = plan.changes.iter().find(|change| &change.path == path);
(path.as_path(), change.map_or(text.as_str(), |change| change.after.as_str()))
});
let focus = Focus { name: told.name, home: told.home, unit: told.unit, accounted: &accounted };
// The member's home set (the declaring file, what it includes and what
// includes it, and the edited files): where a bare mention can mean it.
let edited: Vec<PathBuf> = plan.changes.iter().map(|change| change.path.clone()).collect();
// `None` — list every mention — for a non-member, and for a member whose
// home set is not known (an include the engine cannot resolve).
let local = match told.member {
true => vlog_refactor::home_set(&set.files, told.home, &edited),
false => None,
};
let focus = Focus {
name: told.name,
home: told.home,
unit: told.unit,
accounted: &accounted,
named: &named,
local: local.as_deref(),
};
let mentions = mentions::find(project, written, &focus);
let done = apply::run(project, &plan)?;
let mut tail = Vec::new();
let warnings: Vec<String> = plan.warnings.iter().map(|w| set.rooted(project, w)).collect();
render::warnings(&mut tail, &warnings);
tail.extend(set.warning(project).map(|warning| format!("warning: {warning}")));
tail.extend(mentions.block());
Ok(Done { files: done.changed.len() + done.created.len(), tail })
}
/// The `(file, line)` pairs the engine's unresolved-path warnings name
/// (`rtl/a.sv:3,7: a hierarchical path through …`), so the `unresolved:`
/// block does not list them a second time.
fn path_warned(warnings: &[String]) -> Vec<(String, u32)> {
let mut out = Vec::new();
for warning in warnings {
let Some((head, _)) = warning.split_once(": a hierarchical path through `") else {
continue;
};
let Some((file, lines)) = head.rsplit_once(':') else { continue };
out.extend(
lines
.split(',')
.filter_map(|line| line.parse().ok())
.map(|line| (file.to_string(), line)),
);
}
out
}
/// Where each of one file's edits lands in the text as written: its start
/// shifted by what the edits before it added or removed, its length the
/// new text's.
+35 -2
View File
@@ -83,7 +83,7 @@ fn with_uses(project: &Project, name: &str, found: &[Declaration]) -> Vec<String
account(&mut accounted, hits);
}
Err(why) => {
let why = engine_refusal(&set.rooted(project, &why));
let why = engine_refusal(&set.rooted(&why));
lines.push(format!(" uses not listed: {why}"));
}
}
@@ -93,13 +93,46 @@ fn with_uses(project: &Project, name: &str, found: &[Declaration]) -> Vec<String
lines.push(format!("uses listed for {REFS_CAP} of {followed} declarations"));
}
let home = &found[0].path;
let focus = Focus { name, home, unit: None, accounted: &accounted };
let local = member_files(&set, found, &accounted);
let focus = Focus {
name,
home,
unit: None,
accounted: &accounted,
named: &[],
local: local.as_deref(),
};
let files = set.files.iter().map(|(path, text)| (path.as_path(), text.as_str()));
lines.extend(mentions::find(project, files, &focus).block());
lines.extend(set.warning(project).map(|warning| format!("warning: {warning}")));
lines
}
/// The files a bare mention of a **module member** can mean it in — each
/// declaration's home set (`vlog_refactor::home_set`) with every file the
/// engine found a use in — or `None` when
/// any declaration is not a member (a unit, a package member, a macro), whose
/// every mention is listed (§65.1, lead's inspection: a `state_q` found in forty
/// modules is not news about this one).
fn member_files(
set: &WholeSet,
found: &[Declaration],
accounted: &[(PathBuf, Vec<TextRange>)],
) -> Option<Vec<PathBuf>> {
if found.iter().any(Declaration::is_macro) {
return None;
}
let hit_files: Vec<PathBuf> = accounted.iter().map(|(path, _)| path.clone()).collect();
let mut local: Vec<PathBuf> = Vec::new();
for declaration in found {
let text = set.files.iter().find(|(p, _)| *p == declaration.path).map(|(_, t)| t)?;
let unit_itself = matches!(declaration.kind, "module" | "interface" | "program");
vlog_refactor::enclosing_module(text, declaration.offset).filter(|_| !unit_itself)?;
local.extend(vlog_refactor::home_set(&set.files, &declaration.path, &hit_files)?);
}
Some(local)
}
/// The engine's hits, one file per line: `file:12,40`.
fn uses(project: &Project, set: &WholeSet, hits: &[(PathBuf, TextRange)]) -> Vec<String> {
let mut sites: Vec<(String, u32)> = Vec::new();
+20
View File
@@ -52,6 +52,17 @@ pub struct Focus<'a> {
pub unit: Option<&'a str>,
/// Per file, the spans an engine returned (hits) or rewrote (edits).
pub accounted: &'a [(PathBuf, Vec<TextRange>)],
/// `(file, line)` pairs an engine warning already names — a `rename`'s
/// unresolved-path warning — which are not repeated as mentions.
pub named: &'a [(String, u32)],
/// For a member of a module or interface (a net, a port, a block, …):
/// the files where a bare spelling can mean it — its home set: the
/// declaring file, what it includes and what includes it, and the files
/// the edit wrote or the engine found uses in. Elsewhere only a
/// spelling right after a `.` (`".state_q"`, `` `HIER.u.state_q``) is
/// listed. `None` for a name any file may spell bare (a unit, a package
/// member): every mention is listed.
pub local: Option<&'a [PathBuf]>,
}
impl Mentions {
@@ -93,7 +104,13 @@ pub fn find<'t>(
let spans = accounted.map_or(&[][..], |(_, spans)| spans.as_slice());
let lines = LineIndex::new(text);
let mut last_line = 0;
let foreign = focus.local.is_some_and(|local| !local.iter().any(|p| p == path));
for (at, _) in spellings(text, focus.name) {
if foreign
&& !text.as_bytes().get((at as usize).wrapping_sub(1)).is_some_and(|&b| b == b'.')
{
continue;
}
let end = at + focus.name.len() as u32;
if spans.iter().any(|span| span.start <= at && end <= span.end) {
continue;
@@ -109,6 +126,9 @@ pub fn find<'t>(
.unwrap_or("");
let rank = rank(accounted.is_some(), focus.unit, source);
let mention = Mention { file: project.relative(path), line };
if focus.named.iter().any(|(file, at)| *file == mention.file && *at == line) {
continue;
}
found.push((rank, shared_components(path, focus.home), mention));
}
}
+6 -6
View File
@@ -63,18 +63,18 @@ fn add_port(
) -> Result<Answer, String> {
let set = whole_set(project, None, &[module.to_string()])?;
let edit = vlog_refactor::add_port(&set.files, ModuleRef::Name(module), declaration)
.map_err(|why| set.rooted(project, &why))?;
.map_err(|why| set.rooted(&why))?;
let tokens = vlog_parser::tokenize(declaration).unwrap_or_default();
let port = place::port_name(&tokens).map(|token| token.text.clone()).unwrap_or_default();
let show = &|path: &Path| project.relative(path);
let edit = match after.map(str::trim) {
Some(after) => {
let spec = place::Spec { module, file, after, port: &port, declaration, show };
place::after(&set.files, &edit, &spec).map_err(|why| set.rooted(project, &why))?
place::after(&set.files, &edit, &spec).map_err(|why| set.rooted(&why))?
}
None => edit,
};
let told = Told { name: &port, home: file, unit: Some(module) };
let told = Told { name: &port, home: file, unit: Some(module), member: true };
let (count, files) = instantiations(project, module);
let done = write_telling(project, edit, &set, &told)?;
let head = format!("added port {port} in module {module}: {}", census(count, files));
@@ -89,9 +89,9 @@ fn remove_port(
) -> Result<Answer, String> {
let offset = port_offset(project, module, file, port)?;
let set = whole_set(project, Some(file), &[port.to_string(), module.to_string()])?;
let edit = vlog_refactor::remove_port(&set.files, file, offset)
.map_err(|why| set.rooted(project, &why))?;
let told = Told { name: port, home: file, unit: Some(module) };
let edit =
vlog_refactor::remove_port(&set.files, file, offset).map_err(|why| set.rooted(&why))?;
let told = Told { name: port, home: file, unit: Some(module), member: true };
let (count, files) = instantiations(project, module);
let done = write_telling(project, edit, &set, &told)?;
let head = format!("removed port {port} in module {module}: {}", census(count, files));
+44 -12
View File
@@ -76,6 +76,10 @@ pub struct WholeSet {
pub files: Vec<(PathBuf, String)>,
/// The files left out, with why.
pub skipped: Vec<(PathBuf, String)>,
/// How an engine sentence names each file of the set, and the
/// root-relative spelling it becomes — built once per set by
/// [`WholeSet::read`] ([`WholeSet::rooted`]).
names: Vec<(String, String)>,
}
impl WholeSet {
@@ -85,13 +89,14 @@ impl WholeSet {
pub fn read(project: &Project, extra: Option<&Path>) -> WholeSet {
let mut wanted: BTreeSet<PathBuf> = project.index().files().iter().cloned().collect();
wanted.extend(extra.map(Path::to_path_buf));
let mut set = WholeSet { files: Vec::new(), skipped: project.skipped() };
let mut set = WholeSet { files: Vec::new(), skipped: project.skipped(), names: Vec::new() };
for path in wanted {
match std::fs::read_to_string(&path) {
Ok(text) => set.files.push((path, text)),
Err(e) => set.skipped.push((path, format!("no longer reads: {e}"))),
}
}
set.names = names_of(project, &set.files);
set
}
@@ -105,18 +110,17 @@ impl WholeSet {
})
}
/// An engine sentence with each bare file name written root-relative
/// (`p1.sv:2` → `rtl/p1.sv:2`), where the name is the base name of
/// exactly one file of the set — the engines name files by base name,
/// and only an unambiguous one can be placed.
pub fn rooted(&self, project: &Project, sentence: &str) -> String {
/// An engine sentence with every file of the set written root-relative.
/// The engines name a file by its base name when that is unique in the
/// set they were handed (`p1.sv:2` → `rtl/p1.sv:2`) and by the path they
/// were given otherwise (`/abs/…/top_a/pwrmgr_if.sv:80` →
/// `top_a/…/pwrmgr_if.sv:80`, generate-label-rename R1). One pass over
/// the set's spellings per sentence; the table itself is built once.
pub fn rooted(&self, sentence: &str) -> String {
let mut out = sentence.to_string();
for (path, _) in &self.files {
let Some(base) = path.file_name().and_then(|name| name.to_str()) else { continue };
let same = self.files.iter().filter(|(other, _)| other.file_name() == path.file_name());
let shown = project.relative(path);
if same.count() == 1 && shown != base {
out = replace_file_name(&out, base, &shown);
for (spelled, shown) in &self.names {
if out.contains(spelled.as_str()) {
out = replace_file_name(&out, spelled, shown);
}
}
out
@@ -140,6 +144,34 @@ impl WholeSet {
}
}
/// Every file's engine spelling and its root-relative one: the full path for
/// a base name several files share, else the base name (skipped when it is
/// already the relative path). Full paths first, so a bare base name never
/// rewrites the tail of one.
fn names_of(project: &Project, files: &[(PathBuf, String)]) -> Vec<(String, String)> {
let mut count: HashMap<&std::ffi::OsStr, usize> = HashMap::new();
for (path, _) in files {
if let Some(base) = path.file_name() {
*count.entry(base).or_default() += 1;
}
}
let (mut full, mut bare) = (Vec::new(), Vec::new());
for (path, _) in files {
let Some(base) = path.file_name() else { continue };
let shown = project.relative(path);
match count.get(base) {
Some(1) => {
if let Some(base) = base.to_str().filter(|base| *base != shown) {
bare.push((base.to_string(), shown));
}
}
_ => full.push((path.display().to_string(), shown)),
}
}
full.extend(bare);
full
}
/// `text` with every occurrence of the file name `base` that stands alone —
/// not the tail of a longer path or name — replaced by `path`.
fn replace_file_name(text: &str, base: &str, path: &str) -> String {
+7 -2
View File
@@ -544,8 +544,11 @@ const SM: &str = "module main_sm (\n input logic clk_i,\n output logic busy_o
const DV: &str = "module dv_x;\n logic a, b;\n assign a = `HIER.u_a[2].state_q;\n assign b = `HIER.u_a[2].state_q_d;\n assign b = `HIER.u_a[state_q].x;\nendmodule\n";
// Dotted spellings: `state_q` is a member of `main_sm`, so since §65.1's
// scoping of mentions a bare spelling in another file is not listed, and a
// path-like one (`.state_q`) still is — which keeps this CRLF check alive.
const CRLF: &str =
"module c;\r\n // one\r\n // state_q two\r\n string s = \"state_q\";\r\nendmodule\r\n";
"module c;\r\n // one\r\n // u.state_q two\r\n string s = \"u.state_q\";\r\n // state_q bare, not listed\r\nendmodule\r\n";
#[test]
fn qa_mentions_find_every_kind_and_only_whole_words() {
@@ -580,7 +583,9 @@ fn qa_mentions_find_every_kind_and_only_whole_words() {
#[test]
fn qa_mentions_are_capped_at_50_with_the_edited_file_first() {
let far: String = (0..60).map(|i| format!("// state_q far {i}\n")).collect::<String>()
// Path-like, so listed from a file that neither declares nor uses the
// member (§65.1's scoping of mentions drops a bare one there).
let far: String = (0..60).map(|i| format!("// u.state_q far {i}\n")).collect::<String>()
+ "module far; endmodule\n";
let files = [("rtl/sm.sv", SM), ("zz/far.sv", far.as_str())];
let (tree, mut server) = served(&files);
+7 -2
View File
@@ -277,7 +277,10 @@ const MACRO_ARG: &[(&str, &str)] = &[
"top.sv",
"`include \"defs.svh\"\nmodule top (input logic clk);\n logic peek;\n core u_core0 (.clk, .q());\n assign peek = `ID(u_core0.state_q);\nendmodule\n",
),
("third.sv", "module third;\n // state_q is mentioned here\n initial $display(\"state_q\");\nendmodule\n"),
(
"third.sv",
"module third;\n // u_core0.state_q is mentioned here\n initial $display(\"u_core0.state_q\");\n // a bare state_q here is another module's word\nendmodule\n",
),
("m.sv", "module m (input logic a, output logic q);\n /* q */ assign q = a;\nendmodule\n"),
];
@@ -285,7 +288,9 @@ const MACRO_ARG: &[(&str, &str)] = &[
fn qa_uses_never_include_a_comment_a_string_or_macro_text() {
let scratch = Scratch::with(MACRO_ARG);
let mut s = Session::ready(&scratch);
// `third.sv` writes the word only in a comment and a string; `top.sv`
// `third.sv` writes the word only in a comment and a string (dotted —
// a bare spelling in a file that neither declares nor uses the member
// is not listed since §65.1's scoping of mentions); `top.sv`
// only inside a macro call's argument, which the engine does not follow:
// those are the unresolved mentions, never uses.
assert_eq!(
+73 -13
View File
@@ -717,17 +717,19 @@ fn qa_rework_every_local_kind_is_found_and_renamed_by_name_file_and_unit() {
#[test]
fn qa_rework_renaming_a_generate_label_never_leaves_a_path_through_it_behind() {
// `find g_lane refs` lists no use and `rename` answers `renamed 1 site`,
// leaving `g_lane[0].lane_q` naming a block that no longer exists —
// while `edit_item delete g_lane` sees the use (`rtl/fsm.sv:19:18`).
// `find g_lane refs` used to list no use and `rename` answered `renamed
// 1 site`, leaving `g_lane[0].lane_q` naming a block that no longer
// existed — while `edit_item delete g_lane` saw the use
// (`rtl/fsm.sv:19:18`). Lead's ruling R1 had the MCP layer refuse the
// rename; TODO §65.1 fixed the engine (a path segment through a block is
// a reference to its label), and the refusal is lifted.
let tree = Tree::with(&[("rtl/fsm.sv", LOCALS)]);
// Lead's ruling R1: the MCP layer refuses the rename, and the source
// is untouched.
let said = session(&tree, &[("rename", json!({"name": "g_lane", "new_name": "g_ln"}))]);
assert!(said[0].refused, "{}", said[0].text);
let why = &said[0].text;
assert!(why.starts_with("`rename` does not rename generate block labels"), "{why}");
assert_eq!(tree.read("rtl/fsm.sv"), LOCALS);
let found = text(&tree, "find", json!({"name": "g_lane", "refs": true}));
assert_eq!(found, "block g_lane rtl/fsm.sv:12\n rtl/fsm.sv:19\n");
let renamed = text(&tree, "rename", json!({"name": "g_lane", "new_name": "g_ln"}));
assert_eq!(renamed, "renamed 2 sites in 1 file\n");
assert_eq!(tree.read("rtl/fsm.sv"), LOCALS.replace("g_lane", "g_ln"));
assert!(tree.read("rtl/fsm.sv").contains("busy = tmp | g_ln[0].lane_q;"));
}
#[test]
@@ -747,10 +749,15 @@ fn qa_rework_a_shared_base_name_is_named_by_path_or_left_alone() {
assert_eq!(text(&tree, "rename", one), "renamed 2 sites in 1 file\n");
assert!(tree.read("rtl/y/p1.sv").contains("logic d2;"));
assert!(tree.read("rtl/x/p1.sv").contains("logic dup;"));
// The engine's sentences: `p1.sv` is two files, so it stays as said;
// `p1b.sv` is one, so it is named by its path.
// The engine's sentences: `p1.sv` is two files, so the engine names it by
// the path it was given and the answer makes that root-relative (§65.1
// re-check R1 — it used to stay a bare, unplaceable `p1.sv`); `p1b.sv`
// is one, so it is named by its path too.
let added = text(&tree, "port", json!({"module": "sub", "add": "input logic zz"}));
assert!(added.contains("`u_s` at p1.sv:4 connects with `.*` and p1.sv has"), "{added}");
assert!(
added.contains("`u_s` at rtl/y/p1.sv:4 connects with `.*` and rtl/y/p1.sv has"),
"{added}"
);
assert!(added.contains("(rtl/z/p1b.sv:3)"), "{added}");
assert!(!added.contains("rtl/z/rtl/"), "{added}");
}
@@ -807,3 +814,56 @@ fn qa_rework_an_escaped_local_outline_lists_is_found() {
assert!(text(&tree, "outline", json!({"file": "rtl/g.sv"})).contains("var \\loc.v 3"));
assert_eq!(text(&tree, "find", json!({"name": "\\loc.v"})), "var \\loc.v rtl/g.sv:3\n");
}
#[test]
fn a_rename_names_each_same_named_file_by_its_root_relative_path_once() {
// §65.1 re-check R1 and the lead's fifth ruling: two `x_if.sv` holding an
// unresolved path through the label are two findable warning lines, and
// neither line is repeated under `unresolved:`.
let probe = "module probe_IDX (output logic o);\n assign o = tb.dut.g_sw.q;\nendmodule\n";
let (a, b) = (probe.replace("IDX", "a"), probe.replace("IDX", "b"));
let tree = Tree::with(&[
("rtl/dut.sv", "module dut_x;\n if (1) begin : g_sw\n logic q;\n end\nendmodule\n"),
("dv/a/x_if.sv", a.as_str()),
("dv/b/x_if.sv", b.as_str()),
]);
let said = text(&tree, "rename", json!({"name": "g_sw", "new_name": "g_hw"}));
let path_lines: Vec<&str> =
said.lines().filter(|line| line.contains("a hierarchical path through")).collect();
assert_eq!(path_lines.len(), 2, "{said}");
assert!(path_lines[0].starts_with("warning: dv/a/x_if.sv:2: "), "{said}");
assert!(path_lines[1].starts_with("warning: dv/b/x_if.sv:2: "), "{said}");
assert!(!said.contains("unresolved:"), "each line is said once: {said}");
assert!(tree.read("rtl/dut.sv").contains("begin : g_hw"));
}
#[test]
fn a_members_rename_lists_only_its_own_mentions_and_dotted_ones_elsewhere() {
// §65.1, lead's inspection: two modules each with a `state_q`, each
// spelling it in an `ASSERT argument, a comment and a string. Renaming
// `a`'s warns and lists only `a`'s — plus `b`'s dotted spellings, which
// may be paths to it. A package-level name still lists everything.
let defs = "`define ASSERT(n, e) n: assert property (e);\n";
let a = "module a (input logic clk);\n logic state_q;\n always_ff @(posedge clk) state_q <= ~state_q;\n `ASSERT(A_T, state_q)\n // state_q is a's\n initial $display(\"state_q\");\nendmodule\n";
let b = "module b (input logic clk);\n logic state_q;\n a u_a (.clk);\n always_ff @(posedge clk) state_q <= ~state_q;\n `ASSERT(B_T, state_q)\n `ASSERT(B_P, u_a.state_q)\n // state_q is b's\n initial $display(\"state_q\");\n initial $display(\"u_a.state_q\");\nendmodule\n";
let pkg = "package p;\n localparam int W = 1;\nendpackage\n";
let user = "module u import p::*;\n // W is p's\n localparam int X = W;\nendmodule\n";
let tree = Tree::with(&[
("rtl/defs.svh", defs),
("rtl/a.sv", a),
("rtl/b.sv", b),
("rtl/p.sv", pkg),
("rtl/u.sv", user),
]);
let said = text(&tree, "rename", json!({"name": "a.state_q", "new_name": "state_r"}));
let macro_lines: Vec<&str> = said.lines().filter(|l| l.contains("macro invocation")).collect();
assert_eq!(macro_lines.len(), 2, "{said}");
assert!(
macro_lines[0].contains("rtl/a.sv:4") && macro_lines[1].contains("rtl/b.sv:6"),
"{said}"
);
assert!(said.ends_with("unresolved:\n rtl/a.sv:4,5,6\n rtl/b.sv:6,9\n"), "{said}");
assert!(tree.read("rtl/b.sv").contains("logic state_q;"), "b's own stays");
let found = text(&tree, "find", json!({"name": "p.W", "refs": true}));
assert!(found.contains("unresolved:\n rtl/u.sv:2\n"), "a package member lists all: {found}");
}
+10 -3
View File
@@ -795,7 +795,13 @@ fn rename_lists_the_old_names_unresolved_mentions() {
text.contains("\nwarning: `state_q` appears in the body of macro `SM_STATE`"),
"{text}"
);
assert!(text.ends_with("\nunresolved:\n rtl/sm.sv:1,8\n dv/probe_if.sv:2,4,6\n"), "{text}");
// Line 6 is `tb.…state_q`, a path nothing resolves: the engine's own
// warning names it (§65.1 F1), so it is not repeated as a mention.
assert!(
text.contains("\nwarning: dv/probe_if.sv:6: a hierarchical path through `state_q`"),
"{text}"
);
assert!(text.ends_with("\nunresolved:\n rtl/sm.sv:1,8\n dv/probe_if.sv:2,4\n"), "{text}");
// The hierarchical use in core.sv is renamed, so it is not a mention;
// the text the block names is left as it was.
assert!(read(&tree, "rtl/core.sv").contains("u_main_sm.main_state_q"));
@@ -894,12 +900,13 @@ fn engine_sentences_name_files_root_relative() {
assert_eq!(before, snapshot(&tree));
let added = server.text("port", json!({"module": "spare", "add": "input logic en"}));
assert!(added.contains("at `u_s` (rtl/spare_user.sv:5)"), "{added}");
// A base name two files share cannot be placed: left as the engine said.
// A base name two files share: the engine names it by its path (§65.1
// re-check R1), which the answer makes root-relative like any other.
let (tree, mut server) = served("edit");
fs::create_dir_all(tree.path("alt")).unwrap();
fs::write(tree.path("alt/cell.sv"), "module cell2; endmodule\n").unwrap();
let twice = refusal(&mut server, "port", json!({"module": "cell", "remove": "en"}));
assert!(twice.contains("inside `cell` at cell.sv:6"), "{twice}");
assert!(twice.contains("inside `cell` at rtl/cell.sv:6"), "{twice}");
}
#[test]
+84 -23
View File
@@ -30,12 +30,18 @@ use crate::convert::Positions;
use crate::state::Workspace;
use crate::uri::{path_to_uri, uri_to_path};
/// The module the cursor names, as the root of a hierarchy — its own
/// declaration, or an instantiation of it.
mod calls;
mod tf;
/// The root of a hierarchy at the cursor.
///
/// `None` for every other position, which is what stops an editor from opening
/// an empty hierarchy view on a `wire`. A name the workspace index does not
/// hold as a module declines the same way: there is no node to stand on.
/// In order: a module's own declaration name, or the module name of an
/// instantiation (both unchanged since M11); an instance name, which stands
/// for the instantiated module; a function or task the cursor names — its
/// declaration, a call, its end label; the function or task whose body holds
/// the cursor; and the module, interface or program whose body holds it.
/// `None` only where nothing encloses the cursor, which is what stops an
/// editor from opening an empty view.
///
/// A name two files declare returns *both* items rather than a guess, the same
/// answer `textDocument/definition` gives for the same ambiguity — the client
@@ -51,11 +57,27 @@ pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Option<Vec<CallHierarc
let positions = doc.positions();
return Some(vec![item(uri.clone(), &positions, decl)?]);
}
// The cursor on an instantiation names the module being instantiated.
// The cursor on an instantiation names the module being instantiated —
// through its module name or through one of its instance names.
let sites = instantiations::sites(&doc.tree.items);
let site = sites.iter().find(|site| touches(site.inst.module_span, offset))?;
let items = declarations_of(ws, &site.inst.module);
(!items.is_empty()).then_some(items)
let on_module = sites.iter().find(|site| touches(site.inst.module_span, offset));
let on_instance = || {
sites.iter().find(|site| site.inst.instances.iter().any(|i| touches(i.name_span, offset)))
};
if let Some(site) = on_module.or_else(on_instance) {
let items = declarations_of(ws, &site.inst.module);
if !items.is_empty() {
return Some(items);
}
}
if let Some(items) = tf::prepare(ws, doc, uri, offset) {
return Some(items);
}
let decl = instantiations::declarations(&doc.tree.items)
.into_iter()
.filter(|decl| tf::holds(decl.span, offset))
.min_by_key(|decl| decl.span.end - decl.span.start)?;
Some(vec![item(uri.clone(), &doc.positions(), decl)?])
}
/// Who instantiates this module: one call per **instantiating module**, with
@@ -63,7 +85,14 @@ pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Option<Vec<CallHierarc
///
/// One name asked of the batch below, which is the only census in this server
/// — the code lens counts what this lists.
///
/// A function or task item (one carrying `data`) is answered by its call
/// sites instead (`hierarchy/calls.rs`); a package or class caller item has
/// no incoming calls.
pub fn incoming(ws: &Workspace, item: &CallHierarchyItem) -> Vec<CallHierarchyIncomingCall> {
if let Some(data) = tf::Data::of(item) {
return calls::incoming(ws, item, &data);
}
callers_of_each(ws, &[item.name.as_str()]).pop().unwrap_or_default()
}
@@ -131,7 +160,13 @@ pub fn callers_of_each(ws: &Workspace, names: &[&str]) -> Vec<Vec<CallHierarchyI
/// silently. A hierarchy node has nowhere to say "and one more I could not
/// find", and a node pointing at the wrong one of two same-named modules would
/// send the user to the wrong file with no way to tell.
///
/// A function or task item is answered by the calls in its body instead
/// (`hierarchy/calls.rs`). A module item never lists function calls.
pub fn outgoing(ws: &Workspace, item: &CallHierarchyItem) -> Vec<CallHierarchyOutgoingCall> {
if let Some(data) = tf::Data::of(item) {
return calls::outgoing(ws, item, &data);
}
let Some(text) = text_of(ws, &item.uri) else { return Vec::new() };
let (tree, _) = parse_source_tolerant(&text);
let line_index = LineIndex::new(&text);
@@ -431,12 +466,17 @@ endmodule
);
}
/// Reversed by call-hierarchy-everywhere (2026-10-14): the `module`
/// keyword and a connected expression are inside `top` and prepare it,
/// and an instance name stands for the instantiated module. Only a
/// position no module encloses still prepares nothing.
#[test]
fn a_position_on_no_module_prepares_nothing() {
fn a_position_on_no_module_prepares_the_enclosing_one_or_nothing() {
let (_tree, ws, uri) = three("none");
assert!(prepare(&ws, &uri, 0).is_none(), "the `module` keyword");
assert!(prepare(&ws, &uri, at(TOP, "u_a")).is_none(), "the instance name");
assert!(prepare(&ws, &uri, at(TOP, "1'b0")).is_none(), "a connected expression");
let name = |offset| shape(&prepare(&ws, &uri, offset).expect("an item")[0]).0;
assert_eq!(name(0), "top", "the `module` keyword is inside `top`");
assert_eq!(name(at(TOP, "u_a")), "sub", "the instance name stands for its module");
assert_eq!(name(at(TOP, "1'b0")), "top", "a connected expression is inside `top`");
let (_tree, ws, uri) = workspace("nonmodule", &[("p.sv", "package p;\nendpackage\n")]);
assert!(prepare(&ws, &uri, at("package p;", "p;")).is_none(), "a package is not a module");
}
@@ -448,11 +488,14 @@ endmodule
assert!(prepare(&ws, &uri, at(SUB, "sub") + 3).is_some());
}
/// Reversed by call-hierarchy-everywhere (2026-10-14): no item for
/// `nope`, which nothing declares, but the module the cursor is inside.
#[test]
fn an_instantiation_of_a_module_nothing_declares_prepares_nothing() {
fn an_instantiation_of_a_module_nothing_declares_prepares_the_enclosing_module() {
let top = "module top;\n nope u1 ();\nendmodule\n";
let (_tree, ws, uri) = workspace("undeclared", &[("top.sv", top)]);
assert!(prepare(&ws, &uri, at(top, "nope")).is_none());
let items = prepare(&ws, &uri, at(top, "nope")).expect("the enclosing module");
assert_eq!(shape(&items[0]), ("top".to_string(), "top.sv".to_string(), 0));
}
#[test]
@@ -894,18 +937,38 @@ endmodule
assert_eq!(inner_calls[0].to.name, "sub");
}
/// Reversed by call-hierarchy-everywhere (2026-10-14): a comment or a
/// string inside `top` prepares `top` — never the `sub` its text spells.
#[test]
fn qa_prepare_on_a_string_or_comment_is_null() {
fn qa_prepare_on_a_string_or_comment_is_the_enclosing_module_not_the_text() {
let text = "module top;\n // sub lives here\n string s = \"sub\";\nendmodule\n";
let (_tree, ws, uri) = workspace("qa_string_comment", &[("top.sv", text)]);
let comment_offset = at(text, "// sub");
let string_offset = at(text, "\"sub\"") + 1;
assert!(prepare(&ws, &uri, comment_offset + 3).is_none(), "cursor inside a comment");
assert!(prepare(&ws, &uri, string_offset + 1).is_none(), "cursor inside a string literal");
let name = |offset| shape(&prepare(&ws, &uri, offset).expect("an item")[0]).0;
assert_eq!(name(comment_offset + 3), "top", "cursor inside a comment");
assert_eq!(name(string_offset + 1), "top", "cursor inside a string literal");
}
/// Reversed by call-hierarchy-everywhere (2026-10-14): the bind target
/// is still not read as a module name, but the cursor is inside the
/// module the `bind` is written in, and that is what it prepares. The
/// fixture moves the `bind` into `harness` so the two cannot coincide.
#[test]
fn qa_prepare_on_a_bind_target_module_name_is_currently_null() {
fn qa_prepare_on_a_bind_target_module_name_is_the_enclosing_module() {
let harness = "module harness;\n bind top chk u_chk ();\nendmodule\n";
let top = "module top;\nendmodule\n";
let chk = "module chk;\nendmodule\n";
let files = [("harness.sv", harness), ("top.sv", top), ("chk.sv", chk)];
let (_tree, ws, uri) = workspace("qa_bind_target2", &files);
let items = prepare(&ws, &uri, at(harness, "bind top") + 5).expect("the enclosing module");
assert_eq!(shape(&items[0]).0, "harness", "not the bind target `top`");
}
/// The M11 QA pin, kept for its history: the answer it pinned is the
/// enclosing module now, which in this fixture is `top` itself.
#[test]
fn qa_prepare_on_a_bind_target_module_name_was_null() {
// `bind top chk u_chk ();` — cursor on `top`, the bind's *target*
// module. `top` is a real, declared module and a genuine reference to
// it, but neither `declarations()` (which only sees `module ...`
@@ -919,10 +982,8 @@ endmodule
let chk = "module chk;\nendmodule\n";
let (_tree, ws, uri) = workspace("qa_bind_target", &[("top.sv", top), ("chk.sv", chk)]);
let target_offset = at(top, "bind top") + 5;
assert!(
prepare(&ws, &uri, target_offset).is_none(),
"pinning today's answer, not endorsing it"
);
let items = prepare(&ws, &uri, target_offset).expect("the enclosing module");
assert_eq!(shape(&items[0]).0, "top", "the module the bind is written in");
}
#[test]
+512
View File
@@ -0,0 +1,512 @@
//! `incomingCalls` and `outgoingCalls` for a function or task item.
//!
//! A call is a *use* of the function's name that the semantic layer resolved
//! to its declaration — in this file through the symbol table, in another
//! file through the workspace overlay — and that is not one of the three
//! uses of a name that are not calls: the `endfunction : f` label, the name
//! of an out-of-body definition (`function void c::f();`), and the Verilog
//! result variable (`f = f + 1;` inside `f`).
//!
//! **Incoming** reads the same files `textDocument/references` reads: the
//! declaring file, every open buffer, and every closed file the index holds a
//! reference posting for. An ambiguous target falls back to the declaring
//! file alone, as references falls back to the cursor's file. Each call is
//! credited to its caller: the enclosing function or task, else the enclosing
//! module, interface, program, package or class.
//!
//! **Outgoing** reads the item's own body and resolves every call in it; a
//! system task, an unresolved name and an ambiguous one are skipped, as an
//! ambiguous instantiation is for a module.
use std::path::{Path, PathBuf};
use lsp_types::{CallHierarchyIncomingCall, CallHierarchyItem, CallHierarchyOutgoingCall, Uri};
use vlog_parser::TextRange;
use vlog_semantic::{
Def, ExternalTarget, Reference, ReferenceId, ScopeId, ScopeKind, Semantics, SymbolId,
SymbolKind as Kind,
};
use super::tf::{self, Analysis, Data};
use crate::nav::indexed_def_for_symbol;
use crate::state::{first_token_from, Document, Workspace};
use crate::uri::path_to_uri;
/// Every call of the function or task an item names, one entry per caller.
pub(super) fn incoming(
ws: &Workspace,
item: &CallHierarchyItem,
data: &Data,
) -> Vec<CallHierarchyIncomingCall> {
let Some((decl, symbol)) = tf::target(ws, item, data) else { return Vec::new() };
let Some(name) = decl.semantics.symbol(symbol).map(|s| s.name.clone()) else {
return Vec::new();
};
// Only a declaration the index holds — a package or class member — can be
// named through the workspace overlay, from another file or from its own
// (`super.f()` reaches a base class's method that way).
let def = decl
.path
.as_ref()
.and_then(|_| indexed_def_for_symbol(ws, &decl, decl.semantics.symbol(symbol)?));
let mut calls = callers(&item.uri, &decl, &name, |reference, id| {
reference.resolved() == Some(symbol) || def.is_some_and(|def| names_def(&decl, id, def))
});
if let Some(elsewhere) = def.and_then(|def| other_files(ws, &decl, def, &name)) {
calls.extend(elsewhere);
}
calls.sort_by(|a, b| {
(a.from.uri.as_str(), super::key(a.from.selection_range))
.cmp(&(b.from.uri.as_str(), super::key(b.from.selection_range)))
});
calls
}
/// The calls written in every file but the declaring one, or `None` when the
/// workspace cannot say which declaration a use names.
///
/// The same files `textDocument/references` reads for an indexed
/// declaration: every open buffer, and every closed file holding a reference
/// posting for it.
fn other_files(
ws: &Workspace,
decl: &Document,
def: &Def,
name: &str,
) -> Option<Vec<CallHierarchyIncomingCall>> {
let declaring = decl.path.as_deref()?;
if declined(ws, def, name, declaring) {
return None;
}
let index = ws.index();
let is_call_of_def = |doc: &Document, id: ReferenceId| names_def(doc, id, def);
let mut calls = Vec::new();
for (_, doc) in ws.open_documents() {
let Some(path) = doc.path.as_deref().filter(|path| *path != declaring) else { continue };
let Some(uri) = path_to_uri(path) else { continue };
calls.extend(callers(&uri, doc, name, |_, id| is_call_of_def(doc, id)));
}
let mut closed: Vec<PathBuf> = index
.references_to(def)
.iter()
.filter_map(|site| index.path(site.file))
.filter(|path| *path != declaring && ws.document_for_path(path).is_none())
.map(Path::to_path_buf)
.collect();
closed.sort();
closed.dedup();
for path in closed {
let (Some(uri), Some(doc)) = (path_to_uri(&path), tf::load_path(ws, &path)) else {
continue;
};
calls.extend(callers(&uri, &doc, name, |_, id| is_call_of_def(&doc, id)));
}
Some(calls)
}
/// Whether the workspace cannot say which declaration a use of `def` names —
/// the index marks its uses ambiguous, or an open buffer other than the
/// declaring file holds a use that could be `def` or another declaration.
/// References declines in exactly these two cases.
///
/// In a consistent workspace neither can hold for a `def` that
/// `indexed_def_for_symbol` accepted (it demands a single record under the
/// very key every use's lookup reads), so this is the defensive half of the
/// contract; the tests reach it with a buffer the index does not hold and
/// with a lookup asked directly.
fn declined(ws: &Workspace, def: &Def, name: &str, declaring: &Path) -> bool {
ws.index().references_are_ambiguous(def)
|| ws.open_documents().any(|(_, doc)| {
doc.path.as_deref().is_some_and(|path| path != declaring)
&& names_it_ambiguously(doc, name, def)
})
}
/// Whether the workspace overlay answered one use with exactly `def`.
fn names_def(doc: &Document, id: ReferenceId, def: &Def) -> bool {
matches!(doc.external.get(id), Some(ExternalTarget::Resolved(found)) if found == def)
}
/// Whether an open buffer holds a use of `name` that could be `def` or
/// another declaration equally — the case references declines.
fn names_it_ambiguously(doc: &Document, name: &str, def: &Def) -> bool {
doc.semantics.references().iter().enumerate().any(|(at, reference)| {
reference.name == name
&& matches!(
doc.external.get(ReferenceId(at as u32)),
Some(ExternalTarget::Ambiguous(defs)) if defs.contains(def)
)
})
}
/// One file's calls, grouped by caller, for the uses `names_target` accepts.
fn callers(
uri: &Uri,
doc: &Document,
name: &str,
names_target: impl Fn(&Reference, ReferenceId) -> bool,
) -> Vec<CallHierarchyIncomingCall> {
let semantics = &doc.semantics;
let mut groups: Vec<(SymbolId, Vec<TextRange>)> = Vec::new();
for (at, reference) in semantics.references().iter().enumerate() {
if reference.name != name || !names_target(reference, ReferenceId(at as u32)) {
continue;
}
if !is_call(doc, reference) {
continue;
}
let Some(caller) = caller_of(semantics, reference.scope) else { continue };
match groups.iter_mut().find(|(held, _)| *held == caller) {
Some((_, spans)) => spans.push(reference.name_span),
None => groups.push((caller, vec![reference.name_span])),
}
}
let positions = doc.positions();
groups
.into_iter()
.filter_map(|(caller, spans)| {
Some(CallHierarchyIncomingCall {
from: caller_item(uri, doc, caller)?,
from_ranges: spans.into_iter().map(|span| positions.range(span)).collect(),
})
})
.collect()
}
/// The declaration a call written in `scope` is credited to: the innermost
/// function or task, else the module, interface, program, package or class.
/// `None` for a call at file scope, which has no honest caller.
fn caller_of(semantics: &Semantics, mut scope: ScopeId) -> Option<SymbolId> {
loop {
let held = semantics.scope(scope)?;
let owner = held.owner;
match held.kind {
ScopeKind::Function
| ScopeKind::Task
| ScopeKind::Module
| ScopeKind::Package
| ScopeKind::Class
if owner.is_some() =>
{
return owner;
}
ScopeKind::File => return None,
_ => scope = held.parent?,
}
}
}
/// The item a caller is shown as. A module caller is the very item the
/// module hierarchy hands out — no `data` — so expanding it walks
/// instantiations, one level up the design.
fn caller_item(uri: &Uri, doc: &Document, caller: SymbolId) -> Option<CallHierarchyItem> {
let symbol = doc.semantics.symbol(caller)?;
match symbol.kind {
Kind::Function | Kind::Task => tf::item(uri.clone(), doc, symbol),
Kind::Package | Kind::Class => tf::container_item(uri.clone(), doc, symbol),
_ => super::item_of(
uri.clone(),
&doc.positions(),
&symbol.name,
symbol.name_span,
symbol.decl_span,
),
}
}
/// Whether a use of a function or task's name is a call of it.
///
/// Three uses are not: an end label (`endfunction : f`, recorded in the
/// scope *around* the function although written inside its extent), the name
/// of an out-of-body definition (recorded as a redeclaration), and the
/// Verilog result variable — a function's own name inside its own body with
/// no `(` after it, written (`f = a;`) or read (`f = f + 1;`).
fn is_call(doc: &Document, reference: &Reference) -> bool {
let semantics = &doc.semantics;
if semantics.duplicates().iter().any(|dup| dup.name_span == reference.name_span) {
return false;
}
let Some(id) = reference.resolved() else { return true };
let Some(symbol) = semantics.symbol(id) else { return true };
if let Some(body) = symbol.child_scope {
let inside = semantics.scope(body).is_some_and(|scope| {
tf::holds(scope.span, reference.name_span.start)
&& tf::holds(scope.span, reference.name_span.end)
});
if inside && !within(semantics, reference.scope, &[body]) {
return false;
}
}
!(symbol.kind == Kind::Function
&& in_own_body(semantics, reference.scope, id)
&& !followed_by_paren(doc, reference.name_span))
}
/// Whether `scope` is, or is nested in, a function body `function` owns — the
/// prototype's own scope or an out-of-body definition's.
fn in_own_body(semantics: &Semantics, mut scope: ScopeId, function: SymbolId) -> bool {
loop {
let Some(held) = semantics.scope(scope) else { return false };
if held.kind == ScopeKind::Function && held.owner == Some(function) {
return true;
}
match held.parent {
Some(parent) => scope = parent,
None => return false,
}
}
}
/// Whether the token after `span` is `(` — what makes a function's own name
/// inside its body a recursive call rather than its result variable.
fn followed_by_paren(doc: &Document, span: TextRange) -> bool {
let next = first_token_from(&doc.tokens, span.end);
doc.tokens.get(next).is_some_and(|token| token.is_sym("("))
}
/// Whether `scope` is one of `bodies` or nested inside one.
fn within(semantics: &Semantics, mut scope: ScopeId, bodies: &[ScopeId]) -> bool {
loop {
if bodies.contains(&scope) {
return true;
}
match semantics.scope(scope).and_then(|held| held.parent) {
Some(parent) => scope = parent,
None => return false,
}
}
}
/// What a callee is, before its item is built: a declaration in the same
/// file, or one the workspace index answered.
#[derive(PartialEq)]
enum Callee {
Local(SymbolId),
Indexed(Def),
}
/// Every function and task the item's body calls, one entry per callee.
pub(super) fn outgoing(
ws: &Workspace,
item: &CallHierarchyItem,
data: &Data,
) -> Vec<CallHierarchyOutgoingCall> {
let Some((doc, symbol)) = tf::target(ws, item, data) else { return Vec::new() };
let groups = callees(&doc, symbol);
let positions = doc.positions();
// Three hundred callees in one closed package are one parse, not three
// hundred.
let mut loaded = tf::Loaded::new(ws);
groups
.into_iter()
.filter_map(|(callee, spans)| {
let to = match callee {
Callee::Local(id) => tf::item(item.uri.clone(), &doc, doc.semantics.symbol(id)?),
Callee::Indexed(def) => loaded.item(&def),
}?;
let from_ranges = spans.into_iter().map(|span| positions.range(span)).collect();
Some(CallHierarchyOutgoingCall { to, from_ranges })
})
.collect()
}
/// The calls written in `symbol`'s bodies, grouped by what they resolve to.
///
/// "Bodies", plural: an `extern` prototype and its out-of-body definition are
/// two scopes owned by one symbol, and the definition is where the calls are.
fn callees(doc: &Analysis, symbol: SymbolId) -> Vec<(Callee, Vec<TextRange>)> {
let semantics = &doc.semantics;
let bodies: Vec<ScopeId> = semantics
.scopes()
.iter()
.enumerate()
.filter(|(_, scope)| scope.owner == Some(symbol))
.filter(|(_, scope)| matches!(scope.kind, ScopeKind::Function | ScopeKind::Task))
.map(|(at, _)| ScopeId(at as u32))
.collect();
let mut groups: Vec<(Callee, Vec<TextRange>)> = Vec::new();
for (at, reference) in semantics.references().iter().enumerate() {
if !within(semantics, reference.scope, &bodies) || !is_call(doc, reference) {
continue;
}
let Some(callee) = callee_of(doc, reference, ReferenceId(at as u32)) else { continue };
match groups.iter_mut().find(|(held, _)| *held == callee) {
Some((_, spans)) => spans.push(reference.name_span),
None => groups.push((callee, vec![reference.name_span])),
}
}
groups
}
/// The function or task one use resolves to, or `None` for anything else —
/// a variable, an unresolved name, a name two files declare.
fn callee_of(doc: &Document, reference: &Reference, id: ReferenceId) -> Option<Callee> {
if let Some(local) = reference.resolved() {
let symbol = doc.semantics.symbol(local)?;
return tf::is_tf(symbol.kind).then_some(Callee::Local(local));
}
match doc.external.get(id)? {
ExternalTarget::Resolved(def) if tf::is_tf(def.kind) => Some(Callee::Indexed(def.clone())),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Every use of `name` in `text`, as `(line, is a call)`.
fn classified(text: &str, name: &str) -> Vec<(usize, bool)> {
let doc = Document::new(None, text.to_string(), &vlog_semantic::WorkspaceIndex::default());
doc.semantics
.references()
.iter()
.filter(|reference| reference.name == name)
.map(|r| (text[..r.name_span.start as usize].matches('\n').count(), is_call(&doc, r)))
.collect()
}
#[test]
fn an_end_label_a_result_assignment_and_a_redeclaration_are_not_calls() {
let text = "\
class c;
extern function int f(int a);
endclass
function int c::f(int a);
f = a;
f += 1;
return f(a - 1) + f;
endfunction : f
";
assert_eq!(
classified(text, "f"),
[(3, false), (4, false), (5, false), (6, true), (6, false)],
"the out-of-body name, two result writes, a recursive call, a result read (the \
binder records no use for an out-of-body definition's end label)"
);
}
#[test]
fn the_result_variable_read_in_its_own_body_is_not_a_call() {
// QA finding 1: the classic Verilog-2001 `clog2`.
let text = "\
module lg;
function integer clog2(input integer v);
begin
clog2 = 0;
while (v > 1) begin
clog2 = clog2 + 1;
v = v >> 1;
end
end
endfunction
initial $display(clog2(16));
endmodule
";
assert_eq!(
classified(text, "clog2"),
[(3, false), (5, false), (5, false), (10, true)],
"written, written, read inside its own body; called from the module"
);
}
#[test]
fn a_bare_function_name_in_another_body_is_a_call() {
// A function with no arguments may be called without parentheses.
let text = "\
module m;
function int g(); return 1; endfunction
function int h(); return g + 1; endfunction
function int k(); k = g; endfunction
endmodule
";
assert_eq!(classified(text, "g"), [(2, true), (3, true)]);
assert_eq!(classified(text, "k"), [(3, false)], "`k`'s own result, beside the call");
}
#[test]
fn an_end_label_is_not_a_call_but_a_recursive_call_is() {
let text =
"module m;\n function int f(int a);\n return f(a);\n endfunction : f\nendmodule\n";
assert_eq!(classified(text, "f"), [(2, true), (3, false)]);
}
#[test]
fn a_task_enable_without_parentheses_is_a_call() {
let text = "module m;\n task t; endtask\n initial t;\nendmodule\n";
assert_eq!(classified(text, "t"), [(2, true)]);
}
// ------------------------------------------------------------------
// The two ambiguity fallbacks (QA finding 4)
// ------------------------------------------------------------------
/// Package `p` declared twice, each with `f`; the caller writes `p::f()`.
const Z: &str = "package p;\n function int f(); return 1; endfunction\nendpackage\n";
const USER: &str = "module user;\n int k = p::f();\nendmodule\n";
/// A workspace over `root` holding the two `p`s and, if `user` is set,
/// a closed `user.sv`; plus `z1.f`'s indexed record and `z1.sv`'s path.
fn ambiguous(name: &str, user: bool) -> (std::path::PathBuf, Workspace, Def, PathBuf) {
let root =
std::env::temp_dir().join(format!("lucisv_server_calls_{}_{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(root.join("src")).expect("dir");
std::fs::write(root.join("src/z1.sv"), Z).expect("z1");
std::fs::write(root.join("src/z2.sv"), Z).expect("z2");
if user {
std::fs::write(root.join("src/user.sv"), USER).expect("user");
}
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![root.join("src")]);
let z1 = root.join("src/z1.sv");
let def = ws
.index()
.member_in("p", "f", vlog_semantic::Surface::Connection)
.iter()
.find(|def| ws.index().path(def.file) == Some(z1.as_path()))
.cloned()
.expect("z1's f");
(root, ws, def, z1)
}
#[test]
fn an_index_that_marks_the_uses_ambiguous_declines() {
let (root, ws, def, z1) = ambiguous("index", true);
assert!(ws.index().references_are_ambiguous(&def), "premise: user.sv is indexed");
assert_eq!(ws.open_documents().count(), 0, "premise: no buffer is open");
assert!(declined(&ws, &def, "f", &z1));
let _ = std::fs::remove_dir_all(root);
}
#[test]
fn an_open_buffer_holding_an_ambiguous_use_declines() {
// The buffer lives outside the indexed folder, so only its own
// overlay — not the index — knows the use is ambiguous.
let (root, mut ws, def, z1) = ambiguous("buffer", false);
assert!(!ws.index().references_are_ambiguous(&def), "premise: nothing indexed uses it");
assert!(!declined(&ws, &def, "f", &z1), "nothing ambiguous yet");
let outside = root.join("user.sv");
let uri = path_to_uri(&outside).expect("uri");
ws.set_document(uri, USER.to_string());
assert!(declined(&ws, &def, "f", &z1));
let _ = std::fs::remove_dir_all(root);
}
#[test]
fn an_ambiguous_use_in_the_declaring_file_itself_does_not_decline() {
let (root, mut ws, def, z1) = ambiguous("declaring", false);
ws.set_document(path_to_uri(&z1).expect("uri"), format!("{Z}{USER}"));
assert!(!declined(&ws, &def, "f", &z1), "the declaring file answers for itself");
let _ = std::fs::remove_dir_all(root);
}
#[test]
fn a_call_at_file_scope_has_no_caller() {
let text = "function int f(); return 1; endfunction\nlocalparam int P = f();\n";
let (tree, _) = vlog_parser::parse_source_tolerant(text);
let semantics = vlog_semantic::analyze(&tree, text);
let call = semantics.references().iter().find(|r| r.name == "f").expect("the call");
assert_eq!(caller_of(&semantics, call.scope), None);
}
}
+416
View File
@@ -0,0 +1,416 @@
//! Function and task items for the call hierarchy: what the cursor names,
//! what encloses it, and how an item handed back by the client is found
//! again.
//!
//! A module item carries no `data` and is re-found by name, exactly as it
//! always was. A function or task item carries a small [`Data`] object — its
//! kind, its name and the byte offset of its name — because two functions of
//! one name are ordinary (every module may declare its own `log2`) and the
//! name alone cannot tell them apart.
//!
//! See `docs/features/call-hierarchy-everywhere/README.md`.
use std::collections::HashMap;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use lsp_types::{CallHierarchyItem, SymbolKind, Uri};
use serde_json::{json, Value};
use vlog_parser::TextRange;
use vlog_semantic::{Def, Definition, ScopeKind, Semantics, Symbol, SymbolId, SymbolKind as Kind};
use crate::nav::indexed_def_for_symbol;
use crate::state::{Document, Workspace};
use crate::uri::{path_to_uri, uri_to_path};
/// What a non-module item carries in `CallHierarchyItem.data`.
///
/// Serialized as `{"kind": "function"|"task"|"package"|"class", "name": …,
/// "offset": …}`, where `offset` is the byte offset of the declared name in
/// the item's file when the item was built.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Data {
pub kind: ItemKind,
pub name: String,
pub offset: u32,
}
/// Which declaration a [`Data`] item stands for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum ItemKind {
Function,
Task,
/// A package caller: the body of a package called a function outside any
/// function of its own. It has no calls of its own to expand.
Package,
/// A class caller, for a call written in a class body outside a method.
Class,
}
impl ItemKind {
fn tag(self) -> &'static str {
match self {
ItemKind::Function => "function",
ItemKind::Task => "task",
ItemKind::Package => "package",
ItemKind::Class => "class",
}
}
fn of_tag(tag: &str) -> Option<ItemKind> {
match tag {
"function" => Some(ItemKind::Function),
"task" => Some(ItemKind::Task),
"package" => Some(ItemKind::Package),
"class" => Some(ItemKind::Class),
_ => None,
}
}
/// The semantic kind a function or task item re-finds; `None` for the
/// container kinds, which are never re-found.
fn semantic(self) -> Option<Kind> {
match self {
ItemKind::Function => Some(Kind::Function),
ItemKind::Task => Some(Kind::Task),
ItemKind::Package | ItemKind::Class => None,
}
}
}
impl Data {
/// The JSON object the item carries.
fn to_value(&self) -> Value {
json!({ "kind": self.kind.tag(), "name": self.name, "offset": self.offset })
}
/// The data of an item this server built, or `None` for a module item
/// (which carries none) and for anything it does not recognise.
pub fn of(item: &CallHierarchyItem) -> Option<Data> {
let data = item.data.as_ref()?;
let kind = ItemKind::of_tag(data.get("kind")?.as_str()?)?;
let name = data.get("name")?.as_str()?.to_string();
let offset = u32::try_from(data.get("offset")?.as_u64()?).ok()?;
Some(Data { kind, name, offset })
}
}
/// Whether a declaration is something a call hierarchy can stand on as a
/// function or task.
pub(super) fn is_tf(kind: Kind) -> bool {
matches!(kind, Kind::Function | Kind::Task)
}
/// One file's analysis: the open buffer's own, or one built from the text on
/// disk for a file no editor has open.
pub(super) enum Analysis<'a> {
Open(&'a Document),
Fresh(Box<Document>),
}
impl Deref for Analysis<'_> {
type Target = Document;
fn deref(&self) -> &Document {
match self {
Analysis::Open(doc) => doc,
Analysis::Fresh(doc) => doc,
}
}
}
/// The analysis behind an item's URI: the open buffer, else the file on disk.
pub(super) fn load<'a>(ws: &'a Workspace, uri: &Uri) -> Option<Analysis<'a>> {
match ws.document(uri) {
Some(doc) => Some(Analysis::Open(doc)),
None => load_path(ws, &uri_to_path(uri)?),
}
}
/// The analysis of one path: the open buffer for it, else a fresh analysis
/// of the text on disk against the current index.
pub(super) fn load_path<'a>(ws: &'a Workspace, path: &Path) -> Option<Analysis<'a>> {
if let Some(doc) = ws.document_for_path(path) {
return Some(Analysis::Open(doc));
}
let text = ws.text_of(path)?;
Some(Analysis::Fresh(Box::new(Document::new(Some(path.to_path_buf()), text, ws.index()))))
}
/// The analyses one request has loaded, one per path, so a request that
/// builds items in one closed file many times — `outgoingCalls` on a function
/// calling three hundred functions of one package — parses it once.
///
/// Lives for one request and no longer: nothing here may outlast a change to
/// the text it was built from.
pub(super) struct Loaded<'a> {
ws: &'a Workspace,
held: HashMap<PathBuf, Option<Analysis<'a>>>,
}
impl<'a> Loaded<'a> {
pub fn new(ws: &'a Workspace) -> Loaded<'a> {
Loaded { ws, held: HashMap::new() }
}
/// The analysis of `path`, loaded on first ask.
pub fn get(&mut self, path: &Path) -> Option<&Analysis<'a>> {
let ws = self.ws;
self.held.entry(path.to_path_buf()).or_insert_with(|| load_path(ws, path)).as_ref()
}
}
/// The function or task the cursor names — its declaration, a call, an end
/// label — or, failing that, the one whose body encloses the cursor.
///
/// A call two files could answer returns both declarations, as
/// `textDocument/definition` does; the client asks the user which one.
pub(super) fn prepare(
ws: &Workspace,
doc: &Document,
uri: &Uri,
offset: u32,
) -> Option<Vec<CallHierarchyItem>> {
let named = doc
.external
.definition_of(&doc.semantics, offset)
.or_else(|| doc.external.definition_of(&doc.semantics, offset.checked_sub(1)?));
let items: Vec<CallHierarchyItem> = match named {
Some(Definition::Local(symbol)) if is_tf(symbol.kind) => {
item(uri.clone(), doc, symbol).into_iter().collect()
}
Some(Definition::External(defs)) => {
let mut loaded = Loaded::new(ws);
defs.iter().filter(|def| is_tf(def.kind)).filter_map(|def| loaded.item(def)).collect()
}
_ => Vec::new(),
};
if !items.is_empty() {
return Some(items);
}
let symbol = enclosing(&doc.semantics, offset)?;
Some(vec![item(uri.clone(), doc, doc.semantics.symbol(symbol)?)?])
}
/// The function or task whose body holds `offset`, innermost first.
///
/// An out-of-body method definition (`function void c::f(); … endfunction`)
/// is a scope owned by the prototype's symbol, so its body answers the
/// prototype.
fn enclosing(semantics: &Semantics, offset: u32) -> Option<SymbolId> {
semantics
.scopes()
.iter()
.filter(|scope| matches!(scope.kind, ScopeKind::Function | ScopeKind::Task))
.filter(|scope| holds(scope.span, offset))
.filter(|scope| {
scope.owner.and_then(|id| semantics.symbol(id)).is_some_and(|s| is_tf(s.kind))
})
.min_by_key(|scope| scope.span.end - scope.span.start)
.and_then(|scope| scope.owner)
}
/// The item for a function or task declared in `doc`, reported against `uri`.
pub(super) fn item(uri: Uri, doc: &Document, symbol: &Symbol) -> Option<CallHierarchyItem> {
let kind = if symbol.kind == Kind::Task { ItemKind::Task } else { ItemKind::Function };
let in_class = scope_kind(&doc.semantics, symbol) == Some(ScopeKind::Class);
let lsp_kind = if in_class { SymbolKind::METHOD } else { SymbolKind::FUNCTION };
built(uri, doc, symbol, kind, lsp_kind)
}
/// The item for a package or class that is a caller.
pub(super) fn container_item(
uri: Uri,
doc: &Document,
symbol: &Symbol,
) -> Option<CallHierarchyItem> {
match symbol.kind {
Kind::Package => built(uri, doc, symbol, ItemKind::Package, SymbolKind::PACKAGE),
Kind::Class => built(uri, doc, symbol, ItemKind::Class, SymbolKind::CLASS),
_ => None,
}
}
/// An item with [`Data`], framed against `doc`'s text.
fn built(
uri: Uri,
doc: &Document,
symbol: &Symbol,
kind: ItemKind,
lsp_kind: SymbolKind,
) -> Option<CallHierarchyItem> {
let mut item =
super::item_of(uri, &doc.positions(), &symbol.name, symbol.name_span, symbol.decl_span)?;
item.kind = lsp_kind;
item.detail = container_name(&doc.semantics, symbol);
let data = Data { kind, name: symbol.name.clone(), offset: symbol.name_span.start };
item.data = Some(data.to_value());
Some(item)
}
/// The kind of the scope a declaration is bound in.
fn scope_kind(semantics: &Semantics, symbol: &Symbol) -> Option<ScopeKind> {
semantics.scope(symbol.scope).map(|scope| scope.kind)
}
/// The name of the module, package or class a function is declared in —
/// shown beside the name, so two `log2`s in one list can be told apart.
fn container_name(semantics: &Semantics, symbol: &Symbol) -> Option<String> {
let owner = semantics.scope(symbol.scope)?.owner?;
Some(semantics.symbol(owner)?.name.clone())
}
impl Loaded<'_> {
/// The item for a function or task another file declares, re-found in
/// that file's live analysis so its ranges are the text's as it is now.
pub fn item(&mut self, def: &Def) -> Option<CallHierarchyItem> {
let ws = self.ws;
let path = ws.index().path(def.file)?;
let uri = path_to_uri(path)?;
let doc = self.get(path)?;
let symbol = live_symbol(ws, doc, def)?;
item(uri, doc, doc.semantics.symbol(symbol)?)
}
}
/// The symbol in `doc` that is the indexed declaration `def`: by identity —
/// asked first of the symbol still at the recorded position, which is the
/// answer unless the file moved — and by position as a last resort.
fn live_symbol(ws: &Workspace, doc: &Document, def: &Def) -> Option<SymbolId> {
let candidates: Vec<SymbolId> = doc
.semantics
.symbols()
.iter()
.enumerate()
.filter(|(_, symbol)| symbol.kind == def.kind)
.map(|(at, _)| SymbolId(at as u32))
.collect();
let symbol = |id: &SymbolId| doc.semantics.symbol(*id);
let is_def =
|id: &&SymbolId| symbol(id).and_then(|s| indexed_def_for_symbol(ws, doc, s)) == Some(def);
let at_position = |id: &&SymbolId| symbol(id).is_some_and(|s| s.name_span == def.name_span);
let positioned = candidates.iter().find(at_position);
positioned.filter(is_def).or_else(|| candidates.iter().find(is_def)).or(positioned).copied()
}
/// The declaration a function or task item stands for, in its file's live
/// analysis.
///
/// The recorded offset wins; an edit since the item was built moves it, and
/// then the item's own selection range is tried. Failing both, the name
/// decides only when it is unambiguous: the one declaration of that name and
/// kind whose container is the item's `detail`.
/// Otherwise nothing — two `log2`s in two modules are ordinary, and answering
/// for the wrong one would be a confident wrong hierarchy.
pub(super) fn target<'a>(
ws: &'a Workspace,
item: &CallHierarchyItem,
data: &Data,
) -> Option<(Analysis<'a>, SymbolId)> {
let kind = data.kind.semantic()?;
let doc = load(ws, &item.uri)?;
let candidates: Vec<SymbolId> = doc
.semantics
.symbols_named(&data.name)
.filter(|id| doc.semantics.symbol(*id).is_some_and(|s| s.kind == kind))
.collect();
let starts_at = |offset: u32| {
candidates
.iter()
.find(|id| doc.semantics.symbol(**id).is_some_and(|s| s.name_span.start == offset))
.copied()
};
let selected = doc.positions().offset(item.selection_range.start);
let found = starts_at(data.offset)
.or_else(|| starts_at(selected))
.or_else(|| by_name(&doc.semantics, &candidates, item.detail.as_deref()))?;
Some((doc, found))
}
/// The one candidate a name alone can stand for: the only one declared in
/// the container the item's `detail` names (no container for `$unit`).
///
/// The container is asked even of a lone candidate: when `mb`'s `log2` has
/// been renamed away, `ma`'s is the only `log2` left, and it is still not the
/// function the item stood for.
fn by_name(
semantics: &Semantics,
candidates: &[SymbolId],
detail: Option<&str>,
) -> Option<SymbolId> {
let mut inside = candidates.iter().filter(|id| {
semantics.symbol(**id).is_some_and(|s| container_name(semantics, s).as_deref() == detail)
});
match (inside.next(), inside.next()) {
(Some(one), None) => Some(*one),
_ => None,
}
}
/// Whether `span` holds `offset`, its end included.
pub(super) fn holds(span: TextRange, offset: u32) -> bool {
span.start <= offset && offset <= span.end
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use lsp_types::{Position, Range};
use super::*;
fn bare(data: Option<Value>) -> CallHierarchyItem {
let range = Range::new(Position::new(0, 0), Position::new(0, 1));
CallHierarchyItem {
name: "f".to_string(),
kind: SymbolKind::FUNCTION,
tags: None,
detail: None,
uri: Uri::from_str("file:///x.sv").expect("uri"),
range,
selection_range: range,
data,
}
}
#[test]
fn data_round_trips_through_its_json() {
for kind in [ItemKind::Function, ItemKind::Task, ItemKind::Package, ItemKind::Class] {
let data = Data { kind, name: "f".to_string(), offset: 42 };
assert_eq!(Data::of(&bare(Some(data.to_value()))), Some(data));
}
}
#[test]
fn a_module_item_and_foreign_data_carry_no_data_of_ours() {
assert_eq!(Data::of(&bare(None)), None, "a module item");
for foreign in [
json!({ "kind": "rocket", "name": "f", "offset": 1 }),
json!({ "kind": "function", "name": "f" }),
json!({ "kind": "function", "name": 7, "offset": 1 }),
json!({ "kind": "function", "name": "f", "offset": -1 }),
json!({ "kind": "function", "name": "f", "offset": 5_000_000_000u64 }),
json!("function"),
] {
assert_eq!(Data::of(&bare(Some(foreign.clone()))), None, "{foreign}");
}
}
#[test]
fn the_innermost_function_or_task_encloses_an_offset() {
let text = "module m;\n task t;\n begin\n x = 1;\n end\n endtask\n \
wire w;\nendmodule\n";
let (tree, _) = vlog_parser::parse_source_tolerant(text);
let semantics = vlog_semantic::analyze(&tree, text);
let name = |offset| {
enclosing(&semantics, offset)
.and_then(|id| semantics.symbol(id))
.map(|s| s.name.clone())
};
let at = |needle: &str| text.find(needle).expect("needle") as u32;
assert_eq!(name(at("x = 1")).as_deref(), Some("t"), "through a nested block");
assert_eq!(name(at("endtask") + 7).as_deref(), Some("t"), "the end included");
assert_eq!(name(at("wire")), None, "a module item is in no task");
}
}
+32 -34
View File
@@ -170,16 +170,10 @@ fn leaves_this_file(ws: &Workspace, doc: &Document, offset: u32) -> bool {
}
// A member is reachable as `unit::name`, as `.name` in a connection list
// or as the tail of a hierarchical path, so the unit that owns the
// declaring scope is what to ask about.
let owner = doc
.semantics
.scope(symbol.scope)
.and_then(|scope| scope.owner)
.and_then(|owner| doc.semantics.symbol(owner));
match owner {
Some(owner) => {
!ws.index().member_in(&owner.name, &symbol.name, Surface::Hierarchical).is_empty()
}
// declaring scope is what to ask about — under the key the index files
// it by, which for a named block is `module.label`.
match doc.semantics.member_key(symbol.scope) {
Some(key) => !ws.index().member_in(&key, &symbol.name, Surface::Hierarchical).is_empty(),
None => false,
}
}
@@ -262,11 +256,8 @@ fn indexed_def_in_file<'a>(
let defs = if symbol.scope == semantics.file_scope() {
ws.index().units(&symbol.name)
} else {
let owner = semantics
.scope(symbol.scope)
.and_then(|scope| scope.owner)
.and_then(|owner| semantics.symbol(owner))?;
ws.index().member_in(&owner.name, &symbol.name, Surface::Hierarchical)
let key = semantics.member_key(symbol.scope)?;
ws.index().member_in(&key, &symbol.name, Surface::Hierarchical)
};
if defs.len() != 1 {
return None;
@@ -1510,8 +1501,8 @@ endmodule
);
assert!(leaves_this_file(&ws, doc, at(text, "module m") + 7), "and the module is a unit");
assert!(
!leaves_this_file(&ws, doc, at(text, "wire gen_only") + 5),
"but a generate-block-scoped net is on neither surface"
leaves_this_file(&ws, doc, at(text, "wire gen_only") + 5),
"and since TODO §65.1 so is a generate-block-scoped net, under `m.g`: `u_m.g.gen_only`"
);
assert!(
!leaves_this_file(&ws, doc, at(text, "assign b") + 7),
@@ -2248,13 +2239,13 @@ endpackage
let _ = fs::remove_dir_all(&dir);
}
/// A net declared inside a **generate block** is on neither surface: its
/// scope is the block's, not the module's (`hierarchical-tail`, "a unit's
/// members are the symbols of its own scope"). So the gate still says no
/// and the answer is still the honest single-file one — the same refusal
/// a rename gives `u_x.g.sig`.
/// A net declared inside a **generate block**. Until TODO §65.1 it was on
/// neither surface and this pinned the honest single-file answer; a named
/// block is now on its module's hierarchical surface and its members under
/// `gleaf.g` (`docs/features/generate-label-rename/README.md`), so the gate
/// says yes and `u_g.g.gsig` in the other file is one of the references.
#[test]
fn a_generate_block_scoped_net_still_never_asks_the_workspace() {
fn a_generate_block_scoped_net_is_found_through_the_instance_path() {
let dir = temp_dir("hier_generate");
let leaf = "\
module gleaf;
@@ -2278,11 +2269,15 @@ endmodule
let decl = at(leaf, "wire gsig") + 5;
let doc = ws.document(&leaf_uri).expect("open");
assert!(!leaves_this_file(&ws, doc, decl), "the index exports it on no surface");
assert!(leaves_this_file(&ws, doc, decl), "the index exports it hierarchically");
assert_eq!(
places(&references(&ws, &leaf_uri, decl, true)),
vec![("gleaf.sv".to_string(), 2), ("gleaf.sv".to_string(), 3)],
"this file only, and `u_g.g.gsig` is left to the editor"
vec![
("gleaf.sv".to_string(), 2),
("gleaf.sv".to_string(), 3),
("guser.sv".to_string(), 3)
],
"this file and `u_g.g.gsig`"
);
let _ = fs::remove_dir_all(&dir);
}
@@ -2941,12 +2936,11 @@ endmodule
}
/// Case (a), sharpened: an **indexed generate array**, not just a named
/// block. `u_g.gen[0].gsig` is still on neither surface — the array
/// index changes how many instances of the scope exist, not which scope
/// `gsig` belongs to — so the honest single-file fallback must hold here
/// too.
/// block. The array index changes how many instances of the scope exist,
/// not which scope `gsig` belongs to — which since TODO §65.1 is exactly
/// why `u_g.gen[0].gsig` is walked as `u_g.gen.gsig` and found.
#[test]
fn qa_a_generate_for_arrays_scoped_net_still_never_asks_the_workspace() {
fn qa_a_generate_for_arrays_scoped_net_is_found_through_the_indexed_path() {
let dir = temp_dir("qa_generate_for");
let leaf = "\
module gfleaf;
@@ -2970,11 +2964,15 @@ endmodule
let decl = at(leaf, "wire gsig") + 5;
let doc = ws.document(&leaf_uri).expect("open");
assert!(!leaves_this_file(&ws, doc, decl), "an indexed generate scope is on no surface");
assert!(leaves_this_file(&ws, doc, decl), "a generate array's scope is exported too");
assert_eq!(
places(&references(&ws, &leaf_uri, decl, true)),
vec![("gfleaf.sv".to_string(), 2), ("gfleaf.sv".to_string(), 3)],
"this file only; `u_g.gen[0].gsig` is left to the editor"
vec![
("gfleaf.sv".to_string(), 2),
("gfleaf.sv".to_string(), 3),
("gfuser.sv".to_string(), 3)
],
"this file and `u_g.gen[0].gsig`"
);
let _ = fs::remove_dir_all(&dir);
}
+6 -1
View File
@@ -1168,7 +1168,12 @@ mod tests {
#[test]
fn a_macro_file_the_rename_does_read_is_warned_about_exactly_once() {
let tree = Tree::new("macrocontrol");
let far = format!("module far;\n sub u_far (.sig(1'b0));\n {M_FAR}endmodule\n");
// Spelled after a `.`: since §65.1's scoping of rename warnings, a
// *bare* `sig` in `far`'s own macro is `far`'s word, not `sub`'s port,
// and the engine rightly says nothing about it; a dotted one may be a
// path to the port and is still said — once.
let dotted = M_FAR.replace("sig)", "u_far.sig)");
let far = format!("module far;\n sub u_far (.sig(1'b0));\n {dotted}endmodule\n");
let (ws, uri) = macro_workspace(&tree, &far);
let handed = ws.rename_sources_traced(&tree.path.join("top.sv"), "sig", Some("probe")).0;
@@ -125,7 +125,7 @@ fn widen_of_takes_the_cheap_path_for_a_pure_add_and_nothing_else() {
// directory is raised on its own and none of them is ever dropped — so
// this is an add like any other, and the widen's own file diff is what
// stops the overlap being read twice
// (`state::tests::a_widen_that_subsumes_the_old_scope_reads_only_the_files_it_adds`).
// (`state::tests::widen::a_widen_that_subsumes_the_old_scope_reads_only_the_files_it_adds`).
let ip = PathBuf::from("/w");
assert_eq!(
widen_of(std::slice::from_ref(&a), &[ip.clone(), a.clone()]),
@@ -0,0 +1,691 @@
//! Call hierarchy from wherever the cursor is, and for functions and tasks
//! (`docs/features/call-hierarchy-everywhere/README.md`), driven through the
//! real dispatch.
//!
//! The fixture is a small design: a package of functions (one recursive), a
//! module that imports it and calls through a function, a task and an
//! `always` block, a top that instantiates that module and calls the package
//! with a scoped name, and a class whose methods call each other through
//! `this.` and through a handle.
use lsp_types::request::{CallHierarchyIncomingCalls, CallHierarchyOutgoingCalls};
use lsp_types::{CallHierarchyIncomingCall, CallHierarchyItem, CallHierarchyOutgoingCall};
use super::*;
const PKG: &str = "\
package util_pkg;
function automatic int add1(int a);
return a + 1;
endfunction : add1
function automatic int fact(int n);
if (n <= 1) return 1;
return n * fact(n - 1);
endfunction
endpackage
";
const CORE: &str = "\
module core (input logic clk, output int q);
import util_pkg::*;
int r;
function automatic int twice(int a);
twice = add1(a) + add1(a);
endfunction
task automatic kick(input int v);
r = twice(v);
$display(\"%0d\", v);
endtask
always_ff @(posedge clk) begin
q <= twice(r);
end
initial kick(3);
endmodule
";
const TOP: &str = "\
// the top of the design
module top;
logic clk;
int q;
core u_core (.clk(clk), .q(q));
int z = util_pkg::add1(2);
endmodule
";
const CLS: &str = "\
class counter;
int n;
extern function void reset();
function void bump();
n++;
endfunction
function void bump_twice();
bump();
this.bump();
endfunction
task run();
counter h;
h = new;
h.bump();
endtask
endclass
class fancy extends counter;
function void bump_more();
super.bump();
endfunction
endclass
function void counter::reset();
bump();
endfunction
";
/// The design on disk, a wide session over it, `core.sv` open.
fn design(name: &str) -> (Tree, Session, Uri) {
let tree = Tree::new(name);
tree.write("util_pkg.sv", PKG);
tree.write("core.sv", CORE);
tree.write("top.sv", TOP);
tree.write("cls.sv", CLS);
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("core.sv"), CORE);
session.drain();
(tree, session, uri)
}
/// The LSP position of the `nth` occurrence of `needle` in `text`, `skip`
/// bytes in.
fn pos(text: &str, needle: &str, nth: usize, skip: usize) -> Value {
let mut at = text.find(needle).expect("needle");
for _ in 0..nth {
at = text[at + 1..].find(needle).expect("nth needle") + at + 1;
}
let at = at + skip;
let line = text[..at].matches('\n').count();
let character = at - text[..at].rfind('\n').map_or(0, |nl| nl + 1);
serde_json::json!({ "line": line, "character": character })
}
/// `prepareCallHierarchy` at a position: `None` for a `null` answer.
fn prepare(session: &mut Session, uri: &Uri, position: Value) -> Option<Vec<CallHierarchyItem>> {
let result = session.result(
CallHierarchyPrepare::METHOD,
serde_json::json!({ "textDocument": { "uri": uri }, "position": position }),
);
serde_json::from_value(result).expect("items or null")
}
/// The one item prepared at a position.
fn one(session: &mut Session, uri: &Uri, position: Value) -> CallHierarchyItem {
let items = prepare(session, uri, position).expect("an item");
assert_eq!(items.len(), 1, "{items:#?}");
items.into_iter().next().expect("one")
}
fn incoming(session: &mut Session, item: &CallHierarchyItem) -> Vec<CallHierarchyIncomingCall> {
let result =
session.result(CallHierarchyIncomingCalls::METHOD, serde_json::json!({ "item": item }));
serde_json::from_value(result).expect("incoming calls")
}
fn outgoing(session: &mut Session, item: &CallHierarchyItem) -> Vec<CallHierarchyOutgoingCall> {
let result =
session.result(CallHierarchyOutgoingCalls::METHOD, serde_json::json!({ "item": item }));
serde_json::from_value(result).expect("outgoing calls")
}
/// An item as `(name, file name, selection line)`.
fn shape(item: &CallHierarchyItem) -> (String, String, u32) {
let file = item.uri.as_str().rsplit('/').next().unwrap_or("?").to_string();
(item.name.clone(), file, item.selection_range.start.line)
}
/// Each incoming call as `(caller name, caller file, lines of its ranges)`.
fn callers(calls: &[CallHierarchyIncomingCall]) -> Vec<(String, String, Vec<u32>)> {
calls
.iter()
.map(|call| {
let (name, file, _) = shape(&call.from);
(name, file, call.from_ranges.iter().map(|r| r.start.line).collect())
})
.collect()
}
/// Each outgoing call as `(callee name, callee file, lines of its ranges)`.
fn callees(calls: &[CallHierarchyOutgoingCall]) -> Vec<(String, String, Vec<u32>)> {
calls
.iter()
.map(|call| {
let (name, file, _) = shape(&call.to);
(name, file, call.from_ranges.iter().map(|r| r.start.line).collect())
})
.collect()
}
fn s(text: &str) -> String {
text.to_string()
}
// ----------------------------------------------------------------------
// prepare, every position
// ----------------------------------------------------------------------
#[test]
fn an_instance_name_prepares_the_instantiated_module() {
let (tree, mut session, _) = design("hev_instance");
let top = session.open(&tree.path.join("top.sv"), TOP);
let item = one(&mut session, &top, pos(TOP, "u_core", 0, 2));
assert_eq!(shape(&item), (s("core"), s("core.sv"), 0));
assert_eq!(item.kind, lsp_types::SymbolKind::MODULE);
assert!(item.data.is_none(), "a module item is the M11 item, unchanged");
}
#[test]
fn a_function_declaration_a_call_and_its_end_label_prepare_the_function() {
let (tree, mut session, core) = design("hev_function");
let pkg = session.open(&tree.path.join("util_pkg.sv"), PKG);
let declared = one(&mut session, &pkg, pos(PKG, "add1(int", 0, 1));
let labelled = one(&mut session, &pkg, pos(PKG, ": add1", 0, 3));
let called = one(&mut session, &core, pos(CORE, "add1(a)", 0, 0));
for item in [&declared, &labelled, &called] {
assert_eq!(shape(item), (s("add1"), s("util_pkg.sv"), 1));
assert_eq!(item.kind, lsp_types::SymbolKind::FUNCTION);
assert_eq!(item.detail.as_deref(), Some("util_pkg"));
let data = item.data.as_ref().expect("data");
assert_eq!(data["kind"], "function");
assert_eq!(data["name"], "add1");
assert!(data["offset"].is_u64(), "{data}");
}
assert_eq!(declared, called, "one item, wherever it was prepared from");
}
#[test]
fn a_cursor_just_past_a_call_name_prepares_the_function() {
let (_tree, mut session, core) = design("hev_caret");
let item = one(&mut session, &core, pos(CORE, "twice(v)", 0, 5));
assert_eq!(shape(&item), (s("twice"), s("core.sv"), 4));
}
#[test]
fn a_task_declaration_and_a_call_prepare_the_task() {
let (_tree, mut session, core) = design("hev_task");
for position in [pos(CORE, "kick(input", 0, 0), pos(CORE, "kick(3)", 0, 1)] {
let item = one(&mut session, &core, position);
assert_eq!(shape(&item), (s("kick"), s("core.sv"), 8));
assert_eq!(item.data.as_ref().expect("data")["kind"], "task");
assert_eq!(item.kind, lsp_types::SymbolKind::FUNCTION);
}
}
#[test]
fn inside_a_function_or_task_body_prepares_it() {
let (_tree, mut session, core) = design("hev_body");
let in_task = one(&mut session, &core, pos(CORE, "$display", 0, 2));
assert_eq!(shape(&in_task), (s("kick"), s("core.sv"), 8), "a system task names no item");
let on_arg = one(&mut session, &core, pos(CORE, "v);", 0, 0));
assert_eq!(shape(&on_arg).0, "kick", "a use of an argument");
let on_keyword = one(&mut session, &core, pos(CORE, "endfunction", 0, 3));
assert_eq!(shape(&on_keyword).0, "twice", "the closing keyword");
}
#[test]
fn inside_a_module_body_prepares_the_module() {
let (_tree, mut session, core) = design("hev_module");
for (what, position) in [
("a net declaration", pos(CORE, "int r", 0, 4)),
("inside an always block", pos(CORE, "q <=", 0, 0)),
("an import", pos(CORE, "import", 0, 2)),
] {
let item = one(&mut session, &core, position);
assert_eq!(shape(&item), (s("core"), s("core.sv"), 0), "{what}");
assert!(item.data.is_none(), "{what}: the module item, as M11 builds it");
}
}
#[test]
fn where_nothing_encloses_the_cursor_prepare_is_null() {
let (tree, mut session, _) = design("hev_null");
let top = session.open(&tree.path.join("top.sv"), TOP);
assert!(prepare(&mut session, &top, pos(TOP, "the top", 0, 0)).is_none(), "a file comment");
let pkg = session.open(&tree.path.join("util_pkg.sv"), PKG);
assert!(
prepare(&mut session, &pkg, pos(PKG, "\n\n", 0, 1)).is_none(),
"a package body outside its functions"
);
let cls = session.open(&tree.path.join("cls.sv"), CLS);
assert!(
prepare(&mut session, &cls, pos(CLS, "int n", 0, 4)).is_none(),
"a class property: the call hierarchy has no class node to open"
);
}
#[test]
fn existing_module_answers_are_unchanged() {
let (tree, mut session, core) = design("hev_unchanged");
let top = session.open(&tree.path.join("top.sv"), TOP);
let declared = one(&mut session, &core, pos(CORE, "module core", 0, 7));
let instantiated = one(&mut session, &top, pos(TOP, "core u_core", 0, 1));
assert_eq!(declared, instantiated);
assert!(declared.data.is_none());
assert_eq!(callers(&incoming(&mut session, &declared)), [(s("top"), s("top.sv"), vec![4])]);
assert!(outgoing(&mut session, &declared).is_empty(), "a module lists no function calls");
}
// ----------------------------------------------------------------------
// incoming and outgoing for functions and tasks
// ----------------------------------------------------------------------
#[test]
fn a_function_called_from_a_task_and_an_always_block() {
let (_tree, mut session, core) = design("hev_twice");
let twice = one(&mut session, &core, pos(CORE, "twice(int", 0, 0));
let calls = incoming(&mut session, &twice);
assert_eq!(
callers(&calls),
[(s("core"), s("core.sv"), vec![14]), (s("kick"), s("core.sv"), vec![9])],
"the task and the module of the always block; not `twice = …`, which is a result"
);
assert_eq!(calls[0].from.kind, lsp_types::SymbolKind::MODULE);
assert!(calls[0].from.data.is_none(), "a module caller is the M11 item");
assert_eq!(calls[1].from.data.as_ref().expect("data")["kind"], "task");
let from = calls[1].from_ranges[0];
assert_eq!((from.start.character, from.end.character), (8, 13), "the call's name");
}
#[test]
fn a_task_called_from_an_initial_block_and_its_outgoing_calls() {
let (_tree, mut session, core) = design("hev_kick");
let kick = one(&mut session, &core, pos(CORE, "kick(input", 0, 0));
assert_eq!(callers(&incoming(&mut session, &kick)), [(s("core"), s("core.sv"), vec![17])]);
assert_eq!(
callees(&outgoing(&mut session, &kick)),
[(s("twice"), s("core.sv"), vec![9])],
"`$display` is a system task and is skipped"
);
}
#[test]
fn outgoing_calls_resolve_into_another_file_grouped_by_callee() {
let (_tree, mut session, core) = design("hev_out");
let twice = one(&mut session, &core, pos(CORE, "twice(int", 0, 0));
let calls = outgoing(&mut session, &twice);
assert_eq!(callees(&calls), [(s("add1"), s("util_pkg.sv"), vec![5, 5])]);
assert_eq!(calls[0].to.data.as_ref().expect("data")["kind"], "function");
}
#[test]
fn a_package_function_is_called_from_modules_in_other_files() {
// `util_pkg.sv` and `top.sv` are closed: the item is prepared from the
// call in `core.sv`, and the callers are found the way references are.
let (_tree, mut session, core) = design("hev_cross");
let add1 = one(&mut session, &core, pos(CORE, "add1(a)", 0, 0));
let calls = incoming(&mut session, &add1);
assert_eq!(
callers(&calls),
[(s("twice"), s("core.sv"), vec![5, 5]), (s("top"), s("top.sv"), vec![5])],
"a function caller in an open file, a module caller in a closed one; the end label is no call"
);
let top = &calls[1].from;
let instantiated = outgoing(&mut session, top);
assert_eq!(
callees(&instantiated),
[(s("core"), s("core.sv"), vec![4])],
"expanding a module caller walks the design, one level down"
);
}
#[test]
fn the_cross_file_answer_matches_references() {
let (_tree, mut session, core) = design("hev_refs");
let add1 = one(&mut session, &core, pos(CORE, "add1(a)", 0, 0));
let mut from_calls: Vec<(String, u32, u32)> = incoming(&mut session, &add1)
.iter()
.flat_map(|call| {
let file = shape(&call.from).1;
call.from_ranges.iter().map(move |r| (file.clone(), r.start.line, r.start.character))
})
.collect();
let references = session.result(
References::METHOD,
serde_json::json!({
"textDocument": { "uri": core },
"position": pos(CORE, "add1(a)", 0, 0),
"context": { "includeDeclaration": false },
}),
);
let mut from_refs: Vec<(String, u32, u32)> = references
.as_array()
.expect("locations")
.iter()
.map(|loc| {
let file =
loc["uri"].as_str().unwrap_or("").rsplit('/').next().unwrap_or("").to_string();
let start = &loc["range"]["start"];
(
file,
start["line"].as_u64().unwrap_or(0) as u32,
start["character"].as_u64().unwrap_or(0) as u32,
)
})
.filter(|(file, line, _)| !(file == "util_pkg.sv" && *line == 3))
.collect();
from_calls.sort();
from_refs.sort();
assert_eq!(from_calls, from_refs, "every reference but the end label is a call");
}
#[test]
fn a_recursive_function_is_its_own_caller_and_callee() {
let (tree, mut session, _) = design("hev_fact");
let pkg = session.open(&tree.path.join("util_pkg.sv"), PKG);
let fact = one(&mut session, &pkg, pos(PKG, "fact(int", 0, 0));
assert_eq!(callers(&incoming(&mut session, &fact)), [(s("fact"), s("util_pkg.sv"), vec![7])]);
assert_eq!(callees(&outgoing(&mut session, &fact)), [(s("fact"), s("util_pkg.sv"), vec![7])]);
}
#[test]
fn class_methods_called_through_this_a_handle_and_super() {
let (tree, mut session, _) = design("hev_class");
let cls = session.open(&tree.path.join("cls.sv"), CLS);
let bump = one(&mut session, &cls, pos(CLS, "bump();\n n++", 0, 0));
assert_eq!(bump.kind, lsp_types::SymbolKind::METHOD);
assert_eq!(bump.detail.as_deref(), Some("counter"));
assert_eq!(
callers(&incoming(&mut session, &bump)),
[
(s("reset"), s("cls.sv"), vec![24]),
(s("bump_twice"), s("cls.sv"), vec![7, 8]),
(s("run"), s("cls.sv"), vec![13]),
(s("bump_more"), s("cls.sv"), vec![19]),
],
"a bare call and `this.`; a handle; the out-of-body definition's body, \
credited to its prototype; `super.` from a subclass"
);
let twice = one(&mut session, &cls, pos(CLS, "bump_twice", 0, 0));
assert_eq!(callees(&outgoing(&mut session, &twice)), [(s("bump"), s("cls.sv"), vec![7, 8])]);
}
#[test]
fn an_out_of_body_definition_prepares_and_expands_its_prototype() {
let (tree, mut session, _) = design("hev_extern");
let cls = session.open(&tree.path.join("cls.sv"), CLS);
let inside = one(&mut session, &cls, pos(CLS, "bump();\nendfunction", 0, 0));
assert_eq!(shape(&inside).0, "bump", "on the call");
let body = one(&mut session, &cls, pos(CLS, "endfunction\n", 3, 3));
assert_eq!(shape(&body), (s("reset"), s("cls.sv"), 2), "the prototype");
assert_eq!(callees(&outgoing(&mut session, &body)), [(s("bump"), s("cls.sv"), vec![24])]);
}
#[test]
fn a_super_method_call_resolves_through_the_workspace_overlay() {
// `super.bump()` inside `fancy` is answered by the workspace overlay
// (the base class is a file-scope declaration the index holds), not by
// the file's own symbol table — both directions must read both layers.
let (tree, mut session, _) = design("hev_super");
let cls = session.open(&tree.path.join("cls.sv"), CLS);
let more = one(&mut session, &cls, pos(CLS, "bump_more", 0, 0));
assert_eq!(callees(&outgoing(&mut session, &more)), [(s("bump"), s("cls.sv"), vec![19])]);
}
#[test]
fn a_method_called_through_a_handle_from_another_file() {
let pkg = "\
package env_pkg;
class driver;
task drive();
endtask
endclass
endpackage
";
let tb = "\
module tb;
import env_pkg::*;
driver d;
initial begin
d = new;
d.drive();
end
endmodule
";
let tree = Tree::new("hev_handle");
tree.write("env_pkg.sv", pkg);
tree.write("tb.sv", tb);
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("env_pkg.sv"), pkg);
session.drain();
let drive = one(&mut session, &uri, pos(pkg, "drive()", 0, 0));
assert_eq!(drive.kind, lsp_types::SymbolKind::METHOD);
assert_eq!(drive.detail.as_deref(), Some("driver"));
assert_eq!(callers(&incoming(&mut session, &drive)), [(s("tb"), s("tb.sv"), vec![5])]);
let tb_uri = session.open(&tree.path.join("tb.sv"), tb);
let from_call = one(&mut session, &tb_uri, pos(tb, "drive()", 0, 1));
assert_eq!(from_call, drive, "the call through the handle prepares the method");
}
#[test]
fn a_unit_scope_function_answers_in_its_own_file_only() {
// A `$unit` function works like any other in the file that declares it.
// A call from *another* file is a documented limit: the semantic layer
// resolves an unqualified value-position name through imports only, so
// `ufn(1)` in `user.sv` names nothing and the cursor there falls back to
// the enclosing module (README, Handshakes).
let unit = "\
function automatic int ufn(int a);
return a;
endfunction
module local_user;
int j = ufn(2);
endmodule
";
let user = "module user;\n int k = ufn(1);\nendmodule\n";
let tree = Tree::new("hev_unit");
tree.write("unit.sv", unit);
tree.write("user.sv", user);
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("unit.sv"), unit);
session.drain();
let ufn = one(&mut session, &uri, pos(unit, "ufn", 0, 0));
assert_eq!(shape(&ufn), (s("ufn"), s("unit.sv"), 0));
assert_eq!(ufn.detail, None, "declared at `$unit`, in no container");
assert_eq!(one(&mut session, &uri, pos(unit, "ufn(2)", 0, 0)), ufn);
assert_eq!(
callers(&incoming(&mut session, &ufn)),
[(s("local_user"), s("unit.sv"), vec![4])],
"the call in `user.sv` is not resolved, so it is not listed"
);
let user_uri = session.open(&tree.path.join("user.sv"), user);
let there = one(&mut session, &user_uri, pos(user, "ufn", 0, 0));
assert_eq!(shape(&there).0, "user", "the limit: the enclosing module, not `ufn`");
}
#[test]
fn an_edit_since_the_item_was_built_is_followed() {
// The item's recorded offset no longer matches once a line is added
// above the function; the selection range is stale too, so the item is
// re-found by name — `twice` is the only one, in its container `core`.
let (tree, mut session, core) = design("hev_stale");
let twice = one(&mut session, &core, pos(CORE, "twice(int", 0, 0));
let edited = format!("// a new first line\n{CORE}");
session.open(&tree.path.join("core.sv"), &edited);
let calls = incoming(&mut session, &twice);
assert_eq!(
callers(&calls),
[(s("core"), s("core.sv"), vec![15]), (s("kick"), s("core.sv"), vec![10])]
);
}
/// QA finding 3: two `log2`s in one file. After an edit moves both, the old
/// item for `mb`'s answers `mb`'s callers (its `detail` breaks the tie); once
/// `mb`'s is renamed away it answers nothing — never `ma`'s.
#[test]
fn a_stale_item_never_answers_for_a_same_named_function_elsewhere() {
let text = "\
module ma;
function int log2(int v); return v; endfunction
int a = log2(1);
endmodule
module mb;
function int log2(int v); return v; endfunction
int b = log2(2);
int c = log2(3);
endmodule
";
let tree = Tree::new("hev_ma_mb");
tree.write("two.sv", text);
let mut session = Session::wide(vec![tree.path.clone()], false);
let path = tree.path.join("two.sv");
let uri = session.open(&path, text);
session.drain();
let in_mb = one(&mut session, &uri, pos(text, "log2(int", 1, 0));
assert_eq!(in_mb.detail.as_deref(), Some("mb"));
let moved = format!("// one\n// two\n// three\n{text}");
session.open(&path, &moved);
assert_eq!(
callers(&incoming(&mut session, &in_mb)),
[(s("mb"), s("two.sv"), vec![9, 10])],
"the tie broken by the container"
);
let renamed = moved.replace(
"log2(int v); return v; endfunction\n int b",
"lg(int v); return v; endfunction\n int b",
);
session.open(&path, &renamed);
assert!(incoming(&mut session, &in_mb).is_empty(), "never `ma`'s `log2`");
assert!(outgoing(&mut session, &in_mb).is_empty());
}
#[test]
fn the_classic_clog2_is_not_its_own_caller() {
// QA finding 1: `clog2 = clog2 + 1;` reads the result variable.
let text = "\
module lg (output integer o);
function integer clog2(input integer v);
begin
clog2 = 0;
while (v > 1) begin
clog2 = clog2 + 1;
v = v >> 1;
end
end
endfunction
initial o = clog2(16);
endmodule
";
let tree = Tree::new("hev_clog2");
tree.write("lg.sv", text);
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("lg.sv"), text);
session.drain();
let clog2 = one(&mut session, &uri, pos(text, "clog2(input", 0, 0));
assert_eq!(callers(&incoming(&mut session, &clog2)), [(s("lg"), s("lg.sv"), vec![10])]);
assert!(outgoing(&mut session, &clog2).is_empty(), "no false recursion");
}
#[test]
fn an_untitled_buffer_answers_from_itself() {
let text = "module m;\n function int f(); return 1; endfunction\n int x = f();\nendmodule\n";
let tree = Tree::new("hev_untitled");
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = Uri::from_str("untitled:Untitled-1").expect("uri");
session.notify(
DidOpenTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "languageId": "systemverilog", "version": 1, "text": text }
}),
);
session.drain();
let f = one(&mut session, &uri, pos(text, "f()", 1, 0));
assert_eq!(f.uri, uri);
assert_eq!(callers(&incoming(&mut session, &f)), [(s("m"), s("untitled:Untitled-1"), vec![2])]);
}
#[test]
fn two_functions_of_one_name_are_told_apart_by_data() {
let text = "\
module a;
function int f(); return 1; endfunction
initial $display(f());
endmodule
module b;
function int f(); return 2; endfunction
int x = f();
int y = f();
endmodule
";
let tree = Tree::new("hev_same_name");
tree.write("two.sv", text);
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("two.sv"), text);
session.drain();
let in_b = one(&mut session, &uri, pos(text, "f()", 2, 0));
assert_eq!(shape(&in_b), (s("f"), s("two.sv"), 6), "the declaration in `b`");
assert_eq!(callers(&incoming(&mut session, &in_b)), [(s("b"), s("two.sv"), vec![7, 8])]);
let in_a = one(&mut session, &uri, pos(text, "f()", 0, 0));
assert_eq!(callers(&incoming(&mut session, &in_a)), [(s("a"), s("two.sv"), vec![2])]);
}
#[test]
fn an_item_whose_data_is_not_ours_is_treated_as_a_module_item() {
let (_tree, mut session, core) = design("hev_foreign");
let mut item = one(&mut session, &core, pos(CORE, "twice(int", 0, 0));
item.data = Some(serde_json::json!({ "kind": "rocket" }));
assert!(incoming(&mut session, &item).is_empty(), "no module is called `twice`");
assert!(outgoing(&mut session, &item).is_empty());
}
// ----------------------------------------------------------------------
// type hierarchy inside a class body
// ----------------------------------------------------------------------
fn prepare_type(session: &mut Session, uri: &Uri, position: Value) -> Vec<String> {
let result = session.result(
TypeHierarchyPrepare::METHOD,
serde_json::json!({ "textDocument": { "uri": uri }, "position": position }),
);
match result.as_array() {
Some(items) => {
items.iter().map(|i| i["name"].as_str().unwrap_or("?").to_string()).collect()
}
None => Vec::new(),
}
}
#[test]
fn inside_a_class_body_prepares_the_class_and_super_prepares_its_base() {
let (tree, mut session, core) = design("hev_type");
let cls = session.open(&tree.path.join("cls.sv"), CLS);
assert_eq!(
prepare_type(&mut session, &cls, pos(CLS, "int n", 0, 4)),
["counter"],
"a property"
);
assert_eq!(
prepare_type(&mut session, &cls, pos(CLS, "n++", 0, 0)),
["counter"],
"a method body"
);
assert_eq!(
prepare_type(&mut session, &cls, pos(CLS, "this.bump", 0, 1)),
["counter"],
"`this`"
);
assert_eq!(
prepare_type(&mut session, &cls, pos(CLS, "super.bump", 0, 2)),
["counter"],
"`super`"
);
assert_eq!(
prepare_type(&mut session, &cls, pos(CLS, "super.bump", 0, 7)),
["fancy"],
"the method name after `super.` is inside `fancy`"
);
assert!(prepare_type(&mut session, &core, pos(CORE, "int r", 0, 4)).is_empty(), "a module");
}
@@ -52,13 +52,16 @@ mod code_action;
mod file_ops;
mod folders;
mod formatting;
mod hierarchy_everywhere;
mod hierarchy_reach;
mod index;
mod large_file;
mod lint_snapshot;
mod progress;
mod pull_diagnostics;
mod qa_generate_label;
mod qa_rename_implicit;
mod rename_generate_label;
mod rename_implicit;
mod requests;
mod scan;
@@ -0,0 +1,86 @@
//! QA attacks on TODO §65.1 over the wire: `references` and `rename` through
//! a block label with the other files closed, and the `member_key` spelling
//! of a block that lives inside a function.
//! `docs/features/generate-label-rename/README.md`, QA log 2026-09-30.
use super::*;
/// `(file name, line)` of every location in a `references` answer.
fn places(found: &Value) -> Vec<(String, u64)> {
let mut out: Vec<(String, u64)> = found
.as_array()
.expect("an array")
.iter()
.map(|l| {
let uri = l["uri"].as_str().unwrap_or("?");
let name = uri.rsplit('/').next().unwrap_or("?").to_string();
(name, l["range"]["start"]["line"].as_u64().unwrap_or(0))
})
.collect();
out.sort();
out
}
fn position(uri: &Uri, text: &str, line: usize, name: &str) -> Value {
let row = text.lines().nth(line).expect("the line");
let character = row.find(name).expect("the name on that line");
serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": line, "character": character },
"context": { "includeDeclaration": true },
})
}
/// A module `ff` with a block `fb` holding `t`, and — in another file — a
/// function `ff` with a named block `fb` holding its own `t`. The function's
/// `t` is a local: nothing outside the function can name it, and the module's
/// `t` is a different declaration.
const MODULE_FF: &str = "module ff;\n if (1) begin : fb\n logic t;\n end\nendmodule\n";
const USER: &str =
"module user (output logic o);\n ff u_ff ();\n assign o = u_ff.fb.t;\nendmodule\n";
const FUNC: &str = "module host;\n function automatic void ff();\n begin : fb\n logic t;\n t = 1'b0;\n end\n endfunction\nendmodule\n";
#[test]
fn a_function_local_in_a_named_block_is_never_mistaken_for_a_modules_block_member() {
let tree = Tree::new("qa_genlabel_member_key");
tree.write("ff.sv", MODULE_FF);
tree.write("user.sv", USER);
tree.write("host.sv", FUNC);
let mut session = Session::wide(vec![tree.path.clone()], false);
let host = session.open(&tree.path.join("host.sv"), FUNC);
let found = places(&session.result(References::METHOD, position(&host, FUNC, 3, "t;")));
assert_eq!(found, vec![("host.sv".to_string(), 3), ("host.sv".to_string(), 4)]);
let mut params = position(&host, FUNC, 3, "t;");
params["newName"] = serde_json::json!("t2");
let answer = session.request(Rename::METHOD, params).response_result.expect("renames");
let changes = answer["changes"].as_object().expect("changes");
assert_eq!(changes.len(), 1, "only host.sv: {answer:#}");
}
/// Three files: the block's module, an intermediate module instantiating it,
/// and a testbench naming a member through two instances and the block. Only
/// the declaring file is open.
const LEAF: &str = "module leaf;\n for (genvar i = 0; i < 2; i++) begin : g_l\n logic s;\n end : g_l\nendmodule\n";
const MID: &str = "module mid;\n leaf u_leaf ();\nendmodule\n";
const TB: &str = "module tbq (output logic o);\n mid u_mid ();\n assign o = u_mid.u_leaf.g_l[1].s;\nendmodule\n";
#[test]
fn a_two_instance_path_through_a_block_is_renamed_with_every_other_file_closed() {
let tree = Tree::new("qa_genlabel_two_hops");
tree.write("leaf.sv", LEAF);
tree.write("mid.sv", MID);
tree.write("tbq.sv", TB);
let mut session = Session::wide(vec![tree.path.clone()], false);
let leaf = session.open(&tree.path.join("leaf.sv"), LEAF);
let found = places(&session.result(References::METHOD, position(&leaf, LEAF, 1, "g_l")));
let at = |f: &str, l| (f.to_string(), l);
assert_eq!(found, vec![at("leaf.sv", 1), at("leaf.sv", 3), at("tbq.sv", 2)]);
let mut params = position(&leaf, LEAF, 2, "s;");
params["newName"] = serde_json::json!("s_q");
let answer = session.request(Rename::METHOD, params).response_result.expect("renames");
let changes = answer["changes"].as_object().expect("changes");
let tb = path_to_uri(&tree.path.join("tbq.sv")).expect("a uri");
assert_eq!(changes.get(tb.as_str()).and_then(Value::as_array).map_or(0, Vec::len), 1);
}
@@ -0,0 +1,150 @@
//! A generate block label over the wire (TODO §65.1, topo §2.9-43).
//!
//! `references`, `prepareRename` and `rename` at a block label reach the
//! closing label and every path through the block — the same-file
//! `g_lane[0].sig` and another file's `u_x.g_lane[1].sig` — through the
//! engine and the index's hierarchical surface, whether the other file is
//! open or closed.
use super::*;
const SUB: &str = "module sub (input logic clk, output logic o);\n for (genvar i = 0; i < 2; i++) begin : g_lane\n logic sig;\n assign sig = clk;\n end : g_lane\n assign o = g_lane[0].sig;\nendmodule\n";
const TOP: &str = "module top (input logic clk, output logic o);\n sub u_x (.clk, .o());\n assign o = u_x.g_lane[1].sig;\nendmodule\n";
/// The LSP position of the `g_lane` on 0-based `line` of `text`.
fn at_label(uri: &Uri, text: &str, line: usize) -> Value {
let row = text.lines().nth(line).expect("the line");
let character = row.find("g_lane").expect("the label on that line");
serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": line, "character": character },
})
}
/// `(file name, line)` of every location in a `references` answer.
fn places(found: &Value) -> Vec<(String, u64)> {
let mut out: Vec<(String, u64)> = found
.as_array()
.expect("an array")
.iter()
.map(|l| {
let uri = l["uri"].as_str().unwrap_or("?");
let name = uri.rsplit('/').next().unwrap_or("?").to_string();
(name, l["range"]["start"]["line"].as_u64().unwrap_or(0))
})
.collect();
out.sort();
out
}
/// The two-file tree, with `sub.sv` and/or `top.sv` open.
fn session_with(tag: &str, open_sub: bool, open_top: bool) -> (Tree, Session, Uri, Uri) {
let tree = Tree::new(tag);
tree.write("sub.sv", SUB);
tree.write("top.sv", TOP);
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = |name: &str| path_to_uri(&tree.path.join(name)).expect("a uri");
let (sub, top) = (uri("sub.sv"), uri("top.sv"));
if open_sub {
session.open(&tree.path.join("sub.sv"), SUB);
}
if open_top {
session.open(&tree.path.join("top.sv"), TOP);
}
(tree, session, sub, top)
}
fn expected() -> Vec<(String, u64)> {
let sub = |line| ("sub.sv".to_string(), line);
vec![sub(1), sub(4), sub(5), ("top.sv".to_string(), 2)]
}
#[test]
fn references_at_the_label_reach_the_closing_label_and_every_path_with_the_user_closed() {
let (_tree, mut session, sub, _) = session_with("genlabel_refs_closed", true, false);
let mut params = at_label(&sub, SUB, 1);
params["context"] = serde_json::json!({ "includeDeclaration": true });
assert_eq!(places(&session.result(References::METHOD, params)), expected());
}
#[test]
fn references_from_the_other_files_segment_are_the_same_set_with_the_declarer_closed() {
// The declaring file is closed, so its own uses (the closing label and
// `g_lane[0].sig`) come from §64.1's one-file re-analysis: a block is a
// hierarchical-only declaration.
let (_tree, mut session, _, top) = session_with("genlabel_refs_open", false, true);
let mut params = at_label(&top, TOP, 2);
params["context"] = serde_json::json!({ "includeDeclaration": true });
assert_eq!(places(&session.result(References::METHOD, params)), expected());
}
#[test]
fn references_with_both_files_open_are_the_same_set() {
let (_tree, mut session, _, top) = session_with("genlabel_refs_both", true, true);
let mut params = at_label(&top, TOP, 2);
params["context"] = serde_json::json!({ "includeDeclaration": true });
assert_eq!(places(&session.result(References::METHOD, params)), expected());
}
#[test]
fn prepare_rename_and_rename_rewrite_every_site_in_both_files() {
let (tree, mut session, sub, _) = session_with("genlabel_rename", true, false);
let prepared = session.result(PrepareRenameRequest::METHOD, at_label(&sub, SUB, 4));
assert_eq!(prepared["placeholder"], "g_lane", "{prepared:#}");
let mut params = at_label(&sub, SUB, 4);
params["newName"] = serde_json::json!("g_ln");
let answer = session.request(Rename::METHOD, params).response_result.expect("renames");
let changes = answer["changes"].as_object().expect("changes");
let count = |path: &str| {
let uri = path_to_uri(&tree.path.join(path)).expect("a uri");
changes.get(uri.as_str()).and_then(Value::as_array).map_or(0, Vec::len)
};
assert_eq!((count("sub.sv"), count("top.sv")), (3, 1), "{answer:#}");
let mut texts = changes.values().flat_map(|e| e.as_array().into_iter().flatten());
assert!(texts.all(|e| e["newText"] == "g_ln"), "{answer:#}");
}
/// A member of a **nested** block is found on the index's `sub.g_a.g_b` key
/// (`Semantics::member_key`), so the reference list from its declaration in
/// an open buffer reaches the closed file's path to it.
#[test]
fn references_at_a_nested_blocks_member_reach_the_path_from_another_file() {
const NSUB: &str = "module nsub;\n if (1) begin : g_a\n for (genvar j = 0; j < 2; j++) begin : g_b\n logic deep;\n end\n end\nendmodule\n";
const NTOP: &str = "module ntop (output logic o);\n nsub u_n ();\n assign o = u_n.g_a.g_b[1].deep;\nendmodule\n";
let tree = Tree::new("genlabel_nested");
tree.write("nsub.sv", NSUB);
tree.write("ntop.sv", NTOP);
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("nsub.sv"), NSUB);
let params = serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": 3, "character": NSUB.lines().nth(3).and_then(|l| l.find("deep")) },
"context": { "includeDeclaration": true },
});
let found = places(&session.result(References::METHOD, params));
assert_eq!(found, vec![("nsub.sv".to_string(), 3), ("ntop.sv".to_string(), 2)]);
}
/// QA F1 over the wire: an open buffer is always in the rename's set, so its
/// path through the label that resolves to nothing (`tb.u_x.…`, rooted at a
/// top module this server cannot resolve) is shown as a warning, unedited.
#[test]
fn an_unresolved_path_in_an_open_buffer_is_shown_as_a_rename_warning() {
const PROBE: &str =
"module probe (output logic o);\n assign o = tb.u_x.g_lane[0].sig;\nendmodule\n";
let (tree, mut session, sub, _) = session_with("genlabel_unresolved", true, false);
tree.write("probe.sv", PROBE);
session.open(&tree.path.join("probe.sv"), PROBE);
let _ = session.drain();
let mut params = at_label(&sub, SUB, 1);
params["newName"] = serde_json::json!("g_ln");
let answer = session.request(Rename::METHOD, params).response_result.expect("renames");
let probe = path_to_uri(&tree.path.join("probe.sv")).expect("a uri");
assert!(answer["changes"].get(probe.as_str()).is_none(), "probe.sv is not edited: {answer:#}");
let shown = session.shown();
assert!(
shown.iter().any(|(_, m)| m.contains("probe.sv:2:") && m.contains("`g_lane`")),
"{shown:?}"
);
}
+131
View File
@@ -0,0 +1,131 @@
//! The open buffers: installing, closing and finding them, and which
//! text — the buffer's or the disk's — speaks for a path when the index
//! or a refactoring asks.
use std::fs;
use std::path::Path;
use lsp_types::Uri;
use vlog_semantic::FileFacts;
use super::discover::{oversize, Found};
use super::{Document, Workspace};
use crate::uri::uri_to_path;
impl Workspace {
pub fn document(&self, uri: &Uri) -> Option<&Document> {
self.docs.get(uri)
}
/// The open document backed by `path`, if there is one.
pub fn document_for_path(&self, path: &Path) -> Option<&Document> {
self.docs.values().find(|doc| doc.path.as_deref() == Some(path))
}
/// Every open document and its URI.
pub fn open_documents(&self) -> impl Iterator<Item = (&Uri, &Document)> {
self.docs.iter()
}
/// Replace a buffer's contents and re-analyze it.
///
/// Also the one place a directory enters the folder scope: a buffer with a
/// path puts its own directory on the list `scope_dirs` raises. An
/// `untitled:` buffer has no path and contributes none.
///
/// And the one place the **large-file fast path** is chosen: a text over
/// `lucisv.largeFile.threshold` is line-indexed and nothing more. Because
/// the decision lives here it is re-taken on every `didOpen`, `didChange`
/// and text-carrying `didSave`, which is what makes a buffer edited past
/// the threshold — or back under it — change mode at that moment and not
/// before (`docs/features/large-file-mode/README.md`).
pub fn set_document(&mut self, uri: Uri, text: String) {
let path = uri_to_path(&uri);
if let Some(dir) = path.as_deref().and_then(Path::parent) {
if !self.opened_dirs.iter().any(|seen| seen == dir) {
self.opened_dirs.push(dir.to_path_buf());
self.opened_dirs.sort();
}
}
// This path now has a buffer speaking for it, so whatever the view
// cache holds for it is both unwanted and possibly older than the
// edits the buffer carries.
if let Some(path) = path.as_deref() {
self.forget_view(path);
}
let doc = match self.is_large(&text) {
true => Document::large(path, text),
false => Document::new(path, text, &self.index),
};
self.docs.insert(uri, doc);
}
/// Whether a buffer of this text takes the fast path. `0` disables it, and
/// the comparison is strict, so a buffer of exactly the threshold is still
/// analyzed in full.
fn is_large(&self, text: &str) -> bool {
let threshold = self.client.large_file_threshold;
threshold != 0 && text.len() as u64 > threshold
}
/// Whether any open buffer is on the large-file fast path.
///
/// The gate in `server.rs` runs before every request, and this is what
/// keeps that from costing a URI parse per request in the session where
/// nothing is large — which is every session but one.
pub fn has_large_documents(&self) -> bool {
self.docs.values().any(|doc| doc.large)
}
pub fn close_document(&mut self, uri: &Uri) {
let closed = self.docs.remove(uri);
// Disk is the authority again, and a view made before this buffer was
// opened predates every save it made.
if let Some(path) = closed.and_then(|doc| doc.path) {
self.forget_view(&path);
}
}
/// Every open buffer's URI, for republishing diagnostics after a rebuild.
pub fn open_uris(&self) -> Vec<Uri> {
self.docs.keys().cloned().collect()
}
/// The text of a workspace file: the open buffer if there is one, else
/// what is on disk. Same precedence the index rebuild uses, so a location
/// is never computed against text the index did not see.
pub fn text_of(&self, path: &Path) -> Option<String> {
let open = self.docs.values().find(|d| d.path.as_deref() == Some(path));
match open {
Some(doc) => Some(doc.text.clone()),
None => fs::read_to_string(path).ok(),
}
}
/// The text one in-scope file contributes right now, by `collect_sources`'s
/// rules — `None` when it contributes nothing at all.
pub(super) fn current_text(&self, path: &Path) -> Option<String> {
if let Some(doc) = self.docs.values().find(|doc| doc.path.as_deref() == Some(path)) {
// A fast-path buffer contributes nothing, exactly as it does in
// `collect_sources` — indexing it is the parse the fast path
// exists to skip.
return (!doc.large).then(|| doc.text.clone());
}
if oversize(&Found::of(path), self.client.max_file_size, &mut 0).is_some() {
return None;
}
fs::read_to_string(path).ok()
}
/// The index facts and the completion words of the open buffer backing
/// `path`, read off the analysis it already holds — `None` when no buffer
/// does, or when the one that does is on the large-file fast path and has
/// no analysis of its own text to read.
///
/// The buffer is found the same way [`Workspace::current_text`] finds the
/// text, so the two always speak for the same `Document`.
pub(super) fn analysis_of(&self, path: &Path) -> Option<(FileFacts, Vec<String>)> {
let doc = self.docs.values().find(|doc| doc.path.as_deref() == Some(path))?;
(!doc.large).then(|| (doc.facts(path.to_path_buf()), doc.words()))
}
}
+232
View File
@@ -0,0 +1,232 @@
//! One open buffer, analyzed once from its text — [`Document`] and
//! everything derived from it — and the two binary searches that find a
//! token in it by offset without sweeping the buffer.
use std::path::PathBuf;
use vlog_parser::ast::SourceFile;
use vlog_parser::defines::{collect_defines, DefineTable};
use vlog_parser::token::Token;
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex, ParseDiagnostic};
use vlog_semantic::{
analyze, resolve_external, ExternalResolutions, FileFacts, Semantics, WorkspaceIndex,
};
use crate::convert::Positions;
/// One open buffer, fully analyzed. Every field is derived from `text`, so a
/// change throws the whole thing away and builds a new one.
pub struct Document {
/// The buffer's path, absent for a `untitled:` document.
pub path: Option<PathBuf>,
pub text: String,
pub line_index: LineIndex,
/// Empty when the file does not lex — the lexer is all-or-nothing.
pub tokens: Vec<Token>,
/// The tolerant parse of `text` — the tree `semantics` was analyzed from,
/// kept so the lint pass reads it instead of parsing the buffer again
/// ("one parse, two tools", `docs/features/one-parse/README.md`).
pub tree: SourceFile,
pub diagnostics: Vec<ParseDiagnostic>,
pub semantics: Semantics,
pub defines: DefineTable,
/// The workspace layer's answers for this file's external candidates.
pub external: ExternalResolutions,
/// Whether this buffer was opened on the **large-file fast path**: every
/// field above except `text` and `line_index` is the empty analysis of an
/// empty file, because nothing lexed it. Handlers that would scan the text
/// itself check this flag; the ones that read the analysis need not, since
/// there is nothing in it to find. See
/// `docs/features/large-file-mode/README.md`.
pub large: bool,
/// The formatter's fence answer for exactly this `text`, computed on
/// first use and never again — a whole tolerant parse the code-action
/// path used to pay for on every request. Filled through
/// [`crate::fences::of`], which is the only thing that may touch it; it
/// is bound to this revision because a change builds a new `Document`.
pub fences: std::sync::OnceLock<Vec<vlog_formatter::fence::Region>>,
/// This buffer's lint findings, kept while every input that produced them
/// is unchanged — read by the diagnostics pass and by quick-fix discovery
/// alike, so one revision is linted once rather than twice (review round
/// §R1a, `crate::lint_snapshot`). Bound to this revision for the same
/// structural reason `fences` is; the inputs that can move *without* a new
/// `Document` are the snapshot's own key, and the index moving is
/// [`Document::refresh_overlay`], which clears it.
pub lint: crate::lint_snapshot::Slot,
}
impl Document {
/// Analyze a buffer from scratch against the current workspace index.
pub fn new(path: Option<PathBuf>, text: String, index: &WorkspaceIndex) -> Document {
// One lex: the tree is built from a clone of the token stream instead
// of re-lexing the buffer (`parse_source_tolerant` is exactly
// `tokenize` + `parse_tolerant`, so the tree is identical). A buffer
// that does not lex keeps the old path, so its all-error tree and its
// lex diagnostic are byte-for-byte what they always were.
use crate::lint_trace::{rebuild, Rebuild};
crate::lint_trace::saw_document();
let (tokens, (tree, diagnostics)) = match rebuild(Rebuild::Lex, || tokenize(&text)) {
Ok(tokens) => {
let parsed = rebuild(Rebuild::Parse, || parse_tolerant(tokens.clone(), &text));
(tokens, parsed)
}
Err(_) => (Vec::new(), rebuild(Rebuild::Parse, || parse_source_tolerant(&text))),
};
let defines = rebuild(Rebuild::Defines, || collect_defines(&tokens));
let semantics = rebuild(Rebuild::Analyze, || analyze(&tree, &text));
let external = rebuild(Rebuild::External, || resolve_external(&semantics, index));
let line_index = rebuild(Rebuild::Lines, || LineIndex::new(&text));
let large = false;
Document {
path,
text,
line_index,
tokens,
tree,
diagnostics,
semantics,
defines,
external,
large,
fences: std::sync::OnceLock::new(),
lint: crate::lint_snapshot::Slot::new(),
}
}
/// Take a buffer on the **fast path**: index its lines and nothing else.
///
/// One newline scan is the whole cost of opening a 100 MB netlist. The
/// derived fields are the analysis of the *empty* file rather than of this
/// one — built by parsing `""`, which costs nothing and needs no new API
/// from `vlog_parser` — so every handler that reads the analysis finds
/// exactly nothing and answers empty without knowing this path exists.
pub fn large(path: Option<PathBuf>, text: String) -> Document {
let (tree, _) = parse_source_tolerant("");
let semantics = analyze(&tree, "");
let line_index = LineIndex::new(&text);
Document {
path,
text,
line_index,
tokens: Vec::new(),
tree,
diagnostics: Vec::new(),
semantics,
defines: DefineTable::default(),
external: ExternalResolutions::default(),
large: true,
fences: std::sync::OnceLock::new(),
lint: crate::lint_snapshot::Slot::new(),
}
}
/// This document's position converter.
pub fn positions(&self) -> Positions<'_> {
Positions::new(&self.text, &self.line_index)
}
/// The source token covering `offset`, found without sweeping the buffer.
pub fn token_at(&self, offset: u32) -> Option<&Token> {
let after = self.tokens.partition_point(|token| token.span.start <= offset);
let token = self.tokens.get(after.checked_sub(1)?)?;
token.span.contains(offset).then_some(token)
}
/// Re-run only the workspace overlay, after the index was rebuilt. The
/// single-file analysis is unaffected by other files, by construction.
pub fn refresh_overlay(&mut self, index: &WorkspaceIndex) {
self.external = resolve_external(&self.semantics, index);
// The index is what the census oracle answers from, so a lint result
// taken under the old one is no longer this buffer's answer. This is
// the whole of the snapshot's index invalidation: every mutation of
// `Workspace::index` ends in the loop that calls this, so there is no
// generation counter to keep in step (review round §R1a).
self.lint.clear();
}
/// What this buffer contributes to the workspace index, read off the
/// analysis it already holds instead of from its text.
///
/// [`FileFacts::of`] is `tokenize` + `parse_tolerant` + `analyze` followed
/// by the fact walk, and the first three are exactly what [`Document::new`]
/// already did to fill `tree`, `defines` and `semantics` — from the same
/// text, with the same functions, down to the lex-failure branch. So this
/// is `FileFacts::of(path, &self.text)` with the parse already paid for,
/// not a second way of computing it
/// (`an_open_buffer_offers_the_facts_and_words_its_text_would_over_the_real_corpus`).
///
/// Never called for a buffer on the large-file fast path: its analysis is
/// the analysis of the empty file, and such a buffer contributes nothing to
/// the index at all (see `collect_sources`).
pub fn facts(&self, path: PathBuf) -> FileFacts {
FileFacts::from_analysis(
path,
&self.tree,
&self.defines,
&self.semantics,
&self.text,
&self.line_index,
&self.tokens,
)
}
/// The completion words this buffer contributes, read off the tokens it was
/// analyzed from rather than by lexing its text a second time.
pub fn words(&self) -> Vec<String> {
crate::candidates::words_of_tokens(&self.tokens)
}
}
// ----------------------------------------------------------------------
// Finding a token by offset without sweeping the buffer
// ----------------------------------------------------------------------
//
// The lexer emits tokens in source order and they never overlap, so
// `span.start` and `span.end` both rise across the vector: `end[i] <=
// start[i+1] <= end[i+1]`. That makes both predicates below monotone, which
// is the whole precondition `partition_point` needs. Every handler that used
// to sweep the vector looking for a token at the cursor is one comparison
// away from one of these two indices — see
// `docs/features/interactive-latency/README.md` for the per-call-site
// argument that each swap returns exactly what the sweep returned.
/// The index of the first token that **reaches** `offset` — the first with
/// `span.end >= offset`. `tokens.len()` when none does.
///
/// Every token before it ends strictly before `offset`, so it cannot cover,
/// end at, or contain `offset`. The token *at* this index is therefore the
/// first candidate any such question has.
pub fn first_token_reaching(tokens: &[Token], offset: u32) -> usize {
tokens.partition_point(|token| token.span.end < offset)
}
/// The index of the first token that **begins** at or after `offset` — the
/// first with `span.start >= offset`. `tokens.len()` when none does.
pub fn first_token_from(tokens: &[Token], offset: u32) -> usize {
tokens.partition_point(|token| token.span.start < offset)
}
/// A buffer of `blocks` repeated blocks, for the tests that check a binary
/// search against the sweep it replaced.
///
/// Deliberately awkward: tokens written with no space between them (`a=b;`),
/// line and block comments, a string, nested `begin`/`end` and several depths
/// of parentheses. The offsets those tests walk are *every byte*, and the ones
/// that could tell a binary search from a sweep are exactly the bytes two
/// tokens share — which only adjacent punctuation produces.
#[cfg(test)]
pub fn mixed_buffer(blocks: usize) -> String {
let mut src = String::from("module mixed (input logic clk, output logic [7:0] q);\n");
for n in 0..blocks {
src.push_str(&format!(
" // block {n}\n \
wire [7:0] w{n};assign w{n}=(q[0]?8'd1:8'd2)+{{4'h0,4'hF}};\n \
/* {n} */ always @(posedge clk) begin\n \
if (w{n}[0]) begin q<=w{n}; end else begin q<=8'd0; end\n \
end\n \
initial $display(\"block {n}\", w{n});\n"
));
}
src.push_str("endmodule\n");
src
}
@@ -0,0 +1,118 @@
//! Re-indexing one saved file the index already holds, patching every
//! table rather than rebuilding it — the cheap path a `didSave` takes
//! before falling back to a whole rescan.
use std::path::Path;
use super::Workspace;
use crate::scan_trace::ScanTrace;
impl Workspace {
/// Rebuild the index for **one** file, leaving every other file's
/// contribution exactly as it is. Reports whether it could.
///
/// `false` means the caller must fall back to [`Workspace::rebuild_index`]:
/// the file is not one this index already holds, which is the one case the
/// cheap path cannot settle. A file appearing changes which *other* files
/// exist as far as the include graph is concerned (a `` `include`` that had
/// nothing to resolve to now has something), and answering that takes a
/// walk — so the rule is simply "a file the index already holds".
///
/// The four pieces of state a rebuild produces, and what happens to each:
///
/// * **the workspace index** — [`WorkspaceIndex::update_file`] /
/// [`WorkspaceIndex::remove_file`], which promise the index a whole
/// rebuild over the same file set would have produced;
/// * **the completion tables** — the two index-derived ones re-derived, the
/// word table patched by this file's words alone;
/// * **the include graph** — this file's edges re-scanned, the known-file
/// and folded-spelling tables re-learned from the index's list;
/// * **every open buffer's overlay** — refreshed, exactly as a rebuild
/// refreshes it, because any of them may resolve into the file that moved.
///
/// The text is chosen by `collect_sources`'s rules, for one path: an open
/// buffer beats disk and is never capped; a walked file over
/// `lucisv.index.maxFileSize`, one that has been deleted, and one that
/// cannot be read are all "this file is not in the index any more".
pub fn update_one(&mut self, path: &Path) -> bool {
if !self.index.files().iter().any(|held| held == path) {
return false;
}
// Re-indexing one file *is* the claim that its bytes moved.
self.forget_view(path);
match self.current_text(path) {
Some(text) => {
// The same rule a whole rebuild follows: when the text came
// from an open buffer, that buffer's finished analysis is the
// facts and the words, and neither is derived from the text a
// second time. `current_text` answers with a buffer's text only
// when that buffer is not on the large-file fast path, so the
// analysis found here is a real one.
match self.analysis_of(path) {
Some((facts, words)) => {
self.index.update_facts(facts);
self.candidates.update_words(&self.index, path, words);
}
None => {
self.index.update_file(path.to_path_buf(), &text);
// The words come back out of the record the update
// just wrote, so the file is lexed once rather than
// twice (`FACTS_FORMAT` 13). A path the index somehow
// does not hold falls back to lexing, which is what
// this line always did.
match self.index.facts_for(path).map(|facts| facts.words().to_vec()) {
Some(words) => self.candidates.update_words(&self.index, path, words),
None => self.candidates.update_file(&self.index, path, &text),
}
}
}
self.includes.update_file(path, &text, self.index.files());
// Written through here too, so an hour of saves is an hour of
// work the next session does not repeat. The record is the
// one the update just made — no second parse — and it is
// keyed by the text it was made from, which is the buffer's
// when a buffer beat disk. That record is simply never hit
// again if the file on disk says something else.
// A save is the other thing that asks the store something, so
// it opens a re-open a scan deferred rather than writing into
// the store the previous rescan left in hand ([`StoreOpen`]).
self.open_store(&mut ScanTrace::default());
if let Some(facts) = self.index.facts_for(path) {
self.cache.record(facts, &text);
}
}
None => {
self.index.remove_file(path);
self.candidates.remove_file(&self.index, path);
self.includes.remove_file(path, self.index.files());
}
}
for doc in self.docs.values_mut() {
doc.refresh_overlay(&self.index);
}
true
}
/// [`Workspace::update_one`], then a whole rebuild over the same
/// workspace, asserting the two produced the same thing — the paranoid
/// form, for tests.
///
/// It is the incremental path's whole claim, checked rather than argued:
/// the index's fingerprint (ids, disambiguation order, member tables,
/// edges, define counts) and the completion word table, which is the one
/// piece of derived state that is patched rather than re-derived. The
/// workspace is left holding the *rebuilt* index, which is the same index,
/// so a test may keep using it.
#[cfg(test)]
pub fn update_one_checked(&mut self, path: &Path) -> bool {
if !self.update_one(path) {
return false;
}
let index = self.index.fingerprint();
let words = self.candidates.words("").to_vec();
self.rebuild_index();
assert_eq!(index, self.index.fingerprint(), "incremental index != rebuilt index");
assert_eq!(words, self.candidates.words(""), "incremental words != rebuilt words");
true
}
}
File diff suppressed because it is too large. Load diff
+758
View File
@@ -0,0 +1,758 @@
//! Driving a scan, whole or widen, from its work list to the landed
//! tables: `begin_scan`/`begin_widen` take the list, `scan_step` indexes
//! one file, `publish_scan` makes the tables answer for what has been
//! staged so far, and `finish_scan` lands them. The one-shot forms the
//! tests use are at the end.
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use vlog_semantic::FileFacts;
use super::discover::oversize;
use super::scan::{self, Analyzed, IndexEvent, Scan, ScanKind};
use super::{StoreOpen, Workspace};
use crate::candidates::Candidates;
use crate::includes::{self, IncludeGraph};
use crate::index_cache::IndexCache;
use crate::scan_order::{self, WorkList};
use crate::scan_trace::{CacheWork, ScanTrace};
#[cfg(test)]
use crate::settings::IndexScope;
impl Workspace {
/// Take the work list one scan will run through: resolve the scope and put
/// the user's own neighbourhood at the front of it.
///
/// **No file's text is read here** — only the open buffers', which are in
/// memory already. Everything else is read at the step that indexes it
/// ([`Workspace::scan_step`]), so the first file can be indexed as soon as
/// the walk is done rather than after the whole scope has been read.
///
/// Nothing is indexed here and the live index is untouched, so a scan that
/// is never stepped changes nothing but the view cache and the open cache
/// handle.
pub fn begin_scan(&mut self, watch: &mut dyn FnMut(IndexEvent), trace: bool) -> Scan {
let mut trace = ScanTrace::opened(&mut self.scans, trace, "whole");
// A rescan says nothing about *which* file moved, so nothing held from
// before it can be trusted.
self.views.borrow_mut().clear();
let discovering = trace.now();
let mut skipped = 0usize;
// The cap's skips are reported by `collect_sources` and counted here,
// because the end message names them and the scan is what owns that
// number now.
let mut counting = |event: IndexEvent<'_>, skipped: &mut usize| {
if matches!(event, IndexEvent::Skipped { .. }) {
*skipped += 1;
}
watch(event);
};
let (mut scope, pending) = {
let mut count = |event: IndexEvent<'_>| counting(event, &mut skipped);
self.first_scope(&mut count, &mut trace)
};
ScanTrace::add(&mut trace.discovery_ms, discovering);
let buffered = std::mem::take(&mut scope.buffered);
let analyzed = std::mem::take(&mut scope.analyzed);
let ordering = trace.now();
// The same list the index will be built from, with the user's own
// neighbourhood moved to the front of it.
let WorkList { files: work, head } = self.open_first(std::mem::take(&mut scope.files));
// A scan that has not walked the whole workspace yet cannot ask
// whether its head is a minority of it — the count that would answer
// is the walk it is postponing. `splits_discovery` is what bounds the
// head instead, and it refuses exactly the case `worth_waiting`
// refuses: a buffer whose folder is the workspace.
let head = match pending.is_some() {
true => head,
false => scan_order::worth_waiting(head, work.len()),
};
let paths = work.clone();
ScanTrace::add(&mut trace.order_ms, ordering);
// Re-opened rather than held across rescans: the directory it belongs
// in depends on settings that arrive after startup, and a second
// session over the same workspace may have written records this one
// has not seen. **Deferred** to the first file that asks the store
// anything ([`StoreOpen`]), so a scan with no files reads nothing.
self.store = StoreOpen::Deferred(self.cache_dir());
trace.measure_work(work.len(), held_bytes(&buffered), skipped, self.cache.work());
Scan {
kind: ScanKind::Whole,
work,
head,
buffered,
includes: HashMap::new(),
unread: Vec::new(),
paths,
gone: Vec::new(),
analyzed,
incdirs: scope.incdirs,
warnings: scope.warnings,
at: 0,
pending,
staged: Vec::new(),
staged_at: Vec::new(),
words: HashMap::new(),
skipped,
cached: 0,
trace,
}
}
/// Take the work list for a **scope widen**: the files `added` brings into
/// scope that the index does not already hold, plus every open buffer's own
/// analysis.
///
/// The cheap answer to a `didOpen` in a folder the scope had not reached.
/// A whole rescan re-reads, re-hashes and re-merges every file already
/// indexed to learn about a handful of new ones; this reads only the new
/// ones, and [`Workspace::finish_scan`] folds them in beside what is
/// already there. What comes out is the index, the completion tables and
/// the include graph a whole rescan would have produced — **given that the
/// disk files already indexed have not changed since they were indexed**,
/// which is the file watcher's job and is written down in
/// `docs/features/index-scope/README.md`.
///
/// Two halves make that equivalence hold, and both are why this is not
/// simply "index the new files":
///
/// * **every open buffer is re-indexed from the analysis it holds**, so a
/// buffer carrying unsaved edits contributes those edits exactly as a
/// whole rescan's `collect_sources` overlay would. That costs a fact walk
/// and a word set per open buffer (~5 ms for a 1.4 MB buffer, rescan-reuse
/// round) and no parse at all.
/// * **a buffer on the large-file fast path contributes nothing**, so a
/// file the index holds whose buffer has grown past the threshold is
/// taken back out — the one thing a widen removes, and the same rule
/// `collect_sources` follows.
///
/// `added` is the directories that entered [`Workspace::scope_dirs`]; the
/// caller decides that they really are an addition and nothing else
/// (`server.rs`'s `widen_of`).
pub fn begin_widen(
&mut self,
added: &[PathBuf],
watch: &mut dyn FnMut(IndexEvent),
trace: bool,
) -> Scan {
let mut trace = ScanTrace::opened(&mut self.scans, trace, "widen");
let discovering = trace.now();
let held: HashSet<PathBuf> = self.index.files().iter().cloned().collect();
let cap = self.client.max_file_size;
let spoken_for: HashSet<&Path> =
self.docs.values().filter_map(|doc| doc.path.as_deref()).collect();
let mut skipped = 0usize;
let mut files: Vec<PathBuf> = Vec::new();
let mut warnings: Vec<String> = Vec::new();
// The walk of the *added* directories alone, by the same rung-3 rules
// `folder_files` follows — the whole scope is the union of these walks,
// so the files this one finds beyond what is already indexed are
// exactly the ones the widen owes.
let mut stats = 0usize;
for found in self.widened_files(added, &mut |w| warnings.push(w), &mut trace) {
let path = found.path.clone();
// Already indexed: by another scope directory this walk overlaps,
// or by an earlier scan. Re-reading it is the cost this path
// exists to avoid.
if held.contains(&path) {
continue;
}
if let Some(size) = oversize(&found, cap, &mut stats) {
watch(IndexEvent::Skipped { path: &path, size, cap });
skipped += 1;
continue;
}
if spoken_for.contains(path.as_path()) {
continue;
}
files.push(path);
}
let mut analyzed = Analyzed::default();
let mut buffered: HashMap<PathBuf, String> = HashMap::new();
let mut gone: Vec<PathBuf> = Vec::new();
for doc in self.docs.values() {
let Some(path) = doc.path.clone() else { continue };
files.retain(|taken| taken != &path);
if doc.large {
if held.contains(&path) {
gone.push(path);
}
continue;
}
analyzed.facts.insert(path.clone(), doc.facts(path.clone()));
analyzed.words.insert(path.clone(), doc.words());
buffered.insert(path.clone(), doc.text.clone());
files.push(path);
}
ScanTrace::add(&mut trace.discovery_ms, discovering);
let ordering = trace.now();
let WorkList { files: work, head } = self.open_first(files);
let head = scan_order::worth_waiting(head, work.len());
ScanTrace::add(&mut trace.order_ms, ordering);
trace.measure_work(work.len(), held_bytes(&buffered), skipped, self.cache.work());
// A whole scan drops the view cache entire, because a rescan claims
// nothing about *which* file moved. A widen names exactly the files it
// is reading, so it drops exactly those — which keeps the cache's own
// rule ("every way a file's text can move drops its entry",
// [`Workspace::file_view`]) literally true rather than nearly so.
for path in &work {
self.views.borrow_mut().retain(|view| &view.path != path);
}
// Which files exist once this widen lands: what the index holds, less
// what it is about to lose, plus what the widen brings in.
let mut paths: Vec<PathBuf> =
held.into_iter().filter(|path| !gone.contains(path)).collect();
paths.extend(work.iter().cloned());
paths.sort();
paths.dedup();
gone.sort();
Scan {
kind: ScanKind::Widen,
work,
head,
buffered,
includes: HashMap::new(),
unread: Vec::new(),
paths,
gone,
analyzed,
// Rung 3 is the only rung an open buffer can widen, and it names no
// `+incdir+`. Carried from the graph in hand rather than assumed
// empty, so folding a widen in never *changes* the search path.
incdirs: self.includes.incdirs().to_vec(),
// A widen resolves no filelist — rung 1 is not a scope an open
// buffer can widen — so the only warnings here are the walk's own.
warnings,
at: 0,
// A widen names the directories it is about to walk, so there is
// never anything left to discover.
pending: None,
staged: Vec::new(),
staged_at: Vec::new(),
words: HashMap::new(),
skipped,
cached: 0,
trace,
}
}
/// Walk the rest of the workspace, once the user's own neighbourhood has
/// been indexed and published — the second half of a split discovery
/// ([`PendingDiscovery`]). Reports whether there was anything to walk.
///
/// **Its own step, indexing nothing.** The step it shares a call with
/// would otherwise report a file against a denominator that grew inside
/// the same call, and a bar whose percentage falls is worse than one that
/// waits (`docs/features/indexing-ux/README.md`). So this discovers, says
/// "there is more", and lets the next step be an ordinary one.
fn discover_the_rest(&mut self, scan: &mut Scan, watch: &mut dyn FnMut(IndexEvent)) -> bool {
let Some(mut pending) = scan.take_pending() else { return false };
let discovering = scan.trace.now();
let mut skipped = 0usize;
let (files, warnings, walked_skips) = {
let mut counting = |event: IndexEvent<'_>| {
if matches!(event, IndexEvent::Skipped { .. }) {
skipped += 1;
}
watch(event);
};
self.rest_of_scope(&mut pending, &mut counting, &mut scan.trace)
};
debug_assert_eq!(skipped, walked_skips, "the cap reports every skip it counts");
ScanTrace::add(&mut scan.trace.discovery_ms, discovering);
scan.land_discovery(files, warnings, walked_skips, pending.tracker.has_conflict());
scan.trace.measure_work(
scan.work.len(),
held_bytes(&scan.buffered),
scan.skipped,
scan.trace.cache,
);
true
}
/// Open the store a whole rescan asked for, if this is the first thing to
/// need it ([`StoreOpen`]).
///
/// Called from the two places that ask the store anything — a scan's step
/// and a save's write-through — so a rescan that reaches no file never
/// reads it, and the widen behind that rescan still finds it open the
/// moment it reaches one.
pub(super) fn open_store(&mut self, trace: &mut ScanTrace) {
let StoreOpen::Deferred(dir) = std::mem::replace(&mut self.store, StoreOpen::Done) else {
return;
};
let opening = trace.now();
self.cache = IndexCache::open(dir);
ScanTrace::add(&mut trace.cache_open_ms, opening);
// The counters this scan is charged for start where the store it has
// just opened does. A scan that never opens one keeps the baseline
// `measure_work` took, so its delta is the nothing it did.
trace.cache = CacheWork::default();
}
/// Index the next file of `scan`, reporting whether there was one.
///
/// One file is the whole step: **its text is read**, its record is taken —
/// from the open buffer's own analysis, from the persistent cache, or from
/// a parse — its `` `include``s are scanned off that text and its
/// completion words are taken off the record. All three are *staged* on
/// the scan rather than merged, because merging is a pass over the whole
/// workspace and one per file would be quadratic
/// ([`WorkspaceIndex::absorb`]).
///
/// **The text is read here and dropped here** (2026-09-08). Everything the
/// scan will ever want from it — the content hash the store is keyed by,
/// the parse, the include lines — is taken in this one step, so a whole
/// scan reads each file's bytes exactly once and holds one file's text at
/// a time rather than the whole scope's. An **open buffer's** text is not
/// read: it was taken with the work list, beside the analysis that
/// describes the same bytes, so a `didChange` mid-scan cannot make the two
/// disagree. A file that cannot be read is remembered as `unread` and
/// contributes nothing, which is what a file `collect_sources` could not
/// read used to do before the work list existed.
pub fn scan_step(&mut self, scan: &mut Scan, watch: &mut dyn FnMut(IndexEvent)) -> bool {
let (done, total) = (scan.at, scan.work.len());
if done == total {
return self.discover_the_rest(scan, watch);
}
scan.at += 1;
// The first file of a scan is the first thing to ask the store
// anything, so it is where the store this scan asked for is opened.
self.open_store(&mut scan.trace);
let path = scan.work[done].clone();
let Some(source) = scan.take_text(&path) else {
scan.unread.push(path);
return true;
};
let text = source.as_str();
let held = scan.analyzed.facts.remove(&path);
let known_words = scan.analyzed.words.remove(&path);
let facts = match held {
// An open buffer's own finished analysis comes first. It is the
// only source of facts that is right when the buffer has unsaved
// edits, which is precisely when the content-keyed cache below has
// nothing to offer. The record is written through all the same, so
// the next session starts from it.
Some(facts) => {
watch(IndexEvent::Analyzed { done, total, path: &path });
scan.trace.buffers += 1;
self.cache.record(&facts, text);
facts
}
// The cache answers for the exact bytes about to be indexed, so a
// hit is the parse and not a guess at it. A miss — a new file, a
// changed one, a record this version cannot read — parses, and
// the result is written through immediately, which is what makes
// an interrupted scan resumable.
None => match self.cache.facts_for(&path, text) {
Some(facts) => {
scan.cached += 1;
watch(IndexEvent::Cached { done, total, path: &path });
facts
}
None => {
watch(IndexEvent::Parsing { done, total, path: &path });
let parsing = scan.trace.now();
let facts = FileFacts::of(path.clone(), text);
ScanTrace::add(&mut scan.trace.parse_ms, parsing);
scan.trace.parse_bytes += text.len();
self.cache.record(&facts, text);
facts
}
},
};
// Read off the record rather than lexed here: since `FACTS_FORMAT` 13
// a file's identifier census *is* one of its facts, so a cached hit
// brings its words with it and a parse harvested them from the tokens
// it already had. That retires the per-file re-lex a scan used to pay
// for the completion word table (TODO §10's deferred item;
// `docs/features/semantic-lints-on/README.md` has the measurement).
// An open buffer's words are still the caller's, read off the tokens
// it was analyzed from.
let words = known_words.unwrap_or_else(|| facts.words().to_vec());
// Scanned here, off the text this step read, because the include graph
// is built when the scan ends and by then the text is gone. It is a
// line scan over bytes already in cache, and it replaces the identical
// scan `IncludeGraph::build` used to run over the same text later.
scan.includes.insert(path.clone(), includes::scan(text));
scan.words.insert(path, words);
scan.staged.push(facts);
scan.staged_at.push(done);
true
}
/// The work list in the order a scan walks it: the open buffers' own
/// files, then the rest of the folders those buffers raise to, then
/// everything else in path order ([`crate::scan_order`]).
///
/// **A reporting and latency decision and nothing else.**
/// `vlog_semantic::IndexBuilder` sorts by path inside `finish` since
/// 2026-08-27, so no insertion order can reach the index: this changes
/// which file the progress bar names first — the user's own, and then
/// what they are looking at across the folder — and changes nothing about
/// the result. Pinned both ends: the builder's own
/// `no_insertion_order_can_change_what_the_builder_produces`, and
/// `the_open_files_are_indexed_first_and_the_index_cannot_tell` here.
/// Re-order what is left of `scan` around the buffers open **now** — the
/// same ranking [`Workspace::begin_scan`] applied, re-applied because a
/// `didOpen` answered mid-scan changed the answer to "where is the user
/// working?".
///
/// Called after the burst carrying that `didOpen` has been applied, so the
/// buffer is installed and the folder it raises to is known. What was
/// already indexed is untouched; only the tail moves, and the finished
/// index cannot tell ([`Scan::reorder`]).
/// **The rest of the workspace is walked first when it has not been.** A
/// split startup is leading with the folder the user *was* in; a `didOpen`
/// says they are somewhere else now, and re-ordering a work list that does
/// not yet contain the new folder would answer the request behind that
/// `didOpen` off a prefix that cannot hold what it is asking about. The
/// walk this order postpones is exactly what makes the new folder
/// nameable, so it happens here
/// (`docs/features/perf5r-first-answer/README.md`).
pub fn open_next(&mut self, scan: &mut Scan, watch: &mut dyn FnMut(IndexEvent)) {
self.discover_the_rest(scan, watch);
let ordered = self.open_first(scan.remaining());
scan.reorder(ordered);
}
fn open_first(&self, files: Vec<PathBuf>) -> WorkList {
let open: Vec<PathBuf> = self.docs.values().filter_map(|doc| doc.path.clone()).collect();
scan_order::work_list(files, &open, &self.raised_dirs())
}
/// Make every table answer for the files `scan` has taken since the last
/// publish — the moment a mid-scan answer is worth paying a merge for.
///
/// **All three tables together, never one of them.** The index, the
/// completion tables and the include graph are what an answer reads, and a
/// hover that saw a scanned file while a completion or an include link
/// could not would make "the workspace as far as it has been scanned"
/// three different things at once. Each is folded in with the batch form
/// of the incremental update it already had, so one publish is one pass
/// over the index and not one per file.
pub fn publish_scan(&mut self, scan: &mut Scan) {
if scan.staged.is_empty() {
return;
}
let taken = std::mem::take(&mut scan.staged_at);
let absorbing = scan.trace.now();
self.index.absorb(std::mem::take(&mut scan.staged), &[]);
ScanTrace::add(&mut scan.trace.publish_absorb_ms, absorbing);
let completing = scan.trace.now();
let published: Vec<PathBuf> = taken.iter().map(|&at| scan.work[at].clone()).collect();
let words = published
.iter()
.map(|path| (path.clone(), scan.words.get(path).cloned().unwrap_or_default()))
.collect();
self.candidates.absorb(&self.index, words);
ScanTrace::add(&mut scan.trace.publish_candidates_ms, completing);
let including = scan.trace.now();
let found = scan::included(&scan.includes, &published);
self.includes.absorb_includes(&scan.incdirs, &scan.paths, &found);
ScanTrace::add(&mut scan.trace.publish_includes_ms, including);
let refreshing = scan.trace.now();
// Every open buffer resolves against the index, so a buffer whose
// cross-file names the scan has just reached must be able to see them.
for doc in self.docs.values_mut() {
doc.refresh_overlay(&self.index);
}
ScanTrace::add(&mut scan.trace.publish_overlay_ms, refreshing);
scan.trace.saw_publish(taken.len());
}
/// Finish `scan`: the index, the completion tables, the include graph and
/// every open buffer's overlay. Reports the warnings from resolving the
/// scope.
///
/// **What comes out is the index a one-shot scan over the same work list
/// would have produced**, however many times [`Workspace::publish_scan`]
/// ran in between: a publish only ever folds records in, and the index's
/// tables are a pure function of the records it holds
/// ([`WorkspaceIndex::absorb`]).
pub fn finish_scan(&mut self, scan: Scan) -> Vec<String> {
match scan.kind {
ScanKind::Whole => self.finish_whole_scan(scan),
ScanKind::Widen => self.finish_widen(scan),
}
}
/// [`Workspace::finish_scan`] for a whole scan.
fn finish_whole_scan(&mut self, scan: Scan) -> Vec<String> {
let Scan {
mut work, unread, incdirs, warnings, staged, words, includes, mut trace, ..
} = scan;
// What the scan really indexed, which is its work list unless a file
// left the disk between the walk and its own step. Such a file is not
// in scope any more, so it must land in `gone` exactly as it would
// have if the walk had missed it.
work.retain(|path| !unread.contains(path));
let found = scan::included(&includes, &work);
let leaving = trace.now();
// Whatever the last scan left in the index that this one's work list
// does not name is a file that is no longer in scope.
let held: HashSet<&Path> = work.iter().map(PathBuf::as_path).collect();
let gone: Vec<PathBuf> = self
.index
.files()
.iter()
.filter(|path| !held.contains(path.as_path()))
.cloned()
.collect();
ScanTrace::add(&mut trace.gone_ms, leaving);
let absorbing = trace.now();
self.index.absorb(staged, &gone);
ScanTrace::add(&mut trace.absorb_ms, absorbing);
// The one moment the live set of entries is known, so the one moment
// the append log is worth rewriting — and only when this scan reached
// a file at all. A scan with an empty work list asked the store
// nothing and never opened it, so there is nothing of this session's
// in it and nothing to rewrite it from (§P4b (b1)); the rewrite of a
// store that *is* open is itself skipped when it would reproduce the
// file byte for byte ([`IndexCache::compact`], §P4b (a)).
if matches!(self.store, StoreOpen::Done) {
self.cache.compact();
}
let completing = trace.now();
// Built from the words every step took off its own record — the same
// list, so a file the scope ladder excluded contributes no completion
// candidates either, and nothing is lexed twice.
self.candidates = Candidates::from_words(&self.index, words);
ScanTrace::add(&mut trace.candidates_ms, completing);
let including = trace.now();
// Same list again: an `` `include`` in a file the scope excluded is
// not an edge, and a file it excluded is not a hop away from anything.
// The lines themselves were read at each file's own step.
self.includes = IncludeGraph::from_includes(&found, incdirs);
ScanTrace::add(&mut trace.includes_ms, including);
let refreshing = trace.now();
for doc in self.docs.values_mut() {
doc.refresh_overlay(&self.index);
}
ScanTrace::add(&mut trace.overlay_ms, refreshing);
self.landed(trace);
warnings
}
/// Close a scan's trace: the tables it left behind, measured, and the
/// whole thing set aside for the server to log.
///
/// Every size it reads is a walk, so the trace itself decides whether to
/// take them ([`ScanTrace::landed`]); a scan nobody traced sets nothing
/// aside.
fn landed(&mut self, mut trace: ScanTrace) {
trace.landed(self.docs.len(), &self.cache, &self.index, &self.candidates, &self.includes);
if trace.on() {
self.last_trace = trace;
}
}
/// The trace of the scan that just finished, taken away — an inert one
/// when the scan was not being traced.
pub fn take_scan_trace(&mut self) -> ScanTrace {
std::mem::take(&mut self.last_trace)
}
/// [`Workspace::finish_scan`] for a widen: the same three tables, folded
/// into rather than replaced.
///
/// Each table is landed with the batch form of the incremental update it
/// already had, which is the same one [`Workspace::publish_scan`] uses —
/// so what comes out is what a whole scan over the union of the old files
/// and the new ones would have produced. The three claims that makes, one
/// per table:
///
/// * **the index** — [`WorkspaceIndex::absorb`] keeps the records
/// path-sorted and one to a path and merges them the way a whole build
/// does;
/// * **the completion tables** — the two index-derived ones are re-derived
/// from the index, and the word table is patched per file into the same
/// total order a whole build sorts into;
/// * **the include graph** — the known-file and folded-spelling tables are
/// relearned from the whole in-scope list and every held edge is
/// re-spelled against it (the graph is rebuilt from every file's staged
/// include list, [`IncludeGraph::from_includes`]), so a file that is in
/// scope for the first time can lend its spelling to an edge that was
/// resolved before it arrived.
///
/// One thing a whole scan does that this deliberately does not: the
/// persistent store is **not compacted**. A widen does not know the live
/// set of entries — it only added to it — and the next whole rescan
/// rewrites the log anyway.
fn finish_widen(&mut self, scan: Scan) -> Vec<String> {
let Scan {
mut work,
mut paths,
gone,
incdirs,
warnings,
staged,
words,
includes,
mut trace,
unread,
..
} = scan;
// A widen only ever adds, so a file whose text had gone by its own
// step is simply not added — it is in neither list below.
work.retain(|path| !unread.contains(path));
paths.retain(|path| !unread.contains(path));
let found = scan::included(&includes, &work);
let absorbing = trace.now();
self.index.absorb(staged, &gone);
ScanTrace::add(&mut trace.absorb_ms, absorbing);
// Before the additions, so the two never disagree about a path that is
// in both lists — which cannot happen today (a large buffer is in
// neither `work` nor `paths`) and would be a silent wrong answer if it
// ever did.
for path in &gone {
self.candidates.remove_file(&self.index, path);
self.includes.remove_file(path, &paths);
}
let batch: Vec<(PathBuf, Vec<String>)> = work
.iter()
.map(|path| (path.clone(), words.get(path).cloned().unwrap_or_default()))
.collect();
let completing = trace.now();
self.candidates.absorb(&self.index, batch);
ScanTrace::add(&mut trace.candidates_ms, completing);
let including = trace.now();
self.includes.absorb_includes(&incdirs, &paths, &found);
ScanTrace::add(&mut trace.includes_ms, including);
let refreshing = trace.now();
for doc in self.docs.values_mut() {
doc.refresh_overlay(&self.index);
}
ScanTrace::add(&mut trace.overlay_ms, refreshing);
self.landed(trace);
warnings
}
// ------------------------------------------------------------------
// The one-shot forms: the protocol above run to the end in one call.
// Test-only, every one of them — the server drives the three calls
// itself so that it can answer messages between two of them.
// ------------------------------------------------------------------
/// Adopt the workspace roots and build the index for the first time.
/// Returns whatever the caller should tell the user about the scope.
///
/// The unwatched form. `server.rs` always watches (it has a progress bar
/// to move), so this is reachable from tests alone — of which there are
/// several dozen across this crate, and none of them has an opinion about
/// progress reporting.
#[cfg(test)]
pub fn open_roots(&mut self, roots: Vec<PathBuf>) -> Vec<String> {
self.open_roots_with(roots, &mut |_| {})
}
/// [`Workspace::open_roots`] with `lucisv.index.scope` set to
/// `"workspace"`: adopt the roots and index **all** of them, which is what
/// every session did before 2026-08-27.
///
/// Test-only, and used by the dozens of tests across this crate that are
/// about something other than scope — a hover, a rename, an inlay hint —
/// and want the whole fixture tree in the index without opening a buffer
/// in each of its directories first. Spelling it out at the call site is
/// what keeps "this test wants the wide scope" a statement rather than an
/// accident. The folder scope's own behaviour is tested by the tests named
/// in `docs/features/index-scope/README.md`.
#[cfg(test)]
pub fn open_whole_workspace(&mut self, roots: Vec<PathBuf>) -> Vec<String> {
self.open_whole_workspace_with(roots, &mut |_| {})
}
/// [`Workspace::open_whole_workspace`], watched. Test-only, for the two
/// tests that want the wide scope *and* the events.
#[cfg(test)]
pub fn open_whole_workspace_with(
&mut self,
roots: Vec<PathBuf>,
watch: &mut dyn FnMut(IndexEvent),
) -> Vec<String> {
self.client.index_scope = IndexScope::Workspace;
self.open_roots_with(roots, watch)
}
/// [`Workspace::open_roots`], watched — the unwatched form's sibling, and
/// test-only for the same reason: the server drives the scan itself now,
/// one file at a time, so it adopts the roots and steps the scan rather
/// than calling this.
#[cfg(test)]
pub fn open_roots_with(
&mut self,
roots: Vec<PathBuf>,
watch: &mut dyn FnMut(IndexEvent),
) -> Vec<String> {
self.adopt_roots(roots);
self.rebuild_index_with(watch)
}
/// Re-scan the workspace and rebuild the index and the completion tables,
/// then refresh every open buffer's overlay. Called on `initialize` and on
/// every `didSave`.
///
/// Returns the warnings from resolving the scope — a filelist naming a
/// file that is gone, say. Rendering them is `server.rs`'s job; this
/// module speaks no protocol.
///
/// The unwatched form, reachable from tests alone for the same reason
/// `open_roots` is.
#[cfg(test)]
pub fn rebuild_index(&mut self) -> Vec<String> {
self.rebuild_index_with(&mut |_| {})
}
/// [`Workspace::rebuild_index`], watched: `watch` is called once for every
/// file the size cap skipped and once for every file about to be parsed,
/// in index order and before the parse, so a caller can report where the
/// rescan has got to.
///
/// The events cover the index build alone. The completion tables and the
/// include graph are built from the same list afterwards and are not
/// reported: they cost a small fraction of the parse, and a bar that went
/// to 100% and then sat there would be worse than one that ends.
///
/// A scan with nothing happening between its files, which is what every
/// caller but the server's message loop wants. The loop drives the same
/// three calls itself and answers messages between two of them
/// (`docs/features/scan-interleave/README.md`) — so "one shot" and
/// "interleaved" are not two scans that have to be kept in step, they are
/// this loop with and without a drain in it.
///
/// Test-only for that reason: the server takes the three calls, and this
/// is what every test that just wants an index calls instead.
#[cfg(test)]
pub fn rebuild_index_with(&mut self, watch: &mut dyn FnMut(IndexEvent)) -> Vec<String> {
let mut scan = self.begin_scan(watch, false);
while self.scan_step(&mut scan, watch) {}
self.finish_scan(scan)
}
/// [`Workspace::begin_widen`] run to the end in one shot, the way
/// [`Workspace::rebuild_index_with`] runs a whole scan. Test-only for the
/// same reason: the server drives the three calls itself.
#[cfg(test)]
pub fn widen_index(&mut self, added: &[PathBuf]) -> Vec<String> {
self.widen_index_with(added, &mut |_| {})
}
/// [`Workspace::widen_index`], watched.
#[cfg(test)]
pub fn widen_index_with(
&mut self,
added: &[PathBuf],
watch: &mut dyn FnMut(IndexEvent),
) -> Vec<String> {
let mut scan = self.begin_widen(added, watch, false);
while self.scan_step(&mut scan, watch) {}
self.finish_scan(scan)
}
}
/// How many bytes of buffer text a scan carries for its whole life — every
/// other file's text lives from its own step to the end of that step.
fn held_bytes(buffered: &HashMap<PathBuf, String>) -> usize {
buffered.values().map(String::len).sum()
}
+227
View File
@@ -0,0 +1,227 @@
//! What decides the scope: the workspace roots, the `lucisv.*` settings a
//! client pushed, and the ladder they select — which rung is in force and
//! which directories it walks.
use std::path::{Path, PathBuf};
use super::{StoreOpen, Workspace};
use crate::index_cache::IndexCache;
use crate::settings::{ClientSettings, IndexScope};
impl Workspace {
/// Take the workspace roots without indexing anything.
///
/// The half of [`Workspace::open_roots_with`] that is not a scan, for the
/// caller that drives the scan itself — the server, which runs the startup
/// scan through the same interleaved path every later rescan takes.
pub fn adopt_roots(&mut self, roots: Vec<PathBuf>) {
self.roots = roots;
}
/// Add and remove workspace roots mid-session, reporting whether the set
/// actually moved — which is whether the caller owes a rebuild.
///
/// Removals are applied before additions, so a folder named in both lists
/// (which the protocol does not forbid, and which is how some clients
/// spell "this folder moved") ends up present. Adding a root that is
/// already held and removing one that was never held are both no-ops, and
/// say so by leaving the set equal: `didChangeWorkspaceFolders` is a
/// notification, so there is nowhere to report a disagreement to and
/// nothing to gain from re-scanning for one.
pub fn change_roots(&mut self, added: Vec<PathBuf>, removed: &[PathBuf]) -> bool {
let before = self.roots.clone();
self.roots.retain(|root| !removed.contains(root));
for root in added {
if !self.roots.contains(&root) {
self.roots.push(root);
}
}
self.roots != before
}
/// Whether the client opened a workspace at all.
///
/// Without one there is nothing to walk but the open buffers' own
/// directories, and nothing to clamp the folder scope's climb against.
///
/// Test-only since 2026-08-27: `didOpen` used to branch on it, and now
/// branches on whether the file widened the scope, which is the same
/// question asked of the rung that is actually in force.
#[cfg(test)]
pub fn has_roots(&self) -> bool {
!self.roots.is_empty()
}
/// The workspace folders, in the order the client named them.
///
/// The first one is what a relative path in a setting is resolved against,
/// which is what [`Workspace::filelist_path`] does inline and what
/// `lucisv.lint.waivers` needs too.
pub fn roots(&self) -> &[PathBuf] {
&self.roots
}
/// The directories the folder scope walks: every directory a buffer has
/// been opened from this session, each raised `lucisv.index.scopeDepth`
/// levels. **Empty when the folder scope is not the active rung** — a
/// filelist and the whole-workspace walk are scopes an open buffer cannot
/// widen.
///
/// Public because `server.rs` compares it across a `didOpen` to decide
/// whether the file just opened widened the scope, which is the one thing
/// that makes a `didOpen` worth a rebuild.
pub fn scope_dirs(&self) -> Vec<PathBuf> {
if !self.folder_scoped() {
return Vec::new();
}
let mut dirs: Vec<PathBuf> = self.opened_dirs.iter().map(|dir| self.raised(dir)).collect();
dirs.sort();
dirs.dedup();
dirs
}
/// Whether rung 3 — the folder scope — is the one in force.
///
/// A filelist outranks it, and so does an explicit
/// `lucisv.index.scope: "workspace"` **when there is a workspace to
/// walk**: with no roots there is nothing that setting could name, so a
/// rootless session is folder-scoped whatever it says.
fn folder_scoped(&self) -> bool {
self.filelist_path().is_none() && !self.walks_the_workspace()
}
/// Whether rung 2 — the walk of every workspace folder — is in force.
pub(super) fn walks_the_workspace(&self) -> bool {
self.client.index_scope == IndexScope::Workspace && !self.roots.is_empty()
}
/// `dir` raised `lucisv.index.scopeDepth` ancestor levels, clamped twice:
/// it never climbs above the workspace root that contains it — the deepest
/// one, for nested roots — and never above the filesystem root, which is
/// where a directory belonging to no root stops.
///
/// The root clamp is what keeps a `scopeDepth` of 5 in a two-deep project
/// from indexing the user's home directory.
///
/// **A rootless session does not climb at all** (2026-08-28). The clamp is
/// the whole reason a raise is safe, and with no workspace folder there is
/// nothing to clamp against: a lone file opened from
/// `~/work/chip/hw/ip/aes/rtl/` would otherwise raise the shipped
/// [`crate::settings::DEFAULT_SCOPE_DEPTH`] into `~/work/chip/hw/ip/` and
/// walk a tree the user never named. The single-file case stays what it
/// has always been — the buffer's own directory, read flat — and a user
/// who wants more opens the folder, which is what gives the climb a floor.
fn raised(&self, dir: &Path) -> PathBuf {
if self.roots.is_empty() {
return dir.to_path_buf();
}
let floor = self
.roots
.iter()
.filter(|root| dir.starts_with(root))
.max_by_key(|root| root.components().count());
let mut out = dir;
for _ in 0..self.client.index_scope_depth {
if Some(out) == floor.map(PathBuf::as_path) {
break;
}
let Some(parent) = out.parent() else { break };
out = parent;
}
out.to_path_buf()
}
/// The directories the open buffers' own folders raise to, whichever rung
/// of the ladder is in force.
///
/// [`Workspace::scope_dirs`] answers the same question *as a scope* and is
/// therefore empty unless rung 3 is in force. This one is an **ordering**
/// question — where in the workspace the user is working — and it has the
/// same answer under a filelist or an explicit `workspace` scope, where it
/// is the only thing that says which part of a 4 000-file walk to index
/// first.
pub(super) fn raised_dirs(&self) -> Vec<PathBuf> {
let mut dirs: Vec<PathBuf> = self.opened_dirs.iter().map(|dir| self.raised(dir)).collect();
dirs.sort();
dirs.dedup();
dirs
}
/// The `lucisv.*` settings in force, for the resolution points in
/// `format.rs` to fold in.
pub fn client_settings(&self) -> &ClientSettings {
&self.client
}
/// Adopt the settings a client pushed.
///
/// Returns `true` when the caller must rebuild the index: `exclude`,
/// `filelist`, `index.maxFileSize`, `index.scope` and `index.scopeDepth`
/// are the five that change *which files exist* as far as this server is
/// concerned. `lineLength` and `indent` are read afresh by every
/// formatting request, so they need no invalidation at all — and neither
/// does `index.logFiles`, which changes only how loudly the *next* rescan
/// narrates itself.
///
/// `largeFile.threshold` asks for no rescan either, and deliberately: it
/// is consulted where a `Document` is *built*, so a change to it reaches
/// each open buffer at that buffer's next `didOpen`/`didChange` and not
/// before. A rescan now would index by the mode each buffer is still in,
/// which is the mode the index already reflects
/// (`docs/features/large-file-mode/README.md`).
pub fn set_client_settings(&mut self, settings: ClientSettings) -> bool {
let rescan = self.client.exclude != settings.exclude
|| self.client.filelist != settings.filelist
|| self.client.max_file_size != settings.max_file_size
|| self.client.index_scope != settings.index_scope
|| self.client.index_scope_depth != settings.index_scope_depth;
// Neither cache setting changes *which files exist*, so neither asks
// for a rescan — but both change where, or whether, the cache writes,
// and the cache in hand was opened under the old ones. Dropping it
// here is what makes `persist: false` take effect at once in both
// directions: nothing more is written, and nothing held is read. The
// next whole rescan opens the store the new settings name.
if self.client.index_persist != settings.index_persist
|| self.client.index_cache_path != settings.index_cache_path
{
self.cache = IndexCache::disabled();
// And a deferred re-open goes with it, or the next file to want
// the store would open the directory the old settings named.
self.store = StoreOpen::Done;
}
self.client = settings;
rescan
}
/// Where the persistent index cache should live, by
/// [`crate::index_cache::cache_dir`]'s ladder — the client's setting, the
/// editor's storage folder, this platform's cache directory, or nowhere.
pub(super) fn cache_dir(&self) -> Option<PathBuf> {
// In this crate's own tests nothing falls through to the OS cache
// directory: a unit test must not write into the developer's own
// `~/Library/Caches`, and every test that is *about* the cache names
// a directory of its own — a `cachePath` or a `storagePath` — which
// the ladder below still answers with. The OS rung itself is tested
// where it is written, against `index_cache::cache_dir` directly.
#[cfg(test)]
if self.client.index_cache_path.is_none() && self.storage.is_none() {
return None;
}
crate::index_cache::cache_dir(
&self.client,
self.storage.as_deref(),
&self.roots,
self.filelist_path().as_deref(),
)
}
/// Adopt `initializationOptions.storagePath` — the folder the editor set
/// aside for this workspace's server state.
///
/// Called once, before the first index build, because it is one rung of
/// the ladder that decides where the cache is read from. A client that
/// sends nothing leaves the OS cache directory to decide.
pub fn set_storage_path(&mut self, storage: Option<PathBuf>) {
self.storage = storage;
}
}
+358
View File
@@ -0,0 +1,358 @@
//! The file sets handed to the refactorings: the whole scope, or — for a
//! port edit, a rename, a file rename — the fan-out the index already
//! bounds, so a request reads a handful of files instead of the workspace.
use std::collections::BTreeSet;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Instant;
use vlog_semantic::{Def, FileId};
use super::scan::{HeldAnalyses, Sources};
use super::Workspace;
use crate::module_select::{self, Reach};
use crate::rename_trace::{self, Rung, SelectionTrace, Wanted};
use crate::scan_trace::ScanTrace;
impl Workspace {
/// The in-scope files and their current text — what a refactoring reads.
///
/// The same list `rebuild_index` feeds the index, recomputed rather than
/// kept: a refactoring is a rare, user-initiated request, and a second
/// copy of the workspace in memory is a high price for saving one walk.
///
/// This is the one caller that really does want every file's text at once,
/// so it is where the read a scan no longer does in one pass still
/// happens. A file that cannot be read contributes nothing, exactly as it
/// did when `collect_sources` read them all.
pub fn sources(&self) -> Vec<(PathBuf, String)> {
let Sources { files, mut buffered, .. } =
self.collect_sources(&mut |_| {}, HeldAnalyses::Unused, &mut ScanTrace::new(false));
files
.into_iter()
.filter_map(|path| {
let text = match buffered.remove(&path) {
Some(text) => text,
None => fs::read_to_string(&path).ok()?,
};
Some((path, text))
})
.collect()
}
/// The in-scope files a port refactoring on `modules`, requested in `file`,
/// can read or write — [`Workspace::sources`] narrowed to the fan-out the
/// index already holds.
///
/// A `textDocument/codeAction` arrives on every cursor move and
/// `sources()` reads the whole file set from disk, so a cursor resting on
/// an instantiation used to cost one workspace read per keystroke (3.1 s
/// on OpenTitan, and every queued request waited behind it). The index
/// knows who declares a module and who instantiates it, so the engine can
/// be handed those files and nothing else. Why the smaller set gives the
/// same answer is argued in `docs/features/refactor-ports/README.md`; the
/// four rungs are:
///
/// * **the file the request names**, whatever else it is;
/// * **every file declaring one of `modules`** ([`WorkspaceIndex::units`])
/// — all of them, so a name declared twice still refuses instead of
/// quietly picking the one definer that made it into the set;
/// * **every file that instantiates one** ([`WorkspaceIndex::instantiations_of`])
/// or otherwise refers to one ([`WorkspaceIndex::references_to`]) —
/// between them, every file the plan can edit and every file whose
/// meaning the verifier could see move;
/// * **every open buffer**, because its unsaved text may add or remove an
/// instantiation the saved edges do not know about.
///
/// Each file's text comes from the same place `collect_sources` takes it:
/// the open buffer when there is one, disk otherwise, and neither for a
/// buffer on the large-file fast path or a file over the size cap.
pub fn module_sources(&self, file: &Path, modules: &[String]) -> Vec<(PathBuf, String)> {
self.module_sources_reaching(file, modules, Reach::none())
}
/// [`Workspace::module_sources`] plus the **fifth rung**: every file whose
/// tokens write one of `reach`'s scope names down
/// ([`crate::module_select`], topology handshake 33).
///
/// Only inline-module asks for it, and only because its `no_hierarchy`
/// refusal is about a path *through* the instance it dissolves rather
/// than about either module's name: a testbench two wrapper levels above
/// is in none of the four rungs. The rung can only add files, so every
/// other caller's answer is untouched — and so is its cost, since
/// [`Reach::none`] walks nothing.
pub fn module_sources_reaching(
&self,
file: &Path,
modules: &[String],
reach: Reach<'_>,
) -> Vec<(PathBuf, String)> {
let mut wanted: BTreeSet<PathBuf> = module_select::hierarchical_users(&self.index, reach);
wanted.insert(file.to_path_buf());
for name in modules {
for def in self.index.units(name) {
wanted.extend(self.index.path(def.file).map(Path::to_path_buf));
for site in self.index.references_to(def) {
wanted.extend(self.index.path(site.file).map(Path::to_path_buf));
}
}
for edge in self.index.instantiations_of(name) {
wanted.extend(self.index.path(edge.file).map(Path::to_path_buf));
}
}
wanted.extend(self.docs.values().filter_map(|doc| doc.path.clone()));
wanted
.into_iter()
.filter_map(|path| {
let text = self.current_text(&path)?;
Some((path, text))
})
.collect()
}
/// The in-scope files a rename of `name` — to `new_name`, when the request
/// carries one — can read, write or refuse over: [`Workspace::sources`]
/// narrowed to what the index already knows about those two spellings.
///
/// A `textDocument/rename` cost 3.6–8.7 s on OpenTitan and a
/// `prepareRename` 2.5–3.0 s, almost all of it re-reading, re-parsing and
/// re-indexing 3 976 files to find the handful that spell one name. The
/// index holds every declaration of a name and every use it resolved, so
/// the engine can be handed those files and nothing else. **Why the
/// smaller set gives the same answer is argued in full in
/// `docs/features/refactor-rename/README.md`**; the rungs are:
///
/// * **the file the request names**, whatever else it is;
/// * **every open buffer**, whose unsaved text the index has not seen —
/// the one place this set deliberately does not trust the index;
/// * per spelling `N` in `{name, new_name}`:
/// * **every file declaring `N`** — as a unit or as a member of one
/// ([`WorkspaceIndex::workspace_symbols`], filtered to the exact
/// name). This is the rung the whole equality argument turns on:
/// `follow_paths` only ever looks a reference's *own* name up, so a
/// set holding every declarer of `N` resolves every reference spelling
/// `N` exactly as the whole workspace does;
/// * **every file declaring `N` on a module's hierarchical surface**
/// ([`WorkspaceIndex::hierarchical_declarations`]) — an internal net
/// is not a workspace symbol, and a hierarchical tail in another file
/// resolves to one;
/// * **every file with a use the index resolved to one of them**
/// ([`WorkspaceIndex::references_to`]) — every file a rename can edit,
/// and every file whose meaning the verifier could see move;
/// * **every file instantiating `N`**
/// ([`WorkspaceIndex::instantiations_of`]), which records a site whose
/// reference resolved to nothing and therefore has no posting;
/// * **every file whose `` `define`` table names `N` or spells it in a
/// macro body**, walked over the tables the index already holds, for
/// the two `` `define`` warnings;
/// * **the units that export `N` as a member**, and every file
/// declaring, referring to or instantiating one of those — how a third
/// file's `.N(...)` connection or `u::N` is reached.
/// * and, for the **new** name only, **every file that spells it in a use
/// this workspace had to look outside that file to answer, including
/// the uses it could not answer at all**
/// ([`WorkspaceIndex::files_spelling`]).
///
/// **Why that last rung is the new name's alone.** It exists because a
/// rename can give a name that meant *nothing* a meaning: `import
/// taken_pkg::*` in a file with no other tie to the rename resolves to
/// nothing today and to the renamed package tomorrow, which the
/// whole-workspace verifier refuses over and the first five rungs cannot
/// see. The old name has no such case, because a rename only ever
/// **removes** declarations of it: a use of the old name that resolves is
/// in that declaration's postings (rung 2, which walks *every* declaration
/// of the name, not only the target's), and one that resolves to nothing
/// still resolves to nothing afterwards — a lookup cannot start
/// succeeding because a candidate was taken away. So the old name's uses
/// are either already in the set or provably unmoved, and scanning for
/// them would buy nothing.
///
/// One escape hatch, and it is the honest one: when the index says a
/// declaration of `N` is named by an **ambiguous** use
/// ([`WorkspaceIndex::references_are_ambiguous`]), the file holding that
/// use is in no posting table, and the whole-workspace rename refuses
/// because of it. Rather than lose that refusal, this hands back
/// `sources()` and the slow path answers.
/// It also says **which rung asked for each file**: [`Wanted`] is a path
/// set that records the first rung to insert a path, so watching the
/// selection cannot change it (take 5 §P2a).
pub fn rename_sources_traced(
&self,
file: &Path,
name: &str,
new_name: Option<&str>,
) -> (Vec<(PathBuf, String)>, SelectionTrace) {
let started = Instant::now();
let elapsed = |at: Instant| at.elapsed().as_secs_f64() * 1000.0;
let mut wanted = Wanted::new();
wanted.insert(file.to_path_buf());
for spelling in [Some(name), new_name].into_iter().flatten() {
if !self.fan_out_of(spelling, &mut wanted) {
let sources = self.sources();
let trace = SelectionTrace::whole_scope(sources.len(), elapsed(started));
return (sources, trace);
}
}
// The sixth rung, and the **new** name's alone. See the doc comment
// above for why the old name does not need it.
if let Some(new_name) = new_name {
wanted.on(Rung::Speller);
self.want_spellers(new_name, &mut wanted);
}
wanted.on(Rung::OpenBuffer);
wanted.extend(self.docs.values().filter_map(|doc| doc.path.clone()));
let (mut paths, mut trace) = wanted.finish();
// One hop down: the modules those files instantiate, so a `.*` into
// one is read rather than refused (M3.5). In `selected`, under no rung.
let handed: Vec<&Path> = paths.keys().map(PathBuf::as_path).collect();
for below in module_select::instantiated_by(&self.index, &handed) {
paths.entry(below).or_insert(Rung::Instantiation);
}
// §P2d's census: which rungs asked for files that write neither name
// down, and therefore contribute to this request only by shaping how
// the others resolve. One record lookup per selected file, no read.
trace.indirect =
rename_trace::indirect_census(&self.index, &paths, [name, new_name.unwrap_or(name)]);
let texts: Vec<(PathBuf, String)> = paths
.into_keys()
.filter_map(|path| {
let text = self.current_text(&path)?;
Some((path, text))
})
.collect();
// A file a rung wanted whose text this workspace no longer contributes
// (deleted, oversize, a fast-path buffer) is counted by its rung and
// is not in the input: the rungs total the *wanted* set, `selected`
// the one the engine gets.
trace.selected = texts.len();
trace.ms = elapsed(started);
(texts, trace)
}
/// Add one spelling's fan-out to `wanted`. `false` means the index cannot
/// bound it — see [`Workspace::rename_sources_traced`]'s escape hatch.
fn fan_out_of(&self, name: &str, wanted: &mut Wanted) -> bool {
// Every declaration of the name, wherever it is written. `units` alone
// would miss a port, a parameter or a package member, and those are
// exactly the declarations a `.port` connection or a `pkg::x` reaches
// across files for.
let mut containers: BTreeSet<&str> = BTreeSet::new();
for symbol in self.index.workspace_symbols(name) {
if symbol.name != name {
continue;
}
if self.index.references_are_ambiguous(symbol.def) {
return false;
}
containers.extend(symbol.container);
self.want_declaration(symbol.def, wanted);
}
// And every declaration of it on a module's **hierarchical** surface,
// which `workspace_symbols` deliberately does not list: an internal
// net is not a workspace symbol, but `assign w = u_x.sig;` in another
// file resolves to one and a rename must edit both ends. Without this
// rung the fan-out would hold the file that *names* the net and not
// the file that declares it (`docs/features/hierarchical-tail`).
for (unit, def) in self.index.hierarchical_declarations(name) {
if self.index.references_are_ambiguous(def) {
return false;
}
containers.insert(unit);
self.want_declaration(def, wanted);
}
self.want_sites(name, wanted);
self.want_macro_text(name, wanted);
for unit in containers {
for def in self.index.units(unit) {
self.want_declaration(def, wanted);
}
self.want_sites(unit, wanted);
}
true
}
/// One declaration's own file, and every file the index recorded a use of
/// it in.
fn want_declaration(&self, def: &Def, wanted: &mut Wanted) {
wanted.on(Rung::Declaration);
wanted.extend(self.index.path(def.file).map(Path::to_path_buf));
wanted.on(Rung::Reference);
for site in self.index.references_to(def) {
wanted.extend(self.index.path(site.file).map(Path::to_path_buf));
}
}
/// Every file that instantiates a name — the census the reference postings
/// cannot speak for, because an instantiation of something the workspace
/// does not declare resolves to nothing and is posted nowhere.
fn want_sites(&self, name: &str, wanted: &mut Wanted) {
wanted.on(Rung::Instantiation);
for edge in self.index.instantiations_of(name) {
wanted.extend(self.index.path(edge.file).map(Path::to_path_buf));
}
}
/// Every file that spells a name in a use the index had to look outside
/// that file to answer, **including the uses it could not answer at all**
/// ([`WorkspaceIndex::files_spelling`]).
///
/// The rung that closes the rename's one lost refusal (QA, 2026-08-28).
/// A file whose only tie to the new name is `import new_name::*` of a
/// package nothing declares yet holds no declaration, no posting, no
/// instantiation edge and no macro entry — and the rename is exactly what
/// gives that import a meaning, which the whole-workspace verifier refuses
/// over. Only the postings' *keys* miss it; the per-file records keep every
/// external use by the name it spells, so this reads it back.
fn want_spellers(&self, name: &str, wanted: &mut Wanted) {
for file in self.index.files_spelling(name) {
wanted.extend(self.index.path(file).map(Path::to_path_buf));
}
}
/// Every file whose `` `define`` table names the name or spells it in a
/// macro **body** — the two warnings `Scope::define_sites` produces.
///
/// The index holds every file's `DefineTable` already, so this is a walk
/// over tables in memory: no file is read and nothing is parsed. The
/// question is asked with `vlog_refactor::contains_word`, which is the
/// function `define_sites` itself decides with, so the fan-out and the
/// warning cannot disagree about which files carry one.
fn want_macro_text(&self, name: &str, wanted: &mut Wanted) {
wanted.on(Rung::MacroText);
for id in 0..self.index.files().len() {
let file = FileId(id as u32);
let Some(defines) = self.index.defines(file) else { continue };
let touched = defines.entries().iter().any(|define| {
define.name == name || vlog_refactor::contains_word(&define.body, name)
});
if touched {
wanted.extend(self.index.path(file).map(Path::to_path_buf));
}
}
}
/// The in-scope files a `workspace/willRenameFiles` can rewrite: the ones
/// the include graph recorded a resolving `` `include`` in, plus every open
/// buffer.
///
/// `will_rename` reads a file only to scan its `` `include``s and asks the
/// graph where each one lands; a file whose includes all resolve to nothing
/// — or that has none — contributes neither an edit nor a warning, and the
/// graph's edge table is exactly the set of files that have at least one
/// resolving include. So reading the rest was reading the whole workspace
/// to answer "nothing" 3 900 times. Open buffers are added whatever the
/// graph holds: the graph is rebuilt on save, so an `` `include`` typed and
/// not yet saved is in the buffer and not in the edges.
pub fn include_sources(&self) -> Vec<(PathBuf, String)> {
let mut wanted: BTreeSet<PathBuf> = self.includes.includers().cloned().collect();
wanted.extend(self.docs.values().filter_map(|doc| doc.path.clone()));
wanted
.into_iter()
.filter_map(|path| {
let text = self.current_text(&path)?;
Some((path, text))
})
.collect()
}
}
@@ -0,0 +1,142 @@
//! A `Document`'s own analysis: the two token searches against the sweep
//! they replaced, what a buffer holds once analyzed, and — TODO §63.2 QA —
//! the trace's arithmetic, attacked with the three shapes TODO.md names: a
//! buffer that fails to lex, a `define` edit that changes the macro table,
//! and (via the server-level parity re-run) an edit that moves a fence.
use super::*;
/// The precondition both binary searches rest on. If the lexer ever emits
/// a token out of order, or two tokens that overlap, `partition_point`'s
/// predicates stop being monotone and every handler that calls
/// [`first_token_reaching`] or [`first_token_from`] starts answering
/// something else. This is the test that would fail first.
#[test]
fn the_token_stream_rises_and_never_overlaps() {
let text = mixed_buffer(20);
let doc = Document::new(None, text, &WorkspaceIndex::default());
assert!(doc.tokens.len() > 500, "premise: a stream worth searching");
for pair in doc.tokens.windows(2) {
assert!(pair[0].span.start <= pair[1].span.start, "{pair:?}");
assert!(pair[0].span.end <= pair[1].span.start, "overlapping tokens: {pair:?}");
assert!(pair[0].span.start <= pair[0].span.end, "an inverted span: {pair:?}");
}
}
/// Both searches, against the sweep they stand in for, at every byte of a
/// buffer full of tokens that touch.
#[test]
fn every_offset_finds_the_token_a_sweep_would_have_found() {
let text = mixed_buffer(20);
let doc = Document::new(None, text.clone(), &WorkspaceIndex::default());
for offset in 0..=text.len() as u32 {
let swept = doc.tokens.iter().position(|t| t.span.end >= offset);
assert_eq!(
first_token_reaching(&doc.tokens, offset),
swept.unwrap_or(doc.tokens.len()),
"first token reaching {offset}"
);
let swept = doc.tokens.iter().position(|t| t.span.start >= offset);
assert_eq!(
first_token_from(&doc.tokens, offset),
swept.unwrap_or(doc.tokens.len()),
"first token from {offset}"
);
}
}
#[test]
fn a_document_analyzes_a_clean_file() {
let mut ws = Workspace::default();
ws.set_document(uri("file:///rtl/m.sv"), "module m;\n wire a;\nendmodule\n".into());
let doc = ws.document(&uri("file:///rtl/m.sv")).expect("open");
assert!(doc.diagnostics.is_empty());
assert_eq!(doc.path.as_deref(), Some(Path::new("/rtl/m.sv")));
assert!(doc.semantics.symbols().iter().any(|s| s.name == "m"));
assert!(!doc.tokens.is_empty());
}
#[test]
fn a_broken_file_still_analyzes() {
let mut ws = Workspace::default();
ws.set_document(uri("file:///rtl/m.sv"), "module m;\n wire ;\nendmodule\n".into());
let doc = ws.document(&uri("file:///rtl/m.sv")).expect("open");
assert!(!doc.diagnostics.is_empty(), "a broken buffer must report");
assert!(doc.semantics.symbols().iter().any(|s| s.name == "m"), "and still bind");
}
#[test]
fn a_file_that_does_not_lex_has_no_tokens_but_has_a_diagnostic() {
let mut ws = Workspace::default();
ws.set_document(uri("file:///rtl/m.sv"), "module m;\n wire a; /* unterminated\n".into());
let doc = ws.document(&uri("file:///rtl/m.sv")).expect("open");
assert!(doc.tokens.is_empty());
assert_eq!(doc.diagnostics.len(), 1);
}
#[test]
fn an_untitled_buffer_has_no_path() {
let mut ws = Workspace::default();
ws.set_document(uri("untitled:Untitled-1"), "module m;\nendmodule\n".into());
let doc = ws.document(&uri("untitled:Untitled-1")).expect("open");
assert_eq!(doc.path, None);
}
/// A buffer that never lexes still reports a `Lex` stage (the failed
/// attempt is real work and costs real time) and a `Parse` stage (the
/// `parse_source_tolerant` fallback), and still counts as one document.
/// `defines`/`analyze`/`external`/`lines` all still run over the empty
/// token stream and empty-error tree exactly as the un-instrumented
/// path always did — the wrapping must not skip a stage just because
/// an earlier one errored.
#[test]
fn a_buffer_that_fails_to_lex_still_records_every_rebuild_stage() {
crate::lint_trace::arm();
// An unterminated string literal is an unambiguous lex error that
// does not depend on lexer internals that could drift between
// versions (`vlog_parser::tokenize` is documented all-or-nothing).
let text = "module m;\n string s = \"unterminated\nendmodule\n".to_string();
let doc = Document::new(None, text, &WorkspaceIndex::default());
assert!(doc.tokens.is_empty(), "a lex failure leaves an empty token stream");
assert!(!doc.diagnostics.is_empty(), "a lex failure is a diagnostic");
let trace = crate::lint_trace::disarm().expect("armed");
// Every stage's field is present on the line, whether or not it
// took measurable time (`saw_document`, not a duration, is what
// says a rebuild happened at all — see the flaky test this round
// fixed in `lint_trace.rs`).
let line = trace.line();
assert!(line.contains("documents=1"), "{line}");
for stage in ["lex=", "parse=", "defines=", "analyze=", "external=", "lines=", "publish="] {
assert!(line.contains(stage), "{line}");
}
}
/// A `` `define `` edit changes the macro table `collect_defines`
/// produces, and nothing about wrapping that call in `rebuild` changes
/// which tokens it sees or what it returns: the new revision's table
/// reflects only the new text, never a stale value from the revision
/// before it (`Document::new` builds a fresh `DefineTable` every time,
/// same as before this round).
#[test]
fn a_define_edit_changes_the_macro_table_the_rebuild_reports_on() {
crate::lint_trace::arm();
let before = Document::new(
None,
"`define WIDTH 8\nmodule m;\n wire [`WIDTH-1:0] w;\nendmodule\n".to_string(),
&WorkspaceIndex::default(),
);
assert_eq!(before.defines.latest("WIDTH").map(|d| d.body.trim()), Some("8"));
assert!(before.defines.latest("DEPTH").is_none());
let after = Document::new(
None,
"`define DEPTH 16\nmodule m;\n wire [`DEPTH-1:0] w;\nendmodule\n".to_string(),
&WorkspaceIndex::default(),
);
assert!(after.defines.latest("WIDTH").is_none(), "no macro survives across documents");
assert_eq!(after.defines.latest("DEPTH").map(|d| d.body.trim()), Some("16"));
let trace = crate::lint_trace::disarm().expect("armed");
let line = trace.line();
assert!(line.contains("documents=2"), "two fresh Document::new calls, two rebuilds: {line}");
}
@@ -0,0 +1,223 @@
//! Rung 1 of the scope ladder: a filelist defines the index exactly, its
//! warnings reach the caller, and its `+incdir+`s reach the include graph.
use super::*;
/// A tree with three packages, one of which a filelist deliberately omits.
fn filelist_tree(name: &str) -> Tree {
let tree = Tree::new(name);
tree.package("rtl/a.sv", "a");
tree.package("rtl/b.sv", "b");
tree.package("rtl/unlisted.sv", "unlisted");
tree.write("files.f", "// the project\nrtl/a.sv\nrtl/b.sv\n");
tree
}
#[test]
fn a_configured_filelist_defines_the_index_exactly() {
// The point of a filelist: a file sitting in the tree that the project
// does not build is not indexed, however much the walk would find it.
let tree = filelist_tree("filelistkey");
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
let mut ws = Workspace::default();
let warnings = ws.open_roots(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a", "b"]);
assert!(warnings.is_empty(), "{warnings:?}");
}
#[test]
fn the_filelist_setting_beats_the_config_key_and_may_be_absolute() {
let tree = filelist_tree("filelistsetting");
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
tree.write("other.f", "rtl/unlisted.sv\n");
// Relative: against the workspace root, not the current directory.
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("other.f"));
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["unlisted"], "the setting wins");
// Absolute: taken as written.
let absolute = tree.path.join("other.f");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist(&absolute.display().to_string()));
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["unlisted"]);
}
#[test]
fn a_filelist_that_cannot_be_read_falls_back_to_the_walk_and_says_so() {
// The failure that must never happen: an empty index and no
// explanation because a path in a settings UI has a typo.
let tree = filelist_tree("filelistgone");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("typo.f"));
let warnings = ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a", "b", "unlisted"], "the walk ran");
assert_eq!(warnings.len(), 1);
assert!(warnings[0].contains("typo.f"), "{warnings:?}");
assert!(warnings[0].contains("indexing the workspace instead"), "{warnings:?}");
}
#[test]
#[cfg(unix)]
fn an_unreadable_directory_is_said_once_per_scan_and_the_rest_is_indexed() {
// TODO §45.2: the walk's warnings ride out on the scope's own
// warnings, which the server logs once per scan. Before the channel
// existed the walk returned an error the index simply dropped, so a
// permission-denied directory cost every file after it silently.
use std::os::unix::fs::PermissionsExt;
let tree = Tree::new("walkwarn");
tree.package("rtl/a.sv", "a");
tree.package("rtl/z.sv", "z");
tree.package("locked/hidden.sv", "hidden");
std::os::unix::fs::symlink("nowhere.sv", tree.path.join("rtl/gone.sv")).expect("symlink");
let locked = tree.path.join("locked");
fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).expect("chmod");
let mut ws = Workspace::default();
let warnings = ws.open_whole_workspace(vec![tree.path.clone()]);
let _ = fs::set_permissions(&locked, fs::Permissions::from_mode(0o755));
assert_eq!(indexed(&ws, &["a", "z", "hidden"]), ["a", "z"], "the scan finished");
assert_eq!(warnings.len(), 2, "{warnings:?}");
assert!(warnings.iter().any(|w| w.contains("locked")), "{warnings:?}");
assert!(warnings.iter().any(|w| w.contains("gone.sv: broken symbolic link")), "{warnings:?}");
}
#[test]
fn a_filelists_own_warnings_reach_the_caller() {
let tree = filelist_tree("filelistwarn");
tree.write("files.f", "rtl/a.sv\nrtl/moved.sv\n-nonsense\n");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("files.f"));
let warnings = ws.open_roots(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a"], "the rest is still indexed");
assert_eq!(warnings.len(), 2, "{warnings:?}");
assert!(warnings.iter().any(|w| w.contains("moved.sv")), "{warnings:?}");
assert!(warnings.iter().any(|w| w.contains("-nonsense")), "{warnings:?}");
}
#[test]
fn an_open_buffer_is_indexed_even_when_the_filelist_omits_it() {
// Open buffers overlay every rung of the ladder: a scratch file the
// project does not build still gets its own symbols.
let tree = filelist_tree("filelistbuffer");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("files.f"));
ws.open_roots(vec![tree.path.clone()]);
let path = tree.path.join("rtl/unlisted.sv");
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(uri, "package unlisted;\n localparam K = 1;\nendpackage\n".into());
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a", "b", "unlisted"]);
}
#[test]
fn with_no_workspace_root_the_open_files_own_directory_is_indexed() {
// The single-file case: no folder was opened, so the scope is what
// sits beside the buffer — and nothing below it.
let tree = Tree::new("noroot");
tree.package("rtl/open.sv", "open_pkg");
tree.package("rtl/sibling.sv", "sibling");
tree.package("rtl/deeper/below.sv", "below");
tree.package("elsewhere/far.sv", "far");
let mut ws = Workspace::default();
own_folder_only(&mut ws);
assert!(!ws.has_roots(), "the premise: no workspace folder");
let path = tree.path.join("rtl/open.sv");
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(uri, "package open_pkg;\n localparam K = 1;\nendpackage\n".into());
ws.rebuild_index();
assert_eq!(
indexed(&ws, &["open_pkg", "sibling", "below", "far"]),
["open_pkg", "sibling"],
"the buffer and its neighbours only"
);
}
#[test]
fn a_filelist_still_wins_when_there_is_no_workspace_root() {
let tree = filelist_tree("norootfilelist");
let mut ws = Workspace::default();
// With no root a relative setting cannot be anchored, so an absolute
// path is the only sensible way to name one — and it works.
ws.set_client_settings(using_filelist(&tree.path.join("files.f").display().to_string()));
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a", "b"]);
}
/// Where `ws` would look for `` `include "<name>" `` written in `from`.
fn resolved_include(ws: &Workspace, from: &Path, name: &str) -> Option<PathBuf> {
let text = format!("`include \"{name}\"\n");
let include = crate::includes::scan(&text).into_iter().next().expect("one include");
ws.includes().resolve(Some(from), &include)
}
/// A tree whose filelist names one `+incdir+` and nests a filelist naming
/// another, with a header in each — plus one only the nested incdir holds.
fn incdir_tree(name: &str) -> Tree {
let tree = Tree::new(name);
tree.package("rtl/a.sv", "a");
tree.write("first/defs.svh", "`define W 1\n");
tree.write("ip/include/defs.svh", "`define W 2\n");
tree.write("ip/include/ip_only.svh", "`define X 1\n");
tree.write("ip/ip.f", "+incdir+include\n");
tree.write("files.f", "+incdir+first\n-f ip/ip.f\nrtl/a.sv\n");
tree
}
#[test]
fn a_filelists_incdirs_reach_the_include_graph_in_filelist_order() {
// M1 recorded `+incdir+` and used it for nothing; this is the wire
// that spends it. A nested `-f`'s incdirs come through flattened,
// *after* the ones named before the `-f` — which is the order an
// include is searched in, so it is worth pinning here and not only in
// the parser.
let tree = incdir_tree("incdirs");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("files.f"));
let warnings = ws.open_roots(vec![tree.path.clone()]);
assert!(warnings.is_empty(), "{warnings:?}");
let from = tree.path.join("rtl/a.sv");
assert_eq!(
resolved_include(&ws, &from, "defs.svh"),
Some(tree.path.join("first/defs.svh")),
"the root filelist's incdir is searched before the nested one's"
);
assert_eq!(
resolved_include(&ws, &from, "ip_only.svh"),
Some(tree.path.join("ip/include/ip_only.svh")),
"and the nested one is searched at all"
);
}
#[test]
fn without_a_filelist_there_are_no_incdirs_at_all() {
// Rungs 2 and 3 of the ladder name no include path, so an `` `include``
// there has only the including file's own directory to go on.
let tree = incdir_tree("noincdirs");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(resolved_include(&ws, &tree.path.join("rtl/a.sv"), "defs.svh"), None);
}
#[test]
fn a_broken_filelist_leaves_the_include_graph_without_incdirs() {
let tree = incdir_tree("badfilelistincdirs");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("typo.f"));
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(
resolved_include(&ws, &tree.path.join("rtl/a.sv"), "defs.svh"),
None,
"the walk fallback names no include path"
);
}
@@ -0,0 +1,406 @@
//! The folder scope (index-scope, 2026-08-27): rung 3's climb and the two
//! clamps on it, what outranks it, and the inherited obligations from that
//! round's review.
use super::*;
/// A project laid out the way the owner described it: the file being
/// worked on in `rtl/`, a header folder beside it, and a third folder that
/// has nothing to do with either.
fn two_folder_tree(name: &str) -> Tree {
let tree = Tree::new(name);
tree.package("rtl/open.sv", "open_pkg");
tree.package("rtl/beside.sv", "beside_pkg");
tree.package("rtl/deeper/below.sv", "below_pkg");
tree.package("include/defs.sv", "defs_pkg");
tree.package("elsewhere/far.sv", "far_pkg");
tree
}
/// The four fixture packages, as the ones that are in the index.
fn scoped(ws: &Workspace) -> Vec<String> {
indexed(ws, &["open_pkg", "beside_pkg", "below_pkg", "defs_pkg", "far_pkg"])
}
#[test]
fn the_folder_scope_at_depth_zero_is_the_open_files_own_folder_and_everything_under_it() {
// The headline of the index-scope round: a workspace root is open, but
// the index covers the folder the user is working in, not the project.
// At depth 0 — the shipped default until 2026-08-28, and still exactly
// what an explicit `scopeDepth: 0` asks for.
let tree = two_folder_tree("scopedefault");
let mut ws = Workspace::default();
own_folder_only(&mut ws);
ws.open_roots(vec![tree.path.clone()]);
assert!(scoped(&ws).is_empty(), "premise: nothing is open, so nothing is in scope");
open(&mut ws, &tree, "rtl/open.sv");
ws.rebuild_index();
assert_eq!(
scoped(&ws),
["open_pkg", "beside_pkg", "below_pkg"],
"the buffer's own folder and its subtree — and no sibling folder"
);
}
#[test]
fn a_scope_depth_of_one_reaches_the_folder_beside_it() {
// `rtl/` plus `../include`: the layout the setting exists for.
let tree = two_folder_tree("scopedepth");
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings { index_scope_depth: 1, ..Default::default() });
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/open.sv");
ws.rebuild_index();
assert_eq!(
scoped(&ws),
["open_pkg", "beside_pkg", "below_pkg", "defs_pkg", "far_pkg"],
"one level up is the whole tree here, sibling folders included"
);
}
#[test]
fn the_climb_stops_at_the_workspace_root() {
// The clamp that keeps a depth of 99 in a two-deep project from
// indexing the user's home directory. Asserted on the directories
// themselves rather than on an index, because the failure this guards
// against is a walk that should never be started.
let tree = two_folder_tree("scopeclamp");
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings { index_scope_depth: 99, ..Default::default() });
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/deeper/below.sv");
assert_eq!(ws.scope_dirs(), vec![tree.path.clone()], "clamped at the root, not above it");
// The deepest containing root wins, so a nested root clamps tighter.
assert!(ws.change_roots(vec![tree.path.join("rtl")], &[]));
assert_eq!(ws.scope_dirs(), vec![tree.path.join("rtl")], "the deepest root is the floor");
}
#[test]
fn a_rootless_session_does_not_climb_at_all() {
// Changed 2026-08-28, with the shipped depth. The climb used to run
// with `/` as its only floor, which was survivable while the shipped
// depth was 0 and nobody climbed by accident. It is not survivable at
// depth 2: a lone file opened from `~/work/chip/hw/ip/aes/rtl/` would
// raise into `~/work/chip/hw/ip/` and walk a tree the user never
// named. The clamp is what makes a raise safe, so with nothing to
// clamp against there is no raise, whatever the depth says.
let tree = two_folder_tree("scoperootless");
for depth in [0, 1, 99] {
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings { index_scope_depth: depth, ..Default::default() });
open(&mut ws, &tree, "rtl/open.sv");
assert!(!ws.has_roots(), "the premise: no workspace folder to clamp against");
assert_eq!(
ws.scope_dirs(),
vec![tree.path.join("rtl")],
"depth {depth}: the buffer's own directory, and nothing above it"
);
}
}
#[test]
fn a_rootless_session_reads_its_own_directory_flat_until_the_depth_is_raised() {
// The `folder_files` exception, from the other side. The *directory*
// is the buffer's own whatever the depth (no root, no climb — see
// above), but the depth still chooses how it is read: 0 reads it flat,
// one level, no `.gitignore`, and a raise means the user has asked for
// a tree, so the tree below the buffer is walked.
let tree = two_folder_tree("scoperootlesswalk");
for (depth, expected) in
[(0, vec!["open_pkg", "beside_pkg"]), (1, vec!["open_pkg", "beside_pkg", "below_pkg"])]
{
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings { index_scope_depth: depth, ..Default::default() });
open(&mut ws, &tree, "rtl/open.sv");
ws.rebuild_index();
assert_eq!(scoped(&ws), expected, "depth {depth}");
}
}
#[test]
fn the_workspace_scope_setting_restores_the_walk_of_every_root() {
// The migration line in the README, pinned: with `scope: "workspace"`
// the index is the whole tree with no buffer open at all — which is
// exactly what this fixture gave before this round.
let tree = two_folder_tree("scopewide");
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings {
index_scope: IndexScope::Workspace,
..Default::default()
});
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(
scoped(&ws),
["open_pkg", "beside_pkg", "below_pkg", "defs_pkg", "far_pkg"],
"every file under the root, no buffer needed"
);
// And the depth is not consulted at all on that rung.
let mut raised = Workspace::default();
raised.set_client_settings(ClientSettings {
index_scope: IndexScope::Workspace,
index_scope_depth: 3,
..Default::default()
});
raised.open_roots(vec![tree.path.clone()]);
assert_eq!(raised.index().files(), ws.index().files(), "the depth changes nothing here");
}
#[test]
fn a_filelist_still_defines_the_scope_exactly_whatever_the_folder_rung_would_say() {
// Rung 1 outranks rung 3 as it always outranked rung 2: the filelist
// is the project file, and it names files in folders no buffer has
// been opened from.
let tree = two_folder_tree("scopefilelist");
tree.write("files.f", "include/defs.sv\nelsewhere/far.sv\n");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("files.f"));
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/open.sv");
ws.rebuild_index();
assert_eq!(
scoped(&ws),
["open_pkg", "defs_pkg", "far_pkg"],
"the filelist, plus the open buffer that overlays every rung"
);
assert!(ws.scope_dirs().is_empty(), "and no `didOpen` can widen a filelist");
}
#[test]
fn closing_a_file_never_narrows_the_scope() {
// The decision, pinned: the scope only grows within a session. A
// rebuild after a close must not take away answers the user had a
// moment ago, and no `didClose` costs a rescan.
let tree = two_folder_tree("scopeclose");
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings { index_scope_depth: 0, ..Default::default() });
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/open.sv");
open(&mut ws, &tree, "include/defs.sv");
ws.rebuild_index();
assert_eq!(scoped(&ws), ["open_pkg", "beside_pkg", "below_pkg", "defs_pkg"]);
let closed = crate::uri::path_to_uri(&tree.path.join("include/defs.sv")).expect("uri");
ws.close_document(&closed);
ws.rebuild_index();
assert_eq!(
scoped(&ws),
["open_pkg", "beside_pkg", "below_pkg", "defs_pkg"],
"the closed file's folder is still indexed"
);
}
#[test]
fn the_folder_scope_honours_every_exclude_and_the_gitignores_below_it() {
// Rung 3 walks with the same function rung 2 walks with, so nothing a
// user excluded comes back because the scope narrowed — with **one
// honest exception**, pinned here rather than left to be discovered:
// `lucisv_core`'s walk reads `.gitignore` files from its own starting
// directory downwards, so a rule written at the workspace root does
// not reach a walk that starts below it. The `exclude` patterns are
// matched against whole paths and are unaffected either way. Stated in
// `walked_files` and in `docs/features/index-scope/README.md`.
let tree = Tree::new("scopefilters");
tree.write("lucisv.toml", "exclude = [\"vendor\"]\n");
tree.write(".gitignore", "generated/\n");
tree.write("rtl/.gitignore", "dumps/\n");
tree.package("rtl/open.sv", "open_pkg");
tree.package("rtl/vendor/ip.sv", "vendor_pkg");
tree.package("rtl/dumps/net.sv", "dumps_pkg");
tree.package("rtl/generated/net.sv", "generated_pkg");
tree.package("rtl/scratch/wip.sv", "scratch_pkg");
let names = &["open_pkg", "vendor_pkg", "dumps_pkg", "generated_pkg", "scratch_pkg"];
let mut ws = Workspace::default();
ws.set_client_settings(excluding(&["scratch"]));
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/open.sv");
ws.rebuild_index();
assert_eq!(
indexed(&ws, names),
["open_pkg", "generated_pkg"],
"both excludes and the .gitignore inside the scope applied; the one at the \
root, above where this walk starts, did not"
);
// ...and the wide scope, whose walk starts at the root, does apply it.
let mut wide = Workspace::default();
wide.set_client_settings(ClientSettings {
exclude: vec!["scratch".to_string()],
index_scope: IndexScope::Workspace,
..Default::default()
});
wide.open_roots(vec![tree.path.clone()]);
assert_eq!(indexed(&wide, names), ["open_pkg"], "everything filtered, from the root");
}
#[test]
fn a_folder_added_mid_session_widens_nothing_until_a_file_in_it_is_opened() {
// The interaction between the two ways a scope can move. Under the
// folder rung a workspace folder is a *clamp*, not a work list, so
// adding one changes which files exist only once a buffer in it makes
// it a scope directory.
let first = Tree::new("scopefolderfirst");
first.package("a.sv", "a");
let second = Tree::new("scopefoldersecond");
second.package("b.sv", "b");
let mut ws = Workspace::default();
ws.open_roots(vec![first.path.clone()]);
open(&mut ws, &first, "a.sv");
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a", "b"]), ["a"], "premise: the first folder's file");
assert!(ws.change_roots(vec![second.path.clone()], &[]), "the root set moved");
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a", "b"]), ["a"], "but no buffer lives there yet");
open(&mut ws, &second, "b.sv");
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a", "b"]), ["a", "b"], "opening one widens the scope");
}
#[test]
fn a_scope_or_a_depth_change_asks_for_a_rescan() {
// Both change which files exist, so both join `exclude`, `filelist`
// and the size cap in the rescan test.
let mut ws = Workspace::default();
let wide = ClientSettings { index_scope: IndexScope::Workspace, ..Default::default() };
assert!(ws.set_client_settings(wide.clone()), "a new scope rescans");
assert!(!ws.set_client_settings(wide.clone()), "the same one does not");
assert!(ws.set_client_settings(ClientSettings::default()), "and going back does");
let deep = ClientSettings { index_scope_depth: 5, ..Default::default() };
assert!(ws.set_client_settings(deep.clone()), "a new depth rescans");
assert!(!ws.set_client_settings(deep), "the same one does not");
assert!(ws.set_client_settings(ClientSettings::default()), "and going back does");
}
#[test]
fn the_open_files_are_indexed_first_and_the_index_cannot_tell() {
// Two halves of one claim. First: the progress events name the open
// buffers before anything else, which is what makes a big rescan feel
// like it is working on the user's own files.
let tree = Tree::new("scopeorder");
tree.package("rtl/a_first.sv", "a_first");
tree.package("rtl/m_open.sv", "m_open");
tree.package("rtl/z_last.sv", "z_last");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/m_open.sv");
// Every file of the work list, however it got into the index: since
// 2026-08-28 the open buffer goes in from its own analysis and reports
// `Analyzed` rather than `Parsing`, and the claim under test is about
// the *order* the work list is walked in, not about who parses.
let mut seen: Vec<PathBuf> = Vec::new();
ws.rebuild_index_with(&mut |event| match event {
IndexEvent::Parsing { path, .. }
| IndexEvent::Cached { path, .. }
| IndexEvent::Analyzed { path, .. } => seen.push(path.to_path_buf()),
IndexEvent::Skipped { .. } => {}
});
assert_eq!(
seen,
vec![
tree.path.join("rtl/m_open.sv"),
tree.path.join("rtl/a_first.sv"),
tree.path.join("rtl/z_last.sv"),
],
"the open buffer first, then the rest in path order"
);
// Second, and the reason the first is allowed to be true: the index
// is byte-identical to the one the plain path order builds. The
// builder sorts inside `finish`, so the order above is a reporting
// decision and nothing more (`vlog_semantic`'s
// `no_insertion_order_can_change_what_the_builder_produces` is the
// other end of this).
let mut plain = Workspace::default();
plain.set_client_settings(ClientSettings {
index_scope: IndexScope::Workspace,
..Default::default()
});
plain.open_roots(vec![tree.path.clone()]);
assert_eq!(ws.index().files(), plain.index().files(), "same files, same ids");
assert_eq!(ws.index().counts(), plain.index().counts(), "and the same index");
}
#[test]
fn lowering_the_scope_depth_narrows_the_index_on_the_next_rescan() {
// The scope grows only along the *open* axis — a `didClose` never
// narrows it. A settings change is the other axis and moves both ways,
// because it is a deliberate statement about how much of this machine's
// time to spend. Verified by hand by the previous round's QA; pinned
// here.
let tree = two_folder_tree("depthdown");
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings { index_scope_depth: 1, ..Default::default() });
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/open.sv");
ws.rebuild_index();
assert!(scoped(&ws).contains(&"defs_pkg".to_string()), "premise: depth 1 reaches beside");
assert!(
ws.set_client_settings(ClientSettings { index_scope_depth: 0, ..Default::default() }),
"lowering the depth asks for a rescan"
);
ws.rebuild_index();
assert_eq!(scoped(&ws), ["open_pkg", "beside_pkg", "below_pkg"], "narrowed, not kept");
}
#[test]
fn a_filelist_appearing_mid_session_flips_the_ladder_to_rung_one() {
// Not just "asks for a rescan" — that the index really becomes the
// filelist's files, from a folder scope that was covering something
// else entirely.
let tree = two_folder_tree("filelistmid");
tree.write("files.f", "elsewhere/far.sv\n");
let mut ws = Workspace::default();
own_folder_only(&mut ws);
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/open.sv");
ws.rebuild_index();
assert_eq!(scoped(&ws), ["open_pkg", "beside_pkg", "below_pkg"], "premise: the folder rung");
assert!(ws.set_client_settings(using_filelist("files.f")), "a rescan is owed");
ws.rebuild_index();
assert_eq!(
scoped(&ws),
["open_pkg", "far_pkg"],
"rung 1 defines the scope exactly — plus the open buffer, which overlays every rung"
);
}
#[test]
fn a_buffer_opened_outside_every_root_rides_the_folder_rung_like_a_rootless_one() {
// `raised()`'s floor is the deepest root *containing* the directory, and
// there is none here — so the climb stops at `/`, exactly as it does
// with no root at all. Verified by hand by the previous round's QA;
// pinned here, on the directories rather than by walking one.
let inside = Tree::new("outsideroot_in");
inside.package("rtl/a.sv", "a_pkg");
let outside = Tree::new("outsideroot_out");
outside.package("other/b.sv", "b_pkg");
let mut ws = Workspace::default();
own_folder_only(&mut ws);
ws.open_roots(vec![inside.path.clone()]);
open(&mut ws, &outside, "other/b.sv");
assert_eq!(
ws.scope_dirs(),
vec![outside.path.join("other")],
"at depth 0 it is the buffer's own directory and nothing else"
);
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a_pkg", "b_pkg"]), ["b_pkg"], "the root's own tree is not in it");
ws.set_client_settings(ClientSettings { index_scope_depth: 99, ..Default::default() });
assert_eq!(
ws.scope_dirs(),
vec![PathBuf::from("/")],
"and with nothing to clamp against the climb stops at the filesystem root"
);
}
@@ -0,0 +1,233 @@
//! Workspace folders added and removed mid-session
//! (`didChangeWorkspaceFolders`): what widens the scan, what narrows it,
//! what changes nothing, and what is left when the last root goes.
use super::*;
#[test]
fn a_root_added_mid_session_widens_the_scan_and_a_removed_one_narrows_it() {
let first = Tree::new("rootsfirst");
first.package("a.sv", "a");
let second = Tree::new("rootssecond");
second.package("b.sv", "b");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![first.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b"]), ["a"], "premise: one folder");
assert!(ws.change_roots(vec![second.path.clone()], &[]), "a new folder moves the set");
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a", "b"]), ["a", "b"], "both folders are scanned");
assert!(ws.change_roots(Vec::new(), from_ref(&first.path)), "and so does dropping one");
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a", "b"]), ["b"], "the dropped folder's files are gone");
}
#[test]
fn a_subdirectory_of_an_existing_root_added_as_its_own_root_is_not_double_indexed() {
// Overlap does not duplicate a file's registration: `walked_files`
// walks each root independently and `dedup`s the combined, sorted
// list by path, so a file both roots would reach lands in the index
// once, not twice (a second identical registration would show up as
// an *ambiguous* member — `indexed` below only counts a name found
// exactly once).
//
// It is NOT exclude-proof, though, and that half is a genuine
// consequence of "each root is governed by its own config"
// (documented on `walked_files`): a directory the parent root's
// `lucisv.toml` excludes is added *as a root in its own right* here,
// and nothing excludes a root from itself. QA (2026-08-27): flagged
// in the QA log as a finding, not a bug fix — this is consistent
// with the per-root config model, but it was unreachable before this
// round (roots used to be frozen at `initialize`), so it is worth a
// pin and a name.
let tree = Tree::new("subdirroot");
tree.write("lucisv.toml", "exclude = [\"sub\"]\n");
tree.package("kept.sv", "kept");
tree.package("sub/hidden.sv", "hidden_pkg");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["kept", "hidden_pkg"]), ["kept"], "excluded, as configured");
assert!(ws.change_roots(vec![tree.path.join("sub")], &[]));
ws.rebuild_index();
assert_eq!(
indexed(&ws, &["kept", "hidden_pkg"]),
["kept", "hidden_pkg"],
"reachable once through the added root, and only once — not ambiguous"
);
}
/// A workspace whose tree links back into itself. Before the walk kept a
/// visited set (`docs/features/walk-cycles/README.md`) this scan never
/// finished — the editor's index simply never came up. Each directory is
/// entered once now, so each package is registered exactly once: a second
/// registration would make the name *ambiguous*, and `indexed` only
/// counts a name found exactly once.
#[cfg(unix)]
#[test]
fn a_cyclic_workspace_is_scanned_once_and_finishes() {
let tree = Tree::new("cycle");
tree.package("rtl/a.sv", "a");
tree.package("rtl/sub/b.sv", "b");
// `rtl/self` is `rtl` itself; `rtl/sub/up` is `rtl` from one level
// down. Either one alone runs until the OS refuses a path.
std::os::unix::fs::symlink("../rtl", tree.path.join("rtl/self")).expect("symlink");
std::os::unix::fs::symlink("..", tree.path.join("rtl/sub/up")).expect("symlink");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b"]), ["a", "b"]);
assert_eq!(
ws.walked_files(from_ref(&tree.path), &mut |_| {}, &mut ScanTrace::new(false)).len(),
2,
"two files, once each"
);
}
#[test]
fn a_folder_change_that_changes_nothing_asks_for_no_rescan() {
// Every no-op shape a client can send. Each must leave the root set
// exactly as it was, and say so — a rescan here is pure cost.
let tree = Tree::new("rootsnoop");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
assert!(!ws.change_roots(Vec::new(), &[]), "an empty event");
assert!(!ws.change_roots(vec![tree.path.clone()], &[]), "a folder already held");
let never = tree.path.join("never-added");
assert!(!ws.change_roots(Vec::new(), from_ref(&never)), "a folder never held");
assert!(!ws.change_roots(vec![tree.path.clone()], from_ref(&never)), "and both at once");
assert!(ws.has_roots(), "the root survived every one of them");
}
#[test]
fn a_trailing_slash_in_the_removed_folder_still_matches_the_held_root() {
// `uri_to_path` decodes a URI verbatim, trailing slash and all, and
// `change_roots` compares by `PathBuf` equality — which compares
// components, not raw strings, so `/a/b/` and `/a/b` are already the
// same path as far as `retain`/`contains` are concerned. Pinned
// because the doc README calls this out as a boundary worth
// checking, not because the standard library needed help.
let tree = Tree::new("trailingslash");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
let mut with_slash = tree.path.clone().into_os_string();
with_slash.push("/");
assert!(
ws.change_roots(Vec::new(), from_ref(&PathBuf::from(with_slash))),
"the trailing slash must not hide the match"
);
assert!(!ws.has_roots());
}
#[test]
fn a_folder_named_in_both_halves_of_one_event_stays() {
// Removals run first, so "removed and added again" — which is how a
// moved folder reaches some clients — is not a way to lose a root.
let tree = Tree::new("rootsboth");
tree.package("a.sv", "a");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert!(!ws.change_roots(vec![tree.path.clone()], from_ref(&tree.path)), "no net change");
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a"]), ["a"]);
}
#[test]
fn a_folder_added_twice_across_two_events_is_absent_after_one_removal() {
// The root set is a set, not a multiset: `change_roots` dedups on
// push (`if !self.roots.contains(&root)`), so a second add of the
// same path — even from a *later*, separate notification — never
// grows a reference count for it. One removal is therefore always
// enough, however many times a client (redundantly) added it.
// QA (2026-08-27): pinned per the review checklist's multiset-vs-set
// question.
let tree = Tree::new("addedtwice");
let extra = Tree::new("addedtwiceextra");
extra.package("x.sv", "x");
let mut ws = Workspace::default();
// Whole-workspace scope, so the indexed-content assertions below see
// the roots at all — under the default folder scope nothing is
// walked until a buffer opens, and the closing assertion was vacuous
// (QA finding, 2026-08-27, lead-fixed).
ws.open_whole_workspace(vec![tree.path.clone()]);
assert!(ws.change_roots(vec![extra.path.clone()], &[]), "the first add moves the set");
assert!(
!ws.change_roots(vec![extra.path.clone()], &[]),
"a second, separate add of the same path is a no-op"
);
ws.rebuild_index();
assert_eq!(indexed(&ws, &["x"]), vec!["x".to_string()], "present while added");
assert!(
ws.change_roots(Vec::new(), from_ref(&extra.path)),
"one removal is enough to take it out"
);
ws.rebuild_index();
assert_eq!(indexed(&ws, &["x"]), Vec::<String>::new(), "gone, not merely decremented");
}
#[test]
fn removing_the_last_root_falls_back_to_the_rootless_model() {
// Rung 3 of the ladder is not a startup-only state: a session that
// closes its last folder becomes the single-file case, and an open
// buffer must still resolve against the files beside it.
let tree = Tree::new("rootslast");
tree.package("rtl/open.sv", "open_pkg");
tree.package("rtl/sibling.sv", "sibling");
tree.package("elsewhere/far.sv", "far");
let mut ws = Workspace::default();
own_folder_only(&mut ws);
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["open_pkg", "sibling", "far"]), ["open_pkg", "sibling", "far"]);
let path = tree.path.join("rtl/open.sv");
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(uri, "package open_pkg;\n localparam K = 1;\nendpackage\n".into());
assert!(ws.change_roots(Vec::new(), from_ref(&tree.path)));
assert!(!ws.has_roots(), "the workspace is rootless now");
ws.rebuild_index();
assert_eq!(
indexed(&ws, &["open_pkg", "sibling", "far"]),
["open_pkg", "sibling"],
"the buffer and its neighbours, as if the file had been opened on its own"
);
}
#[test]
fn removing_the_last_root_leaves_a_relative_filelist_unanchored() {
// `filelist_path` anchors a relative setting at `roots.first()`. With
// no roots left there is nothing to anchor it to, and the path comes
// back exactly as the client wrote it — not resolved against the
// folder that is now gone, and not resolved against anything else
// either. Nothing panics: `source_files` still falls back to the
// rootless walk with a warning when that bare path cannot be read
// (`a_filelist_that_cannot_be_read_falls_back_to_the_walk_and_says_so`
// covers that fallback). QA (2026-08-27): pinned because this is new
// reachable behaviour this round — losing the last root used to be
// impossible.
let tree = Tree::new("rootslastfilelist");
tree.package("rtl/open.sv", "open_pkg");
tree.write("files.f", "rtl/open.sv\n");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("files.f"));
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(
ws.filelist_path(),
Some(tree.path.join("files.f")),
"anchored at the root while it exists"
);
assert!(ws.change_roots(Vec::new(), from_ref(&tree.path)));
assert_eq!(
ws.filelist_path(),
Some(PathBuf::from("files.f")),
"with no roots left, the same setting comes back bare — anchored at nothing"
);
}
@@ -0,0 +1,191 @@
//! The incremental path (incremental-index, 2026-08-27): one saved file
//! re-indexed in place, checked against the whole rebuild it stands in for.
use super::*;
#[test]
fn only_a_file_the_index_already_holds_takes_the_incremental_path() {
// The whole gate, from both sides. A file the index holds is one the
// update can replace; anything else is a rebuild's business, because a
// file appearing changes what *other* files' includes resolve to.
let tree = Tree::new("incrgate");
tree.package("rtl/a.sv", "a_pkg");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert!(ws.update_one_checked(&tree.path.join("rtl/a.sv")), "a file the index holds");
assert!(!ws.update_one(&tree.path.join("rtl/new.sv")), "a file it does not");
assert!(!ws.update_one(&tree.path.join("rtl/a.txt")), "and a path it never would");
// A file that appears is exactly the "not held" case, and stays so
// until something rebuilds.
tree.package("rtl/new.sv", "new_pkg");
assert!(!ws.update_one(&tree.path.join("rtl/new.sv")), "still not held");
ws.rebuild_index();
assert!(ws.update_one_checked(&tree.path.join("rtl/new.sv")), "held now");
}
#[test]
fn one_files_edit_reaches_every_table_the_index_answers_from() {
// The four pieces of derived state a rebuild produces, checked one by
// one after an update that moves all four: a declaration, an
// instantiation edge, an inheritance edge, a completion word and an
// `` `include`` edge.
let tree = Tree::new("incrtables");
tree.write("rtl/defs.svh", "`define W 8\n");
tree.write("rtl/sub.sv", "module sub;\nendmodule\nclass base;\nendclass\n");
tree.write("rtl/top.sv", "`include \"defs.svh\"\nmodule top;\n sub u1 ();\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let top = tree.path.join("rtl/top.sv");
assert_eq!(ws.index().instantiations_of("sub").len(), 1, "premise: one site");
assert_eq!(
ws.includes().reachable(vec![top.clone()]).len(),
2,
"premise: top.sv reaches defs.svh"
);
assert_eq!(ws.candidates().words("u1").len(), 1, "premise: the instance name is a word");
fs::write(
&top,
"module top;\n logic renamed_wire;\nendmodule\nclass leaf extends base;\nendclass\n",
)
.expect("write");
assert!(ws.update_one_checked(&top));
assert!(ws.index().instantiations_of("sub").is_empty(), "the site went");
assert_eq!(ws.index().subclasses_of("base").len(), 1, "and an inheritance edge came");
assert!(ws.candidates().words("u1").is_empty(), "the old word was given back");
assert_eq!(ws.candidates().words("renamed_wire").len(), 1, "the new one taken");
assert_eq!(ws.includes().reachable(vec![top]).len(), 1, "the include edge went too");
}
#[test]
fn a_file_the_cap_or_the_disk_takes_away_leaves_the_index() {
let tree = Tree::new("incrremove");
tree.package("rtl/keep.sv", "keep_pkg");
tree.package("rtl/gone.sv", "gone_pkg");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["keep_pkg", "gone_pkg"]).len(), 2, "premise");
// Deleted on disk: the update is a removal.
let gone = tree.path.join("rtl/gone.sv");
fs::remove_file(&gone).expect("remove");
assert!(ws.update_one_checked(&gone), "a held file, even a vanished one");
assert_eq!(indexed(&ws, &["keep_pkg", "gone_pkg"]), ["keep_pkg"]);
// And a file that grew past the cap is the same answer for the same
// reason: it is not a file this server reads any more.
let mut ws = Workspace::default();
let tree = Tree::new("incrcap");
tree.package("rtl/keep.sv", "keep_pkg");
fat_package(&tree, "rtl/netlist.sv", "netlist_pkg", 4096);
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["keep_pkg", "netlist_pkg"]).len(), 2, "premise: under no cap");
ws.set_client_settings(wide(capping(1024)));
assert!(ws.update_one_checked(&tree.path.join("rtl/netlist.sv")));
assert_eq!(indexed(&ws, &["keep_pkg", "netlist_pkg"]), ["keep_pkg"], "the cap took it");
}
#[test]
fn an_open_buffer_beats_disk_on_the_incremental_path_too() {
let tree = Tree::new("incrbuffer");
tree.package("rtl/a.sv", "a_pkg");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let path = tree.path.join("rtl/a.sv");
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(uri, "package buffered_pkg;\n localparam K = 1;\nendpackage\n".to_string());
assert!(ws.update_one_checked(&path));
assert_eq!(
indexed(&ws, &["a_pkg", "buffered_pkg"]),
["buffered_pkg"],
"the buffer's text, not the file's"
);
}
#[test]
fn the_incremental_update_agrees_with_a_whole_rebuild_over_the_real_corpus() {
// The paranoid sweep: take real files out of a real workspace, put a
// mutated version back through the incremental path, and check the
// result against a whole rebuild every time. `update_one_checked` is
// what does the checking; this test is the corpus it does it over.
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
// Copied into a scratch tree, because the sweep rewrites files. Every
// fifth file: `update_one_checked` rebuilds the whole workspace to
// check itself, so the sweep costs a full rebuild per mutation and a
// third of the corpus is still hundreds of real files.
let tree = Tree::new("incrcorpus");
let mut copied = 0;
let mut sample: Vec<PathBuf> = Vec::new();
for (n, source) in walk_sources(&corpus).into_iter().step_by(5).enumerate() {
let Ok(text) = fs::read_to_string(&source) else { continue };
let rel = format!("f{n:04}.sv");
tree.write(&rel, &text);
copied += 1;
if n % 31 == 0 {
sample.push(tree.path.join(&rel));
}
}
assert!(copied > 100, "premise: the corpus was really copied ({copied} files)");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert!(sample.len() > 5, "a sample worth sweeping: {}", sample.len());
for path in &sample {
let text = fs::read_to_string(path).expect("the copy is on disk");
// Four shapes of edit, each checked against a whole rebuild.
assert!(ws.update_one_checked(path), "unchanged");
fs::write(
path,
format!("{text}\nmodule qa_added_module;\n qa_added_sub u1 ();\nendmodule\n"),
)
.expect("write");
assert!(ws.update_one_checked(path), "a declaration and an edge added");
fs::write(path, "class qa_leaf extends qa_base;\nendclass\n").expect("write");
assert!(ws.update_one_checked(path), "replaced wholesale");
fs::write(path, "").expect("write");
assert!(ws.update_one_checked(path), "emptied");
fs::remove_file(path).expect("remove");
assert!(ws.update_one_checked(path), "removed");
}
eprintln!("paranoid sweep: {copied} files, {} of them mutated five ways", sample.len());
}
/// What one file's rescan costs on the incremental path, against the whole
/// rebuild it replaces, over the real corpus.
///
/// `#[ignore]`d like the crate's other measurement probes: it prints
/// numbers rather than asserting one. The numbers themselves are in
/// `docs/features/incremental-index/README.md`.
#[test]
#[ignore]
fn qa_perf_one_file_against_the_whole_rebuild() {
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![corpus]);
let files = ws.index().files().len();
let one = ws.index().files().last().cloned().expect("a file");
let mut whole = std::time::Duration::MAX;
let mut single = std::time::Duration::MAX;
for _ in 0..3 {
let started = std::time::Instant::now();
ws.rebuild_index();
whole = whole.min(started.elapsed());
let started = std::time::Instant::now();
assert!(ws.update_one(&one));
single = single.min(started.elapsed());
}
eprintln!(
"reindex over {files} files: whole rebuild {whole:?}, one file {single:?} \
({:.0}x)",
whole.as_secs_f64() / single.as_secs_f64().max(f64::MIN_POSITIVE)
);
}
@@ -0,0 +1,187 @@
//! An interleaved scan against the one-shot scan it must equal: the
//! publication cadence, the tables however often they were published, a
//! buffer opened mid-scan, and the events in the same order either way.
use super::*;
/// Run a scan the way `server.rs` does, publishing after **every** file —
/// the worst case the interleaved path can produce, and the one a
/// one-shot scan has to agree with.
fn scan_publishing_every_file(ws: &mut Workspace) -> Vec<String> {
let mut scan = ws.begin_scan(&mut |_| {}, false);
while ws.scan_step(&mut scan, &mut |_| {}) {
ws.publish_scan(&mut scan);
}
ws.finish_scan(scan)
}
#[test]
fn the_publication_cadence_holds_a_publish_until_enough_has_been_staged() {
// **The whole of the cadence, at its exact boundary.** A publish is a
// pass over the whole index, and before §61.4 the drain paid one per
// burst of requests — 13 to 18 in one warm opentitan scan, 46 % of it
// (`docs/features/perf5r-publication/README.md`). `publish_is_due`
// spaces them by work done rather than by how often a client asks: no
// publish is due until `PUBLISH_EVERY` records are staged, one is due
// the moment the 512th lands, and publishing clears the debt.
let tree = Tree::new("publishcadence");
for n in 0..scan::PUBLISH_EVERY + 2 {
tree.package(&format!("p{n:04}.sv"), &format!("p{n:04}"));
}
let mut ws = Workspace::default();
ws.client.index_scope = IndexScope::Workspace;
ws.adopt_roots(vec![tree.path.clone()]);
let mut scan = ws.begin_scan(&mut |_| {}, false);
for taken in 1..scan::PUBLISH_EVERY {
assert!(ws.scan_step(&mut scan, &mut |_| {}), "premise: file {taken} exists");
assert!(!scan.publish_is_due(), "{taken} staged is not yet a publish");
}
assert!(ws.scan_step(&mut scan, &mut |_| {}), "premise: the 512th file exists");
assert!(scan.publish_is_due(), "{} staged is", scan::PUBLISH_EVERY);
ws.publish_scan(&mut scan);
assert!(!scan.publish_is_due(), "and publishing clears the debt");
// The cadence is a latency decision and nothing else: what this scan
// lands is what a one-shot scan over the same tree lands.
while ws.scan_step(&mut scan, &mut |_| {}) {}
ws.finish_scan(scan);
let mut one_shot = Workspace::default();
one_shot.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(everything(&one_shot), everything(&ws));
}
#[test]
fn publishing_between_every_file_leaves_what_a_one_shot_scan_leaves() {
// The round's central invariant. The interleaved scan and the one-shot
// scan are the same three calls with and without a drain between them,
// so this pins the thing a drain could break: that folding records in
// as they are taken lands the same index, the same completion tables
// and the same include graph as folding them all in at the end.
let tree = tangled("interleavesame");
let mut one_shot = Workspace::default();
one_shot.open_whole_workspace(vec![tree.path.clone()]);
let mut stepped = Workspace::default();
stepped.client.index_scope = IndexScope::Workspace;
stepped.adopt_roots(vec![tree.path.clone()]);
scan_publishing_every_file(&mut stepped);
assert_eq!(everything(&one_shot), everything(&stepped));
assert!(one_shot.index().files().len() == 4, "premise: every file was scanned");
}
#[test]
fn a_rescan_that_publishes_as_it_goes_still_drops_what_left_the_scope() {
// A publish only ever folds records *in*, so the removal a rescan owes
// — files the last scan held that this one's work list does not name —
// has to survive every publish that happened before it.
let tree = tangled("interleavegone");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert!(!ws.index().units("c").is_empty(), "premise: c.sv is indexed");
std::fs::remove_file(tree.path.join("c.sv")).expect("remove");
scan_publishing_every_file(&mut ws);
let mut fresh = Workspace::default();
fresh.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(everything(&fresh), everything(&ws));
assert!(ws.index().units("c").is_empty(), "the file that left the scope is gone");
assert_eq!(ws.index().files().len(), 3);
}
#[test]
fn a_buffer_opened_or_changed_mid_scan_does_not_change_what_the_scan_indexes() {
// The scan holds the text every file had when its work list was taken,
// and indexes *that* — which is exactly what a `didOpen` or a
// `didChange` landing a moment after the scan finished would leave in
// the index too (neither touches it; a save is what does). So a
// message answered in the middle of a scan cannot move the scan's
// result, and the fingerprint is the witness.
let tree = tangled("interleavemidchange");
let mut one_shot = Workspace::default();
one_shot.open_whole_workspace(vec![tree.path.clone()]);
let mut stepped = Workspace::default();
stepped.client.index_scope = IndexScope::Workspace;
stepped.adopt_roots(vec![tree.path.clone()]);
let mut scan = stepped.begin_scan(&mut |_| {}, false);
assert!(stepped.scan_step(&mut scan, &mut |_| {}), "premise: there is a first file");
stepped.publish_scan(&mut scan);
// The client opens `b.sv` and types in it, mid-scan.
let opened = uri(&format!("file://{}", tree.path.join("b.sv").display()));
stepped.set_document(opened.clone(), "module b;\n localparam MID = 1;\nendmodule\n".into());
while stepped.scan_step(&mut scan, &mut |_| {}) {
stepped.publish_scan(&mut scan);
}
stepped.finish_scan(scan);
assert_eq!(everything(&one_shot), everything(&stepped));
assert_eq!(
stepped.document(&opened).map(|doc| doc.text.as_str()),
Some("module b;\n localparam MID = 1;\nendmodule\n"),
"the buffer keeps the text it was given, index or no index"
);
}
#[test]
fn a_file_opened_mid_scan_is_indexed_next_and_the_index_cannot_tell() {
// The open-first rule for a file opened *after* the work list was
// taken. It moves to the front of what is left, everything it passed
// keeps its place behind it, and the finished index is byte-identical
// — records are merged in path order whatever order they arrived in.
let tree = tangled("interleaveopenfirst");
let mut one_shot = Workspace::default();
one_shot.open_whole_workspace(vec![tree.path.clone()]);
let mut stepped = Workspace::default();
stepped.client.index_scope = IndexScope::Workspace;
stepped.adopt_roots(vec![tree.path.clone()]);
let mut scan = stepped.begin_scan(&mut |_| {}, false);
assert!(stepped.scan_step(&mut scan, &mut |_| {}), "premise: a.sv goes first");
assert!(stepped.index().units("c").is_empty(), "premise: c.sv is not indexed yet");
// The client opens `c.sv`, and the work list is re-ordered around the
// buffers open now — since 2026-09-08 that is one call rather than one
// per opened path, because a buffer brings its folder with it
// (`docs/features/perf5-p4/README.md` §P4b3).
let jumped = uri(&format!("file://{}", tree.path.join("c.sv").display()));
let jumped_text = fs::read_to_string(tree.path.join("c.sv")).expect("the fixture");
stepped.set_document(jumped, jumped_text);
stepped.open_next(&mut scan, &mut |_| {});
assert!(stepped.scan_step(&mut scan, &mut |_| {}));
stepped.publish_scan(&mut scan);
assert!(!stepped.index().units("c").is_empty(), "c.sv was indexed next, not last");
while stepped.scan_step(&mut scan, &mut |_| {}) {}
stepped.finish_scan(scan);
assert_eq!(everything(&one_shot), everything(&stepped));
}
#[test]
fn a_scan_reports_the_same_events_in_the_same_order_however_it_is_driven() {
// The progress bar and the per-file log are the same two things a
// one-shot scan reports, in the same order, against the same total:
// interleaving adds drains between the events, never events.
let tree = tangled("interleaveevents");
let mut one_shot = Workspace::default();
one_shot.client.index_scope = IndexScope::Workspace;
one_shot.adopt_roots(vec![tree.path.clone()]);
let mut said = Vec::new();
one_shot.rebuild_index_with(&mut |event| said.push(seen(&event)));
let mut stepped = Workspace::default();
stepped.client.index_scope = IndexScope::Workspace;
stepped.adopt_roots(vec![tree.path.clone()]);
let mut also = Vec::new();
let mut scan = stepped.begin_scan(&mut |event| also.push(seen(&event)), false);
while stepped.scan_step(&mut scan, &mut |event| also.push(seen(&event))) {
stepped.publish_scan(&mut scan);
}
assert_eq!(scan.skipped(), 0);
assert_eq!(scan.cached(), 0);
stepped.finish_scan(scan);
assert_eq!(said, also);
assert_eq!(said.len(), 4, "one event per file, and nothing else: {said:?}");
}
@@ -0,0 +1,90 @@
//! The large-file fast path: the threshold is strict and `0` turns it off,
//! a fast-path buffer holds the analysis of an empty file and contributes
//! nothing to the index, and a buffer changes mode as it crosses the line.
use super::*;
/// A workspace whose fast path starts at `threshold` bytes.
fn thresholded(threshold: u64) -> Workspace {
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings {
large_file_threshold: threshold,
..ClientSettings::default()
});
ws
}
#[test]
fn the_threshold_is_strict_at_the_boundary() {
let sizes = [99, 100, 101];
let large: Vec<bool> = sizes
.iter()
.map(|&size| {
let mut ws = thresholded(100);
ws.set_document(uri("file:///rtl/big.v"), filler(size));
ws.document(&uri("file:///rtl/big.v")).expect("open").large
})
.collect();
assert_eq!(large, [false, false, true], "under, at, over");
}
#[test]
fn a_threshold_of_zero_turns_the_fast_path_off_entirely() {
let mut ws = thresholded(0);
ws.set_document(uri("file:///rtl/big.v"), filler(200_000));
let doc = ws.document(&uri("file:///rtl/big.v")).expect("open");
assert!(!doc.large);
assert!(!doc.tokens.is_empty(), "it really was lexed");
}
#[test]
fn a_fast_path_buffer_holds_the_analysis_of_an_empty_file() {
let mut ws = thresholded(100);
ws.set_document(uri("file:///rtl/big.v"), filler(500));
let doc = ws.document(&uri("file:///rtl/big.v")).expect("open");
assert!(doc.large);
assert!(doc.tokens.is_empty(), "nothing was lexed");
assert!(doc.diagnostics.is_empty(), "nothing was parsed");
assert!(doc.semantics.symbols().is_empty(), "nothing was analyzed");
assert!(doc.defines.entries().is_empty(), "no defines were collected");
// But the two things the fast path *does* build are real.
assert_eq!(doc.text.len(), 500);
assert!(doc.line_index.line_count() > 1);
}
#[test]
fn a_fast_path_buffer_contributes_nothing_to_the_index_and_leaves_no_disk_copy_behind() {
let tree = Tree::new("largefile");
tree.write("pkg.sv", "package p;\n localparam ON_DISK = 1;\nendpackage\n");
let path = tree.path.join("pkg.sv");
let mut ws = thresholded(100);
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(ws.index().member("p", "ON_DISK").len(), 1, "premise: disk was indexed");
// The same file, opened as a buffer the fast path takes.
let mut text = String::from("package p;\n localparam IN_BUFFER = 1;\nendpackage\n");
text.push_str(&" ".repeat(200));
ws.set_document(crate::uri::path_to_uri(&path).expect("uri"), text);
ws.rebuild_index();
assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 0, "the buffer was not parsed");
assert_eq!(
ws.index().member("p", "ON_DISK").len(),
0,
"and the disk copy the buffer supersedes is not indexed in its place"
);
}
#[test]
fn a_buffer_edited_past_the_threshold_changes_mode_and_back() {
let mut ws = thresholded(200);
let file = uri("file:///rtl/grow.v");
ws.set_document(file.clone(), "module m;\nendmodule\n".into());
assert!(!ws.document(&file).expect("open").large);
ws.set_document(file.clone(), filler(1_000));
assert!(ws.document(&file).expect("open").large, "grew past the threshold");
ws.set_document(file.clone(), "module m;\nendmodule\n".into());
let doc = ws.document(&file).expect("open");
assert!(!doc.large, "and shrank back under it");
assert!(!doc.tokens.is_empty(), "with a full analysis again");
}
@@ -0,0 +1,224 @@
//! The lazy read and the folder-first order (perf5-p4 §P4b3, 2026-09-08):
//! each file's bytes read once, at its own step, with the open buffer's
//! neighbourhood indexed before the rest of the workspace is even walked.
use super::*;
/// The paths a scan reported, whichever way each file got into the index.
fn walked(ws: &mut Workspace) -> Vec<PathBuf> {
let mut seen: Vec<PathBuf> = Vec::new();
ws.rebuild_index_with(&mut |event| match event {
IndexEvent::Parsing { path, .. }
| IndexEvent::Cached { path, .. }
| IndexEvent::Analyzed { path, .. } => seen.push(path.to_path_buf()),
IndexEvent::Skipped { .. } => {}
});
seen
}
/// A workspace whose buffer sits two folders below a root, so the folder
/// the scope ladder raises it to is a real neighbourhood rather than the
/// whole tree — opentitan's `hw/ip/aes/dv/tb/tb.sv` in miniature.
fn neighbourhood_tree(name: &str) -> Tree {
let tree = Tree::new(name);
tree.package("ip/aes/dv/tb/tb.sv", "tb_pkg");
tree.package("ip/aes/rtl/aes.sv", "aes_pkg");
tree.package("ip/aes/rtl/aes_core.sv", "aes_core_pkg");
tree.package("ip/kmac/rtl/kmac.sv", "kmac_pkg");
tree.package("ip/uart/rtl/uart.sv", "uart_pkg");
tree.package("dv/common/util.sv", "util_pkg");
// The crowd the folder has to be a minority of — opentitan's `ip/aes`
// is 124 files of 3 976 (`crate::scan_order::worth_waiting`).
for n in 0..6 {
tree.package(&format!("zz/z{n:03}.sv"), &format!("z{n:03}_pkg"));
}
tree
}
#[test]
fn a_whole_scan_reads_each_files_bytes_exactly_once() {
// The claim the lazy read makes. Everything the scan wants from a
// file's text — the store's content hash, the parse, the `include`
// lines — comes out of one read, and the open buffer's text is not
// read from disk at all.
let tree = neighbourhood_tree("readonce");
let mut ws = Workspace::default();
ws.client.index_scope = IndexScope::Workspace;
ws.adopt_roots(vec![tree.path.clone()]);
let before = crate::scan_trace::source_reads();
assert_eq!(ws.rebuild_index().len(), 0, "premise: the walk is clean");
assert_eq!(
crate::scan_trace::source_reads() - before,
12,
"twelve files in the tree, twelve reads and not one more"
);
open(&mut ws, &tree, "ip/aes/dv/tb/tb.sv");
let before = crate::scan_trace::source_reads();
ws.rebuild_index();
assert_eq!(
crate::scan_trace::source_reads() - before,
11,
"the open buffer's own text is in memory and is never read off disk"
);
}
#[test]
fn the_open_buffers_folder_is_indexed_before_the_rest_and_the_index_cannot_tell() {
// The ordering §P4b2 asked for: the user's own file, then the folder
// the scope ladder raises it to — `ip/aes`, two levels above
// `ip/aes/dv` — and only then the workspace's alphabet.
let tree = neighbourhood_tree("folderfirst");
let mut ws = Workspace::default();
ws.client.index_scope = IndexScope::Workspace;
ws.adopt_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "ip/aes/dv/tb/tb.sv");
assert_eq!(
walked(&mut ws),
[
vec![
tree.path.join("ip/aes/dv/tb/tb.sv"),
tree.path.join("ip/aes/rtl/aes.sv"),
tree.path.join("ip/aes/rtl/aes_core.sv"),
tree.path.join("dv/common/util.sv"),
tree.path.join("ip/kmac/rtl/kmac.sv"),
tree.path.join("ip/uart/rtl/uart.sv"),
],
(0..6).map(|n| tree.path.join(format!("zz/z{n:03}.sv"))).collect(),
]
.concat(),
"the buffer, then its folder in path order, then the rest in path order"
);
// And the reason that is allowed to be true: the finished index does
// not depend on it. `IndexBuilder::finish` sorts by path, so a scan
// with nothing open builds the same thing.
let mut plain = Workspace::default();
plain.client.index_scope = IndexScope::Workspace;
plain.adopt_roots(vec![tree.path.clone()]);
plain.rebuild_index();
assert_eq!(plain.index().fingerprint(), ws.index().fingerprint(), "same index");
assert_eq!(everything(&plain), everything(&ws), "and the same tables around it");
}
#[test]
fn the_neighbourhood_is_what_a_held_request_waits_for() {
// The drain rule's own arithmetic, at the workspace level: `head`
// counts the buffer and its folder and nothing beyond.
let tree = neighbourhood_tree("headsegment");
let mut ws = Workspace::default();
ws.client.index_scope = IndexScope::Workspace;
ws.adopt_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "ip/aes/dv/tb/tb.sv");
let mut scan = ws.begin_scan(&mut |_| {}, false);
assert!(!scan.neighbourhood_indexed(), "nothing is indexed yet");
// Three files are the neighbourhood — the buffer and `ip/aes` — and
// the nine behind it are not.
for expected in [false, false, true, true, true, true, true, true, true, true, true, true] {
assert!(ws.scan_step(&mut scan, &mut |_| {}));
assert_eq!(scan.neighbourhood_indexed(), expected, "at {}", scan.at);
}
ws.finish_scan(scan);
// With nothing open there is no neighbourhood, and a held request is
// answered at the first interleave point exactly as it always was.
let mut bare = Workspace::default();
bare.client.index_scope = IndexScope::Workspace;
bare.adopt_roots(vec![tree.path.clone()]);
let scan = bare.begin_scan(&mut |_| {}, false);
assert!(scan.neighbourhood_indexed(), "no buffer, no wait");
bare.finish_scan(scan);
}
#[test]
fn a_file_opened_mid_scan_lengthens_the_neighbourhood_it_jumps_into() {
// `index_next` moves a file to the front of what is left. When it
// comes from beyond the head segment it pushes one of that segment's
// files a place later, and a held request must not be answered one
// file short of the folder it is waiting for.
let tree = neighbourhood_tree("headjump");
let mut ws = Workspace::default();
ws.client.index_scope = IndexScope::Workspace;
ws.adopt_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "ip/aes/dv/tb/tb.sv");
let mut scan = ws.begin_scan(&mut |_| {}, false);
assert!(ws.scan_step(&mut scan, &mut |_| {}), "the buffer's own file goes first");
open(&mut ws, &tree, "ip/uart/rtl/uart.sv");
ws.open_next(&mut scan, &mut |_| {});
// `uart.sv` is now the head of what is left, and at the shipped
// `scopeDepth: 2` its own folder raises to `ip` — which brings
// `ip/kmac` in with it. Four files of waiting, one behind the file
// already stepped, so the segment ends at five rather than three.
for expected in [false, false, false, true, true] {
assert!(ws.scan_step(&mut scan, &mut |_| {}));
assert_eq!(scan.neighbourhood_indexed(), expected, "at {}", scan.at);
}
ws.finish_scan(scan);
}
#[test]
fn a_file_that_leaves_the_disk_between_the_walk_and_its_step_leaves_the_index() {
// What `collect_sources` used to do by dropping an unreadable file
// before the work list existed: the file contributes nothing, is not
// counted among the cap's skips, and — for a whole scan — is taken
// *out* of the index rather than left in it stale.
let tree = Tree::new("vanished");
tree.package("rtl/stays.sv", "stays_pkg");
tree.package("rtl/goes.sv", "goes_pkg");
let mut ws = Workspace::default();
ws.client.index_scope = IndexScope::Workspace;
ws.adopt_roots(vec![tree.path.clone()]);
ws.rebuild_index();
assert!(!ws.index().units("goes_pkg").is_empty(), "premise: it was indexed once");
let mut scan = ws.begin_scan(&mut |_| {}, false);
assert_eq!(scan.total(), 2, "the walk found both");
fs::remove_file(tree.path.join("rtl/goes.sv")).expect("remove");
let mut said: Vec<String> = Vec::new();
while ws.scan_step(&mut scan, &mut |event| said.push(seen(&event))) {}
assert_eq!(scan.skipped(), 0, "an unreadable file is not one the size cap skipped");
assert_eq!(said.len(), 1, "and it reports no event of its own: {said:?}");
ws.finish_scan(scan);
assert!(ws.index().units("goes_pkg").is_empty(), "it left the scope, so it left the index");
assert!(!ws.index().units("stays_pkg").is_empty(), "and the file beside it did not");
}
#[test]
fn the_tables_a_scan_lands_are_the_ones_the_texts_would_have_built() {
// The lazy read's equivalence, table by table. The scan builds the
// completion tables from the words it took off each record and the
// include graph from the lines it scanned at each step; both must
// equal what `Candidates::build` and `IncludeGraph::build` produce
// from the same files' text.
let tree = tangled("lazytables");
let mut ws = Workspace::default();
ws.client.index_scope = IndexScope::Workspace;
ws.adopt_roots(vec![tree.path.clone()]);
ws.rebuild_index();
let texts: Vec<(PathBuf, String)> = ws
.index()
.files()
.iter()
.map(|path| (path.clone(), fs::read_to_string(path).expect("fixture")))
.collect();
let eagerly = Candidates::build(ws.index(), &texts, HashMap::new());
assert_eq!(eagerly.sizes(), ws.candidates().sizes(), "the same completion tables");
assert_eq!(eagerly.words(""), ws.candidates().words(""), "word for word");
let rebuilt = IncludeGraph::build(&texts, Vec::new());
assert_eq!(rebuilt.sizes(), ws.includes().sizes(), "the same include graph");
for (path, _) in &texts {
assert_eq!(
rebuilt.reachable(vec![path.clone()]),
ws.includes().reachable(vec![path.clone()]),
"the same hops from {}",
path.display()
);
}
}
+283
View File
@@ -0,0 +1,283 @@
//! The `Workspace` tests: one file per topic, every one driven through the
//! real `Workspace` against a scratch tree on disk.
//!
//! This file is the harness — `Tree`, a workspace root removed on drop —
//! followed by the helpers more than one file uses: settings as a client
//! would push them, a buffer opened from disk, and the ways a scan's
//! outcome is read back. The sibling files are the sections the one big
//! test module used to have, under the names they had; a helper used by
//! one section only stayed with it.
use std::fs;
use std::slice::from_ref;
use std::str::FromStr;
use super::*;
use crate::settings::IndexScope;
mod document;
mod filelist;
mod folder_scope;
mod folders;
mod incremental;
mod interleave;
mod large_file;
mod lazy_read;
mod open_buffers;
mod persistence;
mod settings;
mod size_cap;
mod views;
mod widen;
fn uri(s: &str) -> Uri {
Uri::from_str(s).expect("test uri parses")
}
/// A scratch workspace root. Removed on drop.
struct Tree {
path: PathBuf,
}
impl Tree {
fn new(name: &str) -> Tree {
let path =
std::env::temp_dir().join(format!("lucisv_server_scan_{}_{name}", std::process::id()));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("temp dir");
Tree { path }
}
fn write(&self, rel: &str, text: &str) {
let path = self.path.join(rel);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).expect("parent");
}
fs::write(&path, text).expect("write");
}
/// A package declaring one localparam, so the index can be asked
/// whether this file was scanned at all.
fn package(&self, rel: &str, name: &str) {
self.write(rel, &format!("package {name};\n localparam K = 1;\nendpackage\n"));
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
/// Open `rel` in `ws` as the buffer it is on disk.
fn open(ws: &mut Workspace, tree: &Tree, rel: &str) {
let path = tree.path.join(rel);
let text = fs::read_to_string(&path).expect("the fixture is on disk");
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(uri, text);
}
/// A buffer of exactly `bytes` bytes that is also real Verilog.
fn filler(bytes: usize) -> String {
let mut text = String::from("module m;\n");
while text.len() + 9 <= bytes {
text.push_str(" wire a;\n");
}
while text.len() < bytes {
text.push(' ');
}
text
}
/// A tree of three files that declare each other's names and include each
/// other, so a half-published index has something to get wrong.
fn tangled(tag: &str) -> Tree {
let tree = Tree::new(tag);
tree.write("defs.svh", "`define WIDE 32\n");
tree.write(
"a.sv",
"`include \"defs.svh\"\npackage a;\n localparam K = 1;\n \
typedef logic [`WIDE-1:0] word_t;\nendpackage\n",
);
tree.write(
"b.sv",
"`include \"defs.svh\"\nmodule b;\n import a::*;\n word_t w;\n \
localparam K2 = a::K;\nendmodule\n",
);
tree.write("c.sv", "module c;\n b inner ();\nendmodule\n");
tree
}
/// `settings` with the pre-2026-08-27 whole-workspace scope asked for —
/// the push-door twin of [`Workspace::open_whole_workspace`], needed
/// wherever a test pushes settings *after* opening its roots, since a push
/// replaces every field including the scope.
fn wide(settings: ClientSettings) -> ClientSettings {
ClientSettings { index_scope: IndexScope::Workspace, ..settings }
}
/// `lucisv.exclude` as a client would push it.
fn excluding(patterns: &[&str]) -> ClientSettings {
ClientSettings {
exclude: patterns.iter().map(|p| p.to_string()).collect(),
index_scope_depth: 0,
..Default::default()
}
}
/// The folder rung at `scopeDepth: 0` — the open file's own folder and
/// nothing above it.
///
/// Said out loud since 2026-08-28, when the shipped default became
/// [`crate::settings::DEFAULT_SCOPE_DEPTH`]: a test about *this* rung
/// names the depth it is about rather than riding whatever the default is
/// this month. The behaviour it selects is unchanged.
fn own_folder_only(ws: &mut Workspace) {
ws.set_client_settings(ClientSettings { index_scope_depth: 0, ..Default::default() });
}
/// `lucisv.filelist` as a client would push it.
fn using_filelist(path: &str) -> ClientSettings {
ClientSettings { filelist: Some(path.to_string()), ..Default::default() }
}
/// A `ClientSettings` with the size cap set to `bytes`.
fn capping(bytes: u64) -> ClientSettings {
ClientSettings { max_file_size: bytes, ..Default::default() }
}
/// A file of `bytes` bytes that would declare `name` if anything read it.
/// Padded with a trailing comment, so what makes it big is not what makes
/// it a package.
fn fat_package(tree: &Tree, rel: &str, name: &str, bytes: usize) {
let head = format!("package {name};\n localparam K = 1;\nendpackage\n// ");
let mut text = String::with_capacity(bytes + head.len());
text.push_str(&head);
while text.len() < bytes {
text.push('x');
}
text.push('\n');
tree.write(rel, &text);
}
/// A client that keeps its index cache in `dir`.
fn caching(dir: &Path) -> ClientSettings {
ClientSettings {
index_cache_path: Some(dir.to_string_lossy().into_owned()),
index_scope_depth: 0,
..Default::default()
}
}
/// What the index holds, as the names of the packages it found.
fn indexed(ws: &Workspace, names: &[&str]) -> Vec<String> {
names.iter().filter(|n| ws.index().member(n, "K").len() == 1).map(|n| n.to_string()).collect()
}
/// Everything a scan produces, rendered as one comparable value: the
/// index's own witness, the completion tables and the include graph.
///
/// The index's fingerprint alone would not do — this round publishes all
/// three tables together, so all three have to be shown to come out the
/// same however many publishes happened on the way.
fn everything(ws: &Workspace) -> String {
let mut out = ws.index().fingerprint();
out.push_str(&format!("words {:?}\n", ws.candidates().words("")));
out.push_str(&format!(
"units {:?}\n",
ws.candidates().units("").iter().map(|c| &c.name).collect::<Vec<_>>()
));
out.push_str(&format!(
"macros {:?}\n",
ws.candidates().macros("").iter().map(|m| &m.name).collect::<Vec<_>>()
));
let mut reachable: Vec<String> = ws
.index()
.files()
.iter()
.map(|path| {
let mut hops: Vec<String> = ws
.includes()
.reachable(vec![path.clone()])
.iter()
.filter_map(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
.collect();
hops.sort();
format!("reaches {} {hops:?}", path.display())
})
.collect();
reachable.sort();
out.push_str(&reachable.join("\n"));
out
}
/// One [`IndexEvent`] as the word and the numbers a caller would report.
fn seen(event: &IndexEvent) -> String {
match event {
IndexEvent::Parsing { done, total, path } => {
format!("indexing {done}/{total} {}", path.display())
}
IndexEvent::Cached { done, total, path } => {
format!("cached {done}/{total} {}", path.display())
}
IndexEvent::Analyzed { done, total, path } => {
format!("analyzed {done}/{total} {}", path.display())
}
IndexEvent::Skipped { path, size, cap } => {
format!("skipped {} {size} {cap}", path.display())
}
}
}
/// What one whole scan did, file by file: what it parsed, what it took
/// from the cache instead, and what came from an open buffer's own
/// analysis. The three together are the work list.
#[derive(Debug, Default, PartialEq, Eq)]
struct Scan {
parsed: Vec<String>,
cached: Vec<String>,
analyzed: Vec<String>,
}
/// Scan `roots` (or rescan what is already open, with `None`) and record
/// which files were parsed and which came out of the cache.
fn scan(ws: &mut Workspace, roots: Option<Vec<PathBuf>>) -> Scan {
let mut out = Scan::default();
{
let mut see = |event: IndexEvent| match event {
IndexEvent::Parsing { path, .. } => out.parsed.push(file_name(path)),
IndexEvent::Cached { path, .. } => out.cached.push(file_name(path)),
IndexEvent::Analyzed { path, .. } => out.analyzed.push(file_name(path)),
IndexEvent::Skipped { .. } => {}
};
match roots {
Some(roots) => ws.open_whole_workspace_with(roots, &mut see),
None => ws.rebuild_index_with(&mut see),
};
}
out
}
fn file_name(path: &Path) -> String {
path.file_name().expect("a file").to_string_lossy().into_owned()
}
/// Every source file under `dir`, for the corpus sweep above.
fn walk_sources(dir: &Path) -> Vec<PathBuf> {
let mut out = Vec::new();
let mut stack = vec![dir.to_path_buf()];
while let Some(next) = stack.pop() {
let Ok(entries) = fs::read_dir(&next) 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" | "v" | "svh"))
{
out.push(path);
}
}
}
out.sort();
out
}
@@ -0,0 +1,377 @@
//! An open buffer's own analysis (index-scope, 2026-08-28) beats disk in
//! the index and is what the index reuses — and the QA attacks on that:
//! staleness across a close, and crossing the large-file threshold.
use vlog_parser::tokenize;
use super::*;
#[test]
fn an_open_buffer_overrides_disk_in_the_index() {
let dir = std::env::temp_dir().join(format!("lucisv_server_state_{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).expect("temp dir");
let path = dir.join("pkg.sv");
fs::write(&path, "package p;\n localparam ON_DISK = 1;\nendpackage\n").expect("write");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
assert_eq!(ws.index().member("p", "ON_DISK").len(), 1);
assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 0);
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(uri, "package p;\n localparam IN_BUFFER = 1;\nendpackage\n".into());
ws.rebuild_index();
assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 1, "buffer must win");
assert_eq!(ws.index().member("p", "ON_DISK").len(), 0, "disk must lose");
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn an_open_buffers_analysis_indexes_to_exactly_what_its_bytes_on_disk_would() {
// The equivalence the reuse stands on. A rescan takes an open buffer's
// facts and its words off the analysis that buffer already holds; the
// claim is that the index and the completion tables are then byte for
// byte the ones a *parse of those bytes* builds. The buffer carries
// unsaved edits on purpose — bytes that are nowhere on disk, which is
// exactly the case the content-keyed cache cannot help with and the
// one the owner's report was about.
let tree = Tree::new("openfacts");
tree.package("rtl/a.sv", "a_pkg");
tree.package("rtl/other.sv", "other_pkg");
tree.write("rtl/top.sv", "module top;\n a_sub u ();\nendmodule\n");
let edited = "`define TAG 1\nimport a_pkg::*;\npackage edited_pkg;\n \
localparam K = 1;\n class c extends a_base; int x; endclass\n\
endpackage\nmodule top;\n logic [K-1:0] w;\n \
a_sub u (.clk(w));\n a_sub v (.clk(w));\nendmodule\n";
let path = tree.path.join("rtl/top.sv");
let uri = crate::uri::path_to_uri(&path).expect("uri");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
ws.set_document(uri, edited.to_string());
let seen = scan(&mut ws, None);
assert_eq!(
seen.analyzed,
["top.sv"],
"the open buffer went in from its own analysis: {seen:?}"
);
assert_eq!(seen.parsed, ["a.sv", "other.sv"], "and nothing else changed route: {seen:?}");
let from_buffer = ws.index().fingerprint();
let words_from_buffer = ws.candidates().words("").to_vec();
let units_from_buffer: Vec<String> =
ws.candidates().units("").iter().map(|c| c.name.clone()).collect();
// The same bytes on disk, nothing open: the parse route, end to end.
tree.write("rtl/top.sv", edited);
let mut plain = Workspace::default();
plain.set_client_settings(wide(ClientSettings::default()));
let mut route = Scan::default();
plain.open_roots_with(vec![tree.path.clone()], &mut |event| match event {
IndexEvent::Parsing { path, .. } => route.parsed.push(file_name(path)),
IndexEvent::Cached { path, .. } => route.cached.push(file_name(path)),
IndexEvent::Analyzed { path, .. } => route.analyzed.push(file_name(path)),
IndexEvent::Skipped { .. } => {}
});
assert_eq!(route.parsed, ["a.sv", "other.sv", "top.sv"], "premise: it really parsed");
assert_eq!(from_buffer, plain.index().fingerprint(), "the same index, byte for byte");
assert_eq!(words_from_buffer, plain.candidates().words(""), "and the same words");
let units_plain: Vec<String> =
plain.candidates().units("").iter().map(|c| c.name.clone()).collect();
assert_eq!(units_from_buffer, units_plain, "and the same index-derived candidates");
// And through the incremental door as well: `update_one` takes the same
// shortcut, and `update_one_checked` holds it to a whole rebuild.
assert!(ws.update_one_checked(&path), "the buffer's file is one the index holds");
assert_eq!(ws.index().fingerprint(), from_buffer, "still the same index after an update");
}
#[test]
fn an_open_buffer_offers_the_facts_and_words_its_text_would_over_the_real_corpus() {
// `Document::new` and `FileFacts::of` each lex, parse and analyze one
// file, and the reuse is only sound while those two agree. Nothing
// enforces it at compile time — they are separate call sites — so it is
// swept over real files, in the encoded record form, which is every
// field the index and the persistent store ever read.
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let empty = WorkspaceIndex::default();
let mut checked = 0usize;
for path in walk_sources(&corpus).into_iter().step_by(3) {
let Ok(text) = fs::read_to_string(&path) else { continue };
let doc = Document::new(Some(path.clone()), text.clone(), &empty);
assert!(!doc.large, "premise: a full analysis, not the fast path");
assert_eq!(
doc.facts(path.clone()).encode(),
FileFacts::of(path.clone(), &text).encode(),
"the records differ for {}",
path.display()
);
let mut from_buffer = doc.words();
let mut from_text =
crate::candidates::words_of_tokens(&tokenize(&text).unwrap_or_default());
from_buffer.sort();
from_text.sort();
assert_eq!(from_buffer, from_text, "the words differ for {}", path.display());
checked += 1;
}
assert!(checked > 100, "premise: the corpus was really swept ({checked} files)");
eprintln!("open-buffer equivalence: {checked} corpus files, facts and words identical");
}
#[test]
fn qa_attack_crafted_non_corpus_shapes_drift_check() {
// Run on a dedicated thread with a generous stack: `cargo test`'s
// default per-test-thread stack (2 MiB) is smaller than a normal
// process's main-thread stack, and a couple of the crafted shapes
// below are deep enough to overflow the smaller one even though
// `FileFacts::of` alone — no `Document`, no reuse — overflows it
// identically on pristine, unmodified `master`. That is a real,
// pre-existing recursion-depth ceiling in the parser/analyzer,
// independent of this round; it is filed separately (QA log,
// 2026-08-28) rather than blocking this round, since both routes
// being compared here fail *identically*, which is the opposite of
// the drift this test hunts for. Run at 64 MiB so the drift check
// exercises real depth without tripping that unrelated ceiling.
std::thread::Builder::new()
.stack_size(64 * 1024 * 1024)
.spawn(qa_attack_crafted_non_corpus_shapes_drift_check_body)
.expect("spawn")
.join()
.expect("no panic");
}
fn qa_attack_crafted_non_corpus_shapes_drift_check_body() {
let empty = WorkspaceIndex::default();
let cases: Vec<(&str, String)> = vec![
("bom_plain", "\u{feff}module m;\nendmodule\n".to_string()),
("crlf", "module m;\r\n logic w;\r\nendmodule\r\n".to_string()),
("bom_crlf", "\u{feff}module m;\r\n logic w;\r\nendmodule\r\n".to_string()),
("unterminated_block_comment", "module m; /* never closed\nendmodule\n".to_string()),
("unterminated_attribute", "(* foo module m; endmodule\n".to_string()),
(
"unterminated_macro_call",
"`define M(a,b) a+b\nmodule m; logic w = `M(1,2\nendmodule\n".to_string(),
),
("unterminated_string", "module m; string s = \"never closed\nendmodule\n".to_string()),
("unexpected_char", "module m; logic w = \u{1}; endmodule\n".to_string()),
("deeply_nested_begin_end", {
let mut s = String::from("module m;\ninitial begin\n");
for _ in 0..500 {
s.push_str("begin\n");
}
for _ in 0..500 {
s.push_str("end\n");
}
s.push_str("end\nendmodule\n");
s
}),
("deeply_nested_parens", {
let mut s = String::from("module m;\n localparam int W = ");
for _ in 0..2000 {
s.push('(');
}
s.push('1');
for _ in 0..2000 {
s.push(')');
}
s.push_str(";\nendmodule\n");
s
}),
("macro_heavy", {
let mut s = String::new();
for i in 0..500 {
s.push_str(&format!("`define M{i} {i}\n"));
}
s.push_str("module m;\nendmodule\n");
s
}),
(
"include_bearing",
"`include \"foo.svh\"\n`include \"bar/baz.vh\"\nmodule m;\nendmodule\n".to_string(),
),
(
"parse_error_recovery",
"module broken (input logic clk;\n wire w = ;\nendmodule\nmodule after; endmodule\n"
.to_string(),
),
("mixed_line_endings", "module m;\n logic a;\r\n logic b;\nendmodule\n".to_string()),
("null_byte", "module m;\n logic a; // \0 embedded\nendmodule\n".to_string()),
("tab_and_form_feed", "module m;\n\t\u{c}logic a;\nendmodule\n".to_string()),
];
let total = cases.len();
let mut failures = Vec::new();
for (name, text) in cases {
let path = PathBuf::from(format!("/w/{name}.sv"));
let doc = Document::new(Some(path.clone()), text.clone(), &empty);
let from_buffer = doc.facts(path.clone()).encode();
let from_text = FileFacts::of(path.clone(), &text).encode();
if from_buffer != from_text {
failures
.push(format!("FACTS DRIFT in {name}: buffer={from_buffer:?} text={from_text:?}"));
}
let mut wb = doc.words();
let mut wt = crate::candidates::words_of_tokens(&tokenize(&text).unwrap_or_default());
wb.sort();
wt.sort();
if wb != wt {
failures.push(format!("WORDS DRIFT in {name}: buffer={wb:?} text={wt:?}"));
}
}
assert!(failures.is_empty(), "drift found:\n{}", failures.join("\n"));
eprintln!("qa attack: {total} crafted non-corpus shapes, no drift found");
}
#[test]
fn a_buffer_on_the_large_file_fast_path_offers_no_analysis_to_reuse() {
// The one buffer whose held analysis is not an analysis of its text —
// it is the analysis of the empty file. Such a buffer contributes
// nothing to the index at all, which is what keeps the reuse from ever
// meeting it: it is absent from the work list, so it is absent from
// every list a rescan reports.
let tree = Tree::new("openfactslarge");
tree.package("rtl/a.sv", "a_pkg");
let big = format!(
"package big_pkg;\n localparam K = 1;\n{}endpackage\n",
" // filler\n".repeat(200)
);
tree.write("rtl/big.sv", &big);
let mut ws = Workspace::default();
ws.set_client_settings(wide(ClientSettings {
large_file_threshold: 100,
..Default::default()
}));
ws.open_roots_with(vec![tree.path.clone()], &mut |_| {});
let uri = crate::uri::path_to_uri(&tree.path.join("rtl/big.sv")).expect("uri");
ws.set_document(uri.clone(), big);
assert!(ws.document(&uri).expect("open").large, "premise: the fast path");
let seen = scan(&mut ws, None);
assert!(seen.analyzed.is_empty(), "nothing came from an analysis: {seen:?}");
assert_eq!(seen.parsed, ["a.sv"], "and the big buffer is on no list at all: {seen:?}");
assert_eq!(indexed(&ws, &["a_pkg", "big_pkg"]), ["a_pkg"], "nor in the index");
}
#[test]
fn qa_unsaved_edits_win_then_close_reverts_to_disk_on_the_next_rescan() {
// Charter attack 2 (staleness). An open buffer's *unsaved* edits must
// win a rescan (the whole reason the reuse is sound even though the
// content-keyed cache has nothing to key unsaved bytes by), and
// closing the buffer without saving must let the next rescan see disk
// again — nothing about the buffer's now-gone analysis may linger.
let tree = Tree::new("qastaleness");
tree.write("rtl/p.sv", "package p;\n localparam ON_DISK = 1;\nendpackage\n");
let path = tree.path.join("rtl/p.sv");
let uri = crate::uri::path_to_uri(&path).expect("uri");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(ws.index().member("p", "ON_DISK").len(), 1, "premise: disk's member");
// Open the buffer and edit it — never saved, so disk still says
// `ON_DISK` — then rescan.
ws.set_document(uri.clone(), "package p;\n localparam IN_BUFFER = 1;\nendpackage\n".into());
let seen = scan(&mut ws, None);
assert_eq!(seen.analyzed, ["p.sv"], "the live buffer's own analysis went in: {seen:?}");
assert!(seen.parsed.is_empty() && seen.cached.is_empty(), "{seen:?}");
assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 1, "the live edit is indexed");
assert_eq!(ws.index().member("p", "ON_DISK").len(), 0, "disk's stale member is gone");
// Close without saving. Disk still says `ON_DISK`; the buffer's
// analysis of `IN_BUFFER` no longer exists anywhere to be reused.
ws.close_document(&uri);
let seen = scan(&mut ws, None);
assert_eq!(seen.parsed, ["p.sv"], "reparsed from disk, not reused: {seen:?}");
assert!(seen.analyzed.is_empty(), "no buffer left to analyze from: {seen:?}");
assert_eq!(ws.index().member("p", "ON_DISK").len(), 1, "back to disk's member");
assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 0, "the unsaved edit is gone");
}
#[test]
fn qa_a_buffer_edited_past_the_threshold_is_excluded_from_reuse_mid_session() {
// Charter attack 3 (large-file path), the direction the dev's own
// test does not cover: small **on disk**, edited **huge in the
// buffer** without saving. `doc.large` is re-decided on every
// `set_document`, so the very next rescan must drop the buffer from
// the analyzed-reuse route (and from the index) the moment the edit
// crosses the threshold — not one rescan later.
let tree = Tree::new("qathreshgrow");
tree.write("rtl/p.sv", "package p;\n localparam SMALL = 1;\nendpackage\n");
let path = tree.path.join("rtl/p.sv");
let uri = crate::uri::path_to_uri(&path).expect("uri");
let mut ws = Workspace::default();
ws.set_client_settings(wide(ClientSettings {
large_file_threshold: 200,
..Default::default()
}));
ws.open_roots_with(vec![tree.path.clone()], &mut |_| {});
ws.set_document(uri.clone(), "package p;\n localparam SMALL = 1;\nendpackage\n".into());
assert!(!ws.document(&uri).expect("open").large, "premise: a real analysis");
let seen = scan(&mut ws, None);
assert_eq!(seen.analyzed, ["p.sv"], "small buffer reused: {seen:?}");
assert_eq!(ws.index().member("p", "SMALL").len(), 1);
// Edited past the threshold, never saved.
ws.set_document(uri.clone(), filler(1_000));
assert!(ws.document(&uri).expect("open").large, "now on the fast path");
let seen = scan(&mut ws, None);
assert!(seen.analyzed.is_empty(), "the now-huge buffer offers no analysis: {seen:?}");
assert!(seen.parsed.is_empty(), "and disk is not read in its place either: {seen:?}");
assert_eq!(ws.index().member("p", "SMALL").len(), 0, "contributes nothing at all");
// And back under the threshold: a real analysis again, reused again.
ws.set_document(uri.clone(), "package p;\n localparam SMALL = 1;\nendpackage\n".into());
assert!(!ws.document(&uri).expect("open").large, "shrank back");
let seen = scan(&mut ws, None);
assert_eq!(seen.analyzed, ["p.sv"], "reused again: {seen:?}");
assert_eq!(ws.index().member("p", "SMALL").len(), 1);
}
#[test]
fn qa_a_buffer_huge_on_disk_shrunk_live_becomes_a_real_analysis_to_reuse() {
// The other direction of charter attack 3: **huge on disk** (over the
// fast-path threshold if it were read fresh — moot here, since a
// buffer's `large` flag is decided from its own live text, never
// disk), edited down **small in the buffer**. Included for the
// opposite-direction symmetry the brief asks for; the on-disk size is
// irrelevant to `doc.large` by construction (`is_large` reads
// `text.len()`), so this is really the same claim from the other
// starting point.
let tree = Tree::new("qathreshshrink");
let huge_on_disk = filler(1_000);
tree.write("rtl/p.sv", &huge_on_disk);
let path = tree.path.join("rtl/p.sv");
let uri = crate::uri::path_to_uri(&path).expect("uri");
let mut ws = Workspace::default();
ws.set_client_settings(wide(ClientSettings {
large_file_threshold: 200,
..Default::default()
}));
ws.open_roots_with(vec![tree.path.clone()], &mut |_| {});
// Disk alone: `filler` is real Verilog (`module m; wire a; ...`), well
// under no cap, so it is walked and parsed whole — the large-file
// threshold applies to *buffers*, not to the walk.
let seen = scan(&mut ws, None);
assert_eq!(seen.parsed, ["p.sv"], "disk copy parsed in full: {seen:?}");
// Opened as a buffer with that same huge text: the fast path, same as
// any buffer over the threshold.
ws.set_document(uri.clone(), huge_on_disk);
assert!(ws.document(&uri).expect("open").large, "premise: fast path from the live text");
// Edited down to something small, never saved.
ws.set_document(uri.clone(), "package p;\n localparam SHRUNK = 1;\nendpackage\n".into());
assert!(!ws.document(&uri).expect("open").large, "back to a real analysis");
let seen = scan(&mut ws, None);
assert_eq!(seen.analyzed, ["p.sv"], "the shrunk buffer's own analysis is reused: {seen:?}");
assert_eq!(ws.index().member("p", "SHRUNK").len(), 1);
}
@@ -0,0 +1,542 @@
//! The persistent index cache (docs/features/index-persistence): what a
//! warm scan parses, what the key is, where the store lives, and when it
//! is read, written or left exactly as it was found.
use super::*;
/// A workspace that keeps its cache in `store` and indexes every root.
fn cached_workspace(store: &Path) -> Workspace {
let mut ws = Workspace::default();
ws.set_client_settings(wide(caching(store)));
ws
}
#[test]
fn a_second_session_over_the_same_store_parses_nothing_it_parsed_before() {
let tree = Tree::new("cachewarm");
tree.package("a.sv", "a_pkg");
tree.package("b.sv", "b_pkg");
let store = Tree::new("cachewarm_store");
let mut cold = cached_workspace(&store.path);
let first = scan(&mut cold, Some(vec![tree.path.clone()]));
assert_eq!(first.parsed, ["a.sv", "b.sv"], "a cold scan parses everything");
assert!(first.cached.is_empty(), "{first:?}");
let fingerprint = cold.index().fingerprint();
// A whole new server over the same tree and the same store — which is
// what reopening the editor is.
let mut warm = cached_workspace(&store.path);
let second = scan(&mut warm, Some(vec![tree.path.clone()]));
assert!(second.parsed.is_empty(), "a warm scan parses nothing: {second:?}");
assert_eq!(second.cached, ["a.sv", "b.sv"]);
assert_eq!(
warm.index().fingerprint(),
fingerprint,
"and the index it built is the index the parses built"
);
}
#[test]
fn a_half_warm_scan_parses_exactly_what_the_store_cannot_answer_for() {
// The resume case, which is the whole feature: a store holding some
// of the workspace — because the last session was killed halfway, or
// because files have changed since — costs exactly the files it does
// not answer for, and nothing else.
let tree = Tree::new("cachehalf");
tree.package("a.sv", "a_pkg");
tree.package("b.sv", "b_pkg");
let store = Tree::new("cachehalf_store");
let mut first = cached_workspace(&store.path);
scan(&mut first, Some(vec![tree.path.clone()]));
tree.package("b.sv", "b_renamed_pkg"); // changed since
tree.package("c.sv", "c_pkg"); // never seen
let mut second = cached_workspace(&store.path);
let half = scan(&mut second, Some(vec![tree.path.clone()]));
assert_eq!(half.cached, ["a.sv"], "only the untouched file: {half:?}");
assert_eq!(half.parsed, ["b.sv", "c.sv"]);
let mut fresh = Workspace::default();
fresh.set_client_settings(wide(ClientSettings::default()));
fresh.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(
second.index().fingerprint(),
fresh.index().fingerprint(),
"a half-cached index is the index a cacheless scan would have built"
);
}
#[test]
fn the_key_is_the_content_and_only_the_content() {
// Both directions of "no timestamp is trusted": a file rewritten with
// the same bytes still hits (its modification time moved and nothing
// else did), and a file rewritten with *different* bytes of the same
// length misses. A cache keyed on size and mtime would get both of
// these exactly the wrong way round.
let tree = Tree::new("cachekey");
tree.write("a.sv", "package a_pkg;\n localparam K = 1;\nendpackage\n");
let store = Tree::new("cachekey_store");
let mut ws = cached_workspace(&store.path);
scan(&mut ws, Some(vec![tree.path.clone()]));
tree.write("a.sv", "package a_pkg;\n localparam K = 1;\nendpackage\n");
let touched = scan(&mut ws, None);
assert_eq!(touched.cached, ["a.sv"], "the same bytes are the same file: {touched:?}");
tree.write("a.sv", "package a_pkg;\n localparam K = 2;\nendpackage\n");
let changed = scan(&mut ws, None);
assert_eq!(changed.parsed, ["a.sv"], "one byte of difference is a miss: {changed:?}");
}
#[test]
fn the_cache_never_puts_back_a_file_the_scan_no_longer_visits() {
// A record is not a file. The scope ladder decides what is walked;
// the cache only ever answers *for* something already on the work
// list, so a session whose scope has narrowed has an index that
// narrowed with it, records or no records.
let tree = Tree::new("cachescope");
tree.package("rtl/a.sv", "a_pkg");
tree.package("tb/b.sv", "b_pkg");
let store = Tree::new("cachescope_store");
let mut wide_session = cached_workspace(&store.path);
scan(&mut wide_session, Some(vec![tree.path.clone()]));
assert_eq!(indexed(&wide_session, &["a_pkg", "b_pkg"]), ["a_pkg", "b_pkg"]);
// The next session is folder-scoped and only ever opens a file in
// `rtl/`, so `tb/` is not walked at all.
let mut narrow = Workspace::default();
narrow.set_client_settings(caching(&store.path));
narrow.open_roots_with(vec![tree.path.clone()], &mut |_| {});
open(&mut narrow, &tree, "rtl/a.sv");
let narrowed = scan(&mut narrow, None);
// `rtl/a.sv` is this session's open buffer, so it goes in from the
// analysis that buffer already holds rather than from the store —
// beside this test's point, and named so the point stays legible:
// `tb/b.sv` appears on no list at all.
assert_eq!(narrowed.analyzed, ["a.sv"], "{narrowed:?}");
assert!(narrowed.parsed.is_empty() && narrowed.cached.is_empty(), "{narrowed:?}");
assert_eq!(
indexed(&narrow, &["a_pkg", "b_pkg"]),
["a_pkg"],
"the record for tb/b.sv exists and is still not an indexed file"
);
}
/// The store's bytes and its modification time — "not touched" as
/// something a test can see rather than infer.
fn store_stamp(store: &Path) -> (Vec<u8>, std::time::SystemTime) {
let path = store.join("index-cache");
let bytes = fs::read(&path).expect("read store");
let stamp = fs::metadata(&path).expect("meta").modified().expect("mtime");
(bytes, stamp)
}
#[test]
fn a_warm_rescan_that_appended_nothing_leaves_the_store_exactly_as_it_found_it() {
// §P4b (a) through the workspace: every file hits the store, so the
// session appends nothing, so the compaction at the end of the scan
// would rewrite the file it read into itself. It does not run, and
// the store on disk is not touched — not its bytes, not its mtime.
let tree = Tree::new("compactskip");
tree.package("a.sv", "a_pkg");
tree.package("b.sv", "b_pkg");
let store = Tree::new("compactskip_store");
let mut cold = cached_workspace(&store.path);
scan(&mut cold, Some(vec![tree.path.clone()]));
let before = store_stamp(&store.path);
let mut warm = cached_workspace(&store.path);
let second = scan(&mut warm, Some(vec![tree.path.clone()]));
assert_eq!(second.cached, ["a.sv", "b.sv"], "premise: a scan that appends nothing");
assert_eq!(store_stamp(&store.path), before, "the store was not rewritten");
// A third session still reads it, and a file that *did* change still
// costs the rewrite that folds its new record in.
tree.package("b.sv", "b_renamed_pkg");
let mut third = cached_workspace(&store.path);
let changed = scan(&mut third, Some(vec![tree.path.clone()]));
assert_eq!(changed.parsed, ["b.sv"], "{changed:?}");
let after = fs::read_to_string(store.path.join("index-cache")).expect("a store");
assert!(after.contains("b_renamed_pkg"), "the changed file's record landed");
assert_eq!(after.lines().count(), 3, "and the store is one line per path: {after}");
}
#[test]
fn a_scan_with_no_files_neither_reads_the_store_nor_rewrites_it() {
// §P4b (b1). `Server::started` builds the index at the **default**
// settings, before `workspace/configuration` can even be asked — and
// the folder scope is derived from the directories a buffer has been
// opened from, of which there are none, so that scan's work list is
// empty. Warm it still opened a 44 MiB store and rewrote it
// byte-identically: 184 ms of a 1.33 s start, for a scan that indexes
// nothing (`docs/features/perf5-p4/README.md`).
let tree = Tree::new("emptyscan");
tree.package("rtl/a.sv", "a_pkg");
tree.package("rtl/b.sv", "b_pkg");
let store = Tree::new("emptyscan_store");
let mut filling = cached_workspace(&store.path);
scan(&mut filling, Some(vec![tree.path.clone()]));
let before = store_stamp(&store.path);
// The startup shape: the folder scope, no buffer open.
let mut empty = Workspace::default();
empty.set_client_settings(caching(&store.path));
empty.adopt_roots(vec![tree.path.clone()]);
let nothing = scan(&mut empty, None);
assert_eq!(nothing, Scan::default(), "premise: this scan indexes no file");
assert_eq!(store_stamp(&store.path), before, "so the store is neither read nor written");
// And the widen the first `didOpen` triggers still hits every record
// the store holds — the open was deferred to the first file that
// wants it, not dropped.
let opened = tree.path.join("rtl/a.sv");
let uri = crate::uri::path_to_uri(&opened).expect("uri");
empty.set_document(uri, fs::read_to_string(&opened).expect("read"));
let added: Vec<PathBuf> = empty.scope_dirs();
assert_eq!(added, vec![tree.path.join("rtl")], "premise: the open widened the scope");
let mut widened = Scan::default();
empty.widen_index_with(&added, &mut |event| match event {
IndexEvent::Parsing { path, .. } => widened.parsed.push(file_name(path)),
IndexEvent::Cached { path, .. } => widened.cached.push(file_name(path)),
IndexEvent::Analyzed { path, .. } => widened.analyzed.push(file_name(path)),
IndexEvent::Skipped { .. } => {}
});
assert_eq!(widened.analyzed, ["a.sv"], "the open buffer indexes itself: {widened:?}");
assert_eq!(widened.cached, ["b.sv"], "the widen reads the store the scan left: {widened:?}");
assert!(widened.parsed.is_empty(), "not one file reparsed: {widened:?}");
}
#[test]
fn a_cold_session_that_indexes_nothing_creates_no_store_at_all() {
// The same rule the other way up: with no store yet and no file to
// index, nothing is created — no directory, no `.gitignore`, no
// header-only store — and the session that *does* index a file makes
// all three.
let tree = Tree::new("emptycold");
tree.package("rtl/a.sv", "a_pkg");
let store = Tree::new("emptycold_store");
let dir = store.path.join("inner");
let mut empty = Workspace::default();
empty.set_client_settings(caching(&dir));
empty.adopt_roots(vec![tree.path.clone()]);
assert_eq!(scan(&mut empty, None), Scan::default(), "premise");
assert!(!dir.exists(), "a scan with no files creates no cache directory");
let mut indexing = cached_workspace(&dir);
scan(&mut indexing, Some(vec![tree.path.clone()]));
assert!(dir.join("index-cache").exists(), "and a scan with files still writes one");
}
#[test]
fn persistence_off_reads_nothing_and_writes_nothing() {
let tree = Tree::new("cacheoff");
tree.package("a.sv", "a_pkg");
let store = Tree::new("cacheoff_store");
// Nothing is written while it is off…
let mut off = Workspace::default();
off.set_client_settings(wide(ClientSettings { index_persist: false, ..caching(&store.path) }));
scan(&mut off, Some(vec![tree.path.clone()]));
assert!(!store.path.join("index-cache").exists(), "persist: false must not write");
// …and a store that already exists is not read when it goes off.
let mut on = cached_workspace(&store.path);
scan(&mut on, Some(vec![tree.path.clone()]));
assert!(store.path.join("index-cache").exists(), "premise: a store to ignore");
let mut ignoring = Workspace::default();
ignoring
.set_client_settings(wide(ClientSettings { index_persist: false, ..caching(&store.path) }));
let scanned = scan(&mut ignoring, Some(vec![tree.path.clone()]));
assert_eq!(scanned.parsed, ["a.sv"], "persist: false must not read: {scanned:?}");
}
#[test]
fn turning_persistence_off_mid_session_stops_the_write_through_at_once() {
// A save takes the incremental path, which writes its record through
// without any rescan — so `persist: false` has to reach it the moment
// it lands, not at the next scan.
let tree = Tree::new("cachemidsession");
tree.package("a.sv", "a_pkg");
let store = Tree::new("cachemidsession_store");
let mut ws = cached_workspace(&store.path);
scan(&mut ws, Some(vec![tree.path.clone()]));
tree.package("a.sv", "a_pkg_v2");
assert!(ws.update_one(&tree.path.join("a.sv")), "premise: the fast path took it");
let after_save = fs::read_to_string(store.path.join("index-cache")).expect("a store");
assert!(after_save.contains("a_pkg_v2"), "a save writes its record through");
ws.set_client_settings(wide(ClientSettings { index_persist: false, ..caching(&store.path) }));
tree.package("a.sv", "a_pkg_v3");
assert!(ws.update_one(&tree.path.join("a.sv")));
let after_off = fs::read_to_string(store.path.join("index-cache")).expect("a store");
assert_eq!(after_off, after_save, "nothing more is written once it is off");
}
/// QA (2026-08-27), the no-mtime deviation's save-path half: the
/// write-through on `update_one` must key its record on the *buffer's*
/// bytes, never on what happens to be on disk — that is the argument the
/// README gives for why a stored `(size, mtime)` would have been unsound
/// (a save's text can come from an unsaved buffer). Constructed
/// directly: open a buffer whose text disagrees with the file on disk,
/// let the incremental path write its record through, and check the
/// store's record is keyed by the *buffer's* hash and holds the
/// *buffer's* facts — and that disk's actual bytes, hashed, do not
/// match what got written.
#[test]
fn a_saved_buffers_record_is_keyed_and_filled_from_the_buffer_not_stale_disk() {
let tree = Tree::new("cachebuffer");
tree.package("a.sv", "a_pkg_on_disk");
let store = Tree::new("cachebuffer_store");
let mut ws = cached_workspace(&store.path);
scan(&mut ws, Some(vec![tree.path.clone()]));
// The buffer disagrees with disk — as it does the moment a user
// types, before the editor's next `didSave` reaches disk at all.
let path = tree.path.join("a.sv");
let buffer_text = "package a_pkg_in_buffer;\n localparam K = 1;\nendpackage\n";
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(uri, buffer_text.to_string());
assert!(ws.update_one(&path), "premise: the fast path took it");
// The append log still holds the earlier, disk-keyed line too — it is
// not rewritten until the next whole-scan compaction — so the write
// itself is checked by what it added, and the *effective* record
// (what `open` resolves a repeated path to: the last line wins) is
// checked separately below, which is the property that actually
// matters for correctness.
let store_text = fs::read_to_string(store.path.join("index-cache")).expect("a store");
assert!(
store_text.contains("a_pkg_in_buffer"),
"the write-through must have appended the buffer's facts: {store_text}"
);
let buffer_hash = lucisv_core::cache::content_hash(buffer_text.as_bytes());
assert!(
store_text.contains(&format!("{buffer_hash:016x}")),
"the appended record's key is the buffer's content hash: {store_text}"
);
let disk_text = fs::read_to_string(&path).expect("disk");
let disk_hash = lucisv_core::cache::content_hash(disk_text.as_bytes());
assert_ne!(disk_hash, buffer_hash, "premise: disk and buffer really do disagree");
let reopened = IndexCache::open(Some(store.path.clone()));
assert_eq!(
reopened.facts_for(&path, buffer_text),
Some(FileFacts::of(path.clone(), buffer_text)),
"the record a fresh session resolves to is the buffer's, not disk's stale one"
);
assert!(
reopened.facts_for(&path, &disk_text).is_none(),
"disk's own current bytes must not hit — no record was ever keyed on them"
);
}
#[test]
fn a_configured_cache_path_beats_the_editors_storage_folder() {
// Rung 1 over rung 2 of `index_cache::cache_dir`'s ladder, through
// the workspace rather than against the function: the store lands
// where the *setting* says, and the editor's folder is left alone.
let tree = Tree::new("cacheladder");
tree.package("a.sv", "a_pkg");
let storage = Tree::new("cacheladder_storage");
let configured = Tree::new("cacheladder_configured");
let mut ws = Workspace::default();
ws.set_storage_path(Some(storage.path.clone()));
ws.set_client_settings(wide(caching(&configured.path)));
scan(&mut ws, Some(vec![tree.path.clone()]));
assert!(configured.path.join("index-cache").exists(), "the setting won");
assert!(!storage.path.join("index-cache").exists(), "the editor's folder is untouched");
// Unset it and the editor's folder is what is left standing — on the
// next scan, which is when the store is re-opened.
ws.set_client_settings(wide(ClientSettings::default()));
ws.set_storage_path(Some(storage.path.clone()));
scan(&mut ws, None);
assert!(storage.path.join("index-cache").exists(), "and now the editor's folder");
}
#[test]
fn a_storage_folder_that_does_not_exist_yet_is_made_on_demand() {
// What VS Code hands over: `context.storageUri` names a folder the
// editor has not necessarily created.
let tree = Tree::new("cachemkdir");
tree.package("a.sv", "a_pkg");
let storage = Tree::new("cachemkdir_storage");
let nested = storage.path.join("deep/inner");
let mut ws = Workspace::default();
ws.set_storage_path(Some(nested.clone()));
ws.set_client_settings(wide(ClientSettings::default()));
scan(&mut ws, Some(vec![tree.path.clone()]));
assert!(nested.join("index-cache").exists(), "made on demand");
let mut warm = Workspace::default();
warm.set_storage_path(Some(nested));
warm.set_client_settings(wide(ClientSettings::default()));
let second = scan(&mut warm, Some(vec![tree.path.clone()]));
assert_eq!(second.cached, ["a.sv"], "{second:?}");
}
#[test]
fn the_cached_index_is_the_index_a_fresh_scan_would_have_built_over_the_corpus() {
// The paranoid sweep, against the real corpus: every file in, every
// file out of the cache, and the two indexes compared observable by
// observable through the fingerprint.
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let store = Tree::new("cachecorpus_store");
let mut cold = cached_workspace(&store.path);
let first = scan(&mut cold, Some(vec![corpus.clone()]));
assert!(first.parsed.len() > 500, "premise: the corpus was really scanned");
assert!(first.cached.is_empty());
let mut warm = cached_workspace(&store.path);
let second = scan(&mut warm, Some(vec![corpus]));
assert_eq!(second.cached.len(), first.parsed.len(), "every file came back");
assert!(second.parsed.is_empty(), "and none was parsed again");
assert_eq!(
warm.index().fingerprint(),
cold.index().fingerprint(),
"the cached index is the parsed index, file ids and all"
);
assert_eq!(warm.index().counts(), cold.index().counts());
// The completion tables and the include graph are built from the
// files' text either way, so they cannot drift — pinned rather than
// assumed, since the cache is the one thing that skips a file's parse.
assert_eq!(warm.candidates().words(""), cold.candidates().words(""));
}
/// QA (2026-08-27), attack surface 1/4, fixed 2026-08-27: the negative
/// control the equivalence sweep above cannot run on its own, through the
/// whole workspace rather than the store. A record used to be verified
/// only against the *file's* content hash, so a line whose hash matched
/// `a.sv`'s real bytes but whose facts were altered was a hit and the
/// index it produced silently diverged from what a fresh parse gives.
/// Every record now carries a checksum of its own facts, so the damaged
/// line is dropped: the file is parsed, the scan reports it as parsed
/// rather than cached, and the fingerprint is exactly a fresh scan's.
/// That is `docs/features/index-persistence`'s "a performance artifact
/// and never a correctness input" holding against *accidental* damage of
/// any shape; a store deliberately reforged is out of the threat model
/// and pinned as such in `index_cache.rs`.
#[test]
fn a_poisoned_cache_record_is_dropped_and_the_index_is_a_fresh_scans() {
let tree = Tree::new("poisonfingerprint");
tree.package("a.sv", "a_pkg");
let store = Tree::new("poisonfingerprint_store");
let mut cold = cached_workspace(&store.path);
scan(&mut cold, Some(vec![tree.path.clone()]));
let honest = cold.index().fingerprint();
// Hand-tamper the store on disk: keep the header, the hash of `a.sv`'s
// *real* bytes and the checksum the genuine record was written with,
// but swap in facts a parse of those bytes never produced (a different
// package name entirely) — which is what every accidental way a
// written record can change looks like from the reader's side.
let store_file = store.path.join("index-cache");
let text = fs::read_to_string(&store_file).expect("a store");
let header_line = text.lines().next().expect("header").to_string();
let record = text.lines().nth(1).expect("a record").to_string();
let checksum = record.rsplit('\t').next().expect("a checksum field");
let real_text = "package a_pkg;\n localparam K = 1;\nendpackage\n";
let hash = lucisv_core::cache::content_hash(real_text.as_bytes());
let evil = FileFacts::of(
tree.path.join("a.sv"),
"package poisoned_pkg;\n localparam K = 999;\nendpackage\n",
);
let poisoned =
format!("{header_line}\n{hash:016x}\t{}\t{checksum}\n", evil.encode().expect("encodes"));
fs::write(&store_file, poisoned).expect("write");
let mut warm = cached_workspace(&store.path);
let scanned = scan(&mut warm, Some(vec![tree.path.clone()]));
assert_eq!(scanned.parsed, ["a.sv"], "the tampered record is dropped: {scanned:?}");
assert!(scanned.cached.is_empty(), "and it is not served: {scanned:?}");
assert_eq!(
warm.index().fingerprint(),
honest,
"a record whose facts no longer match their checksum cannot reach the index, so \
the equivalence sweep's own claim holds against damage as well as staleness"
);
}
/// The measurement behind the README's numbers: a scan with no cache at
/// all, a cold one that fills the store, a warm one that reads it, and a
/// half-warm one with a single file changed.
#[test]
#[ignore = "measurement, not a test"]
fn qa_perf_cold_warm_and_half_warm_scans() {
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let store = Tree::new("cacheperf_store");
let timed = |ws: &mut Workspace| {
let started = std::time::Instant::now();
let scanned = scan(ws, None);
(started.elapsed(), scanned)
};
// The baseline: what a rescan cost before this feature existed.
let mut off = Workspace::default();
off.set_client_settings(wide(ClientSettings { index_persist: false, ..caching(&store.path) }));
scan(&mut off, Some(vec![corpus.clone()]));
let (cacheless, _) = timed(&mut off);
let mut ws = cached_workspace(&store.path);
let started = std::time::Instant::now();
let cold_scan = scan(&mut ws, Some(vec![corpus.clone()]));
let cold = started.elapsed();
let (warm, warm_scan) = timed(&mut ws);
// Half-warm: the store answers for every file but the one edited.
let one = ws.index().files()[0].clone();
let text = fs::read_to_string(&one).expect("read");
fs::write(&one, format!("{text}\n// edited\n")).expect("write");
let (half, half_scan) = timed(&mut ws);
fs::write(&one, &text).expect("restore");
let files = ws.index().files().len();
eprintln!(
"{files} files: no cache {cacheless:?}; cold {cold:?} ({} parsed); \
warm {warm:?} ({} cached); half-warm {half:?} ({} parsed, {} cached) — \
warm is {:.2}x the cacheless scan",
cold_scan.parsed.len(),
warm_scan.cached.len(),
half_scan.parsed.len(),
half_scan.cached.len(),
cacheless.as_secs_f64() / warm.as_secs_f64().max(f64::MIN_POSITIVE)
);
let store_size = fs::metadata(store.path.join("index-cache")).expect("a store").len();
eprintln!("store: {store_size} bytes for {files} files");
// What the key costs, which is the whole argument for keying on
// content rather than on a timestamp: the text is read on every scan
// anyway (the completion tables and the include graph are built from
// it), so the alternative would only ever have saved this.
let texts: Vec<String> =
ws.index().files().iter().filter_map(|path| fs::read_to_string(path).ok()).collect();
let bytes: usize = texts.iter().map(String::len).sum();
let started = std::time::Instant::now();
let mut sink = 0u64;
for text in &texts {
sink ^= lucisv_core::cache::content_hash(text.as_bytes());
}
eprintln!("hashing {bytes} bytes of {files} files: {:?} ({sink:016x})", started.elapsed());
}
@@ -0,0 +1,184 @@
//! What the walk takes — source extensions, gitignores, the root config's
//! excludes and the client's — and which pushed settings ask for a rescan.
use super::*;
#[test]
fn the_scan_skips_what_a_gitignore_skips() {
let tree = Tree::new("gitignore");
tree.write(".gitignore", "generated/\n*_gen.sv\n");
tree.package("kept.sv", "kept");
tree.package("generated/netlist.sv", "generated_pkg");
tree.package("rtl/top_gen.sv", "gen_pkg");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(ws.index().member("kept", "K").len(), 1, "a plain file is indexed");
assert_eq!(ws.index().member("generated_pkg", "K").len(), 0, "an ignored directory");
assert_eq!(ws.index().member("gen_pkg", "K").len(), 0, "an ignored name, at depth");
}
#[test]
fn the_scan_honours_the_root_configs_excludes() {
let tree = Tree::new("excludes");
tree.write("lucisv.toml", "exclude = [\"vendor\"]\n");
tree.package("kept.sv", "kept");
tree.package("vendor/ip.sv", "vendor_pkg");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(ws.index().member("kept", "K").len(), 1);
assert_eq!(ws.index().member("vendor_pkg", "K").len(), 0, "lucisv.toml excludes apply");
}
#[test]
fn a_broken_root_config_does_not_stop_the_scan() {
// Exit 2 is the CLI's answer to a broken config; a server that indexed
// nothing because of a typo would look simply broken instead.
let tree = Tree::new("brokencfg");
tree.write("lucisv.toml", "bogus = 1\n");
tree.package("kept.sv", "kept");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(ws.index().member("kept", "K").len(), 1);
}
#[test]
fn a_pushed_exclude_hides_files_from_the_index() {
let tree = Tree::new("clientexclude");
tree.package("kept.sv", "kept");
tree.package("scratch/wip.sv", "scratch_pkg");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(ws.index().member("scratch_pkg", "K").len(), 1, "premise: indexed at first");
assert!(ws.set_client_settings(wide(excluding(&["scratch"]))), "an exclude change rescans");
ws.rebuild_index();
assert_eq!(ws.index().member("kept", "K").len(), 1, "an unmatched file stays");
assert_eq!(ws.index().member("scratch_pkg", "K").len(), 0, "the excluded one is gone");
}
#[test]
fn a_pushed_exclude_is_appended_to_the_configs_and_does_not_replace_it() {
// The failure this guards: a user setting `lucisv.exclude` in their
// editor and thereby putting the project's vendored code — which the
// checked-in `lucisv.toml` excludes — back into the index for them only.
let tree = Tree::new("bothexcludes");
tree.write("lucisv.toml", "exclude = [\"vendor\"]\n");
tree.package("kept.sv", "kept");
tree.package("vendor/ip.sv", "vendor_pkg");
tree.package("scratch/wip.sv", "scratch_pkg");
let mut ws = Workspace::default();
ws.set_client_settings(excluding(&["scratch"]));
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(ws.index().member("kept", "K").len(), 1, "an unmatched file stays");
assert_eq!(ws.index().member("vendor_pkg", "K").len(), 0, "the config's exclude holds");
assert_eq!(ws.index().member("scratch_pkg", "K").len(), 0, "and the pushed one applies");
}
#[test]
fn only_an_exclude_change_asks_for_a_rescan() {
// `lineLength` and `indent` are read afresh by every formatting
// request, so re-walking the workspace for them would be pure cost.
let mut ws = Workspace::default();
assert!(!ws.set_client_settings(ClientSettings::default()), "nothing changed");
assert!(
!ws.set_client_settings(ClientSettings {
line_length: Some(120),
indent: Some(4),
..Default::default()
}),
"widths do not move files"
);
// QA (2026-08-26): `format_on_save` is read afresh by
// `will_save_wait_until` exactly as `indent`/`lineLength` are by
// `formatting` — it must not ask for a rescan either, or every
// `lucisv.formatOnSave` toggle would pay for a full re-walk (and, on
// a client that pulls, bump the diagnostics generation along with
// it).
assert!(
!ws.set_client_settings(ClientSettings { format_on_save: true, ..Default::default() }),
"turning the save hook on does not move files either"
);
// The file log changes how loudly a rescan narrates itself and nothing
// about which files exist, so it must not buy one.
assert!(
!ws.set_client_settings(ClientSettings { log_files: false, ..Default::default() }),
"turning the per-file log off does not move files either"
);
assert!(ws.set_client_settings(excluding(&["a"])), "a new exclude does");
// The cap does move files, so it does.
assert!(
ws.set_client_settings(ClientSettings {
exclude: vec!["a".to_string()],
max_file_size: 4096,
..Default::default()
}),
"a new cap rescans"
);
assert!(
!ws.set_client_settings(ClientSettings {
exclude: vec!["a".to_string()],
max_file_size: 4096,
log_files: false,
..Default::default()
}),
"the same cap with a different log setting does not"
);
assert!(
ws.set_client_settings(ClientSettings {
exclude: vec!["a".to_string()],
log_files: false,
..Default::default()
}),
"and going back to the default cap does"
);
ws.set_client_settings(excluding(&["a"]));
assert!(!ws.set_client_settings(excluding(&["a"])), "the same one again does not");
assert!(ws.set_client_settings(excluding(&["a", "b"])), "an added pattern does");
assert!(ws.set_client_settings(ClientSettings::default()), "and so does clearing it");
}
#[test]
fn a_filelist_change_asks_for_a_rescan_too() {
// It changes which files exist as far as this server is concerned,
// which is the whole test for whether a rescan is owed.
let mut ws = Workspace::default();
assert!(ws.set_client_settings(using_filelist("files.f")), "a new filelist rescans");
assert!(!ws.set_client_settings(using_filelist("files.f")), "the same one does not");
assert!(ws.set_client_settings(using_filelist("other.f")), "a different one does");
assert!(ws.set_client_settings(ClientSettings::default()), "and so does clearing it");
}
#[test]
fn the_pushed_settings_are_readable_where_formatting_needs_them() {
let mut ws = Workspace::default();
assert_eq!(ws.client_settings(), &ClientSettings::default(), "default until pushed");
ws.set_client_settings(ClientSettings {
line_length: Some(120),
indent: Some(4),
..Default::default()
});
assert_eq!(ws.client_settings().indent, Some(4));
assert_eq!(ws.client_settings().line_length, Some(120));
}
#[test]
fn the_scan_takes_only_source_extensions() {
let tree = Tree::new("extensions");
tree.package("a.sv", "a");
tree.package("b.v", "b");
tree.package("c.svh", "c");
tree.package("d.vh", "d");
tree.package("e.txt", "e");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
for name in ["a", "b", "c", "d"] {
assert_eq!(ws.index().member(name, "K").len(), 1, "{name} is a source file");
}
assert_eq!(ws.index().member("e", "K").len(), 0, "a .txt is not");
}
@@ -0,0 +1,185 @@
//! `lucisv.index.maxFileSize`: a walked file over the cap is left out of
//! the index, an open buffer never is, and every skip is reported with its
//! size and the cap.
use super::*;
#[test]
fn a_walked_file_over_the_cap_is_left_out_of_the_index() {
let tree = Tree::new("capskip");
tree.package("small.sv", "small_pkg");
fat_package(&tree, "netlist.sv", "netlist_pkg", 4096);
let mut ws = Workspace::default();
ws.set_client_settings(capping(1024));
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(
indexed(&ws, &["small_pkg", "netlist_pkg"]),
["small_pkg"],
"the big file is not in the index, and was never read"
);
}
#[test]
fn the_default_cap_is_a_mebibyte_and_zero_turns_it_off() {
// The shipped default, exercised against a file that really is over
// 1 MiB — the only way to prove the constant is the one in force.
let tree = Tree::new("capdefault");
tree.package("small.sv", "small_pkg");
fat_package(&tree, "huge.sv", "huge_pkg", 1024 * 1024 + 1);
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["small_pkg", "huge_pkg"]), ["small_pkg"], "capped by default");
// `0` is the client asking for no cap, and must be exactly the
// behaviour that existed before there was one.
assert!(ws.set_client_settings(wide(capping(0))), "turning the cap off rescans");
ws.rebuild_index();
assert_eq!(
indexed(&ws, &["small_pkg", "huge_pkg"]),
["small_pkg", "huge_pkg"],
"nothing capped"
);
}
#[test]
fn an_open_buffer_is_indexed_however_big_the_file_is() {
// The documented exemption: the cap is about files nobody asked for.
// A buffer the user opened is indexed and diagnosed whatever its size,
// or the editor would refuse to understand the file on screen.
let tree = Tree::new("capbuffer");
fat_package(&tree, "huge.sv", "huge_pkg", 4096);
let mut ws = Workspace::default();
ws.set_client_settings(capping(1024));
// Whole-workspace scope so the walked file is genuinely capped by the
// CAP, not merely unreachable by the folder scope (QA finding,
// 2026-08-27, lead-fixed: the premise held for the wrong reason).
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["huge_pkg"]), Vec::<String>::new(), "premise: capped on disk");
let uri = crate::uri::path_to_uri(&tree.path.join("huge.sv")).expect("uri");
let text = fs::read_to_string(tree.path.join("huge.sv")).expect("read");
ws.set_document(uri, text);
ws.rebuild_index();
assert_eq!(indexed(&ws, &["huge_pkg"]), ["huge_pkg"], "the open buffer is indexed in full");
}
#[test]
fn qa_an_open_buffer_over_the_cap_is_both_skipped_and_analyzed_unchanged_from_before() {
// QA attack (index-scope, 2026-08-28, charter item 4: the cap
// boundary). `collect_sources` walks the scope and reports
// `Skipped` for every file over `maxFileSize` *before* it knows
// whether an open buffer speaks for that path — that ordering is
// pre-existing (the `spoken_for` short-circuit this round added only
// skips the wasted disk *read*, not the cap check ahead of it). The
// question this pins: did routing an open buffer's facts through its
// own analysis change that reporting, or the fact that the buffer
// still ends up indexed in full? It must not: the file is still
// reported `Skipped` once (the disk phase honestly saying the walked
// copy is over cap), and it still ends up indexed — now via
// `Analyzed` rather than `Parsing`, since the round's whole point is
// that an open buffer's own analysis is reused instead of reparsed.
let tree = Tree::new("capbufferqa");
fat_package(&tree, "huge.sv", "huge_pkg", 4096);
let path = tree.path.join("huge.sv");
let mut ws = Workspace::default();
ws.set_client_settings(capping(1024));
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["huge_pkg"]), Vec::<String>::new(), "premise: capped on disk");
let uri = crate::uri::path_to_uri(&path).expect("uri");
let text = fs::read_to_string(&path).expect("read");
ws.set_document(uri, text);
let mut skipped: Vec<PathBuf> = Vec::new();
let mut analyzed: Vec<PathBuf> = Vec::new();
let mut parsed: Vec<PathBuf> = Vec::new();
ws.rebuild_index_with(&mut |event| match event {
IndexEvent::Skipped { path, .. } => skipped.push(path.to_path_buf()),
IndexEvent::Analyzed { path, .. } => analyzed.push(path.to_path_buf()),
IndexEvent::Parsing { path, .. } => parsed.push(path.to_path_buf()),
IndexEvent::Cached { .. } => {}
});
assert_eq!(skipped, vec![path.clone()], "still reported skipped once, from the disk phase");
assert_eq!(analyzed, vec![path.clone()], "and indexed via its own analysis, not reparsed");
assert!(parsed.is_empty(), "never re-parsed: {parsed:?}");
assert_eq!(indexed(&ws, &["huge_pkg"]), ["huge_pkg"], "still indexed in full, unmoved");
}
#[test]
fn every_skipped_file_is_reported_with_its_size_and_the_cap() {
let tree = Tree::new("capevents");
tree.package("small.sv", "small_pkg");
fat_package(&tree, "netlist.sv", "netlist_pkg", 4096);
let mut ws = Workspace::default();
ws.set_client_settings(capping(1024));
let mut skipped: Vec<(PathBuf, u64, u64)> = Vec::new();
ws.open_whole_workspace_with(vec![tree.path.clone()], &mut |event| {
if let IndexEvent::Skipped { path, size, cap } = event {
skipped.push((path.to_path_buf(), size, cap));
}
});
assert_eq!(skipped.len(), 1, "{skipped:?}");
assert_eq!(skipped[0].0, tree.path.join("netlist.sv"));
assert!(skipped[0].1 >= 4096, "the file's real size: {skipped:?}");
assert_eq!(skipped[0].2, 1024, "and the cap it was measured against");
}
#[test]
fn the_watcher_sees_every_file_in_index_order_against_a_total_it_knew_first() {
// The denominator is the work list *after* the exclude and the cap:
// a bar counting towards a number that included files nobody was
// going to parse would stall short of the end every time.
let tree = Tree::new("capwatch");
tree.package("b.sv", "b");
tree.package("a.sv", "a");
tree.package("skipped/c.sv", "c");
fat_package(&tree, "d.sv", "d_pkg", 4096);
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings {
exclude: vec!["skipped".to_string()],
max_file_size: 1024,
..Default::default()
});
let mut seen: Vec<(usize, usize, PathBuf)> = Vec::new();
ws.open_whole_workspace_with(vec![tree.path.clone()], &mut |event| {
if let IndexEvent::Parsing { done, total, path } = event {
seen.push((done, total, path.to_path_buf()));
}
});
assert_eq!(
seen,
vec![(0, 2, tree.path.join("a.sv")), (1, 2, tree.path.join("b.sv")),],
"sorted, excluded and capped files absent, total known from the first event"
);
assert_eq!(ws.index().files().len(), 2, "and the index holds exactly those");
}
#[test]
fn the_default_cap_changes_nothing_about_the_real_corpus() {
// The cap ships on, so the burden is to show it costs an existing
// project nothing: the index the default cap builds over `corpus/`
// must be the one no cap at all builds. It is — the largest corpus
// file is 94 KB, eleven times under the cap — and this test is what
// notices if a future corpus, or a future default, changes that.
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let mut capped = Workspace::default();
capped.open_whole_workspace(vec![corpus.clone()]);
let mut uncapped = Workspace::default();
uncapped.set_client_settings(capping(0));
uncapped.open_whole_workspace(vec![corpus]);
assert_eq!(capped.index().files(), uncapped.index().files(), "the same files, in order");
assert_eq!(capped.index().counts(), uncapped.index().counts(), "and the same index");
assert!(capped.index().files().len() > 500, "premise: the corpus was really scanned");
}
@@ -0,0 +1,218 @@
//! The closed-file view cache.
//!
//! Every test below observes the cache the only honest way there is: it
//! changes a file on disk *without telling the server*, and asks whether
//! the next view still shows the old text. A view that survives such an
//! edit was cached; one that does not was re-read. That is a cache and not
//! a correctness input, so "still shows the old text" is the expected
//! answer everywhere the invalidation list does not name.
use super::*;
use crate::state::views::{MAX_VIEWS, MAX_VIEW_BYTES};
/// A file with `n` declared modules, so its text is both readable and
/// tellable apart.
fn versioned(n: usize) -> String {
(0..n).map(|k| format!("module m{k};\nendmodule\n")).collect()
}
#[test]
fn a_closed_files_text_is_read_once_and_then_reused() {
let tree = Tree::new("viewreuse");
tree.write("sub.sv", &versioned(1));
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let path = tree.path.join("sub.sv");
let first = ws.file_view(&path).expect("readable").text.clone();
assert!(first.contains("m0"), "premise: the file was read");
// Behind the server's back — no didSave, no watcher, no rescan.
tree.write("sub.sv", &versioned(2));
assert_eq!(
ws.file_view(&path).expect("readable").text,
first,
"the second question about one file costs no second read"
);
}
#[test]
fn a_file_an_open_buffer_speaks_for_has_no_view_of_its_own() {
// The buffer's own `Document` is the authority on its text; a second
// copy here would be a second opinion, so there is deliberately none.
let tree = Tree::new("viewopen");
tree.write("sub.sv", &versioned(1));
let path = tree.path.join("sub.sv");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert!(ws.file_view(&path).is_some(), "premise: readable while closed");
ws.set_document(uri(&format!("file://{}", path.display())), versioned(3));
assert!(ws.file_view(&path).is_none(), "an open buffer answers for itself");
}
#[test]
fn every_way_a_files_text_can_move_drops_its_view() {
// The four invalidation points named in `Workspace::file_view`'s doc
// comment, each proved by the same experiment: warm the view, change
// the file on disk, run the event, and require the next view to be
// the new text rather than the held one.
let path_uri = |path: &Path| uri(&format!("file://{}", path.display()));
for event in ["didOpen", "didClose", "update_one", "rebuild"] {
let tree = Tree::new(&format!("viewdrop_{event}"));
tree.write("sub.sv", &versioned(1));
let path = tree.path.join("sub.sv");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let held = ws.file_view(&path).expect("readable").text.clone();
tree.write("sub.sv", &versioned(2));
assert_eq!(ws.file_view(&path).expect("readable").text, held, "premise: {event}");
match event {
// Opening the file: the buffer takes over, and closing it
// again must not hand back the view from before the buffer
// existed — it predates every save that buffer made.
"didOpen" | "didClose" => {
ws.set_document(path_uri(&path), versioned(9));
assert!(ws.file_view(&path).is_none(), "open: no view at all");
ws.close_document(&path_uri(&path));
}
"update_one" => {
assert!(ws.update_one(&path), "the index holds this file");
}
"rebuild" => {
ws.rebuild_index();
}
_ => unreachable!(),
}
let after = ws.file_view(&path).expect("readable").text.clone();
assert_ne!(after, held, "{event} must drop the held view");
assert!(after.contains("m1"), "{event} must serve the file as it is now: {after}");
}
}
#[test]
fn the_view_cache_holds_a_handful_of_files_and_a_bounded_amount_of_text() {
let tree = Tree::new("viewbound");
let paths: Vec<PathBuf> = (0..MAX_VIEWS + 2)
.map(|n| {
tree.write(&format!("f{n}.sv"), &versioned(n + 1));
tree.path.join(format!("f{n}.sv"))
})
.collect();
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
for path in &paths {
let _ = ws.file_view(path).expect("readable");
}
assert_eq!(ws.views.borrow().len(), MAX_VIEWS, "the count bound holds");
assert_eq!(
ws.views.borrow()[0].path,
paths[paths.len() - 1],
"newest first, so the oldest is what falls off"
);
// One file bigger than the whole byte budget: it is still cached —
// it is exactly the file this cache exists for — and it evicts
// everything else rather than being refused.
tree.write("huge.sv", &"// filler\n".repeat(MAX_VIEW_BYTES / 10 + 1));
let huge = tree.path.join("huge.sv");
let _ = ws.file_view(&huge).expect("readable");
let views = ws.views.borrow();
assert_eq!(views.len(), 1, "a file over the budget holds the cache alone");
assert_eq!(views[0].path, huge);
}
/// QA (2026-08-28): the bound test above only ever caches *one* oversized
/// file. The "newest is kept whatever it weighs" rule is only a bound —
/// not a leak — if a *second* oversized file replaces the first rather
/// than piling up beside it, which is the scenario the brief asks for by
/// name.
#[test]
fn a_second_oversized_file_evicts_the_first_rather_than_growing_beside_it() {
let tree = Tree::new("viewhugehuge");
let filler = "// filler\n".repeat(MAX_VIEW_BYTES / 10 + 1);
tree.write("huge_a.sv", &filler);
tree.write("huge_b.sv", &filler);
let a = tree.path.join("huge_a.sv");
let b = tree.path.join("huge_b.sv");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let _ = ws.file_view(&a).expect("readable");
assert_eq!(ws.views.borrow().len(), 1, "the first huge file holds the cache alone");
let _ = ws.file_view(&b).expect("readable");
let views = ws.views.borrow();
assert_eq!(views.len(), 1, "the second huge file replaces it rather than growing beside it");
assert_eq!(views[0].path, b, "the newest is what survives");
}
/// QA (2026-08-28): `update_one`'s doc comment and the README both say it
/// drops *that path's* view and nothing else — the selectivity half of
/// the invalidation story, which `every_way_a_files_text_can_move_drops_
/// its_view` never exercises because it only ever warms one file's view
/// at a time. A regression that widened `update_one` to `views.clear()`
/// would still pass every existing test in this file.
#[test]
fn updating_one_file_leaves_another_files_cached_view_alone() {
let tree = Tree::new("viewupdateoneselective");
tree.write("a.sv", &versioned(1));
tree.write("b.sv", &versioned(1));
let a = tree.path.join("a.sv");
let b = tree.path.join("b.sv");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let view_a = ws.file_view(&a).expect("readable").text.clone();
let view_b = ws.file_view(&b).expect("readable").text.clone();
tree.write("a.sv", &versioned(2));
tree.write("b.sv", &versioned(2));
assert!(ws.update_one(&a), "the index holds a.sv");
assert_ne!(ws.file_view(&a).expect("readable").text, view_a, "a.sv's view was dropped");
assert_eq!(
ws.file_view(&b).expect("readable").text,
view_b,
"b.sv's view must survive a.sv's update — update_one names one path, not the cache"
);
}
/// QA (2026-08-28): `cached_view` moves a hit to the front so recency,
/// not merely insertion order, decides what falls off — untested until
/// now. Warm four files (the cap), touch the oldest again, then add a
/// fifth: without the recency reorder the just-touched file would be the
/// one to go (it was inserted first), and with it the file nobody has
/// asked about since is what goes instead.
#[test]
fn re_hovering_the_oldest_cached_file_saves_it_from_eviction() {
let tree = Tree::new("viewmru");
let paths: Vec<PathBuf> = (0..MAX_VIEWS + 1)
.map(|n| {
tree.write(&format!("f{n}.sv"), &versioned(n + 1));
tree.path.join(format!("f{n}.sv"))
})
.collect();
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
// Fill the cache: f0 (oldest) through f3 (newest of the first batch).
for path in &paths[..MAX_VIEWS] {
let _ = ws.file_view(path).expect("readable");
}
// Touch the oldest again — it should now count as the most recent.
let _ = ws.file_view(&paths[0]).expect("readable");
// One more file arrives, forcing an eviction.
let _ = ws.file_view(&paths[MAX_VIEWS]).expect("readable");
let paths_held: std::collections::HashSet<PathBuf> =
ws.views.borrow().iter().map(|v| v.path.clone()).collect();
assert!(
paths_held.contains(&paths[0]),
"the file re-hovered a moment ago must survive: {paths_held:?}"
);
assert!(
!paths_held.contains(&paths[1]),
"the file nobody has touched since must be what falls off instead: {paths_held:?}"
);
}
@@ -0,0 +1,459 @@
//! The incremental scope widen (docs/features/index-scope): the tables a
//! widen lands are the ones a whole rescan would have left, and it reads
//! only the files the new folders brought in.
use super::*;
/// Everything a widen must leave equal to what a whole rescan leaves: the
/// index, all three completion tables, and the include graph.
///
/// Rendered as strings so a failure names the table that moved rather than
/// reporting that two opaque values differ.
fn tables(ws: &Workspace) -> Vec<(&'static str, String)> {
let units: Vec<String> = ws
.candidates()
.units("")
.iter()
.map(|c| format!("{} {:?} {}", c.name, c.kind, c.detail))
.collect();
let macros: Vec<String> =
ws.candidates().macros("").iter().map(|m| format!("{} {}", m.name, m.detail)).collect();
vec![
("index", ws.index().fingerprint()),
("words", format!("{:?}", ws.candidates().words(""))),
("units", format!("{units:?}")),
("macros", format!("{macros:?}")),
("includes", ws.includes().fingerprint()),
]
}
fn same_tables(widened: &Workspace, rebuilt: &Workspace, what: &str) {
for ((name, left), (_, right)) in tables(widened).into_iter().zip(tables(rebuilt)) {
assert_eq!(left, right, "{what}: the {name} table a widen left is not a rebuild's");
}
}
/// The directories `open` added to the scope, and the widen that indexes
/// them — the two-line spelling of what `server.rs`'s `didOpen` does.
fn widen(ws: &mut Workspace, open: impl FnOnce(&mut Workspace)) -> Vec<PathBuf> {
let before = ws.scope_dirs();
open(ws);
let after = ws.scope_dirs();
let added: Vec<PathBuf> = after.iter().filter(|dir| !before.contains(dir)).cloned().collect();
assert!(!added.is_empty(), "premise: this open widened the scope");
ws.widen_index(&added);
added
}
/// A two-folder tree with an unsaved edit, a shared header included from
/// both halves, and a name declared on each side.
fn widen_tree(name: &str) -> Tree {
let tree = Tree::new(name);
tree.write("rtl/top.sv", "`include \"defs.svh\"\nmodule top;\n wire a;\nendmodule\n");
tree.write("rtl/defs.svh", "`define RTL_W 8\n");
tree.package("rtl/rtl_pkg.sv", "rtl_pkg");
tree.write("lib/sub.sv", "`include \"lib_defs.svh\"\nmodule sub;\nendmodule\n");
tree.write("lib/lib_defs.svh", "`define LIB_W 16\n");
tree.package("lib/lib_pkg.sv", "lib_pkg");
tree
}
#[test]
fn a_widen_leaves_the_tables_a_whole_rescan_would_have_left() {
let tree = widen_tree("widenequal");
let top = crate::uri::path_to_uri(&tree.path.join("rtl/top.sv")).expect("uri");
let sub = crate::uri::path_to_uri(&tree.path.join("lib/sub.sv")).expect("uri");
// The hostile half: the buffer that is already open carries an edit
// that is on no disk anywhere when the widen runs. A widen that
// indexed only the new folder's files would lose `NEVER_SAVED`, which
// is the objection that stopped this shape being taken in round 19.
let edited = "module top;\n wire never_saved;\n localparam NEVER_SAVED = 1;\nendmodule\n";
let sub_text = fs::read_to_string(tree.path.join("lib/sub.sv")).expect("read");
let mut incremental = Workspace::default();
own_folder_only(&mut incremental);
incremental.open_roots(vec![tree.path.clone()]);
incremental.set_document(top.clone(), edited.to_string());
incremental.rebuild_index();
assert_eq!(incremental.index().files().len(), 3, "premise: the rtl folder alone");
widen(&mut incremental, |ws| ws.set_document(sub.clone(), sub_text.clone()));
let mut rebuilt = Workspace::default();
own_folder_only(&mut rebuilt);
rebuilt.open_roots(vec![tree.path.clone()]);
rebuilt.set_document(top.clone(), edited.to_string());
rebuilt.set_document(sub.clone(), sub_text.clone());
rebuilt.rebuild_index();
assert_eq!(rebuilt.index().files().len(), 6, "premise: both folders");
assert_eq!(
incremental.candidates().words("never_sav"),
["NEVER_SAVED", "never_saved"],
"the unsaved edit is in the widened tables"
);
same_tables(&incremental, &rebuilt, "an unsaved edit across a widen");
}
#[test]
fn a_widen_reads_only_the_files_the_new_folders_brought_in() {
let tree = widen_tree("widenwork");
let top = crate::uri::path_to_uri(&tree.path.join("rtl/top.sv")).expect("uri");
let sub_path = tree.path.join("lib/sub.sv");
let sub = crate::uri::path_to_uri(&sub_path).expect("uri");
let sub_text = fs::read_to_string(&sub_path).expect("read");
let mut ws = Workspace::default();
own_folder_only(&mut ws);
ws.open_roots(vec![tree.path.clone()]);
ws.set_document(top.clone(), fs::read_to_string(tree.path.join("rtl/top.sv")).expect("r"));
ws.rebuild_index();
let mut seen = Scan::default();
{
let mut see = |event: IndexEvent| match event {
IndexEvent::Parsing { path, .. } => seen.parsed.push(file_name(path)),
IndexEvent::Cached { path, .. } => seen.cached.push(file_name(path)),
IndexEvent::Analyzed { path, .. } => seen.analyzed.push(file_name(path)),
IndexEvent::Skipped { .. } => {}
};
let before = ws.scope_dirs();
ws.set_document(sub.clone(), sub_text);
let after = ws.scope_dirs();
let added: Vec<PathBuf> =
after.iter().filter(|dir| !before.contains(dir)).cloned().collect();
ws.widen_index_with(&added, &mut see);
}
seen.parsed.sort();
// The three `rtl/` files are already indexed and are not read again;
// the open buffer is refreshed from the analysis it holds, which is
// what makes an unsaved edit survive the widen.
assert_eq!(seen.parsed, ["lib_defs.svh", "lib_pkg.sv"], "{seen:?}");
seen.analyzed.sort();
// Both open buffers, not only the newly opened one: every buffer's
// held analysis is refreshed, which is what carries an unsaved edit
// across a widen.
assert_eq!(seen.analyzed, ["sub.sv", "top.sv"], "{seen:?}");
assert!(seen.cached.is_empty(), "no cache in this test: {seen:?}");
assert!(!seen.parsed.contains(&"top.sv".to_string()), "the old folder is untouched");
assert_eq!(ws.index().files().len(), 6);
}
#[test]
fn a_widen_bar_counts_the_new_files_and_not_the_whole_scope() {
let tree = widen_tree("widenbar");
let top = crate::uri::path_to_uri(&tree.path.join("rtl/top.sv")).expect("uri");
let sub_path = tree.path.join("lib/sub.sv");
let sub = crate::uri::path_to_uri(&sub_path).expect("uri");
let sub_text = fs::read_to_string(&sub_path).expect("read");
let mut ws = Workspace::default();
own_folder_only(&mut ws);
ws.open_roots(vec![tree.path.clone()]);
ws.set_document(top, fs::read_to_string(tree.path.join("rtl/top.sv")).expect("r"));
ws.rebuild_index();
let mut totals: Vec<usize> = Vec::new();
{
let mut see = |event: IndexEvent| match event {
IndexEvent::Parsing { total, .. }
| IndexEvent::Cached { total, .. }
| IndexEvent::Analyzed { total, .. } => totals.push(total),
IndexEvent::Skipped { .. } => {}
};
let before = ws.scope_dirs();
ws.set_document(sub, sub_text);
let added: Vec<PathBuf> =
ws.scope_dirs().iter().filter(|dir| !before.contains(dir)).cloned().collect();
ws.widen_index_with(&added, &mut see);
}
// Two new files plus the two open buffers refreshed — never the six
// the scope now holds. A bar that counted the whole scope would crawl.
assert_eq!(totals, [4, 4, 4, 4], "the denominator is the widen's own work list");
}
#[test]
fn a_widen_into_a_folder_that_contains_the_old_one_indexes_each_file_once() {
// A file present in both the old scope portion and the new one: the
// added directory is the *parent* of the directory already in scope,
// so its walk finds everything the first scan already indexed.
let tree = Tree::new("widennested");
tree.package("rtl/deep/a.sv", "a_pkg");
tree.package("rtl/b.sv", "b_pkg");
let deep = crate::uri::path_to_uri(&tree.path.join("rtl/deep/a.sv")).expect("uri");
let shallow = crate::uri::path_to_uri(&tree.path.join("rtl/b.sv")).expect("uri");
let deep_text = fs::read_to_string(tree.path.join("rtl/deep/a.sv")).expect("read");
let shallow_text = fs::read_to_string(tree.path.join("rtl/b.sv")).expect("read");
let mut incremental = Workspace::default();
own_folder_only(&mut incremental);
incremental.open_roots(vec![tree.path.clone()]);
incremental.set_document(deep.clone(), deep_text.clone());
incremental.rebuild_index();
assert_eq!(incremental.index().files().len(), 1, "premise: rtl/deep alone");
let mut seen = Scan::default();
{
let mut see = |event: IndexEvent| match event {
IndexEvent::Parsing { path, .. } => seen.parsed.push(file_name(path)),
IndexEvent::Cached { path, .. } => seen.cached.push(file_name(path)),
IndexEvent::Analyzed { path, .. } => seen.analyzed.push(file_name(path)),
IndexEvent::Skipped { .. } => {}
};
let before = incremental.scope_dirs();
incremental.set_document(shallow.clone(), shallow_text.clone());
let added: Vec<PathBuf> =
incremental.scope_dirs().iter().filter(|dir| !before.contains(dir)).cloned().collect();
incremental.widen_index_with(&added, &mut see);
}
assert!(seen.parsed.is_empty(), "both files speak for themselves: {seen:?}");
seen.analyzed.sort();
assert_eq!(seen.analyzed, ["a.sv", "b.sv"], "{seen:?}");
assert_eq!(incremental.index().files().len(), 2, "a.sv is indexed once, not twice");
let mut rebuilt = Workspace::default();
own_folder_only(&mut rebuilt);
rebuilt.open_roots(vec![tree.path.clone()]);
rebuilt.set_document(deep, deep_text);
rebuilt.set_document(shallow, shallow_text);
rebuilt.rebuild_index();
same_tables(&incremental, &rebuilt, "a widen into a containing folder");
}
#[test]
fn a_widen_that_subsumes_the_old_scope_reads_only_the_files_it_adds() {
// opentitan's own shape, and the jump `performance_take2.md` §5b
// measured: at the shipped `scopeDepth: 2`, `ip/aes/dv/tb` raises to
// `ip/aes`, and the very next file — `ip/aes/rtl/aes.sv` — raises to
// `ip`, the *parent* of the directory already in scope. The new scope's
// file set is a superset of the old one, so the widen owes the other
// blocks and nothing else: `ip/aes`'s own already-indexed files are
// never re-read, and the diff that says so is by **file against the
// index**, not by folder against the old walk.
let tree = Tree::new("widensubsume");
tree.package("ip/aes/rtl/aes.sv", "aes_pkg");
tree.package("ip/aes/rtl/aes_core.sv", "aes_core_pkg");
tree.package("ip/aes/dv/tb/tb.sv", "aes_tb_pkg");
tree.package("ip/aes/dv/env/aes_env.sv", "aes_env_pkg");
tree.package("ip/kmac/rtl/kmac.sv", "kmac_pkg");
tree.package("ip/hmac/rtl/hmac.sv", "hmac_pkg");
// Over the cap: not indexed before the widen, so it must not count as
// "already there" — it is walked again, skipped again, and reported.
tree.write(
"ip/kmac/rtl/huge.sv",
&format!("package huge_pkg;\n{}endpackage\n", " // pad\n".repeat(200)),
);
let aes = crate::uri::path_to_uri(&tree.path.join("ip/aes/rtl/aes.sv")).expect("uri");
let tb = crate::uri::path_to_uri(&tree.path.join("ip/aes/dv/tb/tb.sv")).expect("uri");
let aes_text = fs::read_to_string(tree.path.join("ip/aes/rtl/aes.sv")).expect("read");
// An unsaved edit in a buffer that is *not* the one being opened: what
// makes the equivalence below a real claim rather than a coincidence.
let edited_tb =
"package aes_tb_pkg;\n localparam K = 1;\n localparam UNSAVED = 2;\nendpackage\n";
let settings =
ClientSettings { index_scope_depth: 2, max_file_size: 512, ..Default::default() };
let mut incremental = Workspace::default();
incremental.set_client_settings(settings.clone());
incremental.open_roots(vec![tree.path.clone()]);
incremental.set_document(tb.clone(), edited_tb.into());
incremental.rebuild_index();
assert_eq!(
incremental.scope_dirs(),
[tree.path.join("ip/aes")],
"premise: the testbench raises two levels to its own block"
);
assert_eq!(incremental.index().files().len(), 4, "premise: the block's four files");
let mut seen = Scan::default();
let mut totals: Vec<usize> = Vec::new();
let mut skipped: Vec<String> = Vec::new();
let added = {
let mut see = |event: IndexEvent| match event {
IndexEvent::Parsing { path, total, .. } => {
seen.parsed.push(file_name(path));
totals.push(total);
}
IndexEvent::Cached { path, total, .. } => {
seen.cached.push(file_name(path));
totals.push(total);
}
IndexEvent::Analyzed { path, total, .. } => {
seen.analyzed.push(file_name(path));
totals.push(total);
}
IndexEvent::Skipped { path, .. } => skipped.push(file_name(path)),
};
let before = incremental.scope_dirs();
incremental.set_document(aes.clone(), aes_text.clone());
let added: Vec<PathBuf> =
incremental.scope_dirs().iter().filter(|dir| !before.contains(dir)).cloned().collect();
incremental.widen_index_with(&added, &mut see);
added
};
assert_eq!(added, [tree.path.join("ip")], "the added directory contains the old scope");
seen.parsed.sort();
// The two other blocks, and not one file of `ip/aes` — those the index
// already holds, and holding them is what the file diff is for.
assert_eq!(seen.parsed, ["hmac.sv", "kmac.sv"], "{seen:?}");
seen.analyzed.sort();
assert_eq!(seen.analyzed, ["aes.sv", "tb.sv"], "both buffers refresh: {seen:?}");
assert_eq!(skipped, ["huge.sv"], "the capped file is walked and skipped again");
assert_eq!(totals, [4, 4, 4, 4], "the bar counts the two new files and the two buffers");
assert_eq!(incremental.index().files().len(), 6, "four held plus two new, never the cap's");
let mut rebuilt = Workspace::default();
rebuilt.set_client_settings(settings);
rebuilt.open_roots(vec![tree.path.clone()]);
rebuilt.set_document(tb, edited_tb.into());
rebuilt.set_document(aes, aes_text);
rebuilt.rebuild_index();
assert_eq!(rebuilt.index().files().len(), 6, "premise: the same six files");
same_tables(&incremental, &rebuilt, "a widen that subsumed the old scope");
}
#[test]
fn a_widen_lends_a_new_files_spelling_to_an_include_resolved_before_it() {
// The include graph's own hostile case, and the reason this round
// holds each edge as the filesystem answered it: `rtl/top.sv` was
// indexed while `lib/` was out of scope, so its `` `include`` into
// `lib/` could not be spelled the way the index spells that file. The
// widen must re-spell it without re-reading `rtl/top.sv`.
let tree = Tree::new("widenspell");
tree.write("lib/Shared.svh", "`define SHARED 1\n");
// The include is written in the other case, which a case-insensitive
// filesystem happily opens; on a case-sensitive one it does not
// resolve at all, and both workspaces agree on that too.
tree.write("rtl/top.sv", "`include \"../lib/shared.svh\"\nmodule top;\nendmodule\n");
tree.package("lib/lib_pkg.sv", "lib_pkg");
let top = crate::uri::path_to_uri(&tree.path.join("rtl/top.sv")).expect("uri");
let lib = crate::uri::path_to_uri(&tree.path.join("lib/lib_pkg.sv")).expect("uri");
let top_text = fs::read_to_string(tree.path.join("rtl/top.sv")).expect("read");
let lib_text = fs::read_to_string(tree.path.join("lib/lib_pkg.sv")).expect("read");
let mut incremental = Workspace::default();
own_folder_only(&mut incremental);
incremental.open_roots(vec![tree.path.clone()]);
incremental.set_document(top.clone(), top_text.clone());
incremental.rebuild_index();
widen(&mut incremental, |ws| ws.set_document(lib.clone(), lib_text.clone()));
let mut rebuilt = Workspace::default();
own_folder_only(&mut rebuilt);
rebuilt.open_roots(vec![tree.path.clone()]);
rebuilt.set_document(top, top_text);
rebuilt.set_document(lib, lib_text);
rebuilt.rebuild_index();
same_tables(&incremental, &rebuilt, "an include spelled by a file the widen brought in");
}
#[test]
fn a_buffer_grown_past_the_threshold_leaves_the_index_when_the_scope_widens() {
// The one thing a widen takes *out*: a buffer on the large-file fast
// path contributes nothing, exactly as `collect_sources` says, so a
// file the index holds whose buffer has grown past the threshold is
// dropped — the same answer a whole rescan gives.
let tree = Tree::new("widenlarge");
tree.package("rtl/p.sv", "p_pkg");
tree.package("lib/q.sv", "q_pkg");
let small = crate::uri::path_to_uri(&tree.path.join("rtl/p.sv")).expect("uri");
let other = crate::uri::path_to_uri(&tree.path.join("lib/q.sv")).expect("uri");
let other_text = fs::read_to_string(tree.path.join("lib/q.sv")).expect("read");
let huge = filler(1_000);
let mut incremental = Workspace::default();
incremental.set_client_settings(ClientSettings {
large_file_threshold: 200,
index_scope_depth: 0,
..Default::default()
});
incremental.open_roots(vec![tree.path.clone()]);
incremental.set_document(small.clone(), "package p_pkg;\nendpackage\n".into());
incremental.rebuild_index();
assert_eq!(incremental.index().files().len(), 1, "premise: rtl/p.sv is indexed");
incremental.set_document(small.clone(), huge.clone());
assert!(incremental.document(&small).expect("open").large, "premise: the fast path");
widen(&mut incremental, |ws| ws.set_document(other.clone(), other_text.clone()));
assert_eq!(
incremental.index().files().len(),
1,
"the grown buffer left as the new folder arrived"
);
assert!(incremental.index().units("p_pkg").is_empty(), "and its names went with it");
let mut rebuilt = Workspace::default();
rebuilt.set_client_settings(ClientSettings {
large_file_threshold: 200,
index_scope_depth: 0,
..Default::default()
});
rebuilt.open_roots(vec![tree.path.clone()]);
rebuilt.set_document(small, huge);
rebuilt.set_document(other, other_text);
rebuilt.rebuild_index();
same_tables(&incremental, &rebuilt, "a buffer over the threshold at widen time");
}
#[test]
fn the_persistent_cache_answers_for_the_files_a_widen_brings_in() {
let tree = widen_tree("widencache");
let store = Tree::new("widencache_store");
let sub_path = tree.path.join("lib/sub.sv");
let sub = crate::uri::path_to_uri(&sub_path).expect("uri");
let sub_text = fs::read_to_string(&sub_path).expect("read");
let top = crate::uri::path_to_uri(&tree.path.join("rtl/top.sv")).expect("uri");
let top_text = fs::read_to_string(tree.path.join("rtl/top.sv")).expect("read");
// A first session fills the store with every file of both folders.
let mut first = Workspace::default();
first.set_client_settings(wide(caching(&store.path)));
first.open_roots(vec![tree.path.clone()]);
assert_eq!(first.index().files().len(), 6, "premise: the store is filled");
// A second session, folder-scoped, widens into `lib/`: the files it
// brings in come from the store rather than from a parse.
let mut second = Workspace::default();
second.set_client_settings(caching(&store.path));
second.open_roots(vec![tree.path.clone()]);
second.set_document(top, top_text);
second.rebuild_index();
let mut seen = Scan::default();
{
let mut see = |event: IndexEvent| match event {
IndexEvent::Parsing { path, .. } => seen.parsed.push(file_name(path)),
IndexEvent::Cached { path, .. } => seen.cached.push(file_name(path)),
IndexEvent::Analyzed { path, .. } => seen.analyzed.push(file_name(path)),
IndexEvent::Skipped { .. } => {}
};
let before = second.scope_dirs();
second.set_document(sub, sub_text);
let added: Vec<PathBuf> =
second.scope_dirs().iter().filter(|dir| !before.contains(dir)).cloned().collect();
second.widen_index_with(&added, &mut see);
}
seen.cached.sort();
assert_eq!(seen.cached, ["lib_defs.svh", "lib_pkg.sv"], "from the store: {seen:?}");
assert!(seen.parsed.is_empty(), "nothing was parsed twice: {seen:?}");
}
#[test]
fn a_widen_that_adds_nothing_new_still_refreshes_the_open_buffers() {
// A widen whose added directory holds no file the index lacks — the
// degenerate case, and the one where the open-buffer refresh is the
// *whole* of the work. It must still land the buffers' current text.
let tree = Tree::new("widenempty");
tree.package("rtl/a.sv", "a_pkg");
fs::create_dir_all(tree.path.join("empty")).expect("dir");
let a = crate::uri::path_to_uri(&tree.path.join("rtl/a.sv")).expect("uri");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.set_document(a.clone(), "package a_pkg;\n localparam K = 1;\nendpackage\n".into());
ws.rebuild_index();
ws.set_document(a, "package a_pkg;\n localparam EDITED = 1;\nendpackage\n".into());
ws.widen_index(from_ref(&tree.path.join("empty")));
assert_eq!(ws.index().member("a_pkg", "EDITED").len(), 1, "the live edit is indexed");
assert_eq!(ws.index().member("a_pkg", "K").len(), 0);
}
+133
View File
@@ -0,0 +1,133 @@
//! The closed-file view cache: the last few files an answer needed the
//! text of, held with their line index so that answering twice about one
//! file reads it once — and every rule that drops an entry.
use std::fs;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use vlog_parser::LineIndex;
use super::Workspace;
/// One **closed** workspace file's text and the line index over it, held by
/// [`Workspace`] just long enough that answering twice about the same file
/// reads it once.
///
/// Only closed files: an open buffer's own `Document` is the authority on its
/// text, and caching a second copy of it would be a way for the two to
/// disagree.
pub struct FileView {
/// The file this view was read from.
pub path: PathBuf,
/// Its text, as it was on disk when the view was made.
pub text: String,
/// The line index over exactly that text.
pub lines: LineIndex,
}
/// How many closed files the view cache holds, and how much text they may add
/// up to.
///
/// Two bounds, because they answer two different questions. `MAX_VIEWS` is how
/// many files one answer can name — a hover card names one or two, a
/// references list walks a handful before it moves on — and four is a handful.
/// `MAX_VIEW_BYTES` is the memory question, and it exists because the file
/// this cache is *for* can be tens of megabytes on its own: without it, four
/// netlists would be half a gigabyte of server. The newest view is kept
/// whatever it weighs, so a single huge file simply evicts everything else
/// rather than refusing to be cached at all.
pub(super) const MAX_VIEWS: usize = 4;
pub(super) const MAX_VIEW_BYTES: usize = 8 * 1024 * 1024;
impl Workspace {
/// One **closed** file's text and line index, read at most once per file
/// per generation of that file.
///
/// `None` for a file that cannot be read, and — deliberately — for one an
/// open buffer speaks for: that buffer's `Document` already holds both,
/// and a second copy here would be a second opinion. Callers that want
/// "whichever text is authoritative" ask `document_for_path` first, as
/// `locate` does.
///
/// **A cache, never a correctness input.** Every entry is dropped the
/// moment anything could have moved the file's text under it, and there
/// are exactly four such moments:
///
/// * [`Workspace::set_document`] — a `didOpen`/`didChange`/`didSave` for
/// that path; the buffer becomes the authority and the disk copy is no
/// longer what a reader wants;
/// * [`Workspace::close_document`] — the buffer stops being the authority,
/// and whatever was cached for that path predates the edits it may have
/// saved;
/// * [`Workspace::update_one`] — one file re-indexed, which is exactly the
/// claim that its bytes changed;
/// * [`Workspace::rebuild_index_with`] — a whole rescan, which claims
/// nothing about *which* file moved, so the whole cache goes;
/// * [`Workspace::begin_widen`] — a scope widen, which *does* name the
/// files it is about to read, so it drops those and leaves the rest.
///
/// What survives all four is a file changed on disk with nothing telling
/// this server so — and there the index's own spans are stale by the same
/// event, which is what `hover`'s `spells_exactly` guard exists for: a
/// stale view can only ever *omit* a snippet, never show a wrong line.
pub fn file_view(&self, path: &Path) -> Option<Rc<FileView>> {
if self.document_for_path(path).is_some() {
return None;
}
if let Some(hit) = self.cached_view(path) {
return Some(hit);
}
let text = fs::read_to_string(path).ok()?;
let view =
Rc::new(FileView { path: path.to_path_buf(), lines: LineIndex::new(&text), text });
let mut views = self.views.borrow_mut();
views.insert(0, Rc::clone(&view));
trim_views(&mut views);
Some(view)
}
/// The files the view cache is holding, newest first.
///
/// Test-only, and it exists for one question: whether an answer read a
/// file at all. A `Location` computed from the index alone must leave this
/// empty, which is the whole point of `locate::definition_location` — see
/// `docs/features/lazy-code-action/README.md`.
#[cfg(test)]
pub(crate) fn held_views(&self) -> Vec<PathBuf> {
self.views.borrow().iter().map(|view| view.path.clone()).collect()
}
/// The held view for `path`, moved to the front so the bounds below drop
/// whatever has gone longest unused.
fn cached_view(&self, path: &Path) -> Option<Rc<FileView>> {
let mut views = self.views.borrow_mut();
let at = views.iter().position(|view| view.path == path)?;
views[..=at].rotate_right(1);
views.first().cloned()
}
/// Drop whatever is held for one file. Called wherever that file's text
/// may have moved; see [`Workspace::file_view`] for the list.
pub(super) fn forget_view(&mut self, path: &Path) {
self.views.borrow_mut().retain(|view| view.path != path);
}
}
/// Cut the view cache back to its two bounds, newest first.
///
/// The newest view is kept whatever it weighs: one netlist-shaped file can
/// exceed the whole byte budget on its own, and a cache that refused to hold
/// it would be useless for exactly the file it exists for.
fn trim_views(views: &mut Vec<Rc<FileView>>) {
let mut bytes = 0usize;
let mut kept = 0usize;
for view in views.iter() {
bytes += view.text.len();
if kept == MAX_VIEWS || (kept > 0 && bytes > MAX_VIEW_BYTES) {
break;
}
kept += 1;
}
views.truncate(kept);
}
+65 -15
View File
@@ -31,11 +31,12 @@ use crate::state::{Document, Workspace};
use crate::uri::{path_to_uri, uri_to_path};
/// The class the cursor names, as the root of a type hierarchy — its own
/// declaration, or any use of its name.
/// declaration, or any use of its name — else the class whose body holds the
/// cursor (its base, on `super`).
///
/// `None` for every other position, which is what stops an editor from opening
/// an empty hierarchy view on a `wire`. A name that resolves to something other
/// than a class declines the same way: there is no node to stand on.
/// `None` outside every class, which is what stops an editor from opening an
/// empty hierarchy view on a module's `wire`: modules stay off the type
/// hierarchy.
///
/// A name two files declare returns *both* items rather than a guess, the same
/// answer `textDocument/definition` gives for the same ambiguity — the client
@@ -55,7 +56,47 @@ pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Option<Vec<TypeHierarc
// navigation uses: this file's own symbol table, then the workspace
// overlay.
let items = classes_at(ws, doc, uri, offset);
(!items.is_empty()).then_some(items)
if !items.is_empty() {
return Some(items);
}
// Anywhere else inside a class — a property, a method body, a keyword —
// the class that encloses the cursor is the node to stand on, and `super`
// names its base.
let positions = doc.positions();
let decl = enclosing_class(&doc.tree.items, offset)?;
let class = item(uri.clone(), &positions, decl)?;
if on_super(doc, offset) {
let bases = bases_of(ws, doc, uri, &class);
if !bases.is_empty() {
return Some(bases);
}
}
Some(vec![class])
}
/// The innermost class declaration whose extent holds `offset`, its end
/// included.
///
/// Read off the same [`classes::declarations`] walk every other answer here
/// uses, so a class that walk cannot see (one inside a generate block) is not
/// a node from the inside either.
fn enclosing_class(items: &[Item], offset: u32) -> Option<Decl<'_>> {
classes::declarations(items)
.into_iter()
.filter(|decl| decl.span.start <= offset && offset <= decl.span.end)
.min_by_key(|decl| decl.span.end - decl.span.start)
}
/// Whether the cursor is on `super`, the end of it included. The lexer reads
/// `super` as an identifier, so the token's text is what is asked.
fn on_super(doc: &Document, offset: u32) -> bool {
use vlog_parser::token::TokenKind;
let at = crate::state::first_token_reaching(&doc.tokens, offset);
doc.tokens.get(at).is_some_and(|token| {
matches!(token.kind, TokenKind::Ident | TokenKind::Keyword)
&& token.text == "super"
&& token.span.start <= offset
})
}
/// What this class extends: its base class, resolved in this file first and
@@ -409,8 +450,11 @@ endclass
}
}
/// Reversed by call-hierarchy-everywhere (2026-10-14): the `class`
/// keyword and a property are inside `base` and prepare it. A module
/// and its wire still prepare nothing — modules stay off this view.
#[test]
fn a_position_on_no_class_prepares_nothing() {
fn a_position_on_no_class_prepares_the_enclosing_one_or_nothing() {
let text = "\
class base;
int x;
@@ -421,8 +465,9 @@ module m;
endmodule
";
let (_tree, ws, uri) = workspace("none", &[("n.sv", text)]);
assert!(prepare(&ws, &uri, 0).is_none(), "the `class` keyword");
assert!(prepare(&ws, &uri, at(text, "int x") + 4).is_none(), "a property name");
let name = |offset| shape(&prepare(&ws, &uri, offset).expect("a class")[0]).0;
assert_eq!(name(0), "base", "the `class` keyword is inside `base`");
assert_eq!(name(at(text, "int x") + 4), "base", "a property name is inside `base`");
assert!(prepare(&ws, &uri, at(text, "module m") + 7).is_none(), "a module is not a class");
assert!(prepare(&ws, &uri, at(text, "wire w") + 5).is_none(), "a wire");
}
@@ -831,15 +876,21 @@ endclass
// QA (2026-08-26): prepare on the keyword, and name shadowing
// ------------------------------------------------------------------
/// Reversed by call-hierarchy-everywhere (2026-10-14): the keyword is
/// inside `child`'s header and prepares `child` — still not `base`.
#[test]
fn prepare_on_the_extends_keyword_itself_prepares_nothing() {
fn prepare_on_the_extends_keyword_itself_prepares_the_class_it_is_written_in() {
let text = "class base;\nendclass\nclass child extends base;\nendclass\n";
let (_tree, ws, uri) = workspace("keyword", &[("f.sv", text)]);
assert!(prepare(&ws, &uri, at(text, "extends") + 2).is_none(), "the keyword, not a name");
let items = prepare(&ws, &uri, at(text, "extends") + 2).expect("the enclosing class");
assert_eq!(shape(&items[0]).0, "child", "the keyword, not a name");
}
/// Reversed by call-hierarchy-everywhere (2026-10-14): the variable use
/// is inside `child` and prepares `child`. The point of the pin stands —
/// it never prepares the class `base` its text spells.
#[test]
fn a_class_name_shadowed_by_a_local_variable_prepares_the_variable_use_as_nothing() {
fn a_class_name_shadowed_by_a_local_variable_prepares_the_enclosing_class() {
// `base` is both a class and, inside `child`'s method, a local
// variable name. The use on the right-hand side of the assignment
// names the variable, not the class, and must not be treated as a
@@ -857,10 +908,9 @@ endclass
";
let (_tree, ws, uri) = workspace("shadow", &[("f.sv", text)]);
let use_offset = at(text, "base + 1");
assert!(
prepare(&ws, &uri, use_offset).is_none(),
"a local variable named `base`, not the class"
);
let items = prepare(&ws, &uri, use_offset).expect("the enclosing class");
assert_eq!(items.len(), 1);
assert_eq!(shape(&items[0]).0, "child", "a local variable named `base`, not the class");
}
// ------------------------------------------------------------------
+6 -2
View File
@@ -3398,7 +3398,9 @@ fn the_module_hierarchy_round_trips_over_the_wire_in_both_directions() {
"both sites of the same module, in one call"
);
assert_eq!(response(5)["result"], serde_json::Value::Null, "an instance name is no module");
// Reversed by call-hierarchy-everywhere (2026-10-14): an instance name
// prepares the module it instantiates.
assert_eq!(response(5)["result"][0]["name"], "hier_mid", "an instance name is its module");
let _ = std::fs::remove_dir_all(&dir);
}
@@ -4873,7 +4875,9 @@ fn the_class_hierarchy_round_trips_over_the_wire_in_both_directions() {
assert_eq!(subtypes[0]["uri"], leaf_uri.as_str());
assert_eq!(subtypes[0]["kind"], 5, "SymbolKind.Class");
assert_eq!(response(5)["result"], serde_json::Value::Null, "a property name is no class");
// Reversed by call-hierarchy-everywhere (2026-10-14): inside a class body
// the enclosing class answers.
assert_eq!(response(5)["result"][0]["name"], "type_mid", "a property is in its class");
let _ = std::fs::remove_dir_all(&dir);
}
@@ -4,7 +4,8 @@ use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_semantic::{ScopeKind, SymbolKind};
use vlog_parser::span::TextRange;
use vlog_semantic::{Duplicate, ScopeId, ScopeKind, Semantics, Symbol, SymbolKind};
/// See [`Rule::doc`].
pub struct DuplicateDeclaration;
@@ -60,7 +61,7 @@ impl Rule for DuplicateDeclaration {
let mut out = Vec::new();
for duplicate in semantics.duplicates() {
let Some(first) = semantics.symbol(duplicate.first) else { continue };
if !plain(duplicate.kind) || !plain(first.kind) {
if !collides(semantics, duplicate, first) {
continue;
}
let scope = semantics.scope(duplicate.scope).map(|scope| scope.kind);
@@ -85,6 +86,72 @@ impl Rule for DuplicateDeclaration {
}
}
/// Whether a declaration `duplicate` written after `first`, of one name in
/// one scope, is an error: both of a kind written once and once only
/// ([`plain`]); or a **block label** beside any other kind of declaration —
/// a net, a variable, a parameter, an instance, a port, a genvar, a typedef,
/// a function or task (a label and those share one namespace, IEEE 1800
/// §3.13); or two block labels unless both may be arms of one generate
/// `if`/`case`, of which only one elaborates (§27.5). A procedural block and
/// a `for` generate block are never such an arm, whichever comes first
/// (generate-label-rename F3, R4; review L-2).
fn collides(semantics: &Semantics, duplicate: &Duplicate, first: &Symbol) -> bool {
match (duplicate.kind == SymbolKind::Block, first.kind == SymbolKind::Block) {
(false, false) => plain(duplicate.kind) && plain(first.kind),
(true, true) => {
let second = shape_at(semantics, duplicate.scope, duplicate.name_span);
shape_of(semantics, first) != LabelShape::Arm || second != LabelShape::Arm
}
_ => true,
}
}
/// What a block label names, as far as two labels of one name may coexist.
#[derive(PartialEq)]
enum LabelShape {
/// A procedural `begin`/`fork` or a statement label.
Procedural,
/// A generate block that may be one arm of an `if`/`case`.
Arm,
/// A `for` generate block: its scope hangs off the loop header.
Loop,
}
/// The shape of a declared label, read off the scope it opened.
fn shape_of(semantics: &Semantics, label: &Symbol) -> LabelShape {
let Some(child) = label.child_scope.and_then(|id| semantics.scope(id)) else {
return LabelShape::Procedural;
};
match (child.kind, child.parent == Some(label.scope)) {
(ScopeKind::Generate, true) => LabelShape::Arm,
(ScopeKind::Generate, false) => LabelShape::Loop,
_ => LabelShape::Procedural,
}
}
/// The shape of a redeclared label, which owns no scope: read off the scope
/// written at its name — a generate scope of `declared_in` holding it is an
/// arm, unless a generate scope inside that one holds it too (a `for`
/// header, then its body). No scope holding it is a statement label.
fn shape_at(semantics: &Semantics, declared_in: ScopeId, name: TextRange) -> LabelShape {
let holding = |id: &ScopeId| {
semantics.scope(*id).filter(|s| s.span.start <= name.start && name.end <= s.span.end)
};
let Some(outer) =
semantics.scope(declared_in).and_then(|s| s.children.iter().find_map(holding))
else {
return LabelShape::Procedural;
};
if outer.kind != ScopeKind::Generate {
return LabelShape::Procedural;
}
let inner = outer.children.iter().filter_map(holding).any(|s| s.kind == ScopeKind::Generate);
match inner {
true => LabelShape::Loop,
false => LabelShape::Arm,
}
}
/// True for the declaration kinds that may be written **once** and once only.
///
/// Everything left out has a legal shape in which the same name is written
@@ -122,6 +189,55 @@ mod tests {
DuplicateDeclaration.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_block_label_beside_a_net_of_its_name_either_way_round() {
let label_second = "module m;\n logic g;\n if (1) begin : g\n end\nendmodule\n";
let label_first = "module m;\n if (1) begin : g\n end\n logic g;\nendmodule\n";
for src in [label_second, label_first] {
let found = violations(src);
assert_eq!(found.len(), 1, "{src}: {found:?}");
assert!(found[0].message.contains("`g`"), "{}", found[0].message);
}
}
#[test]
fn flags_a_block_label_beside_any_declaration_and_two_procedural_labels() {
for src in [
"module m (input logic g);\n if (1) begin : g\n end\nendmodule\n",
"module m (g);\n input g;\n if (1) begin : g\n end\nendmodule\n",
"module m;\n genvar g;\n if (1) begin : g\n end\nendmodule\n",
"module m;\n typedef logic g;\n if (1) begin : g\n end\nendmodule\n",
"module m;\n function void g();\n endfunction\n if (1) begin : g\n end\nendmodule\n",
"module m;\n task g();\n endtask\n if (1) begin : g\n end\nendmodule\n",
"module m;\n initial begin : g\n end\n initial begin : g\n end\nendmodule\n",
] {
let found = violations(src);
assert_eq!(found.len(), 1, "{src}: {found:?}");
}
}
#[test]
fn two_arms_carrying_one_label_are_not_a_duplicate() {
let src = "module m;\n if (1) begin : g\n end else begin : g\n end\nendmodule\n";
assert!(violations(src).is_empty());
let case = "module m;\n case (1)\n 0: begin : g\n end\n default: begin : g\n end\n endcase\nendmodule\n";
assert!(violations(case).is_empty());
}
/// Review L-2: a `for` generate block is never an arm, and a procedural
/// block beside a generate block is flagged whichever comes first.
#[test]
fn flags_sibling_loops_and_a_procedural_block_beside_a_generate_one() {
let lp = " for (genvar i = 0; i < 2; i++) begin : g\n end\n";
let arm = " if (1) begin : g\n end\n";
let proc = " initial begin : g\n end\n";
for (one, two) in [(lp, lp), (arm, lp), (lp, arm), (proc, arm), (arm, proc)] {
let src = format!("module m;\n{one}{two}endmodule\n");
let found = violations(&src);
assert_eq!(found.len(), 1, "{src}: {found:?}");
}
}
#[test]
fn flags_two_signals_of_one_name() {
let src = "module m;\n logic a;\n logic a;\nendmodule\n";
@@ -190,6 +190,14 @@ mod tests {
assert_eq!(names_in_a_project(src, &[]), names(src), "an empty project changes nothing");
}
#[test]
fn a_block_label_spelled_like_a_net_is_not_a_read_of_it() {
// generate-label-rename F3: the colliding label is a
// `duplicate-declaration`, never a use of the net.
let src = "module m;\n wire g;\n if (1) begin : g\n end\nendmodule\n";
assert!(names(src).is_empty(), "{:?}", names(src));
}
#[test]
fn a_read_but_undriven_signal_is_reported() {
let src = "module m (output logic q);\n wire a;\n assign q = a;\nendmodule\n";
+6 -7
View File
@@ -41,7 +41,7 @@ use vlog_semantic::{
use super::ledger::{pieces_match, Split};
use super::{anchor_of, Anchor, Shifts};
use crate::rename::sites::{binds_implicitly, may_connect_implicitly, nearest, sites, Site};
use crate::rename::{display, Scope};
use crate::rename::Scope;
use crate::TextEdit;
/// The rename's lexical contract for a file whose edits insert connection
@@ -53,10 +53,9 @@ pub(super) fn insertions_match(
after: &str,
edits: &[TextEdit],
names: [&str; 2],
path: &Path,
shown: &str,
) -> Result<(), String> {
let refusal =
|what: &str| format!("the rename would {what} in {}; no edits were made.", display(path));
let refusal = |what: &str| format!("the rename would {what} in {shown}; no edits were made.");
let Ok(old_tokens) = tokenize(before) else {
return Err(refusal("edit a file lucisv cannot lex"));
};
@@ -74,8 +73,8 @@ pub(super) fn insertions_match(
return Err(refusal(&outside));
}
}
let split = Split::read(before, after, edits, path, "the rename")?;
pieces_match(&split, edits, path, "the rename")?;
let split = Split::read(before, after, edits, shown, "the rename")?;
pieces_match(&split, edits, shown, "the rename")?;
let grew = parse_source_tolerant(after).1.len() > parse_source_tolerant(before).1.len();
match grew {
true => Err(refusal("leave a connection list that does not parse")),
@@ -340,7 +339,7 @@ pub(super) fn bindings_match(
let [old, new] = names;
return Err(format!(
"renaming `{old}` to `{new}` would change what an implicit connection of `{instance}` binds in {}; the rename was abandoned.",
display(path)
scope.name_of(path)
));
}
}
+22 -41
View File
@@ -9,13 +9,11 @@
//! the whole of it.
use std::collections::HashMap;
use std::path::Path;
use vlog_parser::span::TextRange;
use vlog_parser::token::TokenKind;
use vlog_parser::tokenize;
use crate::rename::display;
use crate::TextEdit;
use super::{Moving, Origin};
@@ -77,14 +75,11 @@ impl Split {
before: &str,
after: &str,
edits: &[TextEdit],
path: &Path,
shown: &str,
what: &str,
) -> Result<Split, String> {
let (Some(old), Some(new)) = (pieces(before), pieces(after)) else {
return Err(format!(
"{} would no longer lex after {what}; no edits were made.",
display(path)
));
return Err(format!("{} would no longer lex after {what}; no edits were made.", shown));
};
let mut written: Vec<Vec<(TextRange, Piece)>> = Vec::new();
for edit in edits {
@@ -103,7 +98,7 @@ impl Split {
pub(super) fn positions_match(
&self,
edits: &[TextEdit],
path: &Path,
shown: &str,
what: &str,
) -> Result<(), String> {
let clone = |pieces: &[(TextRange, Piece)]| -> Vec<Piece> {
@@ -144,14 +139,14 @@ impl Split {
"{what} would write {} where {} belongs in {}; no edits were made.",
actual.describe(),
expected.describe(),
display(path)
shown
))
}
None => {
return Err(format!(
"{what} would lose {} in {}; no edits were made.",
expected.describe(),
display(path)
shown
))
}
}
@@ -160,7 +155,7 @@ impl Split {
let extra = actual.get(expected.len()).map_or_else(String::new, Piece::describe);
return Err(format!(
"{what} would add {extra} to {}, which is not part of the edit; no edits were made.",
display(path)
shown
));
}
Ok(())
@@ -174,12 +169,12 @@ impl Split {
pub(super) fn pieces_match(
split: &Split,
edits: &[TextEdit],
path: &Path,
shown: &str,
what: &str,
) -> Result<(), String> {
let ledger = Ledger::of(split, edits, TextRange::empty(0));
ledger.check(&display(path), what, &Tally::new())?;
split.positions_match(edits, path, what)
ledger.check(shown, what, &Tally::new())?;
split.positions_match(edits, shown, what)
}
/// The range the move takes text out of file `i`, if it names that file as one
@@ -545,7 +540,7 @@ fn and_list(names: &[String]) -> String {
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use super::*;
use crate::apply;
@@ -556,11 +551,11 @@ mod tests {
before: &str,
after: &str,
edits: &[TextEdit],
path: &Path,
shown: &str,
what: &str,
) -> Result<(), String> {
let split = Split::read(before, after, edits, path, what)?;
super::pieces_match(&split, edits, path, what)
let split = Split::read(before, after, edits, shown, what)?;
super::pieces_match(&split, edits, shown, what)
}
// ------------------------------------------------------------------
@@ -587,7 +582,7 @@ mod tests {
}
fn splice_attack(corrupted: &str) -> Result<(), String> {
pieces_match(PORTS, corrupted, &add_edits(), Path::new("/rtl/m.sv"), "adding port `cfg`")
pieces_match(PORTS, corrupted, &add_edits(), "m.sv", "adding port `cfg`")
}
#[test]
@@ -642,7 +637,7 @@ mod tests {
let at = text.find("hello").expect("string") as u32;
let edits = vec![TextEdit { range: TextRange::empty(at), new_text: "x".into() }];
let corrupted = apply(text, &edits);
let outcome = pieces_match(text, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit");
let outcome = pieces_match(text, &corrupted, &edits, "m.sv", "an edit");
assert!(outcome.is_err(), "the string's own text is not a token lucisv may write");
}
@@ -654,8 +649,7 @@ mod tests {
let end = PORTS.find("*/").expect("comment") as u32 + 2;
let edits = vec![TextEdit { range: TextRange::new(start, end), new_text: String::new() }];
let corrupted = apply(PORTS, &edits);
let outcome =
pieces_match(PORTS, &corrupted, &edits, Path::new("/rtl/m.sv"), "removing port `rst`");
let outcome = pieces_match(PORTS, &corrupted, &edits, "m.sv", "removing port `rst`");
let message = outcome.expect_err("a deleted comment is a refusal");
assert!(message.contains("comments are never dropped"), "{message}");
}
@@ -690,13 +684,7 @@ mod tests {
}
fn move_attack(corrupted: &str) -> Result<(), String> {
pieces_match(
MOVED,
corrupted,
&move_edits(),
Path::new("/rtl/m.sv"),
"converting `m`'s ports to ANSI",
)
pieces_match(MOVED, corrupted, &move_edits(), "m.sv", "converting `m`'s ports to ANSI")
}
#[test]
@@ -773,7 +761,7 @@ mod tests {
];
let corrupted = apply(SHARED, &edits);
assert_eq!(corrupted.matches("// both").count(), 2, "the attack really doubles it");
let message = pieces_match(SHARED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit")
let message = pieces_match(SHARED, &corrupted, &edits, "m.sv", "an edit")
.expect_err("a doubled comment is a refusal");
assert!(message.contains("would write the comment"), "{message}");
}
@@ -786,7 +774,7 @@ mod tests {
let end = MOVED.find("\n output").expect("output") as u32;
let edits = vec![TextEdit { range: TextRange::new(start, end), new_text: String::new() }];
let corrupted = apply(MOVED, &edits);
let message = pieces_match(MOVED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit")
let message = pieces_match(MOVED, &corrupted, &edits, "m.sv", "an edit")
.expect_err("a deleted comment nothing writes back is a refusal");
assert!(message.contains("comments are never dropped"), "{message}");
}
@@ -812,7 +800,7 @@ mod tests {
];
let corrupted = apply(SHARED, &edits);
assert_eq!(corrupted.matches("// shared").count(), 3, "the attack really triples it");
let message = pieces_match(SHARED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit")
let message = pieces_match(SHARED, &corrupted, &edits, "m.sv", "an edit")
.expect_err("a duplicated comment is a refusal");
assert!(message.contains("comments are never duplicated"), "{message}");
}
@@ -832,8 +820,7 @@ mod tests {
}];
let spliced = apply(source, &edits);
assert_eq!(spliced.matches("TODO").count(), 2, "{spliced}");
let outcome =
pieces_match(source, &spliced, &edits, Path::new("/rtl/top.sv"), "adding port `b`");
let outcome = pieces_match(source, &spliced, &edits, "top.sv", "adding port `b`");
assert_eq!(outcome, Ok(()), "a generated placeholder is the engine's own text");
}
@@ -889,13 +876,7 @@ mod tests {
fn attribute_attack(edits: &[TextEdit]) -> Result<(), String> {
let corrupted = apply(ATTRIBUTED, edits);
pieces_match(
ATTRIBUTED,
&corrupted,
edits,
Path::new("/rtl/m.sv"),
"converting `m`'s ports to ANSI",
)
pieces_match(ATTRIBUTED, &corrupted, edits, "m.sv", "converting `m`'s ports to ANSI")
}
#[test]
+23 -21
View File
@@ -21,6 +21,10 @@ mod after;
mod implicit;
mod ledger;
#[cfg(test)]
mod qa_block_attacks;
#[cfg(test)]
mod qa_block_paths;
#[cfg(test)]
mod qa_implicit;
use std::collections::HashMap;
@@ -33,7 +37,7 @@ use vlog_semantic::{
ExternalResolutions, ExternalTarget, ReferenceId, Semantics, SymbolKind, WorkspaceIndex,
};
use crate::rename::{contains_word, display, Scope};
use crate::rename::{contains_word, Scope};
use crate::trace::VerifyTrace;
use crate::{apply, Shift, TextEdit};
@@ -108,7 +112,7 @@ pub(crate) fn verify(
if let Some(what) = before.first_difference(&after) {
return Err(format!(
"renaming `{old_name}` to `{new_name}` would change what {what} means in {}; the rename was abandoned.",
display(path)
scope.name_of(path)
));
}
}
@@ -134,9 +138,10 @@ fn tokens_verified(
) -> Result<(), String> {
for ((i, edits), (path, text)) in edits.iter().zip(edited) {
let Some(before) = scope.text(*i) else { return Err(ABANDONED.to_string()) };
let shown = scope.name_of(path);
stage.measure(|| match edits.iter().any(|e| e.range.is_empty()) {
true => implicit::insertions_match(before, text, edits, names, path),
false => tokens_match(before, text, &Shift::new(edits), names[1], path),
true => implicit::insertions_match(before, text, edits, names, &shown),
false => tokens_match(before, text, &Shift::new(edits), names[1], &shown),
})?;
}
Ok(())
@@ -295,23 +300,24 @@ pub(crate) fn verify_move(
if edits.iter().any(|(i, _)| *i == copied.file) {
return Err(format!(
"{what} would edit {}, which it only copies out of; no edits were made.",
display(path)
scope.name_of(path)
));
}
transit.copy(&display(path), text, copied.region, what)?;
transit.copy(&scope.name_of(path), text, copied.region, what)?;
}
for ((i, edits), (path, text)) in edits.iter().zip(&edited) {
let Some(before) = scope.text(*i) else { return Err(abandoned) };
let split = Split::read(before, text, edits, path, what)?;
let shown = scope.name_of(path);
let split = Split::read(before, text, edits, &shown, what)?;
match region_of(moving, *i) {
// A file the move names balances against the pieces in transit
// rather than on its own; its positional comparison is unchanged.
Some(region) => {
transit.add(&display(path), region, &split, edits);
split.positions_match(edits, path, what)?;
transit.add(&scope.name_of(path), region, &split, edits);
split.positions_match(edits, &shown, what)?;
}
None => pieces_match(&split, edits, path, what)?,
None => pieces_match(&split, edits, &shown, what)?,
}
// A tolerant parse of a file that was already broken still reports its
// old diagnostics, so the bar is "no *new* one", not "none".
@@ -320,7 +326,7 @@ pub(crate) fn verify_move(
if after_count > before_count {
return Err(format!(
"{what} would leave {} unparseable; no edits were made.",
display(path)
scope.name_of(path)
));
}
}
@@ -360,7 +366,7 @@ pub(crate) fn verify_move(
if let Some(what_moved) = before.first_difference(&after) {
return Err(format!(
"{what} would change what {what_moved} means in {}; no edits were made.",
display(path)
scope.name_of(path)
));
}
}
@@ -437,16 +443,12 @@ fn tokens_match(
after: &str,
shift: &Shift,
new_name: &str,
path: &Path,
shown: &str,
) -> Result<(), String> {
let refusal = |what: &str| {
format!("the rename would change {what} in {}; no edits were made.", display(path))
};
let refusal =
|what: &str| format!("the rename would change {what} in {shown}; no edits were made.");
let (Ok(old), Ok(new)) = (tokenize(before), tokenize(after)) else {
return Err(format!(
"{} would no longer lex after the rename; no edits were made.",
display(path)
));
return Err(format!("{shown} would no longer lex after the rename; no edits were made."));
};
if old.len() != new.len() {
return Err(refusal("the token stream's shape"));
@@ -651,7 +653,7 @@ mod tests {
fn attack(corrupted: &str) -> Result<(), String> {
let edits = rename_edits();
tokens_match(SOURCE, corrupted, &Shift::new(&edits), "sig", Path::new("/rtl/m.sv"))
tokens_match(SOURCE, corrupted, &Shift::new(&edits), "sig", "m.sv")
}
#[test]
@@ -0,0 +1,175 @@
//! QA re-attack (TODO §65.1, CLAUDE.md invariant 4) on the rename verifier
//! over block labels, beyond the dev's `qa_block_paths`: corrupted outputs
//! that rename an unrelated block of the same name, rebind a path to another
//! module's block, split a same-label pair of arms, or let a genvar capture
//! a path written inside the loop. Each lexes and parses; each must be
//! refused. `docs/features/generate-label-rename/README.md`, QA log.
use std::path::{Path, PathBuf};
use vlog_parser::span::TextRange;
use super::verify;
use crate::rename::Scope;
use crate::trace::VerifyTrace;
use crate::TextEdit;
/// Two modules, each with its own `g_lane`, both instantiated in `top`.
const SUB: &str = "module sub (input logic clk);
for (genvar i = 0; i < 2; i++) begin : g_lane
logic sig;
assign sig = clk;
end : g_lane
endmodule
";
const OTHER: &str = "module other (input logic clk);
for (genvar i = 0; i < 2; i++) begin : g_lane
logic sig;
assign sig = clk;
end : g_lane
endmodule
";
const TOP: &str = "module top (input logic clk, output logic o, output logic p);
sub u_x (.clk);
other u_y (.clk);
assign o = u_x.g_lane[1].sig;
assign p = u_y.g_lane[0].sig;
endmodule
";
/// Both arms of a generate `if` carry one label, each closed by it.
const ARMS: &str = "module arms #(parameter bit P = 0) (output logic o);
if (P) begin : g_arm
logic q;
end : g_arm
else begin : g_arm
logic q;
end : g_arm
assign o = g_arm.q;
endmodule
";
/// A path to the loop's own block written inside the loop's body.
const INSIDE: &str = "module inside (output logic o);
for (genvar gi = 0; gi < 2; gi++) begin : g_lane
logic sig;
assign sig = g_lane[0].sig;
end
assign o = g_lane[1].sig;
endmodule
";
/// A rename's edit at the `n`th (0-based) whole-word `name` in `text`.
fn at_word(text: &str, name: &str, n: usize, new: &str) -> TextEdit {
let is_word = |b: Option<&u8>| b.is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_');
let bytes = text.as_bytes();
let start = text
.match_indices(name)
.map(|(i, _)| i)
.filter(|&i| {
!is_word(i.checked_sub(1).and_then(|p| bytes.get(p)))
&& !is_word(bytes.get(i + name.len()))
})
.nth(n)
.expect("occurrence");
TextEdit {
range: TextRange::new(start as u32, (start + name.len()) as u32),
new_text: new.into(),
}
}
/// `verify` over `files` with the given edits, keyed by file name.
fn verdict(
files: &[(&str, &str)],
edits: &[(&str, Vec<TextEdit>)],
old: &str,
new: &str,
) -> Result<(), String> {
let sources: Vec<(PathBuf, String)> =
files.iter().map(|(name, text)| (Path::new("/rtl").join(name), text.to_string())).collect();
let mut scope = Scope::build(&sources);
let mut keyed: Vec<(usize, Vec<TextEdit>)> = edits
.iter()
.map(|(name, edits)| {
let i = scope.index_of(&Path::new("/rtl").join(name)).expect("in scope");
(i, edits.clone())
})
.collect();
keyed.sort_by_key(|(i, _)| *i);
verify(&mut scope, &keyed, old, new, &mut VerifyTrace::default())
}
fn three() -> Vec<(&'static str, &'static str)> {
vec![("sub.sv", SUB), ("other.sv", OTHER), ("top.sv", TOP)]
}
/// The honest rename of `sub`'s `g_lane`: its label, its closing label and
/// `u_x`'s path — never `other`'s block or `u_y`'s path.
fn honest() -> Vec<(&'static str, Vec<TextEdit>)> {
vec![
("sub.sv", (0..2).map(|n| at_word(SUB, "g_lane", n, "g_ln")).collect()),
("top.sv", vec![at_word(TOP, "g_lane", 0, "g_ln")]),
]
}
#[test]
fn the_honest_rename_of_one_modules_block_verifies() {
assert_eq!(verdict(&three(), &honest(), "g_lane", "g_ln"), Ok(()));
}
/// Not a corruption, and pinned as such: a rename that *also* moves an
/// unrelated same-named block together with every use of it changes no
/// meaning, and the verifier is a meaning check — it accepts it exactly as it
/// accepts the same shape for a net (`sig` in both modules). That the engine
/// never produces this edit is pinned by `tests/qa_generate_label.rs`
/// (`a_same_named_block_in_another_module_is_never_touched`).
#[test]
fn a_rename_that_also_moved_the_other_modules_block_consistently_is_meaning_preserving() {
let mut edits = honest();
edits.push(("other.sv", (0..2).map(|n| at_word(OTHER, "g_lane", n, "g_ln")).collect()));
edits[1].1.push(at_word(TOP, "g_lane", 1, "g_ln"));
assert_eq!(verdict(&three(), &edits, "g_lane", "g_ln"), Ok(()));
let mut nets = vec![
("sub.sv", (0..2).map(|n| at_word(SUB, "sig", n, "sg")).collect::<Vec<_>>()),
("top.sv", vec![at_word(TOP, "sig", 0, "sg")]),
];
nets.push(("other.sv", (0..2).map(|n| at_word(OTHER, "sig", n, "sg")).collect()));
nets[1].1.push(at_word(TOP, "sig", 1, "sg"));
assert_eq!(verdict(&three(), &nets, "sig", "sg"), Ok(()), "the same for a net");
}
#[test]
fn a_rename_that_moved_the_other_instances_path_instead_is_rejected() {
let edits = vec![
("sub.sv", (0..2).map(|n| at_word(SUB, "g_lane", n, "g_ln")).collect()),
("top.sv", vec![at_word(TOP, "g_lane", 1, "g_ln")]),
];
assert!(verdict(&three(), &edits, "g_lane", "g_ln").is_err(), "`u_y.g_ln` names nothing");
}
#[test]
fn a_rename_of_one_arm_of_a_same_label_pair_is_rejected() {
// The first arm's labels and the path move; the second arm keeps
// `g_arm`, so the pair no longer names one block.
let edits = vec![(
"arms.sv",
vec![0, 1, 4].into_iter().map(|n| at_word(ARMS, "g_arm", n, "g_x")).collect(),
)];
assert!(verdict(&[("arms.sv", ARMS)], &edits, "g_arm", "g_x").is_err());
// …and the second arm's closing label alone left behind.
let edits =
vec![("arms.sv", (0..3).chain([4]).map(|n| at_word(ARMS, "g_arm", n, "g_x")).collect())];
assert!(verdict(&[("arms.sv", ARMS)], &edits, "g_arm", "g_x").is_err());
// The honest one: all five.
let edits = vec![("arms.sv", (0..5).map(|n| at_word(ARMS, "g_arm", n, "g_x")).collect())];
assert_eq!(verdict(&[("arms.sv", ARMS)], &edits, "g_arm", "g_x"), Ok(()));
}
#[test]
fn a_rename_to_the_genvar_that_captures_the_path_inside_the_loop_is_rejected() {
// `g_lane` → `gi`: inside the body `gi[0].sig` would name the genvar.
let edits = vec![("inside.sv", (0..3).map(|n| at_word(INSIDE, "g_lane", n, "gi")).collect())];
assert!(verdict(&[("inside.sv", INSIDE)], &edits, "g_lane", "gi").is_err());
}
@@ -0,0 +1,140 @@
//! TODO §65.1: masked-corruption attacks on the rename verifier over paths
//! through a block label (CLAUDE.md invariant 4).
//!
//! The verifier gained **no** normalization for block labels: a closing label
//! and a path segment are ordinary references now (`vlog_semantic` binds them
//! — `docs/features/generate-label-rename/README.md`), so the unchanged
//! resolution print compares them like any other use. These attacks pin that
//! it does: each hands `verify` a rename of `g_lane` → `g_ln` with one site
//! left out, rewritten wrongly or rewritten where no reference is, every one
//! of which lexes, parses and — before §65.1 — verified clean.
//!
//! Crate-internal because `verify` is.
use std::path::{Path, PathBuf};
use vlog_parser::span::TextRange;
use super::verify;
use crate::rename::Scope;
use crate::trace::VerifyTrace;
use crate::TextEdit;
const SUB: &str = "module sub (input logic clk, output logic o);
for (genvar i = 0; i < 2; i++) begin : g_lane
logic sig;
assign sig = clk;
end : g_lane
assign o = g_lane[0].sig;
// g_lane in a comment
endmodule
";
const TOP: &str = "module top (input logic clk, output logic o);
sub u_x (.clk, .o());
assign o = u_x.g_lane[1].sig;
endmodule
";
/// A rename's edit at the `n`th (0-based) whole-word `name` in `text`.
fn at_word(text: &str, name: &str, n: usize, new: &str) -> TextEdit {
let is_word = |b: Option<&u8>| b.is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_');
let bytes = text.as_bytes();
let start = text
.match_indices(name)
.map(|(i, _)| i)
.filter(|&i| {
!is_word(i.checked_sub(1).and_then(|p| bytes.get(p)))
&& !is_word(bytes.get(i + name.len()))
})
.nth(n)
.expect("occurrence");
TextEdit {
range: TextRange::new(start as u32, (start + name.len()) as u32),
new_text: new.into(),
}
}
/// `verify` over SUB and TOP with the given edits, keyed by file name.
fn verdict(edits: &[(&str, Vec<TextEdit>)]) -> Result<(), String> {
let files = vec![
(PathBuf::from("/rtl/sub.sv"), SUB.to_string()),
(PathBuf::from("/rtl/top.sv"), TOP.to_string()),
];
let mut scope = Scope::build(&files);
let mut keyed: Vec<(usize, Vec<TextEdit>)> = edits
.iter()
.map(|(name, edits)| {
let i = scope.index_of(&Path::new("/rtl").join(name)).expect("in scope");
(i, edits.clone())
})
.collect();
keyed.sort_by_key(|(i, _)| *i);
verify(&mut scope, &keyed, "g_lane", "g_ln", &mut VerifyTrace::default())
}
/// The honest edits: the label, its closing label and both path segments —
/// SUB's first, second and third `g_lane` (the fourth is the comment).
fn honest() -> Vec<(&'static str, Vec<TextEdit>)> {
vec![
("sub.sv", (0..3).map(|n| at_word(SUB, "g_lane", n, "g_ln")).collect()),
("top.sv", vec![at_word(TOP, "g_lane", 0, "g_ln")]),
]
}
#[test]
fn the_honest_rename_verifies() {
assert_eq!(verdict(&honest()), Ok(()));
}
#[test]
fn a_rename_that_left_the_same_file_path_segment_is_rejected() {
let mut edits = honest();
edits[0].1.remove(2);
assert!(verdict(&edits).is_err(), "`g_lane[0].sig` would name nothing");
}
#[test]
fn a_rename_that_left_the_closing_label_is_rejected() {
let mut edits = honest();
edits[0].1.remove(1);
assert!(verdict(&edits).is_err(), "`end : g_lane` would close `begin : g_ln`");
}
#[test]
fn a_rename_that_left_the_other_files_path_is_rejected() {
let mut edits = honest();
edits.remove(1);
assert!(verdict(&edits).is_err(), "`u_x.g_lane[1].sig` would name nothing");
}
#[test]
fn a_rename_of_the_paths_alone_is_rejected() {
let edits = vec![
("sub.sv", vec![at_word(SUB, "g_lane", 2, "g_ln")]),
("top.sv", vec![at_word(TOP, "g_lane", 0, "g_ln")]),
];
assert!(verdict(&edits).is_err(), "the paths would name a block that does not exist");
}
#[test]
fn a_rename_that_also_rewrote_the_comment_is_rejected() {
let mut edits = honest();
edits[0].1.push(at_word(SUB, "g_lane", 3, "g_ln"));
assert!(verdict(&edits).is_err(), "a comment never changes");
}
#[test]
fn a_rename_that_rewrote_a_segment_to_a_different_name_is_rejected() {
let mut edits = honest();
edits[1].1 = vec![at_word(TOP, "g_lane", 0, "g_other")];
assert!(verdict(&edits).is_err(), "every edited token spells the new name");
}
#[test]
fn a_rename_that_also_rewrote_the_member_after_the_segment_is_rejected() {
let mut edits = honest();
let sig = at_word(TOP, "sig", 0, "g_ln");
edits[1].1.push(sig);
assert!(verdict(&edits).is_err(), "`.sig` is another declaration's reference");
}
+4 -11
View File
@@ -16,14 +16,11 @@
//! work log.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use vlog_parser::ast::{ItemKind, SourceFile};
use vlog_parser::span::TextRange;
use vlog_semantic::{Resolution, Semantics, SymbolId, SymbolKind};
use crate::rename::display;
use super::flow;
use super::region::Region;
use super::render::{self, Param, Port};
@@ -148,18 +145,14 @@ impl Crossing {
pub(super) fn warnings(
&self,
new_name: &str,
created: &Option<PathBuf>,
file: &Path,
created: Option<&str>,
file: &str,
) -> Vec<String> {
let mut out = Vec::new();
out.push(match created {
Some(path) => format!(
"`{new_name}` was written to a new file, `{}`.",
display(path)
),
Some(path) => format!("`{new_name}` was written to a new file, `{path}`."),
None => format!(
"`{new_name}` was written below its neighbour in `{}`: this editor did not say it can create files, so lucisv did not make one.",
display(file)
"`{new_name}` was written below its neighbour in `{file}`: this editor did not say it can create files, so lucisv did not make one."
),
});
out.push(format!(
+4 -2
View File
@@ -254,7 +254,9 @@ impl Extraction {
out.push((path.to_path_buf(), file_edits));
}
out.sort_by(|a, b| a.0.cmp(&b.0));
Ok(Extraction { edits: out, warnings: crossing.warnings(new_name, &created, file) })
let created = created.as_deref().map(|path| scope.name_of(path));
let warnings = crossing.warnings(new_name, created.as_deref(), &scope.name_of(file));
Ok(Extraction { edits: out, warnings })
}
}
@@ -285,7 +287,7 @@ fn confirm(
if ports != wanted_ports || params != wanted_params {
return Err(format!(
"{what} would not leave `{new_name}` with the header lucisv intended in {}; no edits were made.",
display(path)
scope.name_of(path)
));
}
return Ok(());
+6 -8
View File
@@ -114,7 +114,7 @@ pub fn inline_module(
let mut scope = Scope::build(files);
let Some(here) = scope.index_of(file) else { return Err(not_in_scope(file)) };
let Some(text) = scope.text(here) else { return Err(not_in_scope(file)) };
let tree = parsed(text, file)?;
let tree = parsed(text, &scope.name_of(file))?;
let Some(found) = Site::read(&tree, text, offset) else { return Err(NOTHING.to_string()) };
let site = found?;
@@ -126,7 +126,7 @@ pub fn inline_module(
let there = declaring_file(&scope, here, &site)?;
let Some(source_text) = scope.text(there) else { return Err(abandoned(&site)) };
let source_path = scope.path(there).unwrap_or(Path::new("?")).to_path_buf();
let source_tree = parsed(source_text, &source_path)?;
let source_tree = parsed(source_text, &scope.name_of(&source_path))?;
let source = Source::read(&source_tree, source_text, scope.index(), &site.target)?;
same_timescale(text, source_text, &site.target)?;
no_hierarchy(&scope, &site)?;
@@ -222,7 +222,7 @@ fn declaring_file(scope: &Scope<'_>, here: usize, site: &Site<'_>) -> Result<usi
return Err(format!(
"`{}` is declared in {}, which is not one of the files lucisv was given.",
site.target,
display(path)
scope.name_of(path)
));
};
match there == here {
@@ -292,7 +292,7 @@ fn no_hierarchy(scope: &Scope<'_>, site: &Site<'_>) -> Result<(), String> {
return Err(format!(
"`{}` is named as a scope of the design hierarchy in {}, and inlining it dissolves the scope that path walks through; no edits were made.",
site.instance,
display(path)
scope.name_of(path)
));
}
}
@@ -304,15 +304,13 @@ fn no_hierarchy(scope: &Scope<'_>, site: &Site<'_>) -> Result<(), String> {
// odds and ends
// ----------------------------------------------------------------------
fn parsed(text: &str, path: &Path) -> Result<vlog_parser::ast::SourceFile, String> {
fn parsed(text: &str, shown: &str) -> Result<vlog_parser::ast::SourceFile, String> {
let (tree, diagnostics) = parse_source_tolerant(text);
match diagnostics.first() {
None => Ok(tree),
Some(problem) => Err(format!(
"{} does not parse ({} at line {}), so lucisv will not inline through it.",
display(path),
problem.message,
problem.line
shown, problem.message, problem.line
)),
}
}
+2 -2
View File
@@ -59,8 +59,8 @@ pub use ports::{
PortOfferKind,
};
pub use rename::{
contains_word, prepare_rename, prepare_rename_here, rename, rename_name_at, rename_preflight,
rename_traced, rename_traced_with, KnownFacts, RenameTarget,
contains_word, home_set, prepare_rename, prepare_rename_here, rename, rename_name_at,
rename_preflight, rename_traced, rename_traced_with, KnownFacts, RenameTarget,
};
pub use trace::{IndexTrace, RenameTrace, Stage, VerifyTrace, WarnTrace};
+23 -23
View File
@@ -3,14 +3,12 @@
//! non-ANSI, empty, or none), guarded against landing inside an `` `ifdef``
//! arm; and the connection every instantiation in scope gains.
use std::path::Path;
use vlog_parser::ast::{Connections, Instance, ItemKind, ListElem, Module, PortList};
use vlog_parser::span::TextRange;
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::{parse_source_tolerant, tokenize, LineIndex};
use crate::rename::{display, Scope};
use crate::rename::Scope;
use crate::TextEdit;
use super::find::{
@@ -96,8 +94,9 @@ pub(super) fn plan_add(
return Err(format!("`{}` already has a port named `{}`.", site.name, port.name));
}
let Some(path) = scope.path(site.file) else { return Err(not_indexed(&site.name)) };
let tokens = tokenize(text).map_err(|_| lex_failed(Some(path)))?;
let file = File { text, path, tokens };
let shown = scope.name_of(path);
let tokens = tokenize(text).map_err(|_| lex_failed(&shown))?;
let file = File { text, shown, tokens };
let mut plan = Plan::default();
let header = header_edits(&file, module, item_span, port, &existing, &mut plan.warnings)?;
@@ -143,15 +142,15 @@ pub(super) fn not_indexed(name: &str) -> String {
format!("lucisv can no longer find the declaration of `{name}`.")
}
fn lex_failed(path: Option<&Path>) -> String {
format!("{} does not lex, so lucisv will not edit it.", display(path.unwrap_or(Path::new("?"))))
fn lex_failed(shown: &str) -> String {
format!("{shown} does not lex, so lucisv will not edit it.")
}
/// The file a module is written in, as the planners read it: its text, its
/// name for a message, and its tokens.
struct File<'a> {
text: &'a str,
path: &'a Path,
shown: String,
tokens: Vec<Token>,
}
@@ -164,7 +163,7 @@ fn header_edits(
existing: &[DeclaredPort],
warnings: &mut Vec<String>,
) -> Result<Vec<TextEdit>, String> {
let (text, path, tokens) = (file.text, file.path, file.tokens.as_slice());
let (text, path, tokens) = (file.text, file.shown.as_str(), file.tokens.as_slice());
let name_end = module.name_span.end;
let list = list_directives(module);
let header = format!("`{}`'s port list", module.name);
@@ -290,14 +289,14 @@ fn guard_conditionals(
at: u32,
region: &str,
text: &str,
path: &Path,
shown: &str,
warnings: &mut Vec<String>,
) -> Result<(), String> {
if directives.is_empty() {
return Ok(());
}
let lines = LineIndex::new(text);
let where_ = |span: TextRange| format!("{}:{}", display(path), lines.line_col(span.start).0);
let where_ = |span: TextRange| format!("{shown}:{}", lines.line_col(span.start).0);
let mut depth = 0i32;
let mut opened: Option<&Directive> = None;
for directive in directives.iter().filter(|d| d.span.start < at) {
@@ -389,6 +388,7 @@ fn instantiation_edits(
if !text.contains(&site.name) {
return Ok((Vec::new(), 0));
}
let shown = scope.name_of(path);
let (tree, _) = parse_source_tolerant(text);
let mut instantiations = Vec::new();
collect_instantiations(&tree.items, &mut instantiations);
@@ -421,7 +421,7 @@ fn instantiation_edits(
warnings.push(format!(
"`{}` at {}:{} writes an empty connection list, so `{}` is left unconnected there.",
instance.name,
display(path),
shown,
lines.line_col(instance.name_span.start).0,
port.name
));
@@ -431,7 +431,7 @@ fn instantiation_edits(
return Err(format!(
"`{}` in {} connects {} of `{}`'s {ports_before} port(s) by position, so lucisv cannot tell where a new one goes; give it named connections first.",
instance.name,
display(path),
shown,
conns.len(),
site.name
));
@@ -448,9 +448,9 @@ fn instantiation_edits(
warnings.push(format!(
"`{}` at {}:{} connects with `.*` and {} has no signal named `{}`, so the new port will not bind; connect it by hand.",
instance.name,
display(path),
shown,
lines.line_col(instance.name_span.start).0,
display(path),
shown,
port.name
));
}
@@ -465,13 +465,13 @@ fn instantiation_edits(
let expr = if visible {
port.name.clone()
} else {
todo.push(at_site(&instance.name, path, &lines, instance.name_span.start));
todo.push(at_site(&instance.name, &shown, &lines, instance.name_span.start));
"/* TODO: connect */".to_string()
};
let element = format!(".{}({expr})", port.name);
let open = match open {
Some(open) => open,
None => return Err(missing_parens(&instance.name, path)),
None => return Err(missing_parens(&instance.name, &shown)),
};
edits.extend(append_to_list(text, Some(open), &spans, &element));
}
@@ -484,11 +484,11 @@ fn instantiation_edits(
let expr = if visible {
port.name.clone()
} else {
empty.push(at_site(&instance.name, path, &lines, instance.name_span.start));
empty.push(at_site(&instance.name, &shown, &lines, instance.name_span.start));
String::new()
};
let Some(open) = conn_list_open(text, instance, spans.first().copied()) else {
return Err(missing_parens(&instance.name, path));
return Err(missing_parens(&instance.name, &shown));
};
edits.extend(append_to_list(text, Some(open), &spans, &expr));
}
@@ -510,14 +510,14 @@ fn instantiation_edits(
}
/// How one instantiation site is named in a warning: `` `u_sub` (top.sv:12) ``.
fn at_site(instance: &str, path: &Path, lines: &LineIndex, offset: u32) -> String {
format!("`{instance}` ({}:{})", display(path), lines.line_col(offset).0)
fn at_site(instance: &str, shown: &str, lines: &LineIndex, offset: u32) -> String {
format!("`{instance}` ({shown}:{})", lines.line_col(offset).0)
}
pub(super) fn missing_parens(instance: &str, path: &Path) -> String {
pub(super) fn missing_parens(instance: &str, shown: &str) -> String {
format!(
"lucisv cannot find the connection list of `{instance}` in {}; no edits were made.",
display(path)
shown
)
}
+5 -7
View File
@@ -64,7 +64,7 @@ pub(super) fn plan_convert(
let Some((module, _)) = find_module(&tree, &name) else {
return Err(format!("lucisv can no longer find the declaration of `{name}`."));
};
let ports = convert_header(file, &diagnostics, module)?;
let ports = convert_header(&scope.name_of(file), &diagnostics, module)?;
let site = locate_module(scope, ModuleRef::Name(&name))?;
if site.file != i {
return Err(elsewhere(&name));
@@ -83,13 +83,13 @@ pub(super) fn plan_convert(
/// Split out of [`plan_convert`] so the code-action offer earns the same
/// refusals from the buffer's own parse (take 5 §P1c, `ports::offer`).
pub(super) fn convert_header<'t>(
file: &Path,
shown: &str,
diagnostics: &[ParseDiagnostic],
module: &'t Module,
) -> Result<Vec<&'t NonAnsiPort>, String> {
let name = &module.name;
let ports = header(module)?;
unparsed(file, diagnostics)?;
unparsed(shown, diagnostics)?;
let names = header_names(module, &ports)?;
if !module.port_directives.is_empty() {
return Err(format!(
@@ -186,14 +186,12 @@ fn header_names(module: &Module, ports: &[&NonAnsiPort]) -> Result<Vec<String>,
/// The refusal a file that does not parse earns. Stricter than the verifier's
/// "no *new* diagnostic" rule, and for the same reason the `.*` expansion is:
/// a header lucisv misread is a header whose ports it would declare twice.
fn unparsed(file: &Path, diagnostics: &[ParseDiagnostic]) -> Result<(), String> {
fn unparsed(shown: &str, diagnostics: &[ParseDiagnostic]) -> Result<(), String> {
match diagnostics.first() {
None => Ok(()),
Some(problem) => Err(format!(
"{} does not parse ({} at line {}), so lucisv will not convert its ports to ANSI.",
display(file),
problem.message,
problem.line
shown, problem.message, problem.line
)),
}
}
+10 -12
View File
@@ -26,7 +26,7 @@ use vlog_parser::span::TextRange;
use vlog_parser::{parse_source_tolerant, LineIndex, ParseDiagnostic};
use vlog_semantic::SymbolKind;
use crate::rename::{display, Scope};
use crate::rename::Scope;
use crate::TextEdit;
use super::add::not_indexed;
@@ -55,7 +55,7 @@ pub(super) fn plan_expand(
let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) };
let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) };
let (tree, diagnostics) = parse_source_tolerant(text);
unparsed(file, &diagnostics)?;
unparsed(&scope.name_of(file), &diagnostics)?;
let Wildcard { instantiation, instance, conns, wildcard } = wildcard_at(&tree.items, offset)?;
if !instance.conn_directives.is_empty() {
return Err(directives(&instance.name, "connection list"));
@@ -86,7 +86,7 @@ pub(super) fn plan_expand(
let mut plan = Plan { sites: 1, ..Plan::default() };
plan.add(i, replacement(text, previous, at, &connections));
if !unbound.is_empty() {
plan.warnings.push(unbound_warning(text, file, instance, &unbound));
plan.warnings.push(unbound_warning(text, &scope.name_of(file), instance, &unbound));
}
plan.expected.push((i, expected(text, &site.name, instance, conns, wildcard, &missing)));
Ok(Expansion { site, plan, count: connections.len(), instance: instance.name.clone() })
@@ -95,14 +95,12 @@ pub(super) fn plan_expand(
/// The refusal a file that does not parse earns. A connection list lucisv
/// misread is a list whose ports it would connect twice, so — unlike the
/// verifier's "no *new* diagnostic" rule — this one asks for none at all.
fn unparsed(file: &Path, diagnostics: &[ParseDiagnostic]) -> Result<(), String> {
fn unparsed(shown: &str, diagnostics: &[ParseDiagnostic]) -> Result<(), String> {
match diagnostics.first() {
None => Ok(()),
Some(problem) => Err(format!(
"{} does not parse ({} at line {}), so lucisv will not expand a `.*` in it.",
display(file),
problem.message,
problem.line
shown, problem.message, problem.line
)),
}
}
@@ -195,19 +193,19 @@ fn unconnected(
let Some(text) = scope.text(site.file) else { return Err(not_indexed(&site.name)) };
let Some(path) = scope.path(site.file) else { return Err(not_indexed(&site.name)) };
let (tree, diagnostics) = parse_source_tolerant(text);
unconnected_in(path, &tree, &diagnostics, &site.name, conns)
unconnected_in(&scope.name_of(path), &tree, &diagnostics, &site.name, conns)
}
/// [`unconnected`] over the declaring file's parse, which the code-action
/// offer makes once instead of once per refactoring (take 5 §P1c).
pub(super) fn unconnected_in(
path: &Path,
shown: &str,
tree: &SourceFile,
diagnostics: &[ParseDiagnostic],
module: &str,
conns: &[ListElem<Connection>],
) -> Result<Vec<String>, String> {
unparsed(path, diagnostics)?;
unparsed(shown, diagnostics)?;
let Some((declaration, _)) = find_module(tree, module) else {
return Err(not_indexed(module));
};
@@ -311,13 +309,13 @@ fn replacement(text: &str, previous: u32, at: TextRange, connections: &[String])
vec![replace(format!("{first},")), insert(after.at, format!("{br}{}", rest.join(&separator)))]
}
fn unbound_warning(text: &str, file: &Path, instance: &Instance, unbound: &[String]) -> String {
fn unbound_warning(text: &str, shown: &str, instance: &Instance, unbound: &[String]) -> String {
let lines = LineIndex::new(text);
format!(
"no net, variable or port named {} is declared where `{}` is instantiated ({}:{}), so `.*` never bound {} — lucisv wrote {} unconnected.",
unbound.iter().map(|n| format!("`{n}`")).collect::<Vec<_>>().join(", "),
instance.name,
display(file),
shown,
lines.line_col(instance.name_span.start).0,
if unbound.len() == 1 { "it" } else { "them" },
if unbound.len() == 1 { "it" } else { "them" },
+2 -2
View File
@@ -39,7 +39,7 @@ use std::path::{Path, PathBuf};
use vlog_parser::ast::{Connections, ItemKind, Module, PortList, SourceFile};
use vlog_parser::parse_source_tolerant;
use crate::rename::{display, Scope};
use crate::rename::Scope;
use crate::{check, RefactorEdit, TextEdit};
use add::{parse_port_decl, plan_add};
@@ -504,7 +504,7 @@ fn confirm(scope: &Scope, plan: &Plan, module: &str, what: &str) -> Result<(), S
if &actual != expected {
return Err(format!(
"{what} would not leave {} with the signature lucisv intended; no edits were made.",
display(path)
scope.name_of(path)
));
}
}
+10 -5
View File
@@ -47,6 +47,7 @@ use super::list::{append_to_list, conn_list_open, elem_spans};
use super::propagate::{connections_of, instance_at, missing_ports};
use super::remove::{body_uses_in, disconnections_in, header_removal, port_at};
use super::{port_action_modules_in, sites_phrase, Plan};
use crate::scope::{display, BaseNames};
/// Which of the four port refactorings an offer names.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -148,6 +149,8 @@ struct Files<'a> {
/// Index of the buffer the cursor is in.
here: usize,
parsed: Vec<Option<Parsed>>,
/// How many sources share each file name, for naming them in messages.
base_names: BaseNames,
}
impl<'a> Files<'a> {
@@ -160,7 +163,8 @@ impl<'a> Files<'a> {
sources.dedup_by(|a, b| a.0 == b.0);
let here = sources.iter().position(|(path, _)| *path == file)?;
let parsed = sources.iter().map(|_| None).collect();
Some(Files { sources, here, parsed })
let base_names = BaseNames::of(sources.iter().map(|(p, _)| *p));
Some(Files { sources, here, parsed, base_names })
}
fn len(&self) -> usize {
@@ -247,11 +251,12 @@ impl<'a> Files<'a> {
if !text.contains(module) {
return Ok((Vec::new(), 0));
}
let shown = self.base_names.name(path);
if i == self.here {
return disconnections_in(text, path, buffer.tree, module, port, warnings);
return disconnections_in(text, &shown, buffer.tree, module, port, warnings);
}
match self.parsed(i) {
Some(parsed) => disconnections_in(text, path, &parsed.tree, module, port, warnings),
Some(parsed) => disconnections_in(text, &shown, &parsed.tree, module, port, warnings),
None => Ok((Vec::new(), 0)),
}
}
@@ -371,7 +376,7 @@ fn expansion(buffer: &Buffer<'_>, files: &mut Files<'_>, offset: u32) -> Option<
let at = files.declaring(buffer.tree, &module_name)?;
let missing = {
let (path, tree, diagnostics) = files.declaration(buffer, at)?;
unconnected_in(path, tree, diagnostics, &module_name, conns).ok()?
unconnected_in(&display(path), tree, diagnostics, &module_name, conns).ok()?
};
if missing.is_empty() {
return None;
@@ -397,7 +402,7 @@ fn conversion(buffer: &Buffer<'_>, files: &mut Files<'_>, offset: u32) -> Option
module_at(&buffer.tree.items, offset, &mut found);
let name = found?;
let (module, _) = find_module(buffer.tree, &name)?;
let ports = convert_header(buffer.file, buffer.diagnostics, module).ok()?;
let ports = convert_header(&display(buffer.file), buffer.diagnostics, module).ok()?;
if files.declaring(buffer.tree, &name)? != Declared::Here {
return None;
}
+3 -3
View File
@@ -11,7 +11,7 @@ use vlog_parser::ast::{
use vlog_parser::span::TextRange;
use vlog_parser::{parse_source_tolerant, LineIndex};
use crate::rename::{display, Scope};
use crate::rename::Scope;
use super::add::{missing_parens, not_indexed};
use super::find::{
@@ -115,7 +115,7 @@ pub(super) fn plan_propagate(
let spans: Vec<TextRange> = elem_spans(conns, |c| c.span);
let Some(open) = conn_list_open(text, instance, spans.first().copied()) else {
return Err(missing_parens(&instance.name, file));
return Err(missing_parens(&instance.name, &scope.name_of(file)));
};
let lines = LineIndex::new(text);
let at = instance.name_span.start;
@@ -147,7 +147,7 @@ pub(super) fn plan_propagate(
plan.warnings.push(format!(
"no signal named {} is in scope at {}:{}, so those connections were left as `/* TODO: connect */`.",
todo.iter().map(|n| format!("`{n}`")).collect::<Vec<_>>().join(", "),
display(file),
scope.name_of(file),
lines.line_col(at).0
));
}
+8 -8
View File
@@ -10,7 +10,7 @@ use vlog_parser::span::TextRange;
use vlog_parser::{parse_source_tolerant, LineIndex};
use vlog_semantic::SymbolKind;
use crate::rename::{display, Scope};
use crate::rename::Scope;
use crate::TextEdit;
use super::add::{element_spans, not_indexed};
@@ -113,7 +113,7 @@ pub(super) fn plan_remove(
return Err(format!(
"`{port}` is still used inside `{}` at {}:{}; remove those uses first.",
site.name,
display(path),
scope.name_of(path),
used.join(", ")
));
}
@@ -163,7 +163,7 @@ pub(super) fn plan_remove(
/// rename after QA found the same hole there (`Scope::macro_argument_sites`,
/// `Scope::define_sites`) answers it here, with news of its own.
fn preprocessor_warnings(scope: &Scope, file: usize, port: &str) -> Vec<String> {
let where_ = display(scope.path(file).unwrap_or(Path::new("?")));
let where_ = scope.name_at(file);
let mut out = Vec::new();
for site in scope.macro_argument_sites(file, port) {
out.push(format!(
@@ -283,7 +283,7 @@ fn disconnection_edits(
return Ok((Vec::new(), 0));
}
let (tree, _) = parse_source_tolerant(text);
disconnections_in(text, path, &tree, &site.name, port, warnings)
disconnections_in(text, &scope.name_of(path), &tree, &site.name, port, warnings)
}
/// [`disconnection_edits`] over a parse the caller already has, so the offer
@@ -291,7 +291,7 @@ fn disconnection_edits(
/// without building a workspace (take 5 §P1c).
pub(super) fn disconnections_in(
text: &str,
path: &Path,
shown: &str,
tree: &SourceFile,
module: &str,
port: &str,
@@ -311,7 +311,7 @@ pub(super) fn disconnections_in(
return Err(format!(
"`{}` in {} connects `{}`'s ports by position; dropping one would silently re-bind the rest, so lucisv made no edits — give it named connections first.",
instance.name,
display(path),
shown,
module
))
}
@@ -325,7 +325,7 @@ pub(super) fn disconnections_in(
warnings.push(format!(
"`{}` at {}:{} connects with `.*`, so nothing was removed there; the signal it bound `{port}` to may now be unused.",
instance.name,
display(path),
shown,
lines.line_col(instance.name_span.start).0
));
continue;
@@ -346,7 +346,7 @@ pub(super) fn disconnections_in(
if !trivial {
warnings.push(format!(
"`{written}` at {}:{} was deleted with the port.",
display(path),
shown,
lines.line_col(expr.span.start).0
));
}
+120
View File
@@ -0,0 +1,120 @@
//! The same-named members a rename leaves in the *other* arms of a generate
//! label, said out loud (generate-label-rename QA F2, re-check R3).
//!
//! Two arms of one generate `if`/`case` may carry one label (IEEE 1800
//! §27.5), and a path `g.x` names whichever arm elaborates. Renaming the `x`
//! of one arm rewrites `g.x` with it, so the `x` of every other arm reachable
//! by the same hierarchical name — through *every* enclosing same-label pair,
//! `g.h.x` with two `g` arms each holding an `h` — is named, not edited.
//!
//! Which arms carry a label is the binder's record: an arm's scope is owned by
//! its label, or — for an arm whose label repeats an earlier one — it is the
//! scope whose span is that redeclaration's (`Semantics::duplicates`).
use vlog_semantic::{ScopeId, ScopeKind, Semantics, SymbolId, SymbolKind};
use super::Target;
use crate::scope::Scope;
impl<'a> Scope<'a> {
/// One warning per other declaration of the renamed name that the same
/// hierarchical name reaches through another combination of arms.
pub(super) fn sibling_arm_warnings(&mut self, target: &Target) -> Vec<String> {
let where_ = self.name_at(target.file);
let text = self.text(target.file).unwrap_or("");
let Some(analysis) = self.analysis(target.file) else { return Vec::new() };
let sem = &analysis.semantics;
let Some(symbol) = sem.symbol(target.symbol) else { return Vec::new() };
let (root, labels) = label_chain(sem, symbol.scope);
if labels.is_empty() {
return Vec::new();
}
let dotted = labels.join(".");
reachable_arms(sem, root, &labels)
.into_iter()
.filter(|&arm| arm != symbol.scope)
.filter_map(|arm| sem.scope(arm)?.lookup_local(&target.name))
.filter_map(|other| sem.symbol(other))
.map(|other| {
let before = text.get(..other.name_span.start as usize).unwrap_or_default();
let line = before.matches('\n').count() + 1;
format!(
"`{}` is also declared at {where_}:{line}, in another arm labelled `{dotted}`; a path `{dotted}.{}` now names only the renamed arm's declaration, and that one was left unchanged.",
target.name, target.name
)
})
.collect()
}
}
/// The labels of the arms enclosing `scope`, outermost first, and the scope
/// the outermost one is declared in. A scope that is no labelled arm ends the
/// chain.
fn label_chain(sem: &Semantics, scope: ScopeId) -> (ScopeId, Vec<String>) {
let mut labels = Vec::new();
let mut here = scope;
while let Some(label) = arm_label(sem, here).and_then(|id| sem.symbol(id)) {
labels.push(label.name.clone());
here = label.scope;
}
labels.reverse();
(here, labels)
}
/// Every arm the dotted `labels` reach from `root`: each label looked up in
/// the scope the previous level's arms open, and every arm carrying it.
fn reachable_arms(sem: &Semantics, root: ScopeId, labels: &[String]) -> Vec<ScopeId> {
let mut level = vec![root];
for label in labels {
level = level
.iter()
.filter_map(|&scope| sem.scope(scope)?.lookup_local(label))
.filter(|&id| sem.symbol(id).is_some_and(|s| s.kind == SymbolKind::Block))
.flat_map(|id| arms_of(sem, id))
.collect();
}
level
}
/// The arm scopes carrying block label `label`: the one it owns, and every
/// arm whose repeated label the binder recorded as a redeclaration of it.
fn arms_of(sem: &Semantics, label: SymbolId) -> Vec<ScopeId> {
let owned = sem.symbol(label).and_then(|s| s.child_scope);
let repeats =
sem.duplicates().iter().filter(|d| d.first == label && d.kind == SymbolKind::Block);
let mut out: Vec<ScopeId> = owned.into_iter().collect();
for repeat in repeats {
out.extend(arm_at(sem, repeat.scope, repeat.decl_span));
}
out
}
/// The label an arm scope carries: its owner, or the first declaration its
/// repeated label redeclares.
fn arm_label(sem: &Semantics, arm: ScopeId) -> Option<SymbolId> {
let scope = sem.scope(arm)?;
if scope.kind != ScopeKind::Generate {
return None;
}
if let Some(owner) = scope.owner {
return (sem.symbol(owner)?.kind == SymbolKind::Block).then_some(owner);
}
let parent = scope.parent?;
sem.duplicates()
.iter()
.find(|d| d.kind == SymbolKind::Block && d.scope == parent && d.decl_span == scope.span)
.map(|d| d.first)
}
/// The generate scope a repeated label's block opened: a child of the scope
/// the label is declared in, spanning exactly the block.
fn arm_at(
sem: &Semantics,
declared_in: ScopeId,
span: vlog_parser::span::TextRange,
) -> Option<ScopeId> {
let parent = sem.scope(declared_in)?;
parent.children.iter().copied().find(|&child| {
sem.scope(child).is_some_and(|c| c.kind == ScopeKind::Generate && c.span == span)
})
}
+324
View File
@@ -0,0 +1,324 @@
//! Which macro arguments can reach a module member from any file (TODO
//! §65.1, independent review H-1/H-2, 2026-10-06).
//!
//! A bare spelling in another file's macro argument is that file's own name
//! — unless the macro *carries* the argument somewhere a bare name is not:
//! after a `.` (`force u_m.sig`, a named connection `.x(x)`), after a `.`
//! through a `` `` `` paste (`` u_m.``sig ``), into a `bind` into the
//! declaring unit (whose connections are evaluated in that unit), or into
//! another macro's argument that is carried. Such an argument is news
//! wherever it is written. So is an argument of a macro the set does not
//! define, or one past the macro's formals: nothing shows it cannot reach.
//!
//! A `bind` is recognised where its keyword is spelled in a `` `define``
//! body of the set (directly, or in a macro that body invokes); a macro that
//! expands to one is a *binder*: every argument it takes is carried, its body
//! is news (as a `bind` statement's would be), and a file invoking it is home
//! (K2).
use std::collections::{HashMap, HashSet};
use super::contains_word;
use super::home::{macro_names, skip_string};
use super::scoped::{binds_into, spellings};
/// One `` `define`` of a macro: its formal names as written and its body.
pub(crate) struct MacroDef {
/// The formal arguments as written (`"a"`, `"b = 8"`); empty for an
/// object-like macro.
pub(crate) params: Vec<String>,
/// The replacement text, line continuations joined.
pub(crate) body: String,
}
/// Macro name → every `` `define`` of it in the set.
pub(crate) type Defs = HashMap<String, Vec<MacroDef>>;
/// Which arguments of which macros are carried, for one declaring unit.
#[derive(Default)]
pub(super) struct Carriers {
/// Macro → per formal position, whether it is carried; `None` when every
/// position is (a binder).
formals: HashMap<String, Option<Vec<bool>>>,
/// The macros that expand to a `bind` into the unit.
binders: HashSet<String>,
}
impl Carriers {
/// The carried arguments of every macro in `defs`, for members of `unit`.
pub(super) fn of(defs: &Defs, unit: &str) -> Carriers {
let mut walk = Walk { defs, unit, binder: HashMap::new(), formals: HashMap::new() };
let names: Vec<&String> = defs.keys().collect();
for name in names {
walk.formals_of(name, &mut HashSet::new());
}
let binders = walk.binder.into_iter().filter(|(_, b)| *b).map(|(n, _)| n).collect();
Carriers { formals: walk.formals, binders }
}
/// Whether argument `position` (0-based) of an invocation of
/// `macro_name` may reach the declaration from any file.
pub(super) fn carries(&self, macro_name: &str, position: usize) -> bool {
match self.formals.get(macro_name) {
Some(Some(formals)) => formals.get(position).copied().unwrap_or(true),
Some(None) | None => true,
}
}
/// Whether `macro_name` expands to a `bind` into the unit.
pub(super) fn binds(&self, macro_name: &str) -> bool {
self.binders.contains(macro_name)
}
/// Whether any macro of the set is a binder.
pub(super) fn any_binder(&self) -> bool {
!self.binders.is_empty()
}
}
/// The memoized recursion over the set's macros.
struct Walk<'a> {
defs: &'a Defs,
unit: &'a str,
binder: HashMap<String, bool>,
formals: HashMap<String, Option<Vec<bool>>>,
}
impl Walk<'_> {
/// Whether `name` expands to a `bind` into the unit, directly or through
/// a macro its body invokes. A cycle (an illegal macro) answers `false`.
fn is_binder(&mut self, name: &str, active: &mut HashSet<String>) -> bool {
if let Some(&known) = self.binder.get(name) {
return known;
}
let Some(defs) = self.defs.get(name) else { return false };
if !active.insert(name.to_string()) {
return false;
}
let mut found = defs.iter().any(|d| body_binds(&d.body, self.unit));
if !found {
let inner: Vec<String> = defs.iter().flat_map(|d| macro_names(&d.body)).collect();
found = inner.iter().any(|n| self.is_binder(n, active));
}
active.remove(name);
self.binder.insert(name.to_string(), found);
found
}
/// The carried formal positions of `name`; `None` when every position is
/// (a binder, an unknown macro, or a cycle — nothing shows otherwise).
fn formals_of(&mut self, name: &str, active: &mut HashSet<String>) -> Option<Vec<bool>> {
if let Some(known) = self.formals.get(name) {
return known.clone();
}
let defs = self.defs.get(name)?;
if active.contains(name) {
return None;
}
if self.is_binder(name, &mut HashSet::new()) {
self.formals.insert(name.to_string(), None);
return None;
}
active.insert(name.to_string());
let mut carried: Vec<bool> = Vec::new();
for def in defs {
for (position, formal) in def.params.iter().enumerate() {
let formal = formal.split('=').next().unwrap_or_default().trim();
if carried.len() <= position {
carried.resize(position + 1, false);
}
carried[position] |= self.formal_is_carried(&def.body, formal, active);
}
}
active.remove(name);
self.formals.insert(name.to_string(), Some(carried.clone()));
Some(carried)
}
/// Whether `body` spells `formal` after a `.`, or passes it to a macro
/// argument that is carried.
fn formal_is_carried(
&mut self,
body: &str,
formal: &str,
active: &mut HashSet<String>,
) -> bool {
if formal.is_empty() || !contains_word(body, formal) {
return false;
}
if spellings(body, formal).1 {
return true;
}
for (inner, arguments) in invocations(body) {
for (position, argument) in arguments.iter().enumerate() {
if !contains_word(argument, formal) {
continue;
}
let carried = match self.formals_of(&inner, active) {
Some(formals) => formals.get(position).copied().unwrap_or(true),
None => true,
};
if carried {
return true;
}
}
}
false
}
}
/// Whether a `` `define`` body holds a `bind` into `unit`; a body that
/// spells `bind` but does not lex is counted (doubt).
fn body_binds(body: &str, unit: &str) -> bool {
if !contains_word(body, "bind") {
return false;
}
match vlog_parser::tokenize(body) {
Ok(tokens) => !binds_into(&tokens, unit).is_empty(),
Err(_) => true,
}
}
/// Every function-like macro invocation in `text` (strings and comments
/// skipped): its name and its top-level argument texts. Invocations nested
/// in another's arguments are listed too.
fn invocations(text: &str) -> Vec<(String, Vec<&str>)> {
let bytes = text.as_bytes();
let mut out = Vec::new();
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'"' => i = skip_string(bytes, i + 1),
b'/' if bytes.get(i + 1) == Some(&b'/') => {
i = bytes[i..].iter().position(|&b| b == b'\n').map_or(bytes.len(), |n| i + n)
}
b'/' if bytes.get(i + 1) == Some(&b'*') => {
i = text[i + 2..].find("*/").map_or(bytes.len(), |n| i + 2 + n + 2)
}
// `` `" `` (stringify) and `` `` `` (paste) open nothing.
b'`' if matches!(bytes.get(i + 1), Some(b'"' | b'`')) => i += 2,
b'`' => {
let len = text[i + 1..]
.bytes()
.take_while(|b| b.is_ascii_alphanumeric() || *b == b'_' || *b == b'$')
.count();
let name = &text[i + 1..i + 1 + len];
i += 1 + len;
let open = i + text[i..].len() - text[i..].trim_start().len();
if !name.is_empty() && bytes.get(open) == Some(&b'(') {
out.push((name.to_string(), split_arguments(&text[open + 1..]).0));
}
}
_ => i += 1,
}
}
out
}
/// The top-level, comma-separated arguments of the list that starts right
/// after its `(`, up to the matching `)` (or the end of `text`), with the
/// byte offset of each argument's start.
fn split_arguments(text: &str) -> (Vec<&str>, Vec<usize>) {
let bytes = text.as_bytes();
let (mut arguments, mut starts) = (Vec::new(), vec![0]);
let (mut depth, mut start, mut i) = (0usize, 0usize, 0usize);
while i < bytes.len() {
match bytes[i] {
b'"' => {
i = skip_string(bytes, i + 1);
continue;
}
b'(' | b'[' | b'{' => depth += 1,
b')' | b']' | b'}' if depth == 0 => break,
b')' | b']' | b'}' => depth -= 1,
b',' if depth == 0 => {
arguments.push(&text[start..i]);
start = i + 1;
starts.push(start);
}
_ => {}
}
i += 1;
}
arguments.push(&text[start..i.min(text.len())]);
(arguments, starts)
}
/// The 0-based position of the argument holding byte `offset` of an
/// invocation's argument text (the text right after its `(`).
pub(super) fn argument_position(arguments: &str, offset: usize) -> usize {
let (_, starts) = split_arguments(arguments);
starts.iter().filter(|&&start| start <= offset).count().saturating_sub(1)
}
#[cfg(test)]
mod tests {
use super::*;
fn defs(entries: &[(&str, &[&str], &str)]) -> Defs {
let mut out = Defs::new();
for (name, params, body) in entries {
let params = params.iter().map(|p| p.to_string()).collect();
out.entry(name.to_string())
.or_default()
.push(MacroDef { params, body: body.to_string() });
}
out
}
#[test]
fn a_formal_after_a_dot_or_a_pasted_dot_is_carried_and_a_plain_one_is_not() {
let set = defs(&[
("CONN", &["x"], ".x(x)"),
("FORCE", &["sig"], "force u_m.sig = 1'b0;"),
("PEEK", &["sig"], "u_m.``sig"),
("ASSERT", &["n", "e"], "n: assert property (e);"),
("STR", &["s"], "`\"s`\""),
]);
let carriers = Carriers::of(&set, "m");
assert!(carriers.carries("CONN", 0));
assert!(carriers.carries("FORCE", 0));
assert!(carriers.carries("PEEK", 0));
assert!(!carriers.carries("ASSERT", 0) && !carriers.carries("ASSERT", 1));
assert!(!carriers.carries("STR", 0));
assert!(carriers.carries("ASSERT", 2), "past the formals");
assert!(carriers.carries("UNKNOWN", 0), "a macro the set does not define");
}
#[test]
fn a_formal_passed_on_is_carried_only_when_the_inner_position_is() {
let set = defs(&[
("OUTER", &["a", "b"], "`INNER(a, b)"),
("INNER", &["p", "q"], "p + top.q"),
("ELSEWHERE", &["a"], "`NOT_IN_SET(a)"),
("LOOP", &["a"], "`LOOP(a)"),
]);
let carriers = Carriers::of(&set, "m");
assert!(!carriers.carries("OUTER", 0));
assert!(carriers.carries("OUTER", 1));
assert!(carriers.carries("ELSEWHERE", 0));
assert!(carriers.carries("LOOP", 0), "a cycle is doubt");
}
#[test]
fn a_macro_expanding_to_a_bind_into_the_unit_is_a_binder_through_other_macros() {
let set = defs(&[
("BIND_CHK", &[], "bind m chk u_chk (.s(state_q));"),
("WRAP", &["x"], "`BIND_CHK x"),
("OTHER", &["x"], "bind n chk u (.s(x));"),
]);
let carriers = Carriers::of(&set, "m");
assert!(carriers.binds("BIND_CHK") && carriers.binds("WRAP"));
assert!(carriers.carries("WRAP", 0));
assert!(!carriers.binds("OTHER") && !carriers.carries("OTHER", 0));
}
#[test]
fn an_argument_position_counts_top_level_commas_only() {
let args = "a, f(b, c), {d, e}, \"x,y\", g)";
assert_eq!(argument_position(args, 0), 0);
assert_eq!(argument_position(args, args.find('c').unwrap_or(0)), 1);
assert_eq!(argument_position(args, args.find('e').unwrap_or(0)), 2);
assert_eq!(argument_position(args, args.find('g').unwrap_or(0)), 4);
}
}
@@ -30,7 +30,7 @@ use vlog_semantic::{ScopeKind, Surface, SymbolId, SymbolKind};
use super::layout::{append, connection, shorthand_tail};
use super::sites::{binds_implicitly, may_connect_implicitly, nearest, sites, Site};
use super::{contains_word, display, Scope, Target};
use super::{contains_word, Scope, Target};
use crate::TextEdit;
/// The insertions a rename's implicit connections need, and the sentences
@@ -451,7 +451,7 @@ impl<'a> Scope<'a> {
/// "`u_leaf` at top.sv:12", the way every sentence here names an instance.
fn describe(&self, file: usize, text: &str, site: &Site) -> String {
let path = self.path(file).map(display).unwrap_or_default();
let path = self.name_at(file);
let line = LineIndex::new(text).line_col(site.instance.name_span.start).0;
format!("`{}` at {path}:{line}", site.instance.name)
}
+326
View File
@@ -0,0 +1,326 @@
//! The **home set** of a declaration: the files whose text the preprocessor
//! pastes into, or out of, the scope the declaration is written in (TODO
//! §65.1, QA final H1–H4 and the lead's corrected ruling, 2026-09-30).
//!
//! The declaring file; every file it `` `include``s, transitively; every file
//! that includes the declaring file (a declaration in an included fragment),
//! and that file's own includes, transitively; and the files the rename
//! edits. An include is resolved against the set by path suffix (`"a/b.svh"`
//! matches `…/a/b.svh`), and when nothing ends that way, by base name — every
//! file of that base name is home.
//!
//! Text only: the include directives are read off the files' bytes, so a
//! commented-out include makes the set larger, never smaller.
use std::collections::{BTreeSet, HashMap, HashSet};
use std::path::{Path, PathBuf};
use super::carry::Defs;
/// The home set of the file at `declaring` in `files`, plus `edited`, as
/// paths — what `lucisv-mcp` scopes a member's mentions with. `None` when the
/// set cannot be known: some include of it names no file of the set, or is
/// not a plain `"…"`/`<…>` name (a macro builds it) — and then nothing may be
/// scoped.
pub fn home_set(
files: &[(PathBuf, String)],
declaring: &Path,
edited: &[PathBuf],
) -> Option<Vec<PathBuf>> {
let sources: Vec<(&Path, &str)> =
files.iter().map(|(p, t)| (p.as_path(), t.as_str())).collect();
let at = sources.iter().position(|(p, _)| *p == declaring)?;
let edited: Vec<usize> =
edited.iter().filter_map(|e| sources.iter().position(|(p, _)| p == e)).collect();
let home = home_of(&sources, at, &edited);
if home.unknown {
return None;
}
Some(home.all.into_iter().filter_map(|i| Some(sources.get(i)?.0.to_path_buf())).collect())
}
/// A home set by source index, with which of its files are include-related to
/// the declaring file (as opposed to edited only).
pub(crate) struct Home {
/// Every home file, the declaring one included.
pub(crate) all: BTreeSet<usize>,
/// The files the declaring file includes, transitively.
pub(crate) included: BTreeSet<usize>,
/// The files that include the declaring file, those that include them,
/// and so on, and everything any of them includes — minus the declaring
/// file and [`Home::included`].
pub(crate) around: BTreeSet<usize>,
/// Whether a file of the include-related set has an include the engine
/// cannot resolve (K3): the set is then not known.
pub(crate) unknown: bool,
}
/// [`home_set`] over a scope's `(path, text)` sources.
pub(crate) fn home_of(sources: &[(&Path, &str)], declaring: usize, edited: &[usize]) -> Home {
let graph = Graph::of(sources);
let included = graph.down(&[declaring], &BTreeSet::from([declaring]));
let mut up: BTreeSet<usize> = BTreeSet::new();
let mut todo = vec![declaring];
while let Some(i) = todo.pop() {
for &j in graph.included_by.get(&i).into_iter().flatten() {
if j != declaring && up.insert(j) {
todo.push(j);
}
}
}
let roots: Vec<usize> = up.iter().copied().collect();
let mut known = included.clone();
known.insert(declaring);
known.extend(roots.iter().copied());
let mut around = up;
around.extend(graph.down(&roots, &known));
around.retain(|i| *i != declaring && !included.contains(i));
let mut all: BTreeSet<usize> = [declaring].into();
all.extend(included.iter().copied());
all.extend(around.iter().copied());
let unknown = all.iter().any(|i| graph.unresolved.contains(i));
all.extend(edited.iter().copied());
Home { all, included, around, unknown }
}
/// Who includes whom in one set of files.
struct Graph {
/// File → the files its includes resolve to.
includes: HashMap<usize, Vec<usize>>,
/// File → the files that include it.
included_by: HashMap<usize, Vec<usize>>,
/// The files with an include that resolves to nothing, or that a macro
/// builds.
unresolved: HashSet<usize>,
}
impl Graph {
fn of(sources: &[(&Path, &str)]) -> Graph {
let mut by_base: HashMap<&std::ffi::OsStr, Vec<usize>> = HashMap::new();
for (i, (path, _)) in sources.iter().enumerate() {
if let Some(base) = path.file_name() {
by_base.entry(base).or_default().push(i);
}
}
let mut graph = Graph {
includes: HashMap::new(),
included_by: HashMap::new(),
unresolved: HashSet::new(),
};
for (i, (_, text)) in sources.iter().enumerate() {
if !text.contains("`include") {
continue;
}
for include in includes_in(text) {
let found = match include {
Some(spelled) => resolve(sources, &by_base, spelled),
None => Vec::new(),
};
if found.is_empty() {
graph.unresolved.insert(i);
}
for j in found {
graph.includes.entry(i).or_default().push(j);
graph.included_by.entry(j).or_default().push(i);
}
}
}
graph
}
/// Every file `roots` include, transitively, that is not in `known`.
fn down(&self, roots: &[usize], known: &BTreeSet<usize>) -> BTreeSet<usize> {
let mut out = BTreeSet::new();
let mut todo = roots.to_vec();
while let Some(i) = todo.pop() {
for &j in self.includes.get(&i).into_iter().flatten() {
if !known.contains(&j) && out.insert(j) {
todo.push(j);
}
}
}
out
}
}
/// Every `` `include`` of one text: `Some(name)` for a plain `"…"`/`<…>`
/// form, `None` for one whose name is built some other way (a macro).
fn includes_in(text: &str) -> Vec<Option<&str>> {
let mut out = Vec::new();
let mut from = 0;
while let Some(hit) = text.get(from..).and_then(|s| s.find("`include")) {
let after = from + hit + "`include".len();
from = after;
// `` `includes`` or `` `include_dir`` is another word.
if text[after..].starts_with(|c: char| c.is_ascii_alphanumeric() || c == '_') {
continue;
}
let rest = text[after..].trim_start();
let close = match rest.chars().next() {
Some('"') => '"',
Some('<') => '>',
_ => {
out.push(None);
continue;
}
};
match rest[1..].find(close) {
Some(end) => out.push(Some(&rest[1..1 + end])),
None => out.push(None),
}
}
out
}
/// The sources an include spelling names: every file of its base name whose
/// path ends in it, else every file of its base name.
fn resolve(
sources: &[(&Path, &str)],
by_base: &HashMap<&std::ffi::OsStr, Vec<usize>>,
spelled: &str,
) -> Vec<usize> {
let wanted = Path::new(spelled);
let Some(candidates) = wanted.file_name().and_then(|base| by_base.get(base)) else {
return Vec::new();
};
let suffix: Vec<usize> =
candidates.iter().copied().filter(|&i| sources[i].0.ends_with(wanted)).collect();
match suffix.is_empty() {
true => candidates.clone(),
false => suffix,
}
}
/// Every macro name invoked in `texts`, and — through the bodies in `defs` —
/// every macro those invoke, and so on: what can expand inside the home set.
pub(crate) fn invoked_from(texts: &[&str], defs: &Defs) -> HashSet<String> {
let mut invoked: HashSet<String> = HashSet::new();
let mut todo: Vec<String> = texts.iter().flat_map(|t| macro_names(t)).collect();
while let Some(name) = todo.pop() {
if !invoked.insert(name.clone()) {
continue;
}
for def in defs.get(&name).into_iter().flatten() {
todo.extend(macro_names(&def.body));
}
}
invoked
}
/// The names after every backtick in `text` that stands in code — not inside
/// a string literal or a comment, where a backtick invokes nothing (QA N2).
/// Directives are included; no `` `define`` can be named like one.
pub(super) fn macro_names(text: &str) -> Vec<String> {
let mut out = Vec::new();
let bytes = text.as_bytes();
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'"' => i = skip_string(bytes, i + 1),
b'/' if bytes.get(i + 1) == Some(&b'/') => {
i = bytes[i..].iter().position(|&b| b == b'\n').map_or(bytes.len(), |n| i + n)
}
b'/' if bytes.get(i + 1) == Some(&b'*') => {
i = text[i + 2..].find("*/").map_or(bytes.len(), |n| i + 2 + n + 2)
}
b'`' => {
let name: String = text[i + 1..]
.chars()
.take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '$')
.collect();
i += 1 + name.len();
if !name.is_empty() {
out.push(name);
}
}
_ => i += 1,
}
}
out
}
/// The offset just past the string literal whose body starts at `i`.
pub(super) fn skip_string(bytes: &[u8], mut i: usize) -> usize {
while i < bytes.len() {
match bytes[i] {
b'\\' => i += 2,
b'"' => return i + 1,
_ => i += 1,
}
}
bytes.len()
}
#[cfg(test)]
mod tests {
use super::super::carry::MacroDef;
use super::*;
fn set(files: &[&str]) -> Vec<(PathBuf, String)> {
files.iter().map(|f| (PathBuf::from(f), String::new())).collect()
}
#[test]
fn an_include_is_read_between_quotes_or_angle_brackets() {
let text = "`include \"a/b.svh\"\n `include <c.sv>\n`include MACRO\n`include_dirs x\n";
assert_eq!(includes_in(text), vec![Some("a/b.svh"), Some("c.sv"), None]);
}
#[test]
fn the_home_set_follows_includes_both_ways_and_takes_every_base_name_match() {
let mut files = set(&[
"/r/m.sv",
"/r/x/m_assert.svh",
"/r/top.sv",
"/r/a/defs.svh",
"/r/b/defs.svh",
"/r/far.sv",
]);
files[0].1 = "module m;\n`include \"m_assert.svh\"\nendmodule\n".into();
files[1].1 = "`include \"defs.svh\"\n".into();
files[2].1 = "`include \"m.sv\"\n".into();
let home = home_set(&files, Path::new("/r/m.sv"), &[]).expect("known");
let names: Vec<&str> = home.iter().filter_map(|p| p.to_str()).collect();
assert_eq!(
names,
vec!["/r/m.sv", "/r/x/m_assert.svh", "/r/top.sv", "/r/a/defs.svh", "/r/b/defs.svh"]
);
}
#[test]
fn the_upward_chain_is_followed_transitively_and_a_cycle_ends() {
let mut files = set(&["/r/frag.svh", "/r/mid.sv", "/r/outer.sv", "/r/side.svh"]);
files[1].1 = "`include \"frag.svh\"\n".into();
files[2].1 = "`include \"mid.sv\"\n`include \"side.svh\"\n".into();
files[3].1 = "`include \"outer.sv\"\n".into();
let home = home_set(&files, Path::new("/r/frag.svh"), &[]).expect("known");
assert_eq!(home.len(), 4, "{home:?}");
}
#[test]
fn an_include_a_macro_builds_or_that_names_no_file_makes_the_set_unknown() {
let mut files = set(&["/r/m.sv", "/r/paths.svh"]);
files[0].1 = "`include \"paths.svh\"\n`include `FRAG\n".into();
assert_eq!(home_set(&files, Path::new("/r/m.sv"), &[]), None);
files[0].1 = "`include \"nowhere.svh\"\n".into();
assert_eq!(home_set(&files, Path::new("/r/m.sv"), &[]), None);
files[0].1 = "// no includes\n".into();
assert!(home_set(&files, Path::new("/r/m.sv"), &[]).is_some());
}
#[test]
fn a_backtick_in_a_string_or_a_comment_invokes_nothing() {
let names = macro_names("x = `A; $display(\"`B \\\" `C\"); // `D\n/* `E */ `F");
assert_eq!(names, vec!["A", "F"]);
}
#[test]
fn invocations_are_followed_through_define_bodies() {
let def = |body: &str| vec![MacroDef { params: Vec::new(), body: body.to_string() }];
let defs: Defs = [("A".to_string(), def("`B(x)")), ("B".to_string(), def("clk_i"))]
.into_iter()
.collect();
let invoked = invoked_from(&[" `A\n"], &defs);
assert!(invoked.contains("A") && invoked.contains("B"));
}
}
+13 -2
View File
@@ -12,17 +12,28 @@
//! workspace every refactoring in this crate reads through, `warnings` is
//! what a finished rename says about the occurrences it could not edit, and
//! `connections` (with `sites` and `layout`) rewrites the `.name` and `.*`
//! connections that bind the renamed name implicitly.
//! connections that bind the renamed name implicitly; `paths` names the
//! hierarchical paths through the name that nothing resolved, and `arms` the
//! same-named members of the other arms of its generate labels; `scoped`
//! decides which text spellings a warning is about the renamed declaration,
//! over `home`'s include-derived home set and `carry`'s macro arguments that
//! reach the declaration from any file.
mod arms;
mod carry;
mod connections;
mod home;
use connections::{combine, fuse};
mod layout;
mod paths;
mod preflight;
mod scoped;
pub(crate) mod sites;
#[cfg(test)]
mod tests;
mod warnings;
pub use home::home_set;
pub use preflight::rename_preflight;
// The rename was the first refactoring, so most of the crate still spells the
@@ -537,7 +548,7 @@ impl<'a> Scope<'a> {
"lucisv found `{name}` recorded at bytes {}..{} of {}, which does not spell it; the rename was abandoned.",
span.start,
span.end,
display(self.path(file).unwrap_or(Path::new("?")))
self.name_at(file)
));
}
if n > 0 && span.start < last_end {
+159
View File
@@ -0,0 +1,159 @@
//! What a rename could not account for **in hierarchical paths**, said out
//! loud (generate-label-rename QA F1).
//!
//! [`Scope::unresolved_path_warnings`]: a segment spelling the renamed name,
//! in *any* file of the set, that resolved to no declaration at all
//! (`tb.dut.g_sw[0].q`, where `tb` is a top module another file declares and
//! nothing resolves the root — TODO §65.4). The rename cannot know whether
//! that path reaches the renamed declaration, so it is left unchanged and
//! named. A segment that resolved to a *different* declaration is not news
//! and is not reported. (The same-label arms are `arms.rs`.)
//!
//! Narrowed by the index's word census and then by a text test for a `.` or
//! `[` beside the name, so a file is analysed only when it could hold such a
//! segment; a name the census cannot hold (an escaped one) is narrowed by
//! text alone.
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::tokenize;
use vlog_semantic::{Resolution, Semantics};
use crate::scope::Scope;
impl<'a> Scope<'a> {
/// One warning per file listing the lines where a path segment spelling
/// `name` resolved to nothing. `edited` files skip a segment with no
/// reference at all: the edited-file stray scan (`unaccounted_warnings`)
/// already names it, and saying it twice is noise.
pub(super) fn unresolved_path_warnings(&mut self, name: &str, edited: &[usize]) -> Vec<String> {
// The census holds no escaped identifier (`words.rs`), so for one the
// text test below is the whole filter.
let escaped = name.starts_with('\\');
let mentioning: Vec<_> = self.index().files_mentioning(name).collect();
let mut out = Vec::new();
for i in 0..self.len() {
if !escaped && !self.file_id(i).is_some_and(|id| mentioning.contains(&id)) {
continue;
}
let Some(text) = self.text(i) else { continue };
if !spelled_beside_a_path(text, name) {
continue;
}
let Some(path) = self.path(i) else { continue };
let Ok(tokens) = tokenize(text) else { continue };
let Some(analysis) = self.analysis(i) else { continue };
let lines =
unresolved_segments(&analysis.semantics, &tokens, name, edited.contains(&i));
if lines.is_empty() {
continue;
}
let at = lines.iter().map(u32::to_string).collect::<Vec<_>>().join(",");
out.push(format!(
"{}:{at}: a hierarchical path through `{name}` was not resolved to any declaration, so it was left unchanged; check whether it reaches the renamed one.",
self.name_of(path)
));
}
out
}
}
/// The 1-based lines of `name` tokens that are a path segment and resolved to
/// nothing: no reference at all (unless `edited`, see the caller), or a
/// reference whose resolution is `NotFound`.
fn unresolved_segments(sem: &Semantics, tokens: &[Token], name: &str, edited: bool) -> Vec<u32> {
let mut lines: Vec<u32> = Vec::new();
for (i, token) in tokens.iter().enumerate() {
if token.kind != TokenKind::Ident || token.text != name || !is_segment(tokens, i) {
continue;
}
if sem.symbol_at(token.span.start).is_some() {
continue;
}
let unresolved = match sem.reference_at(token.span.start) {
Some(r) if r.name_span == token.span => matches!(r.resolution, Resolution::NotFound),
_ => !edited,
};
if unresolved && lines.last() != Some(&token.line) {
lines.push(token.line);
}
}
lines
}
/// Whether the identifier at `i` is one segment of a dotted path: a `.`
/// before it, or a `.` after it past any element selects (`g[0][1].x`).
fn is_segment(tokens: &[Token], i: usize) -> bool {
if i.checked_sub(1).and_then(|p| tokens.get(p)).is_some_and(|t| t.is_sym(".")) {
return true;
}
let mut next = i + 1;
while tokens.get(next).is_some_and(|t| t.is_sym("[")) {
let mut depth = 0usize;
loop {
let Some(t) = tokens.get(next) else { return false };
if t.is_sym("[") {
depth += 1;
} else if t.is_sym("]") {
depth -= 1;
if depth == 0 {
break;
}
}
next += 1;
}
next += 1;
}
tokens.get(next).is_some_and(|t| t.is_sym("."))
}
/// A cheap superset of "`name` is spelled as a path segment somewhere in
/// `text`": a whole-word occurrence with a `.` before it or a `.` or `[`
/// after it, past blanks. A comment between the name and its neighbour is not
/// looked through — it passes, which is what a superset promises.
fn spelled_beside_a_path(text: &str, name: &str) -> bool {
let bytes = text.as_bytes();
let word = |b: u8| b.is_ascii_alphanumeric() || b == b'_' || b == b'$';
let mut from = 0;
while let Some(hit) = text.get(from..).and_then(|s| s.find(name)) {
let start = from + hit;
let end = start + name.len();
from = start + 1;
let before = text[..start].trim_end().as_bytes().last().copied();
let after = text[end..].trim_start().as_bytes().first().copied();
let whole = !start.checked_sub(1).and_then(|p| bytes.get(p)).is_some_and(|&b| word(b))
&& !bytes.get(end).is_some_and(|&b| word(b));
let beside =
matches!(before, Some(b'.' | b'/')) || matches!(after, Some(b'.' | b'[' | b'/'));
if whole && beside {
return true;
}
}
false
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_text_prefilter_passes_every_segment_shape() {
for text in ["a.g.b", "g[0].x", "g [i] .x", "u.g", "u. g", "g /* c */ .x", "u./*c*/g"] {
assert!(spelled_beside_a_path(text, "g"), "{text}");
}
for text in ["assign g = 1;", "gg.x", "u.gg", "x = g + 1;"] {
assert!(!spelled_beside_a_path(text, "g"), "{text}");
}
}
#[test]
fn a_segment_is_a_dot_neighbour_past_element_selects() {
let tokens = tokenize("x = a.g; y = g[0][k[1]].z; w = g[0]; v = g;").expect("lexes");
let at: Vec<bool> = tokens
.iter()
.enumerate()
.filter(|(_, t)| t.text == "g")
.map(|(i, _)| is_segment(&tokens, i))
.collect();
assert_eq!(at, vec![true, true, false, false]);
}
}
+405
View File
@@ -0,0 +1,405 @@
//! Which of the rename's *text* warnings are about the renamed declaration
//! (TODO §65.1: the lead's inspection, QA's final pass H1–H4, rework 4's
//! K1–K3/N1–N3 and the corrected rulings, 2026-09-30).
//!
//! **The governing principle: scoping may drop a warning only when the
//! engine can show the spelling cannot reach the renamed declaration; any
//! doubt falls back to the unscoped behaviour — every spelling warned, as
//! before scoping existed.**
//!
//! Scoping applies only to a declaration that is a **member of a module or
//! interface** (a net, variable, parameter, port, instance, block, a
//! function- or task-local, an enum value written in a module) whose **home
//! set** (`home.rs`) is known. A declaration with no enclosing unit (a
//! fragment's or `$unit`'s own declaration — K1) and one whose home set holds
//! an include the engine cannot resolve (K3) are warned about unscoped.
//! When it applies:
//!
//! * a **bare** spelling (no `.` before it) in a macro argument or an
//! unstructured assertion is news in the declaring file and in a file the
//! rename edits when the scope lookup there (`sites::nearest`) finds the
//! declaration (N1 — another module's own `clk_i` is not); in a file pasted
//! into or around the declaring file always (no scope to look in — H1);
//! inside a `bind` into the declaring unit wherever it is written (H3);
//! in an argument the macro carries after a `.`, into a `bind` into the
//! unit or into a macro the set does not define, wherever it is written
//! (`carry.rs`, review H-1/H-2); elsewhere never;
//! * a **dotted** spelling (`… .state_q`) may be a hierarchical path and is
//! always news;
//! * a `` `define`` body is news when it is written in the home set, when its
//! macro is invoked from the home set — a file with a `bind` into the unit,
//! or invoking a macro that expands to one, counts (K2) — through other
//! bodies too (H2), when the macro itself expands to such a `bind`, or when
//! it spells the name dotted; a macro with a **parameter** named like the
//! declaration never is (N2: the body's spellings are the parameter);
//! * a bare use in the plain code of a pasted file is a use the engine
//! cannot edit, and is said (H4, `Scope::fragment_use_warnings`) — for
//! every renamed declaration, scoped or not.
//!
//! Anything else — a module, interface, package or class, a package's or
//! class's member — can be named bare from any file (an import, a `pkg::`, a
//! handle), and every spelling is reported as before.
use std::collections::HashSet;
use vlog_parser::span::TextRange;
use vlog_parser::token::{Token, TokenKind};
use vlog_semantic::{ScopeId, Semantics, SymbolId};
use super::carry::{Carriers, Defs, MacroDef};
use super::home::{home_of, invoked_from, macro_names, Home};
use super::sites::nearest;
use super::Target;
use crate::scope::Scope;
use crate::TextEdit;
/// What the text scans need to know about the renamed declaration.
pub(super) struct Scoping {
/// The module or interface the declaration is a member of.
unit: Option<String>,
/// Whether spellings may be dropped at all: a member (`unit`) whose home
/// set is known. `false` is the unscoped behaviour.
scoped: bool,
declaring: usize,
symbol: SymbolId,
name: String,
/// The home set (`home.rs`), plus the files holding a `bind` into the
/// unit (K2).
home: Home,
/// Every macro a home-set file invokes, through define bodies.
invoked: HashSet<String>,
/// The macros whose arguments reach the unit from any file, and those
/// expanding to a `bind` into it (`carry.rs`).
carriers: Carriers,
}
impl Scoping {
/// The rule for `target`, renamed by edits to `edited`.
pub(super) fn new(scope: &mut Scope, target: &Target, edited: Vec<usize>) -> Scoping {
let unit = scope
.analysis(target.file)
.and_then(|a| a.semantics.symbol(target.symbol).map(|s| (s.scope, &a.semantics)))
.and_then(|(declared_in, sem)| enclosing_unit(sem, declared_in));
let sources: Vec<_> =
(0..scope.len()).filter_map(|i| Some((scope.path(i)?, scope.text(i)?))).collect();
let mut home = home_of(&sources, target.file, &edited);
let scoped = unit.is_some() && !home.unknown;
let mut invoked = HashSet::new();
let mut carriers = Carriers::default();
if let (Some(unit), true) = (&unit, scoped) {
let defs = define_defs(scope);
carriers = Carriers::of(&defs, unit);
home.all.extend(files_binding_into(scope, unit, &carriers));
let texts: Vec<&str> = home.all.iter().filter_map(|&i| scope.text(i)).collect();
invoked = invoked_from(&texts, &defs);
}
Scoping {
unit,
scoped,
declaring: target.file,
symbol: target.symbol,
name: target.name.clone(),
home,
invoked,
carriers,
}
}
/// The module or interface the declaration is a member of, when spellings
/// are scoped to it.
pub(super) fn unit(&self) -> Option<&str> {
self.unit.as_deref().filter(|_| self.scoped)
}
/// The files the preprocessor pastes into or around the declaring file
/// (H4's fragments), each with whether the declaring file includes it
/// (`true`) or it is on the including side (`false`).
pub(super) fn pasted(&self) -> Vec<(usize, bool)> {
let included = self.home.included.iter().map(|&i| (i, true));
included.chain(self.home.around.iter().map(|&i| (i, false))).collect()
}
/// The declaring file's source index.
pub(super) fn declaring(&self) -> usize {
self.declaring
}
/// Whether a `` `define`` of macro `macro_name` in `file`, whose body
/// spells the name (`params`: its formal arguments), is news.
///
/// The unscoped fallback and a dotted spelling are news first; only then
/// may a parameter named like the declaration silence the body's bare
/// spellings (they are the parameter) — never a bare spelling in a
/// default argument (`default_bare`), which expands in the caller.
pub(super) fn keeps_define_body(
&self,
file: usize,
macro_name: &str,
params: &[String],
dotted: bool,
default_bare: bool,
) -> bool {
if !self.scoped || dotted {
return true;
}
let shadowed =
params.iter().any(|p| p.split('=').next().is_some_and(|p| p.trim() == self.name));
if shadowed && !default_bare {
return false;
}
self.home.all.contains(&file)
|| self.invoked.contains(macro_name)
|| self.carriers.binds(macro_name)
}
/// Whether argument `position` of an invocation of `macro_name` may
/// reach the declaration wherever it is written (`carry.rs`).
pub(super) fn carries(&self, macro_name: &str, position: usize) -> bool {
!self.scoped || self.carriers.carries(macro_name, position)
}
/// Whether a spelling in `file` — dotted or bare, at `offset` — is news.
pub(super) fn keeps(&self, scope: &Scope, file: usize, dotted: bool, offset: u32) -> bool {
!self.scoped || dotted || self.bare_is_news(scope, file, offset)
}
/// A bare spelling: in a pasted file always (no scope to look in); in the
/// declaring file and an edited file when the lookup there finds the
/// declaration — only the declaring file's own analysis can; elsewhere
/// never.
fn bare_is_news(&self, scope: &Scope, file: usize, offset: u32) -> bool {
if self.home.included.contains(&file) || self.home.around.contains(&file) {
return true;
}
if file != self.declaring {
return false;
}
let Some(analysis) = scope.cached(file) else { return true };
nearest(&analysis.semantics, offset, &self.name) == Some(self.symbol)
}
}
/// K2: every file holding a `bind` into `unit` (by name or by an instance
/// path), or invoking a macro that expands to one — home, so the macros it
/// invokes are followed.
fn files_binding_into(scope: &Scope, unit: &str, carriers: &Carriers) -> Vec<usize> {
(0..scope.len())
.filter(|&i| {
let Some(text) = scope.text(i) else { return false };
let invokes_binder = carriers.any_binder()
&& text.contains('`')
&& macro_names(text).iter().any(|m| carriers.binds(m));
if invokes_binder {
return true;
}
if !super::contains_word(text, "bind") {
return false;
}
// A file that spells `bind` but does not lex is counted (L-4).
vlog_parser::tokenize(text).map_or(true, |tokens| !binds_into(&tokens, unit).is_empty())
})
.collect()
}
impl<'a> Scope<'a> {
/// H4: bare uses of the name in the plain code of a file the declaring
/// file includes (or that includes it). That text is analysed on its own,
/// outside the module's scope, so no reference there is the declaration's
/// and the rename cannot edit it: one warning per file, with its lines.
/// A use the rename does edit (`edits`: a cross-file reference the index
/// resolved, such as an instantiation of a renamed module) is not one.
pub(super) fn fragment_use_warnings(
&mut self,
scoping: &Scoping,
edits: &[(usize, Vec<TextEdit>)],
) -> Vec<String> {
let name = scoping.name.clone();
let declaring = self.name_at(scoping.declaring());
let mut out = Vec::new();
for (file, included) in scoping.pasted() {
let Some(text) = self.text(file) else { continue };
if !super::contains_word(text, &name) {
continue;
}
let shown = self.name_at(file);
let relation = match included {
true => format!("a file `{declaring}` includes"),
false => format!("a file that includes `{declaring}` or is included with it"),
};
// A fragment that does not lex cannot be scanned: say it spells
// the name rather than drop it (review L-4).
let tokens = vlog_parser::tokenize(text).ok();
let (Some(tokens), Some(analysis)) = (tokens, self.analysis(file)) else {
out.push(format!(
"{shown}: `{name}` is spelled in {relation}, which lucisv could not read, and was left unchanged."
));
continue;
};
let edited: Vec<TextRange> = edits
.iter()
.filter(|(i, _)| *i == file)
.flat_map(|(_, e)| e.iter().map(|e| e.range))
.collect();
let lines = bare_unbound_uses(&analysis.semantics, &tokens, &name, &edited);
if lines.is_empty() {
continue;
}
let at = lines.iter().map(u32::to_string).collect::<Vec<_>>().join(",");
out.push(format!(
"{shown}:{at}: `{name}` is used in {relation} and was left unchanged; lucisv does not rename inside `included text."
));
}
out
}
}
/// The lines of `name` tokens in one fragment's plain code that are a use no
/// declaration of that fragment answers: not a declaration, not after a `.`,
/// not a reference resolved inside the fragment itself, and not covered by
/// one of the rename's `edited` ranges in it.
fn bare_unbound_uses(
sem: &Semantics,
tokens: &[Token],
name: &str,
edited: &[TextRange],
) -> Vec<u32> {
let mut lines: Vec<u32> = Vec::new();
for (i, token) in tokens.iter().enumerate() {
if token.kind != TokenKind::Ident || token.text != name {
continue;
}
if i.checked_sub(1).and_then(|p| tokens.get(p)).is_some_and(|t| t.is_sym(".")) {
continue;
}
if sem.symbol_at(token.span.start).is_some() {
continue;
}
if edited.iter().any(|e| e.start <= token.span.start && token.span.end <= e.end) {
continue;
}
let local = sem.reference_at(token.span.start).is_some_and(|r| r.resolved().is_some());
if !local && lines.last() != Some(&token.line) {
lines.push(token.line);
}
}
lines
}
/// H3: the byte ranges of the `bind` statements in one file whose target is
/// `unit` — by name, or by an instance path, which lucisv cannot follow to a
/// unit and so counts — from `bind` to its `;`.
pub(super) fn binds_into(tokens: &[Token], unit: &str) -> Vec<TextRange> {
let mut out = Vec::new();
for (i, token) in tokens.iter().enumerate() {
// `bind` lexes as an identifier (it is not a reserved word of every
// standard the lexer serves); a `bind` statement starts with it.
if !(token.kind == TokenKind::Ident && token.text == "bind") {
continue;
}
let Some(target) = tokens.get(i + 1) else { continue };
let path = tokens.get(i + 2).is_some_and(|t| t.is_sym(".") || t.is_sym("["));
if target.text != unit && !path {
continue;
}
let Some(end) = tokens[i..].iter().find(|t| t.is_sym(";")) else { continue };
out.push(TextRange::new(token.span.start, end.span.end));
}
out
}
/// Macro name → every `` `define`` of it in the set.
fn define_defs(scope: &Scope) -> Defs {
let mut out = Defs::new();
for i in 0..scope.len() {
let Some(defines) = scope.file_id(i).and_then(|id| scope.index().defines(id)) else {
continue;
};
for define in defines.entries() {
let params = define.params.clone().unwrap_or_default();
let def = MacroDef { params, body: define.body.clone() };
out.entry(define.name.clone()).or_default().push(def);
}
}
out
}
/// The module or interface a declaration written in `scope` is a member of:
/// the first owned scope outward that is an instantiable unit's (a block,
/// function or task in between does not end the walk). A package, a class or
/// the file scope ends it with `None`.
fn enclosing_unit(sem: &Semantics, scope: ScopeId) -> Option<String> {
let mut here = Some(scope);
while let Some(id) = here {
let current = sem.scope(id)?;
if let Some(owner) = current.owner.and_then(|o| sem.symbol(o)) {
if owner.kind.is_instantiable() {
return Some(owner.name.clone());
}
if matches!(
owner.kind,
vlog_semantic::SymbolKind::Package | vlog_semantic::SymbolKind::Class
) {
return None;
}
}
here = current.parent;
}
None
}
/// The whole-word spellings of `name` in `text`: the byte offsets of the bare
/// ones, and whether any is dotted (a `.` before it, past blanks).
pub(super) fn spellings(text: &str, name: &str) -> (Vec<usize>, bool) {
let bytes = text.as_bytes();
let word = |b: u8| b.is_ascii_alphanumeric() || b == b'_' || b == b'$';
let (mut bare, mut dotted) = (Vec::new(), false);
let mut from = 0;
while let Some(hit) = text.get(from..).and_then(|s| s.find(name)) {
let start = from + hit;
let end = start + name.len();
from = start + 1;
let glued = start.checked_sub(1).and_then(|p| bytes.get(p)).is_some_and(|&b| word(b))
|| bytes.get(end).is_some_and(|&b| word(b));
if glued {
continue;
}
match after_dot(&text[..start]) {
true => dotted = true,
false => bare.push(start),
}
}
(bare, dotted)
}
/// Whether `before` ends in a `.`, past blanks, `` `` `` pastes
/// (`` u_m.``sig `` pastes a path) and block comments (`u_m./*x*/sig`,
/// review L-3).
fn after_dot(before: &str) -> bool {
let mut rest = before.trim_end();
loop {
if let Some(shorter) = rest.strip_suffix("``") {
rest = shorter.trim_end();
} else if let Some(open) = rest.strip_suffix("*/").and_then(|r| r.rfind("/*")) {
rest = rest[..open].trim_end();
} else {
return rest.ends_with('.');
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_spelling_is_dotted_past_blanks_and_bare_otherwise() {
assert_eq!(spellings("x(state_q, a.state_q)", "state_q"), (vec![2], true));
assert_eq!(spellings("x(u . state_q)", "state_q"), (vec![], true));
assert_eq!(spellings("x(state_qq, my_state_q)", "state_q"), (vec![], false));
assert_eq!(spellings("u_m.``state_q", "state_q"), (vec![], true));
assert_eq!(spellings("pre``state_q", "state_q"), (vec![5], false));
assert_eq!(spellings("u_m./*x*/state_q", "state_q"), (vec![], true));
assert_eq!(spellings("u_m. /* c */ state_q", "state_q"), (vec![], true));
assert_eq!(spellings("/* a. */ state_q", "state_q"), (vec![9], false));
}
}
+133 -19
View File
@@ -16,7 +16,6 @@
//! out in the order they always did.
use std::collections::HashMap;
use std::path::Path;
use vlog_parser::defines::DefineKind;
use vlog_parser::span::TextRange;
@@ -26,8 +25,10 @@ use vlog_semantic::{ExternalTarget, ReferenceId, Resolution};
use crate::TextEdit;
use super::carry::argument_position;
use super::scoped::{binds_into, spellings, Scoping};
use super::Target;
use crate::scope::{display, Scope};
use crate::scope::Scope;
use crate::trace::WarnTrace;
/// One file's token stream and its line index, built at most once per
@@ -93,6 +94,7 @@ impl<'a> Scope<'a> {
trace: &mut WarnTrace,
) -> Vec<String> {
let name = &target.name;
let scoping = Scoping::new(self, target, edits.iter().map(|(i, _)| *i).collect());
let (mut defines, mut macro_uses) = (Vec::new(), Vec::new());
let (mut fallbacks, mut unfinished) = (Vec::new(), Vec::new());
// The edited files' scans outlive the loop: the unaccounted scan runs
@@ -100,10 +102,15 @@ impl<'a> Scope<'a> {
let mut kept: HashMap<usize, FileScan> = HashMap::new();
for i in 0..self.len() {
let mut scan = FileScan::default();
defines.extend(trace.defines.measure(|| self.define_warnings(i, name, &mut scan)));
macro_uses
.extend(trace.macro_uses.measure(|| self.macro_use_warnings(i, name, &mut scan)));
fallbacks.extend(trace.sva.measure(|| self.sva_fallback_warnings(i, name, &mut scan)));
defines.extend(
trace.defines.measure(|| self.define_warnings(i, name, &scoping, &mut scan)),
);
macro_uses.extend(
trace.macro_uses.measure(|| self.macro_use_warnings(i, name, &scoping, &mut scan)),
);
fallbacks.extend(
trace.sva.measure(|| self.sva_fallback_warnings(i, name, &scoping, &mut scan)),
);
unfinished.extend(
trace.unfinished.measure(|| self.unresolved_candidate_warnings(i, name, &mut scan)),
);
@@ -118,6 +125,8 @@ impl<'a> Scope<'a> {
warnings.extend(macro_uses);
warnings.extend(fallbacks);
warnings.extend(unfinished);
warnings.extend(trace.paths.measure(|| self.path_warnings(target, edits)));
warnings.extend(trace.paths.measure(|| self.fragment_use_warnings(&scoping, edits)));
for (i, edits) in edits {
let mut scan = kept.remove(i).unwrap_or_default();
warnings.extend(
@@ -143,19 +152,27 @@ impl<'a> Scope<'a> {
edits: &[(usize, Vec<TextEdit>)],
) -> Vec<String> {
let name = &target.name;
let scoping = Scoping::new(self, target, edits.iter().map(|(i, _)| *i).collect());
let mut warnings = Vec::new();
for i in 0..self.len() {
warnings.extend(self.define_warnings(i, name, &mut FileScan::default()));
warnings.extend(self.define_warnings(i, name, &scoping, &mut FileScan::default()));
}
for i in 0..self.len() {
warnings.extend(self.macro_use_warnings(i, name, &mut FileScan::default()));
warnings.extend(self.macro_use_warnings(i, name, &scoping, &mut FileScan::default()));
}
for i in 0..self.len() {
warnings.extend(self.sva_fallback_warnings(i, name, &mut FileScan::default()));
warnings.extend(self.sva_fallback_warnings(
i,
name,
&scoping,
&mut FileScan::default(),
));
}
for i in 0..self.len() {
warnings.extend(self.unresolved_candidate_warnings(i, name, &mut FileScan::default()));
}
warnings.extend(self.path_warnings(target, edits));
warnings.extend(self.fragment_use_warnings(&scoping, edits));
for (i, edits) in edits {
warnings.extend(self.unaccounted_warnings(*i, name, edits, &mut FileScan::default()));
}
@@ -163,13 +180,39 @@ impl<'a> Scope<'a> {
warnings
}
/// The two hierarchical-path scans (`paths.rs`): segments in any file
/// that resolved to nothing, and the renamed member's same-named twins in
/// the other arms of its generate label.
fn path_warnings(&mut self, target: &Target, edits: &[(usize, Vec<TextEdit>)]) -> Vec<String> {
let edited: Vec<usize> = edits.iter().map(|(i, _)| *i).collect();
let mut out = self.unresolved_path_warnings(&target.name, &edited);
out.extend(self.sibling_arm_warnings(target));
out
}
/// lucisv does not preprocess, so a name that is also a macro name, or that
/// appears in a macro body, is left exactly as written — and said so.
fn define_warnings(&self, file: usize, name: &str, scan: &mut FileScan) -> Vec<String> {
let where_ = display(self.path(file).unwrap_or(Path::new("?")));
fn define_warnings(
&self,
file: usize,
name: &str,
scoping: &Scoping,
scan: &mut FileScan,
) -> Vec<String> {
let where_ = self.name_at(file);
let mut out = Vec::new();
for site in self.define_sites_with(file, name, scan) {
let line = site.line;
let body_news = scoping.keeps_define_body(
file,
&site.macro_name,
&site.params,
site.body_dotted,
site.default_bare,
);
if site.defines_the_name.is_none() && !body_news {
continue;
}
match site.defines_the_name {
Some(DefineKind::Define) => out.push(format!(
"`{name}` is also a macro defined at {where_}:{line}; macro names and macro uses are never renamed."
@@ -190,10 +233,39 @@ impl<'a> Scope<'a> {
/// so the name inside `` `BUMP(a) `` is invisible to the semantic layer and
/// cannot be edited. It can be seen, though — and silence would be worse
/// than a warning, because the expansion still spells the old name.
fn macro_use_warnings(&self, file: usize, name: &str, scan: &mut FileScan) -> Vec<String> {
let where_ = display(self.path(file).unwrap_or(Path::new("?")));
self.macro_argument_sites_with(file, name, scan)
fn macro_use_warnings(
&self,
file: usize,
name: &str,
scoping: &Scoping,
scan: &mut FileScan,
) -> Vec<String> {
let where_ = self.name_at(file);
let sites = self.macro_argument_sites_with(file, name, scan);
// H3: an argument inside a `bind` into the declaring unit is
// evaluated in that unit's scope, wherever the directive is written.
let binds = match (scoping.unit(), sites.is_empty()) {
(Some(unit), false) => {
let tokens = self.text(file).and_then(|text| scan.tokens(text));
tokens.map_or_else(Vec::new, |tokens| binds_into(tokens, unit))
}
_ => Vec::new(),
};
let bound = |at: u32| binds.iter().any(|r| r.start <= at && at < r.end);
// A bare argument the macro carries after a `.`, into a `bind` or into
// a macro the set does not define may reach the declaration from here
// (`carry.rs`, review H-1/H-2).
let news = |site: &ArgumentSite, at: u32, position: usize| {
bound(at)
|| scoping.carries(&site.macro_name, position)
|| scoping.keeps(self, file, false, at)
};
sites
.into_iter()
.filter(|site| {
site.dotted
|| site.bare.iter().zip(&site.positions).any(|(&at, &k)| news(site, at, k))
})
.map(|site| {
format!(
"`{name}` appears in the arguments of the macro invocation `{}` at {where_}:{} and was left unchanged; a macro invocation is one opaque token to lucisv, which does not expand macros.",
@@ -220,6 +292,7 @@ impl<'a> Scope<'a> {
&mut self,
file: usize,
name: &str,
scoping: &Scoping,
scan: &mut FileScan,
) -> Vec<String> {
let (Some(text), Some(path)) = (self.text(file), self.path(file)) else {
@@ -238,7 +311,7 @@ impl<'a> Scope<'a> {
covered.extend(analysis.semantics.references().iter().map(|r| r.name_span));
let (Some(tokens), lines) = scan.tokens_and_lines(text) else { return Vec::new() };
let mut at: Vec<u32> = Vec::new();
for token in tokens {
for (n, token) in tokens.iter().enumerate() {
if token.kind != TokenKind::Ident || token.text != name {
continue;
}
@@ -248,6 +321,11 @@ impl<'a> Scope<'a> {
if !regions.iter().any(|r| r.start <= token.span.start && token.span.end <= r.end) {
continue;
}
let dotted =
n.checked_sub(1).and_then(|p| tokens.get(p)).is_some_and(|t| t.is_sym("."));
if !scoping.keeps(self, file, dotted, token.span.start) {
continue;
}
at.push(lines.line_col(token.span.start).0);
}
at.dedup();
@@ -257,7 +335,7 @@ impl<'a> Scope<'a> {
let at = at.iter().map(u32::to_string).collect::<Vec<_>>().join(", ");
vec![format!(
"`{name}` is spelled inside an assertion lucisv could not structure in {} at line(s) {at} and was left unchanged; that property expression did not fit the SVA grammar, so it is kept as source text.",
display(path)
self.name_of(path)
)]
}
@@ -289,12 +367,29 @@ impl<'a> Scope<'a> {
macro_name: define.name.clone(),
line,
defines_the_name: Some(define.kind),
body_dotted: false,
default_bare: false,
params: Vec::new(),
});
} else if contains_word(&define.body, name) {
continue;
}
// A default argument (`(x = state_q)`) expands in the caller
// exactly as the body does, so it is scanned with it.
let params = define.params.clone().unwrap_or_default();
let defaults: String = params
.iter()
.filter_map(|p| p.split_once('=').map(|(_, d)| d))
.collect::<Vec<_>>()
.join(" ");
let (default_bare, default_dotted) = spellings(&defaults, name);
if contains_word(&define.body, name) || contains_word(&defaults, name) {
out.push(DefineSite {
macro_name: define.name.clone(),
line,
defines_the_name: None,
body_dotted: spellings(&define.body, name).1 || default_dotted,
default_bare: !default_bare.is_empty(),
params,
});
}
}
@@ -338,9 +433,15 @@ impl<'a> Scope<'a> {
if !contains_word(arguments, name) {
continue;
}
let opened = (token.text.len() - arguments.len()) as u32;
let (bare, dotted) = spellings(arguments, name);
let at = |offset: usize| token.span.start + opened + offset as u32;
out.push(ArgumentSite {
macro_name: macro_name_of(&token.text).to_string(),
line: lines.line_col(token.span.start).0,
dotted,
positions: bare.iter().map(|&b| argument_position(arguments, b)).collect(),
bare: bare.into_iter().map(at).collect(),
});
}
out
@@ -388,7 +489,7 @@ impl<'a> Scope<'a> {
let at = at.iter().map(u32::to_string).collect::<Vec<_>>().join(", ");
format!(
"`{name}` also occurs in {} at line(s) {at} as {reason}; lucisv records no reference there, so it was left unchanged.",
display(path)
self.name_of(path)
)
})
.collect()
@@ -422,7 +523,7 @@ impl<'a> Scope<'a> {
if !text.contains(name) {
return Vec::new();
}
let where_ = display(path).to_string();
let where_ = self.name_of(path);
let lines = scan.lines(text);
let Some(analysis) = self.analysis(file) else { return Vec::new() };
// Unit that could not be found → the lines it was named on.
@@ -485,6 +586,13 @@ pub(crate) struct DefineSite {
/// `Some` when the name *is* this macro's name; `None` when it only
/// appears in the macro's body.
pub(crate) defines_the_name: Option<DefineKind>,
/// Whether the body or a default argument spells the name after a `.`
/// (`scoped::spellings`).
pub(crate) body_dotted: bool,
/// Whether a default argument spells the name bare.
pub(crate) default_bare: bool,
/// The macro's formal arguments as written (`"a"`, `"b = 8"`).
pub(crate) params: Vec<String>,
}
/// A macro invocation whose arguments spell a name, found by
@@ -493,6 +601,12 @@ pub(crate) struct ArgumentSite {
pub(crate) macro_name: String,
/// 1-based line the invocation starts on.
pub(crate) line: u32,
/// Whether an argument spells the name after a `.`.
pub(crate) dotted: bool,
/// The file offsets of the argument spellings with no `.` before them.
pub(crate) bare: Vec<u32>,
/// For each of `bare`, the 0-based position of the argument holding it.
pub(crate) positions: Vec<usize>,
}
/// Why an identifier spelling the name is not a reference lucisv can edit,
+58 -1
View File
@@ -25,6 +25,7 @@
//! [`KnownFacts`]; `docs/features/perf5r-scope-reuse/README.md` has the rest.
use std::collections::HashMap;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use vlog_parser::parse_source_tolerant;
@@ -170,6 +171,8 @@ pub(crate) struct Scope<'a> {
/// [`Analysis`] that does not depend on the finished index. Moved into
/// `cache` the first time that file's analysis is asked for.
kept: HashMap<usize, Semantics>,
/// How many sources share each file name, for [`Scope::name_of`].
base_names: BaseNames,
}
impl<'a> Scope<'a> {
@@ -262,7 +265,8 @@ impl<'a> Scope<'a> {
.map(|(i, path)| (path.as_path(), FileId(i as u32)))
.collect();
let file_ids = sources.iter().map(|(path, _)| ids.get(path).copied()).collect();
Scope { sources, index, file_ids, cache: HashMap::new(), kept }
let base_names = BaseNames::of(sources.iter().map(|(p, _)| *p));
Scope { sources, index, file_ids, cache: HashMap::new(), kept, base_names }
}
pub(crate) fn len(&self) -> usize {
@@ -333,6 +337,19 @@ impl<'a> Scope<'a> {
pub(crate) fn index(&self) -> &WorkspaceIndex {
&self.index
}
/// How a file of this set is named in a message: its file name when no
/// other file in the set shares it, else the path the caller gave — two
/// `pwrmgr_if.sv` in one answer must name two findable files (§65.1
/// re-check R1). A front end makes the path relative as it does any other.
pub(crate) fn name_of(&self, path: &Path) -> String {
self.base_names.name(path)
}
/// [`Scope::name_of`] for the file at source index `i`.
pub(crate) fn name_at(&self, i: usize) -> String {
self.path(i).map_or_else(|| "?".to_string(), |path| self.name_of(path))
}
}
/// How a file is named in a message: its file name, because an absolute path
@@ -341,6 +358,36 @@ pub(crate) fn display(path: &Path) -> String {
path.file_name().and_then(|n| n.to_str()).unwrap_or("?").to_string()
}
/// How many files of a set share each file name, counted once so that
/// naming every file of a large set is linear, not quadratic (review M-2).
pub(crate) struct BaseNames(HashMap<OsString, usize>);
impl BaseNames {
/// The counts for the files at `all`.
pub(crate) fn of<'p>(all: impl IntoIterator<Item = &'p Path>) -> BaseNames {
let mut counts: HashMap<OsString, usize> = HashMap::new();
for path in all {
if let Some(base) = path.file_name() {
*counts.entry(base.to_os_string()).or_default() += 1;
}
}
BaseNames(counts)
}
/// [`display`] made unambiguous within the counted set: the file name
/// when no other path shares it, else the path as given. The one rule
/// [`Scope::name_of`] and a buffer-level planner (the port offers) both
/// name files by, so an offer and the refactoring it offers say the same
/// thing.
pub(crate) fn name(&self, path: &Path) -> String {
let shared = path.file_name().and_then(|b| self.0.get(b)).is_some_and(|&n| n > 1);
match shared {
true => path.display().to_string(),
false => display(path),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -548,4 +595,14 @@ mod tests {
assert_eq!(scope.index().fingerprint(), built.fingerprint());
assert!(scope.analysis(0).is_some(), "and every file still analyses on demand");
}
#[test]
fn a_file_name_another_file_shares_is_named_by_its_path() {
let paths = [Path::new("/a/x/if.sv"), Path::new("/a/y/if.sv"), Path::new("/a/top.sv")];
let names = BaseNames::of(paths);
assert_eq!(names.name(Path::new("/a/x/if.sv")), "/a/x/if.sv");
assert_eq!(names.name(Path::new("/a/y/if.sv")), "/a/y/if.sv");
assert_eq!(names.name(Path::new("/a/top.sv")), "top.sv");
assert_eq!(names.name(Path::new("/elsewhere/new.sv")), "new.sv", "outside the set");
}
}
+4 -1
View File
@@ -123,6 +123,8 @@ pub struct WarnTrace {
pub sva: Stage,
/// The unresolved-candidate scan.
pub unfinished: Stage,
/// The hierarchical-path scans: unresolved segments and same-label arms.
pub paths: Stage,
/// The edited files' unaccounted-occurrence scan.
pub unaccounted: Stage,
/// Files whose text spelled the name, and which were therefore lexed.
@@ -134,11 +136,12 @@ impl WarnTrace {
fn line(&self) -> String {
format!(
"warnings{{defines={:.1}ms macro_uses={:.1} sva={:.1} unfinished={:.1} \
unaccounted={:.1} scanned={}}}",
paths={:.1} unaccounted={:.1} scanned={}}}",
self.defines.ms,
self.macro_uses.ms,
self.sva.ms,
self.unfinished.ms,
self.paths.ms,
self.unaccounted.ms,
self.scanned,
)
+15
View File
@@ -412,3 +412,18 @@ fn an_unbound_escaped_port_is_terminated_too() {
let (_, diagnostics) = vlog_parser::parse_source_tolerant(&text);
assert!(diagnostics.is_empty(), "{diagnostics:?}\n{text}");
}
/// Review L-13: a refusal names a file by its path when another file of the
/// set shares its base name, as every other refactoring's message does.
#[test]
fn a_file_that_does_not_parse_is_named_by_its_path_when_its_name_is_shared() {
let broken = "module top;\n sub u (.*);\n assign = ;\nendmodule\n";
let set = files(&[
("/w/a/top.sv", broken),
("/w/b/top.sv", "module other;\nendmodule\n"),
("/w/sub.sv", "module sub (input logic clk);\nendmodule\n"),
]);
let refusal = expand_wildcard(&set, &PathBuf::from("/w/a/top.sv"), at(broken, ".*"))
.expect_err("refused");
assert!(refusal.starts_with("/w/a/top.sv does not parse"), "{refusal}");
}
@@ -0,0 +1,757 @@
//! QA attacks on TODO §65.1 (rename and references through a block label).
//!
//! Every test drives the public `rename` / `find_references` over a small
//! in-memory workspace. The contract under attack: every site is rewritten,
//! or the rename is refused or warns — never a silent partial rename.
//! `docs/features/generate-label-rename/README.md`, QA log 2026-09-30.
use std::path::{Path, PathBuf};
use vlog_refactor::{find_references, rename, RefactorEdit};
fn workspace(files: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
files.iter().map(|(name, text)| (path(name), text.to_string())).collect()
}
fn path(name: &str) -> PathBuf {
PathBuf::from("/rtl").join(name)
}
/// The offset of the first whole-word `name` at or after `prefix`.
fn at(text: &str, prefix: &str, name: &str) -> u32 {
let from =
text.find(prefix).unwrap_or_else(|| panic!("`{prefix}` is not in the text")) + prefix.len();
let is_word = |b: Option<&u8>| {
b.is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_' || *b == b'$' || *b == b'\\')
};
let bytes = text.as_bytes();
let mut search = from;
while let Some(hit) = text.get(search..).and_then(|s| s.find(name)) {
let start = search + hit;
let end = start + name.len();
let before = start.checked_sub(1).and_then(|i| bytes.get(i));
if (name.starts_with('\\') || !is_word(before)) && !is_word(bytes.get(end)) {
return start as u32;
}
search = start + 1;
}
panic!("`{name}` does not occur after `{prefix}`");
}
fn apply(text: &str, edit: &RefactorEdit, file: &Path) -> String {
let mut out = String::new();
let mut cursor = 0usize;
for e in edit.edits_for(file) {
out.push_str(&text[cursor..e.range.start as usize]);
out.push_str(&e.new_text);
cursor = e.range.end as usize;
}
out.push_str(&text[cursor..]);
out
}
type Renamed = Result<(Vec<String>, Vec<String>), String>;
/// Rename the `name` after `prefix` in `file`; every file's text afterwards,
/// and the warnings.
fn renamed(files: &[(&str, &str)], file: &str, prefix: &str, name: &str, new: &str) -> Renamed {
let sources = workspace(files);
let text = files.iter().find(|(n, _)| *n == file).map(|(_, t)| *t).expect("the file");
let edit = rename(&sources, &path(file), at(text, prefix, name), new)?;
let texts = files.iter().map(|(n, t)| apply(t, &edit, &path(n))).collect();
Ok((texts, edit.warnings))
}
/// `file:line:text` of every reference to the `name` after `prefix`.
fn references(files: &[(&str, &str)], file: &str, prefix: &str, name: &str) -> Vec<String> {
let sources = workspace(files);
let text = files.iter().find(|(n, _)| *n == file).map(|(_, t)| *t).expect("the file");
let found = find_references(&sources, &path(file), at(text, prefix, name), true)
.unwrap_or_else(|why| panic!("find_references refused: {why}"));
let mut out: Vec<String> = found
.iter()
.map(|(p, span)| {
let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("?");
let text = files.iter().find(|(n, _)| *n == name).map(|(_, t)| *t).expect("file");
let line = text[..span.start as usize].matches('\n').count() + 1;
format!("{name}:{line}:{}", &text[span.as_range()])
})
.collect();
out.sort();
out
}
/// A rename either rewrote every spelling of `old` in code (not comments) in
/// every file — edited or not — or said something: never a silent partial.
/// Callers keep unrelated declarations of `old` out of the workspace.
fn complete_or_loud(result: &Renamed, old: &str) {
let Ok((texts, warnings)) = result else { return };
if !warnings.is_empty() {
return;
}
for text in texts {
let code: String =
text.lines().map(|l| l.split("//").next().unwrap_or("")).collect::<Vec<_>>().join("\n");
let is_word = |b: u8| b.is_ascii_alphanumeric() || b == b'_';
let left = code.match_indices(old).any(|(i, _)| {
let b = code.as_bytes();
!(i > 0 && is_word(b[i - 1])) && !b.get(i + old.len()).is_some_and(|&c| is_word(c))
});
assert!(!left, "silent partial rename, `{old}` left behind:\n{text}");
}
}
// ---------------------------------------------------------------------------
// B. Scope semantics seen through references and rename
// ---------------------------------------------------------------------------
/// Two sibling `for` loops carrying one label (illegal, seen in the wild):
/// no crash, and a rename of the label is all or nothing.
const SIBLINGS: &str = "module sib (output logic o);
for (genvar i = 0; i < 2; i++) begin : g
logic a;
end
for (genvar j = 0; j < 2; j++) begin : g
logic b;
end
assign o = g[0].a;
endmodule
";
#[test]
fn sibling_loops_with_one_label_rename_as_one_label_without_a_crash() {
let result = renamed(&[("s.sv", SIBLINGS)], "s.sv", "begin : ", "g", "gg");
let (texts, _) = result.clone().expect("renames");
assert_eq!(texts[0], SIBLINGS.replace(": g\n", ": gg\n").replace("g[0]", "gg[0]"));
complete_or_loud(&result, "g");
let found = references(&[("s.sv", SIBLINGS)], "s.sv", "o = ", "g");
assert_eq!(found, vec!["s.sv:2:g", "s.sv:5:g", "s.sv:8:g"]);
}
/// A label that shadows an outer net of the same name: inside the outer
/// block the path's head is the inner block, outside it is the net.
const SHADOW: &str = "module sh (output logic o, output logic p);
logic g_a;
assign g_a = 1'b0;
if (1) begin : outer
if (1) begin : g_a
logic q;
end
assign o = g_a.q;
end
assign p = g_a;
endmodule
";
#[test]
fn a_label_shadowing_an_outer_net_takes_only_its_own_path() {
let (texts, warnings) =
renamed(&[("sh.sv", SHADOW)], "sh.sv", "begin : ", "g_a", "g_b").expect("renames");
assert!(warnings.is_empty(), "{warnings:?}");
assert_eq!(
texts[0],
SHADOW.replace("begin : g_a", "begin : g_b").replace("o = g_a.q", "o = g_b.q")
);
let (texts, _) =
renamed(&[("sh.sv", SHADOW)], "sh.sv", "logic ", "g_a", "n_a").expect("the net renames");
assert_eq!(
texts[0],
SHADOW
.replace("logic g_a;", "logic n_a;")
.replace("assign g_a", "assign n_a")
.replace("p = g_a;", "p = n_a;")
);
}
/// A declaration inside an **unnamed** generate `if` stays invisible outside
/// it; one inside `generate … endgenerate` is a name of the module.
#[test]
fn an_unnamed_generate_if_still_hides_its_declarations() {
let text = "module u (output logic o, output logic p);
generate
wire in_region;
if (1) begin
wire hidden;
end
endgenerate
assign o = in_region;
assign p = hidden;
endmodule
";
let found = references(&[("u.sv", text)], "u.sv", "wire ", "in_region");
assert_eq!(found, vec!["u.sv:3:in_region", "u.sv:8:in_region"]);
let found = references(&[("u.sv", text)], "u.sv", "wire ", "hidden");
assert_eq!(found, vec!["u.sv:5:hidden"], "the outer `hidden` is an implicit net, not this one");
}
/// Escaped labels: the label, its closing label and a path through it.
#[test]
fn an_escaped_label_is_renamed_with_its_path() {
let text = "module e (output logic o);
for (genvar i = 0; i < 2; i++) begin : \\g$lane
logic q;
end : \\g$lane
assign o = \\g$lane [0].q;
endmodule
";
let result = renamed(&[("e.sv", text)], "e.sv", "begin : ", "\\g$lane", "g_ln");
match &result {
Ok((texts, _)) => {
assert!(!texts[0].contains("\\g$lane"), "every escaped spelling moves:\n{}", texts[0]);
}
Err(why) => assert!(!why.is_empty()),
}
}
/// A label written in both arms of an `ifdef`: one name, all or nothing.
const IFDEF: &str = "module d (output logic o);
`ifdef WIDE
for (genvar i = 0; i < 4; i++) begin : g_w
logic q;
end : g_w
`else
for (genvar i = 0; i < 2; i++) begin : g_w
logic q;
end : g_w
`endif
assign o = g_w[0].q;
endmodule
";
#[test]
fn a_label_inside_an_ifdef_is_renamed_in_every_arm_or_the_rename_says_so() {
let result = renamed(&[("d.sv", IFDEF)], "d.sv", "o = ", "g_w", "g_v");
complete_or_loud(&result, "g_w");
if let Ok((texts, _)) = &result {
assert_eq!(texts[0], IFDEF.replace("g_w", "g_v"));
}
}
/// A label that is used only by its closing label.
#[test]
fn a_label_used_only_by_its_closing_label_moves_with_it() {
let text = "module c (input logic clk);
if (1) begin : g_only
logic q;
end : g_only
always_ff @(posedge clk) begin : p_only
end : p_only
endmodule
";
let (texts, _) = renamed(&[("c.sv", text)], "c.sv", "end : ", "g_only", "g_x").expect("g");
assert_eq!(texts[0], text.replace("g_only", "g_x"));
let (texts, _) = renamed(&[("c.sv", text)], "c.sv", "begin : ", "p_only", "p_x").expect("p");
assert_eq!(texts[0], text.replace("p_only", "p_x"));
}
/// Named blocks inside a function and a task, with `disable`.
#[test]
fn named_blocks_in_functions_and_tasks_rename_with_disable_and_closing_label() {
let text = "module f;
function automatic int ff(int a);
begin : fblk
if (a == 0) disable fblk;
ff = a;
end : fblk
endfunction
task automatic tt();
begin : tblk
disable tblk;
end : tblk
endtask
endmodule
";
let (texts, _) = renamed(&[("f.sv", text)], "f.sv", "disable ", "fblk", "f2").expect("f");
assert_eq!(texts[0], text.replace("fblk", "f2"));
let (texts, _) = renamed(&[("f.sv", text)], "f.sv", "end : ", "tblk", "t2").expect("t");
assert_eq!(texts[0], text.replace("tblk", "t2"));
}
/// Nested `g_a.g_b[2].x` from another file: every level renames.
const NSUB: &str = "module nsub;
if (1) begin : g_a
for (genvar j = 0; j < 4; j++) begin : g_b
logic x;
end : g_b
end : g_a
endmodule
";
const NTOP: &str = "module ntop (output logic o);
nsub u_n ();
assign o = u_n.g_a.g_b[2].x;
endmodule
";
#[test]
fn every_level_of_a_nested_cross_file_path_renames() {
let files = [("nsub.sv", NSUB), ("ntop.sv", NTOP)];
for (prefix, name, new) in
[("begin : ", "g_a", "g_top"), ("g_a\n for", "g_b", "g_bit"), ("logic ", "x", "xx")]
{
let (texts, warnings) = renamed(&files, "nsub.sv", prefix, name, new).expect(name);
assert!(warnings.is_empty(), "{name}: {warnings:?}");
let word = |t: &str| {
t.replace(&format!(": {name}\n"), &format!(": {new}\n"))
.replace(&format!(".{name}"), &format!(".{new}"))
.replace(&format!("logic {name};"), &format!("logic {new};"))
};
assert_eq!(texts[1], word(NTOP), "{name}");
assert!(!texts[0].contains(&format!(" {name}\n")), "{name}:\n{}", texts[0]);
// Started from the other file, the same edit.
let other = renamed(&files, "ntop.sv", "u_n.", name, new).expect(name);
assert_eq!(other.0, texts, "{name}");
}
}
/// A generate `case` with the same label in several arms, each with a
/// closing label.
#[test]
fn a_case_label_in_three_arms_renames_all_arms_and_the_path() {
let text = "module k #(parameter int P = 0) (output logic o);
case (P)
0: begin : g_c
logic z;
end : g_c
1: begin : g_c
logic z;
end : g_c
default: begin : g_c
logic z;
end : g_c
endcase
assign o = g_c.z;
endmodule
";
for start in ["0: begin : ", "1: begin : ", "default: begin : ", "o = "] {
let (texts, _) = renamed(&[("k.sv", text)], "k.sv", start, "g_c", "g_d").expect(start);
assert_eq!(texts[0], text.replace("g_c", "g_d"), "from `{start}`");
}
}
/// Legal SystemVerilog: both arms of a generate `if` are labelled `g`, and a
/// member exists only in the second one (IEEE 1800 §27.5 — only one arm is
/// elaborated, so `g.b` is valid whenever the `else` arm is).
const ARMS: &str = "module a #(parameter bit P = 0) (output logic o, output logic p);
if (P) begin : g
logic a;
end else begin : g
logic b;
end
assign o = g.a;
assign p = g.b;
endmodule
";
#[test]
fn a_member_only_the_second_arm_declares_is_never_silently_left_behind() {
let result = renamed(&[("a.sv", ARMS)], "a.sv", "logic ", "b", "b2");
complete_or_loud(&result, "b");
}
#[test]
fn a_member_both_arms_declare_is_never_silently_split() {
// `g.x` means the first arm's `x` or the second's depending on `P`:
// renaming one arm's `x` and the path leaves the other arm without it.
let text = "module b2 #(parameter bit P = 0) (output logic o);
if (P) begin : g
logic x;
end else begin : g
logic x;
end
assign o = g.x;
endmodule
";
let result = renamed(&[("b.sv", text)], "b.sv", "logic ", "x", "y");
complete_or_loud(&result, "x");
// Lead's ruling on F2: a warning naming the other arm's declaration; no
// refusal and no extra rewrite.
let (texts, warnings) = result.expect("renames");
assert_eq!(texts[0], text.replacen("logic x;", "logic y;", 1).replace("g.x", "g.y"));
assert!(
warnings.iter().any(|w| w.contains("b.sv:5") && w.contains("another arm labelled `g`")),
"{warnings:?}"
);
}
// ---------------------------------------------------------------------------
// Element selects on things that are not generate arrays
// ---------------------------------------------------------------------------
const PKG: &str = "package pk;
typedef struct packed { logic f; logic g; } pkt_t;
typedef pkt_t arr_t [2];
endpackage
";
#[test]
fn an_element_select_resolves_only_where_the_element_type_is_the_recorded_type() {
let text = "module s import pk::*; (output logic o, output logic p, output logic q);
pkt_t [1:0] packed_arr;
pkt_t unpacked_arr [2];
logic [3:0] vec;
assign o = packed_arr[0].f;
assign p = unpacked_arr[1].f;
assign q = vec[0].f;
endmodule
";
let files = [("pk.sv", PKG), ("s.sv", text)];
let found = references(&files, "pk.sv", "packed { logic ", "f");
// The packed array's element is a `pkt_t`: a reference. The others must
// never resolve to the struct's `f` through a type they do not have.
assert!(found.contains(&"s.sv:5:f".to_string()), "{found:?}");
assert!(
!found.contains(&"s.sv:7:f".to_string()),
"`vec[0].f` is not a struct field: {found:?}"
);
// Renaming the field is complete or loud about the unpacked array.
let result = renamed(&files, "pk.sv", "packed { logic ", "f", "ff");
complete_or_loud(&result, "f");
}
#[test]
fn an_instance_array_and_an_interface_array_path_is_not_a_wrong_answer() {
let leaf = "module leaf (output logic sig);
assign sig = 1'b0;
endmodule
interface bus_if;
logic sig;
endinterface
";
let top = "module top (output logic o, output logic p);
leaf u_arr [2] (.sig());
bus_if b_arr [2] ();
assign o = u_arr[1].sig;
assign p = b_arr[0].sig;
endmodule
";
let files = [("leaf.sv", leaf), ("top.sv", top)];
let found = references(&files, "leaf.sv", "interface bus_if;\n logic ", "sig");
for f in &found {
assert!(!f.starts_with("top.sv:4"), "`u_arr[1].sig` is leaf's port, not bus_if's: {f}");
}
let found = references(&files, "leaf.sv", "output logic ", "sig");
for f in &found {
assert!(!f.starts_with("top.sv:5"), "`b_arr[0].sig` is bus_if's, not leaf's: {f}");
}
}
// ---------------------------------------------------------------------------
// C. Rename attacks
// ---------------------------------------------------------------------------
#[test]
fn renaming_a_label_to_a_name_the_enclosing_scope_declares_is_refused() {
let text = "module r (output logic o);
logic taken;
if (1) begin : g_x
logic q;
end
for (genvar i = 0; i < 2; i++) begin : g_y
logic q;
end
assign o = taken;
endmodule
";
for (prefix, label) in [("begin : ", "g_x"), ("begin : g_x", "g_y")] {
let why = renamed(&[("r.sv", text)], "r.sv", prefix, label, "taken");
assert!(why.is_err(), "`{label}` → `taken` collides in the module: {why:?}");
// and to a sibling block's label
let other = if label == "g_x" { "g_y" } else { "g_x" };
let why = renamed(&[("r.sv", text)], "r.sv", prefix, label, other);
assert!(why.is_err(), "`{label}` → `{other}` collides with the other block: {why:?}");
}
// A net renamed to a block's label collides too.
let why = renamed(&[("r.sv", text)], "r.sv", "logic ", "taken", "g_x");
assert!(why.is_err(), "`taken` → `g_x` collides with the block label: {why:?}");
}
#[test]
fn a_label_renamed_there_and_back_restores_every_byte() {
let files = [("nsub.sv", NSUB), ("ntop.sv", NTOP)];
let (once, _) = renamed(&files, "nsub.sv", "g_a\n for", "g_b", "g_q").expect("there");
let back_files = [("nsub.sv", once[0].as_str()), ("ntop.sv", once[1].as_str())];
let (twice, _) = renamed(&back_files, "ntop.sv", "u_n.g_a.", "g_q", "g_b").expect("back");
assert_eq!(twice, vec![NSUB.to_string(), NTOP.to_string()]);
}
#[test]
fn a_net_inside_a_block_renamed_through_a_bind_and_a_path_from_two_files() {
let sub = "module sub (input logic clk);
for (genvar i = 0; i < 2; i++) begin : g_lane
logic sig;
assign sig = clk;
end
endmodule
";
let top = "module top (input logic clk, output logic o);
sub u_x (.clk);
assign o = u_x.g_lane[1].sig;
endmodule
";
let tb = "module tb;
logic clk, o;
top dut (.clk, .o);
initial $display(\"%b\", dut.u_x.g_lane[0].sig);
endmodule
";
let files = [("sub.sv", sub), ("top.sv", top), ("tb.sv", tb)];
let (texts, warnings) = renamed(&files, "tb.sv", "g_lane[0].", "sig", "sig_q").expect("ok");
assert!(warnings.is_empty(), "{warnings:?}");
assert_eq!(
texts[0],
sub.replace("logic sig;", "logic sig_q;").replace("assign sig ", "assign sig_q ")
);
assert_eq!(texts[1], top.replace(".sig", ".sig_q"));
assert_eq!(texts[2], tb.replace(".sig)", ".sig_q)"));
}
/// The opentitan DV shape (`keymgr_dpe_if.sv:514`, `force
/// tb.dut.gen_sw_assigns[i].hw_key_sel_buf[0] = …`): a path rooted at a
/// top-level module declared in another file. lucisv records nothing for it
/// (0.59.0 neither, for a net), and the file is not edited, so the stray
/// scan never looks at it either — the rename is silently partial.
#[test]
fn a_path_rooted_at_another_files_top_module_is_never_silently_left_behind() {
let dut = "module dut_a;
for (genvar i = 0; i < 2; i++) begin : g_sw
logic buf_q;
end
endmodule
";
let tb = "module tb;
dut_a dut ();
endmodule
";
let probe = "module probe (output logic o);
assign o = tb.dut.g_sw[0].buf_q;
endmodule
";
let files = [("dut_a.sv", dut), ("tb.sv", tb), ("probe.sv", probe)];
complete_or_loud(&renamed(&files, "dut_a.sv", "begin : ", "g_sw", "g_hw"), "g_sw");
complete_or_loud(&renamed(&files, "dut_a.sv", "logic ", "buf_q", "buf_r"), "buf_q");
// Lead's ruling on F1: the path rooted at another file's top module does
// not resolve, so it is left unchanged — and said so, with its line.
for (prefix, old, new) in [("begin : ", "g_sw", "g_hw"), ("logic ", "buf_q", "buf_r")] {
let (texts, warnings) = renamed(&files, "dut_a.sv", prefix, old, new).expect("renames");
assert_eq!(texts[0], dut.replace(old, new), "the declaration moves");
assert_eq!((texts[1].as_str(), texts[2].as_str()), (tb, probe), "nothing else is edited");
let said: Vec<&String> = warnings.iter().filter(|w| w.contains("probe.sv:2:")).collect();
assert_eq!(said.len(), 1, "one warning for the unresolved path: {warnings:?}");
assert!(said[0].contains(&format!("`{old}`")), "{said:?}");
}
}
#[test]
fn a_same_named_block_in_another_module_is_never_touched() {
let sub = "module sub (input logic clk);
for (genvar i = 0; i < 2; i++) begin : g_lane
logic sig;
end : g_lane
endmodule
";
let other = sub.replace("module sub", "module other");
let top = "module top (input logic clk, output logic o, output logic p);
sub u_x (.clk);
other u_y (.clk);
assign o = u_x.g_lane[1].sig;
assign p = u_y.g_lane[0].sig;
endmodule
";
let files = [("sub.sv", sub), ("other.sv", other.as_str()), ("top.sv", top)];
let (texts, warnings) = renamed(&files, "top.sv", "u_x.", "g_lane", "g_ln").expect("renames");
assert!(warnings.is_empty(), "{warnings:?}");
assert_eq!(texts[0], sub.replace("g_lane", "g_ln"));
assert_eq!(texts[1], other, "`other`'s block is another declaration");
assert_eq!(texts[2], top.replace("u_x.g_lane", "u_x.g_ln"));
}
#[test]
fn renaming_a_label_to_its_loops_genvar_is_refused_when_a_path_inside_would_be_captured() {
let text = "module inside (output logic o);
for (genvar gi = 0; gi < 2; gi++) begin : g_lane
logic sig;
assign sig = g_lane[0].sig;
end
assign o = g_lane[1].sig;
endmodule
";
let why = renamed(&[("i.sv", text)], "i.sv", "begin : ", "g_lane", "gi");
assert!(why.is_err(), "`gi[0].sig` inside the body would name the genvar: {why:?}");
}
// ---------------------------------------------------------------------------
// Re-check 2026-09-30: the rework's unresolved-path and sibling-arm warnings
// ---------------------------------------------------------------------------
const RC_DUT: &str = "module dut_a;
for (genvar i = 0; i < 2; i++) begin : g_sw
logic buf_q;
end
endmodule
";
const RC_OTHER: &str = "module dut_b;
for (genvar i = 0; i < 2; i++) begin : g_sw
logic buf_q;
end
endmodule
";
const RC_TB: &str = "module tb;
dut_a dut ();
dut_b other ();
endmodule
";
/// Every shape a path through `g_sw` rooted at another file's `tb` takes.
const RC_PROBE: &str = "module probe (output logic o);
initial force tb.dut.g_sw[0].buf_q = 1'b0;
initial release tb.dut.g_sw[0].buf_q;
initial $assertoff(0, tb.dut.g_sw[1]);
assign o = tb.dut
.g_sw[1]
.buf_q;
// tb.dut.g_sw[0].buf_q in a comment
initial $display(\"tb.dut.g_sw[0]\");
unknown_mod u_unk (.g_sw(1'b0));
endmodule
";
fn rc_files() -> Vec<(&'static str, &'static str)> {
vec![("dut_a.sv", RC_DUT), ("dut_b.sv", RC_OTHER), ("tb.sv", RC_TB), ("probe.sv", RC_PROBE)]
}
#[test]
fn recheck_every_unresolved_path_shape_is_named_once_with_its_lines() {
let (texts, warnings) =
renamed(&rc_files(), "dut_a.sv", "begin : ", "g_sw", "g_hw").expect("renames");
assert_eq!(texts[3], RC_PROBE, "the probe is never edited");
let said: Vec<&String> = warnings.iter().filter(|w| w.contains("probe.sv")).collect();
assert_eq!(said.len(), 1, "one line for the file: {warnings:?}");
assert!(said[0].starts_with("probe.sv:2,3,4,6:"), "{said:?}");
}
#[test]
fn recheck_a_path_that_resolves_to_another_declaration_is_not_warned_about() {
let user = "module user (output logic o);
dut_b u_b ();
assign o = u_b.g_sw[0].buf_q;
endmodule
";
let mut files = rc_files();
files.push(("user.sv", user));
let (_, warnings) = renamed(&files, "dut_a.sv", "begin : ", "g_sw", "g_hw").expect("renames");
assert!(!warnings.iter().any(|w| w.contains("user.sv")), "{warnings:?}");
}
#[test]
fn recheck_an_included_fragment_is_scanned_like_any_file() {
let frag = " initial force tb.dut.g_sw[0].buf_q = 1'b1;\n";
let host = "module host;\n`include \"frag.svh\"\nendmodule\n";
let mut files = rc_files();
files.push(("frag.svh", frag));
files.push(("host.sv", host));
let (_, warnings) = renamed(&files, "dut_a.sv", "begin : ", "g_sw", "g_hw").expect("renames");
assert!(warnings.iter().any(|w| w.starts_with("frag.svh:1:")), "{warnings:?}");
}
/// The word census holds no escaped identifier (`words.rs`: "an escaped
/// identifier is not a word"), so `paths.rs`'s census filter drops the file.
#[test]
fn recheck_an_escaped_label_behind_an_unresolved_root_is_named() {
let dut = "module dut_e;\n if (1) begin : \\g$sw \n logic q;\n end\nendmodule\n";
let tb = "module tbe;\n dut_e dut ();\nendmodule\n";
let probe = "module pe (output logic o);\n assign o = tbe.dut.\\g$sw .q;\nendmodule\n";
let files = [("dut_e.sv", dut), ("tbe.sv", tb), ("pe.sv", probe)];
let result = renamed(&files, "dut_e.sv", "begin : ", "\\g$sw", "g_hw");
complete_or_loud(&result, "\\g$sw");
let (_, warnings) = result.expect("renames");
assert!(warnings.iter().any(|w| w.starts_with("pe.sv:2:")), "{warnings:?}");
}
#[test]
fn recheck_sibling_arm_warnings_in_every_arm_shape() {
let three = "module t3 #(parameter int P = 0) (output logic o);
if (P == 0) begin : g
logic x;
end else if (P == 1) begin : g
logic x;
end else begin : g
logic x;
end
assign o = g.x;
endmodule
";
let case = "module tc #(parameter int P = 0) (output logic o);
case (P)
0: begin : g
logic x;
end
1: begin : g
logic x;
end
default: begin : g
logic x;
end
endcase
assign o = g.x;
endmodule
";
let ifdef = "module td (output logic o);
`ifdef A
if (1) begin : g
logic x;
end
`else
if (1) begin : g
logic x;
end
`endif
assign o = g.x;
endmodule
";
for (name, text, prefix, others) in [
("t3.sv", three, "P == 0) begin : g\n logic ", vec![5, 7]),
("t3.sv", three, "P == 1) begin : g\n logic ", vec![3, 7]),
("tc.sv", case, "0: begin : g\n logic ", vec![7, 10]),
("tc.sv", case, "default: begin : g\n logic ", vec![4, 7]),
("td.sv", ifdef, "`ifdef A\n if (1) begin : g\n logic ", vec![8]),
] {
let (_, warnings) = renamed(&[(name, text)], name, prefix, "x", "y").expect(name);
for line in others {
let at = format!("{name}:{line},");
assert!(
warnings.iter().any(|w| w.contains(&at) && w.contains("another arm")),
"{name} {prefix:?}: no warning for line {line}: {warnings:?}"
);
}
}
}
/// Nested arms: `g.h.x` reaches the `h` inside *either* arm of `g`. The
/// sibling scan looks only at the arms of the innermost label, so renaming
/// the `x` under `g`'s `else` arm leaves `g.h.x` (which resolves to the first
/// arm's) and says nothing — and renaming the first one warns about its
/// `h`-sibling at line 6 but not about line 10.
#[test]
fn recheck_sibling_arms_of_an_enclosing_label_are_warned_about() {
let nested = "module tn #(parameter bit P = 0, parameter bit Q = 0) (output logic o);
if (P) begin : g
if (Q) begin : h
logic x;
end else begin : h
logic x;
end
end else begin : g
if (1) begin : h
logic x;
end
end
assign o = g.h.x;
endmodule
";
let result = renamed(&[("tn.sv", nested)], "tn.sv", "if (1) begin : h\n logic ", "x", "y");
complete_or_loud(&result, "x");
let (_, warnings) =
renamed(&[("tn.sv", nested)], "tn.sv", "if (Q) begin : h\n logic ", "x", "y")
.expect("renames");
assert!(warnings.iter().any(|w| w.contains("tn.sv:10,")), "{warnings:?}");
}
@@ -0,0 +1,521 @@
//! QA attacks on TODO §65.1 rework 3 (`rename/scoped.rs`): a module member's
//! bare spelling in another file's macro argument, `` `define`` body or
//! unstructured assertion is no longer warned about. The danger is a HIDDEN
//! real use — text that expands into the declaring module's scope from
//! another file. `docs/features/generate-label-rename/README.md`, QA log.
use std::path::PathBuf;
use vlog_refactor::rename;
fn workspace(files: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
files.iter().map(|(name, text)| (PathBuf::from("/rtl").join(name), text.to_string())).collect()
}
/// Rename the first `logic <name>` (or `<prefix>` then `name`) in `file`;
/// the rewritten texts and the warnings, or the refusal.
fn run(
files: &[(&str, &str)],
file: &str,
prefix: &str,
name: &str,
new: &str,
) -> Result<(Vec<String>, Vec<String>), String> {
let sources = workspace(files);
let text = files.iter().find(|(n, _)| *n == file).map(|(_, t)| *t).expect("file");
let at = (text.find(prefix).expect("prefix") + prefix.len()) as u32;
let at = at + text[at as usize..].find(name).expect("name") as u32;
let edit = rename(&sources, &PathBuf::from("/rtl").join(file), at, new)?;
let texts = files
.iter()
.map(|(n, t)| {
let mut out = String::new();
let mut cursor = 0usize;
for e in edit.edits_for(&PathBuf::from("/rtl").join(n)) {
out.push_str(&t[cursor..e.range.start as usize]);
out.push_str(&e.new_text);
cursor = e.range.end as usize;
}
out.push_str(&t[cursor..]);
out
})
.collect();
Ok((texts, edit.warnings))
}
/// Whether some warning mentions `file` at `line` (`file:line` or `file at
/// line(s) … line`).
fn said(warnings: &[String], file: &str, line: u32) -> bool {
warnings.iter().any(|w| {
w.contains(&format!("{file}:{line}"))
|| (w.contains(file) && w.contains(&format!(" {line}")))
})
}
const ASSERT_DEFS: &str = "`define ASSERT(n, e) n: assert property (@(posedge clk) e);\n";
/// The opentitan `*_assert.svh` shape: the module includes a fragment whose
/// assertions name the module's own signals bare.
#[test]
fn a_bare_use_in_an_included_fragments_macro_argument_is_said() {
let module = "module m (input logic clk);
logic state_q;
always_ff @(posedge clk) state_q <= ~state_q;
`include \"m_assert.svh\"
endmodule
";
let frag = " `ASSERT(StateKnown_A, !$isunknown(state_q))\n";
let files = [("defs.svh", ASSERT_DEFS), ("m.sv", module), ("m_assert.svh", frag)];
let (_, warnings) = run(&files, "m.sv", "logic ", "state_q", "state_r").expect("renames");
assert!(said(&warnings, "m_assert.svh", 1), "HIDDEN USE: {warnings:#?}");
}
/// The same fragment with the use in plain code, not a macro.
#[test]
fn a_bare_use_in_plain_included_code_is_renamed_or_said() {
let module = "module m (input logic clk, output logic o);
logic state_q;
`include \"m_body.svh\"
endmodule
";
let frag = " assign o = state_q;\n";
let files = [("m.sv", module), ("m_body.svh", frag)];
let (texts, warnings) = run(&files, "m.sv", "logic ", "state_q", "state_r").expect("renames");
// Lead's ruling on H4: said, not renamed (renaming inside included
// fragments is TODO §65.6).
assert_eq!(texts[1], frag, "the fragment is not edited");
assert!(said(&warnings, "m_body.svh", 1), "{warnings:#?}");
}
/// A header's `` `define`` whose body spells the net bare, invoked in the
/// declaring module: the expansion is a real use.
#[test]
fn a_bare_use_in_a_header_macro_body_invoked_in_the_module_is_said() {
let defs = "`define CHK assert property (@(posedge clk) state_q != 0);\n";
let module = "module m (input logic clk);
logic state_q;
always_ff @(posedge clk) state_q <= ~state_q;
`CHK
endmodule
";
let files = [("chk.svh", defs), ("m.sv", module)];
let (_, warnings) = run(&files, "m.sv", "logic ", "state_q", "state_r").expect("renames");
assert!(said(&warnings, "chk.svh", 1), "HIDDEN USE: {warnings:#?}");
}
/// A bind file's connection names the target's net bare inside a macro
/// argument — evaluated in the bound scope.
#[test]
fn a_bare_use_in_a_bind_connection_macro_argument_is_said() {
let defs = "`define Q(x) x\n";
let module = "module m (input logic clk);
logic state_q;
always_ff @(posedge clk) state_q <= ~state_q;
endmodule
";
let chk = "module chk (input logic s);
endmodule
";
let bind = "module m_bind;
bind m chk u_chk (.s(`Q(state_q)));
endmodule
";
let files = [("defs.svh", defs), ("m.sv", module), ("chk.sv", chk), ("m_bind.sv", bind)];
let (texts, warnings) = run(&files, "m.sv", "logic ", "state_q", "state_r").expect("renames");
assert!(texts[3].contains("state_r") || said(&warnings, "m_bind.sv", 2), "{warnings:#?}");
}
/// Same file, several scopes: a function, a generate block and a nested
/// module see the net; an inner declaration of the same name shadows it.
#[test]
fn inside_the_declaring_file_the_lookup_respects_scopes_and_shadowing() {
let module = "module m (input logic clk);
logic state_q;
function automatic logic f();
return `Q(state_q);
endfunction
if (1) begin : g
assign x = `Q(state_q);
end
if (1) begin : h
logic state_q;
assign y = `Q(state_q);
end
endmodule
module other;
logic state_q;
assign z = `Q(state_q);
endmodule
";
let files = [("defs.svh", "`define Q(x) x\n"), ("m.sv", module)];
let (_, warnings) = run(&files, "m.sv", "logic ", "state_q", "state_r").expect("renames");
assert!(said(&warnings, "m.sv", 4), "the function's use: {warnings:#?}");
assert!(said(&warnings, "m.sv", 7), "the generate block's use: {warnings:#?}");
assert!(!said(&warnings, "m.sv", 11), "shadowed by h's own state_q: {warnings:#?}");
assert!(!said(&warnings, "m.sv", 16), "the other module's own: {warnings:#?}");
}
/// Unstructured assertion text and `ifdef`-disabled text in the declaring
/// file.
#[test]
fn unparsed_assertion_and_ifdef_text_in_the_declaring_file_is_said() {
let module = "module m (input logic clk);
logic state_q;
always_ff @(posedge clk) state_q <= ~state_q;
a_weird: assert property (@(posedge clk) state_q |-> ##[1:$] $$$ state_q);
`ifdef NEVER
`Q(state_q)
`endif
endmodule
";
let files = [("defs.svh", "`define Q(x) x\n"), ("m.sv", module)];
let (texts, warnings) = run(&files, "m.sv", "logic ", "state_q", "state_r").expect("renames");
assert!(texts[1].contains("$$$ state_r") || said(&warnings, "m.sv", 4), "{warnings:#?}");
assert!(said(&warnings, "m.sv", 6), "the ifdef'd macro argument: {warnings:#?}");
}
/// Rework 2, R1: three files named `probe.sv` at different depths, each with
/// an unresolved path — each warning must name a findable file.
#[test]
fn recheck_three_same_named_files_are_each_named_by_their_path() {
let dut = "module dut_a;\n for (genvar i = 0; i < 2; i++) begin : g_sw\n logic q;\n end\nendmodule\n";
let tb = "module tb;\n dut_a dut ();\nendmodule\n";
let probe = "module PROBE (output logic o);\n assign o = tb.dut.g_sw[0].q;\nendmodule\n";
let (p1, p2, p3) =
(probe.replace("PROBE", "p1"), probe.replace("PROBE", "p2"), probe.replace("PROBE", "p3"));
let files = [
("dut_a.sv", dut),
("tb.sv", tb),
("probe.sv", p1.as_str()),
("x/probe.sv", p2.as_str()),
("x/y/z/probe.sv", p3.as_str()),
];
let (_, warnings) = run(&files, "dut_a.sv", "begin : ", "g_sw", "g_hw").expect("renames");
let paths: Vec<&String> = warnings.iter().filter(|w| w.contains("hierarchical path")).collect();
assert_eq!(paths.len(), 3, "{warnings:#?}");
for w in &paths {
let named = w.split(':').next().unwrap_or("");
assert!(named.ends_with("probe.sv") && named.contains('/'), "unfindable: {w}");
}
let mut named: Vec<&str> = paths.iter().map(|w| w.split(':').next().unwrap_or("")).collect();
named.dedup();
assert_eq!(named.len(), 3, "three distinct names: {warnings:#?}");
}
/// Rework 2, R3: three levels of same-label arms.
#[test]
fn recheck_three_level_same_label_arms_are_all_warned_about() {
let text = "module t (output logic o);
if (1) begin : a
if (1) begin : b
if (1) begin : c
logic x;
end
end
end else begin : a
if (1) begin : b
if (1) begin : c
logic x;
end
end else begin : b
if (1) begin : c
logic x;
end
end
end
assign o = a.b.c.x;
endmodule
";
let (_, warnings) = run(&[("t.sv", text)], "t.sv", "logic ", "x", "y").expect("renames");
for line in [11, 15] {
assert!(
warnings.iter().any(|w| w.contains(&format!("t.sv:{line}"))),
"{line}: {warnings:#?}"
);
}
// …and from the deepest-else arm.
let (_, warnings) = run(
&[("t.sv", text)],
"t.sv",
"end else begin : b\n if (1) begin : c\n logic ",
"x",
"y",
)
.expect("renames");
for line in [5, 11] {
assert!(
warnings.iter().any(|w| w.contains(&format!("t.sv:{line}"))),
"{line}: {warnings:#?}"
);
}
}
/// Rework 2, R2: an escaped net and an escaped label behind an unresolved root.
#[test]
fn recheck_escaped_net_and_label_paths_are_named() {
let dut = "module dut_e;\n logic \\n$q ;\n if (1) begin : \\g$sw \n logic q;\n end\nendmodule\n";
let tb = "module tbe;\n dut_e dut ();\nendmodule\n";
let probe = "module pe (output logic o, output logic p);\n assign o = tbe.dut.\\g$sw .q;\n assign p = tbe.dut.\\n$q ;\nendmodule\n";
let files = [("dut_e.sv", dut), ("tbe.sv", tb), ("pe.sv", probe)];
let (_, warnings) = run(&files, "dut_e.sv", "begin : ", "\\g$sw", "g_hw").expect("label");
assert!(warnings.iter().any(|w| w.starts_with("pe.sv:2:")), "{warnings:#?}");
let (_, warnings) = run(&files, "dut_e.sv", "logic ", "\\n$q", "n_q").expect("net");
assert!(warnings.iter().any(|w| w.starts_with("pe.sv:3:")), "{warnings:#?}");
}
// ---------------------------------------------------------------------------
// Rework 4 (home set) attacks, 2026-09-30
// ---------------------------------------------------------------------------
const Q_DEFS: &str = "`define Q(x) x\n";
/// A module and a fragment it includes by `spelled`, the fragment naming
/// `state_q` bare in a macro argument; whether renaming `m.state_q` says so.
fn fragment_said(spelled: &str, frag_path: &str, extra: &[(&str, &str)]) -> (bool, Vec<String>) {
let module = format!(
"module m (input logic clk);\n logic state_q;\n always_ff @(posedge clk) state_q <= ~state_q;\n{spelled}\nendmodule\n"
);
let frag = " initial $display(\"%b\", `Q(state_q));\n";
let mut files: Vec<(&str, &str)> =
vec![("defs.svh", Q_DEFS), ("rtl/m.sv", &module), (frag_path, frag)];
files.extend_from_slice(extra);
let (_, warnings) = run(&files, "rtl/m.sv", "logic ", "state_q", "state_r").expect("renames");
let base = frag_path.rsplit('/').next().unwrap_or(frag_path);
(warnings.iter().any(|w| w.contains(base) && w.contains("macro invocation")), warnings)
}
#[test]
fn rework4_include_spellings_all_reach_the_fragment() {
for (spelled, path) in [
("`include \"../inc/m_assert.svh\"", "inc/m_assert.svh"),
("`include \"m_assert.svh\"", "deep/inc/dir/m_assert.svh"),
("`ifdef FOO\n`include \"m_assert.svh\"\n`endif", "rtl/m_assert.svh"),
("`include \"m_assert.svh\" // the assertions", "rtl/m_assert.svh"),
("`include \"m_assert.svh\"\r", "rtl/m_assert.svh"),
] {
let (ok, warnings) = fragment_said(spelled, path, &[]);
assert!(ok, "HIDDEN USE via {spelled:?} → {path}: {warnings:#?}");
}
}
#[test]
fn rework4_a_base_name_matching_two_files_takes_both() {
let other = ("other/m_assert.svh", " initial $display(\"%b\", `Q(state_q));\n");
let (ok, warnings) = fragment_said("`include \"m_assert.svh\"", "inc/m_assert.svh", &[other]);
assert!(ok, "{warnings:#?}");
let both =
warnings.iter().filter(|w| w.contains("m_assert.svh") && w.contains("macro")).count();
assert_eq!(both, 2, "both candidates are home: {warnings:#?}");
}
#[test]
fn rework4_three_level_includes_and_a_cycle_terminate_and_reach() {
let a = ("inc/a.svh", "`include \"b.svh\"\n");
let b = ("inc/b.svh", "`include \"m_assert.svh\"\n`include \"a.svh\"\n");
let (ok, warnings) = fragment_said("`include \"a.svh\"", "inc/m_assert.svh", &[a, b]);
assert!(ok, "three levels, with a cycle a → b → a: {warnings:#?}");
}
/// `` `include `FRAG `` — an include whose file name a macro builds.
#[test]
fn rework4_an_include_built_by_a_macro_is_followed_or_said() {
let defs = ("inc/paths.svh", "`define FRAG \"m_assert.svh\"\n");
let (ok, warnings) =
fragment_said("`include \"paths.svh\"\n`include `FRAG", "inc/m_assert.svh", &[defs]);
assert!(ok, "HIDDEN USE via `include `FRAG: {warnings:#?}");
}
/// The declaration sits in a fragment included by two modules: both
/// includers are home, and a bare use in either's macro argument is said.
#[test]
fn rework4_a_declaration_in_a_fragment_shared_by_two_modules() {
let decl = " logic shared_q;\n";
let m1 =
"module m1;\n`include \"decl.svh\"\n initial $display(\"%b\", `Q(shared_q));\nendmodule\n";
let m2 = "module m2;\n`include \"decl.svh\"\n assign o = shared_q;\nendmodule\n";
let files = [("defs.svh", Q_DEFS), ("decl.svh", decl), ("m1.sv", m1), ("m2.sv", m2)];
let result = run(&files, "decl.svh", "logic ", "shared_q", "shared_r");
let (_, warnings) = result.expect("renames");
assert!(said(&warnings, "m1.sv", 3), "m1's macro argument: {warnings:#?}");
assert!(said(&warnings, "m2.sv", 3), "m2's plain use: {warnings:#?}");
}
/// H2 closure and noise.
#[test]
fn rework4_define_bodies_reached_through_two_other_bodies() {
let hdr = "`define INNER state_q\n`define MID `INNER\n`define OUTER `MID\n";
let module = "module m (input logic clk, output logic [1:0] o);
logic state_q;
assign o = `OUTER;
endmodule
";
let files = [("hdr.svh", hdr), ("m.sv", module)];
let (_, warnings) = run(&files, "m.sv", "logic ", "state_q", "state_r").expect("renames");
let bodies: Vec<&String> = warnings.iter().filter(|w| w.contains("body of macro")).collect();
assert!(
bodies.iter().any(|w| w.contains("`INNER`")),
"HIDDEN USE through two bodies: {warnings:#?}"
);
}
/// Noise, not a hidden use: a macro whose parameter is named like the net,
/// and a macro "invoked" only inside a string.
#[test]
fn rework4_a_parameter_named_like_the_net_and_a_string_invocation_are_not_news() {
let hdr = "`define PARAM(state_q) (state_q + 1)\n`define UNUSED state_q\n";
let module = "module m (input logic clk, output logic [1:0] o);
logic state_q;
assign o = `PARAM(clk);
initial $display(\"`UNUSED\");
endmodule
";
let files = [("hdr.svh", hdr), ("m.sv", module)];
let (_, warnings) = run(&files, "m.sv", "logic ", "state_q", "state_r").expect("renames");
assert!(
!warnings.iter().any(|w| w.contains("`PARAM`") || w.contains("`UNUSED`")),
"{warnings:#?}"
);
}
/// H2 × H3: a bind file into the declaring module invokes a header macro
/// whose body spells the net bare.
#[test]
fn rework4_a_macro_invoked_inside_a_bind_into_the_unit_is_followed() {
let hdr = "`define SIG state_q\n";
let module = "module m (input logic clk);\n logic state_q;\nendmodule\n";
let chk = "module chk (input logic s);\nendmodule\n";
let bind = "module m_bind;\n bind m chk u_chk (.s(`SIG));\nendmodule\n";
let files = [("hdr.svh", hdr), ("m.sv", module), ("chk.sv", chk), ("m_bind.sv", bind)];
let (_, warnings) = run(&files, "m.sv", "logic ", "state_q", "state_r").expect("renames");
assert!(
warnings.iter().any(|w| w.contains("hdr.svh") || w.contains("m_bind.sv")),
"HIDDEN USE: {warnings:#?}"
);
}
/// H3 shapes: an instance path, an interface target, inside a generate.
#[test]
fn rework4_bind_by_path_to_an_interface_and_inside_a_generate() {
let ifc = "interface bus_if (input logic clk);\n logic state_q;\nendinterface\n";
let chk = "module chk (input logic s);\nendmodule\n";
let binds = "module binds;
bind bus_if chk u_a (.s(`Q(state_q)));
bind tb.u_bus chk u_b (.s(`Q(state_q)));
if (1) begin : g
bind bus_if chk u_c (.s(`Q(state_q)));
end
endmodule
";
let files = [("defs.svh", Q_DEFS), ("bus_if.sv", ifc), ("chk.sv", chk), ("binds.sv", binds)];
let (_, warnings) = run(&files, "bus_if.sv", "logic ", "state_q", "state_r").expect("renames");
for line in [2, 3, 5] {
assert!(said(&warnings, "binds.sv", line), "line {line}: {warnings:#?}");
}
}
/// H4: a fragment that declares its own `mem` is never rewritten; a fragment
/// only an unrelated module includes stays silent.
#[test]
fn rework4_fragment_uses_of_a_different_declaration_are_not_rewritten() {
let module = "module m;\n logic [7:0] mem;\n`include \"own.svh\"\nendmodule\n";
let own =
" function automatic int peek();\n logic [7:0] mem;\n return mem;\n endfunction\n";
let unrelated = "module u;\n logic [7:0] mem;\n`include \"far.svh\"\nendmodule\n";
let far = " initial mem = '0;\n";
let files = [("m.sv", module), ("own.svh", own), ("u.sv", unrelated), ("far.svh", far)];
let (texts, warnings) = run(&files, "m.sv", "logic [7:0] ", "mem", "mem_q").expect("renames");
assert_eq!(texts[1], own, "the fragment's own `mem` is never rewritten");
assert_eq!((texts[2].as_str(), texts[3].as_str()), (unrelated, far));
assert!(!warnings.iter().any(|w| w.contains("far.svh")), "{warnings:#?}");
}
// ---------------------------------------------------------------------------
// Rework 5 closing check, 2026-09-30
// ---------------------------------------------------------------------------
/// N1: renaming `sub.clk_i` edits `top` (its connection). `top` has no
/// `clk_i` of its own and spells one in a macro argument of the connection.
/// The bare spelling cannot name `sub`'s port; whatever is said, the port's
/// own module must still warn its own macro argument.
#[test]
fn rework5_an_edited_instantiator_without_its_own_name() {
let sub =
"module sub (input logic clk_i);\n initial $display(\"%b\", `Q(clk_i));\nendmodule\n";
let top = "module top (input logic c);\n sub u (.clk_i(`Q(clk_i)));\nendmodule\n";
let files = [("defs.svh", Q_DEFS), ("sub.sv", sub), ("top.sv", top)];
let (texts, warnings) = run(&files, "sub.sv", "logic ", "clk_i", "clk").expect("renames");
assert!(said(&warnings, "sub.sv", 2), "{warnings:#?}");
assert!(texts[2].contains(".clk("), "the connection's port name moves: {}", texts[2]);
}
/// N1: an edited file that also includes a fragment the declaring module
/// includes, and a nested module that re-declares the name.
#[test]
fn rework5_an_edited_file_sharing_a_fragment_or_nesting_a_redeclaration() {
let sub = "module sub (input logic clk_i);\n`include \"frag.svh\"\nendmodule\n";
let frag = " initial $display(\"%b\", `Q(clk_i));\n";
let top = "module top (input logic clk_i);\n`include \"frag.svh\"\n sub u (.clk_i);\n module inner;\n logic clk_i;\n initial $display(\"%b\", `Q(clk_i));\n endmodule\nendmodule\n";
let files = [("defs.svh", Q_DEFS), ("sub.sv", sub), ("frag.svh", frag), ("top.sv", top)];
let (_, warnings) = run(&files, "sub.sv", "logic ", "clk_i", "clk").expect("renames");
assert!(said(&warnings, "frag.svh", 1), "the shared fragment pastes into sub: {warnings:#?}");
assert!(!said(&warnings, "top.sv", 6), "inner's own clk_i: {warnings:#?}");
}
/// N2: a parameter named like the net silences only a body that has no
/// other way to the net. A path through the name in the body (`u_m.state_q`)
/// can reach it; 0.59.0 warned, rework 5 did not (QA P1: the parameter check
/// ran before `body_dotted` and the unscoped fallback). Fixed: both now come
/// first in `keeps_define_body`.
#[test]
fn rework5_a_shadowing_parameter_does_not_hide_a_dotted_body_spelling() {
let hdr = "`define PATHY(state_q) (state_q + u_m.state_q)\n";
let module = "module m (input logic clk, output logic [1:0] o);
logic state_q;
assign o = `PATHY(clk);
endmodule
";
let files = [("hdr.svh", hdr), ("m.sv", module)];
let (_, warnings) = run(&files, "m.sv", "logic ", "state_q", "state_r").expect("renames");
assert!(warnings.iter().any(|w| w.contains("`PATHY`")), "the dotted path: {warnings:#?}");
}
/// A default argument spelling the name expands into the module when the
/// macro is invoked without it. Silent in 0.59.0 too (QA P2: default
/// arguments were never scanned); now scanned with the body.
#[test]
fn rework5_a_default_argument_spelling_the_name_is_said() {
let hdr = "`define DFLT(x = state_q) (x)\n";
let module = "module m (input logic clk, output logic [1:0] o);
logic state_q;
assign o = `DFLT();
endmodule
";
let files = [("hdr.svh", hdr), ("m.sv", module)];
let (_, warnings) = run(&files, "m.sv", "logic ", "state_q", "state_r").expect("renames");
assert!(
warnings.iter().any(|w| w.contains("`DFLT`") || w.contains("hdr.svh:1")),
"{warnings:#?}"
);
}
/// K2 through a two-level instance path, and N3 three include levels up.
#[test]
fn rework5_bind_by_two_level_path_and_three_levels_of_includers() {
let hdr = "`define SIG state_q\n";
let m = "module m;\n logic state_q;\nendmodule\n";
let chk = "module chk (input logic s);\nendmodule\n";
let bind = "module b;\n bind tb.u_top.u_m chk u_chk (.s(`SIG));\nendmodule\n";
let files = [("hdr.svh", hdr), ("m.sv", m), ("chk.sv", chk), ("b.sv", bind)];
let (_, warnings) = run(&files, "m.sv", "logic ", "state_q", "state_r").expect("renames");
assert!(warnings.iter().any(|w| w.contains("hdr.svh") || w.contains("b.sv")), "{warnings:#?}");
let body = " logic deep_q;\n initial $display(\"%b\", `Q(deep_q));\n";
let l1 = "`include \"body.svh\"\n";
let l2 = "`include \"l1.svh\"\n";
let l3 = "module top;\n`include \"l2.svh\"\n initial $display(\"%b\", `Q(deep_q));\n assign o = deep_q;\nendmodule\n";
let files =
[("defs.svh", Q_DEFS), ("body.svh", body), ("l1.svh", l1), ("l2.svh", l2), ("top.sv", l3)];
let (_, warnings) = run(&files, "body.svh", "logic ", "deep_q", "deep_r").expect("renames");
assert!(said(&warnings, "top.sv", 3), "three levels up, macro argument: {warnings:#?}");
assert!(said(&warnings, "top.sv", 4), "three levels up, plain use: {warnings:#?}");
}
+10 -10
View File
@@ -963,15 +963,15 @@ fn a_tail_naming_a_parameter_is_renamed_across_files() {
);
}
/// The honest refusal, pinned. A net declared inside a **generate block** is
/// not a member of the module: its scope is the block's, and the member table
/// records a unit's own scope only. `u_x.gen_b.sig` therefore does not
/// resolve, the tail is left as written, and the rename says so rather than
/// editing half a design. Widening this means teaching the index about
/// generate scopes and their loop indices (`u_x.gen[0].sig`), which §49
/// deliberately did not do.
/// A net declared inside a **generate block**, named through an instance from
/// another file. Until TODO §65.1 this was the honest refusal pinned here: the
/// member table recorded a unit's own scope only, so `u_x.gen_b.sig` did not
/// resolve and the tail was left as written. A module's named blocks are now
/// on its hierarchical surface and their members under `sub.gen_b`, so the
/// tail is a reference and the rename rewrites it
/// (`docs/features/generate-label-rename/README.md`).
#[test]
fn a_generate_block_scoped_net_named_through_an_instance_is_refused_honestly() {
fn a_generate_block_scoped_net_named_through_an_instance_is_renamed_with_its_path() {
const SUB: &str = concat!(
"module sub;\n",
" if (1) begin : gen_b\n",
@@ -987,8 +987,8 @@ fn a_generate_block_scoped_net_named_through_an_instance_is_refused_honestly() {
assert!(apply(SUB, &edit, &path("sub.sv")).contains("wire signal;"), "the declaration moves");
assert_eq!(
apply(TOP, &edit, &path("top.sv")),
TOP,
"a generate-scoped name is not on either surface, so the tail is left alone"
TOP.replace("gen_b.sig", "gen_b.signal"),
"the tail through the block is a reference, so it moves with the declaration"
);
}
+14 -9
View File
@@ -535,12 +535,13 @@ endmodule
}
#[test]
fn a_bind_target_reached_through_a_generate_block_is_warned_about_never_guessed() {
// `bind tb.gen[0].u_aes …`: the middle hop is a generate block, which the
// index has no record of at all (an indexed segment "keeps only its
// name", per `bind_target_path`'s doc comment) — so the path is one the
// index cannot walk, and the contract is a warning, never a silent miss
// and never a guess at which `u_aes` is meant.
fn a_bind_target_reached_through_a_generate_block_is_followed_and_a_broken_one_warned_about() {
// `bind tb.gen[0].u_aes …`: the middle hop is a generate block. Until
// TODO §65.1 the index had no record of one and this path warned; a
// module's named blocks are now on its hierarchical surface, so the hop
// is walked (`tb` → `tb.gen` → `u_aes`'s `aes`) and the connection is
// renamed. A path naming a block `tb` does not have is still the
// warning, never a silent miss and never a guess.
let tb = "\
module tb;
if (1) begin : gen
@@ -555,23 +556,27 @@ module aes_bind;
);
endmodule
";
let broken = bind.replace("tb.gen[0]", "tb.nogen[0]").replace("aes_bind", "aes_bind2");
let mut files = rtl(bind);
files.push((path("tb.sv"), tb.to_string()));
files.push((path("aes_bind2.sv"), broken.clone()));
let edit =
rename(&files, &path("aes.sv"), at(AES, "logic", "entropy_masking_req"), "masking_req")
.expect("the rename over the rest of the design still succeeds");
assert_eq!(
apply(bind, &edit, &path("aes_bind.sv")),
bind,
"a path through a generate block is never guessed at: {edit:?}"
bind.replace("(entropy_masking_req)", "(masking_req)"),
"a path through a generate block is walked: {edit:?}"
);
assert_eq!(apply(&broken, &edit, &path("aes_bind2.sv")), broken, "never guessed at");
assert!(
edit.warnings
.iter()
.any(|w| w.contains("aes_bind.sv") && w.contains("could not be resolved")),
.any(|w| w.contains("aes_bind2.sv") && w.contains("could not be resolved")),
"the miss is said out loud rather than silently dropped: {:?}",
edit.warnings
);
assert!(!edit.warnings.iter().any(|w| w.contains("aes_bind.sv")), "{:?}", edit.warnings);
}
// ----------------------------------------------------------------------
@@ -0,0 +1,377 @@
//! A rename and a reference list through a block label (TODO §65.1, topo
//! §2.9-43, MCP-14).
//!
//! `rename` of `g_lane` in `for (…) begin : g_lane` used to rewrite the label
//! alone: the loop's label was bound inside the loop header's scope, so
//! `g_lane[0].lane_q` written beside the loop resolved to nothing, and a path
//! from another file (`u_x.g_lane[1].sig`) never reached the block at all.
//! Every test drives the public `rename` / `find_references` over a little
//! in-memory workspace and asserts the whole text of each file afterwards,
//! the reference list, or the refusal's sentence.
use std::path::{Path, PathBuf};
use vlog_refactor::{find_references, prepare_rename, rename, RefactorEdit};
fn workspace(files: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
files.iter().map(|(name, text)| (path(name), text.to_string())).collect()
}
fn path(name: &str) -> PathBuf {
PathBuf::from("/rtl").join(name)
}
/// The offset of the first whole-word `name` at or after `prefix`.
fn at(text: &str, prefix: &str, name: &str) -> u32 {
let from =
text.find(prefix).unwrap_or_else(|| panic!("`{prefix}` is not in the text")) + prefix.len();
let is_word = |b: Option<&u8>| b.is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_');
let bytes = text.as_bytes();
let mut search = from;
while let Some(hit) = text.get(search..).and_then(|s| s.find(name)) {
let start = search + hit;
let end = start + name.len();
if !is_word(start.checked_sub(1).and_then(|i| bytes.get(i))) && !is_word(bytes.get(end)) {
return start as u32;
}
search = start + 1;
}
panic!("`{name}` does not occur after `{prefix}`");
}
fn apply(text: &str, edit: &RefactorEdit, file: &Path) -> String {
let mut out = String::new();
let mut cursor = 0usize;
for e in edit.edits_for(file) {
out.push_str(&text[cursor..e.range.start as usize]);
out.push_str(&e.new_text);
cursor = e.range.end as usize;
}
out.push_str(&text[cursor..]);
out
}
/// Rename the `name` after `prefix` in `file`; every file's text afterwards,
/// and the warnings.
fn renamed(
files: &[(&str, &str)],
file: &str,
prefix: &str,
name: &str,
new_name: &str,
) -> Result<(Vec<String>, Vec<String>), String> {
let sources = workspace(files);
let text = files.iter().find(|(n, _)| *n == file).map(|(_, t)| *t).expect("the file");
let edit = rename(&sources, &path(file), at(text, prefix, name), new_name)?;
let texts = files.iter().map(|(n, t)| apply(t, &edit, &path(n))).collect();
Ok((texts, edit.warnings))
}
/// `(file, line text)` of every reference to the `name` after `prefix`.
fn references(files: &[(&str, &str)], file: &str, prefix: &str, name: &str) -> Vec<String> {
let sources = workspace(files);
let text = files.iter().find(|(n, _)| *n == file).map(|(_, t)| *t).expect("the file");
let found = find_references(&sources, &path(file), at(text, prefix, name), true)
.unwrap_or_else(|why| panic!("find_references refused: {why}"));
found
.iter()
.map(|(p, span)| {
let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("?");
let text = files.iter().find(|(n, _)| *n == name).map(|(_, t)| *t).expect("file");
let line = text[..span.start as usize].matches('\n').count() + 1;
format!("{name}:{line}:{}", &text[span.as_range()])
})
.collect()
}
/// The QA reproduction (MCP-14), with a closing label added.
const FSM: &str = "module fsm (input logic clk, output logic busy);
for (genvar gi = 0; gi < 2; gi++) begin : g_lane
logic lane_q;
assign lane_q = gi[0];
end : g_lane
always_comb begin
automatic logic tmp;
tmp = clk;
busy = tmp | g_lane[0].lane_q | g_lane[gi_top].lane_q;
end
localparam int gi_top = 1;
endmodule
";
#[test]
fn renaming_a_for_generate_label_rewrites_the_closing_label_and_every_indexed_path() {
let (texts, warnings) =
renamed(&[("fsm.sv", FSM)], "fsm.sv", "begin : ", "g_lane", "g_ln").expect("renames");
assert_eq!(texts[0], FSM.replace("g_lane", "g_ln"));
assert!(warnings.is_empty(), "{warnings:?}");
}
#[test]
fn the_rename_is_the_same_from_a_path_segment_and_from_the_closing_label() {
let from_decl = renamed(&[("fsm.sv", FSM)], "fsm.sv", "begin : ", "g_lane", "g_ln");
let from_use = renamed(&[("fsm.sv", FSM)], "fsm.sv", "tmp | ", "g_lane", "g_ln");
let from_end = renamed(&[("fsm.sv", FSM)], "fsm.sv", "end : ", "g_lane", "g_ln");
assert_eq!(from_decl, from_use);
assert_eq!(from_decl, from_end);
}
#[test]
fn find_references_on_the_label_lists_the_declaration_the_closing_label_and_every_segment() {
let found = references(&[("fsm.sv", FSM)], "fsm.sv", "tmp | ", "g_lane");
assert_eq!(
found,
vec!["fsm.sv:2:g_lane", "fsm.sv:5:g_lane", "fsm.sv:9:g_lane", "fsm.sv:9:g_lane"]
);
}
#[test]
fn a_variable_inside_the_block_is_renamed_through_the_path_too() {
let (texts, _) =
renamed(&[("fsm.sv", FSM)], "fsm.sv", "logic ", "lane_q", "lane_r").expect("renames");
assert_eq!(texts[0], FSM.replace("lane_q", "lane_r"));
}
const NESTED: &str = "module n (output logic o, output logic p);
if (1) begin : g_a
for (genvar j = 0; j < 4; j++) begin : g_b
logic x;
assign x = j[0];
end
logic y;
end
generate
case (2)
2: begin : g_c
logic z;
end
default: begin : g_c
logic z;
end : g_c
endcase
endgenerate
assign o = g_a.g_b[2].x ^ g_a.y;
assign p = g_c.z;
endmodule
";
#[test]
fn a_bare_a_nested_and_an_indexed_segment_are_all_references_to_their_labels() {
let (texts, _) = renamed(&[("n.sv", NESTED)], "n.sv", "begin : ", "g_a", "g_top").expect("a");
assert_eq!(texts[0], NESTED.replace("g_a", "g_top"));
let (texts, _) = renamed(&[("n.sv", NESTED)], "n.sv", "g_a.", "g_b", "g_bit").expect("b");
assert_eq!(texts[0], NESTED.replace("g_b", "g_bit"));
}
#[test]
fn a_label_both_arms_of_a_generate_case_carry_is_renamed_as_one_with_both_closing_labels() {
let (texts, _) = renamed(&[("n.sv", NESTED)], "n.sv", "p = ", "g_c", "g_d").expect("renames");
assert_eq!(texts[0], NESTED.replace("g_c", "g_d"));
}
const SUB: &str = "module sub (input logic clk);
for (genvar i = 0; i < 2; i++) begin : g_lane
logic sig;
assign sig = clk;
end : g_lane
logic plain;
endmodule
";
const TOP: &str = "module top (input logic clk, output logic o);
sub u_x (.clk);
assign o = u_x.g_lane[1].sig | u_x.g_lane[0].sig;
// g_lane is only a comment here
endmodule
";
fn cross() -> Vec<(&'static str, &'static str)> {
vec![("sub.sv", SUB), ("top.sv", TOP)]
}
#[test]
fn a_path_from_another_file_through_an_instance_is_rewritten_with_the_label() {
let (texts, _) = renamed(&cross(), "sub.sv", "begin : ", "g_lane", "g_ln").expect("renames");
assert_eq!(texts[0], SUB.replace("g_lane", "g_ln"));
assert_eq!(
texts[1],
TOP.replace("u_x.g_lane", "u_x.g_ln"),
"the comment is not a reference and stays"
);
}
#[test]
fn the_cross_file_rename_is_the_same_started_from_the_other_file() {
let from_decl = renamed(&cross(), "sub.sv", "begin : ", "g_lane", "g_ln");
let from_use = renamed(&cross(), "top.sv", "u_x.", "g_lane", "g_ln");
assert_eq!(from_decl, from_use);
}
#[test]
fn find_references_reaches_the_other_files_segments() {
let found = references(&cross(), "top.sv", "u_x.", "g_lane");
assert_eq!(
found,
vec!["sub.sv:2:g_lane", "sub.sv:5:g_lane", "top.sv:3:g_lane", "top.sv:3:g_lane"]
);
}
#[test]
fn a_signal_in_the_block_is_renamed_through_the_cross_file_path() {
let (texts, _) = renamed(&cross(), "sub.sv", "logic ", "sig", "sig_q").expect("renames");
assert_eq!(
texts[0],
SUB.replace("logic sig;", "logic sig_q;").replace("assign sig", "assign sig_q")
);
assert_eq!(texts[1], TOP.replace(".sig", ".sig_q"));
}
#[test]
fn a_spelling_in_a_macro_or_a_string_is_a_warning_and_the_rest_is_renamed() {
let text = "`define LANE(n) g_lane[n].lane_q
module m (output logic o, output logic p);
for (genvar i = 0; i < 2; i++) begin : g_lane
logic lane_q;
end
assign o = g_lane[0].lane_q;
assign p = `LANE(1);
initial $display(\"g_lane\");
endmodule
";
let (texts, warnings) =
renamed(&[("m.sv", text)], "m.sv", "begin : ", "g_lane", "g_ln").expect("renames");
assert!(texts[0].contains("begin : g_ln\n") && texts[0].contains("o = g_ln[0].lane_q;"));
assert!(texts[0].contains("`define LANE(n) g_lane[n]"), "macro text is not edited");
assert!(texts[0].contains("$display(\"g_lane\")"), "a string is not edited");
assert!(warnings.iter().any(|w| w.contains("LANE")), "{warnings:?}");
}
#[test]
fn an_unnamed_generate_block_has_no_label_to_rename() {
let text = "module m (output logic o);
if (1) begin
logic w;
end
assign o = genblk1.w;
endmodule
";
let files = workspace(&[("m.sv", text)]);
let why =
rename(&files, &path("m.sv"), at(text, "o = ", "genblk1"), "g_x").expect_err("refused");
assert!(why.contains("not resolved"), "{why}");
assert!(prepare_rename(&files, &path("m.sv"), at(text, "o = ", "genblk1")).is_err());
}
const PROCEDURAL: &str = "module p (input logic clk, output logic o);
always_ff @(posedge clk) begin : blk
logic t;
t = ~o;
if (t) disable blk;
o <= t;
end : blk
task automatic poke();
fork : fk
begin end
join : fk
disable fk;
endtask
initial lbl: begin
disable lbl;
end : lbl
endmodule
";
#[test]
fn a_named_procedural_block_its_closing_label_and_disable_are_one_reference_set() {
let (texts, _) =
renamed(&[("p.sv", PROCEDURAL)], "p.sv", "disable ", "blk", "b2").expect("renames");
assert_eq!(texts[0], PROCEDURAL.replace("blk", "b2"));
let (texts, _) = renamed(&[("p.sv", PROCEDURAL)], "p.sv", "join : ", "fk", "f2").expect("fk");
assert_eq!(texts[0], PROCEDURAL.replace("fk", "f2"));
let (texts, _) = renamed(&[("p.sv", PROCEDURAL)], "p.sv", "end : ", "lbl", "l2").expect("l");
assert_eq!(texts[0], PROCEDURAL.replace("lbl", "l2"));
}
#[test]
fn a_net_and_a_block_of_the_same_name_in_different_scopes_are_two_declarations() {
let text = "module s (output logic o);
if (1) begin : g
logic x;
end
if (1) begin : h
logic g;
assign g = 1'b1;
end
assign o = g.x | h.g;
endmodule
";
let (texts, _) = renamed(&[("s.sv", text)], "s.sv", "begin : ", "g", "gg").expect("block");
assert_eq!(
texts[0],
text.replace("begin : g\n", "begin : gg\n").replace("o = g.x", "o = gg.x")
);
let (texts, _) =
renamed(&[("s.sv", text)], "s.sv", "begin : h\n logic ", "g", "n").expect("net");
assert_eq!(
texts[0],
text.replace("logic g;", "logic n;")
.replace("assign g =", "assign n =")
.replace("h.g;", "h.n;")
);
}
#[test]
fn a_new_name_that_a_path_would_then_capture_is_refused() {
// `g_ln` already names a net beside the loop: the path's head would
// rebind to it, so the whole rename is refused.
let text = "module c (output logic o);
logic g_ln;
for (genvar i = 0; i < 2; i++) begin : g_lane
logic q;
end
assign o = g_lane[0].q;
endmodule
";
let why =
renamed(&[("c.sv", text)], "c.sv", "begin : ", "g_lane", "g_ln").expect_err("refused");
assert!(why.contains("g_ln") || why.contains("abandoned"), "{why}");
}
/// QA F1, the lead's rule: a path segment spelling the old name that resolved
/// to *no* declaration, in any file of the set, is a warning with its lines;
/// one that resolved to a *different* declaration is not news.
#[test]
fn an_unresolved_path_through_the_name_warns_and_a_path_to_another_declaration_does_not() {
let sub = "module sub;\n logic state_q;\nendmodule\n";
let other = "module other;\n logic state_q;\nendmodule\n";
let top = "module top (output logic o, output logic p);\n sub u_x ();\n other u_y ();\n assign o = u_x.state_q;\n assign p = u_y.state_q;\nendmodule\n";
let probe = "module probe (output logic o);\n assign o = tb.u_x.state_q;\n assign o = tb.u_x.state_q\n | tb.u_x.state_q;\nendmodule\n";
let files = [("sub.sv", sub), ("other.sv", other), ("top.sv", top), ("probe.sv", probe)];
let (texts, warnings) =
renamed(&files, "sub.sv", "logic ", "state_q", "state_r").expect("renames");
assert_eq!(texts[2], top.replace("u_x.state_q", "u_x.state_r"));
assert_eq!((texts[1].as_str(), texts[3].as_str()), (other, probe));
assert_eq!(warnings.len(), 1, "{warnings:?}");
assert!(warnings[0].starts_with("probe.sv:2,3,4: "), "{warnings:?}");
}
/// Re-check R1: two files of one base name in the set are named by the path
/// the caller gave, so each warning names a findable file; a unique base
/// name stays bare.
#[test]
fn warnings_name_a_shared_base_name_by_its_path_and_a_unique_one_bare() {
let dut = "module dut_x;\n if (1) begin : g_sw\n logic q;\n end\nendmodule\n";
let probe = "module probe_IDX (output logic o);\n assign o = tb.dut.g_sw.q;\nendmodule\n";
let (a, b) = (probe.replace("IDX", "a"), probe.replace("IDX", "b"));
let files = [("dut_x.sv", dut), ("a/x_if.sv", a.as_str()), ("b/x_if.sv", b.as_str())];
let (_, warnings) = renamed(&files, "dut_x.sv", "begin : ", "g_sw", "g_hw").expect("renames");
let lines: Vec<&str> = warnings
.iter()
.filter_map(|w| w.split_once(": a hierarchical path"))
.map(|(h, _)| h)
.collect();
assert_eq!(lines, vec!["/rtl/a/x_if.sv:2", "/rtl/b/x_if.sv:2"], "{warnings:?}");
let unique = [("dut_x.sv", dut), ("a/x_if.sv", a.as_str())];
let (_, warnings) = renamed(&unique, "dut_x.sv", "begin : ", "g_sw", "g_hw").expect("renames");
assert!(warnings.iter().any(|w| w.starts_with("x_if.sv:2: ")), "{warnings:?}");
}
@@ -0,0 +1,138 @@
//! A bare macro argument in another module is that module's own name —
//! unless the macro carries it to the renamed declaration: after a `.`
//! (`force u_m.sig`, a named connection `.x(x)`), through a pasted path
//! (`` u_m.``sig ``), into a `bind` into the declaring module, or into a
//! macro the set does not define (TODO §65.1, independent review H-1/H-2,
//! 2026-10-06). Each of these was warned about in 0.59.0, silent after the
//! scoping rework, and is warned about again.
use std::path::PathBuf;
use vlog_refactor::rename;
/// `m`'s `state_q` is an input port; every test renames it.
const M: &str = "module m (input logic clk, input logic state_q);
logic r;
always_ff @(posedge clk) r <= state_q;
endmodule
";
/// The warnings of renaming `m.state_q` to `state_r` among `files` (plus
/// `m.sv`).
fn warnings_of(files: &[(&str, &str)]) -> Vec<String> {
let mut sources = vec![(PathBuf::from("/rtl/m.sv"), M.to_string())];
sources.extend(files.iter().map(|(n, t)| (PathBuf::from("/rtl").join(n), t.to_string())));
let at = M.find("logic state_q").expect("declaration") as u32 + 6;
rename(&sources, &PathBuf::from("/rtl/m.sv"), at, "state_r").expect("renames").warnings
}
/// Whether some warning names `file:line`.
fn said(warnings: &[String], file: &str, line: u32) -> bool {
warnings.iter().any(|w| w.contains(&format!("{file}:{line}")))
}
/// PC: the instantiation is broken by the rename and must not be silent.
#[test]
fn a_named_connection_a_macro_builds_from_a_bare_argument_is_said() {
let top = "module top (input logic clk, input logic state_q);
m u_m (.clk(clk), `CONN(state_q));
endmodule
";
let warnings = warnings_of(&[("defs.svh", "`define CONN(x) .x(x)\n"), ("top.sv", top)]);
assert!(said(&warnings, "top.sv", 2), "{warnings:#?}");
}
/// PA: a testbench forcing a path the macro builds from its argument.
#[test]
fn a_bare_argument_the_macro_puts_after_a_dot_is_said() {
let tb = "module tb;
logic clk;
m u_m (.clk(clk), .state_q(1'b0));
initial begin
`FORCE(state_q)
end
endmodule
";
let defs = "`define FORCE(sig) force u_m.sig = 1'b0;\n";
let warnings = warnings_of(&[("defs.svh", defs), ("tb.sv", tb)]);
assert!(said(&warnings, "tb.sv", 5), "{warnings:#?}");
}
/// PA2: the same path through a `` `` `` paste.
#[test]
fn a_bare_argument_pasted_after_a_dot_is_said() {
let tb = "module tb;
logic clk, o;
m u_m (.clk(clk), .state_q(1'b0));
assign o = `PEEK(state_q);
endmodule
";
let warnings = warnings_of(&[("defs.svh", "`define PEEK(sig) u_m.``sig\n"), ("tb.sv", tb)]);
assert!(said(&warnings, "tb.sv", 4), "{warnings:#?}");
}
/// A macro passing its argument on to one that carries it carries it too;
/// the position it passes on is the one that counts.
#[test]
fn an_argument_passed_on_to_a_carrying_macro_is_said_and_another_is_not() {
let defs =
"`define FORCE(sig) force u_m.sig = 1'b0;\n`define BOTH(v, sig) v = 1'b1; `FORCE(sig)\n";
let tb = "module tb;
logic clk, state_q;
m u_m (.clk(clk), .state_q(1'b0));
initial `BOTH(state_q, r);
initial `BOTH(x, state_q);
endmodule
";
let warnings = warnings_of(&[("defs.svh", defs), ("tb.sv", tb)]);
assert!(!said(&warnings, "tb.sv", 4), "tb's own state_q: {warnings:#?}");
assert!(said(&warnings, "tb.sv", 5), "{warnings:#?}");
}
/// PD: a macro whose body is a `bind` into `m`, invoked from a file that is
/// not home — the body's `state_q` is evaluated in `m`.
#[test]
fn a_define_body_that_binds_into_the_module_is_said_wherever_it_is_invoked() {
let defs = "`define BIND_CHK bind m chk u_chk (.s(state_q));\n";
let chk = "module chk (input logic s);\nendmodule\n";
let binds = "module binds;\n `BIND_CHK\nendmodule\n";
let warnings = warnings_of(&[("defs.svh", defs), ("chk.sv", chk), ("binds.sv", binds)]);
assert!(said(&warnings, "defs.svh", 1), "{warnings:#?}");
}
/// PD with the name passed in: every argument of a binder is carried.
#[test]
fn a_bare_argument_of_a_macro_that_binds_into_the_module_is_said() {
let defs = "`define BIND_S(sig) bind m chk u_chk (.s(sig));\n";
let chk = "module chk (input logic s);\nendmodule\n";
let binds = "module binds;\n `BIND_S(state_q)\nendmodule\n";
let warnings = warnings_of(&[("defs.svh", defs), ("chk.sv", chk), ("binds.sv", binds)]);
assert!(said(&warnings, "binds.sv", 2), "{warnings:#?}");
}
/// Nothing shows what an undefined macro does with its argument.
#[test]
fn a_bare_argument_of_a_macro_the_set_does_not_define_is_said() {
let tb = "module tb;
logic state_q;
initial `NOWHERE(state_q)
endmodule
";
let warnings = warnings_of(&[("tb.sv", tb)]);
assert!(said(&warnings, "tb.sv", 3), "{warnings:#?}");
}
/// The scoping is kept where it is provable: a macro that uses its argument
/// as a plain expression, in a module with its own `state_q`, is silent.
#[test]
fn a_plain_expression_macro_in_another_module_stays_silent() {
let defs =
"`define ASSERT(n, e) n: assert property (@(posedge clk) e);\n`define CONN(x) .x(x)\n";
let other = "module other (input logic clk);
logic state_q;
`ASSERT(Own, state_q)
endmodule
";
let warnings = warnings_of(&[("defs.svh", defs), ("other.sv", other)]);
assert!(!said(&warnings, "other.sv", 3), "{warnings:#?}");
}
@@ -0,0 +1,173 @@
//! A rename's text warnings are about the renamed declaration (TODO §65.1,
//! lead's inspection 2026-09-30): a module member's bare spelling in another
//! module's macro argument, `` `define`` body or unstructured assertion is
//! that module's own signal, not news; a dotted spelling may be a path to it
//! and is still said; a package-level name is still warned about everywhere.
use std::path::PathBuf;
use vlog_refactor::rename;
fn workspace(files: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
files.iter().map(|(name, text)| (PathBuf::from("/rtl").join(name), text.to_string())).collect()
}
const DEFS: &str = "`define ASSERT(n, e) n: assert property (e);\n`define PEEK_A tb.u_a.state_q\n`define LOCAL_B state_q\n";
const A: &str = "module a (input logic clk);
logic state_q;
always_ff @(posedge clk) state_q <= ~state_q;
`ASSERT(A_Toggles, state_q)
// state_q is a's register
initial $display(\"state_q\");
endmodule
";
const B: &str = "module b (input logic clk);
logic state_q;
a u_a (.clk);
always_ff @(posedge clk) state_q <= ~state_q;
`ASSERT(B_Own, state_q)
`ASSERT(B_Peek, u_a.state_q)
// state_q is b's register
initial $display(\"state_q\");
endmodule
";
/// The warnings of renaming `a`'s `state_q`.
fn warnings_of_renaming_a() -> Vec<String> {
let files = workspace(&[("defs.svh", DEFS), ("a.sv", A), ("b.sv", B)]);
let at = A.find("logic state_q").expect("decl") as u32 + 6;
rename(&files, &PathBuf::from("/rtl/a.sv"), at, "state_r").expect("renames").warnings
}
#[test]
fn only_the_renamed_modules_bare_macro_argument_is_warned_about() {
let warnings = warnings_of_renaming_a();
let macro_args: Vec<&String> =
warnings.iter().filter(|w| w.contains("arguments of the macro invocation")).collect();
assert_eq!(macro_args.len(), 2, "{warnings:#?}");
assert!(macro_args[0].contains("a.sv:4"), "a's own `ASSERT: {warnings:#?}");
assert!(macro_args[1].contains("b.sv:6"), "b's dotted `u_a.state_q`: {warnings:#?}");
}
#[test]
fn a_foreign_define_body_is_said_only_when_it_spells_the_name_dotted() {
let warnings = warnings_of_renaming_a();
let bodies: Vec<&String> = warnings.iter().filter(|w| w.contains("body of macro")).collect();
assert_eq!(bodies.len(), 1, "{warnings:#?}");
assert!(bodies[0].contains("`PEEK_A`"), "{warnings:#?}");
}
#[test]
fn a_package_level_name_is_still_warned_about_in_every_module() {
let pkg = "package p;\n localparam int W = 1;\nendpackage\n";
let user = "module u import p::*; (input logic clk);\n `ASSERT(U_W, W > 0)\nendmodule\n";
let other =
"module v (input logic clk);\n localparam int W = 2;\n `ASSERT(V_W, W > 0)\nendmodule\n";
let files = workspace(&[("defs.svh", DEFS), ("p.sv", pkg), ("u.sv", user), ("v.sv", other)]);
let at = pkg.find("W =").expect("decl") as u32;
let edit = rename(&files, &PathBuf::from("/rtl/p.sv"), at, "WIDTH").expect("renames");
let macro_args: Vec<&String> =
edit.warnings.iter().filter(|w| w.contains("arguments of the macro invocation")).collect();
assert_eq!(macro_args.len(), 2, "both, as before: {:#?}", edit.warnings);
}
/// Rework 5, N1: a port rename edits every instantiating file, and each of
/// those asserts on its *own* `clk_i` — the scope lookup in an edited file
/// says those are not the renamed port. The declaring module's own
/// assertion still warns.
#[test]
fn an_instantiating_modules_own_bare_spelling_is_not_news() {
let flop = "module flop (input logic clk_i, input logic d, output logic q);
always_ff @(posedge clk_i) q <= d;
`ASSERT(FlopKnown_A, !$isunknown(clk_i))
endmodule
";
let user = |n: u32| {
format!(
"module user{n} (input logic clk_i, input logic d, output logic q);
flop u_flop (.clk_i(clk_i), .d, .q);
`ASSERT(User{n}Clk_A, clk_i)
endmodule
"
)
};
let (u1, u2, u3) = (user(1), user(2), user(3));
let files = workspace(&[
("defs.svh", DEFS),
("flop.sv", flop),
("user1.sv", &u1),
("user2.sv", &u2),
("user3.sv", &u3),
]);
let at = flop.find("clk_i").expect("port") as u32;
let edit = rename(&files, &PathBuf::from("/rtl/flop.sv"), at, "clk_x").expect("renames");
assert_eq!(edit.edits.len(), 4, "the port and the three connections");
let macro_args: Vec<&String> =
edit.warnings.iter().filter(|w| w.contains("arguments of the macro invocation")).collect();
assert_eq!(macro_args.len(), 1, "{:#?}", edit.warnings);
assert!(macro_args[0].contains("flop.sv:3"), "{:#?}", edit.warnings);
}
/// Review M-1: a use in an include-related file that the rename *did* edit
/// is not reported as "left unchanged". `all.sv` includes `m.sv` and `n.sv`,
/// so `n.sv` is pasted around `m.sv`; its instantiation of `m` is a
/// cross-file reference the rename rewrites.
#[test]
fn an_edited_use_in_an_include_related_file_is_not_said_to_be_left_unchanged() {
let m = "module m (input logic clk);\nendmodule\n";
let n = "module n (input logic clk);\n m u_m (.clk(clk));\nendmodule\n";
let all = "`include \"m.sv\"\n`include \"n.sv\"\n";
let files = workspace(&[("m.sv", m), ("n.sv", n), ("all.sv", all)]);
let at = m.find("module m").expect("decl") as u32 + 7;
let edit = rename(&files, &PathBuf::from("/rtl/m.sv"), at, "m2").expect("renames");
assert_eq!(edit.edits_for(&PathBuf::from("/rtl/n.sv")).len(), 1, "the instantiation moves");
let left = edit.warnings.iter().any(|w| w.contains("n.sv:2") && w.contains("left unchanged"));
assert!(!left, "{:#?}", edit.warnings);
}
/// The warnings of renaming the first `logic state_q` in `m.sv` among `files`.
fn warnings_renaming_m_state_q(files: &[(&str, &str)]) -> Vec<String> {
let text = files.iter().find(|(n, _)| *n == "m.sv").map(|(_, t)| *t).expect("m.sv");
let at = text.find("logic state_q").expect("decl") as u32 + 6;
let set = workspace(files);
rename(&set, &PathBuf::from("/rtl/m.sv"), at, "state_r").expect("renames").warnings
}
/// Review L-3: a comment between the `.` and the name is still a path.
#[test]
fn a_path_with_a_comment_after_its_dot_is_said() {
let m = "module m (input logic clk);\n logic state_q;\nendmodule\n";
let tb = "module tb;\n m u_m (.clk(1'b0));\n initial $display(\"%b\", `Q(u_m. /* c */ state_q));\nendmodule\n";
let warnings = warnings_renaming_m_state_q(&[
("defs.svh", "`define Q(x) x\n"),
("m.sv", m),
("tb.sv", tb),
]);
assert!(warnings.iter().any(|w| w.contains("tb.sv:3")), "{warnings:#?}");
}
/// Review L-4: a file that spells `bind` but does not lex is counted as
/// binding into the module, so the macros it invokes are followed.
#[test]
fn a_bind_file_that_does_not_lex_still_makes_its_macros_home() {
let m = "module m (input logic clk);\n logic state_q;\nendmodule\n";
let binds = "module binds;\n bind m chk u_chk (.s(`SIG));\n initial $display(\"unterminated);\nendmodule\n";
let warnings = warnings_renaming_m_state_q(&[
("defs.svh", "`define SIG state_q\n"),
("m.sv", m),
("binds.sv", binds),
]);
assert!(warnings.iter().any(|w| w.contains("defs.svh:1")), "{warnings:#?}");
}
/// Review L-4: an included fragment that does not lex is said, not skipped.
#[test]
fn an_included_fragment_that_does_not_lex_is_said() {
let m = "module m (output logic o);\n logic state_q;\n`include \"frag.svh\"\nendmodule\n";
let frag = " assign o = state_q;\n initial $display(\"unterminated);\n";
let warnings = warnings_renaming_m_state_q(&[("m.sv", m), ("frag.svh", frag)]);
assert!(
warnings.iter().any(|w| w.contains("frag.svh") && w.contains("could not read")),
"{warnings:#?}"
);
}
+16 -6
View File
@@ -80,10 +80,10 @@ impl<'a> Binder<'a> {
// `super.b` go to the enclosing class instead, and a spine that
// starts at one of them stops there: `this.a.b` records `a` and
// nothing more (`this` is not a name this crate binds, so there
// is no head to walk from). An indexed or called head
// (`a[i].b`, `f().b`) still resolves its own head and stops:
// chasing those needs the element type of a container, which
// this crate does not model (TODO.md §15).
// is no head to walk from). A called head (`f().b`) still
// resolves its own head and stops. An **indexed** link
// (`g_lane[0].lane_q`, `u_x.g[1].sig`) is walked as the name it
// indexes — see [`spine`] for why that is never a wrong answer.
ExprKind::Member { base, name, .. } => match &base.kind {
ExprKind::Ident(head) if head == "this" => {
self.use_member(scope, name, member_tail(e.span, name), Target::ThisMember)
@@ -240,8 +240,17 @@ impl<'a> Binder<'a> {
/// identifier it starts at, and the members already selected from it, in the
/// order they are written (`a.b.c`'s tail `c` gives `("a", ["b"])`).
///
/// `None` for a spine this crate cannot start walking — an index, a call, a
/// cast, or `this`/`super`, which name no declaration to take a type from.
/// An element select is transparent: `g[0].x` walks as `g.x`. Every link the
/// walk can continue from is one an index selects *another of the same* from
/// — a generate block (an element of a `for` generate is an instance of the
/// same block, IEEE 1800 §27.4), or a declaration whose recorded type is the
/// element's (a packed array of a struct). An unpacked declarator records no
/// type at all (`declare_typed`), and an instance array none either, so
/// `q[i].m` and `u[0].sig` still stop at their head exactly as before.
///
/// `None` for a spine this crate cannot start walking — a call, a cast, a
/// part select, or `this`/`super`, which name no declaration to take a type
/// from.
fn spine(base: &Expr) -> Option<(String, Vec<String>)> {
let mut mids = Vec::new();
let mut current = base;
@@ -256,6 +265,7 @@ fn spine(base: &Expr) -> Option<(String, Vec<String>)> {
mids.push(name.clone());
current = base;
}
ExprKind::Index { base, .. } => current = base,
_ => return None,
}
}
+85
View File
@@ -0,0 +1,85 @@
//! Generate constructs: `if`/`case`/`for` generate and the blocks they own.
//!
//! A generate block's **label is declared in the scope the construct is
//! written in** (IEEE 1800 §27.3–27.5): `g_lane` of `for (…) begin : g_lane`
//! is a name of the enclosing module, which is what lets `g_lane[0].lane_q`
//! written beside the loop resolve its head at all. The loop's genvar is
//! not — it lives in a header scope of its own, and the block's body sees it
//! because the body's scope is opened *inside* that header. So a labelled
//! `for` block is the one declaration whose name and whose body sit in two
//! different scopes (`docs/features/generate-label-rename/README.md`).
use vlog_parser::ast::*;
use vlog_parser::span::TextRange;
use crate::model::{ScopeId, ScopeKind, SymbolKind};
use super::Binder;
impl<'a> Binder<'a> {
pub(super) fn bind_gen_if(&mut self, g: &'a GenIf, scope: ScopeId) {
self.bind_expr(&g.cond, scope);
self.bind_gen_block(&g.then, scope);
match g.els.as_deref() {
Some(GenElse::If(_, inner)) => self.bind_gen_if(inner, scope),
Some(GenElse::Block(b)) => self.bind_gen_block(b, scope),
None => {}
}
}
pub(super) fn bind_gen_for(&mut self, g: &'a GenFor, span: TextRange, scope: ScopeId) {
// The loop header opens a scope of its own so that `for (genvar i...)`
// does not leak `i` into the enclosing module.
let header = self.new_scope(ScopeKind::Generate, scope, span);
match (g.init_genvar, &g.init.lhs.kind) {
// `for (genvar i = 0; ...)` declares; `for (i = 0; ...)` uses a
// `genvar i;` written outside the loop.
(true, ExprKind::Ident(name)) => {
self.declare(header, name, SymbolKind::Genvar, g.init.lhs.span, g.init.lhs.span);
}
_ => self.bind_expr(&g.init.lhs, header),
}
self.bind_expr(&g.init.rhs, header);
self.bind_expr(&g.cond, header);
match &g.step {
ForStep::Assign(a) => {
self.bind_expr(&a.lhs, header);
self.bind_expr(&a.rhs, header);
}
ForStep::Expr(e) => self.bind_expr(e, header),
}
self.bind_gen_body(&g.body, scope, header);
}
/// A generate block whose label, if any, is declared in `scope` and whose
/// body is opened there too — every generate block but a `for` loop's.
pub(super) fn bind_gen_block(&mut self, b: &'a GenBlock, scope: ScopeId) {
self.bind_gen_body(b, scope, scope);
}
/// One generate block: the label declared in `declared_in`, the body's
/// scope opened inside `parent`. The two differ only for a `for` loop,
/// whose body must see the header's genvar.
fn bind_gen_body(&mut self, b: &'a GenBlock, declared_in: ScopeId, parent: ScopeId) {
let label = match (&b.label, b.label_span) {
(Some(label), Some(ls)) => {
self.declare(declared_in, label, SymbolKind::Block, ls, b.span)
}
_ => None,
};
let inner = self.new_scope(ScopeKind::Generate, parent, b.span);
if let Some(sym) = label {
self.symbols[sym.0 as usize].child_scope = Some(inner);
self.scopes[inner.0 as usize].owner = Some(sym);
}
self.bind_items(&b.items, inner);
let opening = b.label.as_deref();
self.use_block_end_label(
declared_in,
inner,
opening,
b.end_label.as_ref(),
b.end_label_span,
);
}
}
+9 -59
View File
@@ -1,7 +1,7 @@
//! The item-level walk: a file or fragment, the `ItemKind` dispatch, modules
//! and interfaces (header, ports, modports, clocking blocks), packages and
//! imports, instantiations and `bind`, generate constructs, functions and
//! tasks. Every item that declares a typed name hands the name to `decl` and
//! imports, instantiations and `bind`, functions and tasks (generate
//! constructs are `generate`'s). Every item that declares a typed name hands the name to `decl` and
//! every body to `stmt`; what stays here is the shape of the item and the
//! scope it opens.
@@ -124,10 +124,10 @@ impl<'a> Binder<'a> {
self.declare(scope, &name.text, SymbolKind::Genvar, name.span, item.span);
}
}
ItemKind::GenerateRegion { items, .. } => {
let inner = self.new_scope(ScopeKind::Generate, scope, item.span);
self.bind_items(items, inner);
}
// `generate … endgenerate` is not a scope (IEEE 1800 §27.3): what
// it holds is declared in the enclosing module, which is where a
// block label written inside it must be found from.
ItemKind::GenerateRegion { items, .. } => self.bind_items(items, scope),
// A bare `begin … end` where an item belongs: bound as the
// unnamed generate scope an unlabeled `if` arm's block gets.
ItemKind::GenBlock(b) => self.bind_gen_block(b, scope),
@@ -396,56 +396,6 @@ impl<'a> Binder<'a> {
self.bind_opt_expr(c.expr.as_ref(), scope);
}
fn bind_gen_if(&mut self, g: &'a GenIf, scope: ScopeId) {
self.bind_expr(&g.cond, scope);
self.bind_gen_block(&g.then, scope);
match g.els.as_deref() {
Some(GenElse::If(_, inner)) => self.bind_gen_if(inner, scope),
Some(GenElse::Block(b)) => self.bind_gen_block(b, scope),
None => {}
}
}
fn bind_gen_for(&mut self, g: &'a GenFor, span: TextRange, scope: ScopeId) {
// The loop header opens a scope of its own so that `for (genvar i...)`
// does not leak `i` into the enclosing module.
let header = self.new_scope(ScopeKind::Generate, scope, span);
match (g.init_genvar, &g.init.lhs.kind) {
// `for (genvar i = 0; ...)` declares; `for (i = 0; ...)` uses a
// `genvar i;` written outside the loop.
(true, ExprKind::Ident(name)) => {
self.declare(header, name, SymbolKind::Genvar, g.init.lhs.span, g.init.lhs.span);
}
_ => self.bind_expr(&g.init.lhs, header),
}
self.bind_expr(&g.init.rhs, header);
self.bind_expr(&g.cond, header);
match &g.step {
ForStep::Assign(a) => {
self.bind_expr(&a.lhs, header);
self.bind_expr(&a.rhs, header);
}
ForStep::Expr(e) => self.bind_expr(e, header),
}
self.bind_gen_block(&g.body, header);
}
fn bind_gen_block(&mut self, b: &'a GenBlock, scope: ScopeId) {
let inner = match (&b.label, b.label_span) {
(Some(label), Some(ls)) => self.declare_with_scope(
scope,
label,
SymbolKind::Block,
ls,
b.span,
ScopeKind::Generate,
),
_ => self.new_scope(ScopeKind::Generate, scope, b.span),
};
self.bind_items(&b.items, inner);
self.use_end_label(scope, inner, b.end_label.as_ref(), b.end_label_span);
}
fn bind_function(&mut self, f: &'a FunctionDecl, span: TextRange, scope: ScopeId) {
if !f.scope.is_empty() {
// An out-of-body definition binds into its class's scope, which
@@ -605,9 +555,9 @@ impl<'a> Binder<'a> {
/// connection in the scope the directive is written in, which is not the
/// scope it elaborates in.
///
/// An indexed segment (`gen[0]`) keeps only its name: the index has no record
/// of a generate block, so such a path answers nothing either way, and a
/// spelling the user can recognize is what the warning needs.
/// An indexed segment (`gen[0]`) keeps only its name: a generate block is on
/// its module's hierarchical surface, and an index into a generate array
/// selects an instance of the same block, so the name is the whole hop.
fn bind_target_path(b: &BindDirective) -> Option<String> {
let mut out = String::new();
for seg in &b.target {
+54 -9
View File
@@ -7,14 +7,16 @@
//! plumbing — opening a scope, declaring a name, recording a use, an end
//! label, a derived span checked against the source. The walk itself is one
//! sibling per grammar domain, each an `impl Binder` block: `item` (the
//! item-level walk), `decl` (declared names and their types), `class`
//! (classes, constraints, out-of-body definitions), `cover` (covergroups),
//! `stmt`, `sva` (assertions) and `expr`.
//! item-level walk), `generate` (generate constructs and their blocks),
//! `decl` (declared names and their types), `class` (classes, constraints,
//! out-of-body definitions), `cover` (covergroups), `stmt`, `sva`
//! (assertions) and `expr`.
mod class;
mod cover;
mod decl;
mod expr;
mod generate;
mod item;
mod stmt;
mod sva;
@@ -222,7 +224,15 @@ impl<'a> Binder<'a> {
first,
scope,
});
self.use_name(scope, name, name_span, Target::Lexical);
// A redeclaration names the first declaration — unless exactly one
// of the two is a block label. Two arms of one generate `if`
// carrying one label are one label; a label spelled like a net of
// the same scope is a collision (`duplicate-declaration`), and
// counting it as a *use* of the net would call the net read.
let first_is_block = self.symbols[first.0 as usize].kind == SymbolKind::Block;
if first_is_block == (kind == SymbolKind::Block) {
self.use_name(scope, name, name_span, Target::Lexical);
}
return None;
}
let id = SymbolId(self.symbols.len() as u32);
@@ -343,12 +353,47 @@ impl<'a> Binder<'a> {
label: Option<&String>,
span: Option<TextRange>,
) {
let (Some(label), Some(span)) = (label, span) else {
return;
};
// `None` when the declaration was a redeclaration and bound no symbol
// of its own; the label is then left unrecorded, as it was before.
let Some(sym) = self.scopes[body.0 as usize].owner else {
// of its own; the label is then left unrecorded.
let owner = self.scopes[body.0 as usize].owner;
self.record_end_label(scope, owner, label, span);
}
/// [`Self::use_end_label`] for a block (`begin`/`fork`, a generate
/// block), whose own opening label is `opening` — the `begin : lbl` name
/// or the `lbl:` prefix. An unowned block may still close with its opening
/// label: the second arm of a generate `if`/`case` carrying the first's
/// label (IEEE 1800 §27.5), whose opening label is already a use of the
/// first declaration, and the prefix form, which declares a label but no
/// owned scope. That closing label is a use of the first same-scope
/// **block** of the name, or a rename rewrites one of the pair and leaves
/// `end : old` closing `begin : new`. A closing label that does not spell
/// the opening one records nothing (review L-1).
pub(super) fn use_block_end_label(
&mut self,
scope: ScopeId,
body: ScopeId,
opening: Option<&str>,
label: Option<&String>,
span: Option<TextRange>,
) {
let owner = self.scopes[body.0 as usize].owner.or_else(|| {
let label = label.filter(|l| opening == Some(l.as_str()))?;
let first = *self.scopes[scope.0 as usize].names.get(label)?;
(self.symbols[first.0 as usize].kind == SymbolKind::Block).then_some(first)
});
self.record_end_label(scope, owner, label, span);
}
/// Records an end label as a use of `owner` when it spells its name.
fn record_end_label(
&mut self,
scope: ScopeId,
owner: Option<SymbolId>,
label: Option<&String>,
span: Option<TextRange>,
) {
let (Some(label), Some(span), Some(sym)) = (label, span, owner) else {
return;
};
if self.symbols[sym.0 as usize].name != *label {
+33 -17
View File
@@ -81,24 +81,35 @@ impl<'a> Binder<'a> {
}
}
/// A `begin`/`fork` block: its own label (if any) declared in `scope`
/// with the block's scope, its statements, and its closing label, which
/// may also close a `prefix:` statement label.
fn bind_block(&mut self, stmt: &'a Stmt, scope: ScopeId, prefix: Option<&str>) {
let (StmtKind::Block { label, label_span, stmts, end_label, end_label_span, .. }
| StmtKind::ForkJoin { label, label_span, stmts, end_label, end_label_span, .. }) =
&stmt.kind
else {
return;
};
let inner = match (label, *label_span) {
(Some(label), Some(ls)) => self.declare_with_scope(
scope,
label,
SymbolKind::Block,
ls,
stmt.span,
ScopeKind::Block,
),
_ => self.new_scope(ScopeKind::Block, scope, stmt.span),
};
self.bind_stmts(stmts, inner);
let opening = label.as_deref().or(prefix);
self.use_block_end_label(scope, inner, opening, end_label.as_ref(), *end_label_span);
}
pub(super) fn bind_stmt(&mut self, stmt: &'a Stmt, scope: ScopeId) {
match &stmt.kind {
StmtKind::Block { label, label_span, stmts, end_label, end_label_span, .. }
| StmtKind::ForkJoin { label, label_span, stmts, end_label, end_label_span, .. } => {
let inner = match (label, *label_span) {
(Some(label), Some(ls)) => self.declare_with_scope(
scope,
label,
SymbolKind::Block,
ls,
stmt.span,
ScopeKind::Block,
),
_ => self.new_scope(ScopeKind::Block, scope, stmt.span),
};
self.bind_stmts(stmts, inner);
self.use_end_label(scope, inner, end_label.as_ref(), *end_label_span);
}
StmtKind::Block { .. } | StmtKind::ForkJoin { .. } => self.bind_block(stmt, scope, None),
StmtKind::If { cond, then, els, .. } => {
self.bind_expr(cond, scope);
self.bind_stmt(then, scope);
@@ -115,7 +126,12 @@ impl<'a> Binder<'a> {
// names its block (IEEE 1800 §9.3.5).
StmtKind::Labeled { name, name_span, stmt: inner } => {
self.declare(scope, name, SymbolKind::Block, *name_span, stmt.span);
self.bind_stmt(inner, scope);
match &inner.kind {
StmtKind::Block { .. } | StmtKind::ForkJoin { .. } => {
self.bind_block(inner, scope, Some(name))
}
_ => self.bind_stmt(inner, scope),
}
}
StmtKind::Import(paths) => {
for path in paths {
+9 -1
View File
@@ -156,7 +156,15 @@ use crate::workspace::{
/// though the `bind` file did not mention it — for exactly the files it had
/// cached, which is the half-right answer every one of these bumps exists to
/// prevent. See `docs/features/rename-bind-occurrences/README.md`.
pub const FACTS_FORMAT: u32 = 20;
/// 20 → 21 (2026-09-30, generate-label-rename): no new field, but new records
/// and different answers in the old fields — a named block is a member on its
/// module's hierarchical surface, its own members are recorded under the
/// synthesized `module.label` key, and a path through a block
/// (`u_x.g_lane[0].lane_q`) is an external reference where it recorded
/// nothing. A 0.59.0 store would answer find-references and the rename of a
/// block label as though no other file named it. See
/// `docs/features/generate-label-rename/README.md`.
pub const FACTS_FORMAT: u32 = 21;
impl FileFacts {
/// These facts as one line's worth of fields, tab-separated.
+34
View File
@@ -282,6 +282,40 @@ impl Semantics {
out
}
/// The key the workspace index files the members of `scope` under: the
/// name of the declaration that owns it, or — for a named block — the key
/// of the scope the block is declared in and the label, joined by a `.`
/// (`sub.g_lane`, `sub.g_a.g_b`).
///
/// How a caller holding one file's analysis asks the index about one of
/// its members: `member_in(key, name, …)`. `None` for a scope nobody owns
/// (an unnamed `begin`), whose members the index does not hold.
///
/// A block inside a function or task is on no cross-file surface — the
/// index never files it — and its key is qualified by the enclosing unit
/// and marked as the subroutine's (`m.ff().fb`), so it can never be the
/// key a module `ff`'s block `fb` is filed under (QA F4).
pub fn member_key(&self, scope: ScopeId) -> Option<String> {
let owner = self.scope(scope)?.owner.and_then(|id| self.symbol(id))?;
if owner.kind != SymbolKind::Block {
return Some(owner.name.clone());
}
Some(format!("{}.{}", self.block_parent_key(owner.scope)?, owner.name))
}
/// The key part a block declared in `scope` hangs off: the enclosing
/// block's or unit's key, or — inside a function or task — the unit's key
/// and the subroutine's name with `()`, which no index key spells.
fn block_parent_key(&self, scope: ScopeId) -> Option<String> {
let owner = self.scope(scope)?.owner.and_then(|id| self.symbol(id))?;
match owner.kind {
SymbolKind::Function | SymbolKind::Task => {
Some(format!("{}.{}()", self.member_key(owner.scope)?, owner.name))
}
_ => self.member_key(scope),
}
}
/// How many uses resolved to a declaration in this file, out of how many
/// were recorded. The corpus test reports the ratio as an honest baseline.
pub fn resolution_counts(&self) -> (usize, usize) {
+9 -5
View File
@@ -199,7 +199,7 @@ fn type_member(
/// `None` — no reference recorded at all — whenever this crate has nothing to
/// say, which is the shape every pre-2026-09-01 hierarchical name had: a head
/// nothing in this file declares, a head that is neither typed nor a unit a
/// hierarchical name may start at (a `logic [3:0]`, a block label, a
/// hierarchical name may start at (a `logic [3:0]`, a genvar, a
/// built-in), a type **this file declares** as something with no members to
/// search (a struct or enum typedef — see [`TypeHere::NotAUnit`]), or a
/// member genuinely absent from a class this file declares whole. Recording a
@@ -428,8 +428,9 @@ fn unit_scope(scopes: &[Scope], symbols: &[Symbol], from: ScopeId, unit: &str) -
/// which is how `tb.dut.u_core.sig` reaches into `tb` (IEEE 1800 §23.6: a
/// top-level module name is the root of a hierarchical path), or a class,
/// where the answer can only ever be that very class's own member. Everything
/// else — a `logic` net, a genvar, a block label, a package — answers `None`,
/// which stops the chain.
/// else — a `logic` net, a genvar, a package — answers `None`, which stops
/// the chain. A block label has no type either, and opens its own scope the
/// way a module does.
fn link_type(scopes: &[Scope], symbols: &[Symbol], id: SymbolId) -> Option<MemberSite> {
let symbol = symbols.get(id.0 as usize)?;
let Some(type_name) = symbol.type_name.as_deref() else {
@@ -638,8 +639,10 @@ fn container_scope(symbols: &[Symbol], id: SymbolId) -> Option<ScopeId> {
/// The scope a symbol opens when a `.` may name its members: a class, a
/// module, or an interface — which is what makes `vif.sig` and `u.internal`
/// reach into one — **or** a `struct`/`union` body, whoever names it. A
/// package is a container to pass through, never a thing a handle can be.
/// reach into one — a named block, which is what `g_lane[0].lane_q` and
/// `blk.tmp` reach into (IEEE 1800 §23.6), **or** a `struct`/`union` body,
/// whoever names it. A package is a container to pass through, never a thing
/// a handle can be.
///
/// The struct half is deliberately written as "any symbol whose child scope is
/// a struct body", not "a `Typedef` whose child scope is one": the same rule
@@ -651,6 +654,7 @@ fn member_scope(scopes: &[Scope], symbols: &[Symbol], id: SymbolId) -> Option<Sc
let symbol = symbols.get(id.0 as usize)?;
if symbol.kind == SymbolKind::Class
|| symbol.kind == SymbolKind::Covergroup
|| symbol.kind == SymbolKind::Block
|| symbol.kind.is_instantiable()
{
return symbol.child_scope;
@@ -49,6 +49,14 @@ use super::{Def, WorkspaceIndex};
/// It gains its instances hierarchically for the same hop reason, and nothing
/// else moves.
///
/// A **named generate block** (and a named procedural block) is on its
/// module's or interface's hierarchical surface, and has only that surface
/// itself: `u_x.g_lane[0].lane_q` names the block and then its variable
/// (§23.6, §27.4), and no connection list can name either. What a block
/// exports is what a path may select from it — its nets, variables, instances,
/// parameters and nested blocks — under the synthesized key
/// `record::block_key` gives it.
///
/// A `typedef struct`/`union` exports its fields, and a field that is itself
/// an inline aggregate exports its own — which is what a generated register
/// package is: `reg2hw_t` → `ctrl` → `q`. A covergroup's surface is its
@@ -80,7 +88,9 @@ pub(super) fn surface_of(unit: SymbolKind, member: SymbolKind) -> Option<Surface
| SymbolKind::LocalParam
| SymbolKind::Property
| SymbolKind::Sequence => Some(Surface::Connection),
SymbolKind::Net | SymbolKind::Var | SymbolKind::Instance => Some(Surface::Hierarchical),
SymbolKind::Net | SymbolKind::Var | SymbolKind::Instance | SymbolKind::Block => {
Some(Surface::Hierarchical)
}
_ => None,
},
SymbolKind::Typedef | SymbolKind::StructMember => {
@@ -101,7 +111,16 @@ pub(super) fn surface_of(unit: SymbolKind, member: SymbolKind) -> Option<Surface
| SymbolKind::Task
| SymbolKind::Modport
| SymbolKind::Clocking => Some(Surface::Connection),
SymbolKind::Instance => Some(Surface::Hierarchical),
SymbolKind::Instance | SymbolKind::Block => Some(Surface::Hierarchical),
_ => None,
},
SymbolKind::Block => match member {
SymbolKind::Net
| SymbolKind::Var
| SymbolKind::Instance
| SymbolKind::Block
| SymbolKind::Param
| SymbolKind::LocalParam => Some(Surface::Hierarchical),
_ => None,
},
_ => None,
+19 -3
View File
@@ -501,7 +501,7 @@ fn collect_members(
continue;
}
let mut decl = Decl::member(member, lines, surface);
let nested = nested_key(key, member);
let nested = nested_key(key, member).or_else(|| block_key(key, member));
if let Some(nested) = &nested {
decl.type_name = Some(nested.clone());
}
@@ -511,8 +511,9 @@ fn collect_members(
// *class's* name — register them there too. A struct `typedef` nested
// in a package is the same shape, an inline aggregate member is the
// same shape under its synthesized key, and so is a covergroup, whose
// labelled coverpoints `cg_inst.cp` reaches. The scope tree is
// acyclic, so this recursion terminates.
// labelled coverpoints `cg_inst.cp` reaches. A named block is the
// inline-aggregate shape: no type name, so a synthesized key. The
// scope tree is acyclic, so this recursion terminates.
if matches!(member.kind, SymbolKind::Class | SymbolKind::Typedef | SymbolKind::Covergroup) {
collect_members(sem, &member.name, member, lines, out);
} else if let Some(nested) = nested {
@@ -543,6 +544,21 @@ fn nested_key(key: &str, member: &Symbol) -> Option<String> {
.then(|| format!("{key}.{}", member.name))
}
/// The member-table key a **named block**'s own members are registered under,
/// and the `type_name` the block's [`Def`] carries so that a path's next hop
/// finds them: the container's key and the label, joined by a `.` —
/// [`nested_key`]'s spelling, for [`nested_key`]'s reasons. A block's label is
/// no type name, and the bare label would collide across every module that
/// writes a `gen_generic` or a `g_lane`; the dotted one is unwritable as a
/// unit name and unique per module (`docs/features/generate-label-rename`).
///
/// Shared with [`crate::Semantics::member_key`], which is how a caller holding
/// one file's analysis names the same table.
fn block_key(key: &str, member: &Symbol) -> Option<String> {
(member.kind == SymbolKind::Block && member.child_scope.is_some())
.then(|| format!("{key}.{}", member.name))
}
/// Parse one file and read its `` `define`` table off the same token stream.
fn parse_and_collect(src: &str) -> (vlog_parser::ast::SourceFile, DefineTable, Census) {
match tokenize(src) {
@@ -0,0 +1,255 @@
//! Named blocks as places a path reaches through (TODO §65.1): a generate
//! block's label is declared where the construct is written, an index into a
//! generate array is walked as the block itself, and a module's blocks and
//! their members are on its hierarchical surface in the workspace index.
//! `docs/features/generate-label-rename/README.md`.
use std::path::PathBuf;
use vlog_parser::parse_source_tolerant;
use vlog_semantic::{
analyze, resolve_external, ExternalTarget, Resolution, Semantics, Surface, SymbolKind,
WorkspaceIndex,
};
fn sem(src: &str) -> Semantics {
let (file, _) = parse_source_tolerant(src);
analyze(&file, src)
}
/// Offset of the `n`th (0-based) occurrence of `needle`, plus `skip` bytes.
fn at(src: &str, needle: &str, n: usize, skip: usize) -> u32 {
(src.match_indices(needle).nth(n).expect("occurrence must exist").0 + skip) as u32
}
fn resolution(s: &Semantics, offset: u32) -> Resolution {
s.reference_at(offset).unwrap_or_else(|| panic!("no reference at {offset}")).resolution.clone()
}
fn declared(s: &Semantics, src: &str, needle: &str, skip: usize) -> Resolution {
let id = s.symbol_at(at(src, needle, 0, skip)).expect("a declaration there");
Resolution::Resolved(id)
}
const LOOP: &str = "module fsm (output logic busy);
for (genvar gi = 0; gi < 2; gi++) begin : g_lane
logic lane_q;
end : g_lane
assign busy = g_lane[0].lane_q | g_lane[gi].lane_q;
endmodule
";
#[test]
fn a_for_generate_label_is_a_name_of_the_enclosing_module_and_its_genvar_is_not() {
let s = sem(LOOP);
let label = declared(&s, LOOP, "begin : g_lane", 8);
assert_eq!(resolution(&s, at(LOOP, "g_lane[0]", 0, 0)), label);
assert_eq!(resolution(&s, at(LOOP, "end : g_lane", 0, 6)), label, "the closing label");
assert_eq!(resolution(&s, at(LOOP, "g_lane[gi]", 0, 0)), label);
assert_eq!(resolution(&s, at(LOOP, "[gi]", 0, 1)), Resolution::NotFound, "no genvar leak");
let lane_q = declared(&s, LOOP, "logic lane_q", 6);
assert_eq!(resolution(&s, at(LOOP, ".lane_q", 0, 1)), lane_q, "through the index");
assert_eq!(resolution(&s, at(LOOP, ".lane_q", 1, 1)), lane_q);
}
#[test]
fn a_nested_block_is_reached_through_its_parent_and_an_index() {
let src = "module n (output logic o);
if (1) begin : g_a
for (genvar j = 0; j < 4; j++) begin : g_b
logic x;
end
end
assign o = g_a.g_b[2].x;
endmodule
";
let s = sem(src);
assert_eq!(resolution(&s, at(src, "g_a.g_b", 0, 4)), declared(&s, src, "begin : g_b", 8));
assert_eq!(resolution(&s, at(src, "[2].x", 0, 4)), declared(&s, src, "logic x", 6));
}
#[test]
fn a_generate_region_is_not_a_scope() {
let src = "module r (output logic o);
generate
if (1) begin : g_in
logic q;
end
wire w;
endgenerate
assign o = g_in.q | w;
endmodule
";
let s = sem(src);
assert_eq!(resolution(&s, at(src, "g_in.q", 0, 0)), declared(&s, src, "begin : g_in", 8));
assert_eq!(resolution(&s, at(src, "| w", 0, 2)), declared(&s, src, "wire w", 5));
}
#[test]
fn both_arms_of_a_generate_if_are_one_label_closing_labels_included() {
let src = "module d (output logic o);
if (1) begin : g
logic q;
end : g
else begin : g
logic q;
end : g
assign o = g.q;
endmodule
";
let s = sem(src);
let first = declared(&s, src, "begin : g", 8);
for (needle, n) in [("begin : g", 1), ("end : g", 0), ("end : g", 1)] {
let skip = needle.len() - 1;
assert_eq!(resolution(&s, at(src, needle, n, skip)), first, "{needle} #{n}");
}
}
#[test]
fn a_prefix_statement_label_owns_its_closing_label() {
let src = "module p;\n initial lbl: begin\n disable lbl;\n end : lbl\nendmodule\n";
let s = sem(src);
let label = declared(&s, src, "lbl:", 0);
assert_eq!(resolution(&s, at(src, "disable lbl", 0, 8)), label);
assert_eq!(resolution(&s, at(src, "end : lbl", 0, 6)), label);
}
/// Review L-1: an unowned block's closing label is a use of a same-named
/// block only when it spells the block's own opening label; a mismatched
/// `end : a` closing `b: begin` records nothing.
#[test]
fn a_closing_label_that_does_not_spell_the_opening_one_attaches_to_nothing() {
let src =
"module e;\n initial begin : a\n end : a\n initial b: begin\n end : a\nendmodule\n";
let s = sem(src);
let a = declared(&s, src, "begin : a", 8);
assert_eq!(resolution(&s, at(src, "end : a", 0, 6)), a, "a's own closing label");
assert!(s.reference_at(at(src, "end : a", 1, 6)).is_none(), "b's mismatched closing label");
}
/// Review L-1: an `endfunction : g` beside a generate block `g` (a duplicate
/// the linter reports) is not a use of the block.
#[test]
fn a_subroutines_closing_label_is_never_a_use_of_a_same_named_block() {
let src = "module e;\n if (1) begin : g\n end : g\n function automatic logic g();\n return 1'b0;\n endfunction : g\nendmodule\n";
let s = sem(src);
let block = declared(&s, src, "begin : g", 8);
let closing = s.reference_at(at(src, "endfunction : g", 0, 14)).map(|r| r.resolution.clone());
assert_ne!(closing, Some(block), "endfunction : g is not the block's");
}
#[test]
fn an_index_is_walked_only_where_the_link_has_members_of_its_own() {
let src = "module t (output logic o);
typedef struct packed { logic f; } pkt_t;
pkt_t [1:0] packed_arr;
pkt_t unpacked_arr [2];
assign o = packed_arr[0].f | unpacked_arr[1].f;
endmodule
";
let s = sem(src);
assert_eq!(resolution(&s, at(src, "[0].f", 0, 4)), declared(&s, src, "logic f", 6));
assert!(s.reference_at(at(src, "[1].f", 0, 4)).is_none(), "an unpacked element is untyped");
}
#[test]
fn a_blocks_member_key_is_its_modules_and_its_labels() {
let src = "module sub;\n if (1) begin : g_a\n if (1) begin : g_b\n logic x;\n end\n end\nendmodule\n";
let s = sem(src);
let key_of = |name: &str| {
let id = s.symbols_named(name).next().expect("declared");
s.symbol(id).and_then(|sym| s.member_key(sym.scope))
};
assert_eq!(key_of("g_a").as_deref(), Some("sub"));
assert_eq!(key_of("g_b").as_deref(), Some("sub.g_a"));
assert_eq!(key_of("x").as_deref(), Some("sub.g_a.g_b"));
}
const SUB: &str = "module sub (input logic clk);
for (genvar i = 0; i < 2; i++) begin : g_lane
logic sig;
if (1) begin : g_in
logic deep;
end
end
endmodule
";
const TOP: &str = "module top (output logic o);
sub u_x (.clk(1'b0));
assign o = u_x.g_lane[1].sig | u_x.g_lane[0].g_in.deep;
endmodule
";
fn index() -> WorkspaceIndex {
WorkspaceIndex::build([("sub.sv", SUB), ("top.sv", TOP)].map(|(p, s)| (PathBuf::from(p), s)))
}
/// The one declaration the overlay answers the reference at `offset` with,
/// as `(kind, the name it spells in SUB)`.
fn external(s: &Semantics, ws: &WorkspaceIndex, offset: u32) -> (SymbolKind, String) {
let overlay = resolve_external(s, ws);
let id = s.reference_id_at(offset).expect("a reference there");
match overlay.get(id) {
Some(ExternalTarget::Resolved(def)) => {
(def.kind, SUB[def.name_span.as_range()].to_string())
}
other => panic!("not resolved: {other:?}"),
}
}
#[test]
fn a_path_from_another_file_reaches_the_block_and_its_members() {
let ws = index();
let s = sem(TOP);
let block = (SymbolKind::Block, "g_lane".to_string());
assert_eq!(external(&s, &ws, at(TOP, "u_x.g_lane", 0, 4)), block);
assert_eq!(external(&s, &ws, at(TOP, "u_x.g_lane", 1, 4)), block);
assert_eq!(external(&s, &ws, at(TOP, ".sig", 0, 1)), (SymbolKind::Var, "sig".to_string()));
assert_eq!(external(&s, &ws, at(TOP, ".g_in", 0, 1)), (SymbolKind::Block, "g_in".into()));
assert_eq!(external(&s, &ws, at(TOP, ".deep", 0, 1)), (SymbolKind::Var, "deep".into()));
}
#[test]
fn a_block_and_its_members_are_hierarchical_only_under_the_dotted_key() {
let ws = index();
assert!(ws.member("sub", "g_lane").is_empty(), "no connection list can name a block");
assert_eq!(ws.member_in("sub", "g_lane", Surface::Hierarchical).len(), 1);
assert_eq!(ws.member_in("sub.g_lane", "sig", Surface::Hierarchical).len(), 1);
assert_eq!(ws.member_in("sub.g_lane.g_in", "deep", Surface::Hierarchical).len(), 1);
assert!(
ws.member_in("g_lane", "sig", Surface::Hierarchical).is_empty(),
"never the bare label"
);
let held: Vec<&str> = ws.hierarchical_declarations("g_lane").map(|(unit, _)| unit).collect();
assert_eq!(held, vec!["sub"]);
}
#[test]
fn an_unnamed_block_declares_nothing_a_path_can_name() {
let src = "module u (output logic o);\n if (1) begin\n logic w;\n end\n assign o = genblk1.w;\nendmodule\n";
let s = sem(src);
assert_eq!(resolution(&s, at(src, "genblk1", 0, 0)), Resolution::NotFound);
assert!(s.reference_at(at(src, "genblk1.w", 0, 8)).is_none());
assert!(s.symbols_named("genblk1").next().is_none(), "no symbol is invented for it");
}
/// QA F3: a block label that collides with a net of its scope is a duplicate
/// and **not** a use of the first declaration, either way round; two arms
/// sharing a label still are one label.
#[test]
fn a_block_label_beside_a_same_named_net_is_a_duplicate_and_not_a_use() {
let net_first = "module c;\n wire g;\n if (1) begin : g\n end : g\nendmodule\n";
let s = sem(net_first);
assert_eq!(s.duplicates().len(), 1);
let net = s.symbols_named("g").next().expect("the net");
assert_eq!(s.symbol(net).map(|x| x.kind), Some(SymbolKind::Net));
assert!(s.references_of(net).is_empty(), "the label is not a read of the net");
let block_first = "module c;\n if (1) begin : g\n end : g\n wire g;\nendmodule\n";
let s = sem(block_first);
assert_eq!(s.duplicates().len(), 1);
let block = s.symbols_named("g").next().expect("the block");
let uses: Vec<u32> = s.references_of(block).iter().map(|r| r.name_span.start).collect();
assert_eq!(uses, vec![at(block_first, "end : g", 0, 6)], "only its closing label");
}
+7 -1
View File
@@ -197,7 +197,6 @@ endmodule
for (spelling, why) in [
("x.bit_field", "a built-in type names no declaration"),
("stranger.thing", "the head is not declared here"),
("blk.inner", "a generate block label is not a type this crate models"),
("h.absent", "the class is known whole and has no such member"),
] {
assert!(s.reference_at(tail(src, spelling, 0)).is_none(), "{spelling}: {why}");
@@ -207,6 +206,13 @@ endmodule
resolution_at(&s, tail(src, "h.known", 0)),
Resolution::Resolved(symbol_named(&s, "known"))
);
// A generate block label was on the list above until TODO §65.1: a named
// block opens a scope a path may select from (IEEE 1800 §23.6), so its
// member resolves (`docs/features/generate-label-rename/README.md`).
assert_eq!(
resolution_at(&s, tail(src, "blk.inner", 0)),
Resolution::Resolved(symbol_named(&s, "inner"))
);
}
/// `this.x` walks the `extends` chain as far as this file declares it.
@@ -0,0 +1,300 @@
//! QA attacks on TODO §65.1's scope rules (a generate label declared in the
//! enclosing scope, `generate … endgenerate` not a scope, a block's member
//! scope, an index transparent in a path's spine).
//! `docs/features/generate-label-rename/README.md`, QA log 2026-09-30.
use vlog_parser::parse_source_tolerant;
use vlog_semantic::{analyze, Resolution, Semantics};
fn sem(src: &str) -> Semantics {
let (file, _) = parse_source_tolerant(src);
analyze(&file, src)
}
/// Offset of the `n`th (0-based) occurrence of `needle`, plus `skip` bytes.
fn at(src: &str, needle: &str, n: usize, skip: usize) -> u32 {
(src.match_indices(needle).nth(n).expect("occurrence must exist").0 + skip) as u32
}
fn resolution(s: &Semantics, offset: u32) -> Option<Resolution> {
s.reference_at(offset).map(|r| r.resolution.clone())
}
fn declared(s: &Semantics, src: &str, needle: &str, n: usize, skip: usize) -> Option<Resolution> {
let id = s.symbol_at(at(src, needle, n, skip)).expect("a declaration there");
Some(Resolution::Resolved(id))
}
#[test]
fn a_genvar_never_leaks_even_past_a_module_signal_of_its_name() {
let src = "module g (output logic o, output logic p);
logic i;
for (genvar i = 0; i < 2; i++) begin : g_l
logic q;
assign q = i[0];
end
assign o = i;
assign p = g_l[1].q;
endmodule
";
let s = sem(src);
assert_eq!(resolution(&s, at(src, "o = i", 0, 4)), declared(&s, src, "logic i", 0, 6));
assert_eq!(resolution(&s, at(src, "q = i", 0, 4)), declared(&s, src, "genvar i", 0, 7));
assert_eq!(resolution(&s, at(src, "g_l[1]", 0, 0)), declared(&s, src, ": g_l", 0, 2));
}
#[test]
fn a_member_lookup_through_a_block_never_climbs_to_the_enclosing_scope() {
// `g_l[0].clk` names a `clk` *inside* the block; there is none, so the
// module's port must never be the answer (a rename of `clk` would then
// rewrite a path that meant something else).
let src = "module m (input logic clk, output logic o, output logic p);
for (genvar i = 0; i < 2; i++) begin : g_l
logic q;
end
if (1) begin : g_b
logic r;
end
assign o = g_l[0].clk;
assign p = g_b.clk;
endmodule
";
let s = sem(src);
let port = declared(&s, src, "logic clk", 0, 6);
for (needle, n) in [(".clk", 0), (".clk", 1)] {
let got = resolution(&s, at(src, needle, n, 1));
assert_ne!(got, port, "{needle} #{n} climbed to the module port: {got:?}");
}
}
#[test]
fn an_unnamed_generate_if_hides_its_declarations_and_a_region_does_not() {
let src = "module u (output logic o, output logic p);
generate
wire in_region;
if (1) begin
wire hidden;
end
begin
wire in_bare;
end
endgenerate
assign o = in_region;
assign p = hidden | in_bare;
endmodule
";
let s = sem(src);
assert_eq!(
resolution(&s, at(src, "o = in_region", 0, 4)),
declared(&s, src, "wire in_r", 0, 5)
);
for (needle, decl) in [("p = hidden", "wire hidden"), ("| in_bare", "wire in_bare")] {
let got = resolution(&s, at(src, needle, 0, needle.find(' ').unwrap_or(0) + 3));
assert_ne!(got, declared(&s, src, decl, 0, 5), "{needle} saw into an unnamed block");
}
}
#[test]
fn a_block_label_named_like_a_module_is_the_lexical_answer() {
// IEEE 1800 §23.8: a name is looked up in the enclosing scopes before it
// is taken as a top-level module name.
let src = "module sub;
logic x;
endmodule
module m (output logic o);
if (1) begin : sub
logic x;
end
assign o = sub.x;
endmodule
";
let s = sem(src);
assert_eq!(resolution(&s, at(src, "sub.x", 0, 0)), declared(&s, src, ": sub", 0, 2));
assert_eq!(resolution(&s, at(src, "sub.x", 0, 4)), declared(&s, src, "logic x", 1, 6));
}
#[test]
fn an_element_select_never_resolves_to_a_declaration_of_another_type() {
let src = "module t (output logic o);
typedef struct packed { logic f; } pkt_t;
typedef struct packed { logic f; } other_t;
typedef pkt_t [1:0] vec_t;
pkt_t [1:0][1:0] two_d;
vec_t v;
logic [3:0] bits;
other_t f;
assign o = two_d[0][1].f | v[1].f | bits[0].f;
endmodule
";
let s = sem(src);
let pkt_f = declared(&s, src, "logic f", 0, 6);
assert_eq!(resolution(&s, at(src, "[1].f |", 0, 4)), pkt_f, "a 2-D packed array of pkt_t");
assert_eq!(resolution(&s, at(src, "v[1].f", 0, 5)), pkt_f, "through a packed-array typedef");
let got = resolution(&s, at(src, "bits[0].f", 0, 8));
assert!(
!matches!(got, Some(Resolution::Resolved(_))),
"`bits[0].f` has no field to name: {got:?}"
);
}
#[test]
fn an_index_through_a_class_queue_or_an_instance_array_is_not_a_wrong_answer() {
let src = "class item;
int m;
endclass
module leaf (output logic sig);
endmodule
module t (output logic o);
int m;
logic sig;
item q[$];
leaf u_arr [2] (.sig());
initial o = q[0].m == 0;
assign o = u_arr[1].sig;
endmodule
";
let s = sem(src);
let got = resolution(&s, at(src, "q[0].m", 0, 5));
assert_ne!(got, declared(&s, src, "int m", 1, 4), "the module's `m`: {got:?}");
let got = resolution(&s, at(src, "u_arr[1].sig", 0, 9));
assert_ne!(got, declared(&s, src, "logic sig", 1, 6), "the module's `sig`: {got:?}");
}
#[test]
fn a_procedural_block_in_a_function_is_one_label_with_disable_and_end() {
let src = "module f;
function automatic int ff(int a);
begin : fb
if (a == 0) disable fb;
ff = a;
end : fb
endfunction
task automatic tt();
fork : fk
join_none : fk
disable fk;
endtask
endmodule
";
let s = sem(src);
let fb = declared(&s, src, ": fb", 0, 2);
assert_eq!(resolution(&s, at(src, "disable fb", 0, 8)), fb);
assert_eq!(resolution(&s, at(src, "end : fb", 0, 6)), fb);
let fk = declared(&s, src, ": fk", 0, 2);
assert_eq!(resolution(&s, at(src, "join_none : fk", 0, 12)), fk);
assert_eq!(resolution(&s, at(src, "disable fk", 0, 8)), fk);
}
#[test]
fn sibling_loops_with_one_label_neither_crash_nor_resolve_into_the_wrong_body() {
let src = "module s (output logic o, output logic p);
for (genvar i = 0; i < 2; i++) begin : g
logic a;
end : g
for (genvar j = 0; j < 2; j++) begin : g
logic b;
end : g
assign o = g[0].a;
assign p = g[1].b;
endmodule
";
let s = sem(src);
let first = declared(&s, src, ": g", 0, 2);
for (needle, n) in [(": g", 1), (": g", 2), (": g", 3), ("g[0]", 0), ("g[1]", 0)] {
let skip = if needle.starts_with(':') { 2 } else { 0 };
assert_eq!(resolution(&s, at(src, needle, n, skip)), first, "{needle} #{n}");
}
assert_eq!(resolution(&s, at(src, ".a", 0, 1)), declared(&s, src, "logic a", 0, 6));
let got = resolution(&s, at(src, ".b", 0, 1));
assert_ne!(got, declared(&s, src, "logic a", 0, 6), "{got:?}");
}
#[test]
fn a_label_in_both_arms_of_an_ifdef_is_one_label() {
let src = "module d (output logic o);
`ifdef WIDE
for (genvar i = 0; i < 4; i++) begin : g_w
logic q;
end : g_w
`else
for (genvar i = 0; i < 2; i++) begin : g_w
logic q;
end : g_w
`endif
assign o = g_w[0].q;
endmodule
";
let s = sem(src);
let first = declared(&s, src, ": g_w", 0, 2);
for n in 1..4 {
assert_eq!(resolution(&s, at(src, ": g_w", n, 2)), first, "label #{n}");
}
assert_eq!(resolution(&s, at(src, "g_w[0]", 0, 0)), first);
}
#[test]
fn a_blocks_member_key_is_none_or_dotted_never_a_bare_colliding_name() {
// A named block inside a function: the function's own name is not a key
// the index files anything under, and `ff.fb` is exactly the key a
// module `ff`'s block `fb` is filed under.
let src = "module m;
function automatic void ff();
begin : fb
logic t;
t = 1'b0;
end
endfunction
endmodule
";
let s = sem(src);
let t = s.symbols_named("t").next().expect("t");
let key = s.symbol(t).and_then(|sym| s.member_key(sym.scope));
assert_ne!(key.as_deref(), Some("ff.fb"), "collides with module `ff`'s block `fb`");
// Fixed (F4): qualified by the enclosing unit, marked as the function's.
assert_eq!(key.as_deref(), Some("m.ff().fb"));
}
/// Re-check of F4: a named block in a package function, a class method, an
/// out-of-body class method and an interface task — never a key the index
/// files a module's block under.
#[test]
fn recheck_a_block_in_a_subroutine_anywhere_keys_by_its_unit_and_subroutine() {
let src = "package pk;
function automatic void pf();
begin : pb
logic pt;
end
endfunction
class cls;
function void cm();
begin : cb
logic ct;
end
endfunction
extern function void ext();
endclass
function void cls::ext();
begin : eb
logic et;
end
endfunction
endpackage
interface ifc;
task automatic it();
begin : ib
logic itv;
end
endtask
endinterface
";
let s = sem(src);
let key = |name: &str| {
let id = s.symbols_named(name).next().expect("declared");
s.symbol(id).and_then(|sym| s.member_key(sym.scope))
};
assert_eq!(key("pt").as_deref(), Some("pk.pf().pb"));
assert_eq!(key("ct").as_deref(), Some("cls.cm().cb"));
assert_eq!(key("itv").as_deref(), Some("ifc.it().ib"));
let et = key("et");
assert!(et.as_deref().is_none_or(|k| k.contains("()")), "{et:?}");
}
@@ -0,0 +1,597 @@
# call-hierarchy-everywhere
Lane A of a two-lane wave (2026-10-14). Builds on `hierarchy` (M11, the
module call hierarchy) and `type-hierarchy` (the class tree); both READMEs
point here for what changed.
## Goal
A user report: in VS Code, "Show Call Hierarchy" showed nothing. The lead
reproduced it at the LSP level — `prepareCallHierarchy` answered only with the
cursor exactly on a module's declaration name or on an instantiated module
name, and `null` everywhere else (an instance name, anywhere in a module body,
on or inside a function or task); `prepareTypeHierarchy` answered `null`
anywhere inside a class body but on its name. An editor that opens nothing
from 95 % of the positions a user invokes the command from looks broken,
whatever the protocol allows. This feature makes both views open from wherever
the cursor is, and gives functions and tasks a call hierarchy of their own —
callers and callees resolved through the semantic and workspace layers, not by
name-matching strings.
## What each prepare position answers
`textDocument/prepareCallHierarchy`, first match wins:
| cursor | answer |
|---|---|
| a module's own declaration name | that module (M11, byte-identical) |
| the module name of an instantiation | every declaration of it (M11, byte-identical) |
| an **instance name** (`u_sub` in `sub u_sub (…)`) | the instantiated module's item(s) — the same answer as its module name |
| a function or task: its declaration name, a call, the `endfunction : f` label | a function/task item (`FUNCTION`, or `METHOD` in a class); a call two files could answer gives both, as `definition` does |
| anywhere else inside a function or task body (incl. its header and `endfunction`) | that function or task |
| anywhere else inside a module, interface or program (incl. its header, comments, strings) | the innermost enclosing module's item, exactly as M11 builds it |
| a package body outside its functions, a file-level or package-level class body outside its methods, file scope, a large-file buffer | `null` |
A class declared *inside a module* is inside that module, so a position in
its body outside a method answers the enclosing module (the innermost-module
rule), not `null`. A cursor on a macro use (`` `CALL_IT(1) ``) is no name
either layer resolves, so it answers the enclosing function or module.
A position just past the last character of a name is on that name (M11's
caret rule, extended to calls: `twice|(v)` prepares `twice`).
`textDocument/prepareTypeHierarchy`: the class name or a use of it as before;
otherwise the **innermost class whose declaration encloses the cursor**; on
`super`, that class's base(s) (`supertypes` of the enclosing class), falling
back to the class itself when the base is unresolvable. `this` needs no case —
it is inside its class. Modules stay off the type hierarchy (the type-hierarchy
README's lead decision): a position in a module and outside every class is
still `null`.
## Item kinds and `data`
| item | `kind` | `data` |
|---|---|---|
| module / interface / program | `MODULE` (unchanged) | none (unchanged) |
| function or task | `FUNCTION`; `METHOD` when declared in a class | `{"kind":"function"\|"task","name":…,"offset":…}` |
| package caller | `PACKAGE` | `{"kind":"package","name":…,"offset":…}` |
| class caller | `CLASS` | `{"kind":"class","name":…,"offset":…}` |
`offset` is the byte offset of the declared name in the item's file when the
item was built. `detail` on a function/task/package/class item is the name of
the container the declaration sits in (`util_pkg`, `counter`), so two `log2`s
in one list can be told apart; `None` at `$unit`.
`incomingCalls`/`outgoingCalls` route on `data`: an item whose `data` parses
as above goes to `hierarchy/calls.rs`; anything else (no `data`, or `data`
this server did not write) is a module item and takes the M11 path untouched.
Package and class caller items answer both directions with nothing.
**Re-finding the declaration.** The item's file (the open buffer, else a fresh
analysis of the file on disk) is searched for symbols of that name and kind:
the one whose name starts at `offset`, else the one at the item's
`selectionRange` start, else — by name alone — the **only** one of that name
and kind declared in the container the item's `detail` names (no container
for `$unit`). Otherwise the item answers nothing: unlike modules, two
functions of one name are ordinary, and the old "first of that name" fallback
let a stale item for `mb`'s `log2` answer for `ma`'s (QA finding 3). `detail`
is the one echoed field relied on besides `data`, and only as a tie-break.
## Incoming and outgoing
**A call** is a use of the function's name that the semantic layer resolved
to the declaration — in the declaring file through the symbol table or the
workspace overlay (`super.f()` reaches a base-class method through the
overlay), in another file through the overlay — and that is not one of three
non-call uses: the `endfunction : f` end label, the name of an out-of-body
definition (`function void c::f();`, recorded as a redeclaration), and the
Verilog **result variable**: a function's own name inside its own body with no
`(` after it, whether written (`f = a;`, `f += 1;`) or read
(`clog2 = clog2 + 1;`). `f(…)` inside its own body is recursion and is listed;
a bare `f` in *another* body is a call (a function with no arguments may be
called without parentheses) and is listed too.
**`incomingCalls`** — every call, workspace-wide, from the same files
`textDocument/references` reads for the same declaration: the declaring file;
for a declaration the index holds (a package or class member), every open
buffer plus every closed file the index has a reference posting for. The same
ambiguity contract too: a declaration whose uses the index marks ambiguous,
or an open buffer holding an ambiguous use of it, falls back to the declaring
file alone (references falls back to the cursor's file). Grouped one entry per
caller — the innermost enclosing function or task, else the enclosing module,
interface, program, package or class — with `fromRanges` the call names. A
call at file scope has no caller and is dropped (the same rule as an
instantiation outside a module). Sorted by caller URI, then line. A **module
caller** is the very M11 module item (no `data`), so expanding it walks
instantiations — one level up the design.
**`outgoingCalls`** — the calls written in the function's bodies (plural: an
`extern` prototype and its out-of-body definition are two scopes owned by one
symbol), each resolved to its declaration, grouped by callee in order of first
call. **Skipped:** system tasks and functions (`$display` is not a reference
at all), an unresolved name, and a name the overlay finds ambiguous — the same
silence M11's `outgoingCalls` keeps for an ambiguous instantiation, for the
same reason (a node pointing at the wrong one of two declarations is
unfalsifiable to the reader).
**Module items do not mix in function calls** (the brief's default, kept). A
module's outgoing calls are instantiations; listing `always`-block calls beside
them would put two relations behind one node with no way for a client to tell
them apart — exactly the argument the type-hierarchy README makes for keeping
modules off `typeHierarchy`. The function-to-module direction does mix, on
purpose: a function's caller may *be* a module, and that node is the module
item, whose own expansion is the design tree.
Each request answers one hop; recursion (`fact` calls `fact`) is the function
appearing as its own caller and callee, and the client drives the expansion.
## Assumptions
- **Callers are found by re-analysing files, not from the index's spans.**
Attribution needs the enclosing scope of every call, which a reference
posting does not carry, so each candidate closed file is parsed and analysed
once (`Document::new`) — the cost is one parse per file that references the
function, the same order as `incomingCalls` for modules reading the files
that instantiate. The *file selection* is references'; the spans are the
live analysis's, so a closed file edited on disk since the last index build
answers with its current text (references would drop the stale span).
- **The result variable is recognised by scope plus one token:** the use
resolves to a function, sits in a body that function owns (its own scope
or an out-of-body definition's), and the next token is not `(`. Tasks have
no result variable. This is the only token-level judgement; everything else
is the semantic model's.
- **An end label is recognised structurally:** it lies inside the extent of
the scope its declaration opens but is recorded in the scope around it
(`vlog_semantic`'s `use_end_label`). A recursive call is recorded inside.
- **Two declarations of one name and kind in one file** resolve by `offset`;
when an edit has moved both the offset and the selection range, by the
item's `detail` (container), and otherwise not at all — see "Re-finding the
declaration".
- **The two ambiguity fallbacks are defensive.** `indexed_def_for_symbol`
accepts a declaration only when its unit's member table holds exactly one
record for the name, and every use's lookup reads that same table, so in a
consistent workspace no use can be ambiguous *and* include a declaration
this feature stands on. The decision lives in one predicate, `declined`,
whose two clauses are each pinned by a unit test that reaches it directly
(an indexed caller of a twice-declared package; an open buffer outside the
indexed folder); kept because references has the same contract and a
future index rule could make the case reachable.
- **A function's caller inside a class body but outside a method** (a
property initializer) is the class; inside a package outside a function, the
package. Both are items with `data` and no further hops.
## Limits
- **A `$unit` function called from another file** is not resolved: the
semantic layer finishes an unqualified value-position name only through
imports, so `ufn(1)` in a file that does not declare `ufn` is `NotFound`.
In-file calls work. The cursor on such a call falls back to the enclosing
module. Pinned by
`hierarchy_everywhere::a_unit_scope_function_answers_in_its_own_file_only`.
- **A module's own function called hierarchically from another module**
(`u_core.twice()`) is not a call this feature sees: module-level functions
are on no index surface (`surface_of(Module, Function)` is `None`).
- **The end label of an out-of-body definition** records no use in the binder,
so prepare on it falls back to the enclosing function (the definition's own
body), which is the right item anyway.
- **Class methods:** calls through `this.`, a bare name, a typed handle
(same file and across files, through `import`) and `super.` all resolve and
are listed. Virtual dispatch is not modelled: `h.f()` is a call of the `f`
the handle's *declared* class resolves to, not of every override.
- `prepareTypeHierarchy` on `super` with an unresolvable base answers the
enclosing class rather than `null`.
- **Macros are not expanded.** A cursor on a macro use answers the enclosing
function or module, and a call written inside a macro body (`` `CALL_IT(1) ``
expanding to `cf(1)`) is not listed by `incomingCalls` or `outgoingCalls` —
the same answer references gives, since neither layer sees the expansion.
## Handshakes
- **Consumes `vlog_semantic`** (read-only, nothing new asked): `Semantics`
scopes/symbols/references/duplicates, `ExternalResolutions::{definition_of,
get}`, `WorkspaceIndex::{references_to, references_are_ambiguous, path}`.
- **Consumes `crate::nav::indexed_def_for_symbol`** (already `pub(crate)`)
— the identity references uses to map a live symbol onto its indexed
declaration, so this feature and references agree on what "the same
function" is by construction. `nav.rs` is unchanged.
- **Consumes `crate::state`**: `Document::new` (a fresh analysis of a closed
file, as `type_hierarchy::supertypes` already does), `document`,
`document_for_path`, `open_documents`, `text_of`, `first_token_from`,
`first_token_reaching`. Unchanged.
- **Promises `server/dispatch.rs`**: nothing new — `hierarchy::{prepare,
incoming, outgoing}` and `type_hierarchy::prepare` keep their signatures,
and the routing on `data` lives inside `hierarchy.rs`. `dispatch.rs` is
untouched.
- **Promises clients**: a module item is byte-identical to M11's wherever M11
answered; `data` is present exactly on function, task, package and class
items.
- **REQUEST to the lead — `crates/lucisv_server/tests/e2e.rs` (not in this
lane's file list).** Two e2e round trips pin the old `null` at positions the
brief now makes answer, and fail on this lane:
- `the_module_hierarchy_round_trips_over_the_wire_in_both_directions`,
line 3401: `assert_eq!(response(5)["result"], Null, "an instance name is
no module")` — request 5 is the cursor on the instance name `u_mid` of
`hier_mid u_mid ();`; it now answers the `hier_mid` item. Proposed:
`assert_eq!(response(5)["result"][0]["name"], "hier_mid", "an instance
name stands for its module")` (and the comment above request 5, "The
instance name is not a module, so there is no hierarchy to open.", to
match).
- `the_class_hierarchy_round_trips_over_the_wire_in_both_directions`,
line 4876: `assert_eq!(response(5)["result"], Null, "a property name is
no class")` — request 5 is the property name `y` inside `type_mid`; it now
answers `type_mid`. Proposed: `assert_eq!(response(5)["result"][0]["name"],
"type_mid", "inside a class body, the enclosing class")` (and the comment
above request 5).
No other test outside this lane's files moved.
- **Note for a future `vlog_semantic` round (not a request this lane
blocks on):** resolving an unqualified call to a `$unit` function declared
in another file would lift the first limit above. It is a resolution-rule
change (compilation-unit scope is tool- and filelist-dependent), not
something to work around here.
- **`editors/vscode` needs no change** (lane B owns it): the client already
sends `prepareCallHierarchy`/`prepareTypeHierarchy` from any position.
## Status / TODO
- [x] `prepareCallHierarchy`: instance name, function/task (declaration, call,
end label), inside a function/task body, inside a module body, `null`
elsewhere — `hierarchy.rs::prepare`, `hierarchy/tf.rs`
- [x] function/task items with `data`; package/class caller items
- [x] `incomingCalls` with references' file selection and ambiguity fallback,
grouped by caller — `hierarchy/calls.rs`
- [x] `outgoingCalls` over the body (and an out-of-body definition), grouped by
callee; system tasks, unresolved and ambiguous names skipped
- [x] module items unchanged in both directions
- [x] `prepareTypeHierarchy` inside a class body, `super` → base —
`type_hierarchy.rs`
- [x] tests: 24 LSP-level in `server/tests/hierarchy_everywhere.rs`, 3 in
`hierarchy/tf.rs`, 4 in `hierarchy/calls.rs`, 1 new in `hierarchy.rs`;
seven existing unit tests that pinned the old `null` updated (work log)
- [x] probe before/after on real server binaries (work log)
- [x] `tests/e2e.rs`: two assertions to update — Handshake request above (lead;
flipped by the lead, verified green by QA 2026-10-14)
- [x] `cargo fmt --all --check`, clippy `-D warnings`; `cargo test -p
lucisv_server` green except the two e2e assertions above
- [x] rework after QA (2026-10-14): findings 1–5 and 7 fixed, with tests
## Work log
- **2026-10-14 (dev)** — read CLAUDE.md, the hierarchy and type-hierarchy
READMEs, `hierarchy.rs`, `type_hierarchy.rs`, `nav.rs` (references),
`vlog_semantic`'s model, binder and instantiation walk.
**Probed the semantic model first** (a throwaway test dumping scopes,
symbols, references and duplicates for module, package, class, extern and
`$unit` functions; deleted). What it showed shaped the design: a function's
scope spans its whole declaration including `endfunction : f`; the end label
is a reference *recorded in the outer scope*; `f = a;` resolves to `f`;
`c::ext`'s name is a reference to the prototype *and* a `Duplicate`; the
out-of-body body is a second scope owned by the prototype's symbol;
`this.f()` and `h.f()` resolve locally; `$display` records nothing.
**Decision — collect callers here rather than reuse `nav::references`.**
`references` takes a cursor in an *open* document, and the item a client
expands is very often in a closed one (prepare on a call in `core.sv`,
the declaration lives in a closed package file). Making `nav.rs` take a
`&Document` was outside this lane's files, so `calls.rs` reads the same
file set through the same public index API (`references_to`,
`references_are_ambiguous`) and the same identity
(`nav::indexed_def_for_symbol`), and a test
(`the_cross_file_answer_matches_references`) asserts the two agree
location for location, end label aside.
**Decision — routing on `data` inside `hierarchy.rs`**, so `dispatch.rs`
is untouched and a module item's path is literally the old code.
**Decision — module callers are M11 module items.** Expanding a function's
caller `top` then shows who instantiates `top`, which reads as one call
chain up the design; the reverse direction (module → functions) stays
closed, argued above.
**Found while testing:** `super.bump()` resolves through the workspace
overlay (an inherited candidate), not the local table, so the first cut's
declaring-file matcher (`resolved() == symbol`) missed it while
`outgoingCalls` (which reads both layers) found it. Fixed: the declaring
file accepts either layer; pinned by
`class_methods_called_through_this_a_handle_and_super`.
**Existing tests changed — seven, all pins of the old `null` at positions
the brief now makes answer** (the brief asks both for these answers and for
existing tests "green and unchanged"; the two cannot both hold, so each one
was changed to assert the new answer, renamed where its name stated the old
one, and given a "Reversed by call-hierarchy-everywhere" doc line):
`hierarchy.rs`: `a_position_on_no_module_prepares_nothing` →
`…_prepares_the_enclosing_one_or_nothing` (`module` keyword and a connected
expression → `top`, instance name → `sub`; the package case still `null`);
`an_instantiation_of_a_module_nothing_declares_prepares_nothing` →
`…_prepares_the_enclosing_module`; `qa_prepare_on_a_string_or_comment_is_null`
→ `…_is_the_enclosing_module_not_the_text`;
`qa_prepare_on_a_bind_target_module_name_is_currently_null` →
`…_was_null` (now `top`, the module the bind is written in) plus a new
`…_is_the_enclosing_module` with the bind moved into a `harness` so target
and enclosing module differ. `type_hierarchy.rs`:
`a_position_on_no_class_prepares_nothing` →
`…_prepares_the_enclosing_one_or_nothing` (`class` keyword and a property →
`base`; module and wire still `null`);
`prepare_on_the_extends_keyword_itself_prepares_nothing` →
`…_prepares_the_class_it_is_written_in` (`child`, never `base`);
`a_class_name_shadowed_by_a_local_variable_prepares_the_variable_use_as_nothing`
→ `…_prepares_the_enclosing_class` (`child`, never `base`). The
generate-class "known gap" pin is unchanged and green: the enclosing-class
fallback reads the same `classes::declarations` walk, so a class that walk
cannot see is not a node from the inside either. The two e2e pins of the
same kind are a Handshake request (not this lane's file).
**Probe** (`probe.py` against `proj/`, a `sub`/`top`/`cls` trio; "before"
is a debug build of master 41a9091 from `git archive`, "after" this lane's
debug build):
```
position before after
instance name u_sub null sub (MODULE, data null)
inside module body (logic r) null sub
inside always_ff null sub
function decl inv null inv (FUNCTION, data function)
call inv(r) null inv
inside poke body null poke (data task)
on endfunction keyword null inv
task decl poke null poke
module decl sub sub sub (identical)
call hello() in leaf_c::go null hello (METHOD, base_c's)
incoming(inv) = [poke @9] outgoing(poke) = [inv @9]
incoming(hello) = [go (METHOD) @9]
type: class name mid_c mid_c mid_c
type: inside leaf_c method body null leaf_c
type: module body null null
```
**Gates.** `cargo fmt --all --check` clean;
`tools/guard.sh -- cargo clippy --workspace --all-targets -- -D warnings`
clean; `tools/guard.sh -t 1800 -- cargo test -p lucisv_server`: unit/server
binary **1753 passed, 36 ignored** (1757 tests before → 1789 after, +32);
`tests/e2e.rs` **97 passed, 2 failed, 2 ignored** — the two failures are
exactly the Handshake request above; `tests/grammar.rs` green. No change to
`vlog_semantic` or `vlog_refactor` behaviour, so their suites were not
re-run. No new dependencies. No commits.
**Files.** New: `crates/lucisv_server/src/hierarchy/tf.rs`,
`crates/lucisv_server/src/hierarchy/calls.rs`,
`crates/lucisv_server/src/server/tests/hierarchy_everywhere.rs`, this README.
Edited: `crates/lucisv_server/src/hierarchy.rs` (prepare chain, routing on
`data`, test updates), `crates/lucisv_server/src/type_hierarchy.rs`
(enclosing-class fallback, `super`, test updates),
`crates/lucisv_server/src/server/tests/mod.rs` (one `mod` line),
`docs/features/hierarchy/README.md` and
`docs/features/type-hierarchy/README.md` (pointer notes). Not touched:
`dispatch.rs`, `nav.rs`, `main.rs`, `vlog_*`, `editors/`, `TODO.md`.
- **2026-10-14 (dev) — rework after QA.** QA's findings 1–5 and 7.
1. **Result variable (MEDIUM).** `is_call` now treats a function's own name
inside a body it owns, with no `(` after it, as the result variable —
read or written — and drops the separate assignment-operator check it
subsumes. `f(…)` there stays recursion; a bare `f` from another body
stays a call. The unit test that pinned `+ f` as a call is flipped;
new: `the_result_variable_read_in_its_own_body_is_not_a_call` (QA's
`clog2`), `a_bare_function_name_in_another_body_is_a_call`, and the
LSP-level `the_classic_clog2_is_not_its_own_caller`.
2. **Per-callee re-parse (MEDIUM, perf).** `tf::Loaded` holds one
analysis per path for the life of one request; `outgoingCalls` and
prepare's multi-declaration answer build every cross-file item through
it, and `live_symbol` asks identity of the symbol at the recorded
position first. QA's shape (one closed 430 KB package of 300 functions,
a caller calling all 300, `scratchpad/lsp/gen_perf.py` + `s_perf.py`),
release builds, three runs each: **before 3 043 / 3 018 / 3 032 ms,
after 21 / 18 / 17 ms**.
3. **Stale item (LOW-MEDIUM).** The "first of that name" fallback is gone:
by name alone only the one candidate in the item's `detail` container
answers, asked even of a lone candidate (a renamed-away `mb` leaves
`ma`'s `log2` as the only one, and it is still the wrong function).
New: `a_stale_item_never_answers_for_a_same_named_function_elsewhere`
(QA's `ma`/`mb` reproduction: after the move it answers `mb`'s callers,
after the rename nothing).
4. **Ambiguity fallbacks (coverage).** Both checks now sit in one
predicate, `declined`, called once before any file is read (same
answers: either clause still returns the declaring file alone). Its
clauses are each killed by a unit test:
`an_index_that_marks_the_uses_ambiguous_declines` (no buffer open, an
indexed `p::f()` with `p` declared twice),
`an_open_buffer_holding_an_ambiguous_use_declines` (index clean, a
buffer outside the indexed folder), plus
`an_ambiguous_use_in_the_declaring_file_itself_does_not_decline`.
**Not killable end to end, and why:** with a consistent workspace the
branch cannot be reached through `incomingCalls` — see the new
Assumption "The two ambiguity fallbacks are defensive". Removing the
single `if declined(..)` line in `other_files` therefore still survives
the suite; the predicate it calls does not.
5. **README.** Limits: macro uses and calls inside macro bodies. The
prepare table: a class inside a module answers the module.
**Gates.** `cargo fmt --all --check` clean; clippy `-D warnings` clean;
`tools/guard.sh -t 1800 -- cargo test -p lucisv_server`: guard exit 0;
server binary **1760 passed, 0 failed, 36 ignored** (1753 before the
rework, +7: five in `hierarchy/calls.rs`, two in
`server/tests/hierarchy_everywhere.rs`); `tests/e2e.rs` 99 passed, 2
ignored; `tests/grammar.rs` 3 passed.
## QA log
### 2026-10-14 — QA agent (Opus)
**Verdict: PASS with findings.** No corruption, panic or regression found; the
M11 module answers are byte-identical and no other client-visible feature moved.
Two medium findings (a false self-recursion for the classic Verilog result-variable
idiom, and per-callee re-parsing in `outgoingCalls`) are worth fixing before
release but block nothing else.
**Gates** (in this worktree):
- `cargo fmt --all --check`: clean.
- `tools/guard.sh -- cargo clippy --workspace --all-targets -- -D warnings`:
clean, guard exit 0.
- `tools/guard.sh -t 1800 -- cargo test -p lucisv_server`: guard exit 0.
Unit/server binary **1753 passed, 0 failed, 36 ignored**; `tests/e2e.rs`
**99 passed, 0 failed, 2 ignored** (the lead's two flipped assertions included);
`tests/grammar.rs` 3 passed. No host stall.
**Mutation check** (a scratch copy of the tree, `cargo test -p lucisv_server
--bin lucisv-server hierarch`, 144 tests in the filter). Killed: return-assignment
check removed (4 failures), instance-name path removed (2), `data.offset` ignored
in `tf::target` (1), end-label exclusion removed (3), `super` → base removed (1),
the caret rule (`offset - 1`) removed (1), the overlay acceptance in the declaring
file removed (1). **Survived: both ambiguity fallbacks** (finding 4).
**Byte-identity vs master 41a9091.** Built 41a9091 in a scratch `git worktree`
(removed afterwards). Ran `prepareCallHierarchy` at **every character offset** of
three projects (3 137 positions: the dev's `sub`/`top`/`cls` trio; an attack
project with packages, classes, DPI, generate and macros; and a module-hierarchy
project with interfaces, a program, multi-instance statements, generate `for`/`if`,
parameter overrides, an undeclared module and a `bind`). Wherever the old server
answered (124 positions), the new answer is identical, byte for byte. The
`incomingCalls`/`outgoingCalls` answers on all 15 distinct module items are also
identical. The old server answered 124 positions and the new one answers 2 832.
**Other features unchanged.** On two projects, compared `documentSymbol` per file
plus `definition`, `references` and `hover` at every identifier (1 340 queries)
between the old and new binaries: **0 differences**.
**Attacks over the wire** (`probe.py`, debug build unless noted). Each was as the
README describes, unless it is listed under findings:
- Ambiguity. A module two files declare gives both items, and each has the
instantiating module as its caller. A package two files declare (`pz` in
`z1.sv`/`z2.sv`): a call prepares both items, as `definition` answers 2; incoming
is empty for both (the declaring-file fallback).
- A function and a module with the same name (`module g` plus `function g` in
`host`). On the instantiation's module name and on its instance name, the answer
is module `g` (MODULE, no `data`). On the call `g(1)` and on the declaration, it
is function `g` (FUNCTION, `detail` `host`). A module that nothing declares, named
like an in-scope function (`nope u1 ();`), answers the enclosing module, never
the function.
- Shadowing. In task `sh`, the local `int g`, written or read, prepares `sh`, never
the function `g`.
- `extern` prototype, out-of-body `c::ext` name, its end label: all prepare the
prototype, and outgoing lists the callees in the out-of-body body (`hook`,
`helper`).
- `push_back`, `.size()`, `randomize()`, `this.randomize() with {…}`: the
enclosing method, with no crash and no callee listed.
- DPI imports (`import "DPI-C" function int c_add…`, a `context task`): FUNCTION
or TASK items, `detail` none, incoming the module that calls them, outgoing
empty. That is a sensible answer.
- `$display` is the enclosing module. A call in a parameter default
(`#(parameter int P = cf(3))`), a `localparam`, a continuous `assign`, and an
`assign` in a generate `for` are all credited to the module. A call at file scope
is dropped.
- Caller attribution. A call in `initial`, `final`, an `always_comb` named block or
a `fork` named block is credited to the enclosing module, method or task. A call
in a package `localparam` is credited to the PACKAGE item, and one in a class
property initializer to the CLASS item. Qualified `pk::kf` is the same function.
- Stale and foreign items (finding 3 covers the one gap). These all answer empty
or correct, never a panic or a wrong file: `offset` 99 999 999, a nonexistent
name, `kind` `class`/`package`/`task` on a function, selection range line 99 999
or character 4e9, `untitled:` / `/etc/hosts` / a directory / a missing file as
URI, `data` missing / null / a string, extra fields in `data`.
- Large-file mode: in a 5 MB buffer, call prepare, type prepare and the module name
all answer `null`, and a package function's incoming skips it.
- UTF-16: ranges after `✓` comments are correct (character 18 where the UTF-16
count is 18).
- Type hierarchy: a method body and an out-of-body body give the class; a class
inside a module gives the class; a module body and a package body give `null`.
**Timing.** Release build, 200 closed files each calling `big_pkg::pf` 31 times
from a module and 10 functions, with only `pkg.sv` and `m000.sv` open:
- prepare: 2 ms;
- `incomingCalls`: 76 / 65 / 55 ms over three runs, 2 200 callers and 6 200 ranges.
This equals `references` (6 200 locations, 23 ms).
- Server RSS: 13 MB, then 69 MB after the first incoming, then flat.
- Debug build: incoming 325 / 312 / 302 ms, references 89 ms, 74 MB.
The README's "each referencing closed file is parsed once" holds for incoming. It
does not hold for outgoing (finding 2).
**Code review.** Production lines (non-blank, non-comment, before `mod tests`):
`hierarchy.rs` 212, `hierarchy/tf.rs` 216, `hierarchy/calls.rs` 246,
`type_hierarchy.rs` 189. All functions are under 50 lines. Production code has no
`unwrap`/`expect`/`panic`, no new indexing (the one slice in `type_hierarchy.rs`
predates the lane), and no byte slicing of text (`Positions::offset` clamps). The
README test counts (24 / 3 / 4) match the code.
**Findings**
1. **Medium: a Verilog result-variable read is counted as a recursive call.**
`crates/lucisv_server/src/hierarchy/calls.rs:208-227` (`is_call`). The unit
test `calls.rs:337-354` pins `+ f` (a bare read) as a call. Reproduction:
```verilog
module lg (output integer o);
function integer clog2(input integer v);
begin
clog2 = 0;
while (v > 1) begin
clog2 = clog2 + 1;
v = v >> 1;
end
end
endfunction
initial o = clog2(16);
endmodule
```
`outgoingCalls(clog2)` = `[clog2 @6]`, and `incomingCalls(clog2)` lists `clog2`
as its own caller at line 6. That is a false recursion on one of the most common
Verilog-2001 idioms. Inside a function's own body, its name without a following
`(` is the result variable, not a call. That is a token-level rule of the same
kind as the existing `assigned` check, and it applies to functions only.
2. **Medium (performance): `outgoingCalls` parses a closed callee file once per
distinct callee.** `calls.rs:272` calls `tf::def_item`, which calls `tf.rs:243`
`load_path`, which calls `Document::new` for every callee. Reproduction: a
236 KB closed package with 300 functions, and a caller function `all` that calls
all 300. In the release build, `outgoingCalls(all)` takes **3 503 ms**, and
34 ms once the package is open. The cost is about 12 ms per callee for this file
size. A per-request cache of loaded analyses keyed by path would make it one
parse per file, as incoming already is.
3. **Low-Medium: after an edit, a stale item silently resolves to a different
function with the same name.** `crates/lucisv_server/src/hierarchy/tf.rs:293-295`
(the `candidates.first()` fallback). Reproduction: `module ma` and `module mb`,
each declaring `log2`. Prepare `mb`'s `log2`, then `didChange` to add 3 comment
lines at the top. `incomingCalls` with the old item answers **`ma`'s** caller
(line 9). After renaming `mb`'s function to `lg`, the old item also answers
`ma`'s callers. The README documents this fallback (Assumptions, "the module
rule"), but its own Goal says two functions of one name are ordinary. For
modules the fallback is rarely wrong; for functions it often is. Suggestion:
fall back to the first candidate only when it is the only one, or break the tie
on the item's `detail` (container name).
4. **Low (coverage): the two ambiguity fallbacks are untested.**
`calls.rs:79-81` (`references_are_ambiguous`) and `calls.rs:86-88`
(`names_it_ambiguously`). Each removed alone, the 144 hierarchy tests stay green.
The README claims "the same ambiguity contract" as references. A test with two
files declaring one package, and the user file closed and then open, would pin
it.
5. **Info: a cursor on a macro use gives the enclosing module, and a call inside a
macro body is not listed.** For `` `CALL_IT(1) `` expanding to `cf(1)`,
incoming(`cf`) omits that line. This matches references, since there is no
macro expansion, but it is not in the README's Limits.
6. **Info: an ambiguous wildcard import resolves to the first package.** With
`import pa::*; import pb::*;` and both declaring `f`, `f(1)` prepares `pa::f`
and is listed in its incoming. This is the semantic layer, and `definition` and
`references` give the same answer. It is not this lane's.
7. **Info: the doc row "a class body outside its methods → null" does not apply to
a class declared inside a module.** There the enclosing module answers. This is
consistent with the "innermost enclosing module" rule; the table row could say
"a file-level class".
**Fixes made by QA:** ticked the `tests/e2e.rs` Status item, since the lead
flipped both assertions and the suite is green. No code changed.
## Review
**2026-10-14 — lead.** Accepted after one rework. The user's report (Show
Call Hierarchy empty in VS Code) was a prepare that answered only on a
module name; it now answers from any position inside a module, function or
task, and functions/tasks are call-hierarchy nodes of their own. QA (Opus)
confirmed the old module answers byte-identical at 3 137 positions and no
change in outline/definition/references/hover at 1 340 queries; its two
mediums (result-variable reads counted as recursion; outgoing re-parsing a
closed file per callee, 3.0 s → 18 ms) and the stale-item fallback are
fixed with tests. The e2e handshake is granted: two assertions that pinned
the old `null` now assert the new answers. The one surviving mutant (the
`declined` call in `other_files`) guards a branch the index makes
unreachable today; kept, and recorded as an Assumption. Merged onto master
with the lane-B references view; gates re-run on the merged tree.
+193
View File
@@ -0,0 +1,193 @@
# decomposition-state — TODO §55: `lucisv_server/src/state/mod.rs`
## Goal
Split the one file every workspace-state lane collides in —
`crates/lucisv_server/src/state/mod.rs`, 5 941 lines: 986 production
(non-blank, non-comment) in one 1 600-line `impl Workspace`, plus a
3 944-line inline `mod tests` — into sibling modules a reader can describe
in one sentence each, with the tests in `state/tests/`, one file per topic,
mirroring `server/tests/`. A **pure move**: no behaviour change, no renamed
item, no function body touched, every path another module imports
preserved by re-exports from `state/mod.rs`, the per-suite test counts
identical to the baseline. `discover.rs` and `scan.rs`, already split out,
are untouched.
## Assumptions
- `lucisv_server` is a binary crate; "public path" means what other
modules of the crate import. Every one of them still resolves at
`crate::state::…`: `Workspace`, `Document`, `FileView`,
`WORKSPACE_SYMBOL_LIMIT`, `first_token_reaching`, `first_token_from`,
`mixed_buffer` (`#[cfg(test)]`), `IndexEvent`, `Scan`,
`discover::HEAD_WALK_MAX`. `Workspace`'s methods are methods whatever
file their `impl` block is in, so no call site in the crate moved.
- Sibling files are private modules; `Workspace`'s fields stay private
(child modules see their ancestor's private items, as `discover.rs`
already relied on), and so does `StoreOpen`. The only widenings are the
private items a *sibling* now calls, all `pub(super)` and all taken from
the compiler rather than guessed: `scope::{walks_the_workspace,
raised_dirs, cache_dir}`, `buffers::{current_text, analysis_of}`,
`views::forget_view`, `rescan::open_store`, and the two view-cache
bounds `views::{MAX_VIEWS, MAX_VIEW_BYTES}` that one test file reads.
- The tests are one `#[cfg(test)] mod tests;` in `state/mod.rs` →
`state/tests/mod.rs`, whose sibling files are the sections the one big
test module had, under the banner names it gave them. A helper more
than one section used moved to `tests/mod.rs`; a helper one section
used stayed with it. Each section's banner became the `//!` doc of its
file, verbatim where the banner had a paragraph (the view cache,
TODO §63.2). The test-local `struct Scan` (a scan's parsed/cached/
analyzed census) shadows `state::Scan` inside `tests` exactly as it did
inside the old inline module; the three files that drive a `state::Scan`
by hand never name the type.
- Moving the tests out of the inline module de-indents them by four
spaces; `cargo fmt` then re-joined a dozen statements that fit in one
line at the new indent. Whitespace only — every test name and body is
the old one, and the 121 names are checked against the baseline log.
- "Production lines" below are non-blank, non-comment lines outside
`mod tests`, the CLAUDE.md metric.
- The `lucisv` CLI does not depend on `lucisv_server`, so the formatter's
output cannot move: the corpus/opentitan byte-identity sweep is vacuous
for this lane and was not run. The gates are the test counts, the fmt
and clippy runs, and the line-multiset check in the work log.
## Handshakes
- **Consumes** (unchanged): everything `state/mod.rs` imported before —
`vlog_parser`, `vlog_semantic`, `crate::{candidates, convert, includes,
index_cache, module_select, rename_trace, scan_order, scan_trace,
settings, uri}` — now imported by the file that uses each.
- **Promises** (unchanged): the public surface listed under Assumptions,
re-exported from `state/mod.rs`.
- **Request to the lead — CLAUDE.md measurement line.** TODO §55's item
reads "CLAUDE.md's measurement line refreshed"; CLAUDE.md is outside
this lane's ownership. The 2026-09-23 line says
`lucisv_server/src/state/mod.rs` at 985 (already over; TODO §55). After
this lane: `state/mod.rs` 63, `discover.rs` 412, `rescan.rs` 411,
`sources.rs` 170, `scan.rs` 135, `document.rs` 122, `scope.rs` 99,
`buffers.rs` 71, `views.rs` 54, `incremental.rs` 54 — nothing in
`state/` over 600.
- **Note, no edit asked**: `server/tests/folders.rs:128` names
`state::tests::a_widen_that_subsumes_the_old_scope_reads_only_the_files_it_adds`
in a plain comment; that test is now
`state::tests::widen::a_widen_that_subsumes_…`. The name still finds it
by grep; the path prefix is one segment stale.
## Status / TODO
- [x] Baseline counts pinned (`cargo test -p lucisv_server` under guard).
- [x] Production split: `document`, `buffers`, `views`, `scope`, `rescan`,
`incremental`, `sources` beside `discover` and `scan`; `mod.rs` keeps
the struct, `StoreOpen`, the table readers and the re-exports.
- [x] Tests out to `state/tests/` (14 topic files + harness), every name
and body kept.
- [x] `cargo fmt -p lucisv_server`; `cargo fmt --all --check` clean.
- [x] `cargo clippy --workspace --all-targets -- -D warnings` clean.
- [x] `cargo test -p lucisv_server` after: counts equal the baseline.
- [x] `cargo test --workspace --all-targets` once at the end.
- [x] TODO §55 ticked.
- [ ] CLAUDE.md measurement line — the lead's (Handshakes).
## Work log
### 2026-10-14 — the move (refactor dev, Fable)
**Baseline** (`tools/guard.sh -t 1800 -- cargo test -p lucisv_server`,
guard exit 0): unittests 1 721 passed / 36 ignored; `tests/e2e.rs` 99 / 2;
`tests/grammar.rs` 3 / 0. 121 of the unit tests are `state::tests::*`.
**Module map** — old `state/mod.rs` line ranges → new file, one sentence
each (production lines after the move in brackets):
| new file | old lines | holds |
|---|---|---|
| `mod.rs` [63] | 1–44, 317–388, 475–503 | `Workspace` itself, `StoreOpen`, `WORKSPACE_SYMBOL_LIMIT`, the readers of its tables (`index`, `known_facts`, `candidates`, `includes`), the module list and the re-exports. |
| `document.rs` [122] | 76–291 | One open buffer analyzed once from its text — `Document` and everything derived from it — and the two binary token searches (`first_token_reaching`, `first_token_from`, `mixed_buffer`). |
| `buffers.rs` [71] | 675–751, 1985–1994, 1502–1515, 1490–1500 | The open buffers: `document`, `document_for_path`, `open_documents`, `set_document`, `is_large`, `has_large_documents`, `close_document`, `open_uris`, and which text speaks for a path (`text_of`, `current_text`, `analysis_of`). |
| `views.rs` [54] | 46–74, 1913–1983, 299–315 | The closed-file view cache: `FileView`, its two bounds, `file_view`, `held_views`, `cached_view`, `forget_view`, `trim_views`. |
| `scope.rs` [99] | 445–473, 505–595, 1557–1571, 597–673 | Roots, client settings and the scope ladder: `adopt_roots`, `change_roots`, `has_roots`, `roots`, `scope_dirs`, `folder_scoped`, `walks_the_workspace`, `raised`, `raised_dirs`, `client_settings`, `set_client_settings`, `cache_dir`, `set_storage_path`. |
| `rescan.rs` [411] | 814–891, 947–1082, 893–945, 1084–1173, 1517–1555, 1175–1380, 391–443, 753–812, 293–297 | Driving a scan, whole or widen, from work list to landed tables: `begin_scan`, `begin_widen`, `discover_the_rest`, `open_store`, `scan_step`, `open_next`/`open_first`, `publish_scan`, `finish_scan`/`finish_whole_scan`/`landed`/`take_scan_trace`, `finish_widen`; then the test-only one-shot forms (`open_roots*`, `open_whole_workspace*`, `rebuild_index*`, `widen_index*`) and `held_bytes`. |
| `incremental.rs` [54] | 1382–1488 | One saved file re-indexed in place: `update_one`, `update_one_checked`. |
| `sources.rs` [170] | 1573–1911 | The file sets handed to refactorings: `sources`, `module_sources`, `module_sources_reaching`, `rename_sources_traced`, `fan_out_of`, `want_*`, `include_sources`. |
Reading order inside `rescan.rs` is the protocol's: begin → step →
publish → finish, with the one-shot wrappers after a separator comment
(the one piece of new comment text in production code). Within every
other file the original order is kept.
**Tests** — old `mod tests` (1 997–5 941) → `state/tests/`:
| file | tests | section it was |
|---|---|---|
| `mod.rs` | — | harness: `uri`, `Tree`, and the 17 helpers more than one section used (`open`, `filler`, `tangled`, `wide`, `excluding`, `own_folder_only`, `using_filelist`, `capping`, `fat_package`, `caching`, `indexed`, `everything`, `seen`, `Scan`/`scan`/`file_name`, `walk_sources`) |
| `document.rs` | 8 | the token searches and `Document` tests at the top; TODO §63.2 QA (the trace's arithmetic) from the bottom |
| `large_file.rs` | 5 | the large-file fast path |
| `views.rs` | 7 | the closed-file view cache |
| `interleave.rs` | 6 | an interleaved scan against the one-shot scan it must equal |
| `folders.rs` | 9 | `didChangeWorkspaceFolders` (the second half of the interleave section) |
| `settings.rs` | 9 | gitignore/config/pushed excludes, which settings ask for a rescan, source extensions |
| `size_cap.rs` | 7 | `lucisv.index.maxFileSize` |
| `filelist.rs` | 11 | rung 1 and its `+incdir+`s |
| `folder_scope.rs` | 15 | the folder scope + inherited obligations (index-scope review) |
| `lazy_read.rs` | 6 | the lazy read and the folder-first order (§P4b3) |
| `incremental.rs` | 6 | the incremental path |
| `persistence.rs` | 15 | the persistent index cache |
| `open_buffers.rs` | 8 | an open buffer's own analysis + the QA attacks on it; `an_open_buffer_overrides_disk_in_the_index` from the top section |
| `widen.rs` | 9 | the incremental scope widen |
121 tests, the same 121 names as the baseline log (diffed).
**How the move was made.** A script sliced the original by line range
(production) and by brace-balanced item (tests, each with its doc comment
and attributes) into the scratchpad, asserting that every one of the
5 941 original lines landed exactly once, was blank, or was one of the
five structural lines (`impl Workspace {`, its `}`, the `mod tests`
wrapper) or a section banner; the new files were then copied into
`state/` and `mod.rs` rewritten from the assembled text (diffed: equal).
Imports per file and the eight `pub(super)` widenings were added by hand,
taken from the compiler. A second script checks the multiset of
production lines of the old file against the union of the new ones: the
only differences are `use` continuation lines and the separator comment
above the one-shot forms.
**Longest functions** (raw lines, before = after, since no body moved):
`begin_widen` 106 (85 production — the one over 80, left as it is; a pure
move does not split functions), `scan_step` 70, `begin_scan` 67,
`update_one` 58, `finish_whole_scan` 55, `rename_sources_traced` 52,
`finish_widen` 48, `fan_out_of` 39, `Document::new` 35, `publish_scan`
29.
**Gates** (every suite through `tools/guard.sh`, logs kept in the
session scratchpad):
- `cargo fmt -p lucisv_server`: reordered the `use` blocks in five new
files and re-joined 12 statements in the de-indented tests; then
`cargo fmt --all --check` exit 0.
- `tools/guard.sh -t 1800 -- cargo clippy --workspace --all-targets --
-D warnings`: guard exit 0, no warnings.
- `tools/guard.sh -t 1800 -- cargo test -p lucisv_server` after the
move: 1 721 passed / 36 ignored, 99 / 2, 3 / 0 — equal to the baseline,
guard exit 0. Two earlier runs each failed **one** `large::tests`
wall-clock budget test (`…locate_their_hits_in_linear_time`, 173 ms
against a 150 ms budget; then `…colours_in_linear_time`) with the host
at load average 12–21 (`mediaanalysisd`, `XProtectRemediator`,
`syspolicyd` near 50 % CPU each, a foreign `rustc`) — the host
condition the brief names; `large.rs` is not touched by this lane, both
tests pass alone, and the third full run passed clean. Reported, not
worked around.
- `tools/guard.sh -t 1800 -- cargo test --workspace --all-targets`: 80
suites, every one `ok`, 5 078 passed / 51 ignored, guard exit 0.
## QA log
## Review
**2026-10-14 — lead.** Accepted as a pure move. Independent check: the
multiset of code lines in the old `state/mod.rs` against the union of the
new `state/` files (excluding `discover.rs`/`scan.rs`) differs only in `use`
lines, the `impl Workspace {` headers, the forced `pub(super)` widenings
listed in the work log, and rustfmt re-wrapping the same tokens in the
de-indented tests — no code line lost or added. The CLAUDE.md measurement
line is refreshed (2026-10-14 paragraph); the stale test path in
`server/tests/folders.rs:128` is corrected. Merged onto master after the
review lows; gates re-run on the merged tree.
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff. Show more