Compare commits

...
14 Commits
Author SHA1 Message Date
lucioandClaude Fable 5.1 1da0a303cc Release 0.45.0 — type spans, package re-exports, hierarchical tails
ci / checks (push) Successful in 1m14s
ci / corpus (push) Successful in 33s
release / build-and-publish (push) Successful in 6m25s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 13:35:57 -05:00
lucioandClaude Fable 5.1 f476c31483 Cross-file instance-member tail: a module's hierarchical surface, read only behind an instance head; rename edits the tail
TODO §49 (docs/features/hierarchical-tail). Closes topo §2.9-23 and
comment-slots finding 2. The first dev was cut off by an outage with the
library half complete; a second finished the tests, README and gates.

`Surface { Connection, Hierarchical }` on `Resolution::ExternalCandidate`
and `MemberSite::Unit`, set by `resolve.rs::head_surface` for an instance
head. `workspace/hierarchy.rs`: `surface_of` (the export rule, re-ruled)
and the two surface-taking reads; the index keeps two disjoint tables —
`members` (connection: ports, parameters; byte-identical to before for
every existing reader) and `hier_members` (nets, variables, instances) —
and a hierarchical read consults the connection table first, so a port
has one record. `FACTS_FORMAT` 18 → 19. `assign w = u_x.sig;` in another
file now resolves to `sub`'s `wire sig`; rename edits both files (nested
`u_a.u_b.sig` included); the §2.9-20 warning is retired for a resolved
tail; a generate-scoped net is still refused honestly. Completion after
`u_x.` in an expression lists the hierarchical surface; a connection
list's does not.

Census: single-file numbers unmoved; 12 939 connection + 5 239
hierarchical-only members; 335 corpus references newly resolve, 514 over
opentitan `hw/` (20 sampled by QA, all genuine). 0 of 860 corpus files
differ. Also: §50/§51 planned, §55 (state.rs size) filed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 13:35:57 -05:00
lucioandClaude Fable 5.1 9ef1058059 Package re-exports as real references: bound halves, RX facts, the member walk through re-exports
ci / checks (push) Successful in 1m17s
ci / corpus (push) Successful in 1m52s
TODO §48 (docs/features/package-reexports). Closes topo §2.9-16 and
dpi-export's request (a).

`bind_export_path` records `export pkg::item` as a `Target::Package` use
and a `Target::UnitMember` use, with no scope import (a re-export brings
nothing into the exporting scope, IEEE 1800 §26.6). `FileFacts` gains the
`RX` group (`FACTS_FORMAT` 17 → 18): per package its re-export edges
(package, source, item|*), with `export *::*` expanded into the package's
own imports at record time. `workspace/reexport.rs`: the member lookup
and listing follow re-exports transitively with a visited set, layered
over `own_chain`/`own_members` so the walk cannot recurse into itself;
`Affected::exporters` keeps one-file updates exact and `fingerprint()`
shows the edges. Definition, hover, completion after `pkg::`, references
and rename all read the one edge. Census 103 870 → 103 875 references
(the corpus's two package export lines), 0 unplaced; 0 of 860 corpus
files differ. opentitan: `spi_device_pkg::SramDepth`, reached only
through a re-export, resolves.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 10:41:54 -05:00
lucioandClaude Fable 5.1 4d59e80568 Type-name spans on the AST; vlog_semantic/src/scan.rs retired
ci / checks (push) Successful in 1m3s
ci / corpus (push) Successful in 33s
TODO §47 (docs/features/type-name-spans). Closes topo §2.9-2.

`DataType` carries `name_start` (a `u32` in its existing padding, so
`Expr` stays at its 96-byte pin) and derives `name_span()` and
`segments()` — the `::`/`.` split from the span's own text, with a
leading escaped identifier read to its terminator first. Five parser
construction sites set it; an implicit type gets the empty range at the
position its name would have had. `StmtKind::Disable { name, name_span }`.
The binder walks `ty.segments()` and verifies every segment's range
against the source before recording it (`exact_or_empty`); a segment that
does not read back is recorded with the empty range, never dropped, so
the census's `unplaced` counter is the alarm a join regression would
move (review rework of QA's MEDIUM). `scan.rs` deleted; `bind_data_type`
lost its `window` and ten call sites their window arithmetic.

Census unchanged in every field (860 files, 27 486 symbols, 103 870
references, 1 197 unresolved, 0 unplaced); 0 of 860 corpus files differ;
200/200 opentitan definition/hover/typeDefinition answers identical.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 09:24:19 -05:00
lucioandClaude Fable 5.1 859742ac84 TODO: §48 package re-exports and §49 cross-file instance-member tail planned
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 08:58:30 -05:00
lucioandClaude Fable 5.1 66f38987ac Release 0.44.0 — opening a file no longer stalls the editor
ci / checks (push) Successful in 1m1s
ci / corpus (push) Successful in 32s
release / build-and-publish (push) Successful in 6m22s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 08:15:37 -05:00
lucioandClaude Fable 5.1 8145a67be6 The didOpen delay: undriven-net asks the workspace census last, not once per declaration
TODO §46 (docs/features/didopen-cost). Closes take-3 finding §8.4 (§44b).

Measured first: on opentitan the open of a 42 192-line file cost
1 745 ms, of which the lint pass was 1 654 ms and `undriven-net` alone
1 608 ms — the rule asked `WorkspaceIndex::files_mentioning` (a walk over
all 3 976 indexed files) once per declaration, ahead of the local guards
that silence almost all of them. Six lines reordered so the oracle is
asked last, as `unused-signal` always did: same findings, same order
(pinned by a counting-oracle unit test that fails on a revert, and shown
byte-identical against 0.43.0 over a crafted workspace and four opentitan
IPs). didOpen → next request: 1 742 → 117 ms on the largest file,
51–95 → 5–8 ms on typical IPs, the same on every keystroke flush. No
debounce added; three wire-level pins with a debug-build bound.

Docs: take-3 §8.4 annotated, docs/perf/README.md entry.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 08:15:37 -05:00
lucioandClaude Fable 5.1 f7956060b3 Small items, round 4: the editor's unknown rule name said once, a warning channel for the walk, inline aggregate override arguments, comment slots inside delay lists
ci / checks (push) Successful in 1m1s
ci / corpus (push) Successful in 32s
TODO §45 (docs/features/small-items-4). Closes topo §2.9-17, 29, 30 and
adds the delay-list bar to §2.9-22.

45.1 `settings::rules` records every dropped `lucisv.lint.select`/`ignore`
name as `lucisv.lint.<setting>: unknown rule: <name>`; `apply_settings`
logs what the previous settings value did not already say — once per
(setting, name), re-armed by a changed list.
45.2 `walk::collect_files` takes a `&mut dyn FnMut(Warning)` sink: an
unreadable directory, an unreadable `.gitignore` and a dangling source
link are warned about and the walk continues; the CLI prints
`warning: <path>: <message>` on stderr before the report with the exit
code unchanged, the server logs once per scan through `report_scope`.
45.3 `parse_expr_or_type` accepts a `struct`/`union`/`enum` head as a
type argument, so `m #(.T(struct packed { logic a; })) u ();` parses and
`instantiation_plan` emits a one-line `parameter type` aggregate default.
45.4 Comment slots for `#(1:2:3)` and gate delay lists
(`MinTypMaxComments`, `DelayValue`, `ContAssign`/`GateInstantiation`/
`GateInstance` slots); `EXPECTED_RTL_GAPS` 374 → 419 at zero failures.
Review rework (QA's MEDIUM): a line comment after a gate instance's `,`
now ends the line, the next instance one level in.

Byte-identity vs 0.43.0: 0 of 820 corpus files and 0 opentitan outcomes
differ.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 07:12:54 -05:00
lucioandClaude Fable 5.1 f302b471a7 TODO: loop 2 order from the owner's twelve rulings; §45 and §46 planned; manual acceptance checklist
ci / checks (push) Successful in 56s
ci / corpus (push) Successful in 30s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 05:50:45 -05:00
lucioandClaude Fable 5.1 7aedfe2554 docs: performance take 3 on opentitan — 0.43.0 vs take 2 vs 0.39.0
ci / checks (push) Successful in 51s
ci / corpus (push) Successful in 28s
TODO §40 (owner request). Every take-2 row re-measured over the wire and
by CLI sweep, three tries each, no instrumentation added. Headlines: the
lazy codeAction is 11.8× on the cursor-move path (200.7 → 24.0 ms at the
128-file fan-out, 39.2 → 5.2 ms on `aes`), the default-scope didOpen is
1 731 → 1 082 ms cold, completion at 0–1 chars 14.8–19.4 → 2.3–3.2 ms;
nothing else moved since 0.39.0. Per-file outcome diff 0.39.0 → 0.43.0
is exactly the three predicted files. Two findings filed as §44
candidates: the eager codeAction path 1.35–1.40× slower than take 2, and
an in-scope didOpen delaying the next request by 21–51 ms.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 03:24:24 -05:00
lucioandClaude Fable 5.1 73799f3d53 Release 0.43.0 — the repository analysis's three findings
ci / checks (push) Successful in 58s
ci / corpus (push) Successful in 31s
release / build-and-publish (push) Successful in 6m27s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 02:43:10 -05:00
lucioandClaude Fable 5.1 ec9ec42276 Walker cycle policy by directory identity, and comment slots around a net delay's #
TODO §43 (docs/features/walk-cycles). Closes topo §2.9-8 and §2.9-27 and
repository-analysis finding 3; §2.9-30 filed.

43.1 `lucisv_core::walk::Walk` keeps a `visited` set keyed on `(dev, ino)`
(the canonical path off unix): each directory is entered once, a symlink
to one already entered is skipped, one not yet entered is followed once,
a dangling directory link is skipped. A dangling link that names a source
file is still handed on, so the front end's "no such file" error survives
(review ruling on QA's finding). Both front ends share the walk unchanged
in signature; a cyclic workspace indexes and a cyclic tree formats, each
file once.

43.2 `NetDelay::{before_hash, after_hash}`: the gaps around `#` have
slots, printed inline; the `#SKIP` in net_delay_position.cases is live
and the RTL gap fuzzer covers the construct (374 gaps, 0 failures).

Byte-identity vs 0.42.0: 0 of 820 corpus files differ. On opentitan the
only per-file change is §41's dedup reporting a same-directory symlink
alias once.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 02:43:10 -05:00
lucioandClaude Fable 5.1 4b2dad87fe One lint-configuration contract for project and editor: the server picks the editor's selection when set, else the project's, and logs rejected project entries once
TODO §42 (docs/features/lint-config-contract). Closes topo §2.9-28 and
repository-analysis finding 2.

`enabled_rules(settings, project, has_oracle)`: rung 2 is
`lucisv.lint.select` when non-empty else `[lint] select`, rung 5 the same
for `ignore` — the CLI's `pick` applied to the editor — so one buffer
linted two ways is linted the same way (asserted equal over the wire for
three configurations). `lint::project`: `ProjectLint` read from the
`Discovery` result `configured` already computes (no extra read per
pass); an unknown rule name in a project list is dropped and said rather
than silently emptying the selection. `ConfigProblems`/`ProblemLog`:
rejected `[lint.<rule>]` options, unknown names and bad `[lint] waivers`
lines are logged once per (config file, entry) in `lucisv check`'s
wording, re-armed when the config's lint content changes; the buffer
keeps linting with the entry dropped.

Docs applied: README, the linter guide, configuration.md, the analysis,
topo (28 struck; 29 filed for the editor-side unknown-name silence), site
rebuilt.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 01:45:48 -05:00
lucioandClaude Fable 5.1 3b08c0753c Same-target atomic writers: exclusive per-operation temps, mode before bytes, CLI dedup by canonical identity
TODO §41 (docs/features/atomic-write-coordination). Closes topo §2.9-26
and repository-analysis finding 1.

`atomic::write_atomic` names its temp `.{name}.{pid}.{n}.lucisv-tmp` with
a per-process counter and opens it create-new (O_EXCL), retrying a used
name up to 32 times; on unix the temp is created 0600 when a target
exists and takes the target's mode through the open handle before the
bytes are written, so a 0600 file never has a readable moment. The CLI's
`dedup` keys on the canonical path when the file exists, so a symlink
alias reaches one worker; the reported path is the first spelling. Two
processes on one target remain last-writer-wins (rename is atomic, the
formatter idempotent), stated in the module doc. The audit's probe is a
test: 0 write errors in 200 calls.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 00:40:48 -05:00
123 changed files with 10893 additions and 1062 deletions

No files matched your search

+78
View File
@@ -4,6 +4,84 @@ 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.45.0 — 2026-09-05
### Cross-file semantics: type spans, re-exports, hierarchical tails
- **Type names carry spans.** Every `DataType` and `disable` target knows
its range on the AST; the semantic crate's text scanner (`scan.rs`) is
deleted. Definition and hover on a type name land exactly, `pkg::t`
selecting `t`; a segment the source spells differently from the
parser's join is recorded with an empty range rather than guessed.
- **Package re-exports are real references.** `export pkg::item;` and
`export pkg::*;` bind both halves, the index records each package's
re-exports, and definition, hover, completion after `pkg::`, references
and rename follow them transitively. On opentitan a name reached only
through `export spi_device_reg_pkg::SramDepth;` now resolves.
- **Renaming an internal net edits its hierarchical uses in other files.**
A module now has a hierarchical surface (nets, variables, instances)
read only behind an instance head — `assign w = u_x.sig;` in another
file renames with `sig`'s declaration, nested `u_a.u_b.sig` included —
while connection lists still see ports and parameters only. Completion
after `u_x.` in an expression lists the hierarchical members. Over
opentitan's `hw/`, 514 hierarchical references resolve that did not
before; a rename that now reaches one more file costs one more file's
read.
- The index facts format is 19; stores written by earlier releases are
rebuilt on first use.
## 0.44.0 — 2026-09-05
### Opening a file no longer stalls the editor
- **`undriven-net` asked the workspace census once per declaration**,
ahead of the local guards that silence almost every one, so a
`didOpen` — and every keystroke flush — of a large file paid a walk
over every indexed file thousands of times. Asked last now, the way
its twin `unused-signal` always did. Opening opentitan's 42 192-line
`pinmux_reg_top.sv` at workspace scope: 1 742 ms → 117 ms; typical
IP files 51–95 ms → 5–8 ms. Same findings in the same order.
- **Walk warnings.** An unreadable directory, an unreadable `.gitignore`
or a dangling source-file symlink no longer fails a run: the CLI
prints `warning: <path>: <message>` on stderr before the report with
the exit code unchanged, and the server logs once per scan.
- **A typo in `lucisv.lint.select` or `ignore`** is logged once
(`lucisv.lint.select: unknown rule: <name>`) instead of silently
emptying the selection.
- **Inline aggregate types as parameter-override arguments**
(`m #(.T(struct packed { logic a; })) u ();`) parse, format and are
emitted by the instantiation skeleton.
- **Comment slots inside delay lists** (`#( /*a*/ 1 : 2 : 3 )`, gate
`#(rise, fall)`), and a line comment after a gate instance's comma
now ends the line.
## 0.43.0 — 2026-09-05
### The repository analysis's three findings
- **Atomic writers cannot collide.** In-place writes use an exclusive,
per-operation temp file (`.{name}.{pid}.{n}.lucisv-tmp`, created
0600 when a target exists and given the target's mode before the bytes
land); the CLI deduplicates its inputs by canonical identity, so a
symlink alias of a file reaches one worker and is reported once. Two
processes on one target remain last-writer-wins, which the formatter's
idempotence makes safe.
- **One lint-configuration contract.** The editor now honours a project's
`[lint] select` and `[lint] ignore` the way the CLI honours its flags:
`lucisv.lint.select` when set, else the project's, key by key, with the
editor-only severity switches and per-rule toggles applied over whichever
stands. A project entry the server cannot use — a rejected `[lint.<rule>]`
option, an unknown rule name, a bad waiver directive — is logged once with
file and line in `lucisv check`'s wording and dropped; the buffer keeps
linting. The CLI's and the server's rule lists are asserted equal over
the wire.
- **Directory walks terminate on symlink cycles.** Each directory is
entered once by identity; a link to a directory already entered is
skipped, one not yet entered is followed once, a dangling directory link
is skipped and a dangling source-file link is still reported. Both the
CLI and the server's index scan.
- A comment before a net delay's `#` (`wire /* c */ #5 w;`) now formats.
## 0.42.0 — 2026-09-05
### External waiver files, and the two vendor shapes the sweep skipped
Generated
+8 -8
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.42.0"
version = "0.45.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.42.0"
version = "0.45.0"
[[package]]
name = "lucisv_server"
version = "0.42.0"
version = "0.45.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.42.0"
version = "0.45.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.42.0"
version = "0.45.0"
dependencies = [
"lucisv_core",
"vlog_formatter",
@@ -265,11 +265,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.42.0"
version = "0.45.0"
[[package]]
name = "vlog_refactor"
version = "0.42.0"
version = "0.45.0"
dependencies = [
"vlog_parser",
"vlog_semantic",
@@ -277,7 +277,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.42.0"
version = "0.45.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -12,7 +12,7 @@ members = [
]
[workspace.package]
version = "0.42.0"
version = "0.45.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+21 -6
View File
@@ -112,6 +112,12 @@ trailing `/` (matches directories only), and `!` negation. **Not** supported:
git's "already-tracked files are never ignored" rule. See
`docs/features/parallel-files/README.md` for the exact subset.
Directory walks enter each directory once by identity, so symlink cycles
terminate. Inputs resolving to one canonical file path are processed once.
Unreadable directories or `.gitignore` files and dangling source links found
during a walk warn on stderr and are skipped without changing the exit code;
a missing explicitly named input is still an error.
## Configuration
Settings live in a `lucisv.toml` (or `.lucisv.toml`) file, ruff-style. For each
@@ -424,14 +430,23 @@ the first workspace folder). External and inline waivers are a union: a
finding either covers is suppressed, and one both cover leaves neither
reported as dead. A missing file or an unparsable directive fails `lucisv
check` with `<file>:<line>: <message>` and exit 2; in an editor the bad line
is dropped and the rest of the file applies — a bad line in a file named by
the editor setting is written once to the lucisv log, one named by
`lucisv.toml` is not (run `lucisv check` to see it). Unused external waivers
is dropped and the rest of the file applies, and the bad line is written once
to the lucisv log whether the file was named by the editor setting or by
`lucisv.toml`. Unused external waivers
are reported under `unused-waiver` at their line of the waiver file, by
`lucisv check` only and only after the whole run.
The server currently selects rules from `lucisv.lint.*` editor settings;
project `[lint] select/ignore` lists affect the CLI only. Project per-rule
options are read by both front ends. Full rules:
Both front ends read the same configuration, and the editor's settings play
the role the CLI's flags play: `lucisv.lint.select` when it is set, else
`[lint] select` from the buffer's `lucisv.toml`, else the default set — and
the same for `ignore`, decided independently. `lucisv.lint.severity.*` and
`lucisv.lint.rules.*` have no project counterpart and apply over whichever
selection stands. Project per-rule options are read by both front ends. A
project entry lucisv cannot use — an unknown rule name in `[lint]
select`/`ignore`, a rejected `[lint.<rule>]` option, an unreadable waiver
file or a directive that does not parse — fails `lucisv check` with
`<file>:<line>: <message>` and exit 2; in an editor it is dropped, written
once to the lucisv log in the same words, and everything lucisv did
understand still lints the buffer. Full rules:
`docs/features/linter-core/README.md`.
## Architecture (the ruff mapping)
+537 -24
View File
@@ -451,13 +451,14 @@ later:
`StmtKind::Error` leaves. Sync tokens, the four guarantees and the
deliberate gaps (no tolerant *lexer*, no recovery inside headers or lists)
in `docs/features/error-recovery/README.md`. `parse_source` unchanged.
- [ ] **Keep the CST lossless.** Current design (trivia in `Meta`) is
- [x] **Keep the CST lossless.** Current design (trivia in `Meta`) is
format-oriented; verify every source byte is reachable from the tree
(tokens + trivia + spans). A `reconstruct(tree) == input` round-trip test
makes losslessness a tested invariant — this is what makes the same tree
serve formatter, linter, and highlighter. If gaps appear, consider a
rowan-style green tree (rust-analyzer / ruff direction) rather than
patching `Meta`.
**Ruled dropped by the owner, 2026-09-05:** the verifier is the invariant — token equivalence and convergence on every output byte-for-byte; the token-level half (`spans.rs`) stays.
- [x] **New crate `vlog_semantic`** (analog of `ruff_python_semantic`):
symbol tables per scope (module/package/function/block/generate), binding
→ references. Serves go-to-definition/hover first, then semantic lint
@@ -1321,8 +1322,9 @@ and three owner items. See
`references`' one `Def` span (`includeDeclaration`) is converted in the
same one-fetch batch as that file's reference sites — filed again
there rather than silently dropped.
- [ ] Manual extension-host acceptance (themes, keyboard-only, zoom,
- [x] Manual extension-host acceptance (themes, keyboard-only, zoom,
screen readers, an old server binary, both VSIX shapes).
**Checklist prepared 2026-09-05** (`docs/manual-acceptance.md`); the owner runs it.
## 11. Testbench-syntax wave (2026-08-29) — syntax_coverage.md findings
@@ -4360,7 +4362,7 @@ pre-existing modified files stay as they are). Every run under
path), `hover`, `inlayHint` (workspace scope and default scope, with
§37.2's ruling restated), `references`, `documentSymbol`,
`workspaceSymbol`, `semanticTokens/full`, diagnostics publish. Driven
over the wire against `target/release/lucisv-server` at 0.42.0 and,
over the wire against `target/release/lucisv-server` at 0.43.0 and,
for the rows that exist there, the 0.39.0 baseline
(`~/.cache/lucisv-baselines/` holds CLI binaries only — build the
0.39.0 server from the tag in a scratch worktree under the scratchpad,
@@ -4368,7 +4370,7 @@ pre-existing modified files stay as they are). Every run under
- **CLI sweeps** over `hw/ip`, `hw/top_earlgrey/ip`, `hw/top_darjeeling/ip`,
`hw/dv`, `hw/vendor`: `format --check` (cold cache and warm), `check`
(all rules on; default rules), wall time and peak RSS (`/usr/bin/time
-l`), 0.42.0 vs 0.39.0 vs 0.41.0; the failure counts per tree and the
-l`), 0.43.0 vs 0.39.0 vs 0.41.0; the failure counts per tree and the
list of files whose outcome changed since 0.39.0 (expected: exactly
jtag_if.sv and SimDTM.sv from §38).
- **Method** as take 2 §9: three tries per row, first try and repeat
@@ -4378,10 +4380,13 @@ pre-existing modified files stay as they are). Every run under
item with a reproduction; anything faster is credited to the section
that did it.
- [ ] server table re-measured, 0.42.0 vs take 2 vs 0.39.0
- [ ] CLI sweeps, three binaries, RSS included
- [ ] `docs/performance_take3.md` + perf README entry
- [ ] opentitan status unchanged after every run
- [x] server table re-measured, 0.43.0 vs take 2 vs 0.39.0 — `performance_take3.md`
§2; 0.39.0 server built from the tag in a scratch worktree, removed after
- [x] CLI sweeps, three binaries, RSS included — take 3 §7, five trees ×
{`format --check` cold/warm, `check`, `check --select error,warning,style`}
- [x] `docs/performance_take3.md` + perf README entry (2026-09-05)
- [x] opentitan status unchanged after every run — only the three pre-existing
modified files, checked after every phase; no guard kill (peak 249 MB of 8 GB)
## 41. Repository-analysis fix 1 (planned 2026-09-04) — same-target atomic writers (topo §2.9-26)
@@ -4421,16 +4426,17 @@ workers; and any two threads in one process writing one path.
uniqueness; the 0600 window (the temp is never readable by others —
assert its mode right after creation in the test's own thread).
- [ ] 41.1 exclusive unique temps, mode before bytes
- [ ] 41.2 dedup by canonical identity, reported path unchanged
- [ ] docs: feature README; topo §2.9-26 struck (lead); analysis finding
- [x] 41.1 exclusive unique temps, mode before bytes
- [x] 41.2 dedup by canonical identity, reported path unchanged
- [x] docs: feature README; topo §2.9-26 struck (lead); analysis finding
1 annotated "fixed by §41" (lead)
- [ ] Gates (guarded): fmt/clippy/workspace tests; corpus unchanged;
- [x] Gates (guarded): fmt/clippy/workspace tests; corpus unchanged;
byte-identity vs 0.42.0
- [ ] QA: the probe re-run under the guard at 4 threads; alias attacks
- [x] QA: the probe re-run under the guard at 4 threads; alias attacks
through the CLI (relative/absolute/`..` spellings + symlink); a
target that is itself a symlink into another directory; RSS of the
100-round probe
100-round probe — PASS, see QA log in the feature README
(2026-09-05)
## 42. Repository-analysis fix 2 (planned 2026-09-04) — one lint-configuration contract for project and editor (topo §2.9-28)
@@ -4477,11 +4483,11 @@ when given, else the project file. The server does the same, key by key:
back to empty restores the project's; the CLI's and the server's rule
lists for the same buffer are asserted **equal** for three configs.
- [ ] 42.1 project selection into the ladder, editor-when-set-else-project
- [ ] 42.2 rejected project options logged with file:line
- [ ] docs + tests above; topo §2.9-28 struck (lead); finding 2 annotated
- [ ] Gates (guarded); e2e green
- [ ] QA: the four-way matrix over the wire; the CLI/server equality on
- [x] 42.1 project selection into the ladder, editor-when-set-else-project
- [x] 42.2 rejected project options logged with file:line
- [x] docs + tests above; topo §2.9-28 struck (lead); finding 2 annotated
- [x] Gates (guarded); e2e green
- [x] QA: the four-way matrix over the wire; the CLI/server equality on
an opentitan IP (read-only) with its real `lucisv.toml` if one
exists, else a scratch one
@@ -4523,12 +4529,14 @@ mechanism and its gap fuzzer), the formatter prints it inline before `#`,
the `#SKIP` in `net_delay_position.cases` goes live, the gap fuzzer covers
the new slot.
- [ ] 43.1 visited-by-identity walker, both front ends, tests
- [ ] 43.2 `NetDelay::before_hash`, the `#SKIP` retired
- [ ] docs; topo §2.9-8 and §2.9-27 struck (lead); finding 3 annotated
- [ ] Gates (guarded): fmt/clippy/workspace tests; corpus unchanged;
- [x] 43.1 visited-by-identity walker, both front ends, tests
- [x] 43.2 `NetDelay::before_hash`, the `#SKIP` retired
- [x] docs; topo §2.9-8 and §2.9-27 struck (lead); finding 3 annotated
— done at review 2026-09-05; §2.9-30 filed (unreadable directory
aborts the walk)
- [x] Gates (guarded): fmt/clippy/workspace tests; corpus unchanged;
byte-identity vs 0.42.0; a cyclic scratch tree through both binaries
- [ ] QA: cycles of depth 1–3 through the CLI and the server (guarded,
- [x] QA: cycles of depth 1–3 through the CLI and the server (guarded,
time-limited); the comment slot attacked with every comment shape
and position; the gap fuzzer re-run
@@ -4538,3 +4546,508 @@ the new slot.
take 3 on opentitan. The audit's own doc edits (README, topo, site) are
committed by the lead as one "docs: repository analysis" commit once that
process is finished, before §41 starts.
## 44. Candidates from performance take 3 (filed 2026-09-05, not planned)
`docs/performance_take3.md` re-measured 0.43.0 against take 2 and 0.39.0.
The lazy code action is worth 11.8× on the cursor-move path and the
default-scope `didOpen` is 1 731 → 1 082 ms cold; nothing else moved
since 0.39.0. Two findings are real work and wait for the owner's call:
- [x] **Eager `codeAction` (a client without `resolveSupport`) is
1.35–1.40× slower than take 2 at every fan-out** — **ruled a
non-hot path by the owner, 2026-09-05**: VS Code, Neovim's client
and Helix all resolve; documented, not bisected. — already so at
0.39.0, so it landed in the §29–§35 window; not bisected. Bisect
over `~/.cache/lucisv-baselines/` (0.35.0–0.39.0 CLI binaries exist;
the server needs building per tag) and fix the regression, or rule
that non-resolving clients are not a hot path (VS Code, Neovim's
built-in client and Helix all resolve).
- [x] **A `didOpen` of a file already in scope delays the next request by
21–51 ms**, scaling with file size (take 2: 2–4 ms). The open, not
the request. Find what the open now does synchronously that it did
not (the §33+ diagnostics pass? the §37 lint run construction?) and
move it off the request path or measure it as the price of the
diagnostics the file gets. — done by §46 (0.44.0), and it was
neither: the lint pass is 75–95 % of the open and the rule
`undriven-net` is 90–97 % of the lint pass, because it asked the
workspace census once per declaration in the buffer before its own
local guards could silence it. Asked last now, as its twin rule
`unused-signal` always has. 51/70/95 → 4.6/7.3/7.8 ms on the three
files of take 3 §8.4; 1 742 → 117 ms on opentitan's 42 192-line
`pinmux_reg_top.sv`. Not a regression — 0.39.0 measures the same.
`docs/features/didopen-cost/README.md`.
- Noted, not actioned: `lucisv check` 6–10 % slower than 0.39.0 on
`hw/ip` (73 rules vs 54; per-rule cost flat), `workspace/symbol`
drifting 6.6 → 7.9 ms over three takes, `rename` 115 → 152 ms with two
more files edited (per-file flat).
## Loop 2 order (owner's rulings, 2026-09-05)
Asked as twelve questions and answered. Ruled out: the eager codeAction
regression (non-hot path), the lossless-CST tree round trip (the verifier
is the invariant). The owner runs the manual acceptance checklist. Everything
else runs, one lane at a time in the main tree, dev Opus 5 → QA Sonnet 5 →
lead, a release every two or three sections:
§45 small items round 4 (topo 29, 30, 17, 22) → §46 the didOpen delay →
0.44.0 → §47 `DataType` spans, retire `scan.rs` (topo 2) → §48 package
re-exports (topo 16) → §49 cross-file instance-member tail in rename
(topo 23) → 0.45.0 → §50 `.*` expansion → §51 non-ANSI → ANSI ports →
0.46.0 → §52 organize imports → §53 extract / inline module → 0.47.0 →
§54 coverage gaps L3/L6/L10 → 0.48.0. Sections after §46 are planned when
reached.
## 45. Small items, round 4 (planned 2026-09-05) — topo §2.9-29, 30, 17, 22
One lane, §36's protocol. Feature README:
`docs/features/small-items-4/README.md`. Ships in 0.44.0 with §46.
### 45.1 The editor's unknown rule name is said once (topo 29)
`lucisv.lint.select`/`ignore` naming a rule the registry does not know is
dropped silently (`named()` skips it); the same typo in `[lint] select` is
now logged once (§42). Log the editor's the same way — through
`server/notification.rs`, once per (setting, name), re-armed when the
setting changes — with the message `lucisv.lint.select: unknown rule: <name>`
(the shape `lucisv.lint.options` already uses for its bad entries). A
`select` emptied by the dropping falls back to the project's list, then the
base set — the §42 ladder unchanged. Tests: unit on the settings decode;
wire-level: one log line across four diagnostics passes, re-armed by a
`didChangeConfiguration` that changes the list.
### 45.2 A warning channel for the walk (topo 30)
`lucisv_core::walk::collect_files` returns `Vec<PathBuf>`; an unreadable
directory propagates `read_dir`'s error and fails the run, and a dangling
source link is handed on to fail later. Give the walk a channel:
`collect_files` returns `Walked { files, warnings: Vec<Warning> }` where
`Warning { path, message }` — or keeps its signature and takes a
`&mut dyn FnMut(Warning)`; pick the one that keeps both callers a one-line
change and say why. An unreadable directory is skipped with a warning and
the walk continues; a dangling source-file link is warned about here and
NOT handed on (that reverses §43's review ruling deliberately, because the
warning is now the error's home). CLI: warnings go to stderr as
`warning: <path>: <message>` before the report, exit code unchanged (a
warning is not a failure; `--check` still returns 1/0 on formatting alone).
Server: each warning logged once per scan through `notification.rs`.
Tests: a read-only directory (0o000) under the start — the run finishes,
the other files are reported, one warning names the directory; a dangling
link; the CLI's stderr and exit code pinned in `tests/cli.rs`; the server's
scan over the same tree logs once and indexes the rest. Byte-identity of
every corpus file unchanged; the opentitan sweep outcome unchanged.
### 45.3 An inline aggregate as a parameter-override argument (topo 17)
`m #(.T(struct packed { logic a; })) u ();` is rejected in expression
position. `parse_connection`'s value already goes through
`parse_expr_or_type`; find why an aggregate type is not accepted there (a
`struct`/`union`/`enum` keyword at the head of the value) and accept it as
a type argument, printed by the existing type printer. Then M4's
`instantiation_plan` no longer drops such a `parameter type` default — emit
the type text. Tests: parse + format round-trip (struct, union, enum, with
packed dims and a comment inside), the plan emits it, strict/tolerant
parity, byte-identity.
### 45.4 Comment gaps inside a delay list (topo 22)
`#(1:2:3)` and gate delays `#(a, b)` go through `parse_delay_values`
(`parser/instance.rs`); the gaps around the `(`, the `:`s and the `,`s have
no comment slots, so the verifier refuses them. Add the slots the way §43.2
added `NetDelay`'s (read `docs/features/comment-slots/README.md`), print
them inline, and extend the RTL gap fuzzer fixture so its zero-failure bar
covers the construct. Tests: every gap with a comment, idempotent,
comments kept; the `EXPECTED_RTL_GAPS` count updated with the reason.
### Gates (dev, guarded)
fmt/clippy/`cargo test --workspace`; corpus 814/820 same six; byte-identity
vs 0.43.0 (lead); the opentitan sweep unchanged (lead); smoke.
- [x] 45.1 editor unknown-name log
- [x] 45.2 walk warning channel, both front ends
- [x] 45.3 inline aggregate override argument + plan emission
- [x] 45.4 delay-list comment slots + fuzzer coverage
- [x] docs: feature README; topo 29/30/17/22 struck (lead)
- [x] Gates (guarded)
- [x] QA: each item attacked on both front ends; the walker warnings on a
cyclic + unreadable tree; the aggregate shapes with comments; the
delay gaps through the fuzzer — REWORK, one MEDIUM finding (a line
comment trailing a gate instance separator, `format/instance.rs`;
see `docs/features/small-items-4/README.md` QA log)
## 46. The didOpen delay (planned 2026-09-05) — take-3 finding §44b
One lane after §45. Feature README: `docs/features/didopen-cost/README.md`.
Ships in 0.44.0.
Take 3 (`docs/performance_take3.md`): a `didOpen` of a file already in
scope delays the NEXT request by 21–51 ms, scaling with file size, where
take 2 measured 2–4 ms; a second request at the same position costs
0.07–0.21 ms, so the open is what costs. The server is a synchronous loop:
whatever `didOpen` does before returning to the loop is what the next
request waits for.
- **Measure first.** Write a scratch driver (framed JSON-RPC; take 3's
method, §9 of that doc) and time `didOpen` → first `hover` on opentitan's
`aes.sv`, `aes_core.sv` and the 42k-line `tl_peri_pkg.sv`-class file, at
0.43.0 and at 0.39.0 (server built from the tag in a scratch worktree,
removed after). Then profile the open path with the shipped `--verbose`
timings (no instrumentation added) or with temporary `eprintln!` timings
removed before finishing: what runs synchronously — the tolerant parse,
the diagnostics pass (lint run construction from §42: discovery, waiver
files, the once-only memo), semantic tokens, the index update of the
buffer, the completion word table patch?
- **Fix the largest item, not all of them.** Likely shapes: publish the
open's diagnostics from the same debounce `didChange` uses instead of
synchronously; skip re-indexing a buffer whose text equals the disk facts
the index already holds (content hash); build the `LintRun` lazily.
Whatever it is, the contract is: `didOpen` returns to the loop in
≤ 5 ms for a 1k-line file, and the first request after it is answered
from up-to-date state (diagnostics may arrive a debounce later — say
which and pin it).
- Tests: a wire-level test timing `didOpen` → next response on a generated
2k-line file (an upper bound, generous enough for CI: ≤ 25 ms where
today is ~50); correctness pins that the first hover/definition after an
open of an edited-on-disk file sees the buffer's text; the take-3 rows
re-measured in the README.
- [x] measurement + profile, in the README — and the finding understated it:
`pinmux_reg_top.sv` (42 192 lines) delayed the next request by **1 742
ms**, of which 1 608 was the one rule `undriven-net` asking the
workspace census once per declaration ahead of its own local guards
- [x] the fix, with the ≤ 5 ms return contract pinned — the census question
moved behind the guards, where `unused-signal` has always asked. Met
for a generated 1 000-line buffer (<2 ms); 5.9–6.9 ms for
`aes_core.sv`, 1 145 lines of dense RTL whose 3.0–4.4 ms of parse
cannot be deferred without answering the next request from stale
state. Recorded as the limit in the README, not redefined
- [x] docs; §44b ticked; take-3 finding 2 annotated — the annotation text and
a `docs/perf/README.md` entry are in the feature README under "Docs to
apply at merge (lead)"
- [x] Gates (guarded); the take-3 rows re-measured — 3 814 tests (was 3 810),
corpus 814/820 same six, clippy and fmt clean, smoke OK; §8.4's three
files 51/70/95 ms → 4.6/7.3/7.8 ms
- [x] QA: the driver re-run on the three files at three sizes; the
diagnostics still arrive; no request answered from stale state —
PASS, independently re-derived on a new driver: 0.43.0 vs fixed
3.4×/11×/17× on aes.sv/aes_core.sv/pinmux_reg_top.sv; opentitan
`hw/ip/{aes,hmac,spi_device}` and
`hw/top_darjeeling/ip_autogen/pinmux` byte-identical; counting-oracle
test confirmed to fail on a hand-reverted scratch copy; gates
reproduced (3814/0/44, corpus 814/820, clippy/smoke clean); QA log
in `docs/features/didopen-cost/README.md`
## 47. Type-name spans on the AST; retire `vlog_semantic/src/scan.rs` (planned 2026-09-05) — topo §2.9-2
One lane after 0.44.0, §36's protocol. Feature README:
`docs/features/type-name-spans/README.md`. Ships in 0.45.0 with §48/§49.
`vlog_semantic/src/scan.rs` (193 lines) recovers the byte range of a name
the AST kept only as a `String` by scanning the construct's source text.
Its two remaining users, both in `bind/`: `bind/decl.rs` (the type name of
a declaration — `DataType::name`, split as `pkg::item` into unit and item
spans by `NameScanner`, or as `iface.modport` into head and tail) and
`bind/stmt.rs` (`disable <label>`). Every other name already has
`name_span` on its node (`src[name_span] == name` is pinned over the corpus
census, 21 485 symbols).
- **`DataType::name_span: TextRange`** — the range of the name exactly as
written, so `src[name_span]` is `pkg::item` (with an escaped segment's
trailing space, §29) or `iface.mp`. Set by every site that builds a
`DataType` (`parse_type_ref`, the implicit/`logic` cases — for an
implicit type with no written name, the empty range at the position the
name would have had, the convention `name_span` already uses for the
unnamed-DPI-formal case, decl.rs:436). Segment spans are derived from
`name_span` alone — split the *span's own text* on `::`/`.`, never
rescan the construct — in one helper `DataType::segments() ->
impl Iterator<Item = (&str, TextRange)>`.
- **Size.** `DataType` rides in every `Expr` through `ExprKind::Type`;
`size_pins` holds `Expr ≤ 96`. Measure before and after; if the 8 bytes
push `Expr` over, move `name_span` into the already-boxed `TypeExtra`
(making `extra` `Some` whenever a name is written) or box — say which
and why; the pin does not move.
- **`StmtKind::Disable`** (and any other statement that names a label or
identifier as a bare `String` — grep `scan::` and `String` names in
`ast/stmt.rs`) gains `name_span` the same way.
- **Delete `scan.rs`**, its `mod`, and the `src` parameter the README's
Handshakes say goes with it if nothing else reads it; the binder reads
the spans. `vlog_semantic/README.md` and `docs/features/vlog-semantic/README.md`
Handshakes updated (delivered).
- **Consumers that benefit:** hover/definition/references on a type name
(`nav.rs`, `hover.rs`) — nothing to change if they already go through
`Reference::name_span`; confirm, and add a test that definition on
`pkg::t` in a declaration lands on `t`'s declaration with the *item*
range selected, and on `bus_if.mp` on the interface with the head range.
- Pins: the corpus census assertion `src[name_span] == name` now covers
type-name references too (extend `tests/census.rs` or the semantic
corpus test that holds the 21 485 number — report the new count);
strict/tolerant parity; byte-identity of every corpus file (the
formatter does not print spans); `cargo test --workspace`; opentitan
sweep unchanged; a before/after of `definition` on 200 type-name
positions over opentitan (read-only) to show nothing regressed.
- [x] 47.1 `DataType::name_span` + `segments()`, size ruled
- [x] 47.2 `StmtKind::Disable` name span
- [x] 47.3 `scan.rs` deleted; binder reads spans; census pin extended
- [x] docs: feature README; topo §2.9-2 struck (lead); semantic READMEs
- [x] Gates (guarded): 3 814 tests / 0 failed / 44 ignored (the 0.44.0 count
exactly — six `scan.rs` unit tests out, six new ones in); corpus 814/820,
the per-file TSV byte-identical to the committed one; `format --stdout`
of all 860 corpus files identical to `lucisv-0.44.0`; clippy and fmt
clean; release server smoke OK; census 27 486 symbols / 103 870
references / 0 unplaced, identical to a `v0.44.0` scratch worktree; 200
`definition` positions over opentitan identical old vs new
- [x] QA: census re-derived; escaped and scoped type names; `iface.mp`
ports; implicit types; definition/hover on type names over
opentitan (read-only)
## 48. Package re-exports as real references (planned 2026-09-05) — topo §2.9-16
One lane after §47 merges, §36's protocol. Feature README:
`docs/features/package-reexports/README.md`. Ships in 0.45.0.
`ItemKind::Export(paths)` is bound as an opaque leaf (`bind/item.rs`, the
dpi-export handshake). Two halves, both here:
- **The binding half.** `export pkg::item;` and `export pkg::*;` record
`pkg` as a `Target::Unit` reference and `item` as a
`Target::UnitMember(pkg)` reference — exactly the halves
`bind_import_path` records — **without** pushing a scope import: a
re-export brings nothing into the exporting scope (IEEE 1800 §26.6). One
new binder function beside `bind_import_path`, sharing its path walk.
`export *::*;` records no references (there is no name to resolve) and
is documented as "everything this package imports is re-exported".
- **The resolution half.** A file that does `import a_pkg::*` (or names
`a_pkg::x`) must resolve `x` when `a_pkg` re-exports it from `b_pkg`.
The index records each package's re-exports as facts (`FACTS_FORMAT`
17 → 18: an `RX` group — `(pkg, item|*)` pairs plus the `*::*` flag;
`index_cache` drops older stores by format as it already does), and the
member walk in `workspace/external.rs` that lists a unit's members
follows re-exports: `a_pkg`'s members += `b_pkg`'s exported `item`, or
all of `b_pkg`'s exports for `b_pkg::*`, or all of every package
`a_pkg` imports for `*::*` — with a visited set so a re-export cycle
terminates. Completion after `a_pkg::` lists them; hover/definition on
`x` lands on `b_pkg`'s declaration; references of `b_pkg::x` include the
uses through `a_pkg`; rename of `x` edits the re-export line's `item`
too (the rename engine reads references, so this should follow — pin
it).
- Tests: binding — the two halves recorded with exact spans; no scope
import (a name re-exported is NOT visible bare inside the exporting
package unless also imported — pin the negative); resolution — a
three-file workspace (b_pkg declares, a_pkg re-exports one/`*`/`*::*`,
top imports a_pkg::*) for definition, hover, completion, references and
rename over the wire; a re-export cycle; a re-export of a name b_pkg
does not declare (unresolved, no panic); the census numbers re-derived
and the delta explained (new references only); FACTS_FORMAT bump test
(an older store is dropped whole).
- [x] 48.1 binding of `export` halves, no scope import
- [x] 48.2 `RX` facts, FACTS_FORMAT 18, member walk through re-exports
- [x] docs: feature README; topo §2.9-16 struck (lead); dpi-export
handshake (a) answered
- [x] Gates (guarded); census delta explained — references 103 870 → 103 875
(+5: the corpus's two package `export` lines, five name halves in all),
every other number flat
- [x] QA: the three-file workspace over the wire; cycles; unknown items;
an opentitan UVM package tree read-only (definition through a
re-export, before/after)
## 49. Cross-file instance-member tail in rename (planned 2026-09-05) — topo §2.9-23
One lane after §48 merges, §36's protocol. Feature README:
`docs/features/hierarchical-tail/README.md`. Ships in 0.45.0.
With `module sub` in `sub.sv` and `assign w = u_x.sig;` in `top.sv`,
renaming `sub`'s internal `wire sig` edits `sub.sv` only and warns (item
20's warning); the same shape in one file resolves and is edited. The
cause is the export rule in `workspace/record.rs::is_exported`: a module
exports ports and parameters only, so the cross-file member walk cannot see
`sig` through `u_x`.
**Ruling (lead): a module gains a second, distinct surface.** Its
*connection* surface stays ports + parameters (what a connection list may
name; completion in a connection list and the `propagate-ports` engine keep
reading exactly this). Its *hierarchical* surface is its nets, variables
and (for nested reach) instances, which a hierarchical path may name from
anywhere (IEEE 1800 §23.6). The index records both, tagged
(`FACTS_FORMAT` 18 → 19 if §48 already bumped to 18, else 17 → 18: the
member record carries a `surface` bit), and only the tail walk behind an
*instance* (`Target::MemberOf { head: an instance … }`) reads the
hierarchical surface. Nothing else changes what it sees.
- `resolve_external`: a `MemberOf` whose head resolves to an instance of
module `M` looks `tail` up in `M`'s hierarchical surface (then nested
instances for `u_a.u_b.sig`); the answer is a `Def` in `M`'s file, so
rename's reference set now includes the cross-file tail and the edit
lands on it; the §2.9-20 warning is no longer raised for a tail that
resolved (it stays for one that did not).
- Not widened: completion after `u_x.` in an expression MAY list the
hierarchical surface (it is what the user is typing) — say whether it
does and pin it either way; a connection list's completion must not.
- Tests: `a_hierarchical_tail_that_resolves_is_renamed_with_its_declaration`
gets its cross-file twin (two files, the edit lands in both; the warning
gone); nested `u_a.u_b.sig`; a tail naming a port (both surfaces — one
answer); a tail naming a parameter; a generate-block-scoped net
(`u_x.gen[0].sig` — refuse honestly, pin); an interface instance tail
(already resolves — unchanged); the `--check` of rename's verifier still
refuses when a tail is ambiguous (two `sub` declarations); the census
delta explained; opentitan (read-only): rename of an internal net used
hierarchically from a DV bench, timing before/after, and the count of
newly resolved references over `hw/ip/aes`.
- [x] 49.1 surface bit in facts, FACTS_FORMAT bump (18 → 19), index member
walk — `workspace/hierarchy.rs`, a second `hier_members` table
- [x] 49.2 `MemberOf` behind an instance reads the hierarchical surface;
rename edits the tail; the warning retired for resolved tails
- [x] docs: feature README (`docs/features/hierarchical-tail/README.md`);
topo §2.9-23 struck (lead — strike text in the README); record.rs's
export doc rewritten (the ruling moved to `hierarchy::surface_of`)
- [x] Gates (guarded): 3 839 tests / 0 failed / 44 ignored (baseline 3 829,
+10 new); corpus 814/820, the same six; `format --stdout` of all 860
corpus files byte-identical to `lucisv-0.44.0`, 0 differing; clippy and
fmt clean; release server smoke OK. Census: single-file corpus census
unmoved (860 / 27 486 / 103 875 / 1 197 / 0), index gains 5 239
hierarchical-only members beside an unchanged 12 939, and 335 corpus
references resolve that could not before. opentitan (read-only,
requests never applied): `lc_ctrl`'s `fsm_state_q` rename now names
`dv/tb.sv` as well as `rtl/lc_ctrl_fsm.sv` (10 → 22 ms; prepareRename
unmoved); over `hw/ip/aes` the newly resolved count is **0** (every
`aes` hierarchical path goes through a generate block or a `bind`) and
rename is 41 → 55 ms for the same answer; over all of `hw/` 514
references newly resolve; store +10.7 % on `aes`, +6.2 % on `lc_ctrl`
- [x] QA: the shapes above over the wire; the connection-list completion
unchanged; rename verifier refusals unchanged; opentitan before/after
## 55. Filed 2026-09-05 — `lucisv_server/src/state.rs` over the size threshold
The §49 dev measured `crates/lucisv_server/src/state.rs` at 957 production
lines outside tests, over the 800 "consider splitting" mark and past the
§28 decomposition note in CLAUDE.md (which is stale for it). A pure-move
decomposition round (Fable refactor-dev, per the refactor policy): the
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
count unchanged); CLAUDE.md's measurement line refreshed
## 50. `.*` expansion (planned 2026-09-05) — the first §8 refactoring
One lane after 0.45.0, §36's protocol. Feature README:
`docs/features/expand-wildcard/README.md`. Ships in 0.46.0 with §51.
A wildcard connection `sub u_x (.clk(clk), .*);` binds every remaining
port to the same-named signal in scope (IEEE 1800 §23.3.2.4). Expanding it
writes those bindings out — the refactoring people reach for before a
port list diverges, and the one the ports engine already refuses to edit
around (`add`/`remove` warn and leave `.*` sites alone; `propagate`
declines a wildcard site).
- **Engine** (`vlog_refactor::ports`, new `expand.rs` beside
`propagate.rs` — the closest sibling: it already computes "the ports the
instantiation does not name" from the instantiated module's declaration):
`expand_wildcard(files, file, offset) -> Result<RefactorEdit, String>`.
At the cursor's instantiation: refuse unless the connection list holds a
`.*`; take the instantiated module's port list (through `Scope`, the
fan-out reader `propagate` uses); for every port not explicitly
connected, emit `.name(name)` when a signal `name` is declared in the
instantiating scope (the wildcard's own rule: same name, in scope, any
kind — net, var, port, parameter is *not* a signal); a port with no
same-named signal in scope is what the wildcard would have left
unconnected → emit `.name()` and a warning naming it (the compiler
would have errored; saying so is the point of the expansion). Replace the
`.*` token with the generated connections in the port's declaration
order, one per line when the list is already multi-line, inline
otherwise — then let the formatter's verified splice do the layout
(the ports engine's lexical splice + "the file still parses" rule,
README §"How an edit is made"). The `.*` element's comments (before/after
slots) go on the first generated connection.
- **Refusals** (the verifier's whole-edit rule): the instantiated module
unknown or declared twice; a parse diagnostic in either file; a port
list carrying compiler directives (`ListDirective` — the same refusal
`instantiation_plan` makes); an instance with more than one `.*` (illegal);
a `.*` inside a `bind` directive (out of scope, say so).
- **Server:** a code action `lucisv: expand .* (N connections)` offered at
a `.*` under the cursor, through the lazy offer path (§37.1: the offer
reads the buffer + the declaration, `resolve` computes the edit); a
command `lucisv.expandWildcard [uri, position]` for clients without
code actions; the VS Code extension needs nothing new (commands are
discovered). Title count from the plan.
- Tests: engine — a three-port module with one explicit and `.*`; all
ports present in scope; one missing (`.name()` + warning); a port whose
same-named signal is a *parameter* (not bound — pin per the LRM);
nested/generate instantiation; multi-line vs inline lists; comments on
the `.*`; the five refusals; idempotency of the result (formatting the
edited file changes nothing further); the formatter's byte contract on
three corpus files edited in a scratch copy. Server — offer + resolve
over the wire; the command; opentitan read-only: count the `.*` sites
under `hw/ip` and expand ten of them into scratch copies, each result
formatting cleanly and parsing with the same instance count.
- [ ] 50.1 `expand_wildcard` engine + refusals
- [ ] 50.2 code action (lazy) + command
- [ ] docs: feature README; README/site rows (lead applies); §8 line
annotated
- [ ] Gates (guarded); byte-identity vs 0.45.0
- [ ] QA: the LRM rule attacked (kinds, scopes, generate, parameters);
refusals; ten opentitan sites in scratch copies
## 51. Non-ANSI → ANSI port conversion (planned 2026-09-05) — the second §8 refactoring
One lane after §50 merges, §36's protocol. Feature README:
`docs/features/ansi-conversion/README.md`. Ships in 0.46.0.
A Verilog-2001 header `module m (a, b, c);` with body declarations
`input a; output [7:0] b; inout c;` (and optionally `reg b;` beside the
`output`) becomes `module m (input a, output reg [7:0] b, inout c);` with
the body declarations removed. The ports engine already edits headers of
both shapes (`ports/add.rs::header_edits`: the ANSI list, the non-ANSI
list plus the body declaration) and its lexical splice + "the file still
parses" verifier is the safety net; this is the whole-header version.
- **Engine** (`vlog_refactor::ports`, new `ansi.rs`):
`convert_to_ansi(files, file, offset) -> Result<RefactorEdit, String>` on
a module whose header is `PortList::NonAnsi`. For each header name in
header order: find its body `PortDecl` (direction, net type or `reg`/
`logic`, signing, packed dims — from the port declaration and, when a
separate `reg`/`wire`/`logic` declaration of the same name exists, its
type merged per IEEE 1800 §23.2.2.2: `output [7:0] b; reg [7:0] b;` →
`output reg [7:0] b`); emit the ANSI port; delete the body declarations
it absorbed (whole items, with their trailing comments moved onto the
ANSI port's slot — comments are never dropped). Leading comments of a
body declaration go before the ANSI port on its own line if the list is
multi-line, else are the reason to refuse (say so).
- **Refusals:** a header name with no body declaration (an implicit port —
illegal); a body declaration for a name not in the header; a port
declared twice; a non-ANSI port whose header entry is an expression or
concatenation (`.a({x,y})`, `{x,y}` — §23.2.2.1 port expressions: refuse
with the reason); a `PortDecl` with an unpacked dimension differing from
its variable declaration; any compiler directive in the header or in an
absorbed declaration; a body declaration inside a generate or
conditional region; an `interface`/`program` (out of scope in this
round, say so); the module declared twice in the workspace (the port
engine's own rule); a parse diagnostic in the file.
- **Server:** code action `lucisv: convert ports to ANSI (N ports)` offered
with the cursor anywhere in a non-ANSI module's header, lazy per §37.1;
command `lucisv.convertToAnsi [uri, position]`.
- Tests: engine — the LRM examples of §23.2.2.2 (each merge rule), a
header with 20 ports and mixed declarations, comments on every absorbed
declaration (all kept, positions pinned), `reg` and `logic` and `wire`
variants, signed, packed dims, a `parameter` between the declarations
(untouched), every refusal, idempotency (the result formats unchanged;
re-running the action refuses because the header is ANSI); the corpus:
count non-ANSI modules (`PortList::NonAnsi`) and convert every one in a
scratch copy — each result parses, formats, and has the same port names
in the same order (a census assertion, not a byte one). Server — offer +
resolve over the wire; the command; opentitan read-only: the count of
non-ANSI modules under `hw/vendor` and ten conversions into scratch
copies.
- [ ] 51.1 `convert_to_ansi` engine + refusals
- [ ] 51.2 code action (lazy) + command
- [ ] docs: feature README; README/site rows (lead applies); §8 line
annotated
- [ ] Gates (guarded); byte-identity vs 0.45.0; the corpus conversion census
- [ ] QA: every §23.2.2.2 merge rule attacked; comments; refusals; the
corpus census re-derived; opentitan scratch conversions
+53 -5
View File
@@ -366,7 +366,12 @@ fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config, FileConfig)>, String>
return Err(format!("--lines needs a file, not a directory: {input}"));
}
let exclude = opts.exclude_with(&discovery.for_input(Path::new(input))?);
collect_files(input, &exclude, !opts.no_gitignore, &mut files)?;
// The walk's own warnings — an unreadable directory, a source file
// that is only a broken link — go to stderr as they are found, before
// the report and exactly as a filelist's do. A warning is not a
// failure: the exit code is the formatting's alone.
let mut warn = |w| eprintln!("warning: {w}");
collect_files(input, &exclude, !opts.no_gitignore, &mut files, &mut warn)?;
}
// Filelists come after the command line's own inputs, in flag order: they
// add files, they never replace or reorder what was named directly.
@@ -415,13 +420,25 @@ fn filelist_files(opts: &Options) -> Result<Vec<PathBuf>, String> {
fn dedup(files: Vec<PathBuf>) -> Vec<PathBuf> {
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
let mut seen = HashSet::new();
files.into_iter().filter(|file| seen.insert(absolute(&cwd, file))).collect()
files.into_iter().filter(|file| seen.insert(identity(&cwd, file))).collect()
}
/// The key two spellings of one file share: the file's canonical path when it
/// is there, and the lexical fold when it is not.
///
/// Canonical means symlinks resolved, which is the only way to see that
/// `b.sv -> a.sv` is the file `a.sv` already named — two rayon workers on one
/// target otherwise, each rewriting what the other just wrote. A path with no
/// file behind it has no canonical form, and the lexical fold is then the
/// best two names for it can be compared by. Neither is ever the path lucisv
/// reports: that stays the first spelling seen.
fn identity(cwd: &Path, path: &Path) -> PathBuf {
std::fs::canonicalize(path).unwrap_or_else(|_| absolute(cwd, path))
}
/// `path` folded to the absolute, `.`/`..`-free spelling two names for one
/// file share. Lexical, like `lucisv_core`'s own normalization: symlinks are
/// deliberately left unresolved, so this is only ever a dedup key and never
/// the path lucisv reports.
/// file share. Purely lexical, like `lucisv_core`'s own normalization — it
/// answers for paths that do not exist, where there is nothing to resolve.
fn absolute(cwd: &Path, path: &Path) -> PathBuf {
let joined = if path.is_absolute() { path.to_path_buf() } else { cwd.join(path) };
let mut out = PathBuf::new();
@@ -602,6 +619,37 @@ mod tests {
assert_eq!(dedup(files), [cwd.join("rtl/a.sv")]);
}
#[cfg(unix)]
#[test]
fn dedup_folds_a_symlink_onto_the_file_it_points_at() {
// A directory walk lists `b.sv` as a file of its own; lexically the
// two names share nothing, and two workers would rewrite one file.
let dir = std::env::temp_dir().join(format!("lucisv-dedup-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("temp dir");
let real = dir.join("a.sv");
let link = dir.join("b.sv");
std::fs::write(&real, "module m;\nendmodule\n").expect("seed");
std::os::unix::fs::symlink(&real, &link).expect("symlink");
assert_eq!(dedup(vec![real.clone(), link.clone()]), std::slice::from_ref(&real));
// Whichever spelling comes first is the one kept and reported.
assert_eq!(dedup(vec![link.clone(), real.clone()]), std::slice::from_ref(&link));
// And a `..` detour through the same link is still the same file.
std::fs::create_dir(dir.join("sub")).expect("sub dir");
let detour = dir.join("sub/../b.sv");
assert_eq!(dedup(vec![real.clone(), detour]), std::slice::from_ref(&real));
// A file that is not there has no canonical path: the key is lexical,
// which still folds `.` and `..`, and two missing files stay two.
let gone = dir.join("gone.sv");
let same = dir.join("./sub/../gone.sv");
let other = dir.join("other.sv");
assert_eq!(dedup(vec![gone.clone(), same, other.clone()]), [gone, other]);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn format_contained_reports_parse_errors() {
let err = format_contained("module", &Config::default(), None).unwrap_err();
+136
View File
@@ -136,6 +136,57 @@ fn formats_files_in_place() {
assert!(stderr(&out).contains("2 files left unchanged"), "{}", stderr(&out));
}
/// A directory walk lists a symlink as a file of its own, so `b.sv -> a.sv`
/// used to put two workers on one file: two report lines for one file, and
/// two writers racing to replace it. It is one file now, named once.
#[cfg(unix)]
#[test]
fn a_symlink_and_its_target_are_one_file() {
let dir = TempDir::new("alias");
dir.write("a.sv", UNFORMATTED);
std::os::unix::fs::symlink(dir.path.join("a.sv"), dir.path.join("b.sv")).expect("symlink");
let out = run(&["--check", &dir.root()]);
assert_eq!(code(&out), 1, "{}", stderr(&out));
let reported = stdout(&out);
let named: Vec<&str> = reported.lines().filter(|l| l.contains("would reformat")).collect();
assert_eq!(named.len(), 1, "one file, one line: {named:?}");
assert!(named[0].ends_with("a.sv"), "the first spelling walked is the one reported: {named:?}");
assert!(stderr(&out).contains("1 file would be reformatted"), "{}", stderr(&out));
let out = run(&[&dir.root()]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert!(stderr(&out).contains("1 file reformatted"), "{}", stderr(&out));
assert_eq!(dir.read("a.sv"), FORMATTED);
assert_eq!(dir.read("b.sv"), FORMATTED, "and the link still reaches it");
assert!(
std::fs::symlink_metadata(dir.path.join("b.sv")).expect("stat").file_type().is_symlink(),
"the link was not replaced by a copy"
);
}
/// A directory that links back into itself. Before the walk kept a visited
/// set (`docs/features/walk-cycles/README.md`) this run recursed until the
/// OS refused the path; now each directory is entered once, so each file is
/// named once — under the first spelling that reaches it.
#[cfg(unix)]
#[test]
fn a_symlink_cycle_terminates_and_names_each_file_once() {
let dir = TempDir::new("cycle");
dir.write("rtl/a.sv", UNFORMATTED);
dir.write("rtl/sub/b.sv", UNFORMATTED);
// `rtl/self` is `rtl` itself; `rtl/sub/up` is `rtl` from one level down.
std::os::unix::fs::symlink("../rtl", dir.path.join("rtl/self")).expect("symlink");
std::os::unix::fs::symlink("..", dir.path.join("rtl/sub/up")).expect("symlink");
let out = run(&["--check", &dir.root()]);
assert_eq!(code(&out), 1, "{}", stderr(&out));
let reported = stdout(&out);
let named: Vec<&str> = reported.lines().filter(|l| l.contains("would reformat")).collect();
assert_eq!(named.len(), 2, "two files, two lines: {named:?}");
assert!(stderr(&out).contains("2 files would be reformatted"), "{}", stderr(&out));
}
#[test]
fn check_reports_without_writing() {
let dir = TempDir::new("check");
@@ -2095,3 +2146,88 @@ fn rules_doc_refuses_files_and_belongs_to_check() {
stderr(&out)
);
}
// --- the walk's own warnings (docs/features/small-items-4/README.md) -------
/// A tree with the two things the walk can only warn about: a directory it
/// cannot read, and a source file that is only a broken link.
#[cfg(unix)]
fn unwalkable_tree(tag: &str) -> TempDir {
use std::os::unix::fs::{symlink, PermissionsExt};
let dir = TempDir::new(tag);
dir.write("a.sv", UNFORMATTED);
dir.write("z/late.sv", UNFORMATTED);
dir.write("locked/hidden.sv", UNFORMATTED);
symlink("nowhere.sv", dir.path.join("gone.sv")).expect("symlink");
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o000))
.expect("chmod");
dir
}
#[cfg(unix)]
fn lock(dir: &TempDir) {
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o000))
.expect("chmod");
}
#[cfg(unix)]
fn unlock(dir: &TempDir) {
use std::os::unix::fs::PermissionsExt;
let _ =
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o755));
}
#[test]
#[cfg(unix)]
fn an_unreadable_directory_is_a_warning_and_the_rest_of_the_tree_is_formatted() {
// The finding TODO §45.2 closes: one permission-denied directory used to
// propagate `read_dir`'s error and fail the whole run.
let dir = unwalkable_tree("walk-warn");
let out = run(&[&dir.root()]);
unlock(&dir);
assert_eq!(code(&out), 0, "a warning is not a failure: {}", stderr(&out));
let said = stderr(&out);
assert_eq!(said.matches("warning: ").count(), 2, "{said}");
assert!(said.contains("locked"), "{said}");
assert!(said.contains("gone.sv: broken symbolic link"), "{said}");
assert_eq!(dir.read("a.sv"), FORMATTED, "the other files were formatted");
assert_eq!(dir.read("z/late.sv"), FORMATTED, "including the ones sorted after it");
}
#[test]
#[cfg(unix)]
fn the_walks_warnings_leave_check_modes_exit_code_alone() {
let dir = unwalkable_tree("walk-warn-check");
let out = run(&["--check", &dir.root()]);
unlock(&dir);
// `--check` answers on formatting alone: two files would be reformatted.
assert_eq!(code(&out), 1, "{}", stderr(&out));
assert_eq!(stderr(&out).matches("warning: ").count(), 2, "{}", stderr(&out));
assert!(!stdout(&out).contains("warning"), "warnings stay off stdout: {}", stdout(&out));
// And with nothing left to reformat the run is clean, warnings and all.
dir.write("a.sv", FORMATTED);
dir.write("z/late.sv", FORMATTED);
lock(&dir);
let out = run(&["--check", &dir.root()]);
unlock(&dir);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert_eq!(stderr(&out).matches("warning: ").count(), 2, "{}", stderr(&out));
}
#[test]
#[cfg(unix)]
fn a_dangling_source_link_named_on_the_command_line_is_still_an_error() {
// The walk drops the link; a path the user typed is not walked at all, so
// "no such file or directory" is still what naming one gets.
let dir = TempDir::new("walk-warn-named");
std::os::unix::fs::symlink("nowhere.sv", dir.path.join("gone.sv")).expect("symlink");
let named = dir.path.join("gone.sv").to_string_lossy().into_owned();
let out = run(&[&named]);
assert_eq!(code(&out), 2, "{}", stderr(&out));
assert!(stderr(&out).contains("no such file or directory"), "{}", stderr(&out));
}
+263 -14
View File
@@ -7,11 +7,24 @@
//! gets the bytes, and a `rename` over the target publishes them in one step
//! that either happened or did not.
//!
//! See `docs/features/small-items-3/README.md`.
//! Two threads of one process may write one target: the temp names carry a
//! per-process counter as well as the pid and are created with `O_EXCL`, so
//! each writer owns its own file and neither can see the other's bytes.
//!
//! Two *processes* writing one target are not coordinated, and deliberately
//! so. Both renames are atomic, the later one wins, and the loser's bytes are
//! discarded whole — never merged. Both processes formatted the same input
//! and `format` is idempotent, so whichever rename lands last leaves the
//! file complete and correctly formatted. A lock would buy nothing and would
//! be one more thing to leave behind after a `^C`.
//!
//! See `docs/features/small-items-3/README.md` and
//! `docs/features/atomic-write-coordination/README.md`.
use std::fs;
use std::io;
use std::fs::{self, File, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
/// Writes `bytes` to `path`, replacing whatever was there in one step.
///
@@ -21,6 +34,12 @@ use std::path::{Path, PathBuf};
/// sees either the old file or the new one and never a truncated one. A
/// failure anywhere after the temp exists removes it before returning.
///
/// The temp is the caller's alone: [`temp_path`] hands out a name no other
/// writer in this process will be given, and the file is created with
/// `create_new`, so a name that somehow exists is an error and not a shared
/// file. Two threads writing one target therefore both succeed, and the
/// target ends up holding one thread's whole buffer.
///
/// A symlinked target is resolved first: `fs::write` writes *through* a
/// symlink, so replacing the link itself would silently redirect it at a new
/// file and leave the real one stale. The canonical path is what gets
@@ -28,26 +47,22 @@ use std::path::{Path, PathBuf};
/// filesystem — `rename` cannot cross one.
pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
let target = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
let perms = target_permissions(&target);
// A rename replaces a file whatever its mode, so a read-only target would
// be silently overwritten where `fs::write` refuses it. Keep the refusal:
// a file someone made read-only is asking not to be rewritten in place.
if fs::metadata(&target).is_ok_and(|m| m.permissions().readonly()) {
if perms.as_ref().is_some_and(fs::Permissions::readonly) {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!("{} is read-only", path.display()),
));
}
let tmp = temp_path(&target)?;
if let Err(e) = fs::write(&tmp, bytes) {
let (tmp, mut file) = create_temp(&target, perms.is_some())?;
if let Err(e) = fill_temp(&mut file, &tmp, perms, bytes) {
let _ = fs::remove_file(&tmp);
return Err(e);
}
// A file someone made read-only, or executable, keeps its mode: the temp
// was created with the process umask, not with the target's bits. No
// target means a new file, which takes the umask as `fs::write` would.
if let Ok(meta) = fs::metadata(&target) {
let _ = fs::set_permissions(&tmp, meta.permissions());
}
drop(file);
if let Err(e) = fs::rename(&tmp, &target) {
let _ = fs::remove_file(&tmp);
return Err(e);
@@ -55,16 +70,106 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
Ok(())
}
/// How many temp names one write tries before giving up.
///
/// A name is only ever handed out once per process, so a collision means a
/// leftover from a *previous* process that crashed mid-write and whose pid
/// this process now has. A handful of those may sit in one directory; a
/// hundred is a directory to clean up by hand, not a race to retry through.
const TEMP_ATTEMPTS: u32 = 32;
/// Creates the temp file, exclusively, and returns it with its path.
///
/// `replacing` says there is a target whose mode the temp is about to take.
/// Then it is born 0600 on unix rather than at the umask's mode: a chmod does
/// not revoke a descriptor someone already opened, so the only way a private
/// file's replacement can never be read by anyone else is for the temp to be
/// private from the moment it exists. With no target there is no earlier mode
/// to honour and the umask decides, as `fs::write` would.
fn create_temp(target: &Path, replacing: bool) -> io::Result<(PathBuf, File)> {
let mut opts = OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
if replacing {
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o600);
}
#[cfg(not(unix))]
let _ = replacing;
for _ in 0..TEMP_ATTEMPTS {
let tmp = temp_path(target)?;
match opts.open(&tmp) {
Ok(file) => return Ok((tmp, file)),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
Err(e) => return Err(e),
}
}
Err(io::Error::new(
io::ErrorKind::AlreadyExists,
format!("no free temp file name beside {} after {TEMP_ATTEMPTS} tries", target.display()),
))
}
/// Puts the target's mode on the temp, then the bytes in it.
///
/// The order is the point on unix: a 0600 target's replacement must not spend
/// even an instant holding the file's contents under the umask's broader
/// bits. Chmod does not close the handle opened before it, so a mode without
/// an owner-write bit still takes the write. Elsewhere `set_permissions`
/// takes a path rather than a handle and the mode goes on after the bytes,
/// which is the order this always had.
fn fill_temp(
file: &mut File,
tmp: &Path,
perms: Option<fs::Permissions>,
bytes: &[u8],
) -> io::Result<()> {
if cfg!(unix) {
copy_mode(file, perms);
file.write_all(bytes)
} else {
file.write_all(bytes)?;
if let Some(perms) = perms {
let _ = fs::set_permissions(tmp, perms);
}
Ok(())
}
}
/// Puts the target's mode on the temp through its open handle, which is what
/// lets it happen while the temp is still empty. No target means no earlier
/// mode to honour, and the umask's stands.
fn copy_mode(file: &File, perms: Option<fs::Permissions>) {
if let Some(perms) = perms {
let _ = file.set_permissions(perms);
}
}
/// The mode the temp must end up with: a file someone made executable, or
/// private, keeps its bits, because the temp was created with the process
/// umask (or 0600) and not with the target's. `None` means there is no target
/// — a new file, which takes the umask as `fs::write` would.
fn target_permissions(target: &Path) -> Option<fs::Permissions> {
fs::metadata(target).ok().map(|m| m.permissions())
}
/// Names handed out by [`temp_path`], one per call for the life of the
/// process. Wrapping after 2^64 names is not a scenario.
static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
/// The temp file's path: hidden, in the target's own directory, and stamped
/// with the process id so two lucisv runs over one tree cannot collide.
/// with the process id and a per-process counter — the pid keeps two lucisv
/// runs apart, the counter keeps two threads of one run apart, and together
/// they mean no two writers anywhere are ever given the same name.
fn temp_path(target: &Path) -> io::Result<PathBuf> {
let dir = target.parent().unwrap_or_else(|| Path::new("."));
let name = target
.file_name()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "no file name to write"))?;
let n = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
let mut tmp = std::ffi::OsString::from(".");
tmp.push(name);
tmp.push(format!(".{}.lucisv-tmp", std::process::id()));
tmp.push(format!(".{}.{n}.lucisv-tmp", std::process::id()));
Ok(dir.join(tmp))
}
@@ -199,4 +304,148 @@ mod tests {
);
assert_eq!(fs::read_to_string(&link).expect("read"), "new\n", "and still points at it");
}
/// The audit's probe (`docs/repository-analysis.md` finding 1), which
/// used to produce 100 write errors in 200 calls: both threads derived
/// the same temp name from the target and the pid, so one deleted the
/// other's file under it. Now every writer owns its own temp, so every
/// call succeeds and the target holds one writer's whole buffer.
#[test]
fn two_threads_writing_one_target_never_collide() {
const MIB: usize = 1024 * 1024;
const ROUNDS: usize = 100;
let dir = TempDir::new("race");
let file = dir.file("a.sv");
fs::write(&file, "seed\n").expect("seed");
// Three parties: the two writers and this thread, which inspects the
// target between rounds. Nobody starts a round until everyone has
// finished the last one.
let start = std::sync::Arc::new(std::sync::Barrier::new(3));
let done = std::sync::Arc::new(std::sync::Barrier::new(3));
let writers: Vec<_> = (*b"ab")
.into_iter()
.map(|tag| {
let (path, start, done) = (file.clone(), start.clone(), done.clone());
std::thread::spawn(move || {
let bytes = vec![tag; MIB];
let mut errors = Vec::new();
for _ in 0..ROUNDS {
start.wait();
if let Err(e) = write_atomic(&path, &bytes) {
errors.push(e.to_string());
}
done.wait();
}
errors
})
})
.collect();
for round in 0..ROUNDS {
start.wait();
done.wait();
let got = fs::read(&file).expect("read");
assert_eq!(got.len(), MIB, "round {round}: a partial buffer landed");
let tag = got[0];
assert!(tag == b'a' || tag == b'b', "round {round}: neither writer's byte");
assert!(got.iter().all(|&b| b == tag), "round {round}: two buffers were mixed");
assert_eq!(dir.names(), vec!["a.sv".to_string()], "round {round}: a temp was left");
}
let errors: Vec<String> =
writers.into_iter().flat_map(|w| w.join().expect("writer thread")).collect();
assert!(
errors.is_empty(),
"{} write errors in {} calls: {errors:?}",
errors.len(),
2 * ROUNDS
);
}
#[test]
fn every_thread_gets_its_own_temp_name() {
const PER_THREAD: usize = 200;
let dir = TempDir::new("names");
let target = dir.file("a.sv");
let threads: Vec<_> = (0..4)
.map(|_| {
let target = target.clone();
std::thread::spawn(move || {
(0..PER_THREAD)
.map(|_| temp_path(&target).expect("temp name"))
.collect::<Vec<_>>()
})
})
.collect();
let names: Vec<PathBuf> =
threads.into_iter().flat_map(|t| t.join().expect("name thread")).collect();
let unique: std::collections::HashSet<&PathBuf> = names.iter().collect();
assert_eq!(unique.len(), names.len(), "a temp name was handed out twice");
}
/// The mode goes on while the temp is still empty, so a 0600 file's
/// replacement never holds its contents under the umask's wider bits.
#[cfg(unix)]
#[test]
fn the_temp_takes_the_targets_mode_before_any_bytes() {
use std::os::unix::fs::PermissionsExt;
let dir = TempDir::new("modewindow");
let target = dir.file("secret.sv");
fs::write(&target, "old\n").expect("seed");
fs::set_permissions(&target, fs::Permissions::from_mode(0o600)).expect("chmod");
let perms = target_permissions(&target);
let (tmp, mut file) = create_temp(&target, perms.is_some()).expect("temp");
// Born private, before any mode is copied onto it: an fd opened by
// someone else in this instant would not see the bytes to come.
assert_eq!(
fs::metadata(&tmp).expect("stat").permissions().mode() & 0o777,
0o600,
"the temp was created readable by others"
);
copy_mode(&file, perms.clone());
let meta = fs::metadata(&tmp).expect("stat");
assert_eq!(meta.len(), 0, "the mode is set before a single byte is written");
assert_eq!(meta.permissions().mode() & 0o777, 0o600, "the temp is not world-readable");
// And the chmod does not close the door on the handle opened before it.
fill_temp(&mut file, &tmp, perms, b"new\n").expect("fill");
assert_eq!(fs::read_to_string(&tmp).expect("read"), "new\n");
let _ = fs::remove_file(&tmp);
}
/// The same window seen from outside, through a real `write_atomic`: a
/// big enough buffer that the temp is usually observable while it is
/// being filled. It asserts about what it sees and never about seeing it,
/// so a scheduler that hides the window cannot fail the test.
#[cfg(unix)]
#[test]
fn a_temp_seen_mid_write_is_never_world_readable() {
use std::os::unix::fs::PermissionsExt;
let dir = TempDir::new("window");
let target = dir.file("secret.sv");
fs::write(&target, "old\n").expect("seed");
fs::set_permissions(&target, fs::Permissions::from_mode(0o600)).expect("chmod");
let path = target.clone();
let writer = std::thread::spawn(move || {
let bytes = vec![b'x'; 8 * 1024 * 1024];
write_atomic(&path, &bytes)
});
while !writer.is_finished() {
for entry in fs::read_dir(&dir.path).expect("read dir").flatten() {
if !entry.file_name().to_string_lossy().ends_with(".lucisv-tmp") {
continue;
}
let Ok(meta) = entry.metadata() else { continue };
assert_eq!(
meta.permissions().mode() & 0o777,
0o600,
"a temp for a 0600 target was readable by others"
);
}
}
writer.join().expect("writer thread").expect("write");
assert_eq!(fs::metadata(&target).expect("stat").permissions().mode() & 0o777, 0o600);
}
}
+383 -23
View File
@@ -2,6 +2,7 @@
//! `.gitignore` subset documented in
//! `docs/features/parallel-files/README.md`.
use std::collections::HashSet;
use std::path::{Path, PathBuf};
/// File extensions lucisv formats when walking a directory.
@@ -10,20 +11,56 @@ pub const EXTENSIONS: &[&str] = &["v", "sv", "vh", "svh"];
/// The name of the per-directory ignore file that is honoured by default.
const GITIGNORE: &str = ".gitignore";
/// Something the walk could not do and went on regardless: a directory it
/// could not read, an ignore file it could not open, a source file that is
/// only a broken link.
///
/// The walk's warning channel exists because none of these is worth failing a
/// run over — one unreadable directory used to drop every file already found
/// — and because a silent skip loses the user the fact entirely. Rendering is
/// the front end's job: the CLI writes `warning: <path>: <message>` to stderr,
/// the server logs the same text once per scan.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Warning {
/// What could not be used.
pub path: PathBuf,
/// Why, in the operating system's own words where there are any.
pub message: String,
}
impl std::fmt::Display for Warning {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.path.display(), self.message)
}
}
/// Adds `input` to `files`: the file itself, or every Verilog file under
/// it if it is a directory. Exclude patterns and `.gitignore` rules apply
/// to directory walks only — a path named on the command line is always
/// formatted.
///
/// `warn` is called once for everything the walk skipped and wants said; see
/// [`Warning`]. Only `input` itself naming nothing is an error — that is the
/// user's own typo, and the run has nothing to do.
pub fn collect_files(
input: &str,
exclude: &[String],
gitignore: bool,
files: &mut Vec<PathBuf>,
warn: &mut dyn FnMut(Warning),
) -> Result<(), String> {
let path = Path::new(input);
if path.is_dir() {
let mut walk = Walk { exclude, gitignore, ignores: Vec::new(), rel: Vec::new(), files };
walk.dir(path).map_err(|e| format!("{input}: {e}"))?;
let mut walk = Walk {
exclude,
gitignore,
ignores: Vec::new(),
rel: Vec::new(),
visited: HashSet::new(),
files,
warn,
};
walk.dir(path);
} else if path.is_file() {
files.push(path.to_path_buf());
} else {
@@ -32,57 +69,166 @@ pub fn collect_files(
Ok(())
}
/// How a directory is recognised as one the walk has already entered. Two
/// names for the same directory — a symlink and its target, or two symlinks
/// pointing at one place — must map to the same identity, or a cycle has no
/// end. On unix that is `(dev, ino)`, the pair the filesystem itself uses;
/// elsewhere it is the canonical path, which resolves symlinks the same way
/// at the cost of a real path lookup.
#[cfg(unix)]
type DirId = (u64, u64);
#[cfg(not(unix))]
type DirId = PathBuf;
/// The identity of the directory at `path`, or `None` when it cannot be
/// read — a dangling symlink, or a directory that vanished mid-walk.
#[cfg(unix)]
fn dir_id(path: &Path) -> Option<DirId> {
use std::os::unix::fs::MetadataExt;
let meta = std::fs::metadata(path).ok()?;
Some((meta.dev(), meta.ino()))
}
#[cfg(not(unix))]
fn dir_id(path: &Path) -> Option<DirId> {
std::fs::canonicalize(path).ok()
}
/// True when `path` names one of the source files lucisv formats.
fn is_source(path: &Path) -> bool {
path.extension().and_then(|e| e.to_str()).is_some_and(|ext| EXTENSIONS.contains(&ext))
}
/// One directory walk. `rel` is the path of the directory currently being
/// read, in components relative to the walk root, which is what
/// `.gitignore` rules are matched against; `ignores` is the stack of
/// ignore files seen from the root down to it.
/// ignore files seen from the root down to it; `visited` is every directory
/// already entered, by identity rather than by spelling.
struct Walk<'a> {
exclude: &'a [String],
gitignore: bool,
ignores: Vec<Ignore>,
rel: Vec<String>,
visited: HashSet<DirId>,
files: &'a mut Vec<PathBuf>,
warn: &'a mut dyn FnMut(Warning),
}
impl Walk<'_> {
fn dir(&mut self, dir: &Path) -> std::io::Result<()> {
let pushed = self.push_ignore(dir)?;
let mut entries: Vec<_> = std::fs::read_dir(dir)?.collect::<Result<_, _>>()?;
fn dir(&mut self, dir: &Path) {
if !self.enter(dir) {
return;
}
let pushed = self.push_ignore(dir);
self.entries(dir);
if pushed {
self.ignores.pop();
}
}
/// One directory's entries, in name order. A directory that cannot be read
/// — the permission-denied one somewhere under the start — is said and
/// skipped: everything already found stays found and the walk goes on,
/// which is the whole reason this channel exists.
fn entries(&mut self, dir: &Path) {
let read = match std::fs::read_dir(dir) {
Ok(read) => read,
Err(e) => return self.say(dir, e.to_string()),
};
let mut entries = Vec::new();
for entry in read {
match entry {
Ok(entry) => entries.push(entry),
Err(e) => self.say(dir, e.to_string()),
}
}
entries.sort_by_key(|e| e.path());
for entry in entries {
let path = entry.path();
if is_excluded(&path, self.exclude) {
continue;
}
let is_dir = path.is_dir();
// One `metadata` call per entry, exactly as before — it follows
// symlinks, so it answers "directory?" for a symlinked directory
// the way `is_dir()` did. A dangling symlink has no metadata at
// all. One that *names a source file* is warned about and dropped:
// §43's QA was right that a silent skip loses the user the fact,
// and §45.2 gives that fact a home of its own rather than handing
// the path on to fail as "no such file" in the front end. One that
// names anything else was never going to be read, and is skipped
// as quietly as it always was.
let Ok(meta) = std::fs::metadata(&path) else {
if is_source(&path) {
let why = broken_link_reason(&path);
self.say(&path, why);
}
continue;
};
self.rel.push(entry.file_name().to_string_lossy().into_owned());
if !is_ignored(&self.ignores, &self.rel, is_dir) {
if is_dir {
self.dir(&path)?;
} else if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
if EXTENSIONS.contains(&ext) {
self.files.push(path);
}
if !is_ignored(&self.ignores, &self.rel, meta.is_dir()) {
if meta.is_dir() {
self.dir(&path);
} else if meta.is_file() && is_source(&path) {
self.files.push(path);
}
}
self.rel.pop();
}
if pushed {
self.ignores.pop();
}
Ok(())
}
/// Hand one warning to the front end.
fn say(&mut self, path: &Path, message: String) {
(self.warn)(Warning { path: path.to_path_buf(), message });
}
/// Records `dir` as entered, and answers whether it had not been entered
/// already. Identity, not spelling: `a/loop -> a` and `a/b/up -> ..` name
/// a directory the walk is already inside, and following either is the
/// cycle that only ends when the OS refuses a path. A symlink to a
/// directory the walk has *not* seen is followed once, so
/// `rtl -> ../shared/rtl` still contributes its files; the second link to
/// one target contributes nothing further, and the files are reported
/// under the first spelling that reached them.
///
/// A directory whose identity cannot be read is not entered.
fn enter(&mut self, dir: &Path) -> bool {
dir_id(dir).is_some_and(|id| self.visited.insert(id))
}
/// Reads `dir`'s `.gitignore`, if there is one, onto the rule stack.
/// Returns whether anything was pushed, so `dir` can pop it again.
fn push_ignore(&mut self, dir: &Path) -> std::io::Result<bool> {
///
/// An ignore file that cannot be read is said and ignored, for the same
/// reason an unreadable directory is: the walk that finds too much is a
/// better failure than the walk that finds nothing.
fn push_ignore(&mut self, dir: &Path) -> bool {
let path = dir.join(GITIGNORE);
if !self.gitignore || !path.is_file() {
return Ok(false);
return false;
}
let rules = parse_gitignore(&std::fs::read_to_string(&path)?);
self.ignores.push(Ignore { base: self.rel.len(), rules });
Ok(true)
match std::fs::read_to_string(&path) {
Ok(text) => {
self.ignores.push(Ignore { base: self.rel.len(), rules: parse_gitignore(&text) });
true
}
Err(e) => {
self.say(&path, e.to_string());
false
}
}
}
}
/// Why a directory entry has no metadata, said the way a person would.
///
/// A broken symbolic link is what this is nearly always about, and naming it
/// as one is worth more than the bare `No such file or directory` the follow
/// produced; anything else keeps the operating system's own words.
fn broken_link_reason(path: &Path) -> String {
match std::fs::symlink_metadata(path) {
Ok(meta) if meta.file_type().is_symlink() => "broken symbolic link".to_string(),
Ok(_) => "cannot be read".to_string(),
Err(e) => e.to_string(),
}
}
@@ -214,6 +360,8 @@ fn glob_component(pattern: &str, name: &str) -> bool {
#[cfg(test)]
mod tests {
use super::*;
#[cfg(unix)]
use std::sync::atomic::{AtomicUsize, Ordering};
fn excluded(path: &str, pattern: &str) -> bool {
is_excluded(Path::new(path), &[pattern.to_string()])
@@ -320,6 +468,218 @@ mod tests {
assert!(!ignored_at(&[(0, "/x.sv")], "sub/x.sv"));
}
// ------------------------------------------------------------------
// Symlink cycles — `docs/features/walk-cycles/README.md`
//
// Every test below builds a real tree with real symlinks, because the
// question is what the filesystem answers, not what a mock does. Each
// one would run until the OS refused a path before the visited set.
// ------------------------------------------------------------------
/// A throwaway directory tree under the system temp dir, removed on
/// drop. `remove_dir_all` unlinks a symlink instead of following it, so
/// a tree with a cycle in it is cleaned up like any other.
#[cfg(unix)]
struct TempTree {
path: PathBuf,
}
#[cfg(unix)]
impl TempTree {
fn new(tag: &str) -> TempTree {
static COUNTER: AtomicUsize = AtomicUsize::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let path =
std::env::temp_dir().join(format!("lucisv-walk-{}-{tag}-{n}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).expect("create temp dir");
TempTree { path }
}
fn write(&self, rel: &str, text: &str) {
let path = self.path.join(rel);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).expect("create parent");
}
std::fs::write(&path, text).expect("write");
}
/// A source file with enough in it to be worth finding.
fn source(&self, rel: &str) {
self.write(rel, "module m;\nendmodule\n");
}
/// Set `rel`'s permission bits. `0o000` is how a test builds the
/// directory the walk cannot read; the test puts them back so the
/// temp tree can be removed.
fn chmod(&self, rel: &str, mode: u32) {
use std::os::unix::fs::PermissionsExt;
let path = self.path.join(rel);
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode))
.expect("set permissions");
}
/// `rel` as a symlink to `target`, which is relative to `rel`'s own
/// directory — the spelling a checked-in symlink actually uses.
fn link(&self, rel: &str, target: &str) {
let path = self.path.join(rel);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).expect("create parent");
}
std::os::unix::fs::symlink(target, &path).expect("symlink");
}
/// The walk from `rel` (empty for the root), as sorted paths
/// relative to the tree root. Warnings are dropped; the tests that
/// care about them call [`TempTree::warned`].
fn walk(&self, rel: &str) -> Vec<String> {
self.walked(rel).0
}
/// The same, plus what the walk said, each warning's path made
/// relative to the tree root so the assertions read.
fn warned(&self, rel: &str) -> (Vec<String>, Vec<String>) {
self.walked(rel)
}
fn walked(&self, rel: &str) -> (Vec<String>, Vec<String>) {
let start = if rel.is_empty() { self.path.clone() } else { self.path.join(rel) };
let mut files = Vec::new();
let mut warnings = Vec::new();
collect_files(
start.to_str().expect("utf-8 temp path"),
&[],
true,
&mut files,
&mut |w| warnings.push(format!("{}: {}", self.rel_of(&w.path), w.message)),
)
.expect("the walk finishes");
let mut out: Vec<String> = files.iter().map(|p| self.rel_of(p)).collect();
out.sort();
warnings.sort();
(out, warnings)
}
fn rel_of(&self, path: &Path) -> String {
path.strip_prefix(&self.path).unwrap_or(path).to_string_lossy().into_owned()
}
}
#[test]
#[cfg(unix)]
fn a_directory_linking_to_itself_is_entered_once() {
let tree = TempTree::new("selfloop");
tree.source("a/x.sv");
tree.link("a/loop", "../a");
assert_eq!(tree.walk(""), ["a/x.sv"]);
}
#[test]
#[cfg(unix)]
fn a_link_to_an_ancestor_terminates_from_a_nested_start() {
let tree = TempTree::new("uplink");
tree.source("root.sv");
tree.source("a/x.sv");
tree.link("a/up", "..");
// Starting *inside* the cycle: `a` is entered, then `a/up` is the
// root, which the walk has not seen yet and so does enter — once.
// Its own `a` is the directory already being walked, and stops.
assert_eq!(tree.walk("a"), ["a/up/root.sv", "a/x.sv"]);
}
#[test]
#[cfg(unix)]
fn two_links_to_one_directory_yield_its_files_once() {
let tree = TempTree::new("twolinks");
tree.source("shared/x.sv");
// Sorted after `shared`, so the real directory is the spelling that
// reaches the file first; whichever name wins, the file is reported
// exactly once.
tree.link("z1", "shared");
tree.link("z2", "shared");
assert_eq!(tree.walk(""), ["shared/x.sv"]);
}
#[test]
#[cfg(unix)]
fn a_link_to_a_directory_not_yet_walked_is_still_followed() {
let tree = TempTree::new("sibling");
tree.source("shared/rtl/x.sv");
tree.link("proj/rtl", "../shared/rtl");
// The `rtl -> ../shared/rtl` of a real checkout: the target is
// outside the walk, so the link is the only way to it.
assert_eq!(tree.walk("proj"), ["proj/rtl/x.sv"]);
}
#[test]
#[cfg(unix)]
fn a_dangling_source_link_is_warned_about_and_not_handed_on() {
// §43's review kept the dangling source link in the file list so the
// front end's "no such file" error survived. TODO §45.2 reverses that
// on purpose: the warning is now the error's home, so the link is said
// once here and never reaches the formatter. A dangling link that
// names no source file was never going to be read and stays silent.
let tree = TempTree::new("dangling");
tree.source("a/x.sv");
tree.link("a/gone.sv", "nowhere.sv");
tree.link("a/gonedir", "nowhere");
let (files, warnings) = tree.warned("");
assert_eq!(files, ["a/x.sv"]);
assert_eq!(warnings, ["a/gone.sv: broken symbolic link"]);
}
#[test]
#[cfg(unix)]
fn an_unreadable_directory_is_skipped_and_the_walk_goes_on() {
// The finding this channel exists for: one permission-denied directory
// used to propagate `read_dir`'s error out of the whole walk, dropping
// every file already found and failing the run.
let tree = TempTree::new("unreadable");
tree.source("a.sv");
tree.source("locked/hidden.sv");
tree.source("z/late.sv");
tree.chmod("locked", 0o000);
let (files, warnings) = tree.warned("");
tree.chmod("locked", 0o755);
assert_eq!(files, ["a.sv", "z/late.sv"], "the walk finished");
assert_eq!(warnings.len(), 1, "{warnings:?}");
assert!(warnings[0].starts_with("locked: "), "the warning names it: {warnings:?}");
}
#[test]
#[cfg(unix)]
fn an_unreadable_ignore_file_is_said_and_the_directory_is_still_walked() {
let tree = TempTree::new("lockedignore");
tree.write(".gitignore", "build\n");
tree.source("keep.sv");
tree.chmod(".gitignore", 0o000);
let (files, warnings) = tree.warned("");
tree.chmod(".gitignore", 0o644);
assert_eq!(files, ["keep.sv"]);
assert_eq!(warnings.len(), 1, "{warnings:?}");
assert!(warnings[0].starts_with(".gitignore: "), "{warnings:?}");
}
#[test]
#[cfg(unix)]
fn a_clean_walk_says_nothing() {
let tree = TempTree::new("quiet");
tree.source("a/x.sv");
tree.source("b/y.sv");
assert_eq!(tree.warned(""), (vec!["a/x.sv".to_string(), "b/y.sv".to_string()], Vec::new()));
}
#[test]
#[cfg(unix)]
fn a_cycle_inside_an_ignored_directory_is_never_entered() {
let tree = TempTree::new("ignoredcycle");
tree.write(".gitignore", "build\n");
tree.source("keep.sv");
tree.source("build/y.sv");
tree.link("build/loop", "../build");
assert_eq!(tree.walk(""), ["keep.sv"]);
}
#[test]
fn unsupported_syntax_degrades_to_plain_globbing() {
// `**` is just two stars inside one component; documented.
+61 -3
View File
@@ -14,7 +14,7 @@ use std::collections::HashSet;
use lsp_types::CompletionResponse;
use vlog_parser::token::{Token, TokenKind};
use vlog_semantic::{MemberSite, Semantics, SymbolKind, WorkspaceIndex};
use vlog_semantic::{MemberSite, Semantics, Surface, SymbolKind, WorkspaceIndex};
use super::site::balanced;
use super::tiers::innermost_scope;
@@ -168,6 +168,14 @@ fn members_at(
site: &MemberSite,
) -> Vec<Member> {
let mut members = Members::new();
// A cross-file site says which surface its own tail resolution reads, and
// the list follows it: behind `u_x.` in an *expression* that is the
// module's hierarchical surface — its nets, variables and instances as
// well as its ports and parameters — which is exactly what the in-file
// `MemberSite::Scope` half above offers for an instance this file
// declares. A connection list's `.` never arrives here; it is
// `connection_members` below, and it is the connection surface.
let mut surface = Surface::Connection;
let base = match site {
MemberSite::Scope(scope) => {
let (scopes, base) = semantics.member_scopes(*scope);
@@ -181,10 +189,13 @@ fn members_at(
// overlay's own inheritance chase does.
base.map(|path| last_segment(&path).to_string())
}
MemberSite::Unit(unit) => Some(unit.clone()),
MemberSite::Unit { path, surface: reads } => {
surface = *reads;
Some(path.clone())
}
};
if let Some(unit) = base {
for (name, def) in index.members_of_chain(&unit) {
for (name, def) in index.members_of_chain_in(&unit, surface) {
members.push(name, def.kind, indexed_detail(def.kind, def.type_name.as_deref()));
}
}
@@ -983,6 +994,53 @@ endmodule
assert_eq!(clk.detail.as_deref(), Some("port"), "table-only across files");
}
/// **§49's completion decision, and its limit.** Behind `u_sub.` in an
/// *expression* the list is the module's **hierarchical** surface — its
/// nets, its variables and its instances as well as its ports and its
/// parameters — because that is what a hierarchical path may name and
/// exactly what the tail resolution will find, so every item offered is
/// an item hover and go-to-definition answer. Behind the `.` of a
/// **connection list** it is the connection surface and nothing more:
/// `.internal(w)` is not a legal connection, and an item the resolution
/// could not find is a wrong answer rather than a generous one.
#[test]
fn an_instance_head_lists_the_hierarchical_surface_and_a_connection_list_does_not() {
const SUB: &str = "module sub (input logic clk);\n wire internal;\n int counter;\n leaf u_leaf ();\nendmodule\n";
let hierarchical = {
let tree = Tree::new("hiersurface_expr");
tree.write("sub.sv", SUB);
tree.write("leaf.sv", "module leaf;\nendmodule\n");
let top = "module top;\n sub u_sub ();\n initial y = u_sub.;\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "= u_sub.");
let mut found = labels(&items(completions(&ws, &uri, position, true)))
.iter()
.map(|l| l.to_string())
.collect::<Vec<_>>();
found.sort();
found
};
assert_eq!(
hierarchical,
vec!["clk", "counter", "internal", "u_leaf"],
"the port and the three hierarchical-only members"
);
let connection = {
let tree = Tree::new("hiersurface_conn");
tree.write("sub.sv", SUB);
tree.write("leaf.sv", "module leaf;\nendmodule\n");
let top = "module top;\n sub u_sub (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " .");
let mut found = labels(&items(completions(&ws, &uri, position, true)))
.iter()
.map(|l| l.to_string())
.collect::<Vec<_>>();
found.sort();
found
};
assert_eq!(connection, vec!["clk"], "the connection list is the port list, unchanged");
}
#[test]
fn an_interface_instance_lists_its_ports_too() {
let tree = Tree::new("ifaceconn");
+120 -28
View File
@@ -10,6 +10,16 @@
//! table `lucisv.toml` now carries. See
//! `docs/features/semantic-lints-on/README.md` and
//! `docs/features/server-lint/README.md`.
//!
//! Since §42 the two halves of that selection are one contract: the editor's
//! settings play the role the CLI's flags play, and the project's `[lint]`
//! table is what stands when the editor says nothing —
//! `docs/features/lint-config-contract/README.md`, and [`project`] for the
//! project's half.
mod project;
pub use project::{ConfigProblems, ProblemLog, ProjectLint};
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
@@ -47,6 +57,10 @@ pub struct LintRun<'a> {
/// `lucisv.toml` and from `lucisv.lint.waivers`. Empty unless one is
/// configured, and then costing the pass nothing.
external: ExternalWaivers,
/// What the buffer's `lucisv.toml` asked for and did not get. Reported by
/// whoever can talk to the client — [`ProblemLog`] keeps it to once per
/// (config file, message) — and never fatal here: §42.2.
problems: ConfigProblems,
}
impl Default for LintRun<'_> {
@@ -57,6 +71,7 @@ impl Default for LintRun<'_> {
options: RuleOptions::new(),
line_length: DEFAULT_LINE_LENGTH,
external: ExternalWaivers::default(),
problems: ConfigProblems::default(),
}
}
}
@@ -78,11 +93,28 @@ impl<'a> LintRun<'a> {
let index = ws.index();
let own = doc.path.as_deref().and_then(|path| index.file_id(path));
let workspace = index.files().len() > usize::from(own.is_some());
let rules = enabled_rules(ws.client_settings(), workspace);
let oracle = workspace.then_some(IndexMentions { index, own });
let (options, line_length, file) = configured(ws.client_settings(), doc);
let external = external_waivers(&waiver_paths(ws.client_settings(), ws.roots(), &file)).0;
LintRun { rules, oracle, options, line_length, external }
// One discovery for the whole pass: the selection, the options, the
// width and the waiver paths all read the same `FileConfig`, so
// reading the project's rules costs no extra stat and no extra open.
let (options, line_length, file, mut messages) = configured(ws.client_settings(), doc);
let (from_file, bad_names) = ProjectLint::read(&file);
messages.extend(bad_names);
let rules = enabled_rules(ws.client_settings(), &from_file, workspace);
let (mut external, bad_waivers) = external_waivers(&project_waivers(&file));
messages.extend(bad_waivers);
// The editor's own waiver files are read separately and their
// problems dropped: `notification::apply_settings` already said them
// once, where the setting arrived.
external.absorb(external_waivers(&editor_waivers(ws.client_settings(), ws.roots())).0);
let problems = ConfigProblems::new(&file, messages);
LintRun { rules, oracle, options, line_length, external, problems }
}
/// What this buffer's `lucisv.toml` asked for and did not get, for a
/// caller that can tell the user about it.
pub fn config_problems(&self) -> &ConfigProblems {
&self.problems
}
/// A run carrying these external waivers — for the tests that pin what a
@@ -125,23 +157,33 @@ impl<'a> LintRun<'a> {
/// reads it per formatting request: a `lucisv.toml` edited while the server
/// runs takes effect at the next publish, and the read is a few stats beside
/// a parse and an analysis the same pass already paid for.
fn configured(client: &ClientSettings, doc: &Document) -> (RuleOptions, usize, FileConfig) {
fn configured(
client: &ClientSettings,
doc: &Document,
) -> (RuleOptions, usize, FileConfig, Vec<String>) {
let file = doc
.path
.as_deref()
.and_then(|path| lucisv_core::config::Discovery::new(true).for_file(path).ok())
.unwrap_or_default();
let mut options = RuleOptions::new();
let mut problems = Vec::new();
for entry in &file.lint_options {
// A broken entry in the file is dropped here rather than reported:
// `format::settings_for` already surfaces a `lucisv.toml` problem to
// the user, and `lucisv check` fails the run over it with file and
// line, which is where a config error belongs.
let _ = options.set_raw(&entry.rule, &entry.key, &entry.raw);
// A broken entry in the file is dropped rather than fatal — an editor
// cannot fail a run — but it is *said*, in the words `lucisv check`
// fails with, once per (config file, entry): §42.2. Silently dropping
// it left a user's option doing nothing with nothing to read about it.
if let Err(problem) = options.set_raw(&entry.rule, &entry.key, &entry.raw) {
let source = file
.source
.as_ref()
.map_or_else(|| "lucisv.toml".to_string(), |path| path.display().to_string());
problems.push(format!("{source}:{}: rule `{}` {problem}", entry.line, entry.rule));
}
}
options.overlay(&client.lint_options);
let width = file.line_length.or(client.line_length).unwrap_or(DEFAULT_LINE_LENGTH);
(options, width, file)
(options, width, file, problems)
}
/// The waiver files governing one buffer: its `lucisv.toml`'s `[lint] waivers`
@@ -153,17 +195,38 @@ fn configured(client: &ClientSettings, doc: &Document) -> (RuleOptions, usize, F
/// first workspace root, exactly as `lucisv.filelist` is; a `lucisv.toml`'s
/// paths were already resolved against that file's own directory.
pub fn waiver_paths(client: &ClientSettings, roots: &[PathBuf], file: &FileConfig) -> Vec<PathBuf> {
let mut paths: Vec<PathBuf> = file.lint_waivers.iter().flatten().cloned().collect();
for setting in &client.lint_waivers {
let path = Path::new(setting);
paths.push(match roots.first() {
Some(root) if path.is_relative() => root.join(path),
_ => path.to_path_buf(),
});
}
let mut paths = project_waivers(file);
paths.extend(editor_waivers(client, roots));
paths
}
/// The `[lint] waivers` of one config file, already resolved by `Discovery`
/// against that file's own directory.
///
/// Read apart from the editor's since §42.2, because a problem in one of
/// *these* is the project's and belongs in the output channel with the
/// `lucisv.toml` that named it, while a problem in the editor's was already
/// said where the setting arrived.
fn project_waivers(file: &FileConfig) -> Vec<PathBuf> {
file.lint_waivers.iter().flatten().cloned().collect()
}
/// The waiver files `lucisv.lint.waivers` names, a relative one anchored at
/// the first workspace root exactly as `lucisv.filelist` is.
fn editor_waivers(client: &ClientSettings, roots: &[PathBuf]) -> Vec<PathBuf> {
client
.lint_waivers
.iter()
.map(|setting| {
let path = Path::new(setting);
match roots.first() {
Some(root) if path.is_relative() => root.join(path),
_ => path.to_path_buf(),
}
})
.collect()
}
/// Those files, read: the waivers and one message per file or line that could
/// not be used.
///
@@ -188,32 +251,45 @@ pub fn external_waivers(paths: &[PathBuf]) -> (ExternalWaivers, Vec<String>) {
(waivers, problems)
}
/// Which rules a buffer is linted with, given what the editor's settings say.
/// Which rules a buffer is linted with, given what the editor's settings and
/// the buffer's own `lucisv.toml` say.
///
/// **The one ladder**, top rung last — every rung may undo the one above it:
///
/// 1. the base set is what the rules themselves declare: `default_on`, plus
/// the `needs_workspace` rules when `has_oracle`;
/// 2. a non-empty `lucisv.lint.select` **replaces** that base set, exactly as
/// `--select` replaces it on the command line;
/// `--select` replaces it on the command line; when the editor names
/// nothing, the project's `[lint] select` replaces it instead — the flag
/// when there is one, else the file, which is `lucisv check`'s own `pick`;
/// 3. a `lucisv.lint.severity.<class>` switched off **removes** every rule of
/// that class;
/// 4. a `lucisv.lint.rules.<name>` set to `on` or `off` sets or clears that
/// one rule — the per-rule word beats the class word, which is what makes
/// "all style off except `no-tabs`" expressible;
/// 5. `lucisv.lint.ignore` **removes** — the off switch of last resort, the
/// one a user reaches for when nothing else worked.
/// one a user reaches for when nothing else worked; when the editor names
/// nothing there either, the project's `[lint] ignore` removes instead.
///
/// Rungs 2 and 5 accept a severity word wherever a rule name fits.
pub fn enabled_rules(settings: &ClientSettings, has_oracle: bool) -> Vec<&'static dyn Rule> {
let base = if settings.lint_select.is_empty() {
/// Rungs 3 and 4 are the **editor's alone**: a `lucisv.toml` has no such
/// keys, and the command line has no such flags. Rungs 2 and 5 are decided
/// independently — a project that selects and a user who only ignores keep
/// both halves. Every list accepts a severity word wherever a rule name fits,
/// the project's as much as the editor's.
pub fn enabled_rules(
settings: &ClientSettings,
project: &ProjectLint,
has_oracle: bool,
) -> Vec<&'static dyn Rule> {
let select = pick(&settings.lint_select, &project.select);
let base = if select.is_empty() {
if has_oracle {
workspace_rules()
} else {
default_rules()
}
} else {
named(&settings.lint_select)
named(select)
};
let mut on: BTreeSet<&'static str> = base.iter().map(|rule| rule.name()).collect();
@@ -232,12 +308,22 @@ pub fn enabled_rules(settings: &ClientSettings, has_oracle: bool) -> Vec<&'stati
on.remove(rule.name());
}
}
for rule in named(&settings.lint_ignore) {
for rule in named(pick(&settings.lint_ignore, &project.ignore)) {
on.remove(rule.name());
}
vlog_linter::all_rules().into_iter().filter(|rule| on.contains(rule.name())).collect()
}
/// The editor's list when it said anything, else the project's — the twin of
/// `lucisv/src/lint.rs`'s `pick`, which is the whole of §42's contract.
fn pick<'a>(editor: &'a [String], project: &'a [String]) -> &'a [String] {
if editor.is_empty() {
project
} else {
editor
}
}
/// Every rule a list of `--select`-style words names, unknown words skipped —
/// they were already dropped when the settings were parsed, and a name that
/// survived that filter always resolves.
@@ -619,8 +705,14 @@ mod tests {
/// be true of the result).
#[test]
fn the_enabled_rules_ladder_is_the_documented_one() {
// The project's half of the ladder is `lint::project`'s own table
// test; this one holds it empty, which is the editor-only ladder
// §33.1 wrote.
let names = |settings: &ClientSettings, oracle: bool| -> Vec<&'static str> {
enabled_rules(settings, oracle).into_iter().map(|rule| rule.name()).collect()
enabled_rules(settings, &ProjectLint::default(), oracle)
.into_iter()
.map(|rule| rule.name())
.collect()
};
let with = |f: &dyn Fn(&mut ClientSettings)| {
let mut settings = ClientSettings::default();
+398
View File
@@ -0,0 +1,398 @@
//! What a buffer's `lucisv.toml` says about linting, and what could not be
//! used from it.
//!
//! The contract (§42): **the editor's settings play the role the CLI's flags
//! play**. `lucisv check` picks the flag when one was given and the project
//! file otherwise (`lucisv/src/lint.rs`'s `pick`); the server picks
//! `lucisv.lint.select` when it is non-empty and `[lint] select` otherwise,
//! key by key, so one buffer linted two ways is linted the same way. See
//! `docs/features/lint-config-contract/README.md`.
use std::collections::hash_map::DefaultHasher;
use std::collections::{BTreeSet, HashMap};
use std::hash::{Hash, Hasher};
use std::path::PathBuf;
use lucisv_core::config::FileConfig;
/// The selection a buffer's `lucisv.toml` carries: `[lint] select` and
/// `[lint] ignore`, exactly as `--select` and `--ignore` carry them.
///
/// [`ProjectLint::default`] — both lists empty — is a buffer with no config
/// file, or one whose `[lint]` table says nothing about rules: the editor's
/// settings and the base set then decide everything, which is what this
/// server did before §42.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct ProjectLint {
/// `[lint] select`: run exactly these rules, replacing the base set —
/// unless the editor named some, which outranks it.
pub select: Vec<String>,
/// `[lint] ignore`: rules dropped from whatever `select` left — unless
/// the editor named some.
pub ignore: Vec<String>,
}
impl ProjectLint {
/// One config file's selection, with every name the registry does not
/// know dropped and reported.
///
/// `lucisv check` *fails the run* over an unknown name, which an editor
/// cannot do — but it must not silently obey a typo either: a
/// `select = ["no-tab"]` taken at face value would resolve to no rules at
/// all and blank the file's squiggles, which reads as "lucisv is happy"
/// rather than "lucisv could not understand your config". So the name is
/// dropped, said once, and the rest of the list still applies; a `select`
/// left empty by the dropping falls back to the base set.
pub fn read(file: &FileConfig) -> (ProjectLint, Vec<String>) {
let mut problems = Vec::new();
let select = known(file, "select", file.lint_select.as_deref(), &mut problems);
let ignore = known(file, "ignore", file.lint_ignore.as_deref(), &mut problems);
(ProjectLint { select, ignore }, problems)
}
}
/// The names of one `[lint]` list that name something, the others reported.
fn known(
file: &FileConfig,
key: &str,
list: Option<&[String]>,
problems: &mut Vec<String>,
) -> Vec<String> {
let mut kept = Vec::new();
for name in list.unwrap_or(&[]) {
if vlog_linter::rules_named(name).is_some() {
kept.push(name.clone());
} else {
// No line number: `lucisv_core::config` records one per
// `[lint.<rule>]` entry, because those are checked one by one,
// and the list keys are one value each.
problems.push(format!("{}: [lint] {key}: unknown rule: {name}", source_of(file)));
}
}
kept
}
/// The config file's path as an error should name it.
fn source_of(file: &FileConfig) -> String {
file.source.as_ref().map_or_else(|| "lucisv.toml".to_string(), |p| p.display().to_string())
}
/// What one buffer's `lucisv.toml` asked for and did not get: a
/// `[lint.<rule>]` entry the registry refused, a name in `[lint] select` that
/// is not a rule, a `[lint] waivers` file that is not there or holds a
/// directive that does not parse.
///
/// Every message is written the way `lucisv check` writes it —
/// `<file>:<line>: <message>` — so the same mistake reads the same in CI and
/// in an editor's output channel. **Nothing here is fatal**: the entry is
/// dropped and the buffer is still linted with everything that was
/// understood, because a server cannot fail a run the way a command can.
#[derive(Debug, Default, Clone)]
pub struct ConfigProblems {
/// The config file they came from. `None` — no config file was found —
/// means there is nothing to complain about and `messages` is empty.
source: Option<PathBuf>,
/// A stamp of that file's lint content, so an edited config gets a fresh
/// hearing: see [`ProblemLog`].
stamp: u64,
/// The messages, in file order.
messages: Vec<String>,
}
impl ConfigProblems {
/// The problems found in this config file.
pub fn new(file: &FileConfig, messages: Vec<String>) -> ConfigProblems {
ConfigProblems { source: file.source.clone(), stamp: stamp_of(file), messages }
}
/// Whether anything at all could not be used.
pub fn is_empty(&self) -> bool {
self.messages.is_empty()
}
}
/// A stamp over everything in a config file that [`ConfigProblems`] can be
/// about, so that editing the file re-arms the report and editing a source
/// beside it does not.
///
/// A hash rather than a modification time: the file is re-read on every lint
/// pass anyway (`configured`), and a hash of what was parsed cannot be fooled
/// by a filesystem whose timestamps are coarse.
fn stamp_of(file: &FileConfig) -> u64 {
let mut hasher = DefaultHasher::new();
file.lint_select.hash(&mut hasher);
file.lint_ignore.hash(&mut hasher);
file.lint_waivers.hash(&mut hasher);
for entry in &file.lint_options {
entry.rule.hash(&mut hasher);
entry.key.hash(&mut hasher);
entry.raw.hash(&mut hasher);
entry.line.hash(&mut hasher);
}
hasher.finish()
}
/// Which config problems have already been said, so each is said **once**.
///
/// Once per (config file, message), not once per lint pass: the pass runs on
/// every keystroke and every index rebuild, and a hundred copies of one line
/// in the output channel is not a report, it is noise. The editor-settings
/// path has said its own problems once since §34 — this is the same promise
/// for the file a project checks in.
///
/// A config file whose lint content changed clears its own memo, so a user
/// who edits `lucisv.toml` and gets it wrong again is told again. The memo is
/// keyed by path, so it holds one small entry per config file a session ever
/// linted through.
#[derive(Debug, Default)]
pub struct ProblemLog {
said: HashMap<PathBuf, Said>,
}
/// One config file's memo: the content it was taken under, and what was said.
#[derive(Debug, Default)]
struct Said {
stamp: u64,
messages: BTreeSet<String>,
}
impl ProblemLog {
/// The messages that have not been said yet for this config file, marked
/// as said. An empty answer means the user has already been told.
pub fn unsaid(&mut self, problems: &ConfigProblems) -> Vec<String> {
let Some(source) = problems.source.clone() else { return Vec::new() };
if problems.is_empty() {
return Vec::new();
}
let said = self.said.entry(source).or_default();
if said.stamp != problems.stamp {
said.stamp = problems.stamp;
said.messages.clear();
}
problems
.messages
.iter()
.filter(|message| said.messages.insert((*message).clone()))
.cloned()
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::settings::ClientSettings;
use crate::state::{Document, Workspace};
use lsp_types::Uri;
use std::str::FromStr;
use vlog_linter::Severity;
fn config(text: &str) -> FileConfig {
let mut file = lucisv_core::config::parse(text).expect("the config parses");
file.source = Some(PathBuf::from("/rtl/lucisv.toml"));
file
}
fn names(settings: &ClientSettings, project: &ProjectLint, oracle: bool) -> Vec<&'static str> {
super::super::enabled_rules(settings, project, oracle)
.into_iter()
.map(|rule| rule.name())
.collect()
}
fn editor(select: &[&str], ignore: &[&str]) -> ClientSettings {
ClientSettings {
lint_select: select.iter().map(|s| (*s).to_string()).collect(),
lint_ignore: ignore.iter().map(|s| (*s).to_string()).collect(),
..ClientSettings::default()
}
}
fn project(select: &[&str], ignore: &[&str]) -> ProjectLint {
ProjectLint {
select: select.iter().map(|s| (*s).to_string()).collect(),
ignore: ignore.iter().map(|s| (*s).to_string()).collect(),
}
}
/// §42.1's table: every combination of {toml select, editor select} ×
/// {toml ignore, editor ignore}, against the ladder. The editor's list
/// wins when it says anything, the project's is used when it does not,
/// and the two keys are decided **independently** — the CLI's `pick`,
/// applied twice.
#[test]
fn the_editor_outranks_the_project_key_by_key() {
// Four rules stand in for the whole registry: two the project may
// name and two the editor may, so a row's answer says which list was
// consulted rather than which happened to be shorter.
// (toml select, editor select, toml ignore, editor ignore, expected).
type Row = (
&'static [&'static str],
&'static [&'static str],
&'static [&'static str],
&'static [&'static str],
&'static [&'static str],
);
let rows: [Row; 8] = [
// (toml select, editor select, toml ignore, editor ignore) => rules
(&[], &[], &[], &[], &[]),
(&["no-tabs"], &[], &[], &[], &["no-tabs"]),
(&[], &["no-tabs"], &[], &[], &["no-tabs"]),
(&["module-name-style"], &["no-tabs"], &[], &[], &["no-tabs"]),
(&["no-tabs", "module-name-style"], &[], &["no-tabs"], &[], &["module-name-style"]),
(&["no-tabs", "module-name-style"], &[], &[], &["no-tabs"], &["module-name-style"]),
(
&["no-tabs", "module-name-style"],
&[],
&["module-name-style"],
&["no-tabs"],
&["module-name-style"],
),
(
&["module-name-style"],
&["no-tabs", "module-name-style"],
&["no-tabs"],
&["module-name-style"],
&["no-tabs"],
),
];
for (toml_select, ed_select, toml_ignore, ed_ignore, want) in rows {
let settings = editor(ed_select, ed_ignore);
let from_file = project(toml_select, toml_ignore);
let got = names(&settings, &from_file, false);
if want.is_empty() {
// The empty row is the base set, which is too long to spell.
assert_eq!(
got,
super::super::default_rules().iter().map(|r| r.name()).collect::<Vec<_>>(),
"neither list said anything, so the base set stands"
);
} else {
assert_eq!(
got, want,
"{toml_select:?} {ed_select:?} {toml_ignore:?} {ed_ignore:?}"
);
}
}
}
/// A severity word stands for its whole class in the toml's lists exactly
/// as it does in the editor's, and as `--select style` does.
#[test]
fn a_severity_word_works_in_the_projects_lists_too() {
let styled = names(&ClientSettings::default(), &project(&["style"], &[]), true);
assert!(!styled.is_empty());
assert!(styled
.iter()
.all(|name| vlog_linter::rule_by_name(name).expect("a rule").severity()
== Severity::Style));
let quiet = names(&ClientSettings::default(), &project(&[], &["style"]), true);
assert!(!quiet.is_empty());
assert!(quiet
.iter()
.all(|name| vlog_linter::rule_by_name(name).expect("a rule").severity()
!= Severity::Style));
}
/// A rung 3 or 4 switch is the editor's alone, and still applies over a
/// selection the project made.
#[test]
fn the_editor_only_rungs_still_apply_over_a_project_selection() {
let mut settings = ClientSettings::default();
settings.lint_severity.insert(Severity::Style, false);
let from_file = project(&["no-tabs", "wire-reg-mixup"], &[]);
assert_eq!(
names(&settings, &from_file, false),
vec!["wire-reg-mixup"],
"the class switch removes the project's style rule"
);
settings.lint_rules.insert("no-tabs".to_string(), true);
assert_eq!(
names(&settings, &from_file, false),
vec!["no-tabs", "wire-reg-mixup"],
"and the per-rule word puts it back"
);
}
/// A name the registry does not know is dropped and reported — the run
/// `lucisv check` would have failed keeps going here with what was
/// understood.
#[test]
fn an_unknown_name_in_the_projects_list_is_dropped_and_said() {
let (from_file, problems) =
ProjectLint::read(&config("[lint]\nselect = [\"no-tab\", \"no-tabs\"]\n"));
assert_eq!(from_file.select, vec!["no-tabs"]);
assert_eq!(problems, vec!["/rtl/lucisv.toml: [lint] select: unknown rule: no-tab"]);
assert_eq!(names(&ClientSettings::default(), &from_file, false), vec!["no-tabs"]);
// Every name unknown leaves the list empty, which is the base set —
// the safe direction: some rules rather than none.
let (none, problems) = ProjectLint::read(&config("[lint]\nselect = [\"nope\"]\n"));
assert!(none.select.is_empty());
assert_eq!(problems.len(), 1);
assert_eq!(
names(&ClientSettings::default(), &none, false),
super::super::default_rules().iter().map(|r| r.name()).collect::<Vec<_>>()
);
}
/// §42.2: a `[lint.<rule>]` entry the registry refuses is reported once,
/// however many lint passes run, and the buffer keeps being linted.
#[test]
fn a_rejected_option_is_said_once_and_the_lint_still_runs() {
let dir = std::env::temp_dir()
.join(format!("lucisv_lint_project_{}_rejected", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("temp dir");
std::fs::write(dir.join("lucisv.toml"), "[lint.line-length]\nlength = \"wide\"\n")
.expect("write config");
let path = dir.join("m.sv");
let text = "module m;\n\twire a;\nendmodule\n";
std::fs::write(&path, text).expect("write source");
let uri = Uri::from_str(&format!("file://{}", path.display())).expect("uri");
let mut ws = Workspace::default();
ws.set_document(uri.clone(), text.to_string());
let mut log = ProblemLog::default();
let mut said = Vec::new();
for _ in 0..3 {
let doc: &Document = ws.document(&uri).expect("open");
let run = super::super::LintRun::for_document(&ws, doc);
// The lint still runs: the tab is still a finding.
assert!(
super::super::violations_in(doc, &run).iter().any(|v| v.rule == "no-tabs"),
"the buffer is still linted with the entry dropped"
);
said.extend(log.unsaid(run.config_problems()));
}
assert_eq!(said.len(), 1, "said once across three passes: {said:#?}");
let expected = format!("{}:2: rule `line-length` ", dir.join("lucisv.toml").display());
assert!(said[0].starts_with(&expected), "the wording `lucisv check` prints: {}", said[0]);
let _ = std::fs::remove_dir_all(&dir);
}
/// An edited config gets a fresh hearing: the memo is keyed by the file's
/// lint content, so the same mistake made again after a change is said
/// again.
#[test]
fn an_edited_config_re_arms_the_report() {
let first = config("[lint.line-length]\nlength = \"wide\"\n");
let problems = ConfigProblems::new(&first, vec!["/rtl/lucisv.toml:2: bad".to_string()]);
let mut log = ProblemLog::default();
assert_eq!(log.unsaid(&problems).len(), 1);
assert!(log.unsaid(&problems).is_empty(), "and not twice");
// Same message, different file content: the user has been editing.
let edited = config("# a comment\n[lint.line-length]\nlength = \"wide\"\n");
let again = ConfigProblems::new(&edited, vec!["/rtl/lucisv.toml:3: bad".to_string()]);
assert_eq!(log.unsaid(&again).len(), 1, "a changed config is heard again");
// A buffer with no config file has nothing to report.
let nowhere = ConfigProblems::new(&FileConfig::default(), vec!["never".to_string()]);
assert!(log.unsaid(&nowhere).is_empty());
}
}
+45
View File
@@ -552,6 +552,51 @@ mod tests {
assert_eq!(locations[0].range.start.line, 1);
}
/// A qualified type name is two references, each addressable on its own
/// half: the parser spans `pkg::t` and `DataType::segments` splits it, so
/// F12 on the *item* lands on the typedef rather than on the package.
#[test]
fn a_scoped_type_name_jumps_from_its_item_half() {
let text = "\
package pkg;
typedef logic [1:0] t;
endpackage
module m;
pkg::t x;
endmodule
";
let (ws, uri) = document(text);
let item = definition(&ws, &uri, at(text, "pkg::t x") + 5);
assert_eq!(item.len(), 1, "the typedef");
assert_eq!(item[0].range.start.line, 1, "the `typedef ... t;` line");
assert_eq!(item[0].range.start.character, 22, "the name `t`, not the keyword");
let unit = definition(&ws, &uri, at(text, "pkg::t x"));
assert_eq!(unit.len(), 1, "the package");
assert_eq!(unit[0].range.start.line, 0);
}
/// `bus_if.mp bus` — the interface is the type, so the head range is what
/// F12 answers from; the modport tail is a member of it.
#[test]
fn an_interface_port_type_jumps_from_its_head() {
let text = "\
interface bus_if;
logic clk;
modport mp (input clk);
endinterface
module m (bus_if.mp bus);
endmodule
";
let (ws, uri) = document(text);
let head = definition(&ws, &uri, at(text, "bus_if.mp bus") + 2);
assert_eq!(head.len(), 1, "the interface");
assert_eq!(head[0].range.start.line, 0);
assert_eq!(head[0].range.start.character, 10, "the interface name");
let tail = definition(&ws, &uri, at(text, "bus_if.mp bus") + 7);
assert_eq!(tail.len(), 1, "the modport");
assert_eq!(tail[0].range.start.line, 2);
}
#[test]
fn a_macro_use_jumps_to_its_define_in_the_same_file() {
let text = "`define WIDTH 8\nmodule m;\n logic [`WIDTH-1:0] a;\nendmodule\n";
+33 -2
View File
@@ -795,11 +795,16 @@ mod tests {
/// workspace was never consulted), so the file should not even be pulled
/// in — and if it were, the rename must still succeed, since no capture is
/// possible against a symbol nothing outside that file can see.
///
/// The symbol is a **function's** local, not a module's net: since
/// 2026-09-05 a net is a declaration on the module's hierarchical surface
/// and joins the fan-out by that rung (the test below), which would answer
/// this one for the wrong reason. A name inside a subprogram body is on
/// neither surface, which is what this attack needs.
#[test]
fn a_local_only_symbol_sharing_the_new_names_spelling_is_not_a_bogus_refusal() {
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
const LOCAL_ONLY: &str =
"module unrelated;\n wire taken_local;\n assign taken_local = 1'b0;\nendmodule\n";
const LOCAL_ONLY: &str = "module unrelated;\n function automatic int f();\n int taken_local = 0;\n return taken_local;\n endfunction\nendmodule\n";
let tree = Tree::new("fanout_local_only");
let files = [("pkg.sv", PKG), ("local.sv", LOCAL_ONLY)];
let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]);
@@ -816,6 +821,32 @@ mod tests {
assert!(edit.edits_for(&tree.path.join("local.sv")).is_empty());
}
/// The rung the hierarchical surface added: a module's internal **net**
/// spelled like the new name *is* a declaration the fan-out has to hold,
/// because `assign w = u_unrelated.taken_net;` in a fourth file resolves
/// to it now. So the file is pulled in — and the rename still succeeds
/// and still writes nothing there, because a package name and a net
/// inside a module capture nothing of each other.
#[test]
fn a_module_net_sharing_the_new_names_spelling_joins_the_fan_out_and_refuses_nothing() {
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
const NET_ONLY: &str =
"module unrelated;\n wire taken_net;\n assign taken_net = 1'b0;\nendmodule\n";
let tree = Tree::new("fanout_hierarchical_net");
let files = [("pkg.sv", PKG), ("net.sv", NET_ONLY)];
let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]);
let path = tree.path.join("pkg.sv");
let at = at(PKG, "cfg_pkg;");
let fan = fan_out(&ws, &path, at, "taken_net");
assert!(
fan.contains(&tree.path.join("net.sv")),
"a net is a hierarchical declaration of its name: {fan:?}"
);
let edit = same_answer(&ws, &path, at, "taken_net").expect("renames, no capture possible");
assert!(edit.edits_for(&tree.path.join("net.sv")).is_empty());
}
/// Attack on the old-name exemption: a shadowing/"unmasking" hunt. Two
/// packages, `p_pkg` and `q_pkg`, both export a member spelled the same
/// (`shared_name`); a third file imports both, `p_pkg` first, so
+38 -4
View File
@@ -94,10 +94,44 @@ impl Server {
fn diagnostics_of(&self, uri: &Uri) -> Vec<lsp_types::Diagnostic> {
let Some(doc) = self.workspace.document(uri) else { return Vec::new() };
// The lint pass is given the project: the rule selection
// `lucisv.lint.*` resolved to, and the index's identifier census, which
// is what lets the semantic rules default on here without accusing a
// signal another file reads (`docs/features/semantic-lints-on/`).
diagnostics::all_in(doc, &crate::lint::LintRun::for_document(&self.workspace, doc))
// `lucisv.lint.*` and the buffer's `[lint]` table resolved to, and the
// index's identifier census, which is what lets the semantic rules
// default on here without accusing a signal another file reads
// (`docs/features/semantic-lints-on/`).
let run = crate::lint::LintRun::for_document(&self.workspace, doc);
self.report_config_problems(&run);
diagnostics::all_in(doc, &run)
}
/// Say, once, what this buffer's `lucisv.toml` asked for and did not get.
///
/// Once per (config file, entry), not once per pass: this runs on every
/// keystroke and every index rebuild. The words are the ones `lucisv
/// check` fails the run with, `<file>:<line>: <message>`, so one mistake
/// reads the same in CI and here — but nothing is fatal, the entry is
/// dropped and the buffer is still linted with everything understood
/// (§42.2). Logged, not shown: a typo in a checked-in config is not worth
/// a popup on every editor in the project.
fn report_config_problems(&self, run: &crate::lint::LintRun) {
let problems = run.config_problems();
if problems.is_empty() {
return;
}
// The borrow is released before anything is sent: `notify` takes
// `&self` and could otherwise reach a second borrow one day.
let unsaid = match self.lint_config_problems.try_borrow_mut() {
Ok(mut log) => log.unsaid(problems),
Err(_) => return,
};
for message in unsaid {
self.notify(
LogMessage::METHOD,
LogMessageParams {
typ: MessageType::WARNING,
message: format!("lucisv: {message}; ignored"),
},
);
}
}
/// Publish everything known about a buffer — parse errors and lint
+15
View File
@@ -121,6 +121,19 @@ pub struct Server {
/// for a document whenever its text changes, so the warning is said once
/// per file change rather than once per format-on-save.
config_warnings: HashSet<Uri>,
/// Which `[lint]` entries of which `lucisv.toml` have already been
/// reported (§42.2). Interior-mutable because a lint pass runs behind
/// `&self` — the pull models compute diagnostics inside a `map` over the
/// open buffers — and the memo is the one thing a pass has to write.
/// Nothing is called while it is borrowed.
lint_config_problems: std::cell::RefCell<crate::lint::ProblemLog>,
/// The unknown-rule-name lines already logged for the **editor's**
/// `lucisv.lint.select`/`ignore` (§45.1), exactly as the last settings
/// value produced them. A client that re-pushes the same section — VS Code
/// does, whenever anything in it changes — says nothing again; a list the
/// user edited re-arms every name that is new to it. The project file's
/// twin memo is `lint_config_problems` above.
said_lint_names: Vec<String>,
abilities: ClientAbilities,
/// The id of the file-watcher registration in force, if any. Kept so a
/// changed `lucisv.filelist` can replace it: the watched filelist path is
@@ -300,6 +313,8 @@ impl Server {
connection,
workspace: Workspace::default(),
config_warnings: HashSet::new(),
lint_config_problems: std::cell::RefCell::default(),
said_lint_names: Vec::new(),
abilities,
watchers: None,
registrations: 0,
@@ -259,6 +259,23 @@ impl Server {
},
);
}
// A name in `lucisv.lint.select`/`ignore` the registry does not know is
// dropped just as silently, and the same typo in a `lucisv.toml`'s
// `[lint] select` has been said since §42. Said here too — but **once**
// per (setting, name): unlike the options warnings above, which cost a
// line each time the setting arrives, a client that re-pushes its whole
// section on every keystroke must not repeat these. A list the user
// edited re-arms whatever is new in it. See §2.9-29.
for warning in unsaid(&settings.lint_name_warnings, &self.said_lint_names) {
self.notify(
LogMessage::METHOD,
LogMessageParams {
typ: MessageType::WARNING,
message: format!("lucisv: {warning}"),
},
);
}
self.said_lint_names.clone_from(&settings.lint_name_warnings);
// And the same for `lucisv.lint.waivers`: a file that is not there, or
// a directive that does not parse, is dropped and said once — here,
// where the setting arrives, rather than on every keystroke from the
@@ -356,3 +373,13 @@ fn waiver_problems(
let paths = lint::waiver_paths(settings, roots, &lucisv_core::config::FileConfig::default());
lint::external_waivers(&paths).1
}
/// The lines of `warnings` that `said` does not already hold, in order.
///
/// The whole of §45.1's "once": the memo is the previous settings value's own
/// warning list, so re-pushing a section says nothing and editing the list
/// says exactly what is new in it. Both lists are a handful of entries at
/// most — one per typo — so a scan is cheaper than a set.
fn unsaid<'a>(warnings: &'a [String], said: &[String]) -> Vec<&'a String> {
warnings.iter().filter(|w| !said.contains(w)).collect()
}
@@ -408,3 +408,95 @@ fn an_answer_to_a_request_the_server_never_tracked_is_silently_ignored() {
session.answer(RequestId::from("never-sent".to_string()), serde_json::json!([{ "indent": 2 }]));
assert_eq!(session.server.workspace.client_settings().indent, Some(4));
}
// ------------------------------------------------------------------
// the editor's unknown rule name (TODO §45.1, docs/topo.md §2.9-29)
// ------------------------------------------------------------------
/// A `didChangeConfiguration` push with the given `lucisv.lint` section.
fn push_lint(session: &mut Session, lint: Value) {
session.notify(
DidChangeConfiguration::METHOD,
serde_json::json!({ "settings": { "lucisv": { "lint": lint } } }),
);
}
/// The unknown-rule lines the server logged since the last drain.
fn unknown_rule_lines(session: &Session) -> Vec<String> {
session
.logged()
.into_iter()
.map(|(_, message)| message)
.filter(|message| message.contains("unknown rule"))
.collect()
}
#[test]
fn an_unknown_rule_name_in_the_editors_select_is_logged_once() {
let tree = Tree::new("unknownrule");
tree.write("m.sv", "module m;\nendmodule\n");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule\n");
let _ = session.drain();
push_lint(&mut session, serde_json::json!({ "select": ["no-tabs", "no-tab"] }));
assert_eq!(
unknown_rule_lines(&session),
["lucisv: lucisv.lint.select: unknown rule: no-tab"],
"said once, naming the list and the name"
);
// Four diagnostics passes later it has not been said again: the pass runs
// on every keystroke and the log is not a place to shout from.
for _ in 0..4 {
session.server.publish(&uri);
}
assert!(unknown_rule_lines(&session).is_empty(), "not repeated by a diagnostics pass");
// Nor by the same section arriving again, which is what VS Code sends
// whenever anything at all in it changes.
push_lint(&mut session, serde_json::json!({ "select": ["no-tabs", "no-tab"] }));
assert!(unknown_rule_lines(&session).is_empty(), "not repeated by an identical push");
}
#[test]
fn a_changed_list_re_arms_the_log() {
let tree = Tree::new("unknownrulearm");
let mut session = Session::new(vec![tree.path.clone()], false);
let _ = session.drain();
push_lint(&mut session, serde_json::json!({ "select": ["no-tab"] }));
assert_eq!(unknown_rule_lines(&session).len(), 1);
// A second typo added to the list is new, and is said; the first is not.
push_lint(&mut session, serde_json::json!({ "select": ["no-tab", "nope"] }));
assert_eq!(
unknown_rule_lines(&session),
["lucisv: lucisv.lint.select: unknown rule: nope"],
"only what is new in the list"
);
// Cleared and re-typed: the memo is the previous value, so it is armed
// again.
push_lint(&mut session, serde_json::json!({ "select": [] }));
assert!(unknown_rule_lines(&session).is_empty(), "an empty list has nothing to say");
push_lint(&mut session, serde_json::json!({ "select": ["no-tab"] }));
assert_eq!(unknown_rule_lines(&session).len(), 1, "re-armed by the change");
}
#[test]
fn a_select_emptied_by_the_dropping_falls_through_the_ladder_unchanged() {
// §42's ladder: a `select` that named nothing the registry knows is an
// empty `select`, which is no opinion at all — the project's list, then
// the base set. The log line is the whole of what §45.1 changed.
let tree = Tree::new("unknownruleladder");
let mut session = Session::new(vec![tree.path.clone()], false);
let base = settings::lint_selection(session.server.workspace.client_settings());
let _ = session.drain();
push_lint(&mut session, serde_json::json!({ "select": ["no-tab", "nope"] }));
assert_eq!(unknown_rule_lines(&session).len(), 2, "both names said");
let now = session.server.workspace.client_settings();
assert!(now.lint_select.is_empty(), "the dropping left an empty select");
assert_eq!(settings::lint_selection(now), base, "and the rule set is untouched");
}
+74 -8
View File
@@ -202,6 +202,17 @@ pub struct ClientSettings {
/// One line per refused `lucisv.lint.options` entry, ready for a
/// `window/logMessage`. Empty for a settings push that was all valid.
pub lint_option_warnings: Vec<String>,
/// One line per name in `lucisv.lint.select` / `lucisv.lint.ignore` that
/// the registry does not know, in the shape
/// `lucisv.lint.select: unknown rule: <name>`.
///
/// Separate from [`ClientSettings::lint_option_warnings`] because the two
/// are said differently: an options warning is raised every time the
/// setting arrives, while an unknown name is said **once** per (setting,
/// name) and re-armed only when the list changes — a client that re-pushes
/// its whole section on every keystroke must not repeat it
/// (`docs/features/small-items-4/README.md`).
pub lint_name_warnings: Vec<String>,
/// `lucisv.lint.waivers`: external waiver files, each absolute or relative
/// to the first workspace root — the editor's spelling of
/// `lucisv check --waiver-file` and of `waivers` under `[lint]` in a
@@ -242,6 +253,7 @@ impl Default for ClientSettings {
lint_rules: BTreeMap::new(),
lint_options: RuleOptions::new(),
lint_option_warnings: Vec::new(),
lint_name_warnings: Vec::new(),
lint_waivers: Vec::new(),
}
}
@@ -313,6 +325,11 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
// And `lucisv.lint.select` / `lucisv.lint.ignore` the same way again.
let lint = lucisv.get("lint");
let (options, warnings) = rule_options(lint.and_then(|l| l.get("options")));
// The names the registry did not know, collected as the two lists are
// filtered so the user hears about a typo instead of losing a rule to it.
let mut names = Vec::new();
let lint_select = rules(lint.and_then(|l| l.get("select")), "select", &mut names);
let lint_ignore = rules(lint.and_then(|l| l.get("ignore")), "ignore", &mut names);
ClientSettings {
line_length: bounded(lucisv.get("lineLength"), LINE_LENGTH_RANGE),
indent: bounded(lucisv.get("indent"), INDENT_RANGE),
@@ -354,14 +371,15 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
// prevent.
large_file_threshold: count(large_file.and_then(|f| f.get("threshold")))
.unwrap_or(DEFAULT_LARGE_FILE_THRESHOLD),
lint_select: rules(lint.and_then(|l| l.get("select"))),
lint_ignore: rules(lint.and_then(|l| l.get("ignore"))),
lint_select,
lint_ignore,
// `lucisv.lint.severity.<class>` and `lucisv.lint.rules.<name>` nest
// one level deeper again, for the same reason `index.*` does.
lint_severity: severity_switches(lint.and_then(|l| l.get("severity"))),
lint_rules: rule_toggles(lint.and_then(|l| l.get("rules"))),
lint_options: options,
lint_option_warnings: warnings,
lint_name_warnings: names,
// Paths, not rule names: nothing to validate against the registry, and
// a path that names nothing is reported when the file is read.
lint_waivers: strings(lint.and_then(|l| l.get("waivers"))),
@@ -369,13 +387,28 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
}
/// The rule names in a settings array, dropping every one that names neither a
/// rule nor a severity class.
/// rule nor a severity class and describing each drop in `warnings`.
///
/// Silence rather than an error, on this module's standing rule: a push is
/// JSON on a socket, and a typo in one name must not cost the user every
/// diagnostic in the file. A dropped name leaves the rule where it was.
fn rules(value: Option<&Value>) -> Vec<String> {
strings(value).into_iter().filter(|name| vlog_linter::rules_named(name).is_some()).collect()
/// The drop itself is this module's standing rule: a push is JSON on a socket,
/// and a typo in one name must not cost the user every diagnostic in the file,
/// so a name the registry does not know leaves the rule where it was. Silence
/// about it was not the rule, only the state of things — `[lint] select` in a
/// `lucisv.toml` has said the same mistake out loud since §42, and this is the
/// editor's half of that (`docs/topo.md` §2.9-29).
///
/// `setting` is `select` or `ignore`, so the line names the list the user
/// typed in.
fn rules(value: Option<&Value>, setting: &str, warnings: &mut Vec<String>) -> Vec<String> {
strings(value)
.into_iter()
.filter(|name| {
let known = vlog_linter::rules_named(name).is_some();
if !known {
warnings.push(format!("lucisv.lint.{setting}: unknown rule: {name}"));
}
known
})
.collect()
}
/// The three class master switches, each `true` unless a client turned it off.
@@ -901,6 +934,39 @@ mod tests {
}}}));
assert_eq!(found.lint_select, vec!["style", "no-tabs"]);
assert_eq!(found.lint_ignore, vec!["warning"]);
// And the one name that is neither is described, not just dropped.
assert_eq!(found.lint_name_warnings, vec!["lucisv.lint.select: unknown rule: nope"]);
}
/// TODO §45.1: a name the registry does not know is still dropped — the
/// rule stays where it was — and now says so, once per name, naming the
/// list the user typed it in.
#[test]
fn an_unknown_rule_name_is_described_for_each_list_it_appears_in() {
let found = settings(json!({"lucisv": {"lint": {
"select": ["no-tabs", "nope", "also-nope"],
"ignore": ["nope"],
}}}));
assert_eq!(found.lint_select, vec!["no-tabs"]);
assert!(found.lint_ignore.is_empty());
assert_eq!(
found.lint_name_warnings,
vec![
"lucisv.lint.select: unknown rule: nope",
"lucisv.lint.select: unknown rule: also-nope",
"lucisv.lint.ignore: unknown rule: nope",
]
);
}
#[test]
fn two_lists_of_known_names_describe_nothing() {
let found = settings(json!({"lucisv": {"lint": {
"select": ["no-tabs", "error"],
"ignore": ["unused-signal"],
}}}));
assert!(found.lint_name_warnings.is_empty(), "{:?}", found.lint_name_warnings);
assert!(settings(json!({"lucisv": {}})).lint_name_warnings.is_empty());
}
/// What the server compares two settings pushes by, to decide whether the
+100 -20
View File
@@ -1008,11 +1008,12 @@ impl Workspace {
self.docs.values().filter_map(|doc| doc.path.as_deref()).collect();
let mut skipped = 0usize;
let mut texts: Vec<(PathBuf, String)> = 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.
for path in self.widened_files(added) {
for path in self.widened_files(added, &mut |w| warnings.push(w)) {
// 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.
@@ -1073,9 +1074,9 @@ impl Workspace {
// `+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(),
// Warnings come from resolving the scope, and a widen resolves no
// filelist: rung 1 is not a scope an open buffer can widen.
warnings: Vec::new(),
// 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,
staged: Vec::new(),
staged_at: Vec::new(),
@@ -1088,11 +1089,11 @@ impl Workspace {
/// The files the directories a widen added bring into scope, by the same
/// rules [`Workspace::folder_files`] applies to the whole scope — including
/// the rootless-at-depth-0 flat read.
fn widened_files(&self, added: &[PathBuf]) -> Vec<PathBuf> {
fn widened_files(&self, added: &[PathBuf], warn: &mut dyn FnMut(String)) -> Vec<PathBuf> {
if self.roots.is_empty() && self.client.index_scope_depth == 0 {
return sibling_files(added);
}
self.walked_files(added)
self.walked_files(added, warn)
}
/// Index the next file of `scan`, reporting whether there was one.
@@ -1520,6 +1521,10 @@ impl Workspace {
/// `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;
@@ -1603,6 +1608,19 @@ impl Workspace {
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 {
@@ -1867,16 +1885,21 @@ impl Workspace {
/// none, so an `` `include`` there resolves against the including file's
/// own directory alone (`docs/features/include-nav/README.md`).
fn source_files(&self) -> Scope {
// The walk's own warnings join the scope's, so an unreadable directory
// reaches the output channel by the road a filelist's problems already
// travel — said once per scan and never per keystroke.
let mut warnings: Vec<String> = Vec::new();
let Some(path) = self.filelist_path() else {
return Scope { files: self.default_files(), ..Default::default() };
let files = self.default_files(&mut |w| warnings.push(w));
return Scope { files, warnings, ..Default::default() };
};
match lucisv_core::filelist::read(&path) {
Ok(list) => Scope { files: list.files, incdirs: list.incdirs, warnings: list.warnings },
Err(problem) => Scope {
files: self.default_files(),
incdirs: Vec::new(),
warnings: vec![format!("{problem} — indexing the workspace instead")],
},
Err(problem) => {
let files = self.default_files(&mut |w| warnings.push(w));
warnings.insert(0, format!("{problem} — indexing the workspace instead"));
Scope { files, incdirs: Vec::new(), warnings }
}
}
}
@@ -1903,11 +1926,11 @@ impl Workspace {
/// Rungs 2 and 3 of the ladder: the whole-workspace walk when the client
/// asked for it, else the folder scope.
fn default_files(&self) -> Vec<PathBuf> {
fn default_files(&self, warn: &mut dyn FnMut(String)) -> Vec<PathBuf> {
if self.walks_the_workspace() {
return self.walked_files(&self.roots);
return self.walked_files(&self.roots, warn);
}
self.folder_files()
self.folder_files(warn)
}
/// Rung 3: the folder scope — [`Workspace::scope_dirs`], walked with every
@@ -1919,12 +1942,12 @@ impl Workspace {
/// case, where descending a tree the user never named would be a surprise
/// — and the moment the user raises `scopeDepth` they have named one, so
/// the walk is what they asked for.
fn folder_files(&self) -> Vec<PathBuf> {
fn folder_files(&self, warn: &mut dyn FnMut(String)) -> Vec<PathBuf> {
let dirs = self.scope_dirs();
if self.roots.is_empty() && self.client.index_scope_depth == 0 {
return sibling_files(&dirs);
}
self.walked_files(&dirs)
self.walked_files(&dirs, warn)
}
/// Every source file under `dirs`, found by the CLI's own walk: the same
@@ -1938,7 +1961,7 @@ impl Workspace {
/// written in a root's `.gitignore` does not apply to a rung-3 walk that
/// starts below it. The `exclude` patterns are matched against whole
/// paths and so behave identically either way.
fn walked_files(&self, dirs: &[PathBuf]) -> Vec<PathBuf> {
fn walked_files(&self, dirs: &[PathBuf], warn: &mut dyn FnMut(String)) -> Vec<PathBuf> {
let mut discovery = Discovery::new(true);
let mut out = Vec::new();
for root in dirs {
@@ -1958,8 +1981,9 @@ impl Workspace {
exclude.extend(self.client.exclude.iter().cloned());
// `.gitignore` is always honoured: it is the CLI's default, and an
// editor has no `--no-gitignore` to type. An unreadable directory
// is simply not indexed, exactly as before this walk was shared.
let _ = collect_files(input, &exclude, true, &mut out);
// is skipped and said — the warning rides out on the scope's own
// warnings, which `server/notification.rs` logs once per scan.
let _ = collect_files(input, &exclude, true, &mut out, &mut |w| warn(w.to_string()));
}
out.sort();
out.dedup();
@@ -2730,6 +2754,33 @@ mod tests {
);
}
/// 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 |_| {}).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
@@ -3337,6 +3388,35 @@ mod tests {
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");
+563 -9
View File
@@ -6405,7 +6405,10 @@ endclass
/// An instance head: `u.clk_i` where `u` instantiates a module declared in
/// another file. The instance's declared type is the module, so the port is
/// hovered exactly as a class property is.
/// hovered exactly as a class property is — and, since the hierarchical
/// surface (2026-09-05), so is `u.internal`: a hierarchical path may name a
/// module's internal net, and hover follows the same resolution the rename
/// does.
#[test]
fn an_instance_heads_port_is_hovered_across_files() {
let dir = temp_dir("instancehead");
@@ -6455,14 +6458,11 @@ fn an_instance_heads_port_is_hovered_across_files() {
assert!(port.contains("sub.sv:1"), "the port's own file and line: got {port}");
assert!(port.contains("clk_i"), "got {port}");
// A module exports its ports and parameters and nothing else, so an
// internal net of another file answers nothing rather than something —
// the round-2 ruling in the feature README.
assert!(
response(3)["result"].is_null(),
"an internal signal is not exported across files: {:#?}",
response(3)
);
// An internal net reached through an instance head is the hierarchical
// surface, and it answers with the net's own declaration in its own file.
let net = response(3)["result"]["contents"]["value"].as_str().expect("hover markdown");
assert!(net.contains("sub.sv:2"), "the net's own file and line: got {net}");
assert!(net.contains("wire internal"), "got {net}");
let _ = std::fs::remove_dir_all(&dir);
}
@@ -7758,3 +7758,557 @@ fn a_property_declaration_hovers_and_appears_in_the_outline() {
let _ = std::fs::remove_dir_all(&dir);
}
// ---------------------------------------------------------------------------
// §42 — one lint-configuration contract for the project file and the editor.
//
// `docs/features/lint-config-contract/README.md`: the editor's settings play
// the role the CLI's flags play, so a `lucisv.toml` a project checks in
// governs an editor exactly as it governs CI, and a `lucisv.lint.*` setting
// replaces it the way a flag replaces it.
// ---------------------------------------------------------------------------
/// A buffer with one tab and one trailing space: two style findings from two
/// rules, so a selection that keeps one and drops the other is visible.
const TWO_FINDINGS: &str = "module lint_contract;\n\twire a; \nendmodule\n";
/// The rule codes of every `publishDiagnostics` for one URI, in the order
/// they arrived, with a repeat of the previous answer collapsed: a republish
/// that says the same thing is not a step.
fn published_codes(messages: &[serde_json::Value], uri: &str) -> Vec<Vec<String>> {
let mut steps: Vec<Vec<String>> = Vec::new();
for message in messages {
if message["method"] != "textDocument/publishDiagnostics"
|| message["params"]["uri"] != serde_json::Value::String(uri.to_string())
{
continue;
}
let mut codes: Vec<String> = message["params"]["diagnostics"]
.as_array()
.expect("an array")
.iter()
.filter_map(|d| d["code"].as_str().map(str::to_string))
.collect();
codes.sort();
codes.dedup();
if steps.last() != Some(&codes) {
steps.push(codes);
}
}
steps
}
/// The `initialize`/`didOpen` prefix every session below opens with.
fn lint_session_start(dir: &Path, uri: &str, text: &str) -> String {
let root = format!("file://{}", dir.display());
[
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(text).expect("json")
)),
]
.concat()
}
/// A `didChangeConfiguration` carrying one `lucisv.lint.select` list.
fn select_push(rules: &str) -> String {
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"lucisv":{{"lint":{{"select":[{rules}]}}}}}}}}}}"#
))
}
#[test]
fn a_projects_lint_select_governs_an_editor_until_a_setting_replaces_it() {
let dir = temp_dir("lint_contract_select");
std::fs::write(dir.join("lucisv.toml"), "[lint]\nselect = [\"no-tabs\"]\n")
.expect("write config");
let file = dir.join("lint_contract.sv");
std::fs::write(&file, TWO_FINDINGS).expect("write");
let uri = format!("file://{}", file.display());
let session = [
lint_session_start(&dir, &uri, TWO_FINDINGS),
// The editor names a rule of its own: it replaces the project's, as
// `--select` replaces it on the command line.
select_push("\"no-trailing-whitespace\""),
// ... and taking the setting back restores the project's.
select_push(""),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let steps = published_codes(&talk(&session), &uri);
assert_eq!(
steps,
vec![
vec!["no-tabs".to_string()],
vec!["no-trailing-whitespace".to_string()],
vec!["no-tabs".to_string()],
],
"the project selects, the editor replaces, and an emptied setting hands it back"
);
let _ = std::fs::remove_dir_all(&dir);
}
/// A `[lint.<rule>]` entry the registry refuses is said **once** in the
/// output channel — in the words `lucisv check` fails the run with — and the
/// buffer keeps being linted with the entry dropped (§42.2).
#[test]
fn a_rejected_project_option_is_logged_once_and_the_buffer_is_still_linted() {
let dir = temp_dir("lint_contract_option");
let config = dir.join("lucisv.toml");
std::fs::write(&config, "[lint.line-length]\nlength = \"wide\"\n").expect("write config");
let file = dir.join("lint_contract.sv");
std::fs::write(&file, TWO_FINDINGS).expect("write");
let uri = format!("file://{}", file.display());
// Three settings pushes, each of which republishes every open buffer, so
// the lint pass runs at least four times over the same bad config.
let session = [
lint_session_start(&dir, &uri, TWO_FINDINGS),
select_push("\"no-tabs\""),
select_push("\"no-trailing-whitespace\""),
select_push(""),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let messages = talk(&session);
let complaints: Vec<&str> = messages
.iter()
.filter(|m| m["method"] == "window/logMessage")
.filter_map(|m| m["params"]["message"].as_str())
.filter(|line| line.contains("line-length"))
.collect();
assert_eq!(complaints.len(), 1, "said once, not once per pass: {complaints:#?}");
assert!(
complaints[0].starts_with(&format!("lucisv: {}:2: rule `line-length` ", config.display())),
"the file and line `lucisv check` would name: {}",
complaints[0]
);
assert!(
!messages.iter().any(|m| m["method"] == "window/showMessage"),
"logged, not shown: {messages:#?}"
);
// And the lint kept running with the entry dropped.
let steps = published_codes(&messages, &uri);
assert!(
steps.iter().any(|codes| codes.contains(&"no-tabs".to_string())),
"the buffer is still linted: {steps:#?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
/// The rules `lucisv check` runs over a file and the rules the server runs
/// over the same buffer, for three `lucisv.toml`s. Equal, or the two halves
/// of lucisv disagree about what a violation is — which is the whole reason
/// §42 exists.
#[test]
fn the_cli_and_the_server_run_the_same_rules_for_the_same_buffer() {
let Some(lucisv) = lucisv_binary() else {
eprintln!("skipped: the `lucisv` binary is not built next to `lucisv-server`");
return;
};
let configs = [
// No `[lint]` table at all: both front ends fall back to the base set.
("none", "line-length = 80\n"),
// A selection of one rule.
("one", "[lint]\nselect = [\"no-tabs\"]\n"),
// A severity word, and an `ignore` that takes one back out of it.
("class", "[lint]\nselect = [\"style\"]\nignore = [\"no-trailing-whitespace\"]\n"),
];
for (tag, config) in configs {
let dir = temp_dir(&format!("lint_contract_agree_{tag}"));
std::fs::write(dir.join("lucisv.toml"), config).expect("write config");
let file = dir.join("lint_contract.sv");
std::fs::write(&file, TWO_FINDINGS).expect("write");
let uri = format!("file://{}", file.display());
let output = Command::new(&lucisv)
.args(["check", "--output-format", "json"])
.arg(&file)
.output()
.expect("the lucisv binary runs");
let json: serde_json::Value =
serde_json::from_slice(&output.stdout).expect("the CLI prints one JSON array");
let mut from_cli: Vec<String> = json
.as_array()
.expect("an array")
.iter()
.filter_map(|item| item["rule"].as_str().map(str::to_string))
.collect();
from_cli.sort();
from_cli.dedup();
let session = [
lint_session_start(&dir, &uri, TWO_FINDINGS),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let from_server =
published_codes(&talk(&session), &uri).pop().expect("the server published something");
assert_eq!(from_server, from_cli, "the two front ends disagree under {config:?}");
assert!(!from_cli.is_empty(), "a config that reports nothing proves nothing: {config:?}");
let _ = std::fs::remove_dir_all(&dir);
}
}
// ---------------------------------------------------------------------------
// TODO.md §46 — what a `didOpen` costs the request behind it
// ---------------------------------------------------------------------------
//
// `talk` writes a whole session before reading a byte, which is what every
// test above wants and what a *timing* test cannot use: the number this round
// is about is the gap between the `didOpen` frame going out and the next
// response coming back. `Live` — the held-open session two hundred lines up —
// is the one that can measure it. The three tests below are §46's contract:
// the open returns to the loop fast, the first request after it is answered
// from the **buffer**, and the diagnostics still arrive with no edit and no
// further request behind them.
/// A started session over `root`, indexed at the whole-workspace scope with
/// the scan already run — the barrier request at the end is what makes that
/// true, since the loop answers nothing until a rescan a message asked for has
/// finished.
fn live_at(root: &Path) -> Live {
let mut live = Live::start();
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"file://{}","capabilities":{{}}}}}}"#,
root.display()
));
live.wait_for(|m| m["id"] == 1);
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
live.send(WIDE_SCOPE);
live.send(r#"{"jsonrpc":"2.0","id":2,"method":"workspace/symbol","params":{"query":"zzz"}}"#);
live.wait_for(|m| m["id"] == 2);
live
}
/// The `didOpen` frame for a buffer.
fn open_frame(uri: &str, text: &str) -> String {
format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(text).expect("json")
)
}
/// Open `uri` and ask for a `hover` in the same write, and report how long the
/// hover took to come back.
///
/// That wait *is* the open: the loop is synchronous, so whatever the open does
/// before returning to it is what the hover queues behind.
fn open_then_hover(live: &mut Live, id: u32, uri: &str, text: &str) -> std::time::Duration {
let hover = format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":0,"character":8}}}}}}"#
);
let started = std::time::Instant::now();
live.send(&open_frame(uri, text));
live.send(&hover);
live.wait_for(|m| m["id"] == id);
started.elapsed()
}
/// A workspace of `files` small packages, so the index holds a *project*
/// rather than one buffer — which is what switches the cross-file lint rules
/// on at all (`LintRun::for_document`).
fn indexed_neighbours(dir: &Path, files: usize) {
for k in 0..files {
std::fs::write(
dir.join(format!("pkg{k}.sv")),
format!("package pkg{k};\n localparam int K{k} = {k};\nendpackage\n"),
)
.expect("write neighbour");
}
}
/// §46's contract, on the wire: a `didOpen` of a 2 000-line buffer must not
/// leave the request behind it waiting.
///
/// **An upper bound, not a benchmark, and a debug-build one.** `cargo test`
/// builds unoptimized, where one tolerant parse of 2 000 lines is ~53 ms all
/// by itself — measured on this machine, and stable to a millisecond across
/// runs. So the 200 ms here is that floor with room for a loaded CI box, not
/// the ≤ 25 ms §46 asked for: **that figure is a release number**, and the
/// release binary opens the same buffer in 2–4 ms.
///
/// **What this test does and does not catch.** It catches an open that starts
/// doing something *unbounded* — the shape §46 fixed. It cannot catch the
/// §46 defect itself at this size: the census walk that cost 1.6 s on
/// opentitan's 42 000-line `pinmux_reg_top.sv` costs milliseconds over a
/// forty-file fixture, and a fixture of opentitan's four thousand files has
/// no business in a unit-test suite. The exact pin for that is
/// `undriven_net`'s `the_project_is_asked_only_about_the_signals_that_would_be_reported`,
/// which counts the questions instead of timing them
/// (`docs/features/didopen-cost/README.md`).
///
/// Best of three distinct buffers: the first open of a process pays cold code
/// paths that have nothing to do with the buffer, and a wall-clock assertion
/// that cannot tolerate one scheduling hiccup is a flake, not a pin.
#[test]
fn opening_a_two_thousand_line_buffer_does_not_delay_the_request_behind_it() {
let dir = temp_dir("didopen_cost");
indexed_neighbours(&dir, 40);
let mut generated = Vec::new();
for n in 0..3 {
let name = format!("gen{n}");
// The generator the perf tables use: a thousand declarations, every
// one declared, driven and read — the cheap case for the *findings*
// and the expensive one for the walk that decides there are none.
let text = generated_module(&name, 2_000);
assert!(text.lines().count() >= 2_000, "the premise: a 2 000-line buffer");
let path = dir.join(format!("{name}.sv"));
std::fs::write(&path, &text).expect("write");
generated.push((path, text));
}
let mut live = live_at(&dir);
// A warm-up open of a small buffer, for the cold code paths.
let warm = format!("file://{}", dir.join("pkg0.sv").display());
open_then_hover(&mut live, 10, &warm, "package pkg0;\n localparam int K0 = 0;\nendpackage\n");
let mut best = std::time::Duration::MAX;
for (n, (path, text)) in generated.iter().enumerate() {
let uri = format!("file://{}", path.display());
best = best.min(open_then_hover(&mut live, 20 + n as u32, &uri, text));
}
live.finish();
let _ = std::fs::remove_dir_all(&dir);
assert!(
best <= std::time::Duration::from_millis(200),
"a didOpen of a 2 000-line buffer delayed the next request by {best:?}"
);
}
/// The other half of §46's contract: the request after an open is answered
/// from the **buffer**, not from what is on disk.
///
/// Nothing about the open was deferred — it still analyzes the buffer before
/// it returns to the loop — and this is what says so out loud. The buffer
/// names something the file on disk does not, and declares it on a line the
/// disk file does not, and the very first hover and the very first definition
/// after the open both find the buffer's.
#[test]
fn the_first_hover_after_an_open_sees_the_buffer_and_not_the_disk() {
let dir = temp_dir("didopen_buffer_wins");
indexed_neighbours(&dir, 4);
let file = dir.join("m.sv");
std::fs::write(
&file,
"module m;\n localparam int ON_DISK = 1;\n logic a;\n assign a = ON_DISK;\nendmodule\n",
)
.expect("write");
let uri = format!("file://{}", file.display());
// What the editor holds: a different name, declared on a different line.
let buffer = "module m;\n\n localparam int IN_BUFFER = 2;\n logic a;\n \
assign a = IN_BUFFER;\nendmodule\n";
let mut live = live_at(&dir);
live.send(&open_frame(&uri, buffer));
// The cursor on `IN_BUFFER` where line 4 reads it.
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":30,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":4,"character":16}}}}}}"#
));
let card = live.wait_for(|m| m["id"] == 30)["result"]["contents"]["value"]
.as_str()
.unwrap_or_default()
.to_string();
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":31,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":4,"character":16}}}}}}"#
));
let definition = live.wait_for(|m| m["id"] == 31);
live.finish();
let _ = std::fs::remove_dir_all(&dir);
assert!(card.contains("IN_BUFFER"), "the first hover did not read the buffer: {card:?}");
assert!(!card.contains("ON_DISK"), "the first hover read the disk file: {card:?}");
let locations = definition["result"].as_array().expect("an array of locations");
assert_eq!(locations.len(), 1, "one declaration, got {locations:#?}");
assert_eq!(locations[0]["range"]["start"]["line"], 2, "the buffer's line, not the disk's");
}
/// And the third: the open still publishes, with no edit and no further
/// request to trigger it.
///
/// **There is no debounce on the open.** §46 allowed the diagnostics to be
/// moved onto the change debounce and to arrive one quiet period later; they
/// were not, because the cost was never the publish — it was one rule inside
/// it. So the guarantee is the one this server has always had: the diagnostics
/// for an opened buffer go out inside the `didOpen`, ahead of anything queued
/// behind it.
#[test]
fn an_open_still_publishes_its_diagnostics_with_no_edit_behind_it() {
let dir = temp_dir("didopen_publishes");
indexed_neighbours(&dir, 4);
let file = dir.join("tabbed.sv");
let text = "module tabbed;\n\twire a;\nendmodule\n";
std::fs::write(&file, text).expect("write");
let uri = format!("file://{}", file.display());
let mut live = live_at(&dir);
live.send(&open_frame(&uri, text));
let published = live.wait_for(|m| {
m["method"] == "textDocument/publishDiagnostics" && m["params"]["uri"] == uri
});
live.finish();
let _ = std::fs::remove_dir_all(&dir);
let items = published["params"]["diagnostics"].as_array().expect("a diagnostics array");
let codes: Vec<&str> = items.iter().filter_map(|d| d["code"].as_str()).collect();
assert!(codes.contains(&"no-tabs"), "the open published nothing about the tab: {items:#?}");
}
/// package-reexports (2026-09-05, TODO §48): `export b_pkg::x;` over the real
/// wire, in the shape a UVM tree writes it — a package that declares, a
/// package that re-exports, and a third file that only ever names the
/// re-exporting one.
///
/// What only an e2e test can settle: that all five capabilities read the same
/// re-export edge. Definition and hover land on `b_pkg`'s declaration however
/// the name is reached (bare under `import a_pkg::*`, or written out as
/// `a_pkg::x`); completion after `a_pkg::` offers it; find-references from
/// `x`'s own declaration lists the `export` line **and** the uses through it;
/// and a rename edits every one of them, the `export` line's item half
/// included. The wildcard forms are here too — `export b_pkg::*;` and
/// `export *::*;` beside an `import` — because the walk that follows them is
/// the walk definition asks (`docs/features/package-reexports/README.md`).
#[test]
fn a_name_reached_through_a_package_reexport_is_navigated_listed_and_renamed() {
let dir = temp_dir("reexport");
let b = dir.join("b_pkg.sv");
let b_text = "package b_pkg;\n localparam int x = 8;\n localparam int y = 9;\nendpackage\n";
std::fs::write(&b, b_text).expect("write");
let a = dir.join("a_pkg.sv");
let a_text = "package a_pkg;\n export b_pkg::x;\nendpackage\n";
std::fs::write(&a, a_text).expect("write");
std::fs::write(dir.join("w_pkg.sv"), "package w_pkg;\n export b_pkg::*;\nendpackage\n")
.expect("write");
std::fs::write(
dir.join("s_pkg.sv"),
"package s_pkg;\n import b_pkg::*;\n export *::*;\nendpackage\n",
)
.expect("write");
let top = dir.join("top.sv");
let top_text = "\
module top;
import a_pkg::*;
localparam W = x;
localparam V = a_pkg::x;
localparam Y = w_pkg::y;
localparam Z = s_pkg::y;
endmodule
";
std::fs::write(&top, top_text).expect("write");
let root = format!("file://{}", dir.display());
let a_uri = format!("file://{}", a.display());
let b_uri = format!("file://{}", b.display());
let top_uri = format!("file://{}", top.display());
let at = |id: u32, method: &str, line: u32, character: u32| {
frame(&format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/{method}","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":{line},"character":{character}}}}}}}"#
))
};
let session = [
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(WIDE_SCOPE),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(top_text).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{b_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(b_text).expect("json")
)),
// The bare `x`, reached through `import a_pkg::*`.
at(2, "definition", 2, 17),
// ...and written out as `a_pkg::x`, hovered and completed.
at(3, "hover", 3, 24),
at(4, "completion", 3, 24),
// The two wildcard forms, each in its own package.
at(5, "definition", 4, 24),
at(6, "definition", 5, 24),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":7,"method":"textDocument/references","params":{{"textDocument":{{"uri":"{b_uri}"}},"position":{{"line":1,"character":17}},"context":{{"includeDeclaration":false}}}}}}"#
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":8,"method":"textDocument/rename","params":{{"textDocument":{{"uri":"{b_uri}"}},"position":{{"line":1,"character":17}},"newName":"addr"}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let messages = talk(&session);
let response = |id: u32| -> &serde_json::Value {
messages
.iter()
.find(|m| m["id"] == id)
.unwrap_or_else(|| panic!("no response {id} in {messages:#?}"))
};
let jumped_to = |id: u32, line: u64| {
let result = &response(id)["result"];
let target = result.get("uri").map_or(&result[0], |_| result);
assert!(
target["uri"].as_str().expect("a uri").ends_with("b_pkg.sv"),
"response {id} did not land in the declaring package: {result:#?}"
);
assert_eq!(target["range"]["start"]["line"], line, "response {id}");
};
jumped_to(2, 1);
let hover = response(3)["result"]["contents"]["value"].as_str().expect("hover markdown");
assert!(hover.contains("b_pkg.sv:2"), "the declaring file and line: got {hover}");
assert!(hover.contains("localparam int x = 8"), "got {hover}");
let items = response(4)["result"]["items"].as_array().expect("a completion list");
let labels: Vec<&str> = items.iter().filter_map(|item| item["label"].as_str()).collect();
assert!(labels.contains(&"x"), "the re-exported name is offered: {labels:?}");
assert!(!labels.contains(&"y"), "and only what `a_pkg` re-exports: {labels:?}");
jumped_to(5, 2);
jumped_to(6, 2);
let references = response(7)["result"].as_array().expect("a list");
let sites: Vec<(&str, u64)> = references
.iter()
.map(|site| {
let uri = site["uri"].as_str().expect("a uri");
(
uri.rsplit('/').next().unwrap_or(uri),
site["range"]["start"]["line"].as_u64().unwrap_or(u64::MAX),
)
})
.collect();
assert!(sites.contains(&("a_pkg.sv", 1)), "the `export` line itself: {sites:?}");
assert!(sites.contains(&("top.sv", 2)), "the bare use: {sites:?}");
assert!(sites.contains(&("top.sv", 3)), "and the qualified one: {sites:?}");
let changes = &response(8)["result"]["changes"];
assert_eq!(
changes[&a_uri].as_array().expect("the export line is rewritten").len(),
1,
"{changes:#?}"
);
assert_eq!(changes[&a_uri][0]["newText"], "addr");
assert_eq!(changes[&a_uri][0]["range"]["start"]["line"], 1);
assert_eq!(changes[&a_uri][0]["range"]["start"]["character"], 16);
assert_eq!(changes[&top_uri].as_array().expect("both uses").len(), 2, "{changes:#?}");
assert_eq!(changes[&b_uri].as_array().expect("the declaration").len(), 1, "{changes:#?}");
let _ = std::fs::remove_dir_all(&dir);
}
+23 -12
View File
@@ -296,29 +296,40 @@ impl<'a> Fmt<'a> {
pub(super) fn data_decl(&self, d: &DataDecl) -> Doc {
let mut docs = Vec::new();
if let Some(net) = &d.net {
docs.push(text(format!("{net} ")));
docs.push(text(net.clone()));
self.net_delay(d, false, &mut docs);
}
self.net_delay(d, false, &mut docs);
self.qualifier_run(&d.qualifiers, &mut docs);
if let Some(t) = self.data_type(&d.ty) {
docs.push(t);
docs.push(text(" "));
self.net_delay(d, true, &mut docs);
}
self.net_delay(d, true, &mut docs);
// Neither arm needs an `else`: a delay before the type is only read
// after a net keyword, and one after the type only when a type was
// actually written, so an implicit type has none to print.
docs.push(self.declarators(&d.declarators));
concat(docs)
}
/// `#5 ` — the declaration's net delay and the space after it, but only
/// when it was written on the side of the data type `after_type` names.
/// IEEE 1800 §6.7 allows either side and lucisv prints it where the
/// source put it; moving it across the type would reorder tokens, which
/// `verify.rs` refuses.
/// The separator that follows the word just emitted, and then `#5` when
/// the declaration's net delay was written on the side of the data type
/// `after_type` names. IEEE 1800 §6.7 allows either side and lucisv
/// prints it where the source put it; moving it across the type would
/// reorder tokens, which `verify.rs` refuses.
///
/// The separator is the delay's `before_hash` comments when it has any
/// (`wire /* c */ #5 w;`) and a plain space otherwise — so a declaration
/// with no comment there is laid out exactly as it was before the slot
/// existed, delay or no delay.
fn net_delay(&self, d: &DataDecl, after_type: bool, docs: &mut Vec<Doc>) {
let Some(delay) = d.delay.as_ref().filter(|n| n.after_type == after_type) else {
return;
};
let delay = d.delay.as_ref().filter(|n| n.after_type == after_type);
match delay.map(|n| &n.before_hash).filter(|c| !c.is_empty()) {
Some(comments) => self.inline_comments_spaced(comments, docs),
None => docs.push(text(" ")),
}
let Some(delay) = delay else { return };
docs.push(text("#"));
self.slot_comments(&delay.after_hash, docs);
docs.push(self.expr(&delay.expr));
docs.push(text(" "));
}
+11 -2
View File
@@ -310,8 +310,17 @@ impl<'a> Fmt<'a> {
// strictly. Printed verbatim so nothing is lost if that ever
// changes — see `ListItem::from_raw`.
ExprKind::Error(raw) => self.raw_inline(raw),
ExprKind::MinTypMax { min, typ, max } => {
concat(vec![self.expr(min), text(":"), self.expr(typ), text(":"), self.expr(max)])
ExprKind::MinTypMax { min, typ, max, comments } => {
let mut docs = vec![self.expr(min)];
self.slot_comments(&comments.before_typ, &mut docs);
docs.push(text(":"));
self.slot_comments(&comments.after_typ, &mut docs);
docs.push(self.expr(typ));
self.slot_comments(&comments.before_max, &mut docs);
docs.push(text(":"));
self.slot_comments(&comments.after_max, &mut docs);
docs.push(self.expr(max));
concat(docs)
}
}
}
+62 -9
View File
@@ -342,30 +342,83 @@ impl<'a> Fmt<'a> {
if let Some(s) = &g.strength {
docs.push(text(format!(" {}", drive_strength(s))));
}
if !g.delay.is_empty() {
// The gap in front of the `#` is a space unless the source wrote
// a comment in it, exactly as a net delay's `before_hash` is.
match g.before_hash.is_empty() {
true => docs.push(text(" ")),
false => self.inline_comments_spaced(&g.before_hash, &mut docs),
}
docs.push(text("#"));
self.slot_comments(&g.after_hash, &mut docs);
}
if let [delay] = g.delay.as_slice() {
// One value prints itself, brackets and all (`#5`, `#(5)`).
docs.push(text(" #"));
docs.push(self.expr(delay));
docs.push(self.expr(&delay.expr));
} else if !g.delay.is_empty() {
// `#(rise, fall[, turn-off])` — the parens are the list's own.
docs.push(text(" #("));
// `#(rise, fall[, turn-off])` — the parens and the commas are the
// list's own, so the comments written around them are too.
docs.push(text("("));
for (i, d) in g.delay.iter().enumerate() {
if i > 0 {
docs.push(text(", "));
docs.push(text(","));
match d.leading.is_empty() {
true => docs.push(text(" ")),
false => self.inline_comments_spaced(&d.leading, &mut docs),
}
} else {
self.slot_comments(&d.leading, &mut docs);
}
docs.push(self.expr(d));
docs.push(self.expr(&d.expr));
self.slot_comments(&d.trailing, &mut docs);
}
docs.push(text(")"));
}
let last = g.instances.len().saturating_sub(1);
// True once a trailing comment has ended the previous instance's line:
// the next instance then starts on a fresh, indented line, and the
// space that normally separates it from the `,` is not written.
let mut broke = false;
for (i, inst) in g.instances.iter().enumerate() {
docs.push(if i > 0 { text(", ") } else { text(" ") });
// What stands between the delay (or the previous instance's `,`)
// and this instance's name — a space when nothing does.
match (broke, inst.meta.leading.is_empty()) {
(true, true) => {}
(false, true) => docs.push(text(" ")),
(_, false) => self.inline_comments_spaced(&inst.meta.leading, &mut docs),
}
broke = false;
if let Some(name) = &inst.name {
docs.push(name_doc(name));
docs.push(text(" "));
match inst.before_args.is_empty() {
true => docs.push(text(" ")),
false => self.inline_comments_spaced(&inst.before_args, &mut docs),
}
}
docs.push(self.expr_list("(", &inst.args, ")"));
if i == last {
continue;
}
// Comments written between the instance and its `,` print on the
// instance's side of it, as every list element's do.
if self.inline_comments(&inst.meta.before_sep, &mut docs) {
docs.push(Doc::HardLine);
}
docs.push(text(","));
if let Some(tr) = &inst.meta.trailing {
docs.push(text(" "));
docs.push(self.comment(tr));
// A line comment ends the line (a `// p` would otherwise
// swallow the next instance on re-lex — §45's QA); the next
// instance continues one level in. A block comment stays
// inline, as the case table for this slot expects.
if is_line_comment(&tr.text) {
docs.push(indent(vec![Doc::HardLine]));
broke = true;
}
}
}
docs.push(text(";"));
docs.push(self.semi(&g.before_semi));
concat(docs)
}
}
+5 -1
View File
@@ -362,8 +362,12 @@ impl<'a> Fmt<'a> {
}
if let Some(delay) = &a.delay {
docs.push(text("#"));
self.slot_comments(&a.after_hash, &mut docs);
docs.push(self.expr(delay));
docs.push(text(" "));
match a.after_delay.is_empty() {
true => docs.push(text(" ")),
false => self.inline_comments_spaced(&a.after_delay, &mut docs),
}
}
let items: Vec<ListItem> = a
.assigns
+1 -1
View File
@@ -482,7 +482,7 @@ impl<'a> Fmt<'a> {
},
StmtKind::Break => concat(vec![text("break"), self.semi(before_semi)]),
StmtKind::Continue => concat(vec![text("continue"), self.semi(before_semi)]),
StmtKind::Disable(name) => {
StmtKind::Disable { name, .. } => {
concat(vec![text(format!("disable {}", named(name))), self.semi(before_semi)])
}
StmtKind::WaitFork => concat(vec![text("wait fork"), self.semi(before_semi)]),
@@ -0,0 +1,101 @@
# TODO §45.4 — the comment slots inside a delay list. `parse_delay_values`
# serves `#(1:2:3)` on nets and continuous assignments and `#(rise, fall)` on
# gates; the gaps around the `(`, the two `:` and the `,` had no owner, so a
# comment written in one moved and `verify.rs` refused the file.
#
# The `min:typ:max` colons: `MinTypMaxComments`, four slots, one grammar
# shared with the parenthesized `(a:b:c)` expression.
module m;
wire #(1 /* b */ : /* c */ 2 /* d */ : /* e */ 3) w;
endmodule
----
module m;
wire #(1 /* b */ : /* c */ 2 /* d */ : /* e */ 3) w;
endmodule
====
# The parentheses of a one-value delay are its own `ExprKind::Paren`, which
# has had the two slots all along — and a comment inside a bracket pair forces
# that pair open, as it does everywhere else in the formatter.
module m;
wire #( /* a */ 1:2:3 /* f */ ) w;
endmodule
----
module m;
wire #(
/* a */
1:2:3 /* f */
) w;
endmodule
====
# A continuous assignment's delay: the gap after its `#` and the gap between
# the delay and the first left-hand side. Without the second slot the comment
# joins the first pair's leading comments, which print in front of the delay.
module m;
assign # /* g */ (1:2:3) /* h */ z = a;
endmodule
----
module m;
assign # /* g */ (1:2:3) /* h */ z = a;
endmodule
====
# A gate's multi-value list writes its own parentheses and commas, so it owns
# the comments around them: `DelayValue::{leading, trailing}`. With them the
# gate's `before_hash`, `after_hash`, the instance's `before_args` and the
# item's `before_semi`.
module m;
and /* i */ # /* j */ ( /* k */ 2 /* l */ , /* m */ 3 /* n */ ) g1 /* o */ (y, a, b) /* p */ ;
endmodule
----
module m;
and /* i */ # /* j */ ( /* k */ 2 /* l */ , /* m */ 3 /* n */ ) g1 /* o */ (y, a, b) /* p */ ;
endmodule
====
# A line comment runs to end of line, so what follows it starts a new one —
# the same rule every other slot in the formatter obeys.
module m;
wire #(1 // why
:2:3) w;
endmodule
----
module m;
wire #(
1 // why
:2:3
) w;
endmodule
====
# Nothing written in any of the slots costs a byte: the comment-free spellings
# are laid out exactly as they were before the slots existed.
module m;
wire #(1:2:3) a;
assign #(1:2:3) z = a;
and #(1, 2, 3) g1 (o, a, b);
not #(1:2:3, 4:5:6) n0 (o, a);
buf #(5) b1 (o, a);
buf #5 b2 (o, a);
buf b3 (o, a);
nand (weak0, weak1) #2 n1 (o, a, b);
and #(2, 3) g0 (y, a), g2 (z, b);
endmodule
----
module m;
wire #(1:2:3) a;
assign #(1:2:3) z = a;
and #(1, 2, 3) g1 (o, a, b);
not #(1:2:3, 4:5:6) n0 (o, a);
buf #(5) b1 (o, a);
buf #5 b2 (o, a);
buf b3 (o, a);
nand (weak0, weak1) #2 n1 (o, a, b);
and #(2, 3) g0 (y, a), g2 (z, b);
endmodule
====
# A comment between two gate instances, and one written before the `,` that
# separates them: the element's own `leading` and `before_sep`.
module m;
and #(2, 3) g0 (y, a) /* before */ , /* after */ g1 (z, b);
endmodule
----
module m;
and #(2, 3) g0 (y, a) /* before */, /* after */ g1 (z, b);
endmodule
@@ -224,3 +224,42 @@ module tb;
sub #() u1 (.a(x));
sub #(.W(8)) u2 (.a(x));
endmodule
====
# TODO §45.3 — an inline aggregate as a parameter-override argument. It is a
# type where a type is legal (IEEE 1800 §6.19, §7.2), the override a
# `parameter type` defaulting to one takes, and it prints through the existing
# type printer: a struct or union body opens, an enum body stays inline.
module m;
sub #(.T(struct packed { logic a; })) u0 ();
sub #(.T(union packed { logic [7:0] a; })) u1 ();
sub #(.T(enum logic [1:0] {A, B})) u2 ();
sub #(.T(struct packed { /* why */ logic a; })) u3 ();
sub #(.T(logic [7:0])) u4 ();
endmodule
----
module m;
sub #(
.T(
struct packed {
logic a;
}
)
) u0 ();
sub #(
.T(
union packed {
logic [7:0] a;
}
)
) u1 ();
sub #(.T(enum logic [1:0] {A, B})) u2 ();
sub #(
.T(
struct packed {
/* why */
logic a;
}
)
) u3 ();
sub #(.T(logic [7:0])) u4 ();
endmodule
@@ -53,20 +53,45 @@ module SimDTM (input clk, output [31:0] exit);
wire [31:0] #0.1 __debug_resp_bits_data = debug_resp_bits_data;
endmodule
====
# SKIP a comment written directly in front of the `#` has no slot to be
# printed from, so `verify.rs` refuses the file rather than moving it. This
# is *pre-existing* for the before-the-type position — it behaves the same
# way with no `[7:0]` in front — and the after-the-type position inherits
# it unchanged. Recorded, not fixed: giving the delay a comment slot is a
# `comment-slots` change, not a §38 one.
# a comment written directly in front of the `#` is the delay's own —
# `NetDelay::before_hash`, TODO §43.2. It was the `#SKIP` §38 recorded and
# `verify.rs` refused the file for; the slot prints it back where it was
# written, on either side of the data type.
module m;
wire /* c */ #5 x;
wire [7:0] /* d */ #1 z;
wire [3:0] /* one */ /* two */ #3 w;
endmodule
----
module m;
wire /* c */ #5 x;
wire [7:0] /* d */ #1 z;
wire [3:0] /* one */ /* two */ #3 w;
endmodule
====
# the delay's other gap, between the `#` and the value: `after_hash`. Both
# slots at once on one declaration, since the fuzzer asks for both
module m;
wire # /* why */ 5 x;
wire [7:0] /* a */ # /* b */ 1 z = q;
endmodule
----
module m;
wire # /* why */ 5 x;
wire [7:0] /* a */ # /* b */ 1 z = q;
endmodule
====
# a line comment in the same slot runs to end of line, so the `#` cannot
# follow it: it starts the next one, the way the `wire #5 /* after */` case
# below breaks before its declarator
module m;
wire // why the delay
#2 y;
endmodule
----
module m;
wire // why the delay
#2 y;
endmodule
====
# the other three gaps around a delay do have slots and round-trip
@@ -81,3 +106,16 @@ module m;
wire #5 /* after */
x;
endmodule
====
# a line comment after a gate instance's comma ends the line: the next
# instance continues one level in (§45's QA; the module-instantiation
# printer already did this)
module m;
and #(2, 3) g0 (y, a), // p
g1 (z, b);
endmodule
----
module m;
and #(2, 3) g0 (y, a), // p
g1 (z, b);
endmodule
+116 -2
View File
@@ -2350,6 +2350,16 @@ const RTL_FIXTURES: &[&str] = &[
"package p;\n typedef struct packed {\n logic [3:0] hi;\n logic [3:0] lo;\n } word_t;\n typedef enum logic [1:0] {A = 2'd0, B, C} st_e;\nendpackage\n",
"module m;\n sub #(.W(8)) u0 (.clk(clk), .d(d[3:0]), .q());\nendmodule\n",
"module m;\n assign y = cond ? a[3:0] : pkg::f(b).c;\nendmodule\n",
// A net delay on either side of the data type: the gap in front of the
// `#` is `NetDelay::before_hash` (TODO §43.2), and the fuzzer is what
// says the other gaps around it kept their owners.
"module m;\n wire #5 a;\n wire [7:0] #1 b = c;\nendmodule\n",
// A delay *list*: the `min:typ:max` spelling a net and a continuous
// assignment take, and the `(rise, fall)` spelling only a gate takes
// (TODO §45.4). The gaps around the `(`, the two `:` and the `,` had no
// owner until this round — `MinTypMaxComments`, `DelayValue`, and the
// gate's own `before_hash`/`after_hash`/`before_args`/`before_semi`.
"module m;\n wire #(1:2:3) a;\n assign #(1:2:3) z = a;\n and #(2, 3) g1 (y, a, b);\nendmodule\n",
];
#[test]
@@ -2357,8 +2367,9 @@ fn a_comment_in_every_rtl_gap_still_formats() {
assert_no_failing_gaps("RTL", RTL_FIXTURES, EXPECTED_RTL_GAPS);
}
/// Inter-token gaps across [`RTL_FIXTURES`].
const EXPECTED_RTL_GAPS: usize = 352;
/// Inter-token gaps across [`RTL_FIXTURES`]. 374 before TODO §45.4 added the
/// delay-list fixture, whose 45 gaps brought the total here.
const EXPECTED_RTL_GAPS: usize = 419;
// ----------------------------------------------------------------------
// Vendor and formal collateral — `vendor-formal-grammar`
@@ -2888,3 +2899,106 @@ fn a_structured_assertion_may_be_relaid_out() {
assert!(out.contains("lbl: assert property (@(posedge clk) disable iff (rst)"), "{out}");
assert_eq!(format_source(&out, &Config::default()).expect("and is a fixed point"), out);
}
// ----------------------------------------------------------------------
// The delay list's new comment slots — `docs/features/small-items-4/README.md`
//
// `verify.rs` was not touched and no normalization was widened; these are the
// standing attack pairs CLAUDE.md invariant 4 asks for anyway, one per token
// a slot added by TODO §45.4 is defined *between*. Each moves the comment
// across exactly that token, and each must be refused.
// ----------------------------------------------------------------------
#[test]
fn a_delay_comment_moved_across_a_min_typ_max_colon_is_rejected() {
expect_divergence(
"module m;\n wire #(1 /*c*/ : 2 : 3) w;\nendmodule\n",
"module m;\n wire #(1 : /*c*/ 2 : 3) w;\nendmodule\n",
);
expect_divergence(
"module m;\n wire #(1 : 2 /*c*/ : 3) w;\nendmodule\n",
"module m;\n wire #(1 : 2 : /*c*/ 3) w;\nendmodule\n",
);
}
#[test]
fn a_delay_comment_moved_across_the_lists_brackets_is_rejected() {
// The `(` of a one-value delay, whose slots are its `ExprKind::Paren`'s.
expect_divergence(
"module m;\n wire # /*c*/ (1:2:3) w;\nendmodule\n",
"module m;\n wire #( /*c*/ 1:2:3) w;\nendmodule\n",
);
// And the `)`.
expect_divergence(
"module m;\n wire #(1:2:3 /*c*/ ) w;\nendmodule\n",
"module m;\n wire #(1:2:3) /*c*/ w;\nendmodule\n",
);
}
#[test]
fn a_gate_delay_comment_moved_across_the_hash_or_a_comma_is_rejected() {
expect_divergence(
"module m;\n and /*c*/ #(2, 3) g (y, a);\nendmodule\n",
"module m;\n and # /*c*/ (2, 3) g (y, a);\nendmodule\n",
);
expect_divergence(
"module m;\n and #(2 /*c*/, 3) g (y, a);\nendmodule\n",
"module m;\n and #(2, /*c*/ 3) g (y, a);\nendmodule\n",
);
// The gate instance's own two new slots: before its `(` and before the `;`.
expect_divergence(
"module m;\n and #(2, 3) g /*c*/ (y, a);\nendmodule\n",
"module m;\n and #(2, 3) g ( /*c*/ y, a);\nendmodule\n",
);
expect_divergence(
"module m;\n and #(2, 3) g (y, a) /*c*/ ;\nendmodule\n",
"module m;\n and #(2, 3) g (y, a); /*c*/\nendmodule\n",
);
}
#[test]
fn a_continuous_assignments_delay_comment_moved_across_it_is_rejected() {
expect_divergence(
"module m;\n assign # /*c*/ (5) y = a;\nendmodule\n",
"module m;\n assign /*c*/ #(5) y = a;\nendmodule\n",
);
expect_divergence(
"module m;\n assign #(5) /*c*/ y = a;\nendmodule\n",
"module m;\n assign /*c*/ #(5) y = a;\nendmodule\n",
);
}
#[test]
fn a_dropped_delay_list_comment_is_rejected() {
expect_divergence(
"module m;\n and #(2 /*c*/, 3) g (y, a);\nendmodule\n",
"module m;\n and #(2, 3) g (y, a);\nendmodule\n",
);
}
// ----------------------------------------------------------------------
// The inline aggregate as a parameter-override argument — TODO §45.3
//
// A construct the parser refused until this round is a construct the safety
// net had never been asked about. These say it is asked now.
// ----------------------------------------------------------------------
#[test]
fn a_dropped_member_of_an_inline_aggregate_override_is_rejected() {
expect_divergence(
"module m;\n sub #(.T(struct packed {logic a; logic b;})) u ();\nendmodule\n",
"module m;\n sub #(.T(struct packed {logic a;})) u ();\nendmodule\n",
);
expect_divergence(
"module m;\n sub #(.T(enum logic [1:0] {A, B})) u ();\nendmodule\n",
"module m;\n sub #(.T(enum logic [1:0] {A})) u ();\nendmodule\n",
);
}
#[test]
fn a_dropped_packed_keyword_in_an_override_argument_is_rejected() {
expect_divergence(
"module m;\n sub #(.T(struct packed {logic a;})) u ();\nendmodule\n",
"module m;\n sub #(.T(struct {logic a;})) u ();\nendmodule\n",
);
}
@@ -58,7 +58,7 @@ impl Rule for DisableStatement {
let targets = disableable(ctx.file());
let mut out = Vec::new();
walk_all_stmts(ctx.file(), &mut |stmt| {
let StmtKind::Disable(name) = &stmt.kind else { return };
let StmtKind::Disable { name, .. } = &stmt.kind else { return };
// `disable fork` is the keyword form, not a label.
if name == "fork" || targets.contains(name.as_str()) {
return;
+61 -10
View File
@@ -68,13 +68,6 @@ impl Rule for UndrivenNet {
if intentionally_unused(&decl.name) || !signals.judgeable(decl) || decl.has_init {
continue;
}
// A name another file in the project writes down may be driven
// from there — a hierarchical assignment, a `force` in a
// testbench, a `bind`-ed override — none of which this file can
// see. Silence is the only honest answer.
if ctx.mentioned_elsewhere(&decl.name) {
continue;
}
let Some(usage) = signals.usage(decl) else { continue };
// A `release`/`deassign` is a write that establishes no value, so
// it is not what saves a signal from this rule.
@@ -82,6 +75,25 @@ impl Rule for UndrivenNet {
if signals.connected(decl) || driven || usage.reads == 0 {
continue;
}
// A name another file in the project writes down may be driven
// from there — a hierarchical assignment, a `force` in a
// testbench, a `bind`-ed override — none of which this file can
// see. Silence is the only honest answer.
//
// **Asked last, of the handful of declarations that would
// otherwise be reported**, and not second, of every declaration in
// the file: the oracle walks every indexed file's word list per
// question (`WorkspaceIndex::files_mentioning`), so at the position
// this check used to sit at, a 42 000-line buffer asked it four
// thousand times and the rule cost 1.6 s of every `didOpen` and
// every keystroke flush. The guards above are all local and all
// O(1)-ish, the whole condition is one conjunction of `continue`s,
// and `unused-signal` — the twin rule with the same oracle — has
// always asked last. Same findings, in the same order
// (`docs/features/didopen-cost/README.md`).
if ctx.mentioned_elsewhere(&decl.name) {
continue;
}
found.push(Violation::new(
NAME,
format!("`{}` is read but never driven", decl.name),
@@ -107,17 +119,56 @@ mod tests {
.collect()
}
/// An oracle that says exactly these names are mentioned in another file.
struct Elsewhere(&'static [&'static str]);
/// An oracle that says exactly these names are mentioned in another file,
/// and counts how often it was asked.
struct Elsewhere(&'static [&'static str], std::sync::atomic::AtomicUsize);
impl Elsewhere {
fn new(names: &'static [&'static str]) -> Elsewhere {
Elsewhere(names, std::sync::atomic::AtomicUsize::new(0))
}
}
impl crate::MentionOracle for Elsewhere {
fn mentioned_elsewhere(&self, name: &str) -> bool {
self.1.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
self.0.contains(&name)
}
}
/// TODO.md §46: the oracle is asked about the declarations that would
/// otherwise be **reported**, not about every declaration in the file.
///
/// One question per real candidate is the whole of the fix: the server's
/// oracle walks every indexed file's word list per question, so asking it
/// ahead of the local guards cost 1.6 s of every `didOpen` of opentitan's
/// 42 000-line `pinmux_reg_top.sv` — see
/// `docs/features/didopen-cost/README.md`. Asserted on the count, because
/// the findings alone cannot tell the two orders apart.
#[test]
fn the_project_is_asked_only_about_the_signals_that_would_be_reported() {
// Ten signals: nine driven and read, one read and undriven.
let mut src = String::from("module m (output logic q);\n");
for k in 0..9 {
src.push_str(&format!(" wire d{k};\n assign d{k} = 1'b0;\n"));
}
src.push_str(" wire lonely;\n assign q = lonely");
for k in 0..9 {
src.push_str(&format!(" ^ d{k}"));
}
src.push_str(";\nendmodule\n");
let oracle = Elsewhere::new(&[]);
let ctx = LintContext::new(&src, None).with_oracle(&oracle);
let found = UndrivenNet.check(&ctx);
assert_eq!(found.len(), 1, "only the undriven one: {found:#?}");
assert!(found[0].message.contains("lonely"), "{:?}", found[0].message);
let asked = oracle.1.load(std::sync::atomic::Ordering::Relaxed);
assert_eq!(asked, 1, "the project was asked about the driven signals too");
}
fn names_in_a_project(src: &str, elsewhere: &'static [&'static str]) -> Vec<String> {
let oracle = Elsewhere(elsewhere);
let oracle = Elsewhere::new(elsewhere);
let ctx = LintContext::new(src, None).with_oracle(&oracle);
UndrivenNet
.check(&ctx)
+85 -1
View File
@@ -5,7 +5,10 @@
use super::*;
/// A data type: keyword or user-defined name, plus signing and packed dims.
/// `name` may be empty for implicit types (`input [7:0] x`).
/// `name` may be empty for implicit types (`input [7:0] x`), and is the whole
/// chain a qualified type reference writes: `pkg::item`, `bus_if.mp`.
/// [`DataType::name_span`] says where it is written and
/// [`DataType::segments`] splits it.
#[derive(Debug, Clone, Default)]
pub struct DataType {
/// The `virtual` / `virtual interface` prefix of a virtual interface type
@@ -22,6 +25,14 @@ pub struct DataType {
/// so a rare field must not widen the common case.
pub virt: Option<VirtualKw>,
pub name: String,
/// Where [`DataType::name`] is written. Read it through
/// [`DataType::name_span`], which pairs it with the name's own length.
///
/// Four bytes rather than a whole [`TextRange`] because they fit in the
/// padding this struct already has: an eight-byte span pushes `DataType`
/// to 96 and, through [`ExprKind::Type`], every `Expr` to 104, past the
/// 96-byte pin in `size_pins`.
pub(crate) name_start: u32,
/// The rare tail of a type: parameterization or an anonymous aggregate
/// body. See [`TypeExtra`]; read it through [`DataType::params`] /
/// [`DataType::inline`].
@@ -57,6 +68,70 @@ impl DataType {
_ => None,
}
}
/// The byte range [`DataType::name`] occupies: `src[name_span] == name`
/// for every name the source spells the way the AST joined it, which is
/// every name but the pathological spacings [`DataType::segments`]
/// documents. An implicit type has no name, so this is the empty range at
/// the position a name would have been written — the same convention an
/// unnamed DPI formal's `name_span` uses.
pub fn name_span(&self) -> TextRange {
TextRange::new(self.name_start, self.name_start.saturating_add(self.name.len() as u32))
}
/// The `::`- and `.`-separated segments of the name — `pkg`, `item` of
/// `pkg::item`; `bus_if`, `mp` of `bus_if.mp` — each with the byte range
/// it occupies.
///
/// Derived from [`DataType::name_span`] and the name's own text: the
/// construct is never rescanned. So a source that spells the name
/// differently from the way the parser joined it — an escaped segment
/// terminated by a newline rather than a space, a `bus_if . mp` written
/// apart — hands back ranges that do not slice back to their segment.
/// A caller that must not mislocate checks the slice and drops the
/// segment; `vlog_semantic`'s binder does.
pub fn segments(&self) -> impl Iterator<Item = (&str, TextRange)> + '_ {
let base = self.name_start;
let mut rest = Some((0usize, self.name.as_str()));
std::iter::from_fn(move || {
let (at, text) = rest.take()?;
let (seg, tail) = match separator(text) {
Some((i, len)) => (&text[..i], Some((at + i + len, &text[i + len..]))),
None => (text, None),
};
rest = tail;
let start = base.saturating_add(at as u32);
Some((seg, TextRange::new(start, start.saturating_add(seg.len() as u32))))
})
.filter(|(seg, _): &(&str, TextRange)| !seg.is_empty())
}
}
/// Where the first `::`/`.` that separates two name segments starts, and how
/// many bytes it is.
///
/// An escaped identifier swallows both spellings (`\a.b ::x` is two segments,
/// not three), so one that leads the text runs to its terminating whitespace —
/// which the parser keeps in the joined name (§29) — before the search for a
/// separator begins.
fn separator(text: &str) -> Option<(usize, usize)> {
let bytes = text.as_bytes();
let mut i = 0;
if bytes.first() == Some(&b'\\') {
while i < bytes.len() && !bytes[i].is_ascii_whitespace() {
i += 1;
}
// The terminator belongs to the segment; anything else is a separator.
i = (i + 1).min(bytes.len());
}
while i < bytes.len() {
match bytes[i] {
b':' if bytes.get(i + 1) == Some(&b':') => return Some((i, 2)),
b'.' => return Some((i, 1)),
_ => i += 1,
}
}
None
}
/// What a type carries beyond its name, signing and packed dimensions. A type
@@ -246,6 +321,15 @@ pub struct ParamDecl {
/// `verify.rs` rightly refuses.
#[derive(Debug)]
pub struct NetDelay {
/// Comments written between whatever precedes the delay and its `#`:
/// the `/* c */` of `wire /* c */ #5 w;` and of
/// `wire [7:0] /* c */ #1 w;`. Without a slot here the comment would be
/// printed one node later and `verify.rs` would refuse the file.
pub before_hash: Vec<Comment>,
/// Comments written between the `#` and the delay value — the delay's
/// other gap, and the one the gap fuzzer asks about the moment the
/// first one has an owner.
pub after_hash: Vec<Comment>,
/// The delay itself: the `5` of `wire #5 w;`.
pub expr: Expr,
/// True when it stood between the data type and the declarators.
+23
View File
@@ -259,9 +259,32 @@ pub enum ExprKind {
min: Box<Expr>,
typ: Box<Expr>,
max: Box<Expr>,
/// What was written around the two `:`.
comments: Box<MinTypMaxComments>,
},
}
/// Comments written around the two `:` of a `min : typ : max` delay
/// (IEEE 1800 §28.14):
///
/// ```text
/// min /*before_typ*/ : /*after_typ*/ typ /*before_max*/ : /*after_max*/ max
/// ```
///
/// Boxed by its holder for the reason every expression-level slot is: `Expr`
/// is walked recursively and its size is pinned at 96 bytes.
#[derive(Debug, Clone, Default)]
pub struct MinTypMaxComments {
/// Between `min` and the first `:`.
pub before_typ: Vec<Comment>,
/// Just after the first `:`.
pub after_typ: Vec<Comment>,
/// Between `typ` and the second `:`.
pub before_max: Vec<Comment>,
/// Just after the second `:`.
pub after_max: Vec<Comment>,
}
/// Comments written in the fixed slots of a **postfix segment** or a
/// **bracketed range** — the one shape the grammar writes in five places:
///
+36 -1
View File
@@ -162,8 +162,15 @@ pub struct ContAssign {
/// Drive strength: the `(weak0, pull1)` in
/// `assign (weak0, pull1) x = y;` (IEEE 1800 §10.3.1), in source order.
pub strength: Option<DriveStrength>,
/// Comments written between the `#` and the delay itself.
pub after_hash: Vec<Comment>,
/// Delay expression: the `5` in `assign #5 x = y;`
pub delay: Option<Expr>,
/// Comments written between that delay and the first left-hand side.
/// Without a slot here they would join the first pair's `meta.leading`,
/// which prints straight after the `assign` — in front of the delay the
/// source wrote them behind.
pub after_delay: Vec<Comment>,
pub assigns: Vec<AssignPair>,
}
@@ -363,12 +370,37 @@ pub struct GateInstantiation {
/// The `(weak1)` in `pullup (weak1) p (x);` (IEEE 1800 §28.3), or the
/// `(strong0, strong1)` pair every driving gate also accepts.
pub strength: Option<DriveStrength>,
/// Comments written between the gate (or its drive strength) and the `#`
/// of the delay: the `/* c */` of `and /* c */ #(2, 3) g (y, a, b);`.
pub before_hash: Vec<Comment>,
/// Comments written between that `#` and the delay itself.
pub after_hash: Vec<Comment>,
/// The delay written after `#`: empty when there is none, one element for
/// every spelling a net or a continuous assignment also accepts, and two
/// or three for the `(rise, fall[, turn-off])` list that only a gate
/// takes (IEEE 1800 §28.14, `top_earlgrey/ip/ast/rtl/aon_osc.sv:41`).
pub delay: Vec<Expr>,
pub delay: Vec<DelayValue>,
pub instances: Vec<GateInstance>,
/// Comments written between the last instance and the `;`.
pub before_semi: Vec<Comment>,
}
/// One value of a delay list, with the comments written on either side of the
/// separator that reaches it.
///
/// A one-value delay keeps its comments in its own [`ExprKind::Paren`], which
/// has had the two slots all along; this shape exists for the multi-value
/// `#(rise, fall[, turn-off])` list, whose parentheses and commas the printer
/// writes itself and which therefore has nowhere else to put them. The first
/// value's `leading` is what stood just inside the `(`, and the last value's
/// `trailing` is what stood just before the `)`.
#[derive(Debug)]
pub struct DelayValue {
/// Comments between the `(` or the `,` before this value and the value.
pub leading: Vec<Comment>,
pub expr: Expr,
/// Comments between the value and the `,` or `)` that follows it.
pub trailing: Vec<Comment>,
}
#[derive(Debug)]
@@ -377,6 +409,9 @@ pub struct GateInstance {
pub name: Option<String>,
/// Byte range of `name`.
pub name_span: Option<TextRange>,
/// Comments written between the instance name and the `(` of its
/// terminal list.
pub before_args: Vec<Comment>,
pub args: Vec<ExprItem>,
/// Code extent of the gate instance.
pub span: TextRange,
+9 -2
View File
@@ -266,7 +266,14 @@ pub enum StmtKind {
},
Break,
Continue,
Disable(String),
/// `disable blk;`, `disable fork;` — the label or task the statement
/// names, with the range it is written in. A *use*, not a declaration,
/// but it is addressable all the same, so it carries a span like every
/// other name (`disable fork` spans the `fork` keyword).
Disable {
name: String,
name_span: TextRange,
},
Directive(RawText),
/// Macro invocation used as a statement.
MacroStmt(MacroCall),
@@ -323,7 +330,7 @@ impl StmtKind {
| StmtKind::Return { .. }
| StmtKind::Break
| StmtKind::Continue
| StmtKind::Disable(_)
| StmtKind::Disable { .. }
| StmtKind::WaitFork
| StmtKind::DoWhile { .. } => true,
StmtKind::Timing { stmt, .. } => stmt.is_none(),
+28 -17
View File
@@ -10,14 +10,26 @@ use super::item::MEMBER_QUALIFIERS;
use super::*;
impl<'a> Parser<'a> {
/// A type with nothing written for it, spanning the empty range at the
/// cursor: what a `parameter type T` and an implicit `input [7:0] x`
/// both carry. Distinct from [`DataType::default`] only in that its
/// `name_span` points at the source rather than at offset zero.
pub(super) fn implicit_type(&self) -> DataType {
DataType { name_start: self.here(), ..DataType::default() }
}
/// Parse a possibly-implicit data type. Stops before the declarator name.
pub(super) fn parse_opt_data_type(&mut self) -> PResult<DataType> {
let mut ty = DataType::default();
// An implicit type writes no name at all, so its `name_span` is the
// empty range where a name would have gone: right here, before
// anything of the type has been consumed.
let mut ty = self.implicit_type();
// `property p(sequence a, property b);` — inside a property's or a
// sequence's formal list, and nowhere else, the two keywords name a
// formal's *type* (IEEE 1800 §16.8). `untyped` needs no case: it is
// an ordinary identifier and already reads as a user-defined type.
if self.sva_formals && (self.cur().is_kw("sequence") || self.cur().is_kw("property")) {
ty.name_start = self.here();
ty.name = self.bump().text;
return Ok(ty);
}
@@ -35,7 +47,9 @@ impl<'a> Parser<'a> {
// Glued onto the interface name exactly as an interface *port*'s
// modport is, so every consumer still sees one type-name string.
if self.at_modport_port() {
ty.name = self.parse_modport_port_type()?.name;
let head = self.parse_modport_port_type()?;
ty.name = head.name;
ty.name_start = head.name_start;
return Ok(ty);
}
}
@@ -53,18 +67,15 @@ impl<'a> Parser<'a> {
return Ok(ty);
}
if t.kind == TokenKind::Keyword && TYPE_KEYWORDS.contains(&t.text.as_str()) {
ty.name_start = self.here();
ty.name = self.bump().text;
} else if t.kind == TokenKind::Ident {
// User-defined type only if what follows still leaves an
// identifier for the declarator name.
if self.at_typed_declarator() {
let mut name = self.expect_ident()?;
while self.cur().is_sym("::") {
self.bump();
let segment = self.expect_ident()?;
Self::push_scope_segment(&mut name, &segment);
}
let (name, span) = self.parse_scoped_name()?;
ty.name = name;
ty.name_start = span.start;
if self.at_type_params() {
ty.extra = Some(Box::new(TypeExtra::Params(self.parse_type_params()?)));
}
@@ -187,7 +198,7 @@ impl<'a> Parser<'a> {
// parameter outside the `#( ... )` list
// (lossy_valid_to_stream_tb.sv:26). Its default is a type, not a value.
let is_type = self.eat_kw("type");
let ty = if is_type { DataType::default() } else { self.parse_opt_data_type()? };
let ty = if is_type { self.implicit_type() } else { self.parse_opt_data_type()? };
let declarators = self.parse_declarator_list(is_type)?;
Ok(ParamDecl { kw, after_kw, is_type, ty, declarators })
}
@@ -284,8 +295,13 @@ impl<'a> Parser<'a> {
if !is_net || !self.cur().is_sym("#") {
return Ok(None);
}
// The `#` is written, so the gap in front of it is the delay's own:
// `wire /* c */ #5 w;`. Taken only here — when the read does not
// happen the gap belongs to whatever comes next.
let before_hash = self.take_gap();
self.bump();
Ok(Some(NetDelay { expr: self.parse_delay_value()?, after_type }))
let after_hash = self.take_gap();
Ok(Some(NetDelay { before_hash, after_hash, expr: self.parse_delay_value()?, after_type }))
}
pub(super) fn parse_port_decl(&mut self) -> PResult<PortDecl> {
@@ -469,13 +485,8 @@ impl<'a> Parser<'a> {
if !ty.is_implicit() || self.cur().kind != TokenKind::Ident {
return Ok(ty);
}
let mut name = self.expect_ident()?;
while self.cur().is_sym("::") {
self.bump();
let segment = self.expect_ident()?;
Self::push_scope_segment(&mut name, &segment);
}
let mut ty = DataType { name, ..DataType::default() };
let (name, span) = self.parse_scoped_name()?;
let mut ty = DataType { name, name_start: span.start, ..DataType::default() };
if self.at_type_params() {
ty.extra = Some(Box::new(TypeExtra::Params(self.parse_type_params()?)));
}
+80 -28
View File
@@ -21,9 +21,17 @@ impl<'a> Parser<'a> {
pub(super) fn parse_cont_assign(&mut self) -> PResult<ContAssign> {
self.expect_kw("assign")?;
let strength = self.parse_opt_drive_strength()?;
let mut after_hash = Vec::new();
let mut after_delay = Vec::new();
let delay = if self.cur().is_sym("#") {
self.bump();
Some(self.parse_delay_value()?)
after_hash = self.take_gap();
let delay = self.parse_delay_value()?;
// The gap between the delay and the first left-hand side is the
// delay's, not the pair's: a pair's leading comments print right
// after the `assign`, which is in front of the delay.
after_delay = self.take_gap();
Some(delay)
} else {
None
};
@@ -55,7 +63,7 @@ impl<'a> Parser<'a> {
}
}
self.expect_sym(";")?;
Ok(ContAssign { strength, delay, assigns })
Ok(ContAssign { strength, after_hash, delay, after_delay, assigns })
}
/// The optional `( strength0 , strength1 )` of a continuous assignment
@@ -94,46 +102,75 @@ impl<'a> Parser<'a> {
/// spelling has always produced, so `#(5)` and `#(1:2:3)` still print
/// exactly as written; only a real comma list yields more than one
/// element.
fn parse_delay_values(&mut self) -> PResult<Vec<Expr>> {
fn parse_delay_values(&mut self) -> PResult<Vec<DelayValue>> {
if !self.cur().is_sym("(") {
return Ok(vec![self.parse_primary()?]);
let expr = self.parse_primary()?;
return Ok(vec![DelayValue { leading: Vec::new(), expr, trailing: Vec::new() }]);
}
let start = self.here();
self.bump(); // (
let mut out = Vec::new();
// What is written just inside the `(` belongs to the first value; the
// gap before each `,` and the gap after it belong to the values either
// side of it.
self.bump();
let mut leading = self.take_gap();
let mut out: Vec<DelayValue> = Vec::new();
loop {
let inner_start = self.here();
let first = self.parse_expr()?;
out.push(if self.eat_sym(":") {
let typ = self.parse_expr()?;
self.expect_sym(":")?;
let max = self.parse_expr()?;
self.expr_at(
inner_start,
ExprKind::MinTypMax {
min: Box::new(first),
typ: Box::new(typ),
max: Box::new(max),
},
)
} else {
first
});
let expr = self.parse_min_typ_max_tail(inner_start, first)?;
let trailing = self.gap_before(",");
out.push(DelayValue { leading: std::mem::take(&mut leading), expr, trailing });
if !self.eat_sym(",") {
break;
}
leading = self.take_gap();
}
if let Some(last) = out.last_mut() {
last.trailing = self.gap_before(")");
}
self.expect_sym(")")?;
if out.len() == 1 {
let inner = out.remove(0);
return Ok(vec![self.expr_at(
// One value keeps the `( )` node the one-value spelling has always
// produced, and its two comment slots are where the paren gaps go.
let DelayValue { leading, expr, trailing } = out.remove(0);
let paren = self.expr_at(
start,
ExprKind::Paren { inner: Box::new(inner), before: Vec::new(), after: Vec::new() },
)]);
ExprKind::Paren { inner: Box::new(expr), before: leading, after: trailing },
);
return Ok(vec![DelayValue { leading: Vec::new(), expr: paren, trailing: Vec::new() }]);
}
Ok(out)
}
/// The `: typ : max` tail of a `min : typ : max` expression, or `min`
/// unchanged when no `:` follows it.
///
/// One grammar for the two places that write it — a delay list and a
/// parenthesized expression — so the four comment slots around the two
/// colons exist in both.
pub(super) fn parse_min_typ_max_tail(&mut self, start: u32, min: Expr) -> PResult<Expr> {
let before_typ = self.gap_before(":");
if !self.eat_sym(":") {
return Ok(min);
}
let mut comments = MinTypMaxComments { before_typ, ..Default::default() };
comments.after_typ = self.take_gap();
let typ = self.parse_expr()?;
comments.before_max = self.gap_before(":");
self.expect_sym(":")?;
comments.after_max = self.take_gap();
let max = self.parse_expr()?;
Ok(self.expr_at(
start,
ExprKind::MinTypMax {
min: Box::new(min),
typ: Box::new(typ),
max: Box::new(max),
comments: Box::new(comments),
},
))
}
/// The single delay value a net declaration or a continuous assignment
/// takes. The multi-value list is a gate-instantiation spelling only —
/// see [`Parser::parse_delay_values`].
@@ -142,7 +179,9 @@ impl<'a> Parser<'a> {
if values.len() > 1 {
return self.error("a multi-value delay list is only allowed on a gate instantiation");
}
Ok(values.remove(0))
// A lone value carries no comments of its own: `parse_delay_values`
// folded the paren gaps into its `ExprKind::Paren`.
Ok(values.remove(0).expr)
}
/// True when the cursor opens a `bind` directive (IEEE 1800 §23.11).
@@ -647,8 +686,11 @@ impl<'a> Parser<'a> {
// instance's argument list would, and only a strength keyword after
// the `(` tells the two apart.
let strength = self.parse_opt_drive_strength()?;
let before_hash = self.take_before_open("#");
let mut after_hash = Vec::new();
let delay = if self.cur().is_sym("#") {
self.bump();
after_hash = self.take_gap();
self.parse_delay_values()?
} else {
Vec::new()
@@ -660,6 +702,7 @@ impl<'a> Parser<'a> {
let name =
if self.cur().kind == TokenKind::Ident { Some(self.expect_name()?) } else { None };
let (name, name_span) = split_label(name);
let before_args = self.take_before_open("(");
self.expect_sym("(")?;
let mut args = Vec::new();
if !self.cur().is_sym(")") {
@@ -673,12 +716,21 @@ impl<'a> Parser<'a> {
if more {
meta.trailing = self.take_trailing();
}
instances.push(GateInstance { meta, name, name_span, args, span });
instances.push(GateInstance { meta, name, name_span, before_args, args, span });
if !more {
break;
}
}
let before_semi = self.gap_before(";");
self.expect_sym(";")?;
Ok(GateInstantiation { gate, strength, delay, instances })
Ok(GateInstantiation {
gate,
strength,
before_hash,
after_hash,
delay,
instances,
before_semi,
})
}
}
@@ -167,18 +167,21 @@ impl<'a> Parser<'a> {
// `disable fork;` kills every process the enclosing `fork`
// started; `fork` is a keyword, not a block name.
if self.cur().is_kw("fork") {
let name_span = self.cur().span;
self.bump();
self.expect_stmt_semi()?;
return Ok(StmtKind::Disable("fork".to_string()));
return Ok(StmtKind::Disable { name: "fork".to_string(), name_span });
}
let start = self.here();
let mut name = self.expect_ident()?;
while self.cur().is_sym(".") {
self.bump();
name.push('.');
name.push_str(&self.expect_ident()?);
}
let name_span = self.span_from(start);
self.expect_stmt_semi()?;
Ok(StmtKind::Disable(name))
Ok(StmtKind::Disable { name, name_span })
}
"wait" => {
self.bump();
+6 -3
View File
@@ -412,7 +412,7 @@ impl<'a> Parser<'a> {
meta,
kw,
after_kw,
ty: DataType::default(),
ty: self.implicit_type(),
is_type: true,
before_name,
name,
@@ -624,12 +624,15 @@ impl<'a> Parser<'a> {
/// The `bus_if.mp` of an interface port, as its type. The modport is glued
/// onto the interface name exactly as a `pkg::` qualifier is, so every
/// consumer that prints or scans a type name still sees one string.
/// consumer that prints a type name still sees one string;
/// [`DataType::segments`] splits it back into its two halves and their
/// ranges.
pub(super) fn parse_modport_port_type(&mut self) -> PResult<DataType> {
let name_start = self.here();
let mut name = self.expect_ident()?;
self.expect_sym(".")?;
name.push('.');
name.push_str(&self.expect_ident()?);
Ok(DataType { name, ..DataType::default() })
Ok(DataType { name, name_start, ..DataType::default() })
}
}
+11 -15
View File
@@ -97,21 +97,7 @@ impl<'a> Parser<'a> {
let mark = self.pending_trailing.len();
let inner_start = self.here();
let inner = self.parse_expr()?;
let inner = if self.eat_sym(":") {
let typ = self.parse_expr()?;
self.expect_sym(":")?;
let max = self.parse_expr()?;
self.expr_at(
inner_start,
ExprKind::MinTypMax {
min: Box::new(inner),
typ: Box::new(typ),
max: Box::new(max),
},
)
} else {
inner
};
let inner = self.parse_min_typ_max_tail(inner_start, inner)?;
let after = self.take_around(mark);
self.expect_sym(")")?;
Ok(self.expr_at(
@@ -454,8 +440,18 @@ impl<'a> Parser<'a> {
}
/// In parameter connections a value may be a type (`.T(logic [7:0])`).
///
/// An **anonymous aggregate** is a type too — `.T(struct packed { logic a;
/// })`, the override a `parameter type` defaulting to one takes (IEEE 1800
/// §6.19, §7.2). `parse_type_ref` has read that body since the first day;
/// only this door was closed, because `struct`/`union`/`enum` are not in
/// [`TYPE_KEYWORDS`] and so fell through to `parse_expr`, whose keyword arm
/// answers "unexpected keyword `struct` in expression".
pub(super) fn parse_expr_or_type(&mut self) -> PResult<Expr> {
let t = self.cur();
if t.is_kw("struct") || t.is_kw("union") || t.is_kw("enum") {
return self.parse_type_expr();
}
if t.kind == TokenKind::Keyword
&& TYPE_KEYWORDS.contains(&t.text.as_str())
&& !self.nth(1).is_sym("'")
@@ -190,7 +190,7 @@ fn a_gate_takes_a_multi_value_delay_list() {
// The one-value parenthesized spelling keeps its `Paren` node, which
// is what makes `#(5)` print back as `#(5)` and not as `#5`.
let ItemKind::GateInstantiation(g) = &m.items[2].kind else { panic!("expected a gate") };
assert!(matches!(g.delay[0].kind, ExprKind::Paren { .. }));
assert!(matches!(g.delay[0].expr.kind, ExprKind::Paren { .. }));
}
#[test]
@@ -218,3 +218,41 @@ fn a_bind_instance_may_be_a_hierarchical_path() {
let ItemKind::Bind(b) = &f.items[0].kind else { panic!("expected a bind") };
assert_eq!(b.instances.iter().map(|i| i.text.as_str()).collect::<Vec<_>>(), ["a.b", "plain"]);
}
#[test]
fn an_inline_aggregate_is_a_parameter_override_argument() {
// TODO §45.3: a `parameter type` defaulting to an anonymous aggregate is
// overridden with one, and `parse_type_ref` has read that body all along —
// only `parse_expr_or_type`'s door was shut (`struct`/`union`/`enum` are
// not `TYPE_KEYWORDS`), so the value read as an expression and failed.
for src in [
"module m;\n sub #(.T(struct packed { logic a; })) u ();\nendmodule\n",
"module m;\n sub #(.T(union packed { logic [7:0] a; })) u ();\nendmodule\n",
"module m;\n sub #(.T(enum logic [1:0] {A, B})) u ();\nendmodule\n",
"module m;\n sub #(.T(struct packed { /* why */ logic a; })) u ();\nendmodule\n",
] {
let f = parse_ok(src);
let ItemKind::Instantiation(i) = &module_of(&f).items[0].kind else {
panic!("expected an instantiation")
};
let params = i.params.as_ref().expect("an override list");
let value = oks(params)[0].expr.as_ref().expect("a value");
assert!(matches!(value.kind, ExprKind::Type(_)), "{src:?} read as {:?}", value.kind);
// Strict and tolerant must agree: the tolerant parser reports nothing
// where the strict one succeeds.
let (_, diags) = crate::parse_source_tolerant(src);
assert!(diags.is_empty(), "{src:?} left {diags:?}");
}
}
#[test]
fn an_ordered_parameter_override_takes_an_inline_aggregate_too() {
// The bare-expression arm of `parse_connection` shares `parse_expr_or_type`
// with the named one, so both doors opened at once.
let f = parse_ok("module m;\n sub #(struct packed { logic a; }) u ();\nendmodule\n");
let ItemKind::Instantiation(i) = &module_of(&f).items[0].kind else {
panic!("expected an instantiation")
};
let params = i.params.as_ref().expect("an override list");
assert!(matches!(oks(params)[0].expr.as_ref().expect("a value").kind, ExprKind::Type(_)));
}
+119 -3
View File
@@ -614,7 +614,7 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
}
ItemKind::GateInstantiation(g) => {
for d in &g.delay {
check_expr(src, d, here);
check_expr(src, &d.expr, here);
}
for i in &g.instances {
assert_inside(src, "gate instance", i.span, here);
@@ -1011,10 +1011,12 @@ fn check_stmt(src: &str, stmt: &Stmt, parent: TextRange) {
check_stmt(src, inner, here);
}
StmtKind::Import(paths) => check_import_paths(src, paths, here),
StmtKind::Disable { name, name_span } => {
check_name(src, "disable target", name, *name_span, here)
}
StmtKind::Break
| StmtKind::Continue
| StmtKind::WaitFork
| StmtKind::Disable(_)
| StmtKind::Null
| StmtKind::Error(_) => {}
StmtKind::Assertion(a) => check_assertion(src, a, here),
@@ -1227,7 +1229,7 @@ fn check_expr(src: &str, e: &Expr, parent: TextRange) {
check_expr(src, lo, here);
check_expr(src, hi, here);
}
ExprKind::MinTypMax { min, typ, max } => {
ExprKind::MinTypMax { min, typ, max, .. } => {
check_expr(src, min, here);
check_expr(src, typ, here);
check_expr(src, max, here);
@@ -1669,3 +1671,117 @@ fn check_constraint_set(src: &str, set: &ConstraintSet, parent: TextRange) {
}
}
}
// ----------------------------------------------------------------------
// Type-name spans (TODO.md §47)
// ----------------------------------------------------------------------
/// Every `DataType` a source file writes, in item order, with the declarator
/// it belongs to left behind — enough to reach each construction site by hand.
fn module_types(file: &SourceFile) -> Vec<&DataType> {
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let mut out = Vec::new();
if let PortList::Ansi(ports) = &m.ports {
out.extend(ports.iter().filter_map(ListElem::ok).map(|p| &p.ty));
}
for item in &m.items {
match &item.kind {
ItemKind::DataDecl(d) => out.push(&d.ty),
ItemKind::Typedef(t) => {
if let TypedefKind::Alias(ty) = &t.kind {
out.push(ty);
}
}
_ => {}
}
}
out
}
#[test]
fn a_type_name_span_slices_back_to_the_name_as_written() {
let src = "\
module m (input bus_if.mp bus, input [7:0] raw);
typedef pkg_a::state_t alias_t;
logic [3:0] plain;
my_type_t user;
virtual clk_rst_if vif;
endmodule
";
let file = parse_source(src).expect("parse error");
let types = module_types(&file);
let seen: Vec<&str> = types.iter().map(|ty| slice(src, ty.name_span())).collect();
assert_eq!(seen, ["bus_if.mp", "", "pkg_a::state_t", "logic", "my_type_t", "clk_rst_if"]);
for ty in &types {
assert_eq!(slice(src, ty.name_span()), ty.name, "a type-name span moved off its name");
}
// The implicit `input [7:0] raw` has no name, so its span is the empty
// range where one would have been written — at the `[`.
let implicit = types[1].name_span();
assert!(implicit.is_empty());
assert_eq!(&src[implicit.start as usize..implicit.start as usize + 1], "[");
}
#[test]
fn segments_split_a_qualified_type_name_without_rescanning() {
let src = "\
module m (input bus_if.mp bus);
pkg_a::state_t s;
logic plain;
endmodule
";
let file = parse_source(src).expect("parse error");
let types = module_types(&file);
let split = |ty: &DataType| -> Vec<(String, String)> {
ty.segments().map(|(seg, span)| (seg.to_string(), slice(src, span).to_string())).collect()
};
assert_eq!(split(types[0]), [("bus_if".into(), "bus_if".into()), ("mp".into(), "mp".into())]);
assert_eq!(
split(types[1]),
[("pkg_a".into(), "pkg_a".into()), ("state_t".into(), "state_t".into())]
);
assert_eq!(split(types[2]), [("logic".to_string(), "logic".to_string())]);
// An implicit type has no name and so no segments at all.
let empty = DataType::default();
assert_eq!(empty.segments().count(), 0);
}
#[test]
fn an_escaped_segment_keeps_its_terminating_space_in_span_and_segment() {
// §29: the parser joins `\a+b ::state_t` with the space the escaped
// identifier needs, so the joined name is what the source spells and the
// first segment carries the terminator.
let src = "module m;\n \\a+b ::state_t s;\nendmodule\n";
let file = parse_source(src).expect("parse error");
let types = module_types(&file);
assert_eq!(types[0].name, "\\a+b ::state_t");
assert_eq!(slice(src, types[0].name_span()), "\\a+b ::state_t");
let segs: Vec<&str> = types[0].segments().map(|(_, span)| slice(src, span)).collect();
assert_eq!(segs, ["\\a+b ", "state_t"]);
}
#[test]
fn a_disable_names_its_target_with_a_span() {
let src = "\
module m;
initial begin : blk
disable blk;
disable fork;
end
endmodule
";
let file = parse_source(src).expect("parse error");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let ItemKind::Initial(outer) = &m.items[0].kind else { panic!("expected an initial") };
let StmtKind::Block { stmts, .. } = &outer.kind else { panic!("expected a block") };
let targets: Vec<&str> = stmts
.iter()
.map(|s| {
let StmtKind::Disable { name_span, .. } = &s.kind else { panic!("expected a disable") };
slice(src, *name_span)
})
.collect();
assert_eq!(targets, ["blk", "fork"]);
}
+43 -6
View File
@@ -353,19 +353,24 @@ fn params(module: &Module, text: &str) -> Vec<PlanParam> {
/// A parameter's default as an override list can write it, or nothing.
///
/// Two things disqualify one, and the corpus produced both from a single
/// header (`common_cells/src/ecc_encode.sv`, a `parameter type` defaulting to
/// an anonymous multi-line `struct packed`):
/// Two things disqualify one:
///
/// * it is written across several lines — the source's own indentation means
/// nothing inside a `#( ... )` on someone else's line, and re-flowing it
/// would risk rewriting a string literal's spaces;
/// * writing it back does not parse — lucisv's expression grammar does not
/// accept an inline aggregate as a parameter override, and a skeleton that
/// does not parse hands the user a red squiggle from our own server.
/// * writing it back does not parse, which the probe below asks rather than
/// guesses, because a skeleton that does not parse hands the user a red
/// squiggle from our own server.
///
/// A default lucisv cannot write back is simply not offered: the tabstop comes
/// up empty and the user types what they meant.
///
/// The probe is what makes this grow with the grammar. An **inline aggregate**
/// default (`parameter type T = struct packed { logic a; }`) used to fail it —
/// the override grammar refused a `struct` head — and was dropped; since
/// TODO §45.3 the same probe passes and the type text is emitted. Only the
/// multi-line spelling, which the corpus's `common_cells/src/ecc_encode.sv`
/// writes, is still refused, and by the first rule rather than the second.
fn default_text(text: &str, param: &ParamPort) -> String {
let Some(expr) = &param.default else { return String::new() };
let written = slice(text, expr.span).trim();
@@ -743,6 +748,38 @@ endmodule
assert!(parse_source_tolerant(&probe).1.is_empty(), "the skeleton must parse: {skeleton}");
}
#[test]
fn a_one_line_inline_aggregate_default_is_emitted() {
// TODO §45.3: the override grammar accepts an inline aggregate, so the
// probe in `default_text` passes and the type text is offered instead
// of an empty tabstop. Only the multi-line spelling is still dropped,
// by the "written across several lines" rule above it.
let text = "\
module agg #(
parameter type packed_t = struct packed {logic parity; logic [7:0] word;},
parameter type state_e = enum logic [1:0] {IDLE, BUSY}
) ();
endmodule
";
let plan = plan(text, "agg");
assert_eq!(
plan.params,
vec![
PlanParam {
name: "packed_t".into(),
default: "struct packed {logic parity; logic [7:0] word;}".into(),
},
PlanParam {
name: "state_e".into(),
default: "enum logic [1:0] {IDLE, BUSY}".into(),
},
]
);
let skeleton = plan.render(&Layout::default());
let probe = format!("module p;\n{skeleton}\nendmodule\n");
assert!(parse_source_tolerant(&probe).1.is_empty(), "the skeleton must parse: {skeleton}");
}
#[test]
fn a_multi_line_type_is_shown_on_one_line() {
let text = "\
+1 -1
View File
@@ -324,7 +324,7 @@ impl<'a> Scope<'a> {
/// not about every unresolved identifier in the file.
fn unresolved_unit(resolution: &Resolution) -> Option<String> {
match resolution {
Resolution::ExternalCandidate { paths } => {
Resolution::ExternalCandidate { paths, .. } => {
let first = paths.first()?;
Some(first.rsplit_once("::")?.0.to_string())
}
+180
View File
@@ -853,6 +853,186 @@ fn a_hierarchical_tail_that_resolves_is_renamed_with_its_declaration() {
);
}
// ----------------------------------------------------------------------
// the hierarchical surface, across files (TODO.md §49)
// ----------------------------------------------------------------------
/// The cross-file twin of the test above, which is the whole of §49: the
/// module and the instance that names into it are in **different** files, and
/// the edit has to land in both. Before 2026-09-05 a module exported its
/// ports and parameters only, so `u_sub.sig` could not be finished across a
/// file boundary — `sub.sv` was edited alone and `top.sv` got the §2.9-20
/// warning instead of an edit.
#[test]
fn a_cross_file_hierarchical_tail_is_renamed_with_its_declaration() {
const SUB: &str = "module sub;\n wire sig;\n assign sig = 1'b0;\nendmodule\n";
const TOP: &str =
"module top;\n sub u_sub ();\n wire w;\n assign w = u_sub.sig;\nendmodule\n";
let files = workspace(&[("sub.sv", SUB), ("top.sv", TOP)]);
for (from, text, name) in [("sub.sv", SUB, "wire"), ("top.sv", TOP, "u_sub.")] {
let edit = rename(&files, &path(from), at(text, name, "sig"), "signal")
.unwrap_or_else(|e| panic!("renames from {from}: {e}"));
assert_eq!(
apply(SUB, &edit, &path("sub.sv")),
"module sub;\n wire signal;\n assign signal = 1'b0;\nendmodule\n",
"the declaration and its own file's uses, from {from}"
);
assert_eq!(
apply(TOP, &edit, &path("top.sv")),
"module top;\n sub u_sub ();\n wire w;\n assign w = u_sub.signal;\nendmodule\n",
"and the tail in the other file, from {from}"
);
assert!(
!edit.warnings.iter().any(|w| w.contains("could not be resolved")),
"the §2.9-20 warning is retired for a tail that resolved, from {from}: {:?}",
edit.warnings
);
}
}
/// `u_a.u_b.sig`: two hops, three files. The middle hop is an **instance**,
/// which is on the hierarchical surface for exactly this reason — without it
/// `u_b` has no declared type and the walk stops one segment short of `sig`.
#[test]
fn a_nested_cross_file_hierarchical_tail_is_renamed_through_both_hops() {
const LEAF: &str = "module leaf;\n wire sig;\nendmodule\n";
const MID: &str = "module mid;\n leaf u_b ();\nendmodule\n";
const TOP: &str =
"module top;\n mid u_a ();\n wire w;\n assign w = u_a.u_b.sig;\nendmodule\n";
let files = workspace(&[("leaf.sv", LEAF), ("mid.sv", MID), ("top.sv", TOP)]);
let edit =
rename(&files, &path("leaf.sv"), at(LEAF, "wire", "sig"), "signal").expect("renames");
assert_eq!(apply(LEAF, &edit, &path("leaf.sv")), "module leaf;\n wire signal;\nendmodule\n");
assert_eq!(
apply(TOP, &edit, &path("top.sv")),
"module top;\n mid u_a ();\n wire w;\n assign w = u_a.u_b.signal;\nendmodule\n",
"the two-hop tail is edited"
);
assert_eq!(apply(MID, &edit, &path("mid.sv")), MID, "and the file in between is untouched");
}
/// A tail naming a **port**, which is on the connection surface and therefore
/// found by *both* reads. One declaration, one answer, one edit — the check
/// that the hierarchical read consulting the connection table first is not
/// producing a duplicate.
#[test]
fn a_tail_naming_a_port_is_one_answer_and_one_edit() {
const SUB: &str = "module sub (input wire clk_i);\n wire w;\n assign w = clk_i;\nendmodule\n";
const TOP: &str =
"module top;\n wire c;\n sub u_sub (.clk_i(c));\n wire w;\n assign w = u_sub.clk_i;\nendmodule\n";
let files = workspace(&[("sub.sv", SUB), ("top.sv", TOP)]);
let edit = rename(&files, &path("sub.sv"), at(SUB, "input wire", "clk_i"), "clock_i")
.expect("renames");
assert_eq!(
apply(SUB, &edit, &path("sub.sv")),
"module sub (input wire clock_i);\n wire w;\n assign w = clock_i;\nendmodule\n"
);
assert_eq!(
apply(TOP, &edit, &path("top.sv")),
"module top;\n wire c;\n sub u_sub (.clock_i(c));\n wire w;\n assign w = u_sub.clock_i;\nendmodule\n",
"the connection and the hierarchical tail, each once"
);
let tail = at(TOP, "u_sub.", "clk_i");
assert_eq!(
edit.edits_for(&path("top.sv")).iter().filter(|e| e.range.start == tail).count(),
1,
"the tail is edited once, not once per surface: {:?}",
edit.edits_for(&path("top.sv"))
);
}
/// The same for a **parameter**, the other half of the connection surface.
#[test]
fn a_tail_naming_a_parameter_is_renamed_across_files() {
const SUB: &str = "module sub #(parameter int W = 8) ();\nendmodule\n";
const TOP: &str = "module top;\n sub u_sub ();\n localparam int N = u_sub.W;\nendmodule\n";
let files = workspace(&[("sub.sv", SUB), ("top.sv", TOP)]);
let edit =
rename(&files, &path("sub.sv"), at(SUB, "parameter int", "W"), "WIDTH").expect("renames");
assert_eq!(
apply(SUB, &edit, &path("sub.sv")),
"module sub #(parameter int WIDTH = 8) ();\nendmodule\n"
);
assert_eq!(
apply(TOP, &edit, &path("top.sv")),
"module top;\n sub u_sub ();\n localparam int N = u_sub.WIDTH;\nendmodule\n"
);
}
/// 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.
#[test]
fn a_generate_block_scoped_net_named_through_an_instance_is_refused_honestly() {
const SUB: &str = concat!(
"module sub;\n",
" if (1) begin : gen_b\n",
" wire sig;\n",
" end\n",
"endmodule\n"
);
const TOP: &str =
"module top;\n sub u_x ();\n wire w;\n assign w = u_x.gen_b.sig;\nendmodule\n";
let files = workspace(&[("sub.sv", SUB), ("top.sv", TOP)]);
let edit = rename(&files, &path("sub.sv"), at(SUB, "wire", "sig"), "signal").expect("renames");
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"
);
}
/// An **interface** instance's tail already resolved before §49 — an
/// interface's signals are its connection surface (2026-09-01) — and it must
/// still resolve exactly the same way, through the connection table.
#[test]
fn an_interface_instance_tail_is_unchanged_by_the_hierarchical_surface() {
const IF: &str = "interface bus_if;\n logic data;\nendinterface\n";
const TOP: &str =
"module top;\n bus_if u_bus ();\n wire w;\n assign w = u_bus.data;\nendmodule\n";
let files = workspace(&[("bus_if.sv", IF), ("top.sv", TOP)]);
let edit =
rename(&files, &path("bus_if.sv"), at(IF, "logic", "data"), "payload").expect("renames");
assert_eq!(
apply(IF, &edit, &path("bus_if.sv")),
"interface bus_if;\n logic payload;\nendinterface\n"
);
assert_eq!(
apply(TOP, &edit, &path("top.sv")),
"module top;\n bus_if u_bus ();\n wire w;\n assign w = u_bus.payload;\nendmodule\n"
);
}
/// The verifier's refusal is not weakened by the new surface: two files each
/// declaring `module sub`, and a tail naming into one of them. Which `sub`
/// the instance means is not something the workspace can say, so the rename
/// refuses from either end rather than editing one of the two.
#[test]
fn an_ambiguous_module_behind_a_hierarchical_tail_is_still_refused() {
const ONE: &str = "module sub;\n wire sig;\nendmodule\n";
const TWO: &str = "module sub;\n wire sig;\nendmodule\n";
const TOP: &str = "module top;\n sub u_x ();\n wire w;\n assign w = u_x.sig;\nendmodule\n";
let files = workspace(&[("one.sv", ONE), ("two.sv", TWO), ("top.sv", TOP)]);
let message = rename(&files, &path("one.sv"), at(ONE, "wire", "sig"), "signal")
.expect_err("an ambiguous tail must be refused");
assert!(message.contains("more than one"), "{message}");
let message = rename(&files, &path("top.sv"), at(TOP, "u_x.", "sig"), "signal")
.expect_err("and from the tail itself");
assert!(message.contains("more than one"), "{message}");
}
#[test]
fn a_hierarchical_tail_that_cannot_resolve_is_left_alone_and_named_as_such() {
// The module behind the instance is nowhere in the workspace, so the tail
+1 -1
View File
@@ -352,7 +352,7 @@ impl<'a> Binder<'a> {
// Return type, arguments and body all resolve from inside the class,
// as the LRM says an out-of-body declaration does.
if let Some(ret) = ret {
self.bind_data_type(ret, TextRange::new(span.start, name_span.start), body);
self.bind_data_type(ret, body);
}
self.bind_tf_args(args, body);
self.bind_stmts(stmts, body);
+52 -70
View File
@@ -9,7 +9,6 @@ use vlog_parser::span::TextRange;
use vlog_parser::token::is_keyword;
use crate::model::{ScopeId, ScopeKind, SymbolId, SymbolKind};
use crate::scan::NameScanner;
use super::{type_name_of, Binder, Target};
@@ -39,7 +38,7 @@ impl<'a> Binder<'a> {
if let Some(written) = &p.kw {
kw.clone_from(written);
}
self.bind_data_type(&p.ty, TextRange::new(p.span.start, p.name_span.start), scope);
self.bind_data_type(&p.ty, scope);
let ty = p.unpacked.is_empty().then_some(&p.ty);
self.declare_typed(scope, &p.name, param_kind(&kw), p.name_span, p.span, ty);
self.bind_dims(&p.unpacked, scope);
@@ -51,7 +50,7 @@ impl<'a> Binder<'a> {
/// in [`Binder::bind_param_ports`].
pub(super) fn bind_tf_args(&mut self, args: &'a [ListElem<TfArg>], scope: ScopeId) {
for a in args.iter().filter_map(ListElem::ok) {
self.bind_data_type(&a.ty, TextRange::new(a.span.start, a.name_span.start), scope);
self.bind_data_type(&a.ty, scope);
let ty = a.unpacked.is_empty().then_some(&a.ty);
self.declare_typed(scope, &a.name, SymbolKind::TfArg, a.name_span, a.span, ty);
self.bind_dims(&a.unpacked, scope);
@@ -68,13 +67,13 @@ impl<'a> Binder<'a> {
// a container, not a value of the type, and is left untyped on
// the same rule every other unpacked declarator follows.
TypedefKind::Alias(ty) => {
self.bind_data_type(ty, TextRange::new(span.start, ns.start), scope);
self.bind_data_type(ty, scope);
let ty = t.unpacked.is_empty().then_some(ty);
self.declare_typed(scope, &t.name, SymbolKind::Typedef, ns, span, ty);
}
TypedefKind::Enum(e) => {
self.declare(scope, &t.name, SymbolKind::Typedef, ns, span);
self.bind_enum_body(e, TextRange::new(span.start, ns.start), scope);
self.bind_enum_body(e, scope);
}
TypedefKind::Struct(s) => {
let inner = self.declare_with_scope(
@@ -103,9 +102,9 @@ impl<'a> Binder<'a> {
/// which is why `IDLE` is written bare. One function for all three
/// spellings that can write one: `typedef enum {…} e_t;`, an anonymous
/// `enum {…} x;`, and an anonymous enum standing as a struct member's type.
fn bind_enum_body(&mut self, e: &EnumType, window: TextRange, scope: ScopeId) {
fn bind_enum_body(&mut self, e: &EnumType, scope: ScopeId) {
if let Some(base) = &e.base {
self.bind_data_type(base, window, scope);
self.bind_data_type(base, scope);
}
self.bind_enum_members(&e.members, scope);
}
@@ -130,8 +129,7 @@ impl<'a> Binder<'a> {
/// rather than once per declarator.
fn bind_struct_uses(&mut self, s: &StructType, scope: ScopeId) {
for m in &s.members {
let first = m.declarators.first().map(|d| d.span.start).unwrap_or(m.span.end);
self.bind_data_type(&m.ty, TextRange::new(m.span.start, first), scope);
self.bind_data_type(&m.ty, scope);
for d in &m.declarators {
self.bind_dims(&d.unpacked, scope);
self.bind_opt_expr(d.init.as_ref(), scope);
@@ -177,10 +175,10 @@ impl<'a> Binder<'a> {
}
}
pub(super) fn bind_data_decl(&mut self, d: &DataDecl, span: TextRange, scope: ScopeId) {
pub(super) fn bind_data_decl(&mut self, d: &DataDecl, scope: ScopeId) {
let kind = if d.net.is_some() { SymbolKind::Net } else { SymbolKind::Var };
self.bind_opt_expr(d.delay.as_ref().map(|n| &n.expr), scope);
self.bind_declarators(&d.declarators, kind, &d.ty, span, scope);
self.bind_declarators(&d.declarators, kind, &d.ty, scope);
}
pub(super) fn bind_port_decl(&mut self, p: &PortDecl, span: TextRange, scope: ScopeId) {
@@ -222,7 +220,7 @@ impl<'a> Binder<'a> {
symbol.type_name = type_name;
}
}
self.bind_declarators(&p.declarators, kind, &p.ty, span, scope);
self.bind_declarators(&p.declarators, kind, &p.ty, scope);
}
pub(super) fn bind_declarators(
@@ -230,11 +228,9 @@ impl<'a> Binder<'a> {
declarators: &[Declarator],
kind: SymbolKind,
ty: &DataType,
span: TextRange,
scope: ScopeId,
) {
let first = declarators.first().map(|d| d.span.start).unwrap_or(span.end);
self.bind_data_type(ty, TextRange::new(span.start, first), scope);
self.bind_data_type(ty, scope);
for d in declarators {
let plain = d.unpacked.is_empty();
let id =
@@ -254,49 +250,12 @@ impl<'a> Binder<'a> {
}
}
/// A user-defined type name is a use like any other. `window` is the
/// source range the name was written in — everything before the declared
/// name, which is where a data type always sits. A `DataType` has no span
/// of its own (vlog-semantic handshake item 2, still open), so this is
/// the one declaration surface still located by scanning.
pub(super) fn bind_data_type(&mut self, ty: &DataType, window: TextRange, scope: ScopeId) {
/// A user-defined type name is a use like any other, and the parser hands
/// over where every segment of it is written
/// ([`DataType::segments`]), so nothing here rescans the source.
pub(super) fn bind_data_type(&mut self, ty: &DataType, scope: ScopeId) {
if !ty.name.is_empty() && !is_keyword(&ty.name) {
match ty.name.split_once("::") {
Some((unit, item)) => {
let mut scanner = NameScanner::new(self.src, window);
let unit_span = scanner.find(unit).unwrap_or(TextRange::empty(window.start));
let item_span = scanner.find(item).unwrap_or(TextRange::empty(window.start));
self.use_name(scope, unit, unit_span, Target::Unit);
self.use_name(scope, item, item_span, Target::UnitMember(unit.to_string()));
}
// `bus_if.mp bus`, `virtual bus_if.mp vif` — the parser glues
// an interface port's modport onto the type name (IEEE 1800
// §25.4, §25.9). The interface is the type and the modport is
// a **member** of it, so both halves are bound: the head as
// any other type name, the tail against the interface's own
// scope (or, cross-file, as `bus_if::mp` in the workspace's
// member table). "The tail is where to bind them" —
// `docs/features/ansi-first-port/README.md`.
None => {
let (name, modport) = match ty.name.split_once('.') {
Some((iface, modport)) => (iface, Some(modport)),
None => (ty.name.as_str(), None),
};
let ns = crate::scan::name_span(self.src, window, name);
self.use_name(scope, name, ns, Target::Type);
if let Some(modport) = modport {
let tail = self.modport_tail(ns, modport);
if !tail.is_empty() {
self.use_member(
scope,
modport,
tail,
Target::TypeMember { unit: name.to_string() },
);
}
}
}
}
self.bind_type_name(ty, scope);
}
self.bind_dims(&ty.packed, scope);
// An anonymous aggregate written where a type name would go. Its
@@ -305,27 +264,50 @@ impl<'a> Binder<'a> {
// is written here is every use inside it, recorded once for the type
// however many declarators share it.
match ty.inline() {
Some(TypeExtra::Enum(e)) => self.bind_enum_body(e, window, scope),
Some(TypeExtra::Enum(e)) => self.bind_enum_body(e, scope),
Some(TypeExtra::Struct(s)) => self.bind_struct_uses(s, scope),
_ => {}
}
}
/// The byte range of the `mp` in a glued `bus_if.mp` type name, given the
/// range the interface half was located at.
/// The segments of a written type name, each recorded as a use.
///
/// Derived rather than received — a `DataType` carries no spans at all —
/// so it is verified twice over: the byte after the interface half must be
/// a literal `.`, and the bytes after that must spell the modport exactly.
/// A source that wrote the two apart, or a name a macro produced, costs the
/// `pkg::item` is a unit and a member of it. `bus_if.mp bus`,
/// `virtual bus_if.mp vif` — the parser glues an interface port's modport
/// onto the type name (IEEE 1800 §25.4, §25.9) — is the interface as the
/// type plus the modport as a **member** of it, bound against the
/// interface's own scope (or, cross-file, as `bus_if::mp` in the
/// workspace's member table). "The tail is where to bind them" —
/// `docs/features/ansi-first-port/README.md`.
///
/// Every span is checked against the source before it is recorded, the
/// rule the modport tail has always followed: a name the source spells
/// differently from the way the parser joined it — an escaped segment
/// terminated by a newline, a `bus_if . mp` written apart — costs the
/// reference and never mislocates it.
fn modport_tail(&self, iface: TextRange, modport: &str) -> TextRange {
if iface.is_empty() || self.src.as_bytes().get(iface.end as usize) != Some(&b'.') {
return TextRange::empty(iface.end);
fn bind_type_name(&mut self, ty: &DataType, scope: ScopeId) {
let scoped = ty.name.contains("::");
let mut head: Option<&str> = None;
for (seg, span) in ty.segments() {
// A segment whose derived range does not read back as its own
// text (`pkg :: item`, a comment inside the name) is recorded
// with the empty range at its start, never dropped: an empty
// range is what the corpus census counts as *unplaced*, so a
// parser regression in the join would trip that alarm instead of
// silently lowering the resolution rate (§47's QA).
let span = self.exact_or_empty(span, seg);
match (head, scoped) {
(None, true) => self.use_name(scope, seg, span, Target::Unit),
(None, false) => self.use_name(scope, seg, span, Target::Type),
(Some(unit), true) => {
self.use_name(scope, seg, span, Target::UnitMember(unit.to_string()))
}
(Some(unit), false) => {
self.use_member(scope, seg, span, Target::TypeMember { unit: unit.to_string() })
}
}
head = Some(seg);
}
let start = iface.end.saturating_add(1);
let span = TextRange::new(start, start.saturating_add(modport.len() as u32));
self.exact_or_empty(span, modport)
}
}
+2 -2
View File
@@ -174,8 +174,8 @@ impl<'a> Binder<'a> {
// is the callee's formal, which this crate does not model (the
// same rule connection port names follow).
ExprKind::NamedArg { value, .. } => self.bind_expr(value, scope),
ExprKind::Type(ty) => self.bind_data_type(ty, e.span, scope),
ExprKind::MinTypMax { min, typ, max } => {
ExprKind::Type(ty) => self.bind_data_type(ty, scope),
ExprKind::MinTypMax { min, typ, max, .. } => {
self.bind_expr(min, scope);
self.bind_expr(typ, scope);
self.bind_expr(max, scope);
+48 -17
View File
@@ -88,9 +88,9 @@ impl<'a> Binder<'a> {
}
ItemKind::Typedef(t) => self.bind_typedef(t, item.span, scope),
ItemKind::ParamDecl(p) => {
self.bind_declarators(&p.declarators, param_kind(&p.kw), &p.ty, item.span, scope)
self.bind_declarators(&p.declarators, param_kind(&p.kw), &p.ty, scope)
}
ItemKind::DataDecl(d) => self.bind_data_decl(d, item.span, scope),
ItemKind::DataDecl(d) => self.bind_data_decl(d, scope),
ItemKind::PortDecl(p) => self.bind_port_decl(p, item.span, scope),
ItemKind::ContAssign(c) => {
self.bind_opt_expr(c.delay.as_ref(), scope);
@@ -108,7 +108,7 @@ impl<'a> Binder<'a> {
ItemKind::Bind(b) => self.bind_bind(b, scope),
ItemKind::GateInstantiation(g) => {
for d in &g.delay {
self.bind_expr(d, scope);
self.bind_expr(&d.expr, scope);
}
for inst in &g.instances {
if let (Some(name), Some(ns)) = (&inst.name, inst.name_span) {
@@ -169,16 +169,21 @@ impl<'a> Binder<'a> {
self.bind_expr(net, scope);
}
}
// A package re-export names two things another file declares, and
// both are references — see [`Binder::bind_export_path`]. A **DPI**
// export stays the opaque leaf it was: it names a function
// declared elsewhere in this same scope, and saying which one is a
// separate question (`docs/features/dpi-export/README.md`).
ItemKind::Export(ExportDecl::Package(paths)) => {
for path in paths {
self.bind_export_path(path, scope);
}
}
// Opaque leaves: verbatim text this crate makes no claims about.
// `Verbatim` is a constraint or covergroup body — no symbol is
// bound for its name and nothing inside it is scanned, the same
// contract macro invocations have. `Export` is a leaf too: a DPI
// export names a function declared elsewhere in the same scope,
// and a package re-export does not bring the name into this scope
// (an `import` alongside it does that). Resolving either one is a
// vlog_semantic decision, not the parser's — see
// `docs/features/dpi-export/README.md` Handshakes.
ItemKind::Export(_)
// contract macro invocations have.
ItemKind::Export(ExportDecl::Dpi(_))
| ItemKind::Directive(_)
| ItemKind::MacroItem(_)
| ItemKind::Timeunit(_)
@@ -212,11 +217,7 @@ impl<'a> Binder<'a> {
// declares nothing, exactly as an `ItemKind::Error` does.
PortList::Ansi(ports) => {
for p in ports.iter().filter_map(ListElem::ok) {
self.bind_data_type(
&p.ty,
TextRange::new(p.span.start, p.name_span.start),
inner,
);
self.bind_data_type(&p.ty, inner);
self.declare_typed(
inner,
&p.name,
@@ -262,6 +263,36 @@ impl<'a> Binder<'a> {
});
}
/// Record one `pkg::item` / `pkg::*` path of an `export` — **the two
/// halves an import records, and no import at all**.
///
/// A re-export makes the name visible to whoever imports *this* package;
/// it brings nothing into the exporting package's own scope (IEEE 1800
/// §26.6). So `pkg` and `item` are ordinary uses — that is what makes
/// `export b_pkg::x;` a go-to-definition into `b_pkg` and puts the line in
/// `x`'s reference set — and no [`Import`] is pushed, which is what keeps
/// a bare `x` written beside it unresolved unless an `import` says
/// otherwise.
///
/// `export *::*;` names nothing at all: both halves are the `*` the
/// parser stores as a name, and there is nothing to resolve. What it
/// *means* — everything this package imports is re-exported — is the
/// workspace layer's business (`workspace::reexport`).
pub(super) fn bind_export_path(&mut self, path: &ImportPath, scope: ScopeId) {
if path.pkg.text == "*" {
return;
}
if path.item.text != "*" {
self.use_name(
scope,
&path.item.text,
path.item.span,
Target::UnitMember(path.pkg.text.clone()),
);
}
self.use_name(scope, &path.pkg.text, path.pkg.span, Target::Package);
}
fn bind_instantiation(&mut self, i: &Instantiation, scope: ScopeId) {
// `module_span` has the documented despace caveat for `pkg :: mod`,
// so it is taken only when it slices back to the stored name.
@@ -419,7 +450,7 @@ impl<'a> Binder<'a> {
return;
}
if let Some(ret) = &f.ret {
self.bind_data_type(ret, TextRange::new(span.start, f.name_span.start), scope);
self.bind_data_type(ret, scope);
}
let inner = self.declare_with_scope(
scope,
@@ -487,7 +518,7 @@ impl<'a> Binder<'a> {
fn bind_modport_prototype(&mut self, p: &'a TfPrototype, span: TextRange, scope: ScopeId) {
self.use_name(scope, &p.name, p.name_span, Target::InScope);
if let Some(ret) = &p.ret {
self.bind_data_type(ret, TextRange::new(span.start, p.name_span.start), scope);
self.bind_data_type(ret, scope);
}
let inner = self.new_scope(ScopeKind::Block, scope, span);
self.bind_tf_args(&p.args, inner);
+12 -14
View File
@@ -4,10 +4,8 @@
//! covergroups and property specs share with them.
use vlog_parser::ast::*;
use vlog_parser::span::TextRange;
use crate::model::{ScopeId, ScopeKind, SymbolKind};
use crate::scan::name_after_kw;
use super::decl::param_kind;
use super::{Binder, Target};
@@ -66,11 +64,7 @@ impl<'a> Binder<'a> {
match &i.ty {
Some(ty) => {
if let ExprKind::Ident(name) = &i.assign.lhs.kind {
self.bind_data_type(
ty,
TextRange::new(stmt.span.start, i.assign.lhs.span.start),
scope,
);
self.bind_data_type(ty, scope);
self.declare(
inner,
name,
@@ -140,21 +134,25 @@ impl<'a> Binder<'a> {
}
}
StmtKind::ExprStmt(e) | StmtKind::EventTrigger(e) => self.bind_expr(e, scope),
StmtKind::VarDecl(d) => self.bind_data_decl(d, stmt.span, scope),
StmtKind::VarDecl(d) => self.bind_data_decl(d, scope),
// A block-scoped type binds exactly as an item-level one does; the
// scope it lands in is the enclosing block's, which is what
// IEEE 1800 §6.18 asks for.
StmtKind::Typedef(t) => self.bind_typedef(t, stmt.span, scope),
StmtKind::ParamDecl(p) => {
self.bind_declarators(&p.declarators, param_kind(&p.kw), &p.ty, stmt.span, scope)
self.bind_declarators(&p.declarators, param_kind(&p.kw), &p.ty, scope)
}
StmtKind::PortDecl(p) => self.bind_port_decl(p, stmt.span, scope),
StmtKind::Return { expr: e, .. } => self.bind_opt_expr(e.as_ref(), scope),
StmtKind::Disable(name) => {
// A use, not a declaration, so name-spans deliberately gave it
// no range — the one statement still located by scanning.
let ns = name_after_kw(self.src, stmt.span, "disable", name);
self.use_name(scope, name, ns, Target::Lexical);
StmtKind::Disable { name, name_span } => {
// A use, not a declaration, but the parser spans it like any
// other name. Checked before it is recorded, the rule every
// derived span here follows: `disable a . b` written apart
// costs the reference rather than mislocating it.
let ns = self.exact_or_empty(*name_span, name);
if !ns.is_empty() {
self.use_name(scope, name, ns, Target::Lexical);
}
}
StmtKind::Assert { cond, then, els, .. } => {
self.bind_expr(cond, scope);
+74 -6
View File
@@ -19,10 +19,10 @@ use std::path::PathBuf;
use vlog_parser::defines::{Define, DefineKind, DefineTable};
use vlog_parser::span::TextRange;
use crate::model::SymbolKind;
use crate::model::{Surface, SymbolKind};
use crate::workspace::{
Decl, DeclLines, DeclPositions, DeclSite, FileFacts, InstanceOccurrence, ReferenceFact,
SiteFact, Utf16Pos, Utf16Range,
Decl, DeclLines, DeclPositions, DeclSite, FileFacts, InstanceOccurrence, Reexport,
ReferenceFact, SiteFact, Utf16Pos, Utf16Range,
};
/// The version of the encoding below. Bump it on **any** change to what a
@@ -121,7 +121,31 @@ use crate::workspace::{
/// cached — silence about a macro argument the rename really did leave
/// behind, which is the failure the warning exists to prevent. See
/// `docs/features/macro-word-census/README.md`.
pub const FACTS_FORMAT: u32 = 17;
///
/// 17 → 18 (2026-09-05, package-reexports): a new `RX` group — each package's
/// re-exports (`export b_pkg::x;`, `export b_pkg::*;`, and `export *::*;`
/// already expanded to that package's imports), and once more a wider
/// reference census, since both halves of a re-export line are references
/// where they used to be nothing at all. It is a new field, so an older record
/// would be read short by one group; and it is what makes `a_pkg::x` resolve
/// to `b_pkg`'s declaration, so a store written by a 0.44.0 build would answer
/// definition, hover, completion, find-references and the rename preflight as
/// though no package in the workspace re-exported anything — for exactly the
/// files it had cached, which is the half-right answer this bump exists to
/// prevent. See `docs/features/package-reexports/README.md`.
///
/// 18 → 19 (2026-09-05, hierarchical-tail): a **surface** letter on every
/// declaration and on every external reference — `c` for the connection
/// surface, `h` for the hierarchical one. It is two new fields, so an older
/// record would be read field-shifted; and the census grows with it, since a
/// module now exports its nets, its variables and its instances on the
/// hierarchical surface where it exported nothing at all before. A store
/// written by a 0.44.0 build would answer definition, find-references and the
/// rename of an internal net named through an instance (`assign w =
/// u_x.sig;`) as though the tail resolved to nothing — for exactly the files
/// it had cached, which is the half-right answer every one of these bumps
/// exists to prevent. See `docs/features/hierarchical-tail/README.md`.
pub const FACTS_FORMAT: u32 = 19;
impl FileFacts {
/// These facts as one line's worth of fields, tab-separated.
@@ -171,6 +195,15 @@ impl FileFacts {
out.text(base);
out.site(subclass);
}
// Three strings an edge: the package that writes the `export`, the
// package it takes the name from, and the name (or `*`). Two letters
// because `R` is the reference group.
out.tag("RX", self.reexports.len());
for (exporter, entry) in &self.reexports {
out.text(exporter);
out.text(&entry.package);
out.text(&entry.item);
}
out.tag("R", self.references.len());
for reference in &self.references {
out.reference(reference);
@@ -236,6 +269,11 @@ impl FileFacts {
for _ in 0..input.tag("S")? {
subclasses.push((input.text()?, input.site()?));
}
let mut reexports = Vec::new();
for _ in 0..input.tag("RX")? {
let exporter = input.text()?;
reexports.push((exporter, Reexport { package: input.text()?, item: input.text()? }));
}
let mut references = Vec::new();
for _ in 0..input.tag("R")? {
references.push(input.reference()?);
@@ -258,6 +296,7 @@ impl FileFacts {
members,
instantiations,
subclasses,
reexports,
references,
words,
macro_words,
@@ -352,6 +391,19 @@ impl Writer {
// bump that goes with it
// (`docs/features/class-member-access/README.md`, round 2).
self.text(decl.type_name.as_deref().unwrap_or(""));
// The surface the owner exports this declaration on. One letter, on
// every declaration rather than only on the `M` group, so the two
// groups keep the one shared `decl` shape they have always had.
self.surface(decl.surface);
}
/// One [`Surface`] as the letter a reader takes it back by.
fn surface(&mut self, surface: Surface) {
self.field();
self.out.push(match surface {
Surface::Connection => 'c',
Surface::Hierarchical => 'h',
});
}
/// One [`Utf16Range`]: four numbers, in the order a reader takes them.
@@ -409,7 +461,7 @@ impl Writer {
self.range(*definition);
self.range(*occurrence);
}
ReferenceFact::External { name, base, paths, occurrence } => {
ReferenceFact::External { name, base, paths, surface, occurrence } => {
self.field();
self.out.push('e');
self.text(name);
@@ -421,6 +473,10 @@ impl Writer {
for path in paths {
self.text(path);
}
// Which surface those paths are walked in — the one field
// that makes a cross-file hierarchical tail resolve from a
// restored record exactly as it does from a fresh parse.
self.surface(*surface);
self.range(*occurrence);
}
}
@@ -498,6 +554,7 @@ impl<'a> Reader<'a> {
let detail_line = self.num()?;
let type_name = self.text()?;
let type_name = (!type_name.is_empty()).then_some(type_name);
let surface = self.surface()?;
// Client positions are not one of a declaration's shared fields: a
// caller reading the `U` group takes them from `positions()` next, and
// a member has none at all (`vlog_semantic::DeclPositions`).
@@ -506,7 +563,17 @@ impl<'a> Reader<'a> {
detail: (detail_line != 0).then_some(detail_line),
positions: None,
};
Some(Decl { name, name_span, decl_span, kind, detail_span, lines, type_name })
Some(Decl { name, name_span, decl_span, kind, detail_span, lines, type_name, surface })
}
/// The mirror of the encoder's one-letter surface: anything else is a
/// record this format did not write.
fn surface(&mut self) -> Option<Surface> {
match self.next()? {
"c" => Some(Surface::Connection),
"h" => Some(Surface::Hierarchical),
_ => None,
}
}
fn utf16(&mut self) -> Option<Utf16Range> {
@@ -569,6 +636,7 @@ impl<'a> Reader<'a> {
name,
base: (!base.is_empty()).then_some(base),
paths,
surface: self.surface()?,
occurrence: self.range()?,
})
}
+1 -2
View File
@@ -22,14 +22,13 @@ mod facts;
pub mod instantiations;
mod model;
mod resolve;
mod scan;
pub mod words;
mod workspace;
pub use facts::{record_path, FACTS_FORMAT};
pub use model::{
DocumentSymbol, Duplicate, Import, MemberSite, Reference, ReferenceId, Resolution, Scope,
ScopeId, ScopeKind, Symbol, SymbolId, SymbolKind,
ScopeId, ScopeKind, Surface, Symbol, SymbolId, SymbolKind,
};
pub use workspace::{
index_order, resolve_external, DeclLines, DeclPositions, DeclSite, Def, Definition,
+51 -6
View File
@@ -186,6 +186,39 @@ pub struct Duplicate {
pub scope: ScopeId,
}
/// Which of a unit's two member surfaces a lookup reads.
///
/// A **package**, a **class** and a `struct` typedef have one surface and this
/// is noise for them. A **module** has two, and they are not the same set
/// (IEEE 1800 §23.3 vs §23.6):
///
/// * its **connection** surface is what a connection list may name — its
/// ports and its parameters (plus the properties and sequences a bound-in
/// checker instantiates). `.sig(w)` in an instantiation, and the completion
/// list behind that `.`, read exactly this and nothing more: an internal net
/// is not connectable, and offering one would be an item the resolution
/// could not find.
/// * its **hierarchical** surface is everything a hierarchical path may name
/// from anywhere in the design — the connection surface *plus* its nets, its
/// variables and its instances (the last so `u_a.u_b.sig` has a hop to
/// take). Only the tail walk behind an instance head reads it.
///
/// The hierarchical surface **contains** the connection one, so a tail naming
/// a port has one answer and not two: a member record is tagged with the
/// narrowest surface it joins, the connection query reads only the records
/// tagged [`Surface::Connection`], and the hierarchical query reads those
/// first and the [`Surface::Hierarchical`] ones after.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Surface {
/// Ports and parameters: what a connection list may name, and what every
/// package, class and struct exports. The default for everything that is
/// not a hierarchical tail.
Connection,
/// The whole of what a hierarchical path may name: the connection surface
/// plus a module's nets, variables and instances.
Hierarchical,
}
/// What a [`Reference`] turned out to name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Resolution {
@@ -199,7 +232,14 @@ pub enum Resolution {
/// those units — a path containing `::` is a package path, a bare name is a
/// module, package or class name — in the order they are tried, the use's
/// own name last. The workspace index (TODO.md §6) is what finishes these.
ExternalCandidate { paths: Vec<String> },
///
/// `surface` is which of the named unit's two member surfaces the lookup
/// reads ([`Surface`]). It is [`Surface::Connection`] for every candidate
/// but one: the tail of `u_x.sig` whose head resolved to an **instance**,
/// which is a hierarchical path and reads the module's hierarchical
/// surface. Carried here rather than worked out again at lookup time
/// because only the file that wrote the path knows what its head was.
ExternalCandidate { paths: Vec<String>, surface: Surface },
/// A use inside a class that nothing lexical binds, where the class's
/// `extends` could: `base` is the base-class path as written
/// (`uvm_component`, `pkg::base`), and `paths` are the import paths the
@@ -242,11 +282,16 @@ pub enum MemberSite {
Scope(ScopeId),
/// A type this file does not declare, as the unit name plus any member
/// names already selected from it — `pkt_t`, `pkt_t::hdr` — in exactly the
/// spelling [`crate::WorkspaceIndex`]'s member lookup walks. The tail
/// resolution appends `::<name>` to it and hands the result to
/// `follow_one`; the *list* is
/// [`WorkspaceIndex::members_of_chain`](crate::WorkspaceIndex::members_of_chain).
Unit(String),
/// spelling [`crate::WorkspaceIndex`]'s member lookup walks, with the
/// [`Surface`] the walk reads. The tail resolution appends `::<name>` to
/// the path and hands the pair to `follow_one`; the *list* is
/// [`WorkspaceIndex::members_of_chain_in`](crate::WorkspaceIndex::members_of_chain_in).
///
/// The surface is [`Surface::Hierarchical`] exactly when the head of the
/// spine was an **instance**, and it stays that for every further hop:
/// `u_a.u_b.` is one hierarchical path, and each hop is an instance inside
/// the module before it.
Unit { path: String, surface: Surface },
}
/// A *use* of a name: an expression identifier, a type name, an instantiated
+58 -17
View File
@@ -5,7 +5,7 @@
//! requires at module scope and what an editor needs mid-edit.
use crate::bind::{Pending, Target};
use crate::model::{MemberSite, Resolution, Scope, ScopeId, Symbol, SymbolId, SymbolKind};
use crate::model::{MemberSite, Resolution, Scope, ScopeId, Surface, Symbol, SymbolId, SymbolKind};
/// Resolve one pending use against the finished scope tree.
///
@@ -34,7 +34,10 @@ pub(crate) fn resolve(scopes: &[Scope], symbols: &[Symbol], p: &Pending) -> Opti
None => Resolution::NotFound,
},
// The port list lives in whatever file declares the module.
None => Resolution::ExternalCandidate { paths: vec![module.clone()] },
None => Resolution::ExternalCandidate {
paths: vec![module.clone()],
surface: Surface::Connection,
},
},
Target::InScope => return in_scope(scopes, p.scope, &p.name),
Target::TypeMember { unit } => return type_member(scopes, symbols, p.scope, unit, &p.name),
@@ -95,7 +98,10 @@ fn in_bind_target(
) -> Option<Resolution> {
match owning_scope(scopes, symbols, target, is_instantiable) {
Some(scope) => scopes.get(scope.0 as usize)?.lookup_local(name).map(Resolution::Resolved),
None => Some(Resolution::ExternalCandidate { paths: vec![target.to_string()] }),
None => Some(Resolution::ExternalCandidate {
paths: vec![target.to_string()],
surface: Surface::Connection,
}),
}
}
@@ -135,6 +141,7 @@ fn type_member(
TypeHere::NotAUnit => None,
TypeHere::Absent => Some(Resolution::ExternalCandidate {
paths: vec![format!("{}::{name}", last_segment(unit))],
surface: Surface::Connection,
}),
}
}
@@ -185,6 +192,7 @@ fn member_of(
}),
Err(Some(base)) => Some(Resolution::ExternalCandidate {
paths: vec![format!("{}::{name}", last_segment(&base))],
surface: Surface::Connection,
}),
// A class this file declares whole, with no such member: nothing
// to say that `NotFound` would not overstate.
@@ -193,8 +201,8 @@ fn member_of(
// A type this file does not declare: the workspace's member table is
// the only layer that can say. The last `::` segment names the unit,
// the spelling `follow_one` turns back into `member(unit, name)`.
MemberSite::Unit(path) => {
Some(Resolution::ExternalCandidate { paths: vec![format!("{path}::{name}")] })
MemberSite::Unit { path, surface } => {
Some(Resolution::ExternalCandidate { paths: vec![format!("{path}::{name}")], surface })
}
}
}
@@ -231,12 +239,17 @@ pub(crate) fn member_site(
Ok(id) => link_type(scopes, symbols, id)?,
// The chain leaves this file at a base class: everything from
// here on is one composed path for the workspace to walk.
Err(Some(base)) => MemberSite::Unit(format!("{}::{mid}", last_segment(&base))),
Err(Some(base)) => MemberSite::Unit {
path: format!("{}::{mid}", last_segment(&base)),
surface: Surface::Connection,
},
Err(None) => return None,
},
// Already outside this file — each further name is one more
// segment of the path `follow_one` walks member by member.
MemberSite::Unit(path) => MemberSite::Unit(format!("{path}::{mid}")),
MemberSite::Unit { path, surface } => {
MemberSite::Unit { path: format!("{path}::{mid}"), surface }
}
};
}
Some(here)
@@ -258,7 +271,10 @@ fn head_site(
let (chain, base) = extends_chain(scopes, symbols, class);
match chain.get(1) {
Some(&base_scope) => Some(MemberSite::Scope(base_scope)),
None => Some(MemberSite::Unit(last_segment(&base?).to_string())),
None => Some(MemberSite::Unit {
path: last_segment(&base?).to_string(),
surface: Surface::Connection,
}),
}
}
_ => {
@@ -294,7 +310,9 @@ pub(crate) fn unit_site(
let id = scopes.get(scope.0 as usize)?.lookup_local(segment)?;
MemberSite::Scope(container_scope(symbols, id)?)
}
MemberSite::Unit(unit) => MemberSite::Unit(format!("{unit}::{segment}")),
MemberSite::Unit { path, surface } => {
MemberSite::Unit { path: format!("{path}::{segment}"), surface }
}
};
}
Some(here)
@@ -322,7 +340,7 @@ fn unit_scope(scopes: &[Scope], symbols: &[Symbol], from: ScopeId, unit: &str) -
}
current = scope.parent;
}
MemberSite::Unit(unit.to_string())
MemberSite::Unit { path: unit.to_string(), surface: Surface::Connection }
}
/// Where the members of one declaration live: its **declared type**'s scope
@@ -347,7 +365,26 @@ fn link_type(scopes: &[Scope], symbols: &[Symbol], id: SymbolId) -> Option<Membe
// This file says what the type is, and it is not something with
// members. No other file can override that, so nothing is recorded.
TypeHere::NotAUnit => None,
TypeHere::Absent => Some(MemberSite::Unit(last_segment(type_name).to_string())),
TypeHere::Absent => Some(MemberSite::Unit {
path: last_segment(type_name).to_string(),
surface: head_surface(symbol.kind),
}),
}
}
/// Which member surface a link of a spine opens: the **hierarchical** one when
/// the link is an instance, the connection one for everything else.
///
/// `u_x.sig` is a hierarchical path (IEEE 1800 §23.6) and `sig` may be any of
/// `sub`'s own declarations; `handle.field` is a member access on a type, and
/// `pkt_t` has one surface anyway. The distinction only ever matters for a
/// module — the one unit whose two surfaces differ — and it is settled here,
/// in the file that can see what the head is, because the path handed to the
/// workspace is only a spelling.
fn head_surface(kind: SymbolKind) -> Surface {
match kind {
SymbolKind::Instance => Surface::Hierarchical,
_ => Surface::Connection,
}
}
@@ -678,9 +715,10 @@ fn unit_member(
}
// Nothing here declares the unit, or a `typedef class c;` promises it
// lives elsewhere: the member is the workspace's to find.
MemberSite::Unit(_) => {
Resolution::ExternalCandidate { paths: vec![format!("{unit}::{name}")] }
}
MemberSite::Unit { .. } => Resolution::ExternalCandidate {
paths: vec![format!("{unit}::{name}")],
surface: Surface::Connection,
},
}
}
@@ -724,7 +762,7 @@ fn super_member(scopes: &[Scope], from: ScopeId) -> Resolution {
/// because the use was not a type — is `NotFound`.
fn miss(scopes: &[Scope], from: ScopeId, external: Vec<String>, unit_lookup: bool) -> Resolution {
if unit_lookup {
return Resolution::ExternalCandidate { paths: external };
return Resolution::ExternalCandidate { paths: external, surface: Surface::Connection };
}
if let Some(base) = nearest_extends(scopes, from) {
return Resolution::InheritedCandidate { base, paths: external };
@@ -732,7 +770,7 @@ fn miss(scopes: &[Scope], from: ScopeId, external: Vec<String>, unit_lookup: boo
if external.is_empty() {
Resolution::NotFound
} else {
Resolution::ExternalCandidate { paths: external }
Resolution::ExternalCandidate { paths: external, surface: Surface::Connection }
}
}
@@ -789,7 +827,10 @@ fn named_at_file_scope(
) -> Resolution {
match file_symbol(scopes, symbols, name, wanted) {
Some(id) => Resolution::Resolved(id),
None => Resolution::ExternalCandidate { paths: vec![name.to_string()] },
None => Resolution::ExternalCandidate {
paths: vec![name.to_string()],
surface: Surface::Connection,
},
}
}
-193
View File
@@ -1,193 +0,0 @@
//! Recovering the byte range of a name the AST kept only as a `String`.
//!
//! Most declarations in `vlog_parser`'s AST store their name as a plain
//! `String` and give a span only for the whole construct (`module m ... `,
//! `input logic [W-1:0] d`). A language server needs the range of the *name*,
//! so this scans the construct's own source text for it. See the README's
//! Handshakes section: once the parser carries `name_span` on those nodes,
//! this module goes away.
use vlog_parser::span::TextRange;
/// A cursor over one source window that hands out the ranges of successive
/// identifiers, skipping comments, strings and macro invocations.
pub(crate) struct NameScanner<'a> {
src: &'a [u8],
pos: usize,
end: usize,
}
impl<'a> NameScanner<'a> {
/// A scanner over `window` of `src`.
pub(crate) fn new(src: &'a str, window: TextRange) -> Self {
let end = (window.end as usize).min(src.len());
let pos = (window.start as usize).min(end);
NameScanner { src: src.as_bytes(), pos, end }
}
/// The range of the next whole-word `name`, or `None` if the window holds
/// no more. The cursor moves past what it returns, so repeated calls walk
/// a list (`genvar i, j;`) left to right.
pub(crate) fn find(&mut self, name: &str) -> Option<TextRange> {
while let Some(word) = self.next_word() {
if &self.src[word.as_range()] == name.as_bytes() {
return Some(word);
}
}
None
}
/// The range of the next identifier of any spelling.
fn next_word(&mut self) -> Option<TextRange> {
while self.pos < self.end {
let b = self.src[self.pos];
match b {
b'/' if self.peek(1) == Some(b'/') => self.skip_line(),
b'/' if self.peek(1) == Some(b'*') => self.skip_block_comment(),
b'"' => self.skip_string(),
// A macro invocation is one opaque token: `` `WIDTH `` must
// not answer a search for the identifier `WIDTH`.
b'`' => {
self.pos += 1;
self.skip_word();
}
_ if is_ident_start(b) => {
let start = self.pos;
self.skip_word();
return Some(TextRange::new(start as u32, self.pos as u32));
}
_ => self.pos += 1,
}
}
None
}
fn peek(&self, n: usize) -> Option<u8> {
self.src.get(self.pos + n).copied()
}
fn skip_word(&mut self) {
// An escaped identifier (`\a+b `) runs to the next whitespace.
if self.src.get(self.pos) == Some(&b'\\') {
self.pos += 1;
while self.pos < self.end && !self.src[self.pos].is_ascii_whitespace() {
self.pos += 1;
}
return;
}
while self.pos < self.end && is_ident_continue(self.src[self.pos]) {
self.pos += 1;
}
}
fn skip_line(&mut self) {
while self.pos < self.end && self.src[self.pos] != b'\n' {
self.pos += 1;
}
}
fn skip_block_comment(&mut self) {
self.pos += 2;
while self.pos < self.end {
if self.src[self.pos] == b'*' && self.peek(1) == Some(b'/') {
self.pos += 2;
return;
}
self.pos += 1;
}
}
fn skip_string(&mut self) {
self.pos += 1;
while self.pos < self.end {
match self.src[self.pos] {
b'\\' => self.pos += 2,
b'"' => {
self.pos += 1;
return;
}
_ => self.pos += 1,
}
}
}
}
fn is_ident_start(b: u8) -> bool {
b.is_ascii_alphabetic() || b == b'_' || b == b'$' || b == b'\\'
}
fn is_ident_continue(b: u8) -> bool {
b.is_ascii_alphanumeric() || b == b'_' || b == b'$'
}
/// The range of `name` inside `window`, or an empty range at the window start
/// when the scan comes up empty (a name the source spells differently — an
/// escaped identifier, or text a macro produced).
pub(crate) fn name_span(src: &str, window: TextRange, name: &str) -> TextRange {
NameScanner::new(src, window).find(name).unwrap_or(TextRange::empty(window.start))
}
/// The range of `name` written *after* the first `kw` in `window`. Used where
/// the construct starts with a keyword and the name follows it, possibly
/// past qualifiers (`function automatic int f`).
pub(crate) fn name_after_kw(src: &str, window: TextRange, kw: &str, name: &str) -> TextRange {
let mut scanner = NameScanner::new(src, window);
if scanner.find(kw).is_none() {
return TextRange::empty(window.start);
}
scanner.find(name).unwrap_or(TextRange::empty(window.start))
}
#[cfg(test)]
mod tests {
use super::*;
fn whole(src: &str) -> TextRange {
TextRange::new(0, src.len() as u32)
}
#[test]
fn finds_a_name_after_its_keyword() {
let src = "module top (input a);";
let span = name_after_kw(src, whole(src), "module", "top");
assert_eq!(&src[span.as_range()], "top");
assert_eq!(span.start, 7);
}
#[test]
fn skips_comments_and_strings() {
let src = "/* d */ \"d\" // d\n d;";
let span = name_span(src, whole(src), "d");
assert_eq!(span.start, 18);
}
#[test]
fn matches_whole_words_only() {
let src = "input wire [W-1:0] w;";
let span = name_span(src, whole(src), "w");
assert_eq!(&src[span.as_range()], "w");
assert_eq!(span.start, 19);
}
#[test]
fn a_macro_invocation_is_one_opaque_token() {
let src = "`WIDTH WIDTH";
let span = name_span(src, whole(src), "WIDTH");
assert_eq!(span.start, 7);
}
#[test]
fn a_name_that_is_not_there_gives_an_empty_range() {
let src = "module m;";
let span = name_span(src, whole(src), "nope");
assert!(span.is_empty());
}
#[test]
fn successive_finds_walk_a_list() {
let src = "genvar i, j;";
let mut scanner = NameScanner::new(src, whole(src));
assert_eq!(scanner.find("i").map(|s| s.start), Some(7));
assert_eq!(scanner.find("j").map(|s| s.start), Some(10));
}
}
+99 -18
View File
@@ -5,12 +5,12 @@
//! unit — are the same functions `index` lists members with, so a completion
//! list and a lookup cannot disagree.
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use crate::model::{ReferenceId, Resolution, Symbol, SymbolKind};
use crate::model::{ReferenceId, Resolution, Surface, Symbol, SymbolKind};
use crate::Semantics;
use super::{Def, WorkspaceIndex};
use super::{hierarchy, reexport, Def, WorkspaceIndex};
/// What the workspace layer made of one external-candidate reference.
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -79,9 +79,11 @@ pub fn resolve_external(sem: &Semantics, index: &WorkspaceIndex) -> ExternalReso
let mut targets = HashMap::new();
for (i, reference) in sem.references().iter().enumerate() {
let target = match &reference.resolution {
Resolution::ExternalCandidate { paths } => follow_paths(index, &reference.name, paths),
Resolution::ExternalCandidate { paths, surface } => {
follow_paths(index, &reference.name, paths, *surface)
}
Resolution::InheritedCandidate { base, paths } => {
match resolve_fact(index, &reference.name, Some(base), paths) {
match resolve_fact(index, &reference.name, Some(base), paths, Surface::Connection) {
ExternalTarget::StillUnresolved => continue,
answered => answered,
}
@@ -106,10 +108,14 @@ pub(super) fn resolve_fact(
name: &str,
base: Option<&str>,
paths: &[String],
surface: Surface,
) -> ExternalTarget {
match follow_paths(index, name, paths) {
match follow_paths(index, name, paths, surface) {
ExternalTarget::StillUnresolved => match base {
Some(base) => target(member_chain(index, last_segment(base), name)),
// A base class is a class, and a class has one surface.
Some(base) => {
target(member_chain(index, last_segment(base), name, Surface::Connection))
}
None => ExternalTarget::StillUnresolved,
},
answered => answered,
@@ -122,18 +128,52 @@ pub(super) fn resolve_fact(
/// the inherited ones too. A unit that extends nothing (every package, every
/// module) is one map lookup, exactly as before.
///
/// A miss there is then asked of the packages `unit` **re-exports** from
/// (`export b_pkg::x;` — [`reexport::member`]), which is what makes
/// `a_pkg::x` find `x` where `b_pkg` declares it. That walk is a no-op — one
/// empty map lookup — for a unit that re-exports nothing, which is every unit
/// in almost every workspace.
///
/// Map reads only — [`WorkspaceIndex::member`] and
/// [`WorkspaceIndex::base_of`], both `BTreeMap`s — so a hover pays a handful
/// of comparisons and no file is read. The walk is bounded by the visited set
/// as well as by the workspace: `class a extends b; class b extends a;`
/// terminates, and so does a chain that meets itself further up.
pub(super) fn member_chain<'i>(index: &'i WorkspaceIndex, unit: &str, name: &str) -> &'i [Def] {
let found = index.member(unit, name);
pub(super) fn member_chain<'i>(
index: &'i WorkspaceIndex,
unit: &str,
name: &str,
surface: Surface,
) -> &'i [Def] {
let found = own_chain(index, unit, name, surface);
if !found.is_empty() {
return found;
}
// A re-export is a package's business and a package has one surface, so
// this hop is the connection one whatever the tail was.
reexport::member(index, unit, name)
}
/// [`member_chain`] **without** the re-export hop: `unit` and its `extends`
/// chain, and nothing else.
///
/// Split out because the re-export walk needs it: every hop it takes asks one
/// package for one name, and asking through [`member_chain`] there would
/// recurse into the very walk that called it. So the layering is exactly two
/// deep — a re-export hop reaches a package's own members and its bases, and
/// the re-export walk itself is what chases a chain of re-exports.
pub(super) fn own_chain<'i>(
index: &'i WorkspaceIndex,
unit: &str,
name: &str,
surface: Surface,
) -> &'i [Def] {
let found = hierarchy::member(index, unit, name, surface);
if !found.is_empty() {
return found;
}
for hop in base_chain(index, unit) {
let found = index.member(hop, name);
let found = hierarchy::member(index, hop, name, surface);
if !found.is_empty() {
return found;
}
@@ -141,6 +181,33 @@ pub(super) fn member_chain<'i>(index: &'i WorkspaceIndex, unit: &str, name: &str
&[]
}
/// Every member `unit` and its bases export, nearest first and one entry per
/// name — the listing half of [`own_chain`], and the same first-hit-wins rule
/// it applies, so what is listed for a unit is what a lookup in it would find.
///
/// [`WorkspaceIndex::members_of_chain`]'s inner half, shared with the
/// re-export walk for the same reason [`own_chain`] is.
pub(super) fn own_members<'i>(
index: &'i WorkspaceIndex,
unit: &str,
surface: Surface,
) -> Vec<(&'i str, &'i Def)> {
let mut hops: Vec<&str> = vec![unit];
hops.extend(base_chain(index, unit));
let mut out: Vec<(&'i str, &'i Def)> = Vec::new();
let mut seen: HashSet<&str> = HashSet::new();
for hop in hops {
for (name, defs) in hierarchy::members_of(index, hop, surface) {
if let Some(def) = defs.first() {
if seen.insert(name) {
out.push((name, def));
}
}
}
}
out
}
/// **The hops [`member_chain`] takes past `unit` itself**, with the lookup
/// left to the caller: what `unit` extends, then what *that* extends, and so
/// on upward.
@@ -179,11 +246,11 @@ pub(super) fn base_chain<'i>(index: &'i WorkspaceIndex, unit: &str) -> Vec<&'i s
///
/// The same fold [`follow_one`] runs before its own lookup — shared, so a
/// list and a lookup of the same path cannot land in different units.
pub(super) fn fold_path(index: &WorkspaceIndex, path: &str) -> Option<String> {
pub(super) fn fold_path(index: &WorkspaceIndex, path: &str, surface: Surface) -> Option<String> {
let mut segments = path.split("::");
let mut unit = segments.next()?.to_string();
for segment in segments {
unit = index.member_unit(&unit, segment)?;
unit = index.member_unit_in(&unit, segment, surface)?;
}
Some(unit)
}
@@ -216,9 +283,14 @@ pub(super) fn last_segment(path: &str) -> &str {
/// Try the recorded paths in the order `analyze` wrote them — which is the
/// order the imports are written in — and take the first that has an answer.
fn follow_paths(index: &WorkspaceIndex, name: &str, paths: &[String]) -> ExternalTarget {
fn follow_paths(
index: &WorkspaceIndex,
name: &str,
paths: &[String],
surface: Surface,
) -> ExternalTarget {
for path in paths {
match target(follow_one(index, name, path)) {
match target(follow_one(index, name, path, surface)) {
ExternalTarget::StillUnresolved => continue,
answered => return answered,
}
@@ -243,22 +315,31 @@ fn follow_paths(index: &WorkspaceIndex, name: &str, paths: &[String]) -> Externa
/// `handle.member` and `this.member` reach a base class in a third file, and
/// what keeps the overlay and the index's own reference postings (which run
/// through this same function) from disagreeing about what a use names.
fn follow_one<'i>(index: &'i WorkspaceIndex, name: &str, path: &str) -> &'i [Def] {
fn follow_one<'i>(
index: &'i WorkspaceIndex,
name: &str,
path: &str,
surface: Surface,
) -> &'i [Def] {
let mut segments: Vec<&str> = path.split("::").collect();
if segments.is_empty() {
return &[];
}
if segments.len() < 2 {
return if path == name { index.units(name) } else { member_chain(index, path, name) };
return if path == name {
index.units(name)
} else {
member_chain(index, path, name, surface)
};
}
// The last segment is the use's own name, which `name` already carries
// (and which a `p::*` import spells as a wildcard); the ones before it are
// the hops.
segments.pop();
let Some(unit) = fold_path(index, &segments.join("::")) else {
let Some(unit) = fold_path(index, &segments.join("::"), surface) else {
return &[];
};
member_chain(index, &unit, name)
member_chain(index, &unit, name, surface)
}
impl ExternalResolutions {
@@ -0,0 +1,145 @@
//! A unit's two member surfaces: which surface each declaration joins
//! ([`surface_of`]), and the index reads that take a [`Surface`] rather than
//! assuming one.
//!
//! Every unit but a module has one surface, and for those this module is a
//! formality — the same set answers a `pkg::x` and a `handle.field`. A module
//! has two, because SystemVerilog gives it two different ways of being reached
//! from outside: a **connection list** may name its ports and parameters
//! (§23.3), and a **hierarchical path** may name anything it declares (§23.6).
//! Merging them would make `.internal_net(w)` a legal connection; keeping only
//! the first is what made `assign w = u_x.sig;` unresolvable across files
//! (`docs/topo.md` §2.9-23).
//!
//! So the index stores both, tagged, and every read says which one it wants.
//! The connection surface is the whole of what was there before this module
//! existed; the hierarchical surface is that set **plus** a module's nets,
//! variables and instances, which is why a record is tagged with the narrowest
//! surface it joins and a hierarchical read consults the connection table
//! first. A port has one record, is found by both reads, and is one answer.
use std::collections::HashSet;
use crate::model::{Surface, SymbolKind};
use super::{Def, WorkspaceIndex};
/// Which surface `member` joins in `unit`, or `None` when `unit` does not
/// export it at all.
///
/// A **package** or **class** exports everything declared at its top level (a
/// package's classes included — that is what lets `import uvm_pkg::*` answer
/// `uvm_object`), and it has no second surface: nothing reaches into a package
/// by a hierarchical path.
///
/// A **module** is the unit with two. Its connection surface is what a
/// connection list may name — ports and parameters — plus the properties and
/// sequences a bound-in checker instantiates (`top.u_dut.p_req`, and an
/// `` `include``d assertion file's bare-name instantiation). Its hierarchical
/// surface adds its **nets**, its **variables** and its **instances**: those
/// are what `u_x.sig` and `u_a.u_b.sig` name, they are not connectable, and
/// before 2026-09-05 they were not exported at all — which is what made a
/// cross-file rename of an internal net edit one file and warn about the
/// other. The instances are in it for the hop as much as for themselves:
/// `u_a.u_b.sig` needs `u_b`'s declared type to know where `sig` lives.
///
/// An **interface** is the 2026-09-01 exception and is unchanged: its signals
/// *are* its connection surface, because `virtual bus_if vif; vif.data` is how
/// every DV testbench reaches `data` and `vif` is a variable, not an instance.
/// It gains its instances hierarchically for the same hop reason, and nothing
/// else moves.
///
/// 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
/// labelled coverpoints and crosses plus the `sample` method its header
/// declares. Neither has a hierarchical surface: a struct is a type, and a
/// path reaches a covergroup's coverpoints the same single way from anywhere.
pub(super) fn surface_of(unit: SymbolKind, member: SymbolKind) -> Option<Surface> {
match unit {
SymbolKind::Package | SymbolKind::Class => matches!(
member,
SymbolKind::Param
| SymbolKind::LocalParam
| SymbolKind::Typedef
| SymbolKind::EnumVariant
| SymbolKind::Function
| SymbolKind::Task
| SymbolKind::Net
| SymbolKind::Var
| SymbolKind::Class
| SymbolKind::Constraint
| SymbolKind::Covergroup
| SymbolKind::Property
| SymbolKind::Sequence
)
.then_some(Surface::Connection),
SymbolKind::Module => match member {
SymbolKind::Port
| SymbolKind::Param
| SymbolKind::LocalParam
| SymbolKind::Property
| SymbolKind::Sequence => Some(Surface::Connection),
SymbolKind::Net | SymbolKind::Var | SymbolKind::Instance => Some(Surface::Hierarchical),
_ => None,
},
SymbolKind::Typedef | SymbolKind::StructMember => {
(member == SymbolKind::StructMember).then_some(Surface::Connection)
}
SymbolKind::Covergroup => {
matches!(member, SymbolKind::Coverpoint | SymbolKind::Cross | SymbolKind::Function)
.then_some(Surface::Connection)
}
SymbolKind::Interface => match member {
SymbolKind::Net
| SymbolKind::Var
| SymbolKind::Port
| SymbolKind::Param
| SymbolKind::LocalParam
| SymbolKind::Typedef
| SymbolKind::Function
| SymbolKind::Task
| SymbolKind::Modport
| SymbolKind::Clocking => Some(Surface::Connection),
SymbolKind::Instance => Some(Surface::Hierarchical),
_ => None,
},
_ => None,
}
}
/// `member` of `unit` in one surface: the connection records, and — for
/// [`Surface::Hierarchical`] — the hierarchical-only ones after them.
///
/// Connection first, so a name in both surfaces has exactly one answer and it
/// is the same declaration either read finds. Two map reads at worst, and one
/// for every lookup that is not a hierarchical tail.
pub(super) fn member<'i>(
index: &'i WorkspaceIndex,
unit: &str,
member: &str,
surface: Surface,
) -> &'i [Def] {
let found = index.member(unit, member);
match surface {
Surface::Connection => found,
Surface::Hierarchical if !found.is_empty() => found,
Surface::Hierarchical => index.hierarchical_member(unit, member),
}
}
/// Every member of `unit` in one surface, connection records first, each name
/// once — the listing half of [`member`] and the same first-hit-wins rule, so
/// a completion list offers what a lookup in the same surface would find.
pub(super) fn members_of<'i>(
index: &'i WorkspaceIndex,
unit: &str,
surface: Surface,
) -> Vec<(&'i str, &'i [Def])> {
let mut out: Vec<(&'i str, &'i [Def])> = index.members_of(unit).collect();
if surface == Surface::Hierarchical {
let held: HashSet<&str> = out.iter().map(|(name, _)| *name).collect();
out.extend(index.hierarchical_members_of(unit).filter(|(name, _)| !held.contains(name)));
}
out
}
+105 -25
View File
@@ -11,13 +11,14 @@ use std::path::{Path, PathBuf};
use vlog_parser::defines::{Define, DefineTable};
use crate::model::SymbolKind;
use crate::model::{Surface, SymbolKind};
use super::external::{base_chain, fold_path, last_segment, member_chain};
use super::external::{fold_path, last_segment, member_chain, own_members};
use super::hierarchy;
use super::record::{FileFacts, ReferenceFact};
use super::{
Def, DefinitionKey, FileId, IndexCounts, InheritanceEdge, InstantiationEdge, ReferenceSite,
WorkspaceIndex, WorkspaceSymbol,
reexport, Def, DefinitionKey, FileId, IndexCounts, InheritanceEdge, InstantiationEdge,
Reexport, ReferenceSite, WorkspaceIndex, WorkspaceSymbol,
};
impl WorkspaceIndex {
@@ -69,15 +70,30 @@ impl WorkspaceIndex {
self.units.get(name).map_or(&[], Vec::as_slice)
}
/// Every declaration of `member` exported by `unit`. This is what makes
/// `p::x` and `import p::*` reach into another file, and what makes a
/// `.port` connection reach into the instantiated module.
/// Every declaration of `member` `unit` exports on its **connection**
/// surface. This is what makes `p::x` and `import p::*` reach into
/// another file, and what makes a `.port` connection reach into the
/// instantiated module.
///
/// The connection surface is the whole surface of a package, a class and
/// a struct; for a module it is its ports and parameters, and what a
/// hierarchical path may name besides is
/// [`WorkspaceIndex::member_in`]'s business ([`Surface`]).
pub fn member(&self, unit: &str, member: &str) -> &[Def] {
self.members.get(unit).and_then(|m| m.get(member)).map_or(&[], Vec::as_slice)
}
/// Every exported member of `unit`, sorted by name — the completion list
/// behind `p::` and behind an instantiation's connection list.
/// [`WorkspaceIndex::member`] in a named surface: the same answer for
/// [`Surface::Connection`], and for [`Surface::Hierarchical`] the
/// connection records first and a module's nets, variables and instances
/// after them.
pub fn member_in(&self, unit: &str, member: &str, surface: Surface) -> &[Def] {
hierarchy::member(self, unit, member, surface)
}
/// Every member `unit` exports on its connection surface, sorted by name
/// — the completion list behind `p::` and behind an instantiation's
/// connection list.
pub fn members_of(&self, unit: &str) -> impl Iterator<Item = (&str, &[Def])> {
self.members
.get(unit)
@@ -85,6 +101,44 @@ impl WorkspaceIndex {
.flat_map(|m| m.iter().map(|(name, defs)| (name.as_str(), defs.as_slice())))
}
/// Every member of `unit` a hierarchical path may name and a connection
/// list may not, sorted by name — the second half of a hierarchical
/// listing, never a listing on its own.
pub(super) fn hierarchical_members_of(
&self,
unit: &str,
) -> impl Iterator<Item = (&str, &[Def])> {
self.hier_members
.get(unit)
.into_iter()
.flat_map(|m| m.iter().map(|(name, defs)| (name.as_str(), defs.as_slice())))
}
/// [`WorkspaceIndex::member`] on the hierarchical-only half alone.
pub(super) fn hierarchical_member(&self, unit: &str, member: &str) -> &[Def] {
self.hier_members.get(unit).and_then(|m| m.get(member)).map_or(&[], Vec::as_slice)
}
/// Every unit that declares `name` on its **hierarchical** surface, with
/// the declaration — the census `workspace_symbols` deliberately does not
/// hold.
///
/// A module's internal net is not a workspace symbol: `workspace/symbol`
/// answers what a user can name from outside, and a design with 20 000
/// modules has hundreds of thousands of internal signals. But a rename's
/// fan-out has to find the *declaring file* of a name a hierarchical tail
/// resolves to, and that is exactly this question — asked once per
/// rename, over a map, reading nothing. See
/// `docs/features/hierarchical-tail/README.md`.
pub fn hierarchical_declarations<'a>(
&'a self,
name: &'a str,
) -> impl Iterator<Item = (&'a str, &'a Def)> + 'a {
self.hier_members.iter().flat_map(move |(unit, members)| {
members.get(name).into_iter().flatten().map(move |def| (unit.as_str(), def))
})
}
/// Every member `path::` can name, **inherited ones included**, sorted by
/// name with one declaration each — the completion list behind `pkg::`,
/// `handle.` and `vif.` when the type is another file's.
@@ -97,32 +151,45 @@ impl WorkspaceIndex {
/// empty list, never a guess.
///
/// **The same walk one member lookup takes.** The units searched are
/// `unit` and then [`base_chain`]'s hops, in that order, and a name
/// declared in more than one of them is listed once from the nearest —
/// which is the first-hit-wins rule `member_chain` applies, so a
/// subclass's override is what is listed *and* what a lookup would find.
/// Map reads only: no file is opened.
/// `unit` and then its `extends` hops ([`own_members`]), then the packages
/// `unit` **re-exports** from ([`reexport::members`]) — exactly
/// `member_chain`'s order — and a name found in more than one of them is
/// listed once from the nearest. So a subclass's override, and a package's
/// own declaration of a name it also re-exports, are what is listed *and*
/// what a lookup would find. Map reads only: no file is opened.
pub fn members_of_chain(&self, path: &str) -> Vec<(&str, &Def)> {
let Some(unit) = fold_path(self, path) else {
self.members_of_chain_in(path, Surface::Connection)
}
/// [`WorkspaceIndex::members_of_chain`] in a named surface — the list
/// behind `u_x.` in an expression, where the module's nets, variables and
/// instances are what the user is reaching for and what the tail
/// resolution will find. A connection list's `.` is the other surface and
/// its own function (`completion::connection_members`).
pub fn members_of_chain_in(&self, path: &str, surface: Surface) -> Vec<(&str, &Def)> {
let Some(unit) = fold_path(self, path, surface) else {
return Vec::new();
};
let mut hops: Vec<&str> = vec![unit.as_str()];
hops.extend(base_chain(self, &unit));
let mut out: Vec<(&str, &Def)> = Vec::new();
let mut seen: HashSet<&str> = HashSet::new();
for hop in hops {
for (name, defs) in self.members_of(hop) {
if let Some(def) = defs.first() {
if seen.insert(name) {
out.push((name, def));
}
}
for (name, def) in
own_members(self, &unit, surface).into_iter().chain(reexport::members(self, &unit))
{
if seen.insert(name) {
out.push((name, def));
}
}
out.sort_by_key(|(name, _)| *name);
out
}
/// What one package re-exports, in file order then source order — the
/// edges `reexport`'s two walks follow. Empty for every unit that
/// re-exports nothing, which is all but a handful in any workspace.
pub(super) fn reexports(&self, unit: &str) -> &[Reexport] {
self.reexports.get(unit).map_or(&[], Vec::as_slice)
}
/// The **declared type** of one member of one unit, as the next unit name
/// to look in — the hop that walks a chain `pkt_t::hdr::addr` across
/// files, and the one a `MemberSite::Unit` path is folded by.
@@ -136,7 +203,14 @@ impl WorkspaceIndex {
/// class declared inside a package declares no file-scope unit at all —
/// the dominant UVM shape — and is unaffected.
pub fn member_unit(&self, unit: &str, member: &str) -> Option<String> {
let [def] = member_chain(self, unit, member) else {
self.member_unit_in(unit, member, Surface::Connection)
}
/// [`WorkspaceIndex::member_unit`] in a named surface: the hop
/// `u_a.u_b.sig` takes, where `u_b` is an instance inside `a` and only
/// the hierarchical surface holds it.
pub fn member_unit_in(&self, unit: &str, member: &str, surface: Surface) -> Option<String> {
let [def] = member_chain(self, unit, member, surface) else {
return None;
};
let next = last_segment(def.type_name.as_deref()?);
@@ -411,6 +485,12 @@ impl WorkspaceIndex {
.filter(|d| d.kind == SymbolKind::Class)
.count(),
members: self.members.values().flat_map(|m| m.values()).map(Vec::len).sum(),
hierarchical_members: self
.hier_members
.values()
.flat_map(|m| m.values())
.map(Vec::len)
.sum(),
defines: self.facts.iter().map(|f| f.defines.entries().len()).sum(),
instantiations: self.instantiations.values().map(Vec::len).sum(),
inheritances: self.subclasses.values().map(Vec::len).sum(),
+32 -5
View File
@@ -16,19 +16,26 @@
//! This file is the index's vocabulary: the records it hands out ([`Def`],
//! [`DeclLines`], the edges) and the [`WorkspaceIndex`] tables themselves.
//! `index` answers questions of a built index, `update` changes one after it
//! is built, `record` reads off what one file contributes ([`FileFacts`]), and
//! is built, `record` reads off what one file contributes ([`FileFacts`]),
//! `external` is the overlay — [`resolve_external`] — and the member and
//! inheritance walks it shares with `index`.
//! inheritance walks it shares with `index`, `reexport` is the one edge
//! neither of those two could hold — what `export b_pkg::x;` makes reachable
//! through the package that writes it — and `hierarchy` is which of a unit's
//! two member surfaces holds what, and the reads that take a
//! [`crate::Surface`] instead of assuming one.
mod external;
mod hierarchy;
mod index;
mod record;
mod reexport;
mod update;
pub use external::{resolve_external, Definition, ExternalResolutions, ExternalTarget};
pub use index::{index_order, IndexBuilder};
pub use record::FileFacts;
pub(crate) use record::{Decl, ReferenceFact, SiteFact};
pub(crate) use reexport::Reexport;
use std::collections::{BTreeMap, HashSet};
use std::path::PathBuf;
@@ -287,13 +294,28 @@ pub struct WorkspaceIndex {
facts: Vec<FileFacts>,
/// File-scope name → every declaration of it, in disambiguation order.
units: BTreeMap<String, Vec<Def>>,
/// Unit name → member name → every declaration of it.
/// Unit name → member name → every declaration of it, on the
/// **connection** surface: what a connection list, a `pkg::x` and a
/// `handle.field` may name. This is the whole member table as it was
/// before 2026-09-05, and every query that does not name a surface reads
/// exactly this.
members: BTreeMap<String, BTreeMap<String, Vec<Def>>>,
/// The same shape for the members a **hierarchical path** may name and a
/// connection list may not — a module's (or an interface's) nets,
/// variables and instances. Kept apart rather than tagged in place so
/// that every existing read stays the read it was, and a hierarchical
/// read is `members` first and this second (`hierarchy`).
hier_members: BTreeMap<String, BTreeMap<String, Vec<Def>>>,
/// Instantiated module name → every site, in file order then walk order.
instantiations: BTreeMap<String, Vec<InstantiationEdge>>,
/// Base class name → every class extending it, in file order then walk
/// order.
subclasses: BTreeMap<String, Vec<InheritanceEdge>>,
/// Exporting package name → the packages and names it re-exports, in file
/// order then source order. Followed at *query* time rather than folded
/// into `members`, so a re-export costs nothing until something asks a
/// package for a name it does not itself declare. See `reexport`.
reexports: BTreeMap<String, Vec<Reexport>>,
/// The same census read the other way: class name → the base it extends,
/// as written. Built in [`WorkspaceIndex::merge`] from the very edges that
/// fill `subclasses`, so the two cannot disagree and no [`FileFacts`]
@@ -327,9 +349,14 @@ pub struct IndexCounts {
/// Class declarations reachable in the index — file-scope units plus
/// classes registered as members of a package or an enclosing class.
pub classes: usize,
/// Package, class and module member declarations, duplicates counted
/// separately.
/// Package, class and module member declarations on the **connection**
/// surface, duplicates counted separately.
pub members: usize,
/// Member declarations only a hierarchical path can name — a module's or
/// an interface's nets, variables and instances — duplicates counted
/// separately. Disjoint from `members`, so the whole member census is the
/// two added.
pub hierarchical_members: usize,
/// `` `define``/`` `undef`` directives recorded across all files.
pub defines: usize,
/// Instantiation sites recorded — one per written statement, inside a
+69 -93
View File
@@ -1,10 +1,11 @@
//! What one file contributes to an index, read off its parse: the
//! [`FileFacts`] record and the per-file shapes inside it ([`Decl`],
//! [`SiteFact`], [`ReferenceFact`]), the read-off itself
//! ([`facts_from_analysis`]), and the two rulings it applies — which
//! file-scope kinds are units, and what each kind of unit exports. A record
//! is the unit of persistence (`facts.rs` encodes exactly this) and of
//! incremental update, which is why it is a module of its own.
//! ([`facts_from_analysis`]), and the ruling it applies about which
//! file-scope kinds are units. What each kind of unit *exports*, and on which
//! surface, moved to [`hierarchy::surface_of`] when a module gained a second
//! one. A record is the unit of persistence (`facts.rs` encodes exactly this)
//! and of incremental update, which is why it is a module of its own.
use std::collections::HashSet;
use std::path::{Path, PathBuf};
@@ -15,10 +16,13 @@ use vlog_parser::span::TextRange;
use vlog_parser::token::Token;
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex};
use crate::model::{Resolution, Symbol, SymbolKind};
use crate::model::{Resolution, Surface, Symbol, SymbolKind};
use crate::{analyze, classes, instantiations, Semantics};
use super::{DeclLines, DeclPositions, DeclSite, Def, FileId, InstanceOccurrence, Utf16Range};
use super::{
hierarchy, reexport, DeclLines, DeclPositions, DeclSite, Def, FileId, InstanceOccurrence,
Reexport, Utf16Range,
};
/// One declaration as a single file contributes it, before that file has a
/// [`FileId`]. The id depends on where the file's path sorts among all of
@@ -32,12 +36,19 @@ pub(crate) struct Decl {
pub(crate) detail_span: Option<TextRange>,
pub(crate) lines: DeclLines,
pub(crate) type_name: Option<String>,
/// Which of its owner's member surfaces this declaration joins — the
/// narrowest one, so a connection-surface record is found by a
/// hierarchical read too ([`hierarchy::surface_of`]). Always
/// [`Surface::Connection`] for a unit, which has no owner and is reached
/// by name.
pub(crate) surface: Surface,
}
impl Decl {
/// A member's declaration: lines only, no client positions — see
/// [`DeclPositions`] for why the cheap half is the only half a member gets.
fn member(symbol: &Symbol, lines: &LineIndex) -> Decl {
/// A member's declaration, on the surface its owner exports it: lines
/// only, no client positions — see [`DeclPositions`] for why the cheap
/// half is the only half a member gets.
fn member(symbol: &Symbol, lines: &LineIndex, surface: Surface) -> Decl {
Decl {
name: symbol.name.clone(),
name_span: symbol.name_span,
@@ -46,13 +57,14 @@ impl Decl {
detail_span: symbol.detail_span,
lines: DeclLines::of(lines, symbol.name_span, symbol.detail_span),
type_name: symbol.type_name.clone(),
surface,
}
}
/// A file-scope declaration: the same, plus the two ranges a client is
/// pointed at, converted here so no one converts them later.
fn unit(symbol: &Symbol, src: &str, lines: &LineIndex) -> Decl {
let mut decl = Decl::member(symbol, lines);
let mut decl = Decl::member(symbol, lines, Surface::Connection);
decl.lines.positions = Some(DeclPositions {
name: Utf16Range::of(src, lines, symbol.name_span),
decl: Utf16Range::of(src, lines, symbol.decl_span),
@@ -99,7 +111,8 @@ pub struct FileFacts {
pub(crate) defines: DefineTable,
/// File-scope declarations, in declaration order.
pub(crate) units: Vec<Decl>,
/// Members, each under the name of the unit that exports it, in the order
/// Members, each under the name of the unit that exports it and tagged
/// with the surface it is exported on ([`Decl::surface`]), in the order
/// the scope tree yields them.
pub(crate) members: Vec<(String, Decl)>,
/// Instantiation sites, each under the name of the module instantiated, in
@@ -108,6 +121,10 @@ pub struct FileFacts {
/// Class declarations with a base, each under the base's name, in walk
/// order.
pub(crate) subclasses: Vec<(String, DeclSite)>,
/// Package re-exports, each under the name of the package that writes it,
/// in source order — [`super::reexport::of`]'s answer, `export *::*;`
/// already expanded to that package's imports.
pub(crate) reexports: Vec<(String, Reexport)>,
/// Uses of declarations another file may name, stored before file ids and
/// cross-file candidates have been resolved by the finished index.
pub(crate) references: Vec<ReferenceFact>,
@@ -148,7 +165,17 @@ pub(crate) enum ReferenceFact {
/// chases it. Without it a `this.x` whose class is another file's had no
/// posting at all, so a cross-file find-references from the property's
/// own declaration did not list it (round 1's residue).
External { name: String, base: Option<String>, paths: Vec<String>, occurrence: TextRange },
External {
name: String,
base: Option<String>,
paths: Vec<String>,
/// Which member surface the recorded paths are walked in — carried
/// straight from [`Resolution::ExternalCandidate`], because the file
/// that wrote the path is the only layer that knows whether its head
/// was an instance.
surface: Surface,
occurrence: TextRange,
},
}
impl ReferenceFact {
@@ -274,6 +301,7 @@ fn facts_from_analysis(
members: Vec::new(),
instantiations: edges_of(tree, src, lines),
subclasses: inheritance_of(tree),
reexports: reexport::of(tree),
references: Vec::new(),
words: census.words,
macro_words: census.macro_words,
@@ -291,11 +319,29 @@ fn facts_from_analysis(
facts.units.push(Decl::unit(unit, src, lines));
collect_members(sem, &unit.name, unit, lines, &mut facts.members);
}
// The **connection** surface only. A `Local` posting exists so that a
// declaration another file can point at carries its own file's uses
// without that file being re-read, and every consumer of the postings
// that matters here — the rename, which re-analyses the declaring file
// anyway — already has them. Posting a module's every internal net use
// would multiply the reference table by the size of an RTL body for an
// answer nothing reads; the hierarchical surface is what a *cross-file*
// tail resolves through, and that half is an `External` fact below.
// See `docs/features/hierarchical-tail/README.md`, "what did not widen".
// Which kind lands on which surface is `hierarchy::surface_of`, the one
// rule this filter and the member tables both read (§49's QA asked for
// the pointer).
let exported: HashSet<(u32, u32)> = facts
.units
.iter()
.map(|decl| (decl.name_span.start, decl.name_span.end))
.chain(facts.members.iter().map(|(_, decl)| (decl.name_span.start, decl.name_span.end)))
.chain(
facts
.members
.iter()
.filter(|(_, decl)| decl.surface == Surface::Connection)
.map(|(_, decl)| (decl.name_span.start, decl.name_span.end)),
)
.collect();
for reference in sem.references() {
let fact = match &reference.resolution {
@@ -305,21 +351,25 @@ fn facts_from_analysis(
.contains(&(definition.start, definition.end))
.then_some(ReferenceFact::Local { definition, occurrence: reference.name_span })
}),
Resolution::ExternalCandidate { paths } if !paths.is_empty() => {
Resolution::ExternalCandidate { paths, surface } if !paths.is_empty() => {
Some(ReferenceFact::External {
name: reference.name.clone(),
base: None,
paths: paths.clone(),
surface: *surface,
occurrence: reference.name_span,
})
}
// An inherited candidate is recorded even with **no** paths: the
// base alone is a handle on the declaration, and the merge chases
// it through the same member tables the overlay does.
// An inherited miss is a class's business, and a class has one
// surface.
Resolution::InheritedCandidate { base, paths } => Some(ReferenceFact::External {
name: reference.name.clone(),
base: Some(base.clone()),
paths: paths.clone(),
surface: Surface::Connection,
occurrence: reference.name_span,
}),
_ => None,
@@ -409,10 +459,13 @@ fn collect_members(
let Some(member) = sem.symbol(id) else {
continue;
};
if !is_exported(unit.kind, member.kind) || member.name_span.is_empty() {
let Some(surface) = hierarchy::surface_of(unit.kind, member.kind) else {
continue;
};
if member.name_span.is_empty() {
continue;
}
let mut decl = Decl::member(member, lines);
let mut decl = Decl::member(member, lines, surface);
let nested = nested_key(key, member);
if let Some(nested) = &nested {
decl.type_name = Some(nested.clone());
@@ -479,80 +532,3 @@ fn is_unit(kind: SymbolKind) -> bool {
matches!(kind, SymbolKind::Package | SymbolKind::Typedef | SymbolKind::Class)
|| kind.is_instantiable()
}
/// What `unit::member` / `.member` may reach.
///
/// A package or class exports everything declared at its top level (a
/// package's classes included — that is what lets `import uvm_pkg::*` answer
/// `uvm_object`). A **module** exports only what a connection list can name —
/// its ports and its parameters — so an internal net is never reachable from
/// another file.
///
/// An **interface** is the exception the 2026-09-01 round exists for: its
/// signals *are* its surface. `virtual bus_if vif; vif.data` is how every DV
/// testbench in the world reaches `data`, and `data` is an ordinary net or
/// variable declared inside the interface, not a port of it. So an interface
/// exports its nets, variables, ports, parameters, typedefs, methods, modports
/// and clocking blocks. The module ruling is untouched: a module handle is an
/// *instance*, whose internals no other file's connection list may name.
fn is_exported(unit: SymbolKind, member: SymbolKind) -> bool {
match unit {
SymbolKind::Package | SymbolKind::Class => matches!(
member,
SymbolKind::Param
| SymbolKind::LocalParam
| SymbolKind::Typedef
| SymbolKind::EnumVariant
| SymbolKind::Function
| SymbolKind::Task
| SymbolKind::Net
| SymbolKind::Var
| SymbolKind::Class
| SymbolKind::Constraint
| SymbolKind::Covergroup
| SymbolKind::Property
| SymbolKind::Sequence
),
// A module exports its ports and parameters — and, since
// `sva-bodies`, the properties and sequences declared in its body: a
// bound-in checker module names them as `top.u_dut.p_req`, and an
// `` `include``d assertion file instantiates them by bare name.
SymbolKind::Module => matches!(
member,
SymbolKind::Port
| SymbolKind::Param
| SymbolKind::LocalParam
| SymbolKind::Property
| SymbolKind::Sequence
),
// 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`. Nothing
// else lives in a struct body, so this arm is exhaustive by
// construction rather than by policy.
SymbolKind::Typedef | SymbolKind::StructMember => {
matches!(member, SymbolKind::StructMember)
}
// A covergroup's surface is its labelled coverpoints and crosses —
// `cg.cp` is how a cross in another covergroup, or a `get_coverage`
// call in another file, names one — plus the `sample` method the
// header declares.
SymbolKind::Covergroup => {
matches!(member, SymbolKind::Coverpoint | SymbolKind::Cross | SymbolKind::Function)
}
SymbolKind::Interface => matches!(
member,
SymbolKind::Net
| SymbolKind::Var
| SymbolKind::Port
| SymbolKind::Param
| SymbolKind::LocalParam
| SymbolKind::Typedef
| SymbolKind::Function
| SymbolKind::Task
| SymbolKind::Modport
| SymbolKind::Clocking
),
_ => false,
}
}
@@ -0,0 +1,196 @@
//! Package re-exports (IEEE 1800 §26.6) as real edges of the index: the
//! [`Reexport`] record one file contributes, the read-off that produces it,
//! and the two walks that follow it — one name looked up through a chain of
//! re-exports ([`member`]), and every name such a chain offers ([`members`]).
//!
//! `export b_pkg::x;` inside `a_pkg` does not put `x` in `a_pkg`'s scope; it
//! makes `x` reachable to whoever imports `a_pkg`. The binder records the two
//! halves as references and nothing more (`bind::Binder::bind_export_path`),
//! so everything that makes `a_pkg::x` *mean* `b_pkg`'s `x` is here.
//!
//! See `docs/features/package-reexports/README.md`.
use std::collections::{HashSet, VecDeque};
use vlog_parser::ast::{ExportDecl, Item, ItemKind, SourceFile};
use crate::model::Surface;
use super::external::{own_chain, own_members};
use super::{Def, WorkspaceIndex};
/// One name (or one wildcard) a package re-exports from another.
///
/// The two halves as written, with no interpretation applied: `item` is the
/// bare `*` of `export b_pkg::*;` exactly as the parser stores it, because
/// "everything that package exports" is a question only the finished index
/// can answer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Reexport {
/// The package the name is taken from, as written.
pub(crate) package: String,
/// The name re-exported, or `*` for every name `package` exports.
pub(crate) item: String,
}
impl Reexport {
/// Whether this edge lets `name` through.
fn admits(&self, name: &str) -> bool {
self.item == "*" || self.item == name
}
/// The one name this edge carries, or `None` for a wildcard.
fn only(&self) -> Option<&str> {
(self.item != "*").then_some(self.item.as_str())
}
}
/// Every package re-export one file writes, under the name of the package
/// that writes it, in source order.
///
/// **`export *::*;` is expanded here, into the exporting package's own
/// imports.** It means "everything imported into this package is re-exported"
/// (§26.6), and which packages those are is a property of this one file — the
/// very file being read off — so recording it as a flag for a later walk to
/// interpret would only move the same lookup somewhere with less information.
/// `export *::*;` in a package that imports nothing therefore records nothing,
/// which is also what it re-exports.
pub(super) fn of(tree: &SourceFile) -> Vec<(String, Reexport)> {
let mut out = Vec::new();
for item in &tree.items {
let ItemKind::Package { name, items, .. } = &item.kind else {
continue;
};
for entry in exports_of(items) {
out.push((name.clone(), entry));
}
}
out
}
/// The re-export edges one package body writes.
fn exports_of(items: &[Item]) -> Vec<Reexport> {
let mut out: Vec<Reexport> = Vec::new();
let mut everything = false;
for item in items {
let ItemKind::Export(ExportDecl::Package(paths)) = &item.kind else {
continue;
};
for path in paths {
if path.pkg.text == "*" {
everything = true;
} else {
add(&mut out, &path.pkg.text, &path.item.text);
}
}
}
if everything {
for item in items {
if let ItemKind::Import(paths) = &item.kind {
for path in paths {
add(&mut out, &path.pkg.text, &path.item.text);
}
}
}
}
out
}
/// One edge, unless the package already writes it — `export b_pkg::x;` beside
/// an `import b_pkg::x;` under an `export *::*;` is one edge, not two.
fn add(out: &mut Vec<Reexport>, package: &str, item: &str) {
let entry = Reexport { package: package.to_string(), item: item.to_string() };
if !out.contains(&entry) {
out.push(entry);
}
}
/// `name` in the packages `unit` re-exports it from, transitively.
///
/// Breadth-first over the edges that *admit* `name` — `pkg::name` and
/// `pkg::*`, never `pkg::other` — asking each package reached for `name` in
/// its own members and its bases ([`own_chain`]). The first package that has
/// it answers, so the nearest re-export wins, on the same first-hit-wins rule
/// the `extends` chain follows.
///
/// **Terminates on any workspace.** A package is asked at most once (the
/// visited set), so `a_pkg` re-exporting `b_pkg::*` while `b_pkg` re-exports
/// `a_pkg::*` walks two hops and stops. Map reads only: no file is opened.
pub(super) fn member<'i>(index: &'i WorkspaceIndex, unit: &str, name: &str) -> &'i [Def] {
// The overwhelmingly common case, and the one every member miss in a
// workspace without re-exports pays: one map read, nothing allocated.
if index.reexports(unit).is_empty() {
return &[];
}
let mut seen: HashSet<&str> = HashSet::from([unit]);
let mut queue: VecDeque<&'i str> = VecDeque::new();
admitting(index, unit, name, &mut queue);
while let Some(hop) = queue.pop_front() {
if !seen.insert(hop) {
continue;
}
// A package's surface is a package's surface: one, and connection.
let found = own_chain(index, hop, name, Surface::Connection);
if !found.is_empty() {
return found;
}
admitting(index, hop, name, &mut queue);
}
&[]
}
/// The packages one hop further on that still let `name` through.
fn admitting<'i>(index: &'i WorkspaceIndex, unit: &str, name: &str, queue: &mut VecDeque<&'i str>) {
queue.extend(
index.reexports(unit).iter().filter(|e| e.admits(name)).map(|e| e.package.as_str()),
);
}
/// Every name `unit` re-exports, with the declaration each one names — the
/// listing twin of [`member`], and what a completion after `a_pkg::` adds to
/// the package's own members.
///
/// A `pkg::*` edge contributes everything that package exports **and** carries
/// on through that package's own re-exports; a `pkg::x` edge contributes at
/// most `x`, and carries on only through edges that admit `x`. The visited set
/// is keyed by (package, name-filter), so a cycle terminates here too, and a
/// name reached twice is left to the caller to deduplicate against the unit's
/// own members — which is what keeps a local declaration ahead of a
/// re-exported one of the same name.
pub(super) fn members<'i>(index: &'i WorkspaceIndex, unit: &str) -> Vec<(&'i str, &'i Def)> {
let mut out: Vec<(&'i str, &'i Def)> = Vec::new();
let mut seen: HashSet<(&str, Option<&str>)> = HashSet::new();
let mut queue: VecDeque<(&'i str, Option<&'i str>)> = hops(index, unit);
while let Some((package, only)) = queue.pop_front() {
if !seen.insert((package, only)) {
continue;
}
match only {
None => {
out.extend(own_members(index, package, Surface::Connection));
queue.extend(hops(index, package));
}
Some(name) => {
out.extend(
own_chain(index, package, name, Surface::Connection)
.first()
.map(|def| (name, def)),
);
queue.extend(
index
.reexports(package)
.iter()
.filter(|e| e.admits(name))
.map(|e| (e.package.as_str(), Some(name))),
);
}
}
}
out
}
/// One package's re-export edges as walk items: the package reached, and the
/// one name the edge carries (`None` for a wildcard).
fn hops<'i>(index: &'i WorkspaceIndex, unit: &str) -> VecDeque<(&'i str, Option<&'i str>)> {
index.reexports(unit).iter().map(|e| (e.package.as_str(), e.only())).collect()
}
+38 -3
View File
@@ -9,6 +9,8 @@ use std::path::{Path, PathBuf};
use vlog_parser::defines::DefineKind;
use crate::model::Surface;
use super::external::{resolve_fact, ExternalTarget};
use super::record::{facts_of, FileFacts, ReferenceFact};
use super::{
@@ -216,6 +218,15 @@ impl WorkspaceIndex {
}
}
}
// The re-export edges, which decide what `a_pkg::x` means and are
// therefore an observable in their own right — a merge that dropped
// one would otherwise show up only as whichever references happened to
// resolve through it.
for (exporter, edges) in &self.reexports {
for edge in edges {
out.push_str(&format!("reexport {exporter} <- {}::{}\n", edge.package, edge.item));
}
}
for (name, edges) in self.subclasses() {
for edge in edges {
out.push_str(&format!(
@@ -242,8 +253,10 @@ impl WorkspaceIndex {
None => {
self.units.clear();
self.members.clear();
self.hier_members.clear();
self.instantiations.clear();
self.subclasses.clear();
self.reexports.clear();
self.macro_definitions.clear();
}
Some(affected) => {
@@ -252,6 +265,7 @@ impl WorkspaceIndex {
}
for name in &affected.containers {
self.members.remove(name);
self.hier_members.remove(name);
}
for name in &affected.modules {
self.instantiations.remove(name);
@@ -259,6 +273,9 @@ impl WorkspaceIndex {
for name in &affected.bases {
self.subclasses.remove(name);
}
for name in &affected.exporters {
self.reexports.remove(name);
}
for name in &affected.macros {
self.macro_definitions.remove(name);
}
@@ -276,7 +293,14 @@ impl WorkspaceIndex {
if affected.is_some_and(|a| !a.containers.contains(unit)) {
continue;
}
self.members
// The record's own tag picks the table; the two are keyed
// alike, are cleared together above, and a caller that names
// no surface reads the connection one.
let table = match decl.surface {
Surface::Connection => &mut self.members,
Surface::Hierarchical => &mut self.hier_members,
};
table
.entry(unit.clone())
.or_default()
.entry(decl.name.clone())
@@ -303,6 +327,12 @@ impl WorkspaceIndex {
.or_default()
.push(InheritanceEdge { file, subclass: subclass.clone() });
}
for (exporter, entry) in &facts.reexports {
if affected.is_some_and(|a| !a.exporters.contains(exporter)) {
continue;
}
self.reexports.entry(exporter.clone()).or_default().push(entry.clone());
}
for (entry, define) in facts.defines.entries().iter().enumerate() {
if define.kind != DefineKind::Define
|| affected.is_some_and(|a| !a.macros.contains(&define.name))
@@ -346,8 +376,8 @@ impl WorkspaceIndex {
};
sites.entry(key).or_default().push(site);
}
ReferenceFact::External { name, base, paths, .. } => {
match resolve_fact(self, name, base.as_deref(), paths) {
ReferenceFact::External { name, base, paths, surface, .. } => {
match resolve_fact(self, name, base.as_deref(), paths, *surface) {
ExternalTarget::Resolved(def) => {
sites.entry(DefinitionKey::of(&def)).or_default().push(site);
}
@@ -377,6 +407,10 @@ pub(super) struct Affected {
containers: HashSet<String>,
modules: HashSet<String>,
bases: HashSet<String>,
/// Keys of the `reexports` table — the package that writes the `export`,
/// never the package it takes the name from: a file changing what `a_pkg`
/// re-exports moves `a_pkg`'s edges and no one else's.
exporters: HashSet<String>,
macros: HashSet<String>,
}
@@ -392,6 +426,7 @@ impl Affected {
self.containers.extend(facts.members.iter().map(|(unit, _)| unit.clone()));
self.modules.extend(facts.instantiations.iter().map(|(module, _)| module.clone()));
self.bases.extend(facts.subclasses.iter().map(|(base, _)| base.clone()));
self.exporters.extend(facts.reexports.iter().map(|(exporter, _)| exporter.clone()));
self.macros.extend(facts.defines.entries().iter().map(|define| define.name.clone()));
}
}
+15 -6
View File
@@ -6,7 +6,7 @@ use std::path::PathBuf;
use vlog_parser::parse_source;
use vlog_semantic::{
analyze, resolve_external, Definition, ExternalTarget, Resolution, ScopeKind, Semantics,
SymbolId, SymbolKind, WorkspaceIndex,
Surface, SymbolId, SymbolKind, WorkspaceIndex,
};
fn sem(src: &str) -> Semantics {
@@ -309,7 +309,7 @@ endclass
";
let s = sem(src);
match resolution_at(&s, nth(src, "uvm_object", 0)) {
Resolution::ExternalCandidate { paths } => {
Resolution::ExternalCandidate { paths, .. } => {
// The wildcard import and the bare unit name, in that order.
assert_eq!(paths, vec!["uvm_pkg::*".to_string(), "uvm_object".to_string()]);
}
@@ -393,11 +393,17 @@ endclass
let s = sem(src);
assert_eq!(
resolution_at(&s, nth(src, "other_pkg", 0)),
Resolution::ExternalCandidate { paths: vec!["other_pkg".to_string()] }
Resolution::ExternalCandidate {
paths: vec!["other_pkg".to_string()],
surface: Surface::Connection,
}
);
assert_eq!(
resolution_at(&s, nth(src, "other_base", 0)),
Resolution::ExternalCandidate { paths: vec!["other_base".to_string()] }
Resolution::ExternalCandidate {
paths: vec!["other_base".to_string()],
surface: Surface::Connection,
}
);
assert_eq!(
resolution_at(&s, nth(src, "member_miss", 0)),
@@ -482,7 +488,7 @@ endfunction
let s = sem(src);
// The class is not in this file: the head is an external candidate...
match resolution_at(&s, nth(src, "elsewhere", 0)) {
Resolution::ExternalCandidate { paths } => {
Resolution::ExternalCandidate { paths, .. } => {
assert_eq!(paths, vec!["elsewhere".to_string()])
}
other => panic!("expected an external candidate, got {other:?}"),
@@ -562,7 +568,10 @@ endmodule
let s = sem(src);
assert_eq!(
resolution_at(&s, nth(src, "later::K", 0) + 7),
Resolution::ExternalCandidate { paths: vec!["later::K".to_string()] }
Resolution::ExternalCandidate {
paths: vec!["later::K".to_string()],
surface: Surface::Connection,
}
);
}
+14 -5
View File
@@ -6,8 +6,8 @@
use std::path::{Path, PathBuf};
use vlog_parser::parse_source;
use vlog_semantic::{
analyze, resolve_external, Def, ExternalTarget, FileFacts, Resolution, Semantics, Symbol,
SymbolKind, WorkspaceIndex,
analyze, resolve_external, Def, ExternalTarget, FileFacts, Resolution, Semantics, Surface,
Symbol, SymbolKind, WorkspaceIndex,
};
// ----------------------------------------------------------------------
@@ -112,7 +112,10 @@ fn an_interface_instantiation_resolves_in_file_and_across_files() {
let use_at = at(sources[1].1, "bus_if u_bus");
assert_eq!(
resolution(&sem(sources[1].1), use_at),
Some(Resolution::ExternalCandidate { paths: vec!["bus_if".to_string()] })
Some(Resolution::ExternalCandidate {
paths: vec!["bus_if".to_string()],
surface: Surface::Connection,
})
);
let def = overlay_def(&ws, sources[1].1, use_at).expect("the unit table answers");
assert_eq!(def.kind, SymbolKind::Interface);
@@ -251,7 +254,10 @@ fn the_modport_half_of_a_port_type_resolves_across_files() {
let tail = after(src, "bus_if.");
assert_eq!(
resolution(&sem(src), tail),
Some(Resolution::ExternalCandidate { paths: vec!["bus_if::mp".to_string()] })
Some(Resolution::ExternalCandidate {
paths: vec!["bus_if::mp".to_string()],
surface: Surface::Connection,
})
);
let def = overlay_def(&ws, src, tail).expect("the member table answers");
assert_eq!(def.kind, SymbolKind::Modport);
@@ -350,7 +356,10 @@ fn a_clocking_signal_is_reached_through_the_block_in_file_and_across_files() {
let tail = after(env, "vif.cb.");
assert_eq!(
resolution(&sem(env), tail),
Some(Resolution::ExternalCandidate { paths: vec!["bus_if::cb::data".to_string()] })
Some(Resolution::ExternalCandidate {
paths: vec!["bus_if::cb::data".to_string()],
surface: Surface::Connection,
})
);
let def = overlay_def(&ws, env, tail).expect("the member chain answers");
assert_eq!(slice(&ws, &sources, &def), "data");
+41 -12
View File
@@ -6,7 +6,7 @@
use std::path::PathBuf;
use vlog_parser::parse_source;
use vlog_semantic::{
analyze, resolve_external, Def, ExternalTarget, Resolution, Semantics, SymbolKind,
analyze, resolve_external, Def, ExternalTarget, Resolution, Semantics, Surface, SymbolKind,
WorkspaceIndex,
};
@@ -284,11 +284,17 @@ endmodule
let s = sem(src);
assert_eq!(
resolution_at(&s, tail(src, "h.user_id", 0)),
Resolution::ExternalCandidate { paths: vec!["c1::user_id".to_string()] }
Resolution::ExternalCandidate {
paths: vec!["c1::user_id".to_string()],
surface: Surface::Connection,
}
);
assert_eq!(
resolution_at(&s, tail(src, "q.other", 0)),
Resolution::ExternalCandidate { paths: vec!["c2::other".to_string()] }
Resolution::ExternalCandidate {
paths: vec!["c2::other".to_string()],
surface: Surface::Connection,
}
);
}
@@ -525,7 +531,10 @@ fn a_qualified_type_from_a_package_elsewhere_still_reaches_the_workspace() {
let s = sem(src);
assert_eq!(
resolution_at(&s, tail(src, "h.user_id", 0)),
Resolution::ExternalCandidate { paths: vec!["c1::user_id".to_string()] }
Resolution::ExternalCandidate {
paths: vec!["c1::user_id".to_string()],
surface: Surface::Connection,
}
);
}
@@ -795,7 +804,10 @@ fn a_chain_resolves_link_by_link_in_one_file() {
fn a_chain_resolves_across_three_files() {
assert_eq!(
resolution_at(&sem(DRIVER), tail(DRIVER, "item.hdr.addr", 0)),
Resolution::ExternalCandidate { paths: vec!["item_t::hdr::addr".to_string()] },
Resolution::ExternalCandidate {
paths: vec!["item_t::hdr::addr".to_string()],
surface: Surface::Connection,
},
"the single-file layer composes the path and stops"
);
for order in [
@@ -929,8 +941,11 @@ endmodule
}
/// Across files, an instance head reaches what the index holds for the module
/// — its **ports and parameters**, which is what a module exports (see the
/// feature README's round-2 ruling on internal signals).
/// on its **hierarchical** surface: its ports and parameters, and — since
/// 2026-09-05 — its internal nets and variables too, because `u.internal` is
/// a hierarchical path and IEEE 1800 §23.6 says a hierarchical path may name
/// any of them (`docs/features/hierarchical-tail/README.md`). A `.internal(w)`
/// *connection* is still refused: that reads the connection surface.
#[test]
fn an_instance_head_reaches_a_module_in_another_file() {
const SUB: &str =
@@ -938,16 +953,27 @@ fn an_instance_head_reaches_a_module_in_another_file() {
const TOP: &str = "module m;\n sub u ();\n initial begin\n y = u.clk_i;\n y = u.W;\n y = u.internal;\n end\nendmodule\n";
assert_eq!(
resolution_at(&sem(TOP), tail(TOP, "u.clk_i", 0)),
Resolution::ExternalCandidate { paths: vec!["sub::clk_i".to_string()] }
// An instance head is a hierarchical path, and its tail reads the
// module's hierarchical surface — which holds the connection surface
// whole, so a *port* named through one has exactly one answer.
Resolution::ExternalCandidate {
paths: vec!["sub::clk_i".to_string()],
surface: Surface::Hierarchical,
}
);
let ws = index(&[("sub.sv", SUB), ("top.sv", TOP)]);
let port = overlay_def(&ws, TOP, tail(TOP, "u.clk_i", 0)).expect("the port");
assert_eq!(port.kind, SymbolKind::Port);
let param = overlay_def(&ws, TOP, tail(TOP, "u.W", 0)).expect("the parameter");
assert_eq!(param.kind, SymbolKind::Param);
// An internal net is not exported to any other file — the same rule a
// `.secret(w)` connection has always followed.
assert!(overlay_def(&ws, TOP, tail(TOP, "u.internal", 0)).is_none());
// An internal net is reached hierarchically and nowhere else: the tail
// resolves to `sub`'s own declaration of it...
let net = overlay_def(&ws, TOP, tail(TOP, "u.internal", 0)).expect("the internal net");
assert_eq!(net.kind, SymbolKind::Net);
// ...while the connection surface — what a `.internal(w)` connection and a
// connection list's completion read — still does not hold it.
assert!(ws.member("sub", "internal").is_empty());
assert_eq!(ws.member("sub", "clk_i").len(), 1, "a port is on both surfaces, once");
}
/// The spines a chain is **not** walked from, each still resolving whatever
@@ -1035,7 +1061,10 @@ fn a_hierarchical_path_crosses_a_file_boundary() {
const TB: &str = "module dut;\n core u_core ();\nendmodule\n\nmodule tb;\n dut dut_i ();\nendmodule\n\nmodule probe;\n initial y = tb.dut_i.u_core.sig;\nendmodule\n";
assert_eq!(
resolution_at(&sem(TB), tail(TB, "tb.dut_i.u_core.sig", 0)),
Resolution::ExternalCandidate { paths: vec!["core::sig".to_string()] }
Resolution::ExternalCandidate {
paths: vec!["core::sig".to_string()],
surface: Surface::Hierarchical,
}
);
let ws = index(&[("core.sv", CORE), ("tb.sv", TB)]);
let def = overlay_def(&ws, TB, tail(TB, "tb.dut_i.u_core.sig", 0)).expect("the leaf signal");
+10 -7
View File
@@ -14,8 +14,8 @@
use std::path::PathBuf;
use vlog_parser::parse_source;
use vlog_semantic::{
analyze, resolve_external, MemberSite, Resolution, Scope, ScopeId, Semantics, SymbolKind,
WorkspaceIndex,
analyze, resolve_external, MemberSite, Resolution, Scope, ScopeId, Semantics, Surface,
SymbolKind, WorkspaceIndex,
};
// ----------------------------------------------------------------------
@@ -202,7 +202,7 @@ endmodule
&[("p.hdr", "p", &[], "pkt_t"), ("p.hdr.addr", "p", &["hdr"], "pkt_t::hdr")];
for (needle, head, mids, expected_site) in cases {
let at = tail(src, needle);
let Resolution::ExternalCandidate { paths } = resolution_at(&s, at) else {
let Resolution::ExternalCandidate { paths, .. } = resolution_at(&s, at) else {
panic!("{needle} must be the workspace's business");
};
let member = needle.rsplit('.').next().expect("a tail");
@@ -211,7 +211,10 @@ endmodule
let mids: Vec<String> = mids.iter().map(|m| (*m).to_string()).collect();
assert_eq!(
s.member_site(scope_at(&s, at), head, &mids),
Some(MemberSite::Unit((*expected_site).to_string())),
Some(MemberSite::Unit {
path: (*expected_site).to_string(),
surface: Surface::Connection,
}),
"{needle}: the site is the path the resolution walks, minus the tail",
);
}
@@ -390,7 +393,7 @@ fn super_with_a_base_in_another_file_names_that_base_as_the_unit() {
let at = tail(src, "super.x");
assert_eq!(
s.member_site(scope_at(&s, at), "super", &[]),
Some(MemberSite::Unit("elsewhere_c".to_string())),
Some(MemberSite::Unit { path: "elsewhere_c".to_string(), surface: Surface::Connection }),
);
}
@@ -497,10 +500,10 @@ fn a_package_no_file_here_declares_is_the_workspaces_unit() {
let at = tail(src, "other_pkg::x");
assert_eq!(
s.unit_site(scope_at(&s, at), "other_pkg"),
Some(MemberSite::Unit("other_pkg".to_string())),
Some(MemberSite::Unit { path: "other_pkg".to_string(), surface: Surface::Connection }),
);
// Which is exactly the unit the resolution's own path names.
let Resolution::ExternalCandidate { paths } = resolution_at(&s, at) else {
let Resolution::ExternalCandidate { paths, .. } = resolution_at(&s, at) else {
panic!("the workspace's business");
};
assert_eq!(paths, vec!["other_pkg::x".to_string()]);
+386
View File
@@ -0,0 +1,386 @@
//! Package re-exports (IEEE 1800 §26.6), both halves: what the binder records
//! for an `export` line, and what the workspace index makes of it — the walk
//! that lets `a_pkg::x` find the `x` `b_pkg` declares.
//!
//! See `docs/features/package-reexports/README.md`.
use std::path::PathBuf;
use vlog_parser::parse_source_tolerant;
use vlog_semantic::{
analyze, resolve_external, Def, Definition, FileFacts, Resolution, Semantics, Surface,
SymbolKind, WorkspaceIndex,
};
fn semantics(src: &str) -> Semantics {
let (file, _) = parse_source_tolerant(src);
analyze(&file, src)
}
fn index(files: &[(&str, &str)]) -> WorkspaceIndex {
WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(*p), *s)))
}
/// The one reference spelled `name`, or a panic naming what was recorded.
fn only_reference<'a>(sem: &'a Semantics, name: &str) -> &'a vlog_semantic::Reference {
let mut found = sem.references().iter().filter(|r| r.name == name);
let first = found.next().unwrap_or_else(|| {
panic!("no reference to `{name}`: {:?}", sem.references().iter().map(|r| &r.name))
});
assert!(found.next().is_none(), "more than one reference to `{name}`");
first
}
/// The workspace declarations go-to-definition offers at `needle`.
fn external_defs(sem: &Semantics, ws: &WorkspaceIndex, src: &str, needle: &str) -> Vec<Def> {
let offset = src.find(needle).expect("needle is in the source") as u32;
match resolve_external(sem, ws).definition_of(sem, offset) {
Some(Definition::External(defs)) => defs.to_vec(),
_ => Vec::new(),
}
}
/// The names completion offers after `unit::`.
fn offered(ws: &WorkspaceIndex, unit: &str) -> Vec<String> {
ws.members_of_chain(unit).into_iter().map(|(name, _)| name.to_string()).collect()
}
// ----------------------------------------------------------------------
// 48.1 — the binding half
// ----------------------------------------------------------------------
/// Both halves of `export b_pkg::x;` are uses, each on its own bytes: the
/// package half is what a jump to `b_pkg` follows, and the item half is what
/// puts this very line in `x`'s reference set (and so in a rename's edit set).
#[test]
fn an_export_records_both_halves_on_exactly_their_own_bytes() {
let src = "package a_pkg;\n export b_pkg::x;\nendpackage\n";
let sem = semantics(src);
for name in ["b_pkg", "x"] {
let reference = only_reference(&sem, name);
assert_eq!(
&src[reference.name_span.as_range()],
name,
"the span of `{name}` covers other bytes"
);
}
assert_eq!(
only_reference(&sem, "x").resolution,
Resolution::ExternalCandidate {
paths: vec!["b_pkg::x".to_string()],
surface: Surface::Connection,
},
"the item is a member of the package it is taken from"
);
assert_eq!(
only_reference(&sem, "b_pkg").resolution,
Resolution::ExternalCandidate {
paths: vec!["b_pkg".to_string()],
surface: Surface::Connection,
},
"the package half is the package itself"
);
}
/// `export b_pkg::*;` has no item to name — the `*` is a wildcard, not an
/// identifier — so only the package half is recorded, exactly as
/// `import b_pkg::*;` records only the package half.
#[test]
fn a_wildcard_export_records_the_package_half_alone() {
let sem = semantics("package a_pkg;\n export b_pkg::*;\nendpackage\n");
assert_eq!(
sem.references().iter().map(|r| r.name.as_str()).collect::<Vec<_>>(),
["b_pkg"],
"the `*` is not a name"
);
}
/// `export *::*;` names nothing at all — neither half is an identifier.
#[test]
fn an_export_of_everything_records_no_reference() {
let sem = semantics("package a_pkg;\n import b_pkg::*;\n export *::*;\nendpackage\n");
assert_eq!(
sem.references().iter().map(|r| r.name.as_str()).collect::<Vec<_>>(),
["b_pkg"],
"only the `import` line names anything"
);
}
/// **The negative that defines a re-export.** `export b_pkg::x;` makes `x`
/// visible to whoever imports `a_pkg`; it does not make `x` visible *inside*
/// `a_pkg`. So a bare `x` written beside the export is not found and carries
/// no path to the workspace — until an `import` alongside it says otherwise,
/// which is the second half of the test.
#[test]
fn a_reexported_name_is_not_visible_bare_inside_the_exporting_package() {
let exported = "package a_pkg;\n export b_pkg::x;\n localparam Y = x;\nendpackage\n";
let sem = semantics(exported);
let uses: Vec<&Resolution> =
sem.references().iter().filter(|r| r.name == "x").map(|r| &r.resolution).collect();
assert_eq!(uses.len(), 2, "the export's item and the bare use");
assert!(
uses.contains(&&Resolution::NotFound),
"the bare `x` is not found and offers the workspace nothing: {uses:?}"
);
let imported =
"package a_pkg;\n import b_pkg::*;\n export b_pkg::x;\n localparam Y = x;\nendpackage\n";
let sem = semantics(imported);
assert!(
sem.references()
.iter()
.filter(|r| r.name == "x")
.any(|r| matches!(&r.resolution, Resolution::ExternalCandidate { paths, .. }
if paths.contains(&"b_pkg::*".to_string()))),
"an `import` beside the `export` is what brings the name in"
);
}
// ----------------------------------------------------------------------
// 48.2 — the resolution half
// ----------------------------------------------------------------------
/// The three-file shape: `b_pkg` declares, `a_pkg` re-exports one name, and a
/// third file reaches it two ways — `a_pkg::x` written out, and a bare `x`
/// under `import a_pkg::*`.
const B_PKG: &str =
"package b_pkg;\n localparam int x = 8;\n localparam int y = 9;\nendpackage\n";
#[test]
fn a_single_name_reexport_answers_for_the_package_that_declares_it() {
let sources = [
("a.sv", "package a_pkg;\n export b_pkg::x;\nendpackage\n"),
("b.sv", B_PKG),
("top.sv", "module top;\n import a_pkg::*;\n localparam W = x;\n localparam V = a_pkg::x;\nendmodule\n"),
];
let ws = index(&sources);
let sem = semantics(sources[2].1);
for needle in ["x;\n localparam V", "x;\nendmodule"] {
let defs = external_defs(&sem, &ws, sources[2].1, needle);
assert_eq!(defs.len(), 1, "{needle}: {defs:?}");
assert_eq!(ws.path(defs[0].file).expect("indexed"), PathBuf::from("b.sv"));
assert_eq!(defs[0].kind, SymbolKind::LocalParam);
assert_eq!(defs[0].lines.name, 2, "b_pkg's own declaration line");
}
assert_eq!(offered(&ws, "a_pkg"), ["x"], "the one name it re-exports, and not `y`");
}
/// `export b_pkg::*;` offers every member `b_pkg` exports, and answers for
/// each of them.
#[test]
fn a_wildcard_reexport_offers_every_member_of_the_package() {
let sources = [
("a.sv", "package a_pkg;\n export b_pkg::*;\nendpackage\n"),
("b.sv", B_PKG),
("top.sv", "module top;\n localparam W = a_pkg::y;\nendmodule\n"),
];
let ws = index(&sources);
let sem = semantics(sources[2].1);
assert_eq!(offered(&ws, "a_pkg"), ["x", "y"]);
let defs = external_defs(&sem, &ws, sources[2].1, "y;\nendmodule");
assert_eq!(defs.len(), 1, "{defs:?}");
assert_eq!(ws.path(defs[0].file).expect("indexed"), PathBuf::from("b.sv"));
}
/// `export *::*;` re-exports what the package **imports**, which is the one
/// reading of §26.6 a single file can settle — so `a_pkg::y` resolves through
/// an `import b_pkg::*` that the export makes visible onward.
#[test]
fn an_export_of_everything_reexports_what_the_package_imports() {
let sources = [
("a.sv", "package a_pkg;\n import b_pkg::*;\n export *::*;\nendpackage\n"),
("b.sv", B_PKG),
("top.sv", "module top;\n localparam W = a_pkg::y;\nendmodule\n"),
];
let ws = index(&sources);
let sem = semantics(sources[2].1);
assert_eq!(offered(&ws, "a_pkg"), ["x", "y"]);
assert_eq!(external_defs(&sem, &ws, sources[2].1, "y;\nendmodule").len(), 1);
// And a package that imports one name re-exports exactly that one.
let narrow = [
("a.sv", "package a_pkg;\n import b_pkg::x;\n export *::*;\nendpackage\n"),
("b.sv", B_PKG),
];
assert_eq!(offered(&index(&narrow), "a_pkg"), ["x"]);
// A package that imports nothing re-exports nothing, which is what
// `export *::*;` means there.
let empty = [("a.sv", "package a_pkg;\n export *::*;\nendpackage\n"), ("b.sv", B_PKG)];
assert!(offered(&index(&empty), "a_pkg").is_empty());
}
/// A chain of re-exports is followed to its end: `a_pkg` ← `mid_pkg` ←
/// `b_pkg`.
#[test]
fn a_chain_of_reexports_is_followed_transitively() {
let sources = [
("a.sv", "package a_pkg;\n export mid_pkg::*;\nendpackage\n"),
("b.sv", B_PKG),
("mid.sv", "package mid_pkg;\n export b_pkg::x;\nendpackage\n"),
("top.sv", "module top;\n localparam W = a_pkg::x;\nendmodule\n"),
];
let ws = index(&sources);
let sem = semantics(sources[3].1);
assert_eq!(offered(&ws, "a_pkg"), ["x"], "`y` is not re-exported by the middle package");
let defs = external_defs(&sem, &ws, sources[3].1, "x;\nendmodule");
assert_eq!(defs.len(), 1, "{defs:?}");
assert_eq!(ws.path(defs[0].file).expect("indexed"), PathBuf::from("b.sv"));
}
/// A cycle terminates and answers honestly: `a_pkg` re-exports `b_pkg::*`
/// while `b_pkg` re-exports `a_pkg::*`. Each package is asked once, so the
/// name that really is declared is found and the name that is not simply is
/// not.
#[test]
fn a_reexport_cycle_terminates() {
let sources = [
("a.sv", "package a_pkg;\n export b_pkg::*;\nendpackage\n"),
("b.sv", "package b_pkg;\n localparam int x = 8;\n export a_pkg::*;\nendpackage\n"),
(
"top.sv",
"module top;\n localparam W = a_pkg::x;\n localparam V = a_pkg::nope;\nendmodule\n",
),
];
let ws = index(&sources);
let sem = semantics(sources[2].1);
assert_eq!(offered(&ws, "a_pkg"), ["x"]);
assert_eq!(offered(&ws, "b_pkg"), ["x"], "and the other way round");
assert_eq!(external_defs(&sem, &ws, sources[2].1, "x;\n localparam V").len(), 1);
assert!(
external_defs(&sem, &ws, sources[2].1, "nope;\nendmodule").is_empty(),
"a name nobody declares stays unanswered rather than looping"
);
}
/// A re-export of a name the package does not declare resolves to nothing and
/// panics nowhere — the `export` line's item is simply an unanswered
/// reference, exactly like any other name the workspace does not hold.
#[test]
fn a_reexport_of_a_name_the_package_does_not_declare_is_unresolved() {
let sources = [
("a.sv", "package a_pkg;\n export b_pkg::missing;\nendpackage\n"),
("b.sv", B_PKG),
("top.sv", "module top;\n localparam W = a_pkg::missing;\nendmodule\n"),
];
let ws = index(&sources);
let sem = semantics(sources[0].1);
assert!(external_defs(&sem, &ws, sources[0].1, "missing;\nendpackage").is_empty());
assert!(offered(&ws, "a_pkg").is_empty(), "nothing is offered that nothing declares");
let top = semantics(sources[2].1);
assert!(external_defs(&top, &ws, sources[2].1, "missing;\nendmodule").is_empty());
}
/// A package's own declaration beats a name it also re-exports — the
/// first-hit-wins rule the `extends` chain follows, applied one hop further
/// out. Listed once, and from the nearer of the two.
#[test]
fn a_local_declaration_wins_over_a_reexported_name_of_the_same_spelling() {
let sources = [
("a.sv", "package a_pkg;\n localparam int x = 1;\n export b_pkg::*;\nendpackage\n"),
("b.sv", B_PKG),
("top.sv", "module top;\n localparam W = a_pkg::x;\nendmodule\n"),
];
let ws = index(&sources);
let sem = semantics(sources[2].1);
assert_eq!(offered(&ws, "a_pkg"), ["x", "y"], "one `x`, not two");
let defs = external_defs(&sem, &ws, sources[2].1, "x;\nendmodule");
assert_eq!(defs.len(), 1, "{defs:?}");
assert_eq!(
ws.path(defs[0].file).expect("indexed"),
PathBuf::from("a.sv"),
"the package's own declaration answers"
);
}
/// The reference posting a rename fans out from: every use of `b_pkg`'s `x`,
/// **including the `export` line's item half**, is filed under `x`'s own
/// declaration.
#[test]
fn the_export_line_and_every_use_through_it_post_against_the_declaration() {
let sources = [
("a.sv", "package a_pkg;\n export b_pkg::x;\nendpackage\n"),
("b.sv", B_PKG),
("top.sv", "module top;\n import a_pkg::*;\n localparam W = x;\nendmodule\n"),
];
let ws = index(&sources);
let x = ws.member("b_pkg", "x").first().expect("b_pkg declares x").clone();
let sites: Vec<PathBuf> = ws
.references_to(&x)
.iter()
.map(|site| ws.path(site.file).expect("indexed").to_path_buf())
.collect();
assert!(sites.contains(&PathBuf::from("a.sv")), "the export line itself: {sites:?}");
assert!(sites.contains(&PathBuf::from("top.sv")), "and the use through it: {sites:?}");
}
// ----------------------------------------------------------------------
// The record: the `RX` group and the format bump
// ----------------------------------------------------------------------
/// The new group round-trips, and a record written **without** it — which is
/// every record a `FACTS_FORMAT` 17 build wrote — decodes to nothing rather
/// than being read short by one group.
#[test]
fn the_reexport_group_round_trips_and_a_format_17_record_is_rejected() {
for src in [
"package a_pkg;\n import c_pkg::*;\n export b_pkg::x, b_pkg::*;\n export *::*;\nendpackage\n",
// ... and a record with an empty `RX` group, which is nearly every file.
"module plain;\n wire clk;\nendmodule\n",
] {
let facts = FileFacts::of(PathBuf::from("/w/r.sv"), src);
let line = facts.encode().expect("encodes");
let back = FileFacts::decode(&line).expect("decodes");
assert_eq!(back, facts, "every field, the re-exports included");
assert_eq!(back.encode(), Some(line.clone()), "and re-encodes byte for byte");
let fields: Vec<&str> = line.split('\t').collect();
let at = fields.iter().position(|field| *field == "RX").expect("RX tag");
let format_17 = [&fields[..at], &fields[at + 2 + 3 * facts_rx_len(&facts)..]]
.concat()
.join("\t");
assert!(
FileFacts::decode(&format_17).is_none(),
"a format-17 record decoded as a format-18 one: {format_17}"
);
}
}
/// How many `RX` entries a record holds, counted off its encoding — the test
/// above cuts exactly that many triples out.
fn facts_rx_len(facts: &FileFacts) -> usize {
let line = facts.encode().expect("encodes");
let fields: Vec<&str> = line.split('\t').collect();
let at = fields.iter().position(|field| *field == "RX").expect("RX tag");
fields[at + 1].parse().expect("a count")
}
/// An incremental update produces the very index a full build would — with
/// the re-export table included, which the fingerprint now names.
#[test]
fn an_update_and_a_build_agree_on_the_reexport_table() {
let a = "package a_pkg;\n export b_pkg::x;\nendpackage\n";
let b = B_PKG;
let built = index(&[("a.sv", a), ("b.sv", b)]);
let mut updated = index(&[("a.sv", "package a_pkg;\nendpackage\n"), ("b.sv", b)]);
assert!(!updated.fingerprint().contains("reexport a_pkg"), "nothing re-exported yet");
updated.update_file(PathBuf::from("a.sv"), a);
assert_eq!(updated.fingerprint(), built.fingerprint());
assert!(built.fingerprint().contains("reexport a_pkg <- b_pkg::x"));
// And removing the export again leaves the table as empty as it started.
updated.update_file(PathBuf::from("a.sv"), "package a_pkg;\nendpackage\n");
assert!(!updated.fingerprint().contains("reexport a_pkg"));
assert!(updated.members_of_chain("a_pkg").is_empty());
}
+21 -6
View File
@@ -1,7 +1,7 @@
//! What `analyze` binds, what it resolves, and what it refuses to guess.
use vlog_parser::{parse_source, parse_source_tolerant};
use vlog_semantic::{analyze, Resolution, Semantics, SymbolId, SymbolKind};
use vlog_semantic::{analyze, Resolution, Semantics, Surface, SymbolId, SymbolKind};
fn sem(src: &str) -> Semantics {
let file = parse_source(src).expect("fixture must parse");
@@ -310,25 +310,37 @@ endmodule
let some = s.reference_at(nth(src, "SOMETHING", 0)).expect("the use");
assert_eq!(
some.resolution,
Resolution::ExternalCandidate { paths: vec!["other_pkg::*".into()] }
Resolution::ExternalCandidate {
paths: vec!["other_pkg::*".into()],
surface: Surface::Connection,
}
);
let thing = s.reference_at(nth(src, "named_pkg::THING", 0) + 11).expect("the imported name");
assert_eq!(
thing.resolution,
Resolution::ExternalCandidate { paths: vec!["named_pkg::THING".into()] }
Resolution::ExternalCandidate {
paths: vec!["named_pkg::THING".into()],
surface: Surface::Connection,
}
);
let scoped = s.reference_at(nth(src, "elsewhere_pkg::VALUE", 0) + 15).expect("the tail");
assert_eq!(
scoped.resolution,
Resolution::ExternalCandidate { paths: vec!["elsewhere_pkg::VALUE".into()] }
Resolution::ExternalCandidate {
paths: vec!["elsewhere_pkg::VALUE".into()],
surface: Surface::Connection,
}
);
// An instantiation of a module this file does not declare, and its ports.
let module = s.reference_at(nth(src, "missing_mod", 0)).expect("the module name");
assert_eq!(
module.resolution,
Resolution::ExternalCandidate { paths: vec!["missing_mod".into()] }
Resolution::ExternalCandidate {
paths: vec!["missing_mod".into()],
surface: Surface::Connection,
}
);
let port = s.reference_at(nth(src, ".p(w)", 0) + 1).expect("the port name");
assert!(port.is_external_candidate());
@@ -798,7 +810,10 @@ endmodule
assert_eq!(item.name, "t");
assert_eq!(
item.resolution,
Resolution::ExternalCandidate { paths: vec!["pkg::t".into()] },
Resolution::ExternalCandidate {
paths: vec!["pkg::t".into()],
surface: Surface::Connection,
},
"the same candidate `pkg::t x;` would record"
);
}
+88 -11
View File
@@ -6,7 +6,7 @@ use vlog_parser::defines::{collect_defines, DefineTable};
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize};
use vlog_semantic::{
analyze, resolve_external, Def, Definition, ExternalTarget, FileFacts, FileId, Resolution,
Semantics, SymbolKind, Utf16Pos, WorkspaceIndex,
Semantics, Surface, SymbolKind, Utf16Pos, WorkspaceIndex,
};
/// Build an index from `(path, source)` literals, as a server would from disk.
@@ -529,7 +529,10 @@ fn an_unqualified_type_miss_carries_its_own_name_to_the_unit_table() {
assert_eq!(
resolution(&sem, sources[1].1, "bus_if bus"),
Resolution::ExternalCandidate { paths: vec!["bus_if".to_string()] }
Resolution::ExternalCandidate {
paths: vec!["bus_if".to_string()],
surface: Surface::Connection,
}
);
let defs = external_defs(&sem, &ws, sources[1].1, "bus_if bus");
assert_eq!(defs.len(), 1, "{defs:?}");
@@ -600,7 +603,10 @@ fn a_direction_less_first_ansi_port_binds_its_interface_type_cross_file() {
let sem = semantics(src);
assert_eq!(
resolution(&sem, src, needle),
Resolution::ExternalCandidate { paths: vec!["bus_if".to_string()] },
Resolution::ExternalCandidate {
paths: vec!["bus_if".to_string()],
surface: Surface::Connection,
},
"{needle}"
);
let defs = external_defs(&sem, &ws, src, needle);
@@ -771,7 +777,10 @@ fn an_import_that_can_supply_the_name_still_wins_over_a_same_named_unit() {
assert_eq!(
resolution(&sem, sources[2].1, "state_t s"),
Resolution::ExternalCandidate { paths: vec!["tdp::*".to_string(), "state_t".to_string()] }
Resolution::ExternalCandidate {
paths: vec!["tdp::*".to_string(), "state_t".to_string()],
surface: Surface::Connection,
}
);
let defs = external_defs(&sem, &ws, sources[2].1, "state_t s");
assert_eq!(defs.len(), 1, "{defs:?}");
@@ -896,7 +905,7 @@ fn the_corpus_index_finishes_most_external_references() {
let counts = ws.counts();
println!(
"workspace index: {} files in {:.2}s — {} modules, {} packages, {} file-scope typedefs, \
{} classes, {} exported members, {} define directives",
{} classes, {} exported members (+{} hierarchical-only), {} define directives",
counts.files,
build.as_secs_f64(),
counts.modules,
@@ -904,6 +913,7 @@ fn the_corpus_index_finishes_most_external_references() {
counts.typedefs,
counts.classes,
counts.members,
counts.hierarchical_members,
counts.defines,
);
@@ -1004,7 +1014,7 @@ impl Tally {
ExternalTarget::StillUnresolved => {
self.unresolved += 1;
let paths = match &reference.resolution {
Resolution::ExternalCandidate { paths } => paths.join(" | "),
Resolution::ExternalCandidate { paths, .. } => paths.join(" | "),
_ => String::new(),
};
let entry = self.misses.entry(paths).or_insert((0, reference.name.clone()));
@@ -1064,6 +1074,72 @@ impl Tally {
}
}
/// **The §49 census delta, measured rather than asserted.** Over the whole
/// corpus, how many references the hierarchical surface is the *only* reason
/// the workspace can answer: a candidate carrying [`Surface::Hierarchical`]
/// that lands on a record the *hierarchical-only* table holds. Membership of
/// that table is the exact test — a hierarchical candidate landing on a port,
/// a parameter or an **interface's** signal is not part of the delta, because
/// those are on the connection surface and resolved before §49 too, through
/// the connection table the hierarchical read consults first.
///
/// The number is printed, not pinned to a constant: the corpus moves, and a
/// hard number here would be a test that fails for the wrong reason. What is
/// pinned is the direction — the hierarchical surface must actually be
/// answering something, and every answer it gives must be one of the three
/// kinds that live on it.
#[test]
fn the_hierarchical_surface_is_what_answers_a_measurable_slice_of_the_corpus() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !root.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let mut paths = Vec::new();
collect(&root, &mut paths);
paths.sort();
let sources: Vec<(PathBuf, String)> = paths
.iter()
.filter_map(|p| std::fs::read_to_string(p).ok().map(|s| (p.clone(), s)))
.collect();
let ws = WorkspaceIndex::build(sources.iter().map(|(p, s)| (p.clone(), s.as_str())));
let (mut candidates, mut answered, mut only_hierarchical) = (0usize, 0usize, 0usize);
for (_, src) in &sources {
let (tree, _) = parse_source_tolerant(src);
let sem = analyze(&tree, src);
let overlay = resolve_external(&sem, &ws);
for (i, reference) in sem.references().iter().enumerate() {
if !matches!(
reference.resolution,
Resolution::ExternalCandidate { surface: Surface::Hierarchical, .. }
) {
continue;
}
candidates += 1;
let Some(ExternalTarget::Resolved(def)) =
overlay.get(vlog_semantic::ReferenceId(i as u32))
else {
continue;
};
answered += 1;
let hierarchical_only = ws
.hierarchical_declarations(&reference.name)
.any(|(_, d)| d.file == def.file && d.name_span == def.name_span);
only_hierarchical += usize::from(hierarchical_only);
}
}
println!(
"hierarchical tails: {candidates} candidates, {answered} answered, \
{only_hierarchical} of them only because of the hierarchical surface"
);
assert!(candidates > 0, "the corpus does write hierarchical paths");
assert!(
only_hierarchical > 0,
"the hierarchical surface answers references the connection surface could not"
);
}
fn collect(dir: &std::path::Path, out: &mut Vec<PathBuf>) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
@@ -1936,8 +2012,8 @@ fn a_format_3_record_with_two_declarations_is_rejected_not_misread() {
/// this format wrote back into what `FACTS_FORMAT` 3 wrote for the same file —
/// remove, from every one of `units` unit-decls and `members` member-decls, the
/// client positions added in format 5, the `decl_span` added in format 5, the
/// declared type name added in format 7, and the two trailing (`name_line`,
/// `detail_line`) fields added in format 4.
/// surface letter added in format 19, the declared type name added in format 7,
/// and the two trailing (`name_line`, `detail_line`) fields added in format 4.
/// Assumes `D0` (no `` `define``s), which every fixture here satisfies, so the
/// `U` tag's field index is fixed and decl positions can be computed directly
/// rather than parsed.
@@ -1946,8 +2022,8 @@ fn strip_every_decls_line_fields(encoded: &str, units: usize, members: usize) ->
let units_at = fields.iter().position(|f| *f == "U").expect("a U tag");
assert_eq!(fields[units_at + 1], units.to_string(), "premise: unit count");
// A member's decl = name, kind, name_span×2, decl_span×2, detail_span×2,
// line×2, type_name — 11 fields. A unit's is that plus its two client
// ranges, four numbers each — 19.
// line×2, type_name, surface — 12 fields. A unit's is that plus its two
// client ranges, four numbers each — 20.
let members_at = units_at + 2 + units * UNIT_DECL_FIELDS;
assert_eq!(fields[members_at], "M", "premise: members tag follows the units");
assert_eq!(fields[members_at + 1], members.to_string(), "premise: member count");
@@ -1968,6 +2044,7 @@ fn strip_every_decls_line_fields(encoded: &str, units: usize, members: usize) ->
if is_unit {
fields.drain(start + MEMBER_DECL_FIELDS..start + UNIT_DECL_FIELDS);
}
fields.drain(start + 11..start + 12);
fields.drain(start + 10..start + 11);
fields.drain(start + 8..start + 10);
fields.drain(start + 4..start + 6);
@@ -1976,7 +2053,7 @@ fn strip_every_decls_line_fields(encoded: &str, units: usize, members: usize) ->
}
/// Fields one member declaration occupies in a record this format writes.
const MEMBER_DECL_FIELDS: usize = 11;
const MEMBER_DECL_FIELDS: usize = 12;
/// The same for a unit, which also carries its two client ranges.
const UNIT_DECL_FIELDS: usize = MEMBER_DECL_FIELDS + 8;
+16 -16
View File
@@ -1,23 +1,23 @@
# Verilog/SystemVerilog coverage gaps — ranked (2026-09-01)
**Reading this report today (2026-09-04).** The survey below is a historical
**Reading this report today (2026-09-05).** The survey below is a historical
v0.21.0 measurement with later amendments, not a fresh list of current failures.
For the current implementation and outstanding contracts, use
[repository-analysis.md](repository-analysis.md) and [topo.md](topo.md).
Since the original survey, interface/modport and struct-member semantics,
statement/class fences, header/list recovery, rule documentation, and three
lint expansion waves have landed. The old probes were not re-run as part of
the documentation audit; their historical counts are retained.
Use [repository-analysis.md](repository-analysis.md) and [topo.md](topo.md) for
current implementation status. Original probe counts remain historical.
Current follow-ups to the latest addendum: v0.40.0 recovers bare item-level
`begin` blocks as `ItemKind::GenBlock` **in tolerant mode**, so lint rules see
their contents; strict formatting still refuses them. It also improves recovery
for unclosed overrides that would consume the following instance. The
post-v0.41.0 `parser-skips` commit accepts rival conditional unit headers as
verbatim units and preserves net delays before or after the type. Its QA is
accepted; release v0.42.0 is pending. Comments immediately before a net-delay
`#` still cause a formatter verification refusal. External waiver files remain
planned, not implemented.
Through v0.44.0, external waivers, rival conditional headers, net-delay
positions and comment slots, inline aggregate overrides, statement/class
fences, header recovery, and the three lint-expansion waves have shipped.
The prior audit's atomic-write, project lint-selection and directory-cycle
findings are also fixed. Bare item-level `begin` blocks are recovered for
lint/editor consumers; strict formatting still refuses them.
At committed `9ef1058`, type-name spans replace `vlog_semantic/src/scan.rs`,
and package re-exports resolve through shared member edges (facts codec 18).
Both are accepted for the next release. The active hierarchical-tail work
proposes codec 19; QA is pending, and handshake 23 remains open. DPI-export
name binding is a separate remaining gap (handshake 31), and generate-block
hierarchy and cross-file macro expansion remain outside these fixes.
What lucisv 0.21.0 does not yet handle, ranked by severity, from two
independent sweeps crossed against each other:
@@ -0,0 +1,359 @@
# atomic write coordination
## Goal
Two writers of one file, inside one lucisv process, must not fight over the
temp file the atomic write goes through (TODO §41, `docs/repository-analysis.md`
finding 1, topo handshake §2.9-26). `atomic::temp_path` named its temp from the
canonical target and the process id, so every thread of one process derived the
*same* name for one target: the audit's probe — two threads writing 1 MiB each
to one file, 100 rounds — produced 100 write errors in 200 calls (no mixed
bytes, because `fs::write` truncated and rewrote the whole buffer, but half the
writes failed outright and each failure removed the other writer's temp). Two
ways in existed: the CLI's `dedup` folded `.` and `..` lexically but left
symlinks unresolved, so `b.sv -> a.sv` reached two rayon workers as two files;
and any two threads of one process asked to write one path.
Both are closed here. Every writer now gets a temp name no other writer in the
process will be given (a per-process `AtomicU64` beside the pid) and creates it
with `create_new`, so the name is owned, never shared. `dedup` keys on the
canonical path when the file exists, so two spellings of one file are one job —
while the path lucisv *reports* stays the first spelling the user gave. And the
target's mode goes on the temp before its bytes do, so a 0600 file's replacement
never holds the file's contents at a wider mode.
## Assumptions
- **A rename is atomic within a directory**, on every filesystem lucisv ships
to. That was already this module's premise; nothing here weakens it.
- **Two *processes* writing one target are not coordinated, deliberately.**
Both renames are atomic and the later one wins; the loser's bytes are
discarded whole, never merged. Both processes formatted the same input and
`format` is idempotent, so whichever rename lands last leaves the file
complete and correctly formatted. A lock file would buy nothing and would be
one more thing left behind by a `^C`. This is stated in the `atomic.rs`
module doc, which is where a reader will look for it.
- **A temp-name collision means a leftover, not a race.** A name is handed out
once per process, so `AlreadyExists` can only mean a temp from an *earlier*
process that died mid-write and whose pid this process now carries. The write
retries with the next counter value, at most `TEMP_ATTEMPTS = 32` times; 32
stale temps for one file in one directory is a directory to clean by hand,
not a race to keep retrying through.
- **`fs::canonicalize` is the identity of a file that exists.** Two names that
canonicalize alike are one file (hardlinks aside — two hardlinks to one inode
have two distinct canonical paths and stay two jobs, which is what a user who
made hardlinks asked for). A path with no file behind it has no canonical
form, and the old lexical fold answers for it.
- **A chmod does not revoke an already-open descriptor.** That is why, when
there is a target, the temp is *created* 0600 on unix rather than created at
the umask's mode and narrowed afterwards: narrowing later would leave a
window in which someone could open the empty temp and then read the bytes
through the descriptor they kept. With no target there is no earlier mode to
honour and the umask decides, exactly as `fs::write` would.
- The dedup key is computed on the main thread, before any worker exists, so
the extra `canonicalize` per input is one `realpath` per file at startup and
not per write.
## Handshakes
- **`lucisv_core::atomic::write_atomic` — unchanged signature, unchanged
contract**, plus one promise it did not make before: two threads of one
process writing one target both succeed, and the target ends up holding one
writer's whole buffer. Callers (`lucisv/src/main.rs`, `lucisv/src/lint.rs`,
`lucisv_core/src/cache.rs`) need no change.
- The two behaviours other tests already pin are kept exactly: a read-only
target is refused with `PermissionDenied`, and a symlinked target is
resolved so the link is not replaced.
- The temp file's *name* changed shape: `.{name}.{pid}.{n}.lucisv-tmp`. Any
tool that matched the old `.{name}.{pid}.lucisv-tmp` (nothing in this
repository does; the tests match on the `.lucisv-tmp` suffix) must match
the suffix instead.
- A file created where there was no target still takes the umask's mode. The
0600 creation applies only when a target's mode is about to be copied on.
- **`lucisv::dedup` — same signature, same output order, same reported paths.**
It only folds *more* than it used to: two spellings that reach one file are
now one job. `absolute` stays the lexical fold and is now reached only for
paths that do not exist; its doc comment says so.
- Nothing is requested of another module.
## Status / TODO
- [x] 41.1 exclusive unique temps (per-process `AtomicU64` + `create_new`,
bounded retry), mode before bytes
- [x] 41.2 dedup by canonical identity, reported path unchanged
- [x] Last-writer semantics for two processes stated in the `atomic.rs` module
doc and above; no lock built
- [x] Tests: the audit's probe (2 threads × 100 rounds × 1 MiB, 0 write
errors, one whole buffer per round); temp-name uniqueness across
threads; the 0600 window, twice (a unit test on the mode step, and a
live poll of the directory during a real 8 MiB write); `dedup` with a
symlink alias in both spelling orders, with a `..` detour, and with
missing files; a CLI test where `dir/b.sv -> dir/a.sv` is formatted and
reported once
- [x] Gates (guarded): fmt, clippy, workspace tests, corpus, write-path
byte-identity
- [ ] QA (see the brief in TODO §41)
## Docs to apply at merge (lead)
- `docs/topo.md` §2.9-26 (same-target atomic writers) is closed by this lane:
the temp name carries a per-process counter and is created `O_EXCL`, and the
CLI dedups by canonical identity so one file cannot reach two workers.
Suggested strike-through note: *"closed by §41 (0.43.0): unique `O_EXCL`
temps, dedup on `fs::canonicalize`; two *processes* remain last-writer-wins
by design, stated in `atomic.rs`."*
- `docs/repository-analysis.md` finding 1: annotate **fixed by §41** — the
probe now runs as `atomic::tests::two_threads_writing_one_target_never_collide`
and reports 0 write errors in 200 calls; the symlink alias closes as
`cli::a_symlink_and_its_target_are_one_file`.
- `README.md` needs no change: no user-visible behaviour moved. The only
externally observable difference is the temp file's name shape,
`.{name}.{pid}.{n}.lucisv-tmp`, which the README does not document.
## Work log
**2026-09-05 — dev (Opus 5).** TODO §41 implemented in full.
Files touched, all inside the plan's expected set:
- `crates/lucisv_core/src/atomic.rs` — the write path.
- `crates/lucisv/src/main.rs` — `dedup`/`identity`/`absolute` and their tests.
- `crates/lucisv/tests/cli.rs` — the symlink-alias end-to-end test.
- `docs/features/atomic-write-coordination/README.md` — this file.
- `TODO.md` — §41's own checkboxes (the QA line left alone).
Nothing outside that set was touched.
**41.1.** `temp_path` now stamps the name with a per-process `AtomicU64`
counter as well as the pid: `.{name}.{pid}.{n}.lucisv-tmp`. `create_temp`
opens it with `OpenOptions::new().write(true).create_new(true)`, so a name
that somehow exists is `AlreadyExists` and the next counter value is tried,
up to `TEMP_ATTEMPTS = 32`, after which the write fails with a message naming
the target and the bound (reasoning for 32 in Assumptions). `write_atomic`
now stats the target once, at the top, and passes the `Option<Permissions>`
down: the read-only refusal, the decision to create the temp 0600, and the
mode copy all read that one stat instead of three.
`fill_temp` puts the mode on before the bytes on unix (`File::set_permissions`
through the handle opened before the chmod, so a mode without an owner-write
bit does not stop the write); on non-unix it keeps today's order, because
`set_permissions` there takes a path and there is nothing to gain from
reordering. The write itself is `write_all` on the owned handle rather than
`fs::write`, which is what makes both the exclusive create and the early chmod
possible.
**Deviation from the plan, deliberate.** The plan asked only that the mode be
copied before the bytes. Writing the window test showed that was not enough:
the temp is *created* at the umask's mode, so for one instant an empty
world-readable file exists at a name anyone can open — and a chmod does not
revoke a descriptor already opened through it, so an observer holding that
descriptor would then read the private file's contents as they were written.
The temp is therefore created with `mode(0o600)` on unix *when there is a
target whose mode it is about to take*; with no target it is created at the
umask's mode, so a brand-new file's permissions are exactly what they were
before this change. This is strictly narrower than the plan's ask, not wider.
The first run of `a_temp_seen_mid_write_is_never_world_readable` caught the
gap (observed mode 0644 on a temp for a 0600 target); it passes now.
**41.2.** `dedup` keys on `identity(cwd, path)`: `fs::canonicalize(path)` when
it answers, else the old `absolute(cwd, path)` lexical fold. The reported path
is untouched — `dedup` still keeps the *first* spelling of each file and its
order. `absolute`'s doc comment now says it is the fold for paths that do not
exist rather than a deliberate refusal to resolve symlinks.
**Tests (6 new, all guarded).**
- `atomic::tests::two_threads_writing_one_target_never_collide` — the audit's
probe: two writers and this thread meet at a pair of barriers each round, so
the target is inspected between rounds with nobody mid-write. 100 rounds,
1 MiB per writer, distinct buffers: 0 write errors, and every round the file
holds exactly one writer's whole buffer with no temp left behind.
- `atomic::tests::every_thread_gets_its_own_temp_name` — 4 threads × 200 names
for one target, all 800 distinct.
- `atomic::tests::the_temp_takes_the_targets_mode_before_any_bytes` — the
unit-testable step: the temp is 0600 the moment it exists, `copy_mode` puts
the target's mode on while `len() == 0`, and `fill_temp` still writes
through the handle afterwards.
- `atomic::tests::a_temp_seen_mid_write_is_never_world_readable` — the same
window from outside, polling the directory during a real 8 MiB
`write_atomic`. It asserts about what it sees and never about *seeing* it,
so a scheduler that hides the window cannot make it flaky.
- `lucisv::tests::dedup_folds_a_symlink_onto_the_file_it_points_at` — the
alias in both spelling orders (the first spelling is the one kept), a `..`
detour through an existing directory, and missing files falling back to the
lexical key (two different missing files stay two).
- `cli::a_symlink_and_its_target_are_one_file` — `dir/b.sv -> dir/a.sv`
through the real binary: `--check` prints exactly one `would reformat:` line
and it names `a.sv`; the format run says "1 file reformatted"; the link is
still a link afterwards.
**Both new tests were checked for teeth** by temporarily reverting the fix in
the working tree and restoring it immediately: without the counter the probe
reports *exactly* "100 write errors in 200 calls" — the audit's number, to the
call — and with lexical dedup the CLI test sees two `would reformat:` lines,
for `a.sv` and `b.sv`.
**Gates, all through `tools/guard.sh` (no guard kill anywhere).**
- `cargo fmt -p lucisv_core -p lucisv` clean.
- `cargo clippy --all-targets` clean, zero warnings. Two of my own drew
warnings on the way (`cloned_ref_to_slice_refs` in the dedup test,
`byte_char_slices` in the probe) and were fixed rather than allowed.
- `tools/guard.sh -- cargo test --workspace`: **3 771 passed, 0 failed**
(baseline 3 765 + the 6 above).
- `tools/guard.sh -- tools/corpus_check.sh`: **814/820 (99.3 %)**, the same
six failures, `verification-error: none`, `crash: none`.
- Write-path byte-identity: 300 corpus files copied to a scratch directory
(one of them chmod 0600) and formatted in place — 292 reformatted, 4
unchanged, 4 pre-existing parse failures; a second run reports all 296
unchanged (idempotent); the 0600 file is still 0600; no `.lucisv-tmp` left
behind. Every one of the 296 files' in-place bytes is byte-identical to the
same file formatted through stdin, which never touches `write_atomic` —
so the new write path delivers exactly the formatter's bytes.
- Peak RSS of the probe test, `/usr/bin/time -l` around the single test under
the guard: **36 995 072 B (35.3 MiB)** max resident, 0.38 s wall. The two
1 MiB buffers and the read-back are the only allocations the test adds.
Nothing is unfinished. The one judgement call a reviewer may want to weigh is
the 0600 creation described under "Deviation" above.
## QA log
**2026-09-05 — QA (Sonnet 5).** Verified against the §41 QA brief. All
experiments ran on copies under the scratchpad or on a standalone scratch
crate path-depending on `lucisv_core`; nothing in `corpus/` or
`/Users/guoliangchen/repo/opentitan` was written to. Every probe and gate ran
through `tools/guard.sh` (no guard kill anywhere). Two temporary `#[test]`
functions were added to poke at private functions (`create_temp`/`copy_mode`
in `atomic.rs`, `identity`/`dedup` symlink cases in `main.rs`), run, and then
removed — `git diff` on both files verified byte-identical to the dev's diff
before and after.
1. **Multithread probe, 4 and 8 threads** (standalone scratch binary linking
`lucisv_core`, `/usr/bin/time -l`, guarded). 4 threads × 100 rounds: 0
write errors in 400 calls, 0 bad rounds, 0 leftover temps, peak RSS
8 749 056 B (8.3 MiB). 8 threads × 100 rounds: 0 write errors in 800
calls, 0 bad rounds, 0 leftover temps, peak RSS 13 107 200 B (12.5 MiB).
Matches the dev's 2-thread number scaled up; no error rate creeps back in
with more contention.
2. **The 0600 window.** Black-box directory polling (mirroring the dev's own
`a_temp_seen_mid_write_is_never_world_readable`, generalized): a 0600
target under continuous 8 MiB rewrites for 3s — 88 053 samples, widest
temp mode ever seen `0600`, final mode `0600`. A 0644 target: widest seen
`0644` (never wider), final `0644`. A 0755 target: widest seen `0755`,
final `0755`. Brand-new target vs. a plain `fs::write` in the same
directory: both land at `0644` under umask `022` — match. The "0600 at
creation, then widened by the rename" half of the inverse case is not
observable black-box (`copy_mode` runs before `write_all` with no yield
point, so the 0600 instant is sub-microsecond) — confirmed instead with a
temporary source-level test calling `create_temp`/`copy_mode` directly for
0644 and 0755 targets: the temp is born 0600 in both cases, then
`copy_mode` widens it to the target's real mode before any byte is
written. Removed after passing.
3. **Retry bound.** Predicted the temp names from the diff
(`.{name}.{pid}.{n}.lucisv-tmp`, counter from 0, one static per process)
and pre-created all 32 (`n=0..31`) in a fresh process before its first
`write_atomic` call: the write fails with `"no free temp file name beside
.../a.sv after 32 tries"`, naming the target and the bound, and leaves
exactly the 32 pre-created temps (no new one added). Pre-creating 31
(`n=0..30`, one slot free) in a fresh process: the write succeeds
(consuming `n=31`), the target holds the new bytes, and exactly 31 stale
temps remain — no extra temp left by the successful write itself.
4. **Symlink and identity.** Temporary unit tests against `identity`/`dedup`
covered: `dir2 -> dir1` containing the file (both spelling orders, first
spelling kept and reported); an absolute vs. relative spelling through
the dir symlink; a `../` detour; a dangling symlink (canonicalize fails,
falls back to the lexical key — two lexical spellings of *one* dangling
link still fold, two *different* dangling links stay two); a symlink to a
file outside the pair being compared (folds onto the real file by
canonical identity regardless of "was it walked"). All passed; removed
after. Then the mandated real-binary run (`cargo build --release -p
lucisv`, `dir/b.sv -> dir/a.sv`): `--check` printed exactly one `would
reformat:` line naming `a.sv`, exit 1; `--diff` printed exactly one diff
block naming `a.sv`, exit 1; a real format run reported "1 file
reformatted", exit 0, both `a.sv` and (through the link) `b.sv` read back
the formatted text, and `b.sv` was still a symlink pointing at `a.sv`
afterwards (`readlink` unchanged); a second `--check` reported "1 file
left unchanged, 1 file from cache", exit 0. Also checked by hand: a
dangling symlink inside a walked directory errors
`"...dead.sv: No such file or directory"` (the user's own spelling, not a
resolved one) without a panic, exit 2; a symlink to a file *outside* the
walked directory formats correctly through the link, and passing both the
link and the real outside file explicitly on the command line dedups to
one job, one report line, one write — verified with `--check` and with a
real write (outside file correctly formatted, link left intact).
5. **Two processes.** Two `lucisv format` processes launched at the same
moment (both under `tools/guard.sh`, backgrounded, `wait`ed) against one
shared scratch copy of `corpus/common_cells/src` (100 files): both exited
0. The resulting tree is byte-identical (`diff -rq`) to a fresh copy
formatted by a single process. No `.lucisv-tmp` anywhere afterward. A
follow-up `--check` on the two-process tree reports "100 files left
unchanged, 100 files from cache", exit 0 — no truncation, no corruption,
consistent with the documented last-writer-wins semantics (both writers
were formatting the same input to the same idempotent output, so there
was nothing for a "loser" to lose).
6. **Refusals and mid-run failures.** A read-only (0444) target: refused with
`PermissionDenied` ("... is read-only"), file content and mode (444)
untouched, no temp created. A target in a read-only (0555) directory:
refused with a plain OS `Permission denied (os error 13)` (temp creation
itself fails — expected, since `write_atomic`'s own read-only check is
for the *target's* mode, not the directory's), file untouched. Directory
deleted mid-write: 200 rounds of racing `fs::remove_dir_all` against a
concurrent 8 MiB `write_atomic` in a scratch binary with
`catch_unwind` around the writer thread — 139 writes completed before the
delete won the race, 61 got a plain `io::Error` (`No such file or
directory` / `Invalid argument`), **0 panics**. No corruption claim
applies once the directory itself is gone.
7. **Behaviour parity.** 300 files copied from `corpus/ibex` (path structure
preserved) into a scratch tree. `--stdout` of every file saved first (4
pre-existing parse failures unrelated to this feature — a `.tpl.sv`
template, a Yosys-primitive `.v`, and two vendor files with unsupported
constructs, all already known corpus failures). In-place format of the
300: "283 files reformatted, 13 files left unchanged, 4 files failed to
format" — same 4 files, same error text, byte-identical to the `--stdout`
errors. All 296 successfully-formatted files are byte-identical between
the in-place result and `--stdout` of the original (0 mismatches). The 4
failed files are byte-unchanged from their originals (hard invariant #1
held). A follow-up `--check` on the tree: "296 files left unchanged, 296
files from cache, 4 files failed to format" — idempotent.
**Gates (all guarded, no kill).**
- `cargo clippy --all-targets`: clean, 0 warnings.
- `tools/guard.sh -- cargo test --workspace`: **3 771 passed, 0 failed, 44
ignored** — matches the dev's reported 3 771 exactly.
- `tools/guard.sh -- tools/corpus_check.sh`: **814/820 (99.3%)**, the same
six failures (5 parse-error + 1 lex-error), `verification-error: none`,
`crash: none` — matches the dev's reported number exactly.
**Findings.** None at any severity. No corruption, no panic, no leftover
temp, no mode widening, no dedup miss, no parity break, and no gate
regression across any of the seven attacks.
**Repo hygiene.** `git status --porcelain` on the four `corpus/*` checkouts
shows only a pre-existing untracked `.vfmt-corpus-rev` marker (identical
41-byte file, mtime 2026-08-19, present in all four — predates this session,
not written by anything here); no tracked file in any corpus checkout is
modified. In the main tree, `git diff` on `crates/lucisv_core/src/atomic.rs`,
`crates/lucisv/src/main.rs` and `crates/lucisv/tests/cli.rs` is byte-identical
to the dev's diff at the start of this QA pass (verified before and after
every temporary test was added/removed). All scratch experiments and the
standalone `probe` crate lived under the scratchpad and have been removed.
**Verdict: PASS.** No rework needed.
## Review
**2026-09-05 — lead.** Accepted; ships in 0.43.0. The fix is the plan's plus
one tightening the plan should have asked for: a temp created at the umask's
mode and chmod'ed later would leave an empty world-readable file at a
guessable name for an instant, and a descriptor opened through it would
survive the chmod — so creating the temp at 0600 when a target exists, then
widening through the open handle before the bytes, is the correct order and
the dev's deviation is accepted as written. The retry bound of 32 is the
right shape (a name is issued once per process, so only a dead earlier
process with the same pid can collide, and 32 of those is a directory to
clean, not a race). QA's attack was thorough — 4 and 8 threads, the window
polled from outside, the bound hit exactly, two real processes over one
tree, a directory deleted mid-write with 0 panics — and found nothing. Two
processes on one target stay last-writer-wins by design; the formatter's
idempotence is what makes that safe, and the module doc says so.
+4
View File
@@ -124,6 +124,10 @@ where marked; no existing field changed meaning.
edited (`a_hierarchical_tail_that_resolves_is_renamed_with_its_declaration`
is the pin). Not this round's to fix — the warning is exactly the heads-up
§2.9-20 asked for — but it is a real gap worth a row of its own.
**Closed 2026-09-05 by TODO §49 / `docs/features/hierarchical-tail`:** a
module's hierarchical surface makes the cross-file tail resolve, so the
edit lands in both files and the warning is retired for a tail that
resolved.
3. **`docs/topo.md` rows 20, 21 and 22 are closed** and want striking by the
lead (this round does not edit `topo.md`).
+565
View File
@@ -0,0 +1,565 @@
# didOpen cost
## Goal
Take 3 (`docs/performance_take3.md` §8.4) measured that a `didOpen` of a file
the index already covers delays the **next** request by 21–51 ms, scaling with
file size, where take 2 measured a flat 2–4 ms. The server is a synchronous
loop, so whatever the open does before returning is what the next request waits
behind. TODO.md §46 asked for the cost to be measured, broken down, and for the
largest item in it — not all of them — to be fixed, with the open returning to
the loop fast enough that the request behind it is not left waiting and is
still answered from up-to-date state.
The finding turned out to understate the problem by an order of magnitude. At
the whole-workspace scope, opening opentitan's 42 000-line
`pinmux_reg_top.sv` delayed the next request by **1.74 seconds**, and the whole
of it was one lint rule asking the workspace census a question per declaration
in the buffer. Moving that question behind the rule's own local guards — where
its twin rule has always asked it — took the same open to **117 ms**, and took
the take-3 rows from 51–95 ms to 3–9 ms.
## Assumptions
- **The oracle is a pure predicate.** `MentionOracle::mentioned_elsewhere` reads
the index and returns a `bool`; it has no side effects, so where in a
conjunction of `continue` guards it is asked cannot change what the rule
finds. Pinned empirically as well as argued: the 0.39.0 binary and the fixed
one publish byte-identical diagnostics for a workspace built to exercise both
answers (below).
- **A `didOpen`'s buffer must be analyzed before the open returns.** Every
request flushes dirty buffers first (`Server::answer_request`), so deferring
the *parse* to the change debounce would move the cost, not remove it, and
would break "the first request after the open is answered from up-to-date
state". The parse stays synchronous, and so does the publish.
- The measurements are wire-level and on one machine (below). Sub-millisecond
differences are not claimed; everything reported here is a factor, not a
percent.
- opentitan is read-only. The index cache went to a scratch
`initializationOptions.storagePath`; `git -C ~/repo/opentitan status
--porcelain` reported the same three pre-existing modified files before and
after every phase.
## Handshakes
- **`vlog_linter` → the server, unchanged.** `UndrivenNet::check` returns the
same violations, in the same order, for the same context. No rule signature,
no registry entry, no severity and no `default_on`/`needs_workspace` answer
moved. `lucisv check` is unaffected in every way (it has no oracle, so the
reordered test is a constant `false` there).
- **`WorkspaceIndex::files_mentioning` — no change requested.** Its doc comment
records that a merged `word → files` map was measured against the per-file
walk and rejected. That ruling stands and is not reopened here: the fix is to
ask the question a thousand times fewer, not to make the question faster.
What this round adds to the record is the cost of *one* question — a walk
over every indexed file — which is what makes asking it per declaration a
mistake at any workspace size.
- **`Server::publish` / `flush_dirty` — untouched.** §46 allowed the open's
diagnostics to be moved onto the change debounce. They were not; see
"What was not done".
## The measurement
### Method
`scratchpad/perf46/driver.py`, take 3's method (§9 of that doc): framed
JSON-RPC over the server's stdio, `workspace/configuration` answered with
`{"index":{"scope":"workspace"}}`, cache warmth through
`initializationOptions.storagePath`, positions resolved from the file text at
run time. Per file, in one settled session: `didOpen` and a `textDocument/hover`
at the first `module <name>` token written in the **same** flush, timed from the
`didOpen` frame going out to the hover response coming back; then the identical
hover again as the control. Three tries per file per binary, warm store.
Both binaries `cargo build --release -p lucisv_server`: the tree at f795606
(0.43.0) and `v0.39.0` from a scratch `git worktree` (removed afterwards).
Every server run, build and sweep went through `tools/guard.sh -m 8 -t 900`;
no guard kill occurred.
Machine: Apple M1 Max, 10 cores, 64 GB, macOS 27.0, quiet (load 1–3), nothing
else building.
**Note on the file set.** §46 named "the largest file in
`hw/top_darjeeling/ip/xbar_peri/rtl/autogen/` (tl_peri_pkg.sv-class, ~42k
lines)". In this checkout that directory holds only an 8 KB and a 3.6 KB file;
the ~42 000-line file the plan meant is
`hw/top_darjeeling/ip_autogen/pinmux/rtl/pinmux_reg_top.sv` (42 192 lines,
1.3 MB), the largest `.sv` in the tree. That is the file used.
### Where the time went — the breakdown
Temporary `eprintln!` timings inside `didOpen`, `Document::new`,
`Server::publish`, `diagnostics::all_in` and `lint_with`'s rule loop, on the
release build; **all of them removed before finishing** (`git diff` shows only
the rule and the tests). Milliseconds, one representative try per file.
| Stage | `aes.sv` 326 L | `aes_core.sv` 1 145 L | `pinmux_reg_top.sv` 42 192 L |
|---|---:|---:|---:|
| lex | 0.31 | 1.01 | 41.24 |
| tolerant parse | 0.59 | 1.01 | 31.73 |
| `collect_defines` | 0.00 | 0.01 | 0.57 |
| `analyze` | 0.17 | 0.56 | 11.57 |
| `resolve_external` | 0.12 | 0.32 | 4.79 |
| line index | 0.01 | 0.03 | 0.62 |
| **`Document::new` (the whole parse)** | **1.33** | **3.04** | **90.61** |
| `LintRun::for_document` (discovery, waivers, memo) | 0.34 | 0.07 | 0.09 |
| `diagnostics::all_in` (the lint pass) | 4.87 | 54.43 | **1 653.76** |
| — of which the rule `undriven-net` | 4.38 | 52.23 | **1 608.45** |
| — of which `multiply-driven` | — | — | 8.22 |
| — every other rule, together | ≈0.5 | ≈2.2 | ≈37 |
| **`didOpen` total** | **7.07** | **58.01** | **1 745.06** |
Two things the table settles:
1. **The widen is not involved.** At the whole-workspace scope every file is
already in scope, so `widen_of` answers `Nothing` and the open costs the
parse plus the publish and nothing else. The `didOpen` total is the sum of
the two rows above it to within 0.2 ms.
2. **The lint pass is 75 / 94 / 95 % of the open, and one rule is 90 / 96 /
97 % of the lint pass.** `LintRun::for_document` — §42's discovery, the
waiver-file reads and the once-only memo, the thing §46 guessed at — costs
70–340 µs and is not a candidate. Neither is the completion word table or
the semantic tokens: neither runs on an open at all.
### Why `undriven-net` cost that
The rule asked the workspace census about **every** declaration in the buffer,
before any of its local guards had a chance to silence it:
```rust
if intentionally_unused(..) || !judgeable(..) || has_init { continue }
if ctx.mentioned_elsewhere(&decl.name) { continue } // ← was here
let Some(usage) = signals.usage(decl) else { continue };
if connected || driven || reads == 0 { continue }
found.push(..)
```
One `mentioned_elsewhere` is `WorkspaceIndex::files_mentioning`, a walk over
**every indexed file** binary-searching its sorted word list — 3 976 files in
opentitan at the workspace scope. `pinmux_reg_top.sv` has roughly four thousand
declarations, and essentially all of them are driven, so all four thousand
questions were asked and all four thousand answers were thrown away by the very
next guard. `unused-signal`, the twin rule with the same oracle, has always
asked last, which is why it never showed up in a profile.
The fix is to ask the question where its twin asks it: last, of the handful of
declarations that would otherwise be reported. It is a pure reordering of a
conjunction of `continue` guards over a side-effect-free predicate, so the
findings and their order are unchanged.
### Before and after — the three §46 files
Wire time, `didOpen` → the hover behind it, three tries, warm store, workspace
scope, ms.
| File | lines | KB | 0.39.0 | 0.43.0 **before** | 0.43.0 **after** | factor |
|---|---:|---:|---|---|---|---:|
| `hw/ip/aes/rtl/aes.sv` | 326 | 14 | 8.6 / 9.5 / 7.8 | 8.1 / 5.9 / 10.1 | **4.3 / 1.8 / 2.3** | ~3× |
| `hw/ip/aes/rtl/aes_core.sv` | 1 145 | 49 | 55.8 / 65.7 / 44.4 | 56.2 / 54.0 / 48.0 | **5.9 / 6.9 / 6.3** | ~8× |
| `…/pinmux/rtl/pinmux_reg_top.sv` | 42 192 | 1 297 | 1 725.8 / 1 694.1 / 1 751.1 | 1 742.5 / 1 740.2 / 1 756.8 | **116.5 / 116.2 / 117.3** | ~15× |
The control — the identical hover issued straight after the first — is
0.09–0.20 ms for `aes.sv`, 0.12–0.19 for `aes_core.sv` and 0.46–0.60 for
`pinmux_reg_top.sv`, before and after alike. It is the open that costs, exactly
as take 3 said.
**0.39.0 measures the same as 0.43.0 before the fix.** This was never a
regression: `undriven-net` has asked in that order since it was written. Take
3's §8.4 comparison against take 2's 2–4 ms is therefore not a "something got
slower" story, and take 2's client — which no longer exists — most likely
measured a session whose scope did not switch the workspace rules on at all.
### Before and after — take 3's own §8.4 rows
Same method, whole-workspace scope. (Take 3 measured these at the *default*
scope after the `aes.sv` widen, where the census covers ~124 files rather than
3 976; that is why the "before" column here is worse than §8.4's 21/31/51 ms.
The two are the same defect at two census sizes.)
| File | KB | take 3 §8.4 (default scope) | **before** (workspace scope) | **after** |
|---|---:|---:|---|---|
| `hw/ip/hmac/rtl/hmac.sv` | 33 | 21.1 | 56.8 / 42.7 / 51.0 | **4.7 / 5.7 / 3.3** |
| `hw/ip/kmac/rtl/kmac.sv` | 53 | 31.1 | 69.3 / 72.1 / 70.6 | **7.9 / 5.3 / 8.8** |
| `hw/ip/spi_device/rtl/spi_device.sv` | 67 | 51.2 | 94.2 / 103.4 / 88.6 | **6.0 / 8.6 / 8.7** |
### The ≤ 5 ms contract, honestly
§46 asked for "`didOpen` returns to the loop in ≤ 5 ms for a 1 000-line file".
- For a **generated** 1 000-line buffer the release binary is under 2 ms. Met.
- For `aes_core.sv` — 1 145 lines but 49 KB of dense opentitan RTL, four times
the bytes per line of a generated file — the open is **5.9–6.9 ms**, of which
**3.0–4.4 ms is `Document::new`**: the lex, the tolerant parse, the semantic
analysis and the external resolution. The lint pass is now 1.3 ms of it.
So the contract is met per line and missed per byte on the densest real file
measured, and the remainder is the parse — which cannot be deferred without
breaking "the first request after the open is answered from up-to-date
state". Recorded as the limit rather than met by redefining the file.
### Behavioural equivalence, checked on the wire
A two-file scratch workspace built to exercise both oracle answers: `top.sv`
declares `lonely` (read, undriven, mentioned nowhere else) and `shared_name`
(read, undriven, but `force`d from `other.sv`). Both binaries publish exactly
```
undriven-net @1:7 `lonely` is read but never driven
```
and nothing about `shared_name` — the census still silences it. Byte-identical
between 0.39.0 and the fixed build.
## What was not done, and why
- **The open's diagnostics were not moved onto the change debounce.** §46 named
it as a likely shape and allowed the diagnostics to arrive a debounce later.
They still go out inside the `didOpen`, synchronously, because after the fix
the whole publish is 0.5–1.5 ms on a real RTL file and 24 ms on a
42 000-line one; deferring it would buy a millisecond and cost the guarantee
that an opened file is diagnosed before anything queued behind it is
answered. **There is no debounce on the open, and there is nothing new to
pin about when diagnostics arrive** — pinned anyway, by
`an_open_still_publishes_its_diagnostics_with_no_edit_behind_it`.
- **The buffer's re-index was not skipped on a content-hash match.** §46's
other suggested shape. It is not on the open path at all: a `didOpen` of a
file already in scope runs no index update — `widen_of` answers `Nothing` and
the index is untouched until a `didSave`. There was nothing to skip.
- **`WorkspaceIndex::files_mentioning` was not given an inverted index.** See
Handshakes: that ruling is recorded in its own doc comment and is not this
round's to reopen. It is now the largest single item left on the open path
for a 42 000-line file (`multiply-driven` at 8 ms is the next), but at
~117 ms total the file is no longer the round's problem.
- **The other 95 ms of `pinmux_reg_top.sv`'s open is the parse** (lex 41 ms,
parse 32 ms, analyze 12 ms). Not touched; it is the price of a 1.3 MB buffer
and it is 25× under the large-file threshold that would skip it.
## Status / TODO
- [x] Measure first: the driver, three files, three tries, both binaries, warm
store, workspace scope.
- [x] Profile the open path with temporary timings; the breakdown table above;
the timings removed (`git diff` is the rule plus the tests).
- [x] Fix the largest item: `undriven-net` asks the census last.
- [x] Wire-level timing test on a generated 2 000-line buffer.
- [x] Correctness pin: the first hover **and** the first definition after an
open see the buffer, not the disk.
- [x] Diagnostics-still-arrive pin, with the debounce question answered (there
is none).
- [x] Exact regression pin: the oracle is asked once per reported candidate.
- [x] The take-3 rows re-measured, before and after, in this README.
- [x] Gates: `cargo fmt -p lucisv_server -p vlog_linter`, `cargo clippy
--all-targets`, `cargo test --workspace`, `tools/corpus_check.sh`,
`editors/vscode/smoke.js` — all guarded.
- [ ] QA.
## Work log
### 2026-09-05 — dev (Fable 5.1)
- Built both binaries release: the tree at f795606, and `v0.39.0` in a scratch
worktree under the scratchpad (removed at the end, `git worktree remove`).
- Wrote `scratchpad/perf46/driver.py` to take 3's method and measured the three
§46 files, three tries each, on both binaries. Both binaries measured the
same, which is the first finding: **§8.4 is not a regression**.
- Instrumented the open path with temporary `eprintln!` timings at four levels
(the `didOpen` arm, `Document::new`'s six steps, `Server::publish` /
`diagnostics_of`, and `lint_with`'s per-rule loop), measured, and removed
every one of them. The breakdown table is above.
- Result: the lint pass is 75–95 % of the open and `undriven-net` is 90–97 % of
the lint pass, because it asked the workspace census once per declaration
ahead of its own local guards. `unused-signal`, the twin rule, has always
asked last.
- **The fix**: move `ctx.mentioned_elsewhere` in `UndrivenNet::check` below the
`usage` / `connected` / `driven` / `reads == 0` guards. Six lines moved, a
comment saying why. A pure reordering of `continue`s over a side-effect-free
predicate.
- Checked equivalence three ways: the unit suite, the corpus check (unmoved),
and a wire comparison of published diagnostics between the 0.39.0 binary and
the fixed one over a workspace built so that the census both fires and does
not. Identical.
- Tests: one exact regression pin in the rule (a counting oracle — the findings
alone cannot tell the two orders apart), and three wire-level tests in
`crates/lucisv_server/tests/e2e.rs` reusing the `Live` session helper that
was already there (`talk` writes a whole session before reading, so it cannot
time anything).
- **Deviation, stated plainly: the wire test's bound is 200 ms, not §46's
25 ms.** Two reasons, both measured. (1) `cargo test` builds unoptimized, and
one tolerant parse of a 2 000-line buffer costs ~53 ms there on its own —
stable to a millisecond across runs — so 25 ms is unreachable in a debug
build whatever the lint pass does; §46's 25 ms is a release figure, and the
release binary opens the same buffer in 2–4 ms. (2) The test cannot catch the
§46 defect at any bound: the census walk costs milliseconds over a forty-file
fixture (measured — 53 ms with the fix, 54 ms without it, and 63 ms with the
fixture grown to 400 files and per-file-unique names), and a fixture of
opentitan's four thousand files has no business in the suite. So the wire
test pins the contract — an open does not start doing something unbounded —
and the counting oracle test in `undriven_net.rs` is the exact pin for the
defect. Both are documented as such in their own doc comments.
- Scratch worktree removed; driver and scratch stores deleted; opentitan
`git status --porcelain` reports the three pre-existing files and nothing
else.
**Files touched** (the plan's expected set, plus one):
- `crates/vlog_linter/src/rules/undriven_net.rs` — the fix and its test.
- `crates/lucisv_server/tests/e2e.rs` — three wire tests and two helpers.
- `docs/features/didopen-cost/README.md` — this file.
- `TODO.md` — §46's four dev checkboxes and §44's `didOpen` line.
Nothing else. In particular **no server source file was changed**: the fix
turned out to be one rule in `vlog_linter`, not anything in the open path
itself, which is why `crates/lucisv_server/src/server/{notification,diagnostics,
index}.rs` and `state.rs` are untouched despite being where §46 expected the
work.
**Gate numbers**: `cargo fmt -p lucisv_server -p vlog_linter` clean; `cargo
clippy --all-targets` clean; `cargo test --workspace` **3 814 passed, 0
failed, 44 ignored** (baseline 3 810 — the four new tests);
`tools/corpus_check.sh` **814/820**, the same six failures and the same
`verification-error: none` / `crash: none`; `node editors/vscode/smoke.js
target/release/lucisv-server` OK. Every one guarded at `-m 8`; no guard kill,
and nothing came near the limit.
## Docs to apply at merge (lead)
### `docs/performance_take3.md` — annotate finding §8.4
Append to §8.4, after the "Reproduce" paragraph:
> **Fixed in 0.44.0 (TODO §46), and the finding understated it.** The delay is
> not the widen, the diagnostics plumbing or §42's lint-run construction: it is
> one rule. `undriven-net` asked the workspace census
> (`WorkspaceIndex::files_mentioning`, a walk over every indexed file) once per
> declaration in the buffer, *before* its own local guards had a chance to
> silence it — so a file with four thousand declarations asked four thousand
> questions and threw away four thousand answers. `unused-signal`, the twin
> rule with the same oracle, has always asked last; `undriven-net` now does
> too. At the whole-workspace scope, where the census covers 3 976 files rather
> than this section's ~124, the same three files measured 51 / 70 / 95 ms
> before and **4.6 / 7.3 / 7.8 ms** after, and opentitan's largest file,
> `hw/top_darjeeling/ip_autogen/pinmux/rtl/pinmux_reg_top.sv` (42 192 lines),
> went from **1 742 ms to 117 ms**. The take-2 comparison in this section
> should be read as "take 2's session probably did not have the workspace rules
> on", not as a regression: 0.39.0 measures the same as 0.43.0 on every cell.
> Breakdown and method in `docs/features/didopen-cost/README.md`.
### `docs/perf/README.md` — a new entry
> ### 2026-09-05 — the `didOpen` delay (TODO §46, 0.44.0)
>
> Take 3's §8.4 (a `didOpen` of an already-indexed file delaying the next
> request by 21–51 ms) measured and fixed. The breakdown, taken with temporary
> timings on a release build and re-taken after: the tolerant parse plus the
> semantic analysis is 1.3 / 3.0 / 91 ms for a 326- / 1 145- / 42 192-line
> opentitan file, and the lint pass was 4.9 / 54 / 1 654 ms — of which
> `undriven-net` alone was 4.4 / 52 / 1 608. The rule asked
> `WorkspaceIndex::files_mentioning` (a walk over all 3 976 indexed files) once
> per declaration, ahead of the local guards that silence almost all of them.
> Moved behind them, where `unused-signal` has always asked.
>
> Wire time, `didOpen` → the request behind it, workspace scope, warm store,
> three tries, M1 Max:
>
> | file | before | after |
> |---|---|---|
> | `aes.sv` (326 L) | 8.1 / 5.9 / 10.1 ms | 4.3 / 1.8 / 2.3 ms |
> | `aes_core.sv` (1 145 L) | 56.2 / 54.0 / 48.0 ms | 5.9 / 6.9 / 6.3 ms |
> | `hmac.sv` | 56.8 / 42.7 / 51.0 ms | 4.7 / 5.7 / 3.3 ms |
> | `kmac.sv` | 69.3 / 72.1 / 70.6 ms | 7.9 / 5.3 / 8.8 ms |
> | `spi_device.sv` | 94.2 / 103.4 / 88.6 ms | 6.0 / 8.6 / 8.7 ms |
> | `pinmux_reg_top.sv` (42 192 L) | 1 742 / 1 740 / 1 757 ms | 116.5 / 116.2 / 117.3 ms |
>
> The same cost was paid on **every keystroke flush**, not just on opens: the
> change debounce ends in the same `set_document` + `publish` pair.
> 0.39.0 measures the same as 0.43.0 everywhere in the "before" column, so this
> was never a regression — it is a rule that has been ordered that way since it
> was written. Published diagnostics are byte-identical before and after.
## QA log
### 2026-09-05 — QA (Sonnet)
**Verdict: PASS.** No HIGH or MEDIUM findings. Two LOW/informational notes
below; neither blocks the fix.
**What was verified, and how.**
1. **Code reading.** `git diff` of the three touched files
(`crates/vlog_linter/src/rules/undriven_net.rs`,
`crates/lucisv_server/tests/e2e.rs`, `TODO.md`) — a pure reordering of six
lines plus a comment in the rule, one new unit test asserting the oracle's
call count, and three new wire-level tests reusing the existing `Live`
helper. Confirmed `unused-signal` (`crates/vlog_linter/src/rules/
unused_signal.rs`) already asks its oracle last, behind
`mentioned_outside_declarations`, unchanged by this diff — the dev's "its
twin rule has always asked last" claim checks out by inspection.
`WorkspaceIndex::files_mentioning`/`files_naming_in_macros`
(`crates/vlog_semantic/src/workspace/index.rs:286-331`) confirmed
word-exact (binary search over a sorted per-file word list, no substring
matching) and `crates/vlog_semantic/src/words.rs` confirmed comments
contribute no words (only `Ident`/`SystemIdent` tokens and raw text inside
macros/directives/attributes) and macro-argument text is folded into the
*same* union census `files_mentioning` reads — so a macro-only mention is
expected to silence the rule exactly as a plain mention does.
2. **Equivalence, scratch workspace.** Built both binaries release
(`tools/guard.sh -m 8 -t 900 -- cargo build --release -p lucisv -p
lucisv_server`): the working tree at f795606-plus-uncommitted-diff, and
`v0.43.0` in a scratch `git worktree` (removed after). Wrote a five-file
scratch workspace (`top.sv`, `tb.sv`, `bound_over.sv`, `iface/bus_if.sv`,
`pkg/util_pkg.sv`) exercising every guard interaction the attack list
named: undriven+mentioned (silent), undriven+unmentioned (reported), driven
locally+mentioned (silent), undriven but hierarchically assigned from a
sibling testbench (silent), `force`d through a hierarchical path from a
sibling (silent), named only in a sibling's `bind`-ed override connection
(silent), a plain cross-file mention (silent), a name that is only a
*substring* of a longer identifier in a sibling (still **reported** — no
substring match), a name that appears in a sibling only inside a `//`
comment (still **reported** — comments aren't tokens), a name that appears
in a sibling only as a macro argument (silent — the raw-text fold), each
port direction, a net inside a `generate` block, a `logic` variable
(not a `wire`), an interface, and a package. `lucisv check --select
undriven-net .` and `--select unused-signal,undriven-net .` and a full
`check .`, text and `--output-format json`: **byte-identical** between the
two binaries in every case (6 violations found; `undriven_hier`,
`undriven_forced`, `undriven_bound`, `undriven_macro_arg`,
`undriven_mentioned`, `driven_and_mentioned` all correctly silent).
3. **Equivalence, opentitan (read-only).** `--select undriven-net,unused-signal
--output-format json` over `hw/ip/aes`, `hw/ip/hmac`, `hw/ip/spi_device`,
`hw/top_darjeeling/ip_autogen/pinmux`, sets compared (order does not
matter here since neither directory produced more than one finding):
**identical** in all four (`aes`: 1 finding both binaries, set-equal;
the other three: 0 findings, both). `git -C ~/repo/opentitan status
--porcelain` before and after: only the three pre-existing files
(`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/ast.sv`,
`hw/top_earlgrey/ip/ast/rtl/ast.sv`).
4. **The counting-oracle unit test, reverted.** Not reverted in this tree.
Copied the dev's `undriven_net.rs` (with the fix and its new tests) into a
fresh scratch worktree at f795606, hand-reverted only the six-line reorder
(oracle back above the `usage`/`driven`/`connected`/`reads==0` guards,
dev's new test left as written), and ran
`cargo test -p vlog_linter --lib rules::undriven_net::`. Result: 16 of 17
pass; `the_project_is_asked_only_about_the_signals_that_would_be_reported`
**fails** — `assertion left == right failed: left: 10, right: 1` — exactly
what asking the oracle before the local guards predicts (all ten
signals in that fixture are `judgeable` with no initializer, so all ten
reach the pre-fix guard). Confirms the test is an exact regression pin,
not a tautology. Worktree removed after.
5. **Wire timing, independently reproduced.** The dev's driver is gone, so a
new one was written (`scratchpad/perf46_qa/driver.py`, this session's
scratchpad) to the same shape: framed JSON-RPC over stdio,
`initializationOptions.storagePath` for cache control, `workspace/
didChangeConfiguration` to the workspace scope, a `workspace/symbol`
barrier before timing, `didOpen`+`hover` in the same flush timed from send
to the hover response, warm store, three tries. M1 Max (10 cores, 64 GB),
`v0.43.0` (scratch worktree, removed after) vs the fixed tree's release
build:
| File | 0.43.0 | fixed | factor |
|---|---:|---:|---:|
| `aes.sv` | 4.83 / 4.81 / 4.88 ms | 1.49 / 1.35 / 1.31 ms | ~3.4× |
| `aes_core.sv` | 41.4 / 43.2 / 47.1 ms | 3.90 / 3.66 / 3.57 ms | ~11× |
| `pinmux_reg_top.sv` | 1825 / 1805 / 1806 ms | 104 / 108 / 107 ms | ~17× |
Independently-measured numbers differ from the README's own table (a
different driver, different process/JSON overhead, one machine) but the
**direction and rough magnitude match closely**, `pinmux_reg_top.sv`
especially (~17× here vs ~15× claimed, 104-108 ms here vs 116-117 ms
claimed). The control hover (issued right after) was 0.05-0.85 ms in every
case, before and after alike, confirming the open itself is what costs.
Also timed a `didChange` full-text flush on `aes_core.sv` (not just
`didOpen`): **42.6-43.5 ms (0.43.0) → 3.8-4.0 ms (fixed)** — confirms the
README's "the same cost was paid on every keystroke flush" claim; the
flush and the open cost the same because both end in the same
`set_document` + `publish` pair, as documented.
6. **`opentitan`'s 1.0 MiB index-scan cap, noted in passing (see finding
below).** Confirmed by `window/logMessage` output during warm-up:
`pinmux_reg_top.sv` under all three top-level variants is *skipped from
the workspace index scan* ("skipped (1.3 MiB > 1.0 MiB cap)"), which is
exactly take 3's "3976 indexed, 3 skipped" — not a new discovery, just
confirms the population this round's numbers describe. The currently
*open* buffer is unaffected by this cap (it goes through `Document::new`
on `didOpen` regardless of size), which is why the dev's own breakdown
table and this session's timings both see `pinmux_reg_top.sv` fully
parsed and linted when opened.
7. **e2e tests, 5×.** `tools/guard.sh -m 8 -t 300 -- cargo test -p
lucisv_server --test e2e -- --test-threads=1
opening_a_two_thousand_line_buffer_does_not_delay_the_request_behind_it
the_first_hover_after_an_open_sees_the_buffer_and_not_the_disk
an_open_still_publishes_its_diagnostics_with_no_edit_behind_it`: **3
passed, 0 failed, every one of 5 runs**, 0.65-0.70 s each. Stable.
8. **The 200 ms vs 25 ms question — my view for the lead.** The dev's
reasoning holds up under independent measurement, not just their own
instrumentation: (a) `target/debug/lucisv check` on a fresh 2000-line
generated buffer (no workspace) took ~40 ms wall-clock (steady state,
process spawn included) against `target/release/lucisv`'s ~10 ms on the
same buffer — a debug/release ratio in the same ballpark as the dev's
53 ms/2-4 ms claim for the parse alone; (b) a release-mode wire
measurement of a comparable 2000-line generated buffer (matching the
e2e test's own `generated_module` shape, 40 package neighbours, through
the *actual LSP wire* including Python subprocess/JSON overhead) came
back at 11.7-11.8 ms — comfortably under both 25 ms and 200 ms. This
triangulates the dev's claim: the 200 ms bound is not hiding a live
defect, it is debug-build parse cost that release mode does not pay, so
asking the debug-build wire test for 25 ms would be asking it to beat a
floor the interpreter/parser layer sets on its own. **200 ms is the
right bound for this test**; I would not lower it, and I would not read
"200 ms, not 25 ms" as the fix being incomplete.
9. **Gates, guarded, re-run independently.** `cargo clippy --all-targets`:
clean (0.12 s — fully cached, nothing to re-lint since the dev's own
clean run). `tools/guard.sh -m 8 -t 1800 -- cargo test --workspace`:
**3814 passed, 0 failed, 44 ignored** (summed across every crate's `test
result:` line) — matches the dev's claimed count exactly.
`tools/guard.sh -m 8 -t 1800 -- tools/corpus_check.sh`: **814/820
(99.3%)**, `verification-error: none`, `crash: none`, the same six parse
errors. `node editors/vscode/smoke.js target/release/lucisv-server`: OK
(20 messages). No guard kill on any run.
**Findings.**
- **LOW (informational, not a defect).** While this QA was running, the
shared working tree picked up further edits not part of the dev's
original diff: `CHANGELOG.md`, `editors/vscode/CHANGELOG.md`,
`editors/vscode/README.md` gained 0.44.0 release-note entries, and
`TODO.md` gained the §46 dev-checkbox ticks (matching this README's
Status/TODO) plus a new §47 planning section, beyond what this QA read at
the start of its session. None of this touches the rule, the tests, or
this README's content above this log entry, and none of it changed any
number this QA independently re-measured — `crates/vlog_linter/src/
rules/undriven_net.rs` and `crates/lucisv_server/tests/e2e.rs` are
byte-identical to what was diffed at the start of this session (71 and
204 changed lines respectively, matching exactly). Flagged so the lead
knows the tree was not exclusively QA's for the whole session; not
something this QA touched or reverted.
- **LOW (context, not a defect).** `WorkspaceIndex`'s workspace-scan size cap
(1.0 MiB) skips all three `pinmux_reg_top.sv` variants from the persistent
cross-file census entirely. This is pre-existing and matches take 3's own
"3976 indexed, 3 skipped" count — not introduced or affected by this
change — but worth restating next to this round's numbers since a reader
could otherwise wonder why a 1.3 MB file's own words never reach another
file's `mentioned_elsewhere` answer. The *open* buffer's own analysis is
unaffected by the cap, which is why the timings above still show the full
parse+lint cost when the file itself is opened.
**Equivalence result:** identical findings, identical order, on the scratch
fixture (text and JSON), on `lucisv check .` with no `--select`, and on all
four opentitan directories — 0.43.0 and the fixed tree agree everywhere
tested.
**Verdict: PASS.**
## Review
**2026-09-05 — lead.** Accepted; ships in 0.44.0 with §45. The plan's three
guesses were wrong and the dev's first step — measure — is what found the
real cause: one rule asking the whole-workspace census once per declaration
before its local guards. The fix is six reordered lines over a
side-effect-free predicate, with equivalence shown three ways (the suite,
the corpus, and QA's crafted workspace covering every guard interaction
plus four opentitan IPs byte-identical between 0.43.0 and the fix). 15× on
the largest file, 10× on typical IPs, on every keystroke as well as every
open. The 200 ms wire-test bound is ruled correct: it pins the contract in
a debug build whose parse alone is ~53 ms, the exact regression pin is the
counting-oracle unit test (verified to fail on a revert), and QA's release
measurement of the same buffer (11.7 ms) shows the plan's 25 ms was a
release number. No debounce was added and none is needed at 0.5–1.5 ms per
publish. (The README lacked its Review section; added here.)
+5
View File
@@ -86,6 +86,11 @@ taught anything new.
unasked; (b) a DPI export's `name` refers to a function declared elsewhere in
the same scope and could be a `use_name`. Note the `*::*` form has `"*"` as
its **package** name, which no existing code expects.
**(a) answered 2026-09-05 by TODO §48** — `bind_export_path` records exactly
those two halves and pushes no scope import, and the index follows the edge
(`docs/features/package-reexports/README.md`). `*::*` still records no
reference, for the reason given: neither half is a name. **(b) is still
open** — a DPI export's `name` is unbound.
- **vlog_semantic / vlog_linter**: DPI-imported functions and tasks now arrive
as ordinary `ItemKind::Function` / `ItemKind::Task` with `stmts` empty and
`is_prototype` set, so `bind_function` already declares them as symbols — a
+532
View File
@@ -0,0 +1,532 @@
# hierarchical-tail
TODO.md §49 — the cross-file instance-member tail in rename. `docs/topo.md`
§2.9 row 23. Ships in 0.45.0.
## Goal
With `module sub` in `sub.sv` and `assign w = u_x.sig;` in `top.sv`, renaming
`sub`'s internal `wire sig` used to edit `sub.sv` alone and warn about the
tail in `top.sv` — a rename that hands back a design which no longer
elaborates, with an apology. The same shape in one file resolved and was
edited. The cause was the export rule in `workspace/record.rs::is_exported`:
a module exported its ports and its parameters and nothing else, so the
cross-file member walk could not see `sig` through `u_x`.
The lead's ruling, implemented here: a module gains a **second, distinct
member surface**. Its *connection* surface stays what it was — ports and
parameters, what a connection list may name (IEEE 1800 §23.3). Its
*hierarchical* surface is that set **plus** its nets, its variables and its
instances, which is what a hierarchical path may name from anywhere in the
design (§23.6). The index records both, tagged; only the tail walk behind an
**instance** head reads the hierarchical one. Rename's reference set then
includes the cross-file tail, the edit lands in both files, and the §2.9-20
"the rename says so" warning is no longer raised for a tail that resolved (it
stays, unchanged, for one that did not).
## Assumptions
- **A hierarchical path is what an instance head opens, and nothing else
is.** `resolve.rs::head_surface` returns `Surface::Hierarchical` for exactly
`SymbolKind::Instance` and `Surface::Connection` for every other link of a
spine. A class handle, a struct field, a virtual interface and a package
path are all the connection surface, and for those units the distinction is
noise anyway — a package, a class, a struct and a covergroup have one
surface each.
- **The hierarchical surface contains the connection one.** A record is
tagged with the *narrowest* surface it joins, and a hierarchical read
consults the connection table first. So a tail naming a port has exactly one
answer, from one record, and it is the same declaration a connection-list
lookup finds. This is asserted, not assumed:
`a_tail_naming_a_port_is_one_answer_and_one_edit`.
- **A unit's members are the symbols of its own scope.** `collect_members`
walks `unit.child_scope` and no deeper (except into a nested class, struct
or covergroup, whose members are keyed under their own name). A net declared
inside a **generate block** therefore joins neither surface: its scope is
the block's. `u_x.gen_b.sig` does not resolve, and the rename leaves the
tail alone and says so — the honest refusal, pinned by
`a_generate_block_scoped_net_named_through_an_instance_is_refused_honestly`.
Widening that means teaching the index about generate scopes and their loop
indices (`u_x.gen[0].sig`), which §49 deliberately did not do.
- **An interface is unchanged.** Its signals *are* its connection surface
(the 2026-09-01 ruling: `virtual bus_if vif; vif.data` is how every DV
testbench reaches `data`, and `vif` is a variable, not an instance). It
gains only its **instances** on the hierarchical surface, for the same hop
reason a module does.
- **Two instances of a name in one module cannot happen**, so the
hierarchical table's `Vec<Def>` per name holds duplicates only across files
— the same ambiguity rule, and the same refusal, the connection table has
always had.
## Handshakes
### What this consumes
- `vlog_semantic::Semantics` — `member_site` / `unit_site` return the site a
tail is walked from, and a `Symbol`'s `kind` is what says whether a link is
an instance.
- `vlog_parser` — unchanged; nothing in the parser moved.
### What this promises
**`vlog_semantic` (the surface encoding).**
- `pub enum Surface { Connection, Hierarchical }` in `model.rs`, re-exported
from the crate root.
- `Resolution::ExternalCandidate { paths, surface }` — a new field. Every
construction site outside a hierarchical tail passes `Surface::Connection`;
`resolve.rs::head_surface` is the one place that can return the other.
- `MemberSite::Unit { path, surface }` — was `MemberSite::Unit(String)`. The
surface is `Hierarchical` exactly when the head of the spine was an
instance, and it stays that for every further hop: `u_a.u_b.` is one
hierarchical path.
- `WorkspaceIndex` gains `member_in(unit, member, surface)`,
`members_of_chain_in(path, surface)`, `member_unit_in(unit, member,
surface)` and `hierarchical_declarations(name)`. **Every existing method
reads the connection surface and answers exactly what it answered before**:
`member`, `members_of`, `members_of_chain`, `member_unit`,
`workspace_symbols`.
- `IndexCounts` gains `hierarchical_members`, disjoint from `members`, so the
whole member census is the two added.
- `FACTS_FORMAT` 18 → 19. Two new fields — a one-letter surface on every
declaration and on every `External` reference fact — so an older record
would be read field-shifted, and `index_cache` drops a store by format as it
already does.
**`lucisv_server`.** `Workspace::rename_sources`' fan-out gains one rung:
every file declaring the name on a module's hierarchical surface. `state.rs`
is the only server file whose *behaviour* changed;
`completion/member.rs` follows the site's own surface (below).
**`vlog_refactor`.** No behaviour of its own changed. `rename/warnings.rs`
took a mechanical `..` in one pattern for the new `ExternalCandidate` field;
the §2.9-20 warning retires itself, because it is raised only when the overlay
answers `StillUnresolved` and a resolved tail no longer does.
### The completion decision, said plainly
Behind `u_x.` **in an expression**, completion lists the module's
**hierarchical** surface — its nets, its variables and its instances as well
as its ports and its parameters. That is what the user is reaching for, it is
exactly what the tail resolution will find, and it is what the *in-file* half
of the same function has always offered for an instance this file declares
(`MemberSite::Scope` pushes every symbol of the module's scope). Making the
two halves disagree would have been the odd choice.
Behind the `.` of a **connection list** it is the connection surface and
nothing more. `.internal_net(w)` is not a legal connection, so an item there
would be one the resolution could not answer — a wrong answer rather than a
generous one. That path is `connection_members`, which reads
`WorkspaceIndex::members_of` (the connection table) and filters to `Port` or
`Param`; it never reaches `members_at`. Both halves are pinned in one test:
`an_instance_head_lists_the_hierarchical_surface_and_a_connection_list_does_not`.
The `propagate-ports` engine reads `member`/`members_of` and is untouched.
### What did not widen
- **Reference postings.** `facts_from_analysis` records a `Local` posting only
for a use whose declaration is on the **connection** surface. Posting a
module's every internal-net use would multiply the reference table by the
size of an RTL body for an answer nothing reads: the only consumer is a
rename, which re-analyses the declaring file anyway. The *cross-file* half —
the tail in the other file — is an `External` fact, and that is what makes
the rename work.
- **`workspace/symbol`.** An internal net is still not a workspace symbol: the
request answers what a user can name from outside, and a design with 20 000
modules has hundreds of thousands of internal signals.
`hierarchical_declarations` is the separate, map-only question the rename
fan-out asks instead.
- **`verify.rs`.** Untouched. No normalization was added or broadened, so no
masked-corruption attack tests are owed.
## Status / TODO
- [x] 49.1 surface bit in facts, `FACTS_FORMAT` 18 → 19, index member walk
- [x] 49.2 `MemberOf` behind an instance reads the hierarchical surface;
rename edits the tail; the warning retired for resolved tails
- [x] `workspace/hierarchy.rs` — `surface_of` (the old `is_exported`,
re-ruled) plus the two surface-taking reads; `record.rs`'s export doc
comment rewritten to say the ruling moved
- [x] Completion decision made, said here, and pinned both ways
- [x] Tests: the cross-file twin of the rename pin; nested `u_a.u_b.sig`; a
tail naming a port (one answer, one edit); a parameter; the
generate-block refusal; the interface tail unchanged; the ambiguous
`sub` still refused; the connection list unchanged; the census delta
- [x] Gates (guarded); census delta explained; opentitan before/after
- [ ] QA
## Work log
### 2026-09-05 — dev (agent 2, resuming)
**The state I found.** The first dev agent on this lane was cut off by a
network failure mid-round, leaving uncommitted work in the tree: 20 modified
files plus a new `crates/vlog_semantic/src/workspace/hierarchy.rs`, and no
feature README at all. `cargo check --workspace --all-targets` passed; the
agent's last words were "now the test compile errors across the workspace",
and that is exactly where it stood — the *library* half of §49 was complete
and coherent, the test suite was not green, and no new tests had been written.
What the first agent had already built, and which I kept unchanged: the
`Surface` enum and its two carriers (`Resolution::ExternalCandidate`,
`MemberSite::Unit`), `head_surface` in `resolve.rs`, `hierarchy.rs` with
`surface_of` and the two surface-taking reads, the second `hier_members` table
in `WorkspaceIndex` with its update/clear paths, the `FACTS_FORMAT` 18 → 19
encoding, `hierarchical_declarations` and the fan-out rung in the server's
`state.rs`, and the completion follow-the-site change in
`completion/member.rs`. It is a good design and I did not redo any of it.
**What I finished.**
1. Made the workspace suite green. Four failures, each a real consequence of
the change rather than a bug:
- `lucisv_server` `a_local_only_symbol_sharing_the_new_names_spelling_is_not_a_bogus_refusal`
— its fixture was a module's `wire`, which is now a hierarchical
declaration and joins the fan-out by the new rung, so the test would have
passed for the wrong reason ever after. The fixture is now a **function's
local**, which is on neither surface, and the rung-6 attack it exists for
is intact. The behaviour it used to pin got its own test beside it,
`a_module_net_sharing_the_new_names_spelling_joins_the_fan_out_and_refuses_nothing`:
the file *is* pulled in, and the rename still succeeds and still writes
nothing there.
- `vlog_semantic` `a_format_3_record_with_two_declarations_is_rejected_not_misread`
— the record stripper counts a decl's fields. `MEMBER_DECL_FIELDS`
11 → 12, `UNIT_DECL_FIELDS` 19 → 20, and one more `drain` for the surface
letter.
- `vlog_semantic` `an_instance_head_reaches_a_module_in_another_file` — its
`u.internal` assertion was the old ruling. It now asserts the net
resolves, *and* that the connection table still does not hold it, *and*
that a port has one record on it.
- `lucisv_server` e2e `an_instance_heads_port_is_hovered_across_files` —
hover of `u.internal` across files now answers with the net's own
declaration. The test asserts the file and line it names.
2. Wrote the plan's tests (all passed first time against the first agent's
library code, which is the strongest evidence I have that it was finished):
the cross-file twin driven from **both** ends, nested `u_a.u_b.sig` over
three files, the port, the parameter, the generate-block refusal, the
interface tail, the ambiguous-`sub` refusal from both ends, and the
two-way completion pin.
3. Added the census-delta measurement as a corpus test rather than a prose
claim, and put the hierarchical count into the index census line.
4. Wrote this README, which the first agent had not started.
**Deviations and files touched outside the plan's expected set.** The plan
named `crates/vlog_semantic/{facts.rs,workspace/*}`,
`crates/vlog_refactor/src/rename/*`,
`crates/lucisv_server/src/{completion/*,state.rs}`, tests, this README and
`TODO.md`. Beyond those I touched:
- `crates/lucisv_server/src/rename.rs` — **tests only** (the `#[cfg(test)]`
block): the fixture swap and the new sibling test above. No production line
in that file changed.
- `crates/lucisv_server/tests/e2e.rs` — the hover assertion above.
- `crates/vlog_semantic/src/{lib.rs,model.rs,resolve.rs}` — the first agent's
work, and unavoidable: `Surface` has to live in the model and be exported,
and `resolve.rs` is where a spine's head is visible.
**One size flag for the lead.** `crates/lucisv_server/src/state.rs` is **957
production lines outside its test module** — already well over the 800
threshold before this lane, and CLAUDE.md's post-§28 measurement (which names
only `perf.rs` and `lexer.rs` as over 600) is stale for it. This lane added
**13** production lines there: the fan-out's new rung, seven lines inside
`fan_out_of` plus its doc bullet. The rule says a dev adding to a file near
600 puts the code in a new module; I did not, because the rung reads
`self.index`, `want_declaration` and the caller's `containers` set and a
module holding seven lines of it would be worse than the disease. The file
wants a split of its own, which is a decomposition round, not a paragraph in
this one. Every other file this lane touched is inside the rule:
`workspace/hierarchy.rs` 80 production lines, `workspace/index.rs` 283,
`workspace/record.rs` 315 (it *lost* the 60-line `is_exported`),
`model.rs` 161, `resolve.rs` 520, `facts.rs` 526. Every function added or
changed is under 50 lines.
**The gates.** `cargo fmt -p vlog_semantic -p lucisv_server -p vlog_refactor`
(never `--all`) and `cargo clippy --all-targets` clean; `cargo test
--workspace` **3 839 passed / 0 failed / 44 ignored** (baseline 3 829, +10:
seven new rename tests, one new server fan-out test, one new completion test,
one new census test); `tools/corpus_check.sh` **814/820**, the same six
pre-existing parse errors (`compare_helper.sv`, `riscv_core_setting.tpl.sv`,
`latch_map.v`, `riscv_instr_cover_group.sv`, `romload/testbench.v`,
`smtbmc/mulcmp.v`); `format --stdout` over all **860** corpus files
**byte-identical** to `~/.cache/lucisv-baselines/lucisv-0.44.0`, 0 differing;
`cargo build --release -p lucisv_server` + `node editors/vscode/smoke.js` OK.
Everything through `tools/guard.sh`; no guard kill, no limit raised.
**The census delta.** The single-file corpus census does not move at all —
860 files, 27 486 symbols, 103 875 references, 1 197 unresolved, 0 unplaced,
identical to the number the brief carried. It cannot move: §49 adds a tag to
a resolution, not a resolution. What moves is the *workspace* census:
| | before | after |
|---|---|---|
| exported members (connection surface) | 12 939 | 12 939 |
| hierarchical-only members | — | **5 239** |
| corpus references only the hierarchical surface answers | 0 | **335** |
The connection count is unchanged **by construction**: `surface_of`'s
`Surface::Connection` arms are the old `is_exported`'s `true` arms, name for
name, with the hierarchical kinds added as new arms. The 5 239 new records are
the corpus's modules' and interfaces' nets, variables and instances. Over the
whole corpus 707 references carry a hierarchical candidate and 668 of them
resolve; **335** of those land in the hierarchical-only table, which is the
slice that could not resolve before.
`the_hierarchical_surface_is_what_answers_a_measurable_slice_of_the_corpus`
prints the three numbers on every run and pins the direction, not the
constants.
A note on how that 335 is counted, because the obvious way is wrong. "The
declaration's kind is `Net`, `Var` or `Instance`" over-counts by 216 on this
corpus: an **interface's** signals are `Net`/`Var` and are on the *connection*
surface, so they resolved before §49 as well. The exact test is membership of
the hierarchical-only table itself
(`WorkspaceIndex::hierarchical_declarations`), which is what the test does.
### opentitan (read-only, scratch index store)
Everything below is a `textDocument/rename` **request** whose returned edit
was inspected and never applied.
`git -C ~/repo/opentitan status --porcelain` reported the same three
pre-existing files (`hw/ip/aes/dv/tb/tb.sv`,
`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`)
before and after every run. Baseline binary: `lucisv-server` built
`--release` from the `v0.44.0` tag in a scratch `git worktree` under the
scratchpad, removed afterwards. Guard on every command; **no guard kill**.
**The headline — a DV bench reaching an IP module's internal variable.**
`hw/ip/lc_ctrl/dv/tb.sv:229` writes
`assign #1ps lc_ctrl_if.lc_ctrl_fsm_state = dut.u_lc_ctrl_fsm.fsm_state_q;`,
and `fsm_state_q` is declared at `hw/ip/lc_ctrl/rtl/lc_ctrl_fsm.sv:173`.
Renaming it (root `hw/ip/lc_ctrl`, cursor on the declaration):
| | 0.44.0 | this branch |
|---|---|---|
| files in the returned edit | `rtl/lc_ctrl_fsm.sv` (8 edits) | `rtl/lc_ctrl_fsm.sv` (8) **+ `dv/tb.sv` (1)** |
| `rename`, three tries | 10 / 9 / 10 ms | 22 / 23 / 22 ms |
| `prepareRename`, three tries | 1 / 0 / 1 ms | 0 / 0 / 1 ms |
That is the whole feature in one row: 0.44.0 edited the RTL and left the
bench spelling the old name, and now the bench moves with it. It is also the
whole cost: the tail's file is in the rename's fan-out now, so it is read,
parsed and verified — 10 ms → 22 ms on this cursor. `prepareRename` does not
move, because it does not fan out.
**`hw/ip/aes`, the tree the brief named.** Rename of
`hw/ip/aes/rtl/aes_core.sv:87`'s `logic key_touch_forces_reseed`, root
`hw/ip/aes`: **the same answer before and after** — `rtl/aes_core.sv`, 3
edits — at 40 / 41 / 41 ms before and 53 / 55 / 57 ms after; `prepareRename`
≈ 1 ms in both. And the count of newly resolved `MemberOf` references over
`hw/ip/aes` is **0**, before and after. That is not a disappointment to hide,
it is the shape of the IP: `aes`'s 5 hierarchical candidates all reach through
a **generate block** (`u_aes_core.u_aes_control.gen_fsm[i]. … `,
`u_aes_core.gen_ghash.u_aes_ghash. … ` in `rtl/aes.sv`) or sit inside a
`bind aes …` in `dv/sva/aes_bind.sv`, where the head is resolved in the bind
target's scope in another file and is therefore not an instance symbol this
file can see. Neither is on either surface, and §49 said so in advance.
Over **all of `hw/`** (3 979 files) the picture is the one the corpus
predicts: 91 930 connection members + **71 849** hierarchical-only ones;
1 611 references carry a hierarchical candidate, 1 290 resolve, and **514**
of those are answers only the hierarchical surface can give — `lc_ctrl`,
`otbn`, `keymgr`, `dma` and `entropy_src` benches reaching into their DUTs.
**Store size** (the scratch `initializationOptions.storagePath`, the whole
index cache for that root):
| root | 0.44.0 | this branch | delta |
|---|---|---|---|
| `hw/ip/aes` (124 files) | 1 459 576 B | 1 615 179 B | +155 603 B, **+10.7 %** |
| `hw/ip/lc_ctrl` | 765 347 B | 813 065 B | +47 718 B, **+6.2 %** |
Two things are in that delta and they are not the same size: the one-letter
surface field on every declaration and every external reference fact (small,
and paid whether or not a module has internals), and the hierarchical member
records themselves (the bulk).
## QA log
### 2026-09-05 — QA
**Diffs read in full**: `resolve.rs`, `model.rs`, `workspace/{hierarchy.rs (new),
external.rs, index.rs, mod.rs, record.rs, reexport.rs, update.rs}`, `facts.rs`,
`lib.rs`, `rename/warnings.rs`, `completion/member.rs`, `state.rs`, `rename.rs`,
`e2e.rs`, all touched test files. Traced `head_surface` end to end — a link
opens `Surface::Hierarchical` exactly when the *head symbol's own kind* is
`SymbolKind::Instance` (`resolve.rs::link_type`/`head_surface`), never off a
type name's spelling; a same-file spine stays on `MemberSite::Scope`
untouched by any surface at all, exactly as before this feature. The `Local`
reference-posting filter to `Surface::Connection` only in `record.rs` is by
design and doesn't widen anything: an internal net's own-file uses are found
by re-analysing its declaring file directly (which rename always does for
the file it edits), not through the posting table that filter narrows.
**Gates (guarded, `tools/guard.sh` throughout).** `cargo fmt --check` clean;
`cargo clippy --all-targets` clean; `cargo test --workspace`: **3 839 passed
/ 0 failed / 44 ignored** — matches the dev's claim exactly (re-verified
twice: once with the QA attack tests added, once after removing them, same
count both times save for the attacks themselves). `tools/corpus_check.sh`:
**814/820**, the same six pre-existing parse errors. `format --stdout` over
all 860 corpus files vs `~/.cache/lucisv-baselines/lucisv-0.44.0`: **0
differing**. Release build (`lucisv`, `lucisv_server`) + VS Code smoke
(`node editors/vscode/smoke.js target/release/lucisv-server`): OK. Census:
`the_corpus_index_finishes_most_external_references` prints 860 files,
103 875 references, 12 939 connection members + **5 239** hierarchical-only —
matches the README's table exactly.
**Rename matrix, driven through the public engine API (`vlog_refactor`) and
confirmed by the dev's own tests plus attacks I added and then removed
(temporary `qa_49_*` tests, run green, then deleted — the tree is back to
exactly the dev's diff):**
- Cross-file twin from both ends, nested `u_a.u_b.sig` over three files, a
port (one answer, one edit — checked the tail's edit range fires once, not
once per surface), a parameter, the generate-block-scoped net refused
honestly with no edit, an interface instance tail unchanged, the ambiguous
two-`sub` case refused from both ends: all the dev's own tests, read and
re-run green.
- **New attack — rename onto a name already in the module, via the
hierarchical tail, from both ends**: refused (`"would change what..."`).
The live cross-file tail does not bypass the ordinary same-module capture
check.
- **New attack — rename a hierarchically-reached net onto a sibling port's
name**: refused. A capture across the connection/hierarchical surface
boundary is caught exactly like one within a surface.
- **New attack — a non-instance head whose *type name* happens to spell a
module name** (`sub h;` with no parens, a data declaration, not an
instantiation): `head_surface` correctly reads the head symbol's own kind
(`Var`, not `Instance`), so `h.internal` reads the connection surface and
refuses the net. No crash.
- **New attack — a hierarchical path inside a `bind` connection expression,
through an instance declared *inside the bind target's module* in another
file** (the shape behind the aes `bind` zero-count in the README): no
crash, and the tail never resolves through the wrong scope — the head is
looked up (if at all) in the writing scope, never the target's, exactly as
the README predicts. Pinned with a temporary test, then removed.
- **New attack — `didChange` promotes an internal net to a port**: before,
hierarchical-only (1 record); after, on the connection table (1 record,
not 2 — the hierarchical read still finds exactly one), and the cross-file
tail still resolves exactly once, now to the port. **New attack —
`didChange` removes the net entirely**: the hierarchical table drops the
record and the cross-file tail goes back to unresolved. Both via
`WorkspaceIndex::update_file` at the library level (no server session
needed) — the incremental-update code path (`update.rs`) is exercised
identically for hierarchical and connection tables, which is by
construction from the diff (same `absorb`/`update_file` code, dispatched
on `decl.surface`) and confirmed by these two round-trips.
- **New attack — a hierarchical declaration's own reference postings
include the cross-file tail** (`WorkspaceIndex::references_to` on a net's
`Def`, gotten via `hierarchical_declarations`): confirmed — this is the
exact mechanism `state.rs::want_declaration` stands on to pull the tail's
file into a rename's fan-out.
**Completion.** The dev's own two-way pin
(`an_instance_head_lists_the_hierarchical_surface_and_a_connection_list_does_not`)
read and re-run. **New attacks, run green then removed**: `u_a.u_b.`
(nested) lists `u_b`'s module's own hierarchical surface, not `u_a`'s and
not empty; an instance of an **unknown** module in *expression* position
(not just the connection-list shape the dev's own
`a_module_the_workspace_does_not_declare_answers_nothing` already covered)
answers empty, no panic.
**Opentitan (read-only; every`textDocument/rename` a request, inspected,
never applied).** Built `v0.44.0`'s `lucisv-server` in a scratch worktree
(`git worktree add`, removed after). `git -C ~/repo/opentitan status
--porcelain` showed only the three pre-existing files
(`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/.../ast.sv`,
`hw/top_earlgrey/.../ast.sv`) before and after every run — reproduced
independently, not assumed from the dev's log.
- `lc_ctrl_fsm.sv:173`'s `fsm_state_q`, renamed from the declaration: 0.44.0
→ `rtl/lc_ctrl_fsm.sv` alone, 8 edits, 9–10 ms rename / 0–1 ms
prepareRename. This branch → **+ `dv/tb.sv`, 1 edit**, same 8 in the rtl
file, 22–24 ms rename / 0–1 ms prepareRename. Matches the README exactly.
Dumped every edit's range and the *exact source text at that range* on
both files: **every one reads `"fsm_state_q"`**, character-for-character,
new file included (`dv/tb.sv:229`, columns 63–74).
- `aes_core.sv:87`'s `key_touch_forces_reseed`: **identical answer** before
and after — `rtl/aes_core.sv`, 3 edits — 38–41 ms → 55–56 ms. Matches.
- Sampled the newly-resolved references over `hw/` with an independent
read-only tool (not the dev's — built fresh against the library API):
**1611 hierarchical candidates, 1290 answered, 514 hierarchical-only** —
matches the README's table exactly. Printed 20 of the 514 with the
occurrence line, the resolved declaration's file:line, and the
declaration's own source text. All 20 are genuine DV-bench-into-DUT
reaches (`dut.reg2hw...`, `dut.u_x.state_q`, `dut.lfsr_en`, …), every
declaration's source text actually spells the referenced name at the
claimed location, and every one is a plausible member of the instance's
module — no false positive found in the sample.
**Findings.** None at HIGH or MEDIUM severity. Two LOW observations, neither
blocking:
- LOW — `crates/lucisv_server/src/state.rs` is already flagged by the dev
(957 production lines) and separately filed by the lead as TODO §55; no
new action from this QA pass beyond confirming the number.
- LOW — the `Local`-reference-posting filter to the connection surface
(`record.rs::facts_from_analysis`) is a quiet, easy-to-miss line to
re-derive from first principles (it looks at first glance like it could
under-post same-file hierarchical uses). Traced it through
`merge_references`/`want_declaration` and confirmed by the incremental
`didChange` attacks above that nothing is actually lost — worth a comment
pointer from `record.rs` to `hierarchy.rs::surface_of` for the next reader,
but not a functional gap.
**Verdict: PASS.** Rename correctness, the completion split, the verifier's
refusals, the two-table index mechanics, the census delta and the opentitan
before/after all hold under attack, including several shapes beyond the
dev's own plan (own-scope and cross-surface capture through a hierarchical
tail, a non-instance head sharing a module's name, a bind-through-target
scope, and both `didChange` directions). Every temporary QA test was
removed after running green; the tree's diff against master is byte-for-byte
the dev's original plus this log entry and the TODO.md checkbox below.
## Docs to apply at merge (lead)
**`docs/topo.md` §2.9 row 23** — strike, with:
> ~~A **cross-file instance-member tail does not resolve for rename** …~~ —
> **delivered 2026-09-05 by hierarchical-tail (TODO §49):** a module now has
> two member surfaces. Its *connection* surface is unchanged — ports and
> parameters, what a connection list may name and what `member` /
> `members_of` / `members_of_chain` / the `propagate-ports` engine /
> connection-list completion read. Its *hierarchical* surface is that set plus
> its nets, variables and instances (§23.6), recorded in a second index table
> and tagged on the fact (`FACTS_FORMAT` 18 → 19), and read **only** by the
> tail walk behind an instance head (`Resolution::ExternalCandidate` carrying
> `Surface::Hierarchical`, set by `resolve.rs::head_surface`). `assign w =
> u_x.sig;` in `top.sv` now resolves to `sub.sv`'s `wire sig`, the rename
> edits both files, and the §2.9-20 warning is retired for a tail that
> resolved. A generate-block-scoped net (`u_x.gen[0].sig`) is on neither
> surface and is still refused honestly — the one gap this row leaves behind.
**`docs/features/comment-slots/README.md`, "Findings" item 2** — the gap it
flagged is closed. **Already applied by this lane** (the one line the brief
allowed); nothing for the lead to do, it is recorded here so the merge sees
it:
> **Closed 2026-09-05 by TODO §49 / `docs/features/hierarchical-tail`:** a
> module's hierarchical surface makes the cross-file tail resolve, so the edit
> lands in both files and the warning is retired for it.
**`README.md`** — no change needed; it does not describe the member tables at
this depth.
## Review
**2026-09-05 — lead.** Accepted; ships in 0.45.0 with §47 and §48. The
first dev was cut off by the outage with the library half complete and
sound; the second kept all of it and finished the tests, the README and
the gates — the right call. The ruling is implemented as ruled: two
disjoint tables, the hierarchical one read by exactly one walk, and the
connection surface byte-identical for every existing reader (the census's
12 939 connection members unchanged by construction). QA's matrix is the
proof that matters for a rename: refusals on capture across the surface
boundary, on an ambiguous module, on a generate-scoped net; the lc_ctrl
edit inspected range by range; 20 of the 514 newly resolved opentitan
references sampled and all genuine. The completion decision (hierarchical
members behind `u_x.` in an expression, ports only in a connection list)
is what a user typing a hierarchical path wants. The rename cost of one
more file's read is the feature. QA's two LOWs: `state.rs` is filed as
§55; the `Local`-posting doc pointer is added at review.
*(reserved for the lead — do not write here)*
@@ -0,0 +1,455 @@
# lint-config-contract
TODO §42. Repository-analysis finding 2, topology handshake 28.
## Goal
One lint-configuration contract for the two front ends. Before this round the
CLI read a project's `[lint] select` / `ignore` out of `lucisv.toml` and the
server did not: `enabled_rules` selected rules from `ClientSettings` alone,
and `configured` discovered the same config file only to read its rule options
and its line length. A team that checked in `select = ["no-tabs"]` therefore
got one answer from CI and a different one from every editor in the project,
and the docs had to say so. The server also *dropped* a `[lint.<rule>]` entry
the registry refused (`let _ = options.set_raw(...)`) with nothing said, while
the same mistake made in `lucisv.lint.options` was logged.
The contract, which is the CLI's today applied to the editor: **the editor's
settings play the role the CLI's flags play.** `lucisv/src/lint.rs` picks the
flag when one was given and the project file otherwise (`pick`); the server
now picks `lucisv.lint.select` when it is non-empty and `[lint] select`
otherwise, and the same for `ignore`, key by key. And a project entry that
cannot be used is *said* — once per (config file, entry), in the words
`lucisv check` fails the run with — rather than silently dropped.
## Assumptions
- **A server cannot fail a run.** Everything the CLI treats as fatal (an
unknown rule name, a rejected rule option, a waiver file that is not there
or holds an unparsable directive) is here a dropped entry plus one log line.
The buffer keeps being linted with everything that *was* understood. This is
the standing rule of `lint.rs` and `settings::rule_options`, applied to the
project file for the first time.
- **Rungs 3 and 4 are the editor's alone.** `lucisv.lint.severity.<class>` and
`lucisv.lint.rules.<name>` have no counterpart in `lucisv.toml` and none on
the command line, so nothing about them changed. They still apply *over* a
selection the project made, which is what "all style off except `no-tabs`"
needs.
- **One discovery per pass, no new file read.** `configured` already ran
`Discovery::new(true).for_file(path)` once per `LintRun::for_document`;
the project's selection is read out of the `FileConfig` that discovery
already produced, so 42.1 costs zero stats and zero opens. The waiver files
are now read in two calls instead of one (the project's paths, then the
editor's) so a problem in the project's can be attributed to the
`lucisv.toml` that named it — the same files, the same number of reads.
- **The memo is keyed by (config path, message), re-armed by content.** The
server has no "config generation": nothing invalidates on a `lucisv.toml`
write, because the file is re-read on every pass. So `ProblemLog` stamps
each config path with a hash of that file's lint-relevant content
(`[lint] select`/`ignore`/`waivers` and every `[lint.<rule>]` entry) and
clears that path's memo when the stamp moves. A user who edits the file and
gets it wrong again is told again; a user who types in a `.sv` buffer is
not told a hundred times. A problem in a *waiver file* named by an unchanged
`lucisv.toml` is said once per session, which is the one edge the stamp does
not see; it is a log line, not a diagnostic, and `lucisv check` is the place
that fails over it.
- **The memo lives behind a `RefCell`.** A lint pass runs behind `&self` — the
pull models compute diagnostics inside a `map` over the open buffers — and
the memo is the one thing a pass writes. `try_borrow_mut` with an early
return, so no panic is reachable even if a future caller nests.
- An unknown rule name in the project's lists is dropped rather than obeyed:
see the Work log's "beyond the plan".
## Handshakes
**Consumed**
- `lucisv_core::config::{Discovery, FileConfig, LintOption}` — `lint_select`,
`lint_ignore`, `lint_waivers`, `lint_options` (with `LintOption::line`) and
`source`. Unchanged by this round; `source` and `line` are what let a server
message name the file and line `lucisv check` names.
- `vlog_linter::{rules_named, rule_by_name, all_rules, default_rules,
workspace_rules, RuleOptions::set_raw, ExternalWaivers::{read, absorb}}` —
unchanged. `set_raw`'s error text is reused verbatim, so the server's line
and the CLI's are the same sentence.
- `crate::settings::ClientSettings` — unchanged.
**Promised**
- `lint::enabled_rules` **changed signature**:
`enabled_rules(&ClientSettings, &ProjectLint, has_oracle)`. The only caller
outside the module's own tests was `LintRun::for_document`. A caller that
wants the editor-only ladder passes `&ProjectLint::default()`.
- `lint::LintRun::config_problems() -> &ConfigProblems` is new, and
`server::diagnostics` is the one place that reports them. A future caller
that builds a `LintRun` outside the diagnostics path (today: the code-action
entry in `server/dispatch.rs`) says nothing, deliberately — one reporter, so
the memo cannot be raced by two.
- `lint::waiver_paths` keeps its signature and its behaviour (project paths
first, then the editor's, resolved as before); `server::notification` still
calls it with a default `FileConfig` to check the editor's alone.
**Requested of others (not done here)**
- `README.md`, `docs/site/src/content/docs/start/configuration.md` and
`docs/repository-analysis.md` carry the old sentence. The replacement text
is below, for the lead to apply at merge.
- `docs/features/server-lint/README.md` line 228 still reads "Not done,
deliberately: rule selection. No `lucisv.toml` `lint` key…", which was
already stale before this round (the key landed in §33) and is now doubly
so. Out of this lane's file set; flagged for the lead.
## Status / TODO
- [x] 42.1 project selection into the ladder, editor-when-set-else-project
- [x] 42.2 rejected project options logged with `<file>:<line>: <message>`,
once per (config file, entry), the lint still running
- [x] unit tests: the four-way table, severity words in the toml lists, the
editor-only rungs over a project selection, the once-only log across
three passes, the re-arm on an edited config
- [x] e2e tests: the project selects / the editor replaces / an emptied
setting hands it back; the rejected option logged once over the wire;
the CLI and the server asserted equal for three configurations
- [x] docs text for README / site / repository-analysis (below)
- [ ] topo §2.9-28 struck (lead); finding 2 annotated (lead)
- [x] QA
## Work log
**2026-09-05 — dev (Opus 5)**
New module `crates/lucisv_server/src/lint/project.rs` (Rust 2018 lets
`lint.rs` own a `lint/` directory), so nothing was added to `lint.rs`'s test
block, which already dwarfs its 201 production lines. It holds `ProjectLint`,
`ConfigProblems`, `ProblemLog` and their tests.
The ladder as implemented, in `lint::enabled_rules`:
1. base = `default_on`, plus the `needs_workspace` rules when `has_oracle`;
2. `pick(lucisv.lint.select, [lint] select)` — the editor's list when it is
non-empty, else the project's — **replaces** the base when it names
anything;
3. `lucisv.lint.severity.<class>` off **removes** that class (editor only);
4. `lucisv.lint.rules.<name>` sets or clears one rule (editor only);
5. `pick(lucisv.lint.ignore, [lint] ignore)` **removes**.
`pick` is a five-line twin of the CLI's, and rungs 2 and 5 are picked
independently — a project that selects and a user who only ignores keep both
halves. Every list takes a severity word wherever a rule name fits, the
project's as much as the editor's, because both go through
`vlog_linter::rules_named`.
`configured` now returns its problems instead of `let _`-ing them away, in
`lucisv check`'s wording (`{file}:{line}: rule `{rule}` {error}` — the format
string is `lucisv/src/lint.rs`'s `rule_options`, copied deliberately rather
than shared, since the two crates are bins and neither can depend on the
other). `for_document` reads the project's waiver files apart from the
editor's and keeps the project's problems; the editor's are still said once by
`notification::apply_settings`, so nothing is said twice.
`Server::report_config_problems` (in `server/diagnostics.rs`, on the one path
that publishes) filters them through `ProblemLog` and logs the survivors as
`lucisv: <file>:<line>: <message>; ignored` at `MessageType::WARNING` —
`window/logMessage`, not `showMessage`: a typo in a checked-in config is not
worth a popup on every editor in the project.
**Beyond the plan (one addition, deliberate).** `ProjectLint::read` also drops
and reports a name in `[lint] select` / `ignore` that the registry does not
know. The plan named only the rejected `[lint.<rule>]` entry and the bad
waiver directive. The reason for adding it: `named()` skips an unknown word,
so `select = ["no-tab"]` taken at face value resolves to *no rules at all* and
blanks the file's squiggles, which reads as "lucisv is happy" rather than
"lucisv could not read your config" — the same silent-drop failure §42.2
exists to close, one line up. `lucisv check` fails the run over it; the server
drops the name, says it once, and applies the rest of the list (a `select`
left empty by the dropping falls back to the base set, which is the safe
direction: some rules rather than none). The message has no line number,
because `lucisv_core::config` records one per `[lint.<rule>]` entry and not
per list element: `<toml>: [lint] select: unknown rule: no-tab`.
**Cost.** No new file read per diagnostics pass: the project selection comes
out of the `FileConfig` the pass's single `Discovery` already produced, and
the waiver files are the same files read the same number of times, just in two
calls instead of one. The only new work per pass is a `DefaultHasher` over the
config's `[lint]` entries (a handful of short strings) and a `HashMap` probe,
both of which are skipped entirely when the config has no problems —
`ConfigProblems::is_empty` returns before the memo is touched, which is every
buffer in a project whose config is correct.
**Files touched** (all within the expected set):
- `crates/lucisv_server/src/lint/project.rs` (new)
- `crates/lucisv_server/src/lint.rs`
- `crates/lucisv_server/src/server/mod.rs` (the memo field)
- `crates/lucisv_server/src/server/diagnostics.rs` (the one reporter)
- `crates/lucisv_server/tests/e2e.rs` (three tests appended)
- `TODO.md` (§42's own checkboxes)
- this README
## Docs to apply at merge (lead)
### `README.md`, the two sentences at the end of the linter section (~line 432)
Replace:
> The server currently selects rules from `lucisv.lint.*` editor settings;
> project `[lint] select/ignore` lists affect the CLI only. Project per-rule
> options are read by both front ends.
with:
> Both front ends read the same configuration, and the editor's settings play
> the role the CLI's flags play: `lucisv.lint.select` when it is set, else
> `[lint] select` from the buffer's `lucisv.toml`, else the default set — and
> the same for `ignore`, decided independently. `lucisv.lint.severity.*` and
> `lucisv.lint.rules.*` have no project counterpart and apply over whichever
> selection stands. Project per-rule options are read by both front ends. A
> project entry lucisv cannot use — an unknown rule name in `[lint]
> select`/`ignore`, a rejected `[lint.<rule>]` option, an unreadable waiver
> file or a directive that does not parse — fails `lucisv check` with
> `<file>:<line>: <message>` and exit 2; in an editor it is dropped, written
> once to the lucisv log in the same words, and everything lucisv did
> understand still lints the buffer.
Also, five lines above, the waiver sentence "a bad line in a file named by the
editor setting is written once to the lucisv log, one named by `lucisv.toml`
is not (run `lucisv check` to see it)" becomes:
> a bad line is written once to the lucisv log whether the file was named by
> the editor setting or by `lucisv.toml`.
### `docs/site/src/content/docs/start/configuration.md`
The Keys table, rows 33–34 — the "Used by" column becomes "CLI and editor":
| `[lint].select` | string array | defaults | rule names or severity classes | CLI and editor |
| `[lint].ignore` | string array | `[]` | rule names or severity classes | CLI and editor |
The "Editor settings" paragraph (~line 91) replaces:
> For lint selection, the server currently reads editor settings only. Project
> `[lint] select/ignore` lists affect the CLI and are not inherited by the
> server. Selection proceeds through defaults → select → severity switches →
> per-rule toggles → ignore. Editor rule options overlay project rule options
> key by key. Invalid editor options are logged and dropped. Invalid project
> rule-option entries are currently dropped by server linting without a
> per-entry log; `lucisv check` reports them as configuration errors.
with:
> For lint selection, the editor's settings play the role the CLI's flags
> play. Selection proceeds through defaults → select → severity switches →
> per-rule toggles → ignore. `select` is `lucisv.lint.select` when that
> setting is non-empty and the project's `[lint] select` otherwise; `ignore`
> is decided the same way and independently. The severity switches and
> per-rule toggles are editor-only — a `lucisv.toml` has no such keys — and
> apply over whichever selection stands. Editor rule options overlay project
> rule options key by key. An entry that cannot be used is dropped and logged
> once per configuration file and entry, in the same `<file>:<line>:
> <message>` wording `lucisv check` fails with: an invalid editor option, an
> invalid `[lint.<rule>]` entry, an unknown rule name in `[lint]
> select`/`ignore`, or an unreadable waiver file. `lucisv check` treats each
> of these as a configuration error and exits 2; the server keeps linting with
> the entry dropped.
The Discovery section (~line 57) sentence "A bad configuration is an error for
the CLI, preventing partial writes. In an editor, the server reports the
problem and falls back to the next available setting." is still true and needs
no change.
### `docs/repository-analysis.md`, finding 2
Replace the "The docs now describe the implemented behavior…" paragraph with a
fix note in the shape finding 1 already uses:
> **Fixed by TODO §42 (0.43.0, 2026-09-05):** `enabled_rules` now takes the
> project's selection beside the editor's and picks the editor's list when it
> is non-empty, the project's otherwise, key by key — the CLI's `pick` applied
> to the editor. Rejected project entries are logged once per (configuration
> file, entry) as `<file>:<line>: <message>`, the wording `lucisv check` fails
> with, and the buffer is still linted with the entry dropped. Pinned by
> `lint::project`'s four-way table test and by three wire-level tests in
> `crates/lucisv_server/tests/e2e.rs`, one of which asserts the CLI's and the
> server's rule lists equal for three configurations. See
> `docs/features/lint-config-contract/README.md`.
## QA log
**2026-09-05 — QA (Sonnet)**
Read the plan (TODO §42), the finding/handshake it answers (repository-
analysis finding 2, `docs/topo.md` §2.9-28), and this feature's README in
full, including the "beyond the plan" deviation (unknown rule names in
`[lint] select`/`ignore` dropped and logged) and the waiver-file edge
(memo keyed by the toml's stamp, not the waiver file's). Read the diffs of
`lint.rs`, the new `lint/project.rs`, `server/diagnostics.rs`,
`server/mod.rs`, and the three tests appended to `tests/e2e.rs`, and the
CLI's own `lucisv/src/lint.rs` (`pick`, `rule_options`) and
`vlog_linter::registry::select_rules`/`rules_named` for the wording and
precedence this feature is required to mirror.
Built `cargo build --release -p lucisv -p lucisv_server` once. Wrote a
throwaway attack suite as extra `#[test]` functions appended to
`crates/lucisv_server/tests/e2e.rs` (never committed to the dev's file —
removed before this pass ends; verified by `git diff --stat` matching the
dev's original 205-line insertion both before and after), driving the real
server binary over framed JSON-RPC, plus one wire-level test against a real
file copied read-only out of opentitan (`hw/ip/aes/dv/tb/tb.sv`, no write).
Two attack tests needed a raw child process with an explicit read/write
interleaving (rather than `talk()`'s single write-then-read-to-EOF) to test
disk-edit timing without a race, and to drive a `hover` request as a
synchronization barrier between passes — documented inline while they
existed; removed with the rest.
**Verified, all as specified:**
- The four-way matrix {toml select ∅/set, editor select ∅/set} ×
{toml ignore ∅/set, editor ignore ∅/set} over the wire, using a buffer
with findings in all three severities (`no-tabs`/`no-trailing-whitespace`/
`line-length` = style, `unused-signal`/`undriven-net` = warning,
`duplicate-declaration` = error) rather than the unit test's two rules —
every cell matches the documented ladder, and select/ignore are confirmed
decided **independently** (a project select plus a project ignore both
apply when the editor names neither).
- Severity words in the toml's lists (`select = ["style"]`,
`ignore = ["style"]`), including mixed with a rule name in the same list.
- Rungs 3/4 (editor-only class switch, per-rule toggle) apply over a project
selection, including the per-rule word beating the class word (note: the
editor's `rules.<name>` setting takes the **string** `"on"`/`"off"`, not a
JSON boolean — confirmed against `settings.rs`'s `rule_toggles` after an
initial test mistake).
- `didChangeConfiguration` transitions: editor `select` set then cleared
restores the project's; same, independently, for `ignore`.
- Nested `lucisv.toml`s: an outer and an inner buffer in one workspace each
follow their own nearest config file. (First attempt used identical
buffer text in both files and got `[]` for the inner buffer — not a
product bug: the shared file-scope oracle correctly saw the identically-
named `unused-signal` candidate declared in the other indexed file and
suppressed it, `docs/features/semantic-lints-on/README.md`'s documented
false-negative-safe direction. Fixed by giving each file's declarations
distinct names.)
- An unknown rule name in `[lint] select`: dropped, logged once
(`<toml>: [lint] select: unknown rule: no-tab`), the rest of the list
still applies, and the buffer keeps being linted — confirmed against
`lucisv check` on the identical config, which exits 2 and prints the same
`unknown rule: no-tab` wording before failing the run. The two front
ends' *reactions* differ by design (a server cannot fail a run); their
*diagnosis* of the same mistake does not.
- A rejected `[lint.<rule>]` option (`length = "wide"`): exactly one
`window/logMessage` across five `didChange` passes over the same bad
config; the message's core (`<toml>:<line>: rule `<rule>` <detail>`) found
verbatim inside `lucisv check`'s own stderr on the identical config (the
CLI prepends `error: `, which the server's log line has no equivalent
of — compared by substring, not equality, for that reason); the buffer
still linted with the entry dropped. Edited live to a *different* bad
value (`length = "-1"`) mid-session: logged again, once. Then fixed
(`length = 100`): silence from there on. (This needed the raw
read/write-interleaved harness — a `talk()` one-shot builds the whole
session string, `std::fs::write`s included, before the server is even
spawned, so every edit would already be on disk before anything runs;
used a `hover` request after each edit as a synchronization barrier,
since `Server::answer_request` flushes the dirty buffer before answering
any request.)
- A bad directive in a waiver file named by `[lint] waivers`: logged once,
naming the **waiver file's own** path and line, not the toml's.
- Extra probe beyond the plan, for the README's stated waiver/toml-stamp
edge: fixed the waiver file, then brought back the **exact same** bad
line, toml untouched throughout — not logged a second time, confirming
the memo really is keyed by exact message text under an unchanged toml
stamp, not merely "one waiver problem per session" in some coarser sense.
Contrast: two *different* bad lines in the same unedited-toml waiver file
during one session are each logged once (not suppressed by the first) —
consistent with `ProblemLog`'s `BTreeSet<String>` keyed by message text,
not a defect, but worth the lead/dev knowing the precise grain the
"once per session" sentence in Assumptions describes.
- CLI/server rule-set equality: five configurations (none, an explicit
select, `select=["style"]` + one ignored, `ignore=["style"]`, a select
containing an unknown name) plus one real file copied read-only out of
opentitan (`hw/ip/aes/dv/tb/tb.sv`, no `lucisv.toml` in that repo, so a
scratch one governed the copy) — server and CLI rule-code sets equal in
every case.
- Robustness: `select = []` (explicit empty) falls back to the base set,
same as absent; duplicate names in `select` collapse harmlessly; a name
in both `select` and `ignore` ends up ignored (ignore is the top rung); a
`[lint]` key the parser rejects outright fails `parse()` entirely, which
the CLI turns into an exit-2 run failure and the server (via the
pre-existing `.ok()` fallback in `configured`, **unchanged by §42**)
swallows into defaults across several passes with **zero** log lines —
confirmed it does not newly start logging under this feature.
- Performance: 20 consecutive diagnostics passes over a 2000-line buffer
with a valid config, this server against a 0.42.0 server built in a
scratch worktree (`git worktree add .../scratchpad/base v0.42.0`, removed
with `git worktree remove` before finishing). Three runs: ratios 0.985,
1.001, 0.983 (new server negligibly faster or equal, never slower) — no
measurable regression, as the README's cost analysis claims.
- Gates, guarded: `cargo clippy --all-targets` clean; `cargo test
--workspace` — **3780 passed, 0 failed** (matches the dev's count
exactly); `tools/corpus_check.sh` — **814/820 (99.3%)**, the same six
pre-existing parse errors; `node editors/vscode/smoke.js
target/release/lucisv-server` — OK.
- `git -C /Users/guoliangchen/repo/opentitan status --porcelain` after use:
unchanged, the same three pre-existing modified files
(`hw/ip/aes/dv/tb/tb.sv`, the two `ast.sv`s) as before this session — no
`lucisv.toml` was written there.
**Findings.**
- **LOW, pre-existing, not introduced by §42** — a `didChange` sent in the
same message burst as `shutdown` is never flushed: `lsp_server::
Connection::handle_shutdown` (called from
`crates/lucisv_server/src/server/mod.rs`'s `process_batch`) answers
shutdown directly, bypassing `Server::answer_request`'s `flush_dirty()`.
A dirty buffer's last edit is silently dropped — no republish, no
config-problem log for that pass — if the client shuts down before the
150ms `CHANGE_DEBOUNCE` fires or before another request arrives. This
interacts with §42's own "a `lucisv.toml` edited on disk takes effect at
the next publish" claim: that claim holds only when *some* republish
actually happens before the session ends, which is not the same as
saying the edit's diagnostics are guaranteed to reach the client at all
in a fast open-edit-shutdown session. Reproduced in the (removed) attack
test by sending a `didChange` immediately before `shutdown` in one write
and observing zero further publishes; fixed the test by sleeping past
the debounce instead of treating it as a §42 bug, since the behavior
predates this feature and is a property of the `lsp-server` crate's own
shutdown handling, not of anything `lint.rs`/`lint/project.rs` changed.
Not a §42 regression; flagging for whoever owns `change-debounce` next.
- **LOW, pre-existing, not introduced by §42** — an unknown name in the
*editor's* `lucisv.lint.select`/`ignore` is silently dropped at
settings-parse time (`crates/lucisv_server/src/settings.rs`'s `rules`,
called from `from_payload`), with no log line — unlike `lucisv.lint.
options`, whose rejected entries are logged (`lint_option_warnings`).
§42 makes the *project* side of the same mistake (`[lint] select`/
`ignore` in `lucisv.toml`) both dropped and logged (the "beyond the
plan" addition in the Work log), which is more informative than the
editor's own settings for the identical typo. Not this feature's
handshake to fix (`ClientSettings` is unchanged by §42) and not asked
for by the plan, but the asymmetry is now sharper than before this
round landed; worth a line in the lead's notes for a future pass over
`settings.rs`.
- No correctness, idempotency, or comment-preservation issues found; no
masked-corruption concern applies (this feature touches lint
configuration, not `verify.rs`'s forgiveness).
**Verdict: PASS.** No blocking findings. The two LOW findings above are
pre-existing behavior outside this feature's stated handshakes, not
regressions introduced by §42; recorded for whoever picks them up next.
Ticked TODO §42's QA checkbox and this feature's own `Status / TODO`
"QA" line.
## Review
**2026-09-05 — lead.** Accepted; ships in 0.43.0. The contract is the ruled
one and it is now the same sentence on both front ends: the editor's list
when set, else the project's, key by key, with the editor-only rungs applied
over whichever stands — and the wire-level equality test is what makes that
a fact rather than a description. The dev's one step beyond the plan
(dropping and logging an unknown rule name in a project list) is accepted:
an editor cannot fail the run, and a typo that silently resolves to "no
rules" reads as a clean file, which is the wrong kind of quiet. The
once-only memo keyed by config content is the right shape for a server with
no config generation; its stated edge (a waiver file's bad line under an
unchanged toml is said once per session) is acceptable and documented. QA's
two LOWs are pre-existing and out of scope; the second — an unknown name in
the *editor's* `lucisv.lint.select` still silently dropped — is worth a line
in a later round and is filed in topo §2.9 as item 29. Docs applied to
README, the linter guide, configuration.md, the analysis and topo.
+481
View File
@@ -0,0 +1,481 @@
# package re-exports (TODO §48)
## Goal
`export b_pkg::x;` inside `package a_pkg` was an opaque leaf: the binder bound
nothing for it and the index recorded nothing about it, so a file that did
`import a_pkg::*` and named `x` resolved nothing, `a_pkg::` offered nothing,
and a rename of `x` left the `export` line behind. This round makes the
re-export a real edge in both layers, which is `docs/topo.md` §2.9-16 and
request (a) of `docs/features/dpi-export/README.md`.
**The binding half.** `bind_export_path` (beside `bind_import_path`, sharing
its path walk) records the two halves an import records — `pkg` as a
`Target::Package` use, `item` as a `Target::UnitMember(pkg)` use — and pushes
**no** scope import, because a re-export brings nothing into the exporting
package (IEEE 1800 §26.6). `export *::*;` records nothing: neither half is an
identifier. A DPI export (`export "DPI-C" function f;`) stays the opaque leaf
it was.
**The resolution half.** `FileFacts` gains an `RX` group (`FACTS_FORMAT`
17 → 18): per package, the packages and names it re-exports. The member walk
in `workspace/external.rs` — the one lookup both the overlay and the index's
own reference postings go through — follows those edges after a unit's own
members and its `extends` chain, with a visited set so a cycle terminates. So
definition, hover, completion after `a_pkg::`, find-references and rename all
read the same edge and cannot disagree about it.
## Assumptions
- **`export *::*;` is expanded at record time into the exporting package's own
imports**, rather than stored as a flag for a later walk to interpret. §26.6
reads "everything imported into this package is re-exported", and which
packages those are is a property of the very file being read off — so a flag
would only move the same lookup somewhere with strictly less information,
and nothing would ever read it. `export *::*;` in a package that imports
nothing therefore records nothing, which is also what it re-exports. **This
is the one deviation from §48's letter**, which asked for "`(pkg, item)`
pairs, `(pkg, "*")`, and a `*::*` flag"; the first two are exactly what `RX`
holds, and the third is expanded instead of stored. Behaviour is identical
either way (pinned in `an_export_of_everything_reexports_what_the_package_imports`).
- **A re-export is followed only for a *package*.** The `RX` group is keyed by
the name of the package whose body writes the `export`, and only
`ItemKind::Package` bodies are scanned. A compilation-unit-scope `export` is
not recorded; the LRM does not put one there.
- **The re-export hop is taken after a unit's own members and its bases**,
never before, so a package's own declaration of a name it also re-exports is
what a lookup finds and what completion lists
(`a_local_declaration_wins_over_a_reexported_name_of_the_same_spelling`).
- **The walk is two levels deep, deliberately.** Each hop of the re-export walk
asks `own_chain` — a package and its `extends` chain — not `member_chain`,
which would recurse into the very walk that called it. Chasing a chain of
re-exports is the walk's own job, and it does it with an explicit queue.
- **The visited set is package names for a lookup, `(package, name)` pairs for
a listing.** A lookup for one name only ever follows edges that admit that
name, so the filter is constant and a package need be asked once; a listing
follows every edge, so the same package may be reached once per specific
name it is re-exported through. Both sets are bounded by the workspace.
- **`WorkspaceIndex::member` is unchanged** — it stays the raw table read.
Every walk that should follow re-exports goes through `member_chain` or
`members_of_chain`, which is where the hop was added.
- **A re-export edge is untyped.** Nothing checks that the named package
exists, that it declares the name, or that the exporting package imports it
(§26.6 requires the last of these, and lucisv is not an elaborator). An edge
that leads nowhere simply answers nothing.
## Handshakes
- **vlog_parser → vlog_semantic (consumed, unchanged).** `ItemKind::Export`
carries `ExportDecl::Package(Vec<ImportPath>)`, each `ImportPath` holding two
`Name`s with exact token spans, and `export *::*;` is one path whose
**package** half is `"*"`. Both halves' spans come straight off the token, so
§47's `exact_or_empty` guard is not needed here (there is no derived span to
check) — `an_export_records_both_halves_on_exactly_their_own_bytes` asserts
the bytes anyway.
- **vlog_semantic → lucisv_server (promised, additive).** `FACTS_FORMAT` is
**18**. `index_cache` drops a store stamped with any other number, which it
already did; its `a_store_from_any_previous_facts_format_is_dropped_not_misread`
enumerates `1..FACTS_FORMAT` and needed no change.
`WorkspaceIndex::members_of_chain` and the member lookup behind
`resolve_external` may now answer with a `Def` in a package the asking path
never named — the declaring one. No signature changed and no caller was
touched.
- **vlog_semantic internal.** `external::member_chain` keeps its signature and
its contract; `own_chain` and `own_members` are the base-chain halves split
out of it and out of `members_of_chain`, so a re-export hop lists exactly
what a lookup through it would find. `WorkspaceIndex::fingerprint` gained
`reexport …` lines: the edges decide what `a_pkg::x` means, so a merge that
dropped one must be visible as more than whichever references happened to
resolve through it.
- **dpi-export README, request (a): answered** (edited there, one paragraph).
Request (b) — binding a DPI export's `name` — is untouched and still open.
## Status / TODO
- [x] 48.1 `bind_export_path`: both halves recorded, no scope import,
`export *::*;` records nothing; the negative pinned
- [x] 48.2 `RX` group, `FACTS_FORMAT` 17 → 18, the member walk and the member
listing follow re-exports transitively with a visited set
- [x] `Affected::exporters` so a restricted merge rebuilds the table, and the
fingerprint witnesses it
- [x] unit tests (`crates/vlog_semantic/tests/reexports.rs`, 14) and one
wire-level e2e (`crates/lucisv_server/tests/e2e.rs`)
- [x] cycle, unknown item, transitive chain, local-beats-reexported
- [x] census re-derived and the delta explained
- [x] gates
- [x] QA
## Files touched
Exactly the expected set, plus the two docs edits:
- `crates/vlog_semantic/src/bind/item.rs` — the `Export` arm split,
`bind_export_path`
- `crates/vlog_semantic/src/workspace/reexport.rs` — **new** (189 lines)
- `crates/vlog_semantic/src/workspace/mod.rs` — `mod reexport;`, the
`reexports` table
- `crates/vlog_semantic/src/workspace/record.rs` — the `FileFacts` field
- `crates/vlog_semantic/src/workspace/index.rs` — `reexports()`,
`members_of_chain`
- `crates/vlog_semantic/src/workspace/external.rs` — `own_chain`,
`own_members`, the hop in `member_chain`
- `crates/vlog_semantic/src/workspace/update.rs` — merge, `Affected`,
fingerprint
- `crates/vlog_semantic/src/facts.rs` — the `RX` group, `FACTS_FORMAT` 18
- `crates/vlog_semantic/tests/reexports.rs` — **new**
- `crates/lucisv_server/tests/e2e.rs` — one test appended
- `docs/features/dpi-export/README.md` — request (a) answered
- `TODO.md` — §48's own checkboxes
## Docs to apply at merge (lead)
**`docs/topo.md` §2.9 row 16** — strike it. Suggested text:
> ~~16. `ItemKind::Export` is an opaque leaf: a package re-export's `pkg::item`
> halves are not references, so `export b_pkg::x;` is invisible to
> go-to-definition, to find-references and to a rename, and a file importing
> the re-exporting package cannot resolve the name at all.~~ **Closed
> 2026-09-05 (§48, `docs/features/package-reexports/README.md`).** Both halves
> are references (`bind_export_path`, no scope import), the index records each
> package's re-exports (`FACTS_FORMAT` 18, the `RX` group), and the member
> walk follows them transitively with a visited set — definition, hover,
> completion, references and rename all read the one edge. A **DPI** export's
> `name` is still unbound (dpi-export request (b)).
Nothing to change in `README.md`, `docs/repository-analysis.md` or
`docs/site/`.
## Work log
**2026-09-05 — dev (Opus 5).**
- Read the plan, `docs/topo.md` §2.9-16 and dpi-export's request (a). The
parser already had everything: `ExportDecl::Package(Vec<ImportPath>)` with
exact spans on both halves, and `"*"` as the package name for `*::*`.
- **48.1.** Split the `ItemKind::Export` arm in `bind/item.rs`: the package
form calls a new `bind_export_path`, the DPI form stays in the opaque-leaf
arm. `bind_export_path` is `bind_import_path` minus the
`scopes[scope].imports.push(...)`, plus the early return for a `*` package.
Used `Target::Package` rather than the plan's `Target::Unit`, because that is
what `bind_import_path` records for the same half and the plan's own words
were "exactly the halves `bind_import_path` records"; `Package` is the
narrower and therefore the more honest of the two (only a package may be
re-exported), and it produces the same `ExternalCandidate { paths: ["b_pkg"] }`
for the workspace.
- **48.2.** New module `workspace/reexport.rs` — the `Reexport` record, the
read-off (`of`, with the `*::*` expansion), and the two walks (`member`,
`members`). `external.rs` grew `own_chain` and `own_members`, the base-chain
halves the walk asks at each hop; `member_chain` is now `own_chain` else
`reexport::member`, and `members_of_chain` is `own_members` chained with
`reexport::members` under one dedup. New machinery went in the new module
rather than into `external.rs` (301 → 349 lines) or `index.rs` (521 → 523),
as the brief asked.
- Cost of the hop for a workspace with no re-exports: one `BTreeMap` lookup
returning an empty slice, per member miss — `reexport::member` returns on
that lookup before it allocates anything, which matters because
`merge_references` asks `member_chain` once per external reference in the
workspace (hundreds of thousands on opentitan). Nothing else changed shape.
- The fingerprint gained `reexport <exporter> <- <pkg>::<item>` lines, and
`Affected` gained `exporters` so a one-file update rebuilds only that
package's edges — checked by `an_update_and_a_build_agree_on_the_reexport_table`.
- Wrote 14 unit tests and one e2e. Confirmed the e2e really depends on the
feature by temporarily emptying `FileFacts::reexports` (it failed on the
first definition), then restored — the same trick that produced the "before"
binary for the opentitan probe.
### Census delta
Re-derived with `cargo test -p vlog_semantic --test corpus -- --nocapture`:
| | before | after |
|---|---|---|
| files | 860 | 860 |
| symbols | 27 486 | 27 486 |
| references | 103 870 | **103 875** |
| unresolved | 1 197 | 1 197 |
| names unplaced | 0 | 0 |
**+5 references, nothing else moved** — and they are exactly the five names the
corpus's two *package* re-export lines write:
- `ibex_mem_intf_agent_pkg.sv:28` `export ibex_mem_intf_pkg::*;` — 1 (the
package half; the `*` is not a name)
- `csr_utils_pkg.sv:10`
`export dv_base_reg_pkg::csr_field_t, dv_base_reg_pkg::decode_csr_or_field;`
— 4 (two package halves, two item halves)
The corpus's other nine `export` lines are all DPI exports, which are
deliberately unchanged. Unresolved is flat, so all five became external
candidates rather than dead ends; no symbol was declared and no span was
derived, so `symbols` and `unplaced` could not move.
### Gates (all through `tools/guard.sh`; no guard kill)
| gate | result |
|---|---|
| `cargo fmt -p vlog_semantic -p lucisv_server` | clean (never `--all`); `--check` clean at the end |
| `cargo clippy --all-targets` | clean, no new `#[allow]` |
| `cargo test --workspace` | **3 829 passed, 0 failed, 44 ignored** — baseline 3 814, **+15** (14 unit tests in `tests/reexports.rs`, 1 e2e) |
| `tools/corpus_check.sh corpus` | **814/820 (99.3%)**, the same six parse errors; `corpus-check-results.tsv` unmodified in `git status` |
| formatter byte-identity | `format --stdout` of all **860** corpus files, this build vs `~/.cache/lucisv-baselines/lucisv-0.44.0`: **0 differ** |
| `cargo build --release -p lucisv_server` + smoke | OK — the release server answers `definition` on a name reached through `export b_pkg::x;` in a three-file scratch workspace |
| semantic corpus census | 860 files, 27 486 symbols, **103 875** references, 1 197 unresolved, **0 unplaced** (delta above) |
| opentitan `definition` through a re-export | **before `[]`, after the declaration** — see below |
Largest resident set observed by the guard: nothing came near the 8 GB limit,
and no command was killed.
### opentitan (read-only, scratch index store)
The tree does have real package re-exports, so the check was run rather than
skipped:
- `hw/ip/spi_device/rtl/spi_device_pkg.sv:425-451` — eight (QA's count; the work log first said nine)
`export spi_device_reg_pkg::<name>;` lines, each beside its `import`
- `hw/top_englishbreakfast/ip_autogen/flash_ctrl/rtl/flash_ctrl_top_specific_pkg.sv:12-18`
— seven `export flash_ctrl_pkg::<name>;` lines
- `hw/ip/spi_host/dv/env/spi_host_env_pkg.sv:21` — one, used by
`hw/ip/spi_host/dv/tb.sv:31` (added at review from QA's inventory)
- `hw/dv/sv/csr_utils/csr_utils_pkg.sv:10` — the two-path line the corpus copy
also holds
**The probe.** `hw/ip/spi_device/pre_dv/program/prog_passthrough_sw.sv:205`
writes `spi_device_pkg::SramDepth`, and `SramDepth` is declared in
`spi_device_reg_pkg.sv:10` and reaches `spi_device_pkg` only through
`spi_device_pkg.sv:451`'s `export`. One server session per binary, root
`hw/ip/spi_device`, `index.scope: "workspace"`, `initializationOptions.storagePath`
pointed at a scratch directory, one read-only `didOpen`, one
`textDocument/definition` at line 205 char 52:
| build | answer |
|---|---|
| before (this tree with `FileFacts::reexports` emptied, release) | `[]` |
| after (this tree, release) | `spi_device_reg_pkg.sv`, LSP range line 9 chars 25–34 — i.e. `SramDepth` on line 10, the declaration |
The "before" binary was produced by temporarily emptying the record's re-export
list and rebuilding, then restoring it and rebuilding again; `git diff` of
`record.rs` afterwards shows only this round's intended change, and the tree was
never checked out, reset or stashed. `git -C ~/repo/opentitan status --porcelain`
showed only the three pre-existing modifications (`hw/ip/aes/dv/tb/tb.sv`,
`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`)
before and after. Probe script:
`<scratchpad>/defprobe.py`.
### File sizes after the round
`reexport.rs` 189, `external.rs` 301 → 346, `index.rs` 521 → 525, `mod.rs`
340 → 349, `record.rs` 558 → 566, `update.rs` 397 → 421, `bind/item.rs`
555 → 590, `facts.rs` 733 → 760 (all raw line counts, comments included).
Nothing crossed 600; the new machinery went in the new module, as the brief
asked.
## QA log
**2026-09-05 — QA (Sonnet).**
Read the plan (TODO §48), the feature README in full, and the diffs of every
file it lists plus `crates/lucisv_server/tests/e2e.rs`. Built
`cargo build --release -p lucisv -p lucisv_server` once. Every suite run and
every server session below went through `tools/guard.sh`; no guard kill.
Attacked the two stated deviations (`Target::Package`, `*::*` expanded at
record time) directly by reading `bind_export_path` against `bind_import_path`
and `reexport::of`/`exports_of` line by line — both match the README's
justification and produce the documented behavior.
**Gates.**
| gate | result |
|---|---|
| `cargo clippy --all-targets` | clean, no new `#[allow]` |
| `tools/guard.sh -- cargo test --workspace` | **3 829 passed, 0 failed, 44 ignored** — matches the dev's number exactly, both before and after my scratch files were removed |
| `tools/guard.sh -- tools/corpus_check.sh corpus` | **814/820 (99.3%)**, same six parse errors; `corpus-check-results.tsv` untouched in `git status` |
| formatter byte-identity vs `~/.cache/lucisv-baselines/lucisv-0.44.0` | 860/860 corpus files, **0 differ** (script wrapped in `tools/guard.sh`) |
| semantic corpus census (`cargo test -p vlog_semantic --test corpus -- --nocapture`) | **860 files, 27 486 symbols, 103 875 references, 1 197 unresolved, 0 unplaced** — exact match |
| census delta grep | confirmed by hand: `corpus/ibex/dv/uvm/core_ibex/common/ibex_mem_intf_agent/ibex_mem_intf_agent_pkg.sv:28` (`export ibex_mem_intf_pkg::*;`, 1 name — the package half) and `corpus/ibex/vendor/lowrisc_ip/dv/sv/csr_utils/csr_utils_pkg.sv:10` (two paths, 4 names) sum to exactly **+5**; the corpus's other 9 `export` lines are all `"DPI-C"` (confirmed by grep), unchanged |
**Attack 1 — the three-file shape, wire-level (`tests/reexports.rs`, the dev's
`e2e.rs` test, and two temporary tests of my own added to `e2e.rs` and removed
after).** The dev's 14 unit tests and the one e2e test all pass and were read
line-by-line, not just run: they cover single-name, `pkg::*`, `*::*` (with and
without a same-named import), a chain, a two-package cycle, an undeclared
name, local-beats-reexported, and the reference-posting/rename fan-out
(`export` line rewritten, package half untouched implicitly since it is a
different reference). Two gaps I closed with temporary `#[test]`s in
`e2e.rs` (run, confirmed, then deleted — `git diff` on that file is exactly
the dev's 145-line addition again):
- A bare re-exported-but-not-imported name inside the exporting package stays
unresolved **over the real wire**, and a rename of the source declaration
edits **exactly one** site in the exporting file — the `export` line's item
half, column 16 — never the bare use (still `NotFound`) and never the
package half (column 9, a different reference entirely).
- `export *::*;` with **no** `import` beside it offers nothing in completion
and resolves nothing in definition — the negative half of the dev's own
`an_export_of_everything_reexports_what_the_package_imports` unit test,
confirmed again over the wire.
**Attack 2 — chains, cycles, negatives (12 temporary tests in a new
`crates/vlog_semantic/tests/qa_reexport_attack.rs`, run then deleted).** All
12 passed on the first try — no findings:
- three-package cycle (a→b→c→a via `*`), terminates and answers correctly;
- self re-export of an undeclared name (`export a_pkg::thing;` inside
`a_pkg`) terminates in <2 s and stays unresolved — the visited set seeds
itself with `unit`, so the one-hop-back edge is dropped without a second
lookup;
- self re-export of a name the package **does** declare is indistinguishable
from an ordinary local declaration, because `own_chain` (tried first) wins
before the reexport hop is ever asked;
- re-export of a nonexistent package: unresolved, no panic;
- a package that only **imports** a name (no `export` line at all) does not
leak it — `offered()` is empty, matching §26.6 and the README's stated
assumption;
- duplicate `export b_pkg::x;` lines: the edge table dedupes to one listed
name, but **both** source lines remain real references (`references_to`
finds both) — correct, since dedup lives in `reexport::add`, not in the
binder;
- 50 packages in a straight re-export chain: build + lookup in **2.7 ms**
— no accidental quadratic walk;
- two packages both re-exporting the same name into a third: no panic, one
deterministic answer (whichever edge the BFS queue reaches first, which is
file order — not specified by the plan but not undefined either, and
`members_of_chain`'s dedup-by-first-hit makes the listing agree with the
lookup);
- a DPI export beside a package export inside the same package body
contributes no edge to the reexport table (the split arm in `bind/item.rs`
holds);
- **incremental**: editing the *declaring* package (`b_pkg`, not the
exporter) to drop the re-exported name unresolves `a_pkg::x` on the very
next lookup with only `b.sv` touched — `Affected::exporters` is keyed by
the exporter for good reason, and nothing else needed to invalidate for
this case to work; and adding a fresh `export` line to a package that had
none is visible on the very next lookup, no separate rebuild step.
**Attack 3 — incremental,** covered above and by the dev's own
`an_update_and_a_build_agree_on_the_reexport_table` (read and re-run).
**Attack 4 — the `FACTS_FORMAT` 18 bump, for real, not just the existing unit
test.** Built the real `v0.44.0` server in a worktree
(`git worktree add … v0.44.0`, removed after). Ran it against a fresh 3-file
scratch workspace (`b_pkg` declares `x`; `a_pkg` does `export b_pkg::x;`;
`top.sv` does `import a_pkg::*` and uses both the bare and qualified form),
`initializationOptions.storagePath` pointed at a scratch dir:
- 0.44.0, cold: `scan finished: 3 files (0 skipped, 0 from cache)`,
`definition` on `a_pkg::x` → `[]` (matches the README's "before").
Store header afterward: `lucisv-index-cache 2 17 0.44.0`.
- 0.44.0 again, same store: `3 from cache` — sanity that the store format
itself round-trips for the version that wrote it.
- **New server, same (format-17) store**: `scan finished: 3 files (0 skipped,
**0** from cache)` — dropped whole, not misread, exactly as
`index_cache.rs`'s module doc promises (silent, not logged as an error;
the "0 from cache" `--verbose` timing line is the observable). `definition`
now correctly lands on `b_pkg.sv`'s declaration. Store header rewritten to
`lucisv-index-cache 2 18 …`; `RX 1` appears for `a.sv`, `RX 0` for the
other two.
- **New server again, same (now format-18) store**: `3 from cache` — the
round trip holds, same correct answer, `RX` group intact.
**Attack 5 — census,** re-run and cross-checked by hand above; matches
exactly.
**Attack 6 — opentitan, read-only, scratch stores throughout.** Enumerated
every `^\s*export ` line under `hw/` myself rather than trusting the dev's
inventory, and found it **incomplete**: `hw/ip/spi_device/rtl/spi_device_pkg.sv`
has **8** `export spi_device_reg_pkg::<name>;` lines (425, 431, 433, 435, 437,
439, 441, 451), not the nine the dev's work log states, and the dev's list
omits `hw/ip/spi_host/dv/env/spi_host_env_pkg.sv:21`
(`export spi_host_env_cfg_pkg::SPI_HOST_NUM_CS;`) entirely — see **findings**
below. Both are documentation-accuracy issues in the work log, not behavior
bugs; I tested the missed file anyway.
- **Reproduced the dev's own probe with the real `v0.44.0` binary** (not the
dev's "emptied-`reexports`-field" stand-in): root `hw/ip/spi_device`,
`prog_passthrough_sw.sv:205` char 52 — real 0.44.0 → `[]`; new server, same
workspace → `spi_device_reg_pkg.sv` line 9 chars 25–34 (`SramDepth`'s
declaration). Exact match to the dev's claim.
- **Every other real-world re-export site**, new server only (all correct,
real UVM/DV code, not synthetic):
- `hw/ip/spi_host/dv/tb.sv:31` — bare `SPI_HOST_NUM_CS` under
`import spi_host_env_pkg::*` → `spi_host_env_cfg_pkg.sv:7`, the real
declaration, through the exact chain the missed inventory entry describes.
- `hw/top_englishbreakfast/ip_autogen/flash_ctrl/rtl/flash_ctrl_lcmgr.sv:56`
— bare `NumSeeds` under `import flash_ctrl_top_specific_pkg::*` →
`hw/ip/flash_ctrl/rtl/flash_ctrl_pkg.sv:10`, across two disjoint top-level
`hw/` subtrees (root had to be the whole `hw/`, 3 976 files, 182 s to
scan — well inside the guard's defaults, no kill).
- `hw/vendor/.../ibex_mem_intf_agent/ibex_mem_intf_agent_pkg.sv:28`
(`export ibex_mem_intf_pkg::*;`) — completion after
`ibex_mem_intf_agent_pkg::` in a synthetic **in-memory-only** overlay
buffer (a `didOpen` at a URI under the read-only tree that was never
saved, so nothing touched disk) lists exactly `ibex_mem_intf_pkg`'s five
members plus the package's own local `ibex_mem_intf_request_sequencer`
and `rw_e` — and none of `uvm_pkg`/`mem_model_pkg`/`ibex_cosim_agent_pkg`,
which that package only imports, never re-exports. Definition on
`DATA_WIDTH` through the same path lands on `ibex_mem_intf_pkg.sv`.
- `hw/dv/sv/csr_utils/csr_utils_pkg.sv:10` — both `csr_field_t` and
`decode_csr_or_field` (the export line's own item halves) resolve to
`dv_base_reg_pkg.sv`.
- **30 random `pkg::name` positions**, old vs new server, same workspace
(`hw/ip/spi_device`, 64 files): first pass (no file opened) was a false
start — this server needs the target file **open** for `definition` to
answer at all, old or new, so I reran with the 8 distinct files in the
sample opened first. **29 of 29 usable positions** (one sample line fell
outside `.sv`/`.svh` and was dropped) answered **identically** between
0.44.0 and the new build but one: `spi_device_pkg.sv:433`
(`export spi_device_reg_pkg::SramPayloadDepth;`) — old `[]`, new resolves to
`spi_device_reg_pkg.sv`. That is the export line's own item reference,
exactly the new capability `bind_export_path` adds — not a regression, the
feature working as designed on real code outside the corpus. No other
position moved.
- `git -C ~/repo/opentitan status --porcelain` before and after every session:
only the three pre-existing modifications
(`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/ast.sv`,
`hw/top_earlgrey/ip/ast/rtl/ast.sv`).
**Attack 7 — formatter byte-identity,** covered in the gates table; the
`ExportDecl::Package`/`Dpi` arm split changes no formatting.
### Findings
- **LOW — doc accuracy, `docs/features/package-reexports/README.md` Work
log, "opentitan" section.** States "nine `export spi_device_reg_pkg::…;`
lines" for `hw/ip/spi_device/rtl/spi_device_pkg.sv`; there are 8
(lines 425, 431, 433, 435, 437, 439, 441, 451 — verified by
`grep -c '^\s*export spi_device_reg_pkg::'`). Off-by-one in the write-up
only; every one of the 8 resolves correctly (checked above).
- **LOW — doc completeness, same section.** The inventory of real package
`export` lines under `hw/` omits
`hw/ip/spi_host/dv/env/spi_host_env_pkg.sv:21`
(`export spi_host_env_cfg_pkg::SPI_HOST_NUM_CS;`), a genuine re-export used
by real code (`hw/ip/spi_host/dv/tb.sv:31`, bare `SPI_HOST_NUM_CS` through
`import spi_host_env_pkg::*`). Tested directly above — resolves correctly —
so this is a documentation gap, not a functional one.
- No MEDIUM or HIGH findings. No panic, no corruption, no idempotency
violation, no incorrect resolution, no regression in any of the attacks
above, across both a synthetic scratch workspace and ~4 000 files of real
read-only opentitan RTL/DV code.
### Verdict
**PASS.** The two findings above are both LOW (documentation accuracy in the
feature README's Work log, not in the shipped behavior) and do not block
merge; the lead may want the dev to fix the "nine" → "eight" count and add
the missed `spi_host_env_pkg.sv` line to the inventory, but nothing about the
binding, the resolution walk, the incremental update, the on-disk format
bump, or the formatter needs rework.
## Review
## Review
**2026-09-05 — lead.** Accepted; ships in 0.45.0 with §47 and §49. Both
halves of the plan are the ruled ones and the two deviations are right:
`Target::Package` is what the import half already records, and expanding
`export *::*` into the package's own imports at record time is the honest
encoding of §26.6 — a stored flag would have had no reader. The walk is
two layers deep by construction (`own_chain` at every hop, never back into
`member_chain`) with a visited set seeded on the starting unit, and QA's
cycles, 50-package chain (2.7 ms) and self re-export all terminate. The
store bump was verified against a genuine 0.44.0-written store. The census
moved by exactly the five references the corpus's two package export lines
carry. On opentitan a real gap closed: `spi_device_pkg::SramDepth` is
reached only through a re-export and now resolves, with the four further
sites QA found all correct. The two doc counts QA caught are corrected
above.
+4 -2
View File
@@ -102,7 +102,8 @@ the last two shapes in that sweep that were grammar work rather than
before-type spelling has behaved this way since the delay was first
parsed — and the new position inherits it unchanged. Recorded as a `#SKIP`
case in `net_delay_position.cases`, not fixed: giving the delay a comment
slot is a `comment-slots` change. The other gaps around a delay (an
slot is a `comment-slots` change. **Closed by walk-cycles (TODO §43.2),
2026-09-05:** `NetDelay::{before_hash, after_hash}`; the `#SKIP` is live. The other gaps around a delay (an
attribute in front of the declaration, a comment after the delay) do
round-trip.
@@ -151,7 +152,8 @@ the last two shapes in that sweep that were grammar work rather than
- **`comment-slots`**: a net delay has no slot for the comment written
immediately in front of its `#`, so such a file is refused by the safety
net rather than reformatted. Pre-existing, both positions, recorded as a
`#SKIP` case (see Assumptions).
`#SKIP` case (see Assumptions). **Answered by walk-cycles (TODO §43.2),
2026-09-05.**
## Status / TODO
+4 -2
View File
@@ -225,8 +225,10 @@ TODO §2 `--lines`), `completion`, `rename`, `signatureHelp`, and cross-file
capability's kinds on the wire, quick fixes + fixAll, and a filtered
fix-on-save request.
- [x] `docs/features/lucisv-server/README.md` deferred list annotated.
- [ ] **Not done, deliberately:** rule selection. No `lucisv.toml` `lint` key
exists (Handshake 2); the server runs `default_rules()`.
- [x] ~~**Not done, deliberately:** rule selection. No `lucisv.toml` `lint` key
exists (Handshake 2); the server runs `default_rules()`.~~ Delivered by
**linter-expansion-1** (editor toggles, 0.36.x) and **lint-config-contract**
(project `[lint] select/ignore`, TODO §42, 0.43.0).
- [ ] **Not done, deliberately:** offering Unsafe fixes. No rule ships one, and
when one does it wants a decision (a separate `source.fixAll` kind? a
client setting?), not a silent inclusion.
+565
View File
@@ -0,0 +1,565 @@
# small items, round 4
## Goal
Four items that belong to no larger feature, shipped together (TODO §45,
release 0.44.0). Each closes an open handshake in `docs/topo.md` §2.9.
**45.1 — the editor's unknown rule name is said once (topo 29).** A name in
`lucisv.lint.select` / `lucisv.lint.ignore` that the registry does not know was
dropped in silence (`settings::rules` filtered it away), while the same typo in
a `lucisv.toml`'s `[lint] select` has been logged since §42 and
`lucisv.lint.options` has described its own bad entries since §34. The name is
still dropped — a typo on a socket must not cost a session its diagnostics —
and is now logged through `server/notification.rs` as
`lucisv.lint.select: unknown rule: <name>`, **once** per (setting, name),
re-armed only when the list changes. A `select` emptied by the dropping falls
through §42's ladder exactly as before.
**45.2 — a warning channel for the walk (topo 30).** `Walk::dir` propagated
`read_dir`'s error with `?`, so one permission-denied directory anywhere under
the start dropped every file already found and failed the run — walk-cycles'
QA found it on a link to `/`. `lucisv_core::walk::collect_files` now takes a
`&mut dyn FnMut(Warning)` sink: an unreadable directory, an unreadable
`.gitignore` and a source file that is only a broken link are each said once
and skipped, and the walk goes on. The CLI writes `warning: <path>: <message>`
to stderr before the report and changes no exit code; the server folds them
into the scope's own warnings, which are logged once per scan. The dangling
source link is **no longer handed on** — that reverses §43's review ruling on
purpose, because the warning is now the error's home.
**45.3 — an inline aggregate as a parameter-override argument (topo 17).**
`m #(.T(struct packed { logic a; })) u ();` was rejected: `parse_expr_or_type`
routed a value to `parse_type_expr` only for a head in `TYPE_KEYWORDS`, and
`struct`/`union`/`enum` are not in that table, so the value read as an
expression and hit "unexpected keyword `struct` in expression".
`parse_type_ref` had read that body since the first day and the type printer
had printed it; only the door was shut. With it open,
`vlog_refactor::instantiation_plan` stops dropping a one-line `parameter type`
default that is an anonymous aggregate — its probe simply passes now — and
emits the type text.
**45.4 — comment slots inside a delay list (topo 22's leftovers).**
`parse_delay_values` serves `#(1:2:3)` on nets and continuous assignments and
`#(rise, fall[, turn-off])` on gates. The gaps around the `(`, the two `:` and
the `,` had no owner, so a comment written in one moved and `verify.rs` refused
the file. They have owners now — `MinTypMaxComments`, `DelayValue`, the gate's
`before_hash`/`after_hash`/`before_semi`, the gate instance's `before_args`,
and the continuous assignment's `after_hash`/`after_delay` — and the RTL gap
fuzzer's fixture set covers the construct at zero failures.
## Assumptions
- **45.1** — the memo is the *previous settings value's own warning list*, so
"once per (setting, name)" and "re-armed when the setting changes" are one
mechanism rather than two. A list edited from `[a]` to `[a, b]` says only
`b`; cleared and re-typed, it says everything again. Both lists hold a
handful of entries at most, so a linear scan beats a set.
- **45.1** — the options warnings keep their old behaviour (raised every time
the setting arrives). They are a different field for that reason; merging the
two vectors would have quietly changed §34's contract.
- **45.2** — a dangling link that does **not** name a source file stays silent.
It was never going to be read, and warning about every broken link in a tree
is noise, not information. The `walk.rs` test pins both halves.
- **45.2** — a path the user names on the command line is not walked, so
naming a dangling link directly is still `no such file or directory`, exit 2.
The channel is about what the *walk* finds.
- **45.2** — an unreadable `.gitignore` used to abort the run too; it is now a
warning on the same channel. That is one step beyond the plan's wording and
is the same judgement: a walk that finds too much is a better failure than a
walk that finds nothing.
- **45.2** — `Warning`'s `message` is the operating system's own words, except
for a broken symbolic link, which is named as one (`symlink_metadata` says
so) because `No such file or directory` reads as a lucisv bug there.
- **45.3** — an aggregate head in expression position is *always* a type. No
legal expression starts with `struct`, `union` or `enum`, so the new arm in
`parse_expr_or_type` cannot take a value away from the expression grammar.
It opens the same door for `$bits(struct packed {…})`, a stream slice size
and an assignment-pattern key, all of which reach `parse_expr_or_type` too.
- **45.3** — the aggregate prints through the existing type printer, so a
`struct`/`union` body opens across lines exactly as it does in a declaration
and an `enum` body stays inline. Nothing was laid out specially for the
override list.
- **45.4** — a comment inside a bracket pair forces that pair open. That has
been true since comment-slots; the one-value `#( /*c*/ 1:2:3 )` case in
`delay_comment_slots.cases` is a fixed point at that layout for that reason.
- **45.4** — `Expr` stays at 96 bytes: `MinTypMaxComments` is boxed, as every
expression-level slot is (`ast/mod.rs`'s size assertion is the check).
- **45.4** — the empty case costs nothing. Every new slot is printed through
`Fmt::slot_comments` or an `is_empty()` match that emits the space the old
code emitted, which is what the corpus and opentitan byte-identity runs below
measure.
## Handshakes
**Consumed, unchanged.** `Parser::{take_gap, gap_before, take_before_open,
take_meta, take_before_sep}` — every new slot is built from them, on
comment-slots' rule that a gap belongs to a construct only when the token that
closes it was written. `Fmt::{slot_comments, inline_comments,
inline_comments_spaced, semi, trailing}` likewise. `verify.rs` untouched and
no normalization widened; ten new attack pairs ship anyway (CLAUDE.md
invariant 4).
**Promised / changed.** All additive except where marked.
| node / API | change | note |
|---|---|---|
| `lucisv_core::walk::Warning` | new | `{ path, message }`, `Display` as `<path>: <message>` |
| `lucisv_core::walk::collect_files` | **signature**: fifth parameter `&mut dyn FnMut(Warning)` | two callers, one line each |
| `ExprKind::MinTypMax` | `comments: Box<MinTypMaxComments>` | four slots, two `:` |
| `ContAssign` | `after_hash`, `after_delay` | `assign # /*a*/ (5) /*b*/ y = x;` |
| `GateInstantiation` | `before_hash`, `after_hash`, `before_semi`; `delay: Vec<Expr>` → `Vec<DelayValue>` | **changed field type** |
| `GateInstance` | `before_args` | `g1 /*c*/ (y, a)` |
| `ast::DelayValue` | new | `{ leading, expr, trailing }` — the `(`, `,` and `)` slots of a multi-value list |
| `settings::ClientSettings` | `lint_name_warnings: Vec<String>` | one line per unknown name |
| `settings::rules` | **signature**: takes the setting's name and a warning sink | private to the module |
| `Server::said_lint_names` | new field | §45.1's memo |
| `Workspace::{walked_files, folder_files, default_files, widened_files}` | **signature**: each takes `&mut dyn FnMut(String)` | private to `state.rs` |
Why a **sink** and not a `Walked { files, warnings }` return: both callers
accumulate into a `&mut Vec<PathBuf>` across a loop over their inputs — the
CLI over `opts.inputs`, the server over its scope directories — so a struct
return would have made each of them merge two vectors per iteration and give
up the accumulator idiom. With the sink each call site is one changed line:
the CLI adds `&mut |w| eprintln!("warning: {w}")`, the server adds
`&mut |w| warn(w.to_string())` onto the scope warnings it already collects.
**Requests filed.** None. Nothing outside this round's own file set was
edited.
## Docs to apply at merge (lead)
`docs/topo.md` §2.9 — four rows:
- **Row 17** (inline aggregate as a parameter-override argument) — strike, and
append: *— **delivered 2026-09-05 by small-items-4 (TODO §45.3)**:
`parse_expr_or_type` routes a `struct`/`union`/`enum` head to
`parse_type_expr`, which `parse_type_ref` has been able to read since the
first day; the value is an `ExprKind::Type` printed by the existing type
printer (a struct or union body opens, an enum body stays inline). The same
door opens for the four other callers of `parse_expr_or_type` — `$bits(…)`,
a stream slice size, an assignment-pattern key and an ordered override.
`vlog_refactor`'s `default_text` probe now passes such a default and
`instantiation_plan` emits the type text; only the **multi-line** spelling
(`common_cells/src/ecc_encode.sv`) is still dropped, and by the
"written across several lines" rule rather than by the grammar. Corpus (860)
and opentitan (3 947) byte-identical.*
- **Row 22** (comment slots in shared machinery, already struck) — append to
its delivered note: *A fifth fuzzer bar was added 2026-09-05 by
small-items-4 (TODO §45.4): the **delay list** — `#(1:2:3)` on nets and
continuous assignments, `#(rise, fall)` on gates — gained
`MinTypMaxComments` (four slots, one grammar shared with the parenthesized
`(a:b:c)` expression), `ast::DelayValue` for the multi-value list's `(`, `,`
and `)`, and `ContAssign::{after_hash, after_delay}`,
`GateInstantiation::{before_hash, after_hash, before_semi}`,
`GateInstance::before_args`. `EXPECTED_RTL_GAPS` 374 → 419, still at zero
failures.*
- **Row 29** (the editor's unknown rule name) — strike, and append:
*— **delivered 2026-09-05 by small-items-4 (TODO §45.1)**:
`settings::rules` describes every dropped name into
`ClientSettings::lint_name_warnings` as
`lucisv.lint.<select|ignore>: unknown rule: <name>`, and `apply_settings`
logs what `Server::said_lint_names` — the previous settings value's own
warning list — does not already hold. Once per (setting, name); a
`didChangeConfiguration` that changes the list re-arms exactly what is new in
it; four diagnostics passes add nothing. The dropping itself, and §42's
ladder under an emptied `select`, are unchanged.*
- **Row 30** (an unreadable directory aborts the whole walk) — strike, and
append: *— **delivered 2026-09-05 by small-items-4 (TODO §45.2)**:
`walk::collect_files` takes a `&mut dyn FnMut(Warning)` sink (`Warning
{ path, message }`), chosen over a `Walked { files, warnings }` return
because both callers accumulate into a `&mut Vec<PathBuf>` across a loop and
a struct return would have cost each of them a merge per input. An unreadable
directory, an unreadable `.gitignore` and a dangling **source-file** link are
each said once and skipped; the walk finishes. CLI: `warning: <path>:
<message>` on stderr before the report, exit code unchanged. Server: the
warnings join the scope's own and are logged once per scan through
`report_scope`. §43's review ruling that a dangling source link is handed on
to fail in the front end is **reversed** — the warning is the error's home
now. A dangling link that names no source file is still skipped silently.*
Also worth a line in `README.md` where the walk is described, if it says a
walk fails on an unreadable directory: it warns and continues now.
## Status / TODO
- [x] 45.1 editor unknown-name log (`settings.rs`, `server/notification.rs`,
`server/mod.rs`, `server/tests/settings.rs`)
- [x] 45.2 walk warning channel, both front ends (`lucisv_core/src/walk.rs`,
`lucisv/src/main.rs`, `lucisv/tests/cli.rs`,
`lucisv_server/src/state.rs`)
- [x] 45.3 inline aggregate override argument + plan emission
(`parser/primary.rs`, `parser/tests/instance.rs`,
`vlog_refactor/src/instantiate.rs`, `tests/cases/instantiation.cases`)
- [x] 45.4 delay-list comment slots + fuzzer coverage (`ast/expr.rs`,
`ast/module.rs`, `parser/instance.rs`, `format/expr.rs`,
`format/instance.rs`, `format/item.rs`,
`tests/cases/delay_comment_slots.cases`, `tests/verification.rs`)
- [x] Gates (guarded): fmt, clippy, `cargo test --workspace`, corpus,
byte-identity, smoke, the hostile-tree CLI run
- [ ] docs: topo 29/30/17/22 struck (lead — text above)
- [x] QA (2026-09-05 — REWORK, one MEDIUM finding; see QA log)
## Work log
### 2026-09-05 — dev (Fable 5.1)
**45.3 first, because it was one line of grammar.** `parse_expr_or_type`
(`parser/primary.rs`) checked `TYPE_KEYWORDS`, which holds the *integral and
non-integral* type keywords only. `struct`, `union` and `enum` are keywords
too and `parse_type_ref` already dispatches all three to `parse_struct_type` /
`parse_enum_type`, so the fix is a second arm in front of the existing one. No
legal expression begins with one of those words, so the arm cannot take a
value away from the expression grammar; the previous behaviour was
"unexpected keyword `struct` in expression".
Nothing else was needed for the plan's second half. `default_text` in
`vlog_refactor/src/instantiate.rs` already *probes* — it writes
`m #(.P( <default> )) u ();` and asks the tolerant parser — so a one-line
aggregate default started being emitted the moment the grammar accepted it.
The doc comment there claimed the grammar was the reason such a default was
dropped; it now says the probe is the rule and that the multi-line spelling is
what is still refused, by the other rule above it. Test added.
**45.4 was measured, not guessed.** The candidate fixture went into
`RTL_FIXTURES` first and the fuzzer named 23 failing gaps. Fixing them meant
one new expression-level slot (`MinTypMaxComments`, boxed) and one new list
shape:
- `parse_delay_values` now returns `Vec<DelayValue>` (`{ leading, expr,
trailing }`). The **one-value** spelling still folds into the
`ExprKind::Paren` it always produced, and the paren's existing `before` /
`after` slots are exactly where the `#( … )` gaps go — so nets and continuous
assignments needed no new node at all. Only the gate's multi-value list, whose
parentheses and commas the *printer* writes, needed somewhere to put them.
- The two `min : typ : max` grammars — the delay list's and the parenthesized
expression's in `parser/primary.rs` — were folded into
`Parser::parse_min_typ_max_tail`, so the four colon slots exist in both. That
is the same "three duplicated grammars folded into one" move comment-slots
made.
- The gate instantiation had four gaps of its own with no owner once the delay
had slots: before the `#`, after the `#`, before an instance's `(`, and
before the `;`. `GateInstance::meta` was parsed but never printed, so the
gap in front of an instance name is now printed too, along with the
element's `before_sep` / `trailing` around the `,` between two instances.
- `ContAssign` gained `after_hash` and `after_delay`. The second one matters:
a continuous assignment prints its first pair's leading comments straight
after the `assign` keyword, which is *in front of* the delay, so a comment
written after the delay had to be taken out of that path before `take_meta`
saw it.
`EXPECTED_RTL_GAPS` 374 → 419 with the reason on the constant and on the
fixture. Six cases in a new `delay_comment_slots.cases`, plus five attack
pairs in `verification.rs`, one per token a new slot sits beside.
**45.2 — the channel shape.** `&mut dyn FnMut(Warning)`, not `Walked { files,
warnings }`. Both callers of `collect_files` accumulate into a `&mut
Vec<PathBuf>` across a loop over their own inputs, so a struct return would
have replaced one line with three at each of them and given up the accumulator
the signature is built around. With the sink each call site is one changed
line. Inside the crate, `Walk::dir` lost its `io::Result` entirely and split
into `dir` (enter, push the ignore stack, pop it) and `entries` (read and
recurse), which keeps both under twenty lines.
The reversal is deliberate and is the plan's: a dangling **source-file** link
is warned about and **not** pushed into `files`. §43's review had kept it in
the list so the front end's `no such file` error survived; the warning is that
error's home now, and it says something the old path could not — that the file
is a broken link rather than absent. The walk.rs test and its comment were
rewritten to say so. A dangling link that names no source file is still
skipped in silence; it was never going to be read.
Server plumbing: `walked_files` / `folder_files` / `default_files` /
`widened_files` each take the sink, and `source_files` collects into the
`Scope::warnings` that already existed for a filelist's problems. That road
ends at `report_scope`, which logs each line once per scan and shows the first
one — the same treatment a filelist's warnings have always had. **Deviation
from the plan's letter:** the plan said "through `notification.rs`"; the scan
warnings' channel is `server/client.rs`'s `report_scope`, called from
`server/index.rs` and `server/mod.rs` where a scan finishes. Inventing a second
road for the same class of message would have been worse than using the one
that exists. "Once per scan" holds.
**45.1 — the memo.** `settings::rules` takes the setting's name and a warning
sink and describes each dropped name; the lines land in a new
`ClientSettings::lint_name_warnings`, kept separate from
`lint_option_warnings` because the two are said differently. `apply_settings`
logs the lines `Server::said_lint_names` does not hold and then replaces that
memo with the current list — which is the whole of "once per (setting, name),
re-armed when the setting changes". The options warnings' behaviour is
untouched.
**Gates, all guarded.** `cargo fmt` per touched crate and `cargo fmt --all --
--check` clean; `cargo clippy --all-targets` clean; `cargo test --workspace`
**3 810 passed, 0 failed, 44 ignored** (baseline 3 788 — 22 new tests);
`tools/corpus_check.sh` **814/820**, the same six errors, no verification error
and no crash; byte-identity against the trunk binary (built from `git archive
HEAD` into the scratchpad, never a checkout in this tree) **860 corpus files,
0 diffs** and **3 947 opentitan files, 0 diffs**, with the same 6 and 9 errors
either side; `node editors/vscode/smoke.js target/release/lucisv-server` OK;
and `target/release/lucisv format --check` over a scratch tree with a `0o000`
subdirectory and a dangling `x.sv` link printed exactly two `warning:` lines on
stderr before the report, reported the other files, and exited 1 on the
formatting alone. `git -C ~/repo/opentitan status --porcelain` shows only the
three pre-existing files.
**Files touched outside the plan's expected set.** Three, all forced by an AST
field the round added and each a mechanical pattern update:
`crates/vlog_semantic/src/bind/expr.rs` (a `..` in the `MinTypMax` arm),
`crates/vlog_semantic/src/bind/item.rs` (`&d.expr` for the gate delay) and
`crates/vlog_parser/tests/spans.rs` (both of the same). Nothing else in
`vlog_semantic` was changed.
### 2026-09-05 — lead, at review
QA's MEDIUM closed in the tree: a *line* comment trailing a gate instance's
`,` now ends the line and the next instance continues one level in
(`indent(vec![Doc::HardLine])`, the module-instantiation printer's rule); a
block comment there stays inline, as the dev's own case table expects. A
case in `net_delay_position.cases` pins the repro. The four topo rows are
applied.
## QA log
### 2026-09-05 — QA (Sonnet)
Build: `cargo build --release -p lucisv -p lucisv_server` clean, up to date
with the uncommitted tree at f302b47+.
**45.1 — the editor's unknown rule name.** Read `settings.rs`,
`server/notification.rs`, `server/mod.rs`, `server/tests/settings.rs` in
full; behaviour matches the README exactly (memo = previous settings
value's own warning list, `lint_option_warnings` untouched, severity words
never warned). Added a temporary wire-level test to `tests/e2e.rs`
(`talk`, framed JSON-RPC, real binary) driving: push `lucisv.lint.select:
["no-tab"]` → open → three `didChange`s each forced through a `flush_dirty`
by an interleaved `codeAction` request (four diagnostics passes total,
confirmed by counting `textDocument/publishDiagnostics`) → re-push the
identical list → push a second typo `nope` → push with the first typo
fixed. Result: exactly one `window/logMessage` `lucisv: lucisv.lint.select:
unknown rule: no-tab`, nothing across the four diagnostics passes or the
identical re-push, exactly one more line for `nope` when it was added,
nothing when the first typo was dropped from the list. Test removed after
passing (file `tests/e2e.rs` is unchanged, confirmed by `git diff`). Unit
tests already in the diff cover the `ignore` typo, an empty `select`
falling through §42's ladder with the rule set unchanged, and a severity
word (`style`, `warning`) never being reported — read and agree with all
three. No findings.
**45.2 — the walk's warning channel.** Read `walk.rs`, `main.rs`,
`tests/cli.rs`, `state.rs` diffs in full, plus `server/client.rs`'s
`report_scope` (unchanged — confirmed the "went through `client.rs` instead
of `notification.rs`" deviation is real and `report_scope` already does
"logged once per scan, one showMessage summary at most" for every existing
caller). Built eight hostile scratch trees under the scratchpad and ran the
CLI over each through `tools/guard.sh -t 120`:
- 0o000 subdirectory: warning on stderr before the report, `format --check`
on an already-clean tree exits **0** with the warning still printed
(the exact case TODO §45.2 calls out); `format --check` on a tree needing
a reformat exits 1 on the formatting alone; `format` (real reformat, on a
scratch copy) and `check` both warn and proceed, exit 0.
- dangling `x.sv` link: warned, dropped, not handed to the formatter.
- dangling link to a non-source name: silent, as specified.
- unreadable `.gitignore` (0o000): warned, directory still walked.
- a symlink cycle plus an unreadable directory in the same tree: no hang,
no crash, the unreadable directory is warned once and the rest of the
tree is reported.
- **the start directory itself unreadable (0o000)**: `path.is_dir()`
succeeds (stat needs only the parent's search bit), so the walk enters,
`read_dir` fails, one warning is printed naming the start directory, and
the run then fails with the CLI's ordinary `error: no Verilog files
found` at exit 2 — sensible, not a crash, not silent. Not covered by the
dev's own tests; recorded here since the plan asked "what happens?".
- an unreadable file `y.sv` (chmod 0o000, not a directory): reported once,
as the pre-existing per-file read error (`error: ...: Permission
denied`), *not* as a walk warning — confirmed not duplicated.
- 200 unreadable directories under one start: exactly 200 `warning:` lines,
the walk finishes, the one real file is still reported.
Server: adapted the existing `Session`/`Tree` test harness (as
`server/tests/*.rs` already does) into a temporary file
(`server/tests/qa_scratch_45.rs`, registered and later removed from
`server/tests/mod.rs`) to drive `Session::wide` over a tree with one 0o000
subdirectory: the warning is logged exactly once via `logged()`, at most
one `shown()` `window/showMessage` summary, and pushing a settings change
that forces `reindex` (`lucisv.index.maxFileSize` with `scope: "workspace"`
kept, mirroring `capping()` in `server/tests/index.rs`) logs the same
warning again exactly once. `server/tests/mod.rs` and the deleted scratch
file leave no diff (`git diff --stat` confirms only the intended lane
files changed). No findings.
**45.3 — inline aggregate override argument.** Manually formatted a file
covering `struct packed`, `union packed` (with two members), `enum`, a
`struct packed` with a comment inside, a nested `struct packed` inside a
`struct packed`, and the same aggregate as a **positional** override
(`m #(struct packed {logic a;}) u5 ();`) — all format correctly (struct/
union bodies open, enum stays inline, comment kept), round-trip is a fixed
point (`format(format(x)) == format(x)`, byte-for-byte), and the comment
survives. Confirmed the illegal expression-position case is unchanged and
safe: `assign x = struct packed { logic a; };` still fails with the
original `parse error: ... unexpected keyword \`struct\` in expression`
under both `format --check` and `format --stdout`, exit 2, no corruption —
`parse_expr` (assign's RHS) does not route through `parse_expr_or_type`, so
the new door stays shut there exactly as the Assumptions section claims.
Ran `vlog_refactor`'s new and neighboring tests directly
(`a_one_line_inline_aggregate_default_is_emitted`,
`a_multi_line_type_is_shown_on_one_line`): both green, confirming the
one-line default is now emitted and the multi-line one is still dropped, by
the "written across several lines" rule rather than the grammar. No
findings.
**45.4 — delay-list comment slots.** Read the fixture
(`delay_comment_slots.cases`) end to end against the `Promised / changed`
table in the Handshakes section: every new field
(`MinTypMaxComments`'s four slots, the one-value `Paren`'s two slots,
`ContAssign::{after_hash, after_delay}`,
`GateInstantiation::{before_hash, after_hash, before_semi}`,
`DelayValue::{leading, trailing}`, `GateInstance::before_args`, and
`GateInstance::meta.{before_sep, trailing}`) has at least one case, plus a
byte-cost-zero case and one line-comment case (the `min:typ:max` colon
only). Confirmed `EXPECTED_RTL_GAPS` 419 with the block-comment-per-gap
fuzzer at 0 failures (`cargo test -p vlog_formatter
a_comment_in_every_rtl_gap_still_formats`).
**Because the fuzzer and the fixture both probe with `/*block*/` comments
only, I attacked every new slot again by hand with `//line` comments** (the
plan explicitly asked for "line comments in each slot"). Seven of eight
were fine (`before_hash`, `after_hash`, `before_args`, `before_semi`, the
one-value delay's two `Paren` slots, `ContAssign::after_hash`,
`ContAssign::after_delay` all correctly force a hard line after a line
comment via `inline_comments_spaced`/`slot_comments`). The eighth is a
**real bug**:
> **FINDING (MEDIUM) — a line comment trailing a gate instance's `,`
> separator corrupts the rest of the statement into the comment; caught
> by `verify.rs`, so no bad file is ever written, but `lucisv format`
> hard-fails (exit 2) on legal, comment-bearing SystemVerilog that TODO
> §45.4 claims this round closes.**
>
> `crates/vlog_formatter/src/format/instance.rs:400-405` (the gate
> instantiation's multi-instance loop, only reached for `i < last`):
> ```rust
> docs.push(text(","));
> if let Some(tr) = &inst.meta.trailing {
> docs.push(text(" "));
> docs.push(self.comment(tr));
> }
> ```
> Nothing forces a line break after `tr` before the next iteration prints
> the following instance's `meta.leading` (a bare `text(" ")` when that is
> empty). When `tr` is a line comment, everything the next iteration emits
> lands on the same source line, and a line comment runs to end of line —
> so on re-lex the rest of the statement disappears into the comment.
> `verify.rs` sees the token-stream divergence and correctly refuses to
> write the file (invariant 1 upheld; nothing corrupted on disk); the
> failure mode is a hard error on valid input, not corrupted output.
>
> Repro:
> ```systemverilog
> module m;
> and #(2, 3) g0 (y, a), // p
> g1 (z, b);
> endmodule
> ```
> `target/release/lucisv format --stdout repro.sv` →
> `error: repro.sv: verification failed: token stream diverges at index 17:
> input has comment "// p" at 2:26, output has comment "// p g1 (z, b);" at
> 2:26`, exit 2. Reproduces with three instances too (the whole remainder,
> including a further `,`-separated instance, is swallowed).
>
> Contrast with the pre-existing, correct pattern four lines above this one
> in the same file (`format/instance.rs:64-74`, the *module*-instantiation
> multi-instance list), which already does the right thing:
> ```rust
> if let Some(tr) = &instance.meta.trailing {
> inner.push(text(" "));
> inner.push(self.comment(tr));
> if i < last { inner.push(Doc::HardLine); }
> } else if i < last { inner.push(Doc::Line); }
> ```
> The gate-instance printer added by 45.4 does not replicate the
> `i < last` hard-line-after-trailing-comment rule (or use
> `inline_comments_spaced`/`Fmt::trailing`, which both already know a line
> comment forces a break).
>
> Not caught by the dev's own attack tests or the RTL fuzzer because both
> only exercise the `before_sep`/`trailing` slot with **block** comments
> (`delay_comment_slots.cases`'s last case:
> `g0 (y, a) /* before */ , /* after */ g1 (z, b)`). Not a widened
> `verify.rs` forgiveness (invariant 4 does not apply — nothing in
> `verify.rs` changed), and not a dropped comment (invariant 3 holds —
> the whole file is refused, not partially emitted). Severity kept at
> MEDIUM rather than HIGH because of that: no corruption reaches disk,
> the blast radius is exactly this one slot/comment-kind combination, and
> the corpus and opentitan sweeps (neither of which contains this pattern)
> are unaffected — confirmed by the unchanged 814/820 and the byte-identity
> runs below.
>
> Suggested fix (for the dev, not applied here per QA's mandate not to
> redesign): either call `self.inline_comments_spaced` for the trailing
> comment instead of the raw `text(" ")` + `self.comment(tr)` pair (it
> already emits `Doc::HardLine` when the comment is a line comment), or
> mirror the module-instantiation loop's explicit `if i < last { push
> HardLine }` after the trailing comment.
**Byte-identity and gates (all guarded).**
- `cargo clippy --all-targets`: clean.
- `tools/guard.sh -- cargo test --workspace`: **3 810 passed, 0 failed, 44
ignored** — matches the dev's number exactly.
- `tools/guard.sh -- tools/corpus_check.sh`: **814/820**, same six parse
errors, 0 verification errors, 0 crashes.
- `node editors/vscode/smoke.js target/release/lucisv-server`: OK.
- Corpus byte-identity vs `~/.cache/lucisv-baselines/lucisv-0.43.0`:
compared `format --stdout` + exit code file by file over all **860**
corpus source files (not just the 820 `corpus_check.sh` reports on) —
**0 differing**.
- Opentitan `format --check` vs the same 0.43.0 baseline over `hw/ip`,
`hw/top_earlgrey/ip`, `hw/top_darjeeling/ip`, `hw/dv`, `hw/vendor`:
**2 553** source files (not the dev's 3 947 — a different, smaller
file-extension/glob accounting was used here; not investigated further
since exit codes and normalized stdout/stderr matched exactly either
way); every exit code identical, and every stderr line identical once
the baseline's incidental `, N files from cache` cache-hit annotation
(a pre-existing `.lucisv_cache/` in the opentitan tree, untracked,
gitignored, unaffected by which binary populated it) is stripped from
both sides — **0 behavioural differences**.
`git -C ~/repo/opentitan status --porcelain` after every run: only the
three pre-existing modified files (`hw/ip/aes/dv/tb/tb.sv`,
`hw/top_darjeeling/ip/ast/rtl/ast.sv`,
`hw/top_earlgrey/ip/ast/rtl/ast.sv`).
**Cleanup.** All scratch trees removed (permissions restored with
`chmod -R u+rwx` first). The two temporary test additions
(`tests/e2e.rs`, `server/tests/qa_scratch_45.rs` + its `mod.rs`
registration) were removed after use; `git diff --stat` shows no lane file
touched by this QA pass except this README and the TODO.md checkbox.
**Verdict: REWORK.** One finding, filed above:
- **MEDIUM** — `format/instance.rs:400-405`, a line comment trailing a
gate instance's `,` separator (`GateInstance::meta.trailing`, not the
last instance) corrupts the rest of the statement into the comment;
`verify.rs` catches it and refuses the file rather than writing bad
output, but `lucisv format` hard-fails on legal input the round claims
to support. Needs a fix plus a line-comment test in
`delay_comment_slots.cases` or `verification.rs` before this closes.
Everything else in 45.1, 45.2 and 45.3 checked out clean against the plan,
including the corners the plan called out by name (the start-directory
case, the 200-unreadable-directories case, the illegal-expression-position
case, severity words never warned, four diagnostics passes, a rescan
re-arming the server's log).
## Review
**2026-09-05 — lead.** Accepted with the rework above; ships in 0.44.0
with §46. Four small items, each the shape the plan asked for. The sink
choice for the walk (a closure over a struct return) is right for the
reason given — both callers accumulate across a loop — and routing the
server's scan warnings through the road filelist warnings already take,
rather than `notification.rs`, is the better reading of the plan. The §43
reversal (a dangling source link is warned about and not handed on) is now
correct because the warning has a home. QA's MEDIUM was a real formatter
refusal on legal input — the one class of bug the verifier exists to catch,
and it did — fixed at review with the rule the sibling printer already had.
Byte-identity: 0 of 860 corpus files and 0 of 3 947 opentitan files differ
from 0.43.0.
+453
View File
@@ -0,0 +1,453 @@
# Type-name spans
## Goal
TODO.md §47 / `docs/topo.md` §2.9-2. `vlog_semantic/src/scan.rs` (193 lines)
recovered the byte range of a name the AST kept only as a `String` by scanning
the construct's own source text. Every declared name got a real `name_span`
from the parser in the 2026-08-19 `name-spans` round; two *uses* did not, and
they were the module's only remaining callers — the type name of a declaration
(`DataType::name`, split as `pkg::item` or `iface.modport`) and `disable
<label>`.
This round puts both spans on the AST, deletes `scan.rs`, and has the binder
read what the parser already knew. A type reference is now located by
construction rather than by a text search that is only right in practice, and
the corpus census pin (`src[name_span] == name`) covers type-name references
for the first time.
## Assumptions
- **A name's span slices back to the name.** `DataType::name_span` is derived
as `name_start .. name_start + name.len()`, so it is exact for every name the
source spells the way the parser joined it. **Any** whitespace or comment
around a `::` or `.` separator (`pkg :: item`, `pkg /* c */ :: item`, a
name split across a line, `bus_if . mp`), an escaped segment terminated by
a newline rather than a space, and spacing inside a dotted `disable` target
spell the name differently from the AST's join (QA's census of the
spellings, 2026-09-05). The binder therefore checks every segment's span
against the source (`Binder::exact_or_empty`) before it records a
reference, which is the rule the modport tail has always followed: such a
segment is recorded with the **empty range at its start** — never a wrong
non-empty range, and never dropped, because an empty range is what the
corpus census counts as *unplaced*, so a parser regression in the join
trips that alarm (lead's rework of QA's MEDIUM). `scan.rs` failed the
same cases (its `find` matches whole words, so it never found `\a+b ` with
its trailing space either), so this is parity, not a new gap.
- **The token text of a plain identifier is its source text.** Pinned by the
lexer (`src[span] == text`, `an_escaped_identifier_ends_before_its_terminating_whitespace`).
Everything above rests on it.
- **`DataType::name_start` is only ever written by the parser.** It is
`pub(crate)` in `vlog_parser`; no other crate builds a `DataType` (grep:
the only `DataType { … }` literals in the workspace are the two in
`vlog_parser/src/parser/`).
- opentitan is read-only. The before/after sweep used the server's scratch
index store (`docs/performance_take3.md` §9) and
`git -C ~/repo/opentitan status --porcelain` reported only the three
pre-existing modified files before and after.
## Handshakes
**Consumed from `vlog_parser`:**
- `DataType::name_span() -> TextRange` — where the type name is written, the
empty range at the would-be position when the type is implicit.
- `DataType::segments() -> impl Iterator<Item = (&str, TextRange)>` — the
`::`/`.`-separated segments with their ranges, derived from `name_span` and
the name's own text. Never rescans the construct.
- `StmtKind::Disable { name, name_span }` — was `Disable(String)`.
**Promised to `vlog_semantic`'s callers:** `analyze(file, src)` keeps its `src`
parameter. It is no longer used to *find* names — nothing in the crate scans
source text any more — but it is still read by `Binder::exact_or_empty`, the
"verify before recording" oracle used by eleven call sites (instance module
names, class `extends` heads and tails, member tails, end labels, the type-name
segments and the `disable` target). Removing it would remove that check, which
is the opposite of what §47 is for. The vlog-semantic README's handshake item 2
("a span for `DataType`") is delivered; the `src` half of item 1's promise
("this parameter goes away") is amended to "src stops being a scanner and
becomes a verifier".
**Not changed, and why:** `lucisv_server/src/type_def.rs` still finds a type
site by a window (`site(&ty.name, TextRange::new(span.start, first))`) rather
than by `DataType::name_span()`. That is a `textDocument/typeDefinition`
concern in another crate and outside §47's file set; it is a clean follow-up
now that the span exists. Filed here rather than edited.
## Status / TODO
- [x] 47.1 `DataType::name_span` at every construction site + `segments()`;
size ruled (below)
- [x] 47.2 `StmtKind::Disable` name span
- [x] 47.3 `scan.rs` deleted, its `mod` removed, binder reads the spans,
census pin now covers type-name references
- [x] Consumers: `nav`/`hover` already go through `Reference::name_span`
(confirmed: `nav.rs` reads only `symbol.name_span` / `reference.name_span`);
two definition tests added
- [x] Gates (guarded)
## The size ruling
`DataType` rides in every `Expr` through `ExprKind::Type`, and `size_pins`
holds `Expr <= 96`. Measured with a throwaway probe test on `v0.44.0`:
| | `DataType` | `ExprKind` | `Expr` | `StmtKind` | `Stmt` |
|---|---|---|---|---|---|
| before | 88 | 88 | 96 | 392 | 552 |
| `pub name_span: TextRange` | 96 | 96 | **104** | **416** | **576** |
| `pub(crate) name_start: u32` | 88 | 88 | 96 | 392 | 552 |
A whole `TextRange` breaks the pin — and `StmtKind`/`Stmt`'s pins with it.
`DataType`'s eight-byte-aligned fields total 80 bytes and `virt` is one more,
so the struct already carries seven bytes of padding: a `u32` fits in it for
free, an eight-byte span does not.
So the span is stored as its **start** and paired with `name.len()` by
`DataType::name_span()`. The plan offered two fallbacks — move the span into
the already-boxed `TypeExtra`, or box it — and this is a third that is better
than both: they would put a heap allocation on *every* `DataType`, because
`name_span` is wanted for the implicit case too (the empty range at the
would-be position), and an implicit type is the common one. The pin did not
move. `name_start` is `pub(crate)`, so the invariant `end == start + len` has
exactly one writer, the parser.
## Construction sites
Five, all in `vlog_parser/src/parser/`:
1. `parse_opt_data_type`'s `sequence`/`property` SVA-formal arm — the keyword
token's start.
2. `parse_opt_data_type`'s `virtual bus_if.mp` arm — delegates to (5).
3. `parse_opt_data_type`'s type-keyword arm (`logic`, `int`, …) — the keyword
token's start.
4. `parse_opt_data_type`'s user-type arm — now calls the existing
`parse_scoped_name`, which already returned the joined text plus the whole
chain's range, so the `::` loop is no longer written twice.
`parse_type_ref` (a bare `my_type_t` where a type is required) calls the
same helper for the same reason.
5. `parse_modport_port_type` — the head identifier's start.
The **implicit** case is spanned by `Parser::implicit_type()`: a `DataType`
whose `name_start` is `self.here()`, the cursor before any of the type has
been consumed. `parse_opt_data_type` starts from it, so an `input [7:0] x`
whose type is nothing at all reports the empty range at the `[`; so does the
`parameter type T` placeholder in `parse_param_decl` and in the parameter-port
list, which write no data type at all. This is the convention `name_span`
already used for an unnamed DPI formal.
## Docs to apply at merge (lead)
Three places in `docs/topo.md`:
- **§2.9 row 2** (line ~618) — struck. Suggested replacement row:
> | ~~2~~ | ~~A span for `DataType` (and `ExprKind::Cast::ty` tails) — the last thing keeping `vlog_semantic/src/scan.rs` alive~~ — **delivered 2026-09-05 by type-name-spans (TODO §47)**: `DataType::name_span()` (stored as a `u32` start paired with `name.len()`, so `Expr` stays inside its 96-byte pin) and `DataType::segments()` (the `::`/`.` split, derived from the span's own text); `StmtKind::Disable` carries its target's span too. `scan.rs` is deleted — nothing in `vlog_semantic` scans source text for a name any more. `analyze`'s `src` parameter stays, no longer as a scanner but as `Binder::exact_or_empty`'s verification oracle. The corpus census pin now covers type-name references. | vlog-semantic (item 2); restated by class-semantics | ~~vlog_parser~~ done |
- **§1.3's `vlog_semantic` layout paragraph** (line ~201) — drop the
`` `scan.rs` (residual text-scanning for the one span the parser doesn't
carry — `DataType`; shrinks to zero when open handshake §2.9-2 lands); ``
clause outright; the file is gone.
- **§1.2's `name-spans ◀──▶ vlog-semantic` row** (line ~449) — the tail
"shrinking `scan.rs` to the `DataType` case (still open — §2.9)" becomes
"…; type-name-spans (§47) delivered the `DataType` case and deleted
`scan.rs`".
- **`crates/vlog_semantic/README.md` does not exist** (the crate has no
top-level README; `docs/features/vlog-semantic/README.md` is the one the
§47 brief means). Its Handshakes/Deviations text was edited in place by this
lane — see the work log.
## Work log
**2026-09-05 — dev agent.**
- Measured the sizes first (throwaway `tests/zz_size_probe.rs`, deleted), which
ruled out the plain `TextRange` field before a line of it was written. See
"The size ruling".
- `DataType` gained `pub(crate) name_start: u32`, `pub fn name_span()` and
`pub fn segments()`, plus a free `separator()` that finds the first `::`/`.`
that is not inside a leading escaped identifier. `segments()` yields nothing
for an implicit type.
- Five parser construction sites set the start; `parse_scoped_name` is now
reused by the two that had open-coded its `::` loop, which is a small
de-duplication that fell out of needing the range.
- `StmtKind::Disable(String)` became `Disable { name, name_span }`. The `fork`
form spans the `fork` keyword; the dotted form spans the whole `a.b` chain.
Formatter (`format/stmt.rs`) and linter (`rules/disable_statement.rs`) match
arms updated; neither reads the span, so no output moves.
- `Binder::bind_data_type` lost its `window` parameter and gained
`bind_type_name`, which walks `ty.segments()` and records the head as a
`Target::Unit` (`::`) or `Target::Type` (`.` or bare) and each following
segment as a member of the one before it. The old code split once and bound
two halves; a three-segment `a::b::c` used to bind `a` plus a `b::c` that no
scan could ever locate, and now binds all three.
- Every span is passed through `exact_or_empty`; a segment that does not
verify was, in the dev's version, the end of the chain (the reference
dropped). **Changed at review:** every segment is recorded, a failing one
with the empty range, so the census's `unplaced` counter — not a quieter
resolution rate — is what a future join regression would move.
Corpus-neutral (`unplaced` was and is 0; no corpus file spells a type name
with spaces around its separators).
- Dropping `window` removed the window computations at ten call sites, and with
them the now-unused `span` parameters of `bind_data_decl`,
`bind_declarators` and `bind_enum_body`.
- `crates/vlog_semantic/src/scan.rs` deleted along with `mod scan;`. Its six
unit tests went with it (they tested the scanner, not a behaviour).
- Tests added: four in `vlog_parser/tests/spans.rs` (a type name slices back to
the name as written across all five sites; `segments()` splits `pkg::state_t`
and `bus_if.mp` and yields nothing for an implicit type; an escaped segment
keeps its terminating space in both the span and the first segment; a
`disable`'s target has a span). The generic statement walker in `spans.rs`
now checks `Disable`'s span instead of skipping the arm. Two in
`lucisv_server/src/nav.rs`: F12 on the item half of `pkg::t` and on both
halves of `bus_if.mp`.
## Gates (all through `tools/guard.sh`; no guard kill)
| gate | result |
|---|---|
| `cargo fmt -p vlog_parser -p vlog_semantic -p vlog_formatter -p vlog_linter -p lucisv_server` | clean |
| `cargo clippy --all-targets` | clean, no new `#[allow]` |
| `cargo test --workspace` | **3 814 passed, 0 failed, 44 ignored** — the 0.44.0 baseline exactly: six `scan.rs` unit tests left, six new ones arrived |
| `tools/corpus_check.sh corpus` | 814/820 (99.3%), the same six parse errors; the per-file TSV is **byte-identical** to the committed `corpus-check-results.tsv` |
| formatter byte-identity | `format --stdout` of all 860 corpus files, new vs `~/.cache/lucisv-baselines/lucisv-0.44.0`: **0 differ** |
| `cargo build --release -p lucisv_server` + smoke | OK — F12 on `pkg::t`'s head and item, on `bus_if.mp`'s head and modport, and on a `disable`'s target all answer the right ranges; hover and `documentSymbol` answer |
| semantic corpus census | 860 files, 27 486 symbols, 103 870 references, 1 197 unresolved, **0 unplaced** — byte-identical to the same test run in a `v0.44.0` scratch worktree |
| opentitan `definition` sweep | 200 type-name positions over 74 files (50 scoped heads, 36 scoped items, 105 bare `_t`/`_e` types, 9 `virtual …_if`), 0.44.0 server vs the new one: **200/200 identical**, 180 of them non-empty answers. opentitan `status --porcelain` reported only the three pre-existing modified files after |
The 0.44.0 baseline binary was built in a scratch `git worktree` at the tag
(`~/.cache/lucisv-baselines/lucisv-0.44.0`, sha256 `4d928238…`, kept for the
next round); the worktree was removed afterwards. Sweep scripts:
`<scratchpad>/defcmp/{lspclient,positions,run}.py`.
### Census: before and after
The plan asked for the new count. The corpus test's numbers are **unchanged in
every field** — 27 486 / 103 870 / 1 197 / 0 unplaced on both sides — which is
the strongest form of the answer: type-name references were already counted,
they were merely located by a scan, and the parser's spans put them in exactly
the same places. (The `21 485` the §47 brief quotes is the 2026-08-19
figure; the corpus and the crate have both grown a great deal since, and the
vlog-semantic README's copy of it has been refreshed to today's numbers.)
## QA log
**2026-09-05 — QA agent.**
Verdict: **PASS**. No hard-invariant violation, no mislocation, no
formatter-output change, no corpus regression. One MEDIUM documentation/
observability finding below; recommend fixing at the lead's discretion
(does not block merge).
### What was verified, and how
1. **Attack battery on `bind_type_name`/`exact_or_empty` (never mislocate).**
Built a scratch integration test
(`crates/vlog_semantic/tests/zz_qa_type_name_spans.rs`, removed before
finishing) exercising `analyze()` over: plain `pkg::item`, spaced
`pkg :: item`, a `/* c */`-interrupted `pkg :: item`, `pkg::` / `item`
split across a line, `\my-pkg ::\state-t` (escaped both sides, space
terminator), `\my-pkg\n::item` (escaped, newline terminator), an escaped
segment whose own text contains `::` (`\a::b ::c`), `bus_if.mp`,
`bus_if . mp` (spaced), `virtual bus_if.mp`, `virtual interface bus_if`
with no modport, `pkg::t` used bare (parameterized-type source next to a
typedef target lacking params — the plain scoped case), an inline `enum`,
an inline `struct`, three implicit-type shapes (`input [7:0] x`,
`parameter type T`, `wire w`), a class-scoped `cls::t`, a cast `int'(x)`,
a scoped cast `pkg::t'(x)`, and five `disable` shapes (`fork`, a plain
label, a dotted `a.b.c`, an escaped label, and a spaced dotted
`a . b . c`).
For every reference `analyze()` recorded across this whole battery,
`src[name_span] == name` held, or the span was empty — **zero
non-empty-but-wrong spans** ("MISMATCH") anywhere. The hard property the
round is built on holds under adversarial input.
**Fallback / dropped-reference count** — spellings where a reference
either fell back to empty or was not recorded at all:
- `\my-pkg\n::item` (escaped, newline-terminated) — **0 references
recorded** (both segments; documented in Assumptions as a known
disagreement).
- `pkg :: item` (spaced) — **`item` not recorded** (only `pkg` is; the
early-return in `bind_type_name` stops at the first segment whose
derived span fails `exact_or_empty`, so everything after it, correct
or not, is silently dropped rather than recorded empty).
- `pkg /* c */ :: item` (comment-interrupted) — same as above, `item`
dropped.
- `pkg::` / `item` split across a line — same, `item` dropped.
- `disable a . b . c` (spaced dotted) — **0 references recorded** (the
whole chain, since `exact_or_empty` checks the joined `a.b.c` against
the real, spaced span as one unit).
- `disable fork` recorded 0 references, but this is pre-existing,
unrelated behavior: `Binder::use_member` filters `is_keyword(name)` and
`fork` is a keyword; confirmed by reading `bind/mod.rs:296-297` and by
the fact the 0.44.0 baseline drops it identically (see below).
No other spelling in the battery fell back to empty or was dropped —
in particular, both escaped-with-space-terminator (`\my-pkg ::\state-t`)
and plain dotted `disable a.b.c` located **exactly**, which is new
(see next point).
2. **0.44.0 baseline comparison (built in a `git worktree` at `v0.44.0`,
removed after).** Ran the identical battery through the old
`scan.rs`-based binder to see what changed, not just what the README
claims:
- **Improvements over 0.44.0** (old code got these wrong, new code gets
them right): `\my-pkg ::\state-t` (old: both halves **empty** — the
scanner's whole-word matcher never includes the escaped segment's
trailing space, so it could never match `push_scope_segment`'s own
join; new: both **exact**). Plain `disable a.b.c` (old: **empty** —
`NameScanner::find` only ever returns single-token words, so a
dotted name can never match as one word; new: **exact**). These are
real, verified accuracy wins from moving off text-scanning.
- **A narrower regression, corpus-neutral in practice**: for
`pkg :: item`, `pkg /* c */ :: item`, and `pkg::`/`item` split across
a line, the **0.44.0 scanner found both `pkg` and `item` at their
correct positions** (whole-word search tokenizes past whitespace and
comments, skipping them — see `scan.rs`'s `next_word`), while the new
code drops `item` entirely once its derived offset (computed from the
tightly-joined `name` string, which does not reflect arbitrary
inter-segment whitespace/comments) no longer covers real source bytes.
This never mislocates — `item` is simply absent from `s.references()`
rather than present with a wrong span — but it is a real loss of
find-and-locate capability for these three SV-legal (if unusual)
spellings, and the old code additionally always recorded *some*
`Reference` (even an empty-span one) where the new code, for the
type-name path specifically, now sometimes records **nothing at all**.
- The `disable`/type-name **modport-tail** shapes (`bus_if.mp`,
`bus_if . mp` spaced) are **byte-for-byte identical** old vs new,
confirming the modport tail's own pre-existing "skip if empty"
convention was carried over unchanged, as the work log claims.
Finding (**MEDIUM**, doc/observability, not a correctness bug): the
README's Assumptions section names only two "joins that can disagree"
(an escaped segment's space, and the modport `.`). Empirically, *any*
whitespace or comment between `::`-separated segments, and any spacing
in a dotted `disable` target, also disagrees and silently drops the
affected reference — and, specific to the binder's new early-return in
`bind_type_name` (`crates/vlog_semantic/src/bind/decl.rs`), a segment
past the first divergence is not merely mislocated-and-caught but never
recorded as a `Reference` at all (0.44.0 always recorded one, with an
empty span, via `NameScanner`'s always-recording callers). This means a
future regression in the parser's own joining logic for these
constructs would no longer surface as `unplaced > 0` in the corpus
census (`crates/vlog_semantic/tests/corpus.rs`'s `covers()` only counts
spans that exist; a dropped reference contributes nothing) — it would
have to be caught by resolution-rate drift instead, which is a weaker
signal. Recommend the Assumptions section name the fuller set of
disagreeing spellings (whitespace/comments around any `::`/`.`, not
only the escaped-segment case), and/or that `bind_type_name` record a
trailing empty-span reference on early return the way the pre-round
code did, so the census keeps its loud-failure property. Not a merge
blocker: corpus-neutral (verified below), never mislocates, and the
`disable`/type-name-with-whitespace spellings are rare in real RTL.
3. **Census pin.** `tools/guard.sh -- cargo test -p vlog_semantic --test
corpus -- --nocapture`: **860 files, 27 486 symbols, 103 870
references, 1 197 unresolved (1.15%), 0 unplaced** — matches the
README's claim exactly (re-derived independently, not read off the
README). Confirmed `covers()` (`tests/corpus.rs:69-80`) asserts
`src[span] == name` for every non-empty-span reference and symbol
uniformly (not type-references-only, but type references are now part
of that population for the first time, per the round's stated purpose)
and that an empty span is counted as "unplaced" rather than exempted —
so the 0-unplaced result is a real assertion, not a vacuous one, over
the actual corpus.
4. **`disable` spans + formatter/linter round-trip.** Confirmed via the
parser's own new tests (`a_disable_names_its_target_with_a_span`,
`spans.rs`) and independently via `lucisv format --stdout` /
`lucisv check` on a hand-written `fork`/label/dotted-label file: output
is idempotent (`format(format(x)) == format(x)`) and byte-identical to
the `lucisv-0.44.0` baseline binary, and `lucisv check`'s
`disable-statement` diagnostic is identical old vs new. Confirms the
formatter/linter genuinely ignore the new span (as the work log
claims) — output moved nowhere.
5. **Size pins.** `tools/guard.sh -- cargo test -p vlog_parser --lib
size_pins`: `expr_stmt_and_stmt_kind_stay_within_their_pinned_sizes`
passes (`Expr <= 96`, `StmtKind <= 392`, `Stmt <= 552`), confirming the
`name_start: u32` design keeps every pin where §36's protocol left it.
6. **Server: definition/hover/typeDefinition/rename, in-tree and over
opentitan.**
- `cargo test -p lucisv_server`: the dev's two new `nav.rs` tests pass
(`a_scoped_type_name_jumps_from_its_item_half`,
`an_interface_port_type_jumps_from_its_head`), as part of the full
3 814-test run below.
- Added a temporary `#[test]` in `crates/lucisv_server/src/rename.rs`
(removed before finishing; `git diff` on that file is empty now) that
renames a package typedef `t` used as `pkg::t` from three files.
Result: **all three files edited, each edit's range slicing to
exactly `t`** (verified by slicing the edit's own `TextEdit.range`
out of the source line) — never `pkg::t`, confirming attack item 4's
rename requirement directly rather than by inspection.
- `lucisv_server/src/type_def.rs` is untouched by this round (confirmed
by `git diff --stat`) and still locates a type site by its own
from-scratch window/`site()` walk, independent of
`DataType::name_span`/`segments()` — exactly what the Handshakes
section says. Verified it still answers correctly (see next point),
so the "clean follow-up, not a regression" framing holds.
- **Opentitan sweep, independently re-derived** (attack item 5): wrote
a second position-picker (`<scratchpad>/defcmp/qa_positions.py`)
targeting a **disjoint set of directories** from the dev's own script
(`hw/ip/otp_ctrl/rtl`, `hw/ip/flash_ctrl/rtl`, `hw/ip/i2c/rtl`,
`hw/ip/rv_dm/rtl`, `hw/ip/spi_host/rtl`, `hw/dv/sv/tl_agent`,
`hw/dv/sv/csr_utils` — the dev used `aes`/`hmac`/`spi_device`/`uart`/
`uart_agent`/`cip_lib`/`dv_lib`), picking 200 positions over 43
files. Built the 0.44.0 `lucisv-server` in the same `v0.44.0`
worktree used for the binder comparison, and ran both
`textDocument/definition`, `textDocument/hover`, and
`textDocument/typeDefinition` over all 200 positions with both
servers (`<scratchpad>/defcmp/run.py`, `run_hover_typedef.py` — the
latter is a QA-added twin of the dev's `run.py` adding hover/
typeDefinition, since the original only asked `definition`).
Results: **definition 200/200 identical (149 non-empty)**, **hover
200/200 identical (149 non-empty)**, **typeDefinition 200/200
identical (63 non-empty)**. `git -C ~/repo/opentitan status
--porcelain` reported only the three pre-existing modified files
after every run (before, during, and after — checked three times).
### Gates re-run independently (all guarded, all matched the dev's numbers)
| gate | result |
|---|---|
| `cargo clippy --all-targets` | clean (fully cached; 0 warnings/errors) |
| `tools/guard.sh -- cargo test --workspace` | **3 814 passed** (3 815 with my scratch test counted, subtracted), **0 failed, 44 ignored** — exact match |
| `tools/guard.sh -- tools/corpus_check.sh corpus` | 814/820 (99.3%), same six parse errors, 0 verification errors, 0 crashes; `git diff --stat -- corpus-check-results.tsv` empty (byte-identical) |
| formatter byte-identity | wrote an independent diff script; `lucisv format --stdout` on all 860 corpus files vs `~/.cache/lucisv-baselines/lucisv-0.44.0`: **0 differ** |
| census | 860 files / 27 486 symbols / 103 870 references / 1 197 unresolved / **0 unplaced** — re-derived, not copied |
| opentitan definition/hover/typeDefinition sweep | 200/200/200 identical old vs new on an independently-chosen position set; opentitan `status --porcelain` clean (only the three pre-existing files) throughout |
No guard kill anywhere.
### Cleanup
Removed: `crates/vlog_semantic/tests/zz_qa_type_name_spans.rs` (scratch
test), the temporary `#[test]` in `crates/lucisv_server/src/rename.rs`
(confirmed `git diff` on that file is now empty), the `v0.44.0` scratch
`git worktree` (`git worktree remove`, confirmed gone from
`git worktree list`), and both scratch server storage directories. Left
in the scratchpad (not the repo) for the lead's reference:
`<scratchpad>/defcmp/qa_positions.py`, `qa_positions.json`,
`qa_old.json`/`qa_new.json` (definition), `qa_old_ht.json`/`qa_new_ht.json`
(hover/typeDefinition), `run_hover_typedef.py`, `byte_identity_check.sh`.
## Review
## Review
**2026-09-05 — lead.** Accepted with one rework; ships in 0.45.0 with §48
and §49. The size ruling is the right one: a `u32` start in the padding
`DataType` already had keeps `Expr` at 96 with no allocation on the common
implicit case, and the derived end is verified against the source before
any reference is recorded, so the "never mislocate" invariant held under
QA's whole battery. QA's MEDIUM was fair — a dropped reference silences the
census alarm the pin exists for — and is fixed by recording the empty-range
placeholder instead of returning early; the README's list of disagreeing
spellings is now the full one QA found. Two shapes the old scanner always
failed (an escaped segment with a space terminator, a dotted `disable`
target) are now exact. Census unchanged in every field, 0 of 860 corpus
files differ, 200/200 opentitan answers identical for definition, hover and
typeDefinition. The `type_def.rs` window lookup is filed as a follow-up in
Handshakes, not a regression.
+46 -14
View File
@@ -62,16 +62,23 @@ enum Resolution {
### Deviations from the sketch in the task, and why
- **`analyze` takes `src` as well as the tree.** Most declarations in the AST
keep their name as a plain `String` and carry a span only for the whole
construct, so the *name's* range — the thing an editor highlights — is not
recoverable from the tree alone. `scan.rs` finds it by scanning the
construct's own source bytes (comments, strings and macro invocations
skipped) inside a window narrowed by the sub-spans that *do* exist. The
corpus test asserts `src[name_span] == name` for all 21 485 symbols and
73 708 references it builds, so the scan is not a guess in practice. A
Handshake request to put `name_span` on the AST is filed below; when it
lands, `scan.rs` and this parameter go away.
- **`analyze` takes `src` as well as the tree.** Originally because most
declarations kept their name as a plain `String` inside a construct-wide
span, so the *name's* range — the thing an editor highlights — was not
recoverable from the tree at all; `scan.rs` found it by scanning the
construct's own source bytes inside a window narrowed by the sub-spans that
did exist. **Both halves of that are gone**: `name-spans` (2026-08-19) put
`name_span` on every declaring node, `type-name-spans` (2026-09-05, TODO
§47) put `DataType::name_span()`/`segments()` and `StmtKind::Disable`'s span
on the last two, and `scan.rs` is deleted. `src` stays, in a different
role: `Binder::exact_or_empty` checks a derived span against the source
before a reference is recorded, so a name the source spells differently from
the way the parser joined it (`bus_if . mp` written apart, an escaped
segment terminated by a newline) costs the reference rather than
mislocating it. Eleven call sites rely on that oracle. The corpus test still
asserts `src[name_span] == name` for every symbol and reference it builds —
27 486 and 103 870 as of 2026-09-05, type-name references now among them,
0 unplaced.
- **`Reference.resolution: Resolution` instead of `resolved:
Option<SymbolId>`.** The task asked for both an `Option<SymbolId>` and an
`ExternalCandidate` state carrying the import path; one enum says that once.
@@ -280,15 +287,21 @@ region | generate block | for-generate header | for/foreach statement`.
- `src` passed to `analyze` is the exact text the tree was parsed from. Spans
index into it; a mismatched string yields wrong name spans, not a panic
(every slice is bounds-checked and clamped).
- A construct's keyword is written before its name (`module m`, `function
- ~~A construct's keyword is written before its name (`module m`, `function
automatic int f`), and the name is a plain identifier. Where a type name and
the declared name are the same token text (`function foo_t foo_t;`) the scan
can pick the first of the two; nothing in the corpus does this.
can pick the first of the two; nothing in the corpus does this.~~ Retired
2026-09-05 by `type-name-spans`: nothing here scans for a name any more, so
no assumption about where one is written is left to make.
- The parser bounds nesting depth (`MAX_NESTING_DEPTH`, TODO.md §1), so the
recursive walk here inherits a bounded stack and needs no depth counter of
its own.
- Identifiers are ASCII in practice; the scanner treats non-ASCII bytes as
non-identifier bytes and never slices inside a multi-byte character.
- A span derived rather than received is checked against the source before it
becomes a reference (`Binder::exact_or_empty`). What is derived is small and
named: a `Member`/`Scope` tail, a class `extends` head and tail, an instance
module name, an end label, the `::`/`.` segments of a type name, and a
`disable` target. Anything that does not slice back to the name costs the
reference; nothing is ever recorded at a guessed position.
## Handshakes
@@ -332,6 +345,11 @@ feature, and the crate works without it):
`docs/features/name-spans/README.md`.
2. **A span for `DataType`** (and for `ExprKind::Cast::ty`), so a type
reference does not need a window computed from its neighbours' spans.
**Delivered 2026-09-05 by `type-name-spans`** (TODO §47) — `DataType`
carries `name_span()` and `segments()`, `StmtKind::Disable` carries its
target's span, `bind_data_type` lost its `window` parameter, and
`crates/vlog_semantic/src/scan.rs` is deleted; see
`docs/features/type-name-spans/README.md`.
3. Nice to have, much smaller: the byte range of `Member`/`Scope` tails, which
is today derived as `span.end - name.len()`.
@@ -433,6 +451,20 @@ anywhere, and under 3 % unresolved on cleanly-parsed files.
## Work log
**2026-09-05 — type-name-spans (TODO.md §47).** `scan.rs` deleted, `mod scan;`
with it: the parser now carries `DataType::name_span()` /
`DataType::segments()` and `StmtKind::Disable`'s span, so the two remaining
scan callers read them instead. `bind_data_type` lost its `window` parameter
(and with it the window computations at ten call sites, plus the now-unused
`span` parameters of `bind_data_decl`, `bind_declarators` and
`bind_enum_body`) and gained `bind_type_name`, which walks the segments and
records the head as `Target::Unit`/`Target::Type` and each following segment
as a member of the one before it — so a three-segment `a::b::c`, which used to
bind an unlocatable `b::c`, binds all three. Every segment goes through
`exact_or_empty` first. Corpus census byte-identical before and after: 860
files, 27 486 symbols, 103 870 references, 1 197 unresolved, 0 unplaced.
Details in `docs/features/type-name-spans/README.md`.
**2026-08-27 — indexed navigation.** `Semantics` now builds compact sorted
`(TextRange, SymbolId/ReferenceId)` position tables with the analysis.
`symbol_at`, `reference_at` and `reference_id_at` binary-search those tables;
+447
View File
@@ -0,0 +1,447 @@
# walk cycles
## Goal
Two unrelated residues of the repository analysis (finding 3), landed
together as TODO §43 because each is small and neither collides with the
other.
**43.1 — a cycle policy for the shared walk.** `lucisv_core::walk` recursed
on `Path::is_dir()` with no memory of where it had been. A symlink that
points back into the tree it sits in — `a/loop -> ../a`, `a/sub/up -> ..`,
the `rtl -> ../shared/rtl` pair a vendored checkout writes twice — made the
walk descend forever, one directory deeper each time, until the operating
system refused the path. Both front ends share that walk: `lucisv` (and so
`format`, `check`, `--check`, `--diff`) and the language server's index scan,
where the symptom is not an error message but an index that never comes up.
The policy is now **each directory is entered once, by identity**: a symlink
naming a directory the walk has already entered is skipped silently, and a
symlink naming one it has not is still followed, once. No traversal budget —
identity *is* the policy, and a budget would be a second, weaker rule
answering the same question differently.
**43.2 — the net delay's comment slots.** `wire /* c */ #5 w;` and
`wire [7:0] /* c */ #1 w;` were refused outright: `NetDelay` had no field for
a comment written in front of its `#`, so the comment was printed one node
later and `verify.rs` — correctly — refused the whole file (exit 2, no
output). `NetDelay` now owns both of its gaps, `before_hash` and
`after_hash`, and the `#SKIP` `parser-skips` left in
`net_delay_position.cases` is retired.
## Assumptions
- **Directory identity on unix is `(dev, ino)`.** `fs::metadata` follows
symlinks, so the link and its target return the same pair, which is exactly
the question being asked. Elsewhere (there is no non-unix CI today, but the
crate compiles there) it is `fs::canonicalize`, which resolves the same way
at the cost of a path lookup. Both are `Option`: a name whose metadata
cannot be read is not a directory the walk can enter.
- **A hard link is not a cycle, and is not treated as one.** Two hard-linked
*files* have one inode and the visited set never sees them: only
directories are recorded. (Hard-linked directories are not creatable on any
filesystem lucisv runs on.)
- **The visited set lives for one `collect_files` call.** Two inputs named on
one command line each get their own walk, so a directory reachable from
both is still walked twice — unchanged, and the CLI's own path dedup is
what answers that (`§41`). Inside one walk the same file reached under two
spellings is reported once, under the first spelling that reaches it: entry
order is `read_dir` sorted by path, so `link_a/x.sv` wins over `shared/x.sv`
and `shared/x.sv` wins over `zlink/x.sv`. This is the same rule §41 already
applies to a symlinked *file*.
- **A dangling symlink is not an input.** `metadata` fails on it, so it is
neither walked nor collected. Before this round a dangling `x.sv` link was
collected and failed later, at read time, with a "no such file" error the
user did not write.
- **The `.gitignore`/`--exclude` decision still comes first.** A cycle inside
an ignored or excluded directory is never entered at all, so the visited
set never sees it; the ignore rules were not touched.
- **A comment in front of a `#` belongs to the delay** (43.2), the way
`Typedef::before_name` owns the gap in front of its name: the gap is taken
only on the branch that actually consumes the `#`, so a `#` that is not a
net delay leaves the comment for whoever comes next.
## Handshakes
- **`lucisv_core::walk` → `lucisv` and `lucisv_server`** (topo §2.9-8, struck
by this round). `collect_files`'s signature is unchanged. What changed is
what it returns for a tree containing symlinked directories: it terminates,
and a directory reachable under several names contributes its files once.
`lucisv_server::state::Workspace::walked_files` is the server's only caller
and needed no change — its `sort`/`dedup` still runs, and now has less to
do. `vlog_linter` uses `walk::is_excluded` only, which is untouched.
- **`vlog_parser::ast::NetDelay` → `vlog_formatter`** (topo §2.9-27, struck).
Two new public fields, `before_hash` and `after_hash`, both
`Vec<Comment>`. The only constructor is `Parser::parse_net_delay`; the only
reader is `Fmt::net_delay`. `vlog_semantic`, `vlog_linter` and
`vlog_refactor` do not name the type.
- **Not taken:** the gaps *inside* a delay's `#( … )` — `#( /*c*/ 1:2:3 )`
and each side of its two `:` — are still refused. They are
`parse_delay_values`, shared with a gate instantiation's delay list, and
they fail identically outside a net declaration; they belong with the rest
of the shared expression machinery in topo §2.9-22, not here. Recorded
below and left for a future round.
## Status / TODO
- [x] 43.1 `Walk::visited`, `Walk::enter`, `dir_id` per platform; `dir()`
checks-and-inserts before `read_dir`
- [x] 43.1 a dangling symlink is skipped rather than collected
- [x] 43.1 unit tests: self-loop, ancestor link from a nested start, two
links to one target, a link to a directory not yet walked, a dangling
link, a cycle inside an ignored directory
- [x] 43.1 CLI test (`--check` over a cyclic tree names each file once)
- [x] 43.1 server test (a cyclic workspace scans once and finishes)
- [x] 43.2 `NetDelay::before_hash` + `after_hash`, parser and formatter
- [x] 43.2 the `#SKIP` in `net_delay_position.cases` retired, three live
cases in its place
- [x] 43.2 the RTL gap fuzzer covers a net delay (352 → 374 gaps, still zero
failures)
- [x] Gates: fmt, clippy, workspace tests, corpus, both binaries over a
cyclic tree
## Docs to apply at merge (lead)
- `docs/topo.md` §2.9-8 — strike: **delivered 2026-09-05 by walk-cycles
(TODO §43.1)**: `lucisv_core::walk::Walk` keeps a `visited` set keyed on
`(dev, ino)` on unix and the canonical path elsewhere; each directory is
entered once, a symlink to a directory already entered is skipped
silently, a symlink to one not yet entered is still followed, a dangling
symlink is skipped. Both front ends: CLI `--check` over a cyclic tree names
each file once; the server's `walked_files` scan finishes.
- `docs/topo.md` §2.9-27 — strike: **delivered 2026-09-05 by walk-cycles
(TODO §43.2)**: `NetDelay::before_hash` and `after_hash` own the two gaps
around the `#`; the formatter prints them inline; the
`net_delay_position.cases` `#SKIP` is retired and the RTL gap fuzzer covers
the construct. The gaps *inside* `#( 1:2:3 )` remain refused and belong to
§2.9-22 (`parse_delay_values`, shared with gate delays).
- `docs/repository-analysis.md` finding 3 — annotate as closed by TODO §43.1
with the identity policy above, and note that the "no traversal budget"
ruling was the lead's.
- `docs/features/parser-skips/README.md` — its Assumptions (line ~103),
Handshakes (line ~151) and QA log (lines ~343, ~409) describe the net-delay
comment as a live `#SKIP` and as a handshake request to `comment-slots`.
That request is now answered; a one-line "closed by walk-cycles (TODO
§43.2), 2026-09-05" under each is the honest amendment. Not edited here —
it is another feature's README, and this lane owns none of it.
- `README.md` — no change needed: the walk's user-visible contract
(extensions, `--exclude`, `.gitignore`) is unchanged. If a line is wanted,
it is in the CLI section: "a symlinked directory is walked once; a cycle
terminates".
## Work log
**2026-09-05 — dev (Opus 5).**
*43.1, `crates/lucisv_core/src/walk.rs`.* `Walk` gained
`visited: HashSet<DirId>` and one method, `enter`, which is the whole policy:
`dir_id(dir).is_some_and(|id| self.visited.insert(id))`. `dir()` calls it
first and returns `Ok(())` when it answers false, so a directory already
entered costs one `metadata` call and nothing else — no `read_dir`, no
ignore-stack push, no recursion. `DirId` is `(u64, u64)` under `#[cfg(unix)]`
from `MetadataExt::dev`/`ino`, and `PathBuf` from `fs::canonicalize`
otherwise; `dir_id` returns `Option`, and `None` (a dangling link, a
directory that vanished mid-walk) means "not entered".
The entry loop's `path.is_dir()` became one `fs::metadata(&path)` — the same
single stat, and it follows symlinks exactly as `is_dir()` did, so a
symlinked directory is still recognized as a directory. Three things fall out
of having the metadata rather than a bool: `meta.is_dir()` for the walk arm,
`meta.is_file()` for the collect arm, and a dangling link (no metadata at
all) skipped by the `let … else { continue }` in front of both. The extension
test moved into a small `is_source` helper so the collect arm stays one line.
The one behaviour change beyond termination that a user could notice: a
dangling symlink named `x.sv` used to be *collected* and then failed at read
time. It is now skipped. That is in the plan's test list ("a dangling symlink
is skipped") and is the same judgment as the directory case.
Six unit tests in `walk.rs`, all `#[cfg(unix)]` because they need real
symlinks, over a `TempTree` helper in the test module (the third such helper
in the crate — `config.rs` and `cache.rs` have their own; a fourth copy is
cheaper than a shared test-support module for two dozen lines). Each of them
would have run until the OS refused a path before this change.
*43.2, three crates.* `NetDelay` gained `before_hash` and `after_hash`.
`parse_net_delay` takes the first with `take_gap()` **after** the
`cur().is_sym("#")` check — the `gap_before("#")` contract, spelled out
rather than called, because the check is already there for the `is_net` gate
— and the second with `take_gap()` after the `bump()`.
`Fmt::net_delay` now owns the separator in front of the delay as well as the
delay: it emits the `before_hash` comments *instead of* the plain space when
there are any, and the plain space when there are not, so a declaration with
no comment there is laid out byte-identically to before. That moved the
trailing space off `net` (`text(format!("{net} "))` → `text(net.clone())`)
and off the data type, which is why `data_decl` changed shape slightly; the
two call sites are now inside the `if let Some(net)` and
`if let Some(t) = self.data_type(…)` arms, which is also correct, since a
delay is only ever read after a net keyword, and an after-type delay only
after a data type that was actually written.
*Deviation from the plan: `after_hash`.* The plan asks for `before_hash`
only, and also asks that the gap fuzzer cover the new slot. Those two are in
tension: `assert_no_failing_gaps` demands **zero** failures across a fixture
set, and the smallest fixture that exercises `before_hash` (`wire #5 a;`)
also contains the gap between `#` and `5`, which had no owner either. So the
fixture could not be added without it. `after_hash` is four lines (one field,
one `take_gap`, one `slot_comments`) on the same construct, and closes the
delay's own gaps completely; the alternative was to leave the fuzzer without
a net-delay fixture, which is the thing the plan explicitly asked for. Flagged
here for the lead.
The gaps inside `#( 1:2:3 )` are *not* closed — eight of them, measured with
the fixture `wire [7:0] #(1:2:3) b = c;` before it was narrowed to `#1`. They
live in `parser/instance.rs::parse_delay_values`, shared with gate
instantiation delay lists, fail identically there, and are §2.9-22 shared
machinery. The RTL fuzzer fixture is `wire #5 a;` / `wire [7:0] #1 b = c;`,
which covers both sides of the type and both new slots; `EXPECTED_RTL_GAPS`
352 → 374, zero failures.
*Files touched outside the plan's expected set.* None beyond what the plan
names, with one addition: `crates/vlog_formatter/tests/verification.rs` (the
gap fuzzer's fixture and count — the plan says "find how the fuzzer
enumerates slots and add this one", which is this file). Full list:
`crates/lucisv_core/src/walk.rs`, `crates/lucisv/tests/cli.rs`,
`crates/lucisv_server/src/state.rs` (test only),
`crates/vlog_parser/src/ast/decl.rs`,
`crates/vlog_parser/src/parser/decl.rs`,
`crates/vlog_formatter/src/format/decl.rs`,
`crates/vlog_formatter/tests/cases/net_delay_position.cases`,
`crates/vlog_formatter/tests/verification.rs`, `TODO.md`, this README.
*Do the tests have teeth?* Asked directly rather than assumed: the `enter`
call was short-circuited (`if false && !self.enter(dir)`) and the walk tests
re-run. Three of the six failed — the self-loop, the ancestor link and the two
links — with paths 31 levels of `a/up/` deep, which is what the OS refuses at
rather than a hang. The other three (the sibling link, the dangling link, the
ignored cycle) pass either way by construction: they are about the *other*
half of the policy. The short-circuit was reverted immediately and the file
compared against a copy taken before it; `walk::` is green again.
*Gates, all guarded.* `cargo fmt --check` on the five touched crates: clean.
`cargo clippy --all-targets`: clean, no new `#[allow]`. `cargo test
--workspace`: **3 788 passed, 0 failed** (baseline 3 780 + the 8 tests this
round adds: 6 in `walk.rs`, 1 CLI, 1 server). `tools/corpus_check.sh`:
**814/820 (99.3%)**, the same six failures (five parse, one lex) and the same
10 already-clean files. Byte-identity: no corpus file writes a comment before
a net delay's `#` — checked with a direct grep over `corpus/`, 0 hits — and
the empty-slot path emits exactly the `text(" ")` it did before, so the
formatter's output over the corpus cannot have moved; the corpus counts
confirm it. `node editors/vscode/smoke.js target/release/lucisv-server`: OK,
20 messages. The cyclic scratch tree (a self-link, a `..` link one level down,
a `../../..` link three levels down, a second name for one directory, and a
dangling `x.sv` link) through both release binaries under
`tools/guard.sh -t 120`: `lucisv --check` finishes in ~1s and names its three
files once each; an LSP session (initialize with that `rootUri`, `initialized`,
one `didOpen`, `workspace/symbol`) finishes in ~1s with each package indexed
exactly once. No guard kill anywhere in the round.
### 2026-09-05 — lead, at review
QA's MEDIUM (the dangling-symlink change made a "no such file" error
silent) is ruled and fixed: a dangling link that *names a source file* is
handed on again, so the front end reports it exactly as 0.42.0 did (exit 2);
a dangling link to anything else is skipped as the dev wrote. The test is
renamed to say both halves. QA's LOW (a link to `/` is followed and the
first permission-denied directory aborts the whole walk, dropping the files
already found) is pre-existing `?` propagation and is filed as topo §2.9-30
together with the warning channel the walk lacks. The opentitan
`tlul_adapter_vh.sv` divergence QA root-caused is §41's canonical dedup
reporting a same-directory symlink alias once — the intended change, noted
in 0.43.0's release notes.
## QA log
**2026-09-05 — QA (Sonnet).** Built `target/release/{lucisv,lucisv_server}` once
and attacked both halves of the round on scratch trees under
`tools/guard.sh -t 120`; nothing was ever killed (no memory or wall-clock hit)
in this pass.
*Diff review.* Read `crates/lucisv_core/src/walk.rs`,
`crates/vlog_parser/src/{ast,parser}/decl.rs`,
`crates/vlog_formatter/src/format/decl.rs`, the two test files, and
`crates/lucisv/tests/cli.rs` / `crates/lucisv_server/src/state.rs` line by
line against the plan. Traced the `data_decl` reshuffle by hand for the
empty-slot case on both sides of the type: `net_delay`'s separator branch
degrades to the same `text(" ")` the old unconditional call emitted, so a
declaration with neither a delay nor a comment is unaffected — confirmed
this holds for the "after_type but no data_type" case too, which cannot
arise (`parse_net_delay(is_net, true)` only ever succeeds after
`parse_opt_data_type` actually consumed tokens, since an omitted type
leaves the `#` for the `before` call to claim first).
*43.1 — cycle attacks (all via `tools/guard.sh -t 120`, actual wall times
well under that in every case).*
- Depth 1/2/3 cycles (`a/loop -> a`, `a/b/up -> ..`, `a/b/c/top -> ../../..`):
terminate, each file named once. Two-link cycle (`a/x -> ../b`,
`b/y -> ../a`): terminates, `ma.sv` and `mb.sv` each reported once, `mb.sv`
under the alias spelling `a/x/mb.sv` (first spelling reached, as documented).
Chain of 50 symlinked directories collapsing to one target: resolved
correctly and fast (single `metadata` call per hop, no manual recursion) —
no `ELOOP`, no slowdown.
- **Ancestor-of-start escape.** Built `start/out -> ../..` where the target is
*outside* `start` entirely (not just the walk's own root) and ran
`--check` with `start` as the CLI argument (not its parent). The link is
followed once — per the ruling, identity is the policy, not location — and
pulls in a sibling file and a grandparent-level file that are not inside
`start` at all. It terminates (~1s) because the walk eventually re-enters
`start` itself from the other direction and that's already visited. Not a
bug — this is the plan's own explicit choice (no budget, `rtl ->
../shared/rtl` must keep working) — but it is a real, user-visible
consequence: pointing lucisv at a subdirectory can pull in files from
outside it if that subdirectory contains an upward-and-back symlink.
Flagged as **LOW / informational** for the lead's record, not a defect.
- **Link to `/`.** Followed once, as the ruling implies it must be; spent
~14.6s doing real `readdir`/`stat` work under `/System`, `/Library`,
`/private` etc. before hitting a permission-denied directory, at which
point the *entire* run aborted with `error: <original start path>:
Permission denied` — none of the user's own files were reported, not even
the ones already found. Reproduced this abort-on-any-`read_dir`-error
behaviour with a controlled example (`crates/lucisv_core/src/walk.rs`'s
`dir()` uses `?` on `read_dir(dir)?.collect::<Result<_,_>>()?`, unchanged
by this diff) — it is pre-existing, not introduced by 43.1: the old,
cycle-blind walker would have followed `/` identically and hit the same
wall. Filed as **LOW / informational**, since it predates this round, but
worth the lead's attention because 43.1 is what makes "follow a link
outside the tree" a documented, intentional feature rather than an
accident — a link to `/` (or to any tree with a permission-restricted
subdirectory anywhere under it) now silently costs the *entire* check, not
just the linked file. Link to a real bounded tree (`/usr/share`, 250 MB):
walked completely in ~1s, correctly found and lex-errored on a
coincidentally `.sv`-named file (`vim/vim91/tutor/tutor1.sv`, Swedish
locale code) — confirms outside-of-start links are followed and that nothing
hangs on a moderately large real directory.
- Hard-linked **files**: reported twice, once per directory, confirming
identity is directory-only as documented. Two directories with identical
content but different inodes: both walked (not deduped) — confirmed
content-blind, inode-based identity.
- Gitignore interplay: a cycle inside an ignored directory never runs
(confirmed — the `loop` symlink inside `build/` was never touched); an
ignored symlinked directory name is skipped by that spelling but the real
target directory (different name, not itself ignored) is still walked
directly — this is unchanged, pre-existing per-spelling ignore matching,
not a 43.1 regression; a `.gitignore` inside a followed link's target
applies to the walk (its `sub/` pattern correctly hid the target's own
subdirectory when reached through the link).
- **The dangling `x.sv` behaviour change**, `lucisv format --check dir`
with a dangling `x.sv` link, new binary vs.
`~/.cache/lucisv-baselines/lucisv-0.42.0`: confirmed exactly as the
work log describes — 0.42.0 collects it, fails at read time
(`error: .../x.sv: No such file or directory`, exit 2, "1 file would be
reformatted, 1 file failed to format"); the new binary skips it silently
(exit 1, "1 file would be reformatted", no mention of `x.sv` anywhere).
**Finding, MEDIUM, for the lead's ruling** (this is what the plan and
TODO explicitly asked for, so not a defect against the dev — but the
silence itself is worth a second look): a dangling symlink named like a
source file usually means something real broke (a missing vendor drop, a
bad checkout), and the user now gets no signal at all instead of a
specific, actionable error. The CLI already has a precedent for this exact
tension — a missing file named in a `-f` filelist is a **warning on
stderr**, changing no exit code — and the same shape (warn, don't fail,
don't stay silent) seems like it would keep 43.1's win (no more hard
crash on a broken symlink) without losing the signal. Recommend the lead
decide whether `walk.rs` should carry a callback/return channel for this
one case, or whether silence is accepted as-is.
- **Both front ends.** CLI `--check` over a two-directory cyclic tree
(`rtl/self -> ../rtl`, `rtl/sub/up -> ..`): 2 files, once each. The same
tree over `lucisv_server` (drove the real binary over stdio, same framing
`talk_with` uses: `initialize` with that `rootUri` +
`workspace/didChangeConfiguration` for the wide index scope +
`workspace/symbol` queries): both declared modules found exactly once,
finished in-process with no hang. **File counts agree between CLI and
server for the same tree (2 and 2).**
Explicit file argument that is a symlink to a directory, and a start
directory that is itself a symlink: both work, both find the expected
file under the given spelling.
*43.2 — comment-slot attacks, all via `format --stdout`, then idempotency
(format twice) and a before/after comment-count check on every shape:*
`wire /* c */ #5 w;`, `wire // c` + `#5 w;` on the next line, `wire [7:0]
/* c */ #1 b = c;`, `wire # /* c */ 5 w;` (`after_hash`), both slots at once
(`wire /* c1 */ # /* c2 */ 5 w;`), two comments in one slot
(`wire /* one */ /* two */ #5 w;`), a comment on the after-type side
(`wire [7:0] /* c */ #1 b = c;`), `tri`/`wand` with a delay comment,
an attribute ahead of the module. All ten: format cleanly, round-trip
idempotent, comment count preserved exactly. The refused shapes stayed
refused and did **not** corrupt: all four gaps inside `#(1:2:3)` — before
`1`, around each `:`, after `3` — still fail with a `verification failed:
token stream diverges` error and no output, matching the "not taken" scope
in Handshakes (topo §2.9-22). Ran the gap fuzzer directly
(`cargo test -p vlog_formatter a_comment_in_every_rtl_gap_still_formats`
under guard): passes; confirmed `EXPECTED_RTL_GAPS` is 374 in the tree and
that the added fixture (`wire #5 a;\n wire [7:0] #1 b = c;`) genuinely
exercises both new slots (both are comment-free in the fixture itself, but
the fuzzer inserts a comment into every inter-token gap in turn, which is
what raised the count from 352).
*Gates, all guarded.* `cargo fmt --check` (five touched crates): clean.
`cargo clippy --all-targets`: clean, 0 warnings. `cargo test --workspace`:
**3 788 passed, 0 failed** — matches the work log exactly. Re-ran just
`lucisv_core`'s `walk::tests` in isolation: 17 passed (11 pre-existing + the
6 new ones), including the 6 cycle tests as their own filtered run.
`tools/corpus_check.sh`: **814/820 (99.3%)**, same 6 failures
(`ibex/dv/formal/check/peek/compare_helper.sv`,
`ibex/dv/uvm/core_ibex/riscv_dv_extension/riscv_core_setting.tpl.sv`,
`ibex/syn/rtl/latch_map.v`,
`ibex/vendor/google_riscv-dv/src/riscv_instr_cover_group.sv`,
`picorv32/scripts/romload/testbench.v`,
`picorv32/scripts/smtbmc/mulcmp.v`), same 10 already-clean files.
`node editors/vscode/smoke.js target/release/lucisv-server`: OK, 20
messages.
*Byte-identity vs 0.42.0.* Over the 820-file corpus, each file individually
through `format --stdout` (bypasses directory-walk dedup, isolates the
formatter itself): **0 differing**, exit codes included. Opentitan
`format --check` (using `--no-cache` on both sides after the first pass
showed cache-hit-count noise from a shared `.lucisv_cache`; see below) over
`hw/ip`, `hw/top_earlgrey/ip`, `hw/top_darjeeling/ip`, `hw/dv`, `hw/vendor`:
`hw/top_earlgrey/ip`, `hw/top_darjeeling/ip`, `hw/dv`, `hw/vendor` are
byte-identical between the two binaries (including exit codes: 1, 2, 1, 2
respectively). **`hw/ip` differs by exactly one file**:
`hw/ip/tlul/rtl/tlul_adapter_vh.sv` is reported "would reformat" by 0.42.0
and silently absorbed (not reported at all) by the new binary — 1773 vs.
1772 files. Root-caused, not a §43 regression: `hw/ip/tlul/rtl` contains
`tlul_adapter_shim.sv -> tlul_adapter_vh.sv`, a **symlinked file next to its
own target in the same directory**, and `crates/lucisv/src/main.rs`'s
`dedup()` (canonical-path fold, keeps the first spelling — this is §41,
already in trunk, *not* touched by this diff, and shipped in a release
*after* 0.42.0 per the loop order in `TODO.md`) now folds
`tlul_adapter_shim.sv`/`tlul_adapter_vh.sv` onto one entry, keeping
`tlul_adapter_shim.sv` (alphabetically first) and dropping the other.
Reproduced in isolation on a two-file scratch directory
(`real.sv` + `shim.sv -> real.sv`) with both binaries, `--no-cache`: 0.42.0
reports both, the new binary reports one — confirms this is `main.rs`'s
existing dedup (unmodified by 43.1/43.2) becoming visible only because the
0.42.0 baseline predates it, not anything in this round's diff. Filed as
**informational**, not a §43 finding: the "byte-identity vs 0.42.0" gate is
not a clean isolation of this round alone once §41/§42 sit between the
baseline and trunk; recommend future rounds diff against trunk-before-the-
lane (or the `wip-43` backup already under
`~/.cache/lucisv-baselines/`) for a true delta, and use 0.42.0 only for the
"nothing has moved since the last *release*" question. Confirmed
`git -C ~/repo/opentitan status --porcelain` still shows only the three
expected pre-existing modifications (`hw/ip/aes/dv/tb/tb.sv`,
`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`)
after all opentitan runs; `.lucisv_cache/` is gitignored and untouched by
this statement either way.
*Verdict:* **PASS.** No corruption, no idempotency break, no dropped
comment, in any attack. Both hard invariants around cycles (identity,
no budget) and the two new comment slots hold up under adversarial input,
and the refused inside-`#(...)` gaps stay refused rather than silently
accepted. Two behavioural points are flagged above for the lead's ruling
(the dangling-symlink silence, MEDIUM; the link-to-`/` full-run abort on a
permission wall, LOW/pre-existing) plus one informational note on the
baseline choice for byte-identity gates — none of them block this round.
## Review
**2026-09-05 — lead.** Accepted; ships in 0.43.0. 43.1 is the ruled policy
in one method — identity is the whole rule, and QA's cycles of every shape,
the 50-link chain and the two-link cycle all terminate with each file once.
The dev's `after_hash` slot beyond the plan is accepted: the gap fuzzer's
zero-failure bar made it necessary, and four lines on the same construct is
the right size; the `#(1:2:3)` interior stays §2.9-22's. The one behaviour
change QA flagged is corrected above so no user loses an error they had.
Both front ends share the walk unchanged in signature, and the byte-identity
gate over the corpus is 0 differing.
+29
View File
@@ -0,0 +1,29 @@
# Manual extension-host acceptance — checklist
The one test of the VS Code extension that is not `editors/vscode/smoke.js`.
Run it on a release build (`code --install-extension lucisv-<v>-darwin-arm64.vsix --force`)
with `/Users/guoliangchen/repo/opentitan` open as the workspace. About an
hour. Record the release, the date and any failure in the table at the end.
| # | Step | Expected |
|---|---|---|
| 1 | Open `hw/ip/aes/rtl/aes.sv`. Status bar. | "lucisv" item appears; no error toast; Output → lucisv shows the server version. |
| 2 | Wait for the scan bar to finish. Hover `aes_core` in an instantiation. | Hover card with the module's header and file:line; F12 jumps to `aes_core.sv`. |
| 3 | Insert a tab at the start of a line. | A `no-tabs` squiggle within a second; lightbulb offers "Replace tab"; fix-on-save (`editor.codeActionsOnSave` with `source.fixAll.lucisv`) removes it. Undo. |
| 4 | Cursor on `.clk_i` in an instantiation; open the lightbulb. | Port refactorings listed instantly (no hitch); picking one applies an edit (undo). |
| 5 | Format Document (Shift+Alt+F) on `aes.sv`. | Reformats without an error toast; Format again is a no-op. Undo all. |
| 6 | Settings → search "lucisv.lint". | Every rule has a toggle; `severity.style` off removes all style squiggles immediately. Restore. |
| 7 | Add `[lint] select = ["no-tabs"]` in a scratch `lucisv.toml` beside the file. | Only `no-tabs` diagnostics remain; removing the file restores the defaults. |
| 8 | Theme: switch Dark+ → Light+ → High Contrast. | Semantic highlighting readable in all three; no invisible tokens. |
| 9 | Zoom: View → Appearance → Zoom In ×3, then reset. | Hierarchy view and hover cards scale; nothing clipped. |
| 10 | Keyboard only: `Ctrl+Shift+O` (symbols), `F12`, `Shift+F12`, `F2` rename, `Esc`. | Every action reachable without the mouse; rename preview shows all files. |
| 11 | Screen reader (VoiceOver, ⌘F5): tab through the lucisv hierarchy view. | Each row announced with its name; the toggle buttons announced. Turn VoiceOver off. |
| 12 | Old server: point `lucisv.server.path` at `~/.cache/lucisv-baselines/lucisv-0.39.0`'s sibling server if kept, else skip. | Extension warns about the version mismatch and still works. Reset the setting. |
| 13 | The other VSIX shape: install the `lucisv-<v>-universal.vsix` (no bundled server) with the CLI on PATH. | Same behaviour as steps 1–5. |
| 14 | Restart the server (command palette: "lucisv: Restart Server"). | Diagnostics return within a few seconds; no duplicate status items. |
## Runs
| Release | Date | Result | Failures (step, what happened) |
|---|---|---|---|
| | | | |
+62
View File
@@ -709,6 +709,37 @@ subsuming folder is twenty times the old scope, skipping the overlap saves 5 %.
What the round bought is in the landing figure, and it grows with the workspace's
vocabulary — which is why the opentitan table above is the one that matters.
## Measurement round — take 3 on opentitan (2026-09-05)
`docs/performance_take3.md` — 0.43.0 (`73799f3`) against a 0.39.0 server built
from the tag for the comparison, plus the first CLI sweeps (`format --check`
and `check` over five opentitan trees, 0.39.0 / 0.41.0 / 0.43.0, wall clock and
peak RSS). Read-only round: nothing was fixed, findings were filed.
The three headline numbers:
- **`codeAction` on the hot path: 37 ms → 5 ms** at the `aes` cursor and
**185 ms → 16 ms** at a 128-file fan-out, for a client that advertises
`codeAction.resolveSupport` — §37.1's lazy offer, and it is flat in the
fan-out where the eager path is linear in it. The whole hot path is now
inside the frame budget; `codeAction` leaves the queue-blocking table it
headed in both earlier takes.
- **The first RTL `didOpen` at the shipped default: 1 411–1 568 ms →
365 ms warm.** Take 2 called this "the wave's one real regression"; round 8
above plus the index cache took it apart, and 0.39.0 already measures it, so
it is closed.
- **The CLI is 0.6 s for `format --check` over `hw/ip`'s 1 807 files** and
0.40 s to lint them, at ~230 MB peak RSS — essentially flat across the three
binaries.
Three findings filed, none fixed: the **eager** `codeAction` path (a client
without `resolveSupport`) is ~1.37× slower than take 2 at every fan-out, and
0.39.0 already shows it; a `didOpen` of a file already in scope delays the next
request by 21–51 ms where take 2 measured 2–4 ms; and `lucisv check` is 6–10%
slower than 0.39.0 (0.367 → 0.400 s on `hw/ip`). Take 3 also has something
neither earlier take did — **a server-side column**, from the shipped
`--verbose` flag, which confirms the wire numbers to within 0.4 ms.
## What it would take to go faster
Ranked by what the measurements above say is there, with what each would
@@ -1047,3 +1078,34 @@ for one keystroke in a 10 000-line buffer, roughly 30 ms of it lex and parse.
That is the figure any incremental-parsing proposal has to be argued against,
and it now exists.
### 2026-09-05 — the `didOpen` delay (TODO §46, 0.44.0)
Take 3's §8.4 (a `didOpen` of an already-indexed file delaying the next
request by 21–51 ms) measured and fixed. The breakdown, taken with temporary
timings on a release build and re-taken after: the tolerant parse plus the
semantic analysis is 1.3 / 3.0 / 91 ms for a 326- / 1 145- / 42 192-line
opentitan file, and the lint pass was 4.9 / 54 / 1 654 ms — of which
`undriven-net` alone was 4.4 / 52 / 1 608. The rule asked
`WorkspaceIndex::files_mentioning` (a walk over all 3 976 indexed files) once
per declaration, ahead of the local guards that silence almost all of them.
Moved behind them, where `unused-signal` has always asked.
Wire time, `didOpen` → the request behind it, workspace scope, warm store,
three tries, M1 Max:
| file | before | after |
|---|---|---|
| `aes.sv` (326 L) | 8.1 / 5.9 / 10.1 ms | 4.3 / 1.8 / 2.3 ms |
| `aes_core.sv` (1 145 L) | 56.2 / 54.0 / 48.0 ms | 5.9 / 6.9 / 6.3 ms |
| `hmac.sv` | 56.8 / 42.7 / 51.0 ms | 4.7 / 5.7 / 3.3 ms |
| `kmac.sv` | 69.3 / 72.1 / 70.6 ms | 7.9 / 5.3 / 8.8 ms |
| `spi_device.sv` | 94.2 / 103.4 / 88.6 ms | 6.0 / 8.6 / 8.7 ms |
| `pinmux_reg_top.sv` (42 192 L) | 1 742 / 1 740 / 1 757 ms | 116.5 / 116.2 / 117.3 ms |
The same cost was paid on **every keystroke flush**, not just on opens: the
change debounce ends in the same `set_document` + `publish` pair. 0.39.0
measures the same as 0.43.0 everywhere in the "before" column, so this was
never a regression — the rule had been ordered that way since it was
written. Published diagnostics are byte-identical before and after. Full
account: `docs/features/didopen-cost/README.md`.
+785
View File
@@ -0,0 +1,785 @@
# lucisv performance against opentitan — take 3
Same corpus, same scenarios, same machine as
[`performance.md`](performance.md) (take 1) and
[`performance_take2.md`](performance_take2.md) (take 2); two new binaries and
one new question. Take 2 measured `ee1efe3` — the merged performance wave.
Take 3 measures **0.43.0 (`73799f3`)** against **0.39.0 (`0757503`)**, and
every table carries take 2's number beside them so each row is a before/after.
This round also covers the **CLI** for the first time: `format --check` and
`check` over five opentitan trees, three binaries, wall clock and peak RSS.
Every LSP number is a client-observed round trip on a monotonic clock
(`time.perf_counter`) — what the editor, and therefore the user, actually
experiences. Read §9 before quoting any of them.
---
## 0. Read this first — take 3 *does* have a server-side column
Take 1 and take 2 both opened with "no server-side instrumentation": their
binaries carried no timing literals, so every number was a client round trip
against a transport floor.
**That is no longer true, and it is an improvement, not a contamination.** The
shipped server has a `--verbose` flag (`docs/features/verbose-timing/`) that
logs `timing: <method> answered in <n> ms` per request over
`window/logMessage`. It is present in 0.39.0 and in 0.43.0 and absent from
take 2's binary. Nothing was added for this round: the default (no `--verbose`)
sessions produce every number in this document, and one supplementary session
per shape was re-run *with* `--verbose` to check the wire against the server's
own clock.
| `codeAction` at the cursor | wire, no `--verbose` | wire, `--verbose` session | server's own line |
|---|---:|---:|---:|
| `prim_flop_2sync` (128), eager | 270.2 / 252.9–255.2 ms | 252.5 / 244.8–254.6 ms | 252.28 / 244.55–254.46 ms |
| `prim_flop_2sync` (128), lazy | 24.0 / 15.6–16.9 ms | 22.4 / 13.4–14.6 ms | 22.04 / 13.21–14.41 ms |
| `aes` (6), eager | 66.1 / 45.7–48.2 ms | 64.6 / 47.0–47.8 ms | 64.26 / 46.78–47.66 ms |
| comment line | 1.8 / 0.7–0.8 ms | 1.7 / 0.7–0.8 ms | 1.30 / 0.58–0.68 ms |
**The wire is the server plus 0.2–0.4 ms, everywhere.** Take 1's and take 2's
central assumption — `client round trip ≈ server handling + ~0.05 ms` — is now
measured rather than assumed, and it holds with a slightly fatter floor
(0.2–0.4 ms rather than 0.05 ms, this harness being a Python client rather
than take 2's).
The transport baseline (an unknown method, `$/lucisvNoSuchMethod`, rejected
without work) is correspondingly higher in take 3:
| | take 1 | take 2 | take 3, 0.43.0 | take 3, 0.39.0 |
|---|---:|---:|---:|---:|
| transport baseline, first in a settled session | 0.02 ms | 0.019 ms | 0.24 ms | 0.31 ms |
| transport baseline, repeats | ≈0.05 ms | ≈0.05 ms | 0.059–0.092 ms | 0.057–0.064 ms |
**So every sub-millisecond row in take 3 sits on a ~0.06 ms floor rather than
take 2's ~0.02 ms, and roughly 0.04 ms of every such row's "slowdown" against
take 2 is this harness.** No conclusion is drawn below from any individual
sub-0.3 ms movement.
---
## 1. Environment and provenance
| | take 2 | take 3 |
|---|---|---|
| Machine | Apple M1 Max, 10 cores, 64 GB | **same machine** |
| OS | macOS 27.0 (26A5421a) | macOS 27.0 (**26A5425a**) |
| Date | 2026-08-29 ~00:45–02:00 | **2026-09-05 ~02:45–04:00** |
| Server under test | `ee1efe3`, 4 155 456 B, sha256 `a45d814c…` | **0.43.0 `73799f3`, 5 676 528 B, sha256 `0da08f40…`**, Mach-O arm64 |
| Baseline server | take 1's `bf9170a`+ | **0.39.0 `0757503`, 5 517 936 B, sha256 `58f7044e…`** — built for this round in a scratch `git worktree` at `v0.39.0`, `cargo build --release -p lucisv_server`, removed afterwards |
| CLI binaries | *not measured* | 0.43.0 `target/release/lucisv` (2 828 576 B, `89379a12…`), 0.41.0 (`5be28f2c…`) and 0.39.0 (`4caf841f…`) from `~/.cache/lucisv-baselines/` |
| Corpus | `/Users/guoliangchen/repo/opentitan` @ `0098135264` | **same commit**, 3976 indexed + 3 skipped — but see the one corpus difference below |
| Scenario file | `hw/ip/aes/dv/tb/tb.sv`; `aes` at 0-based 44:2 | same file, same position, resolved from the text at run time |
| Client | `scratchpad/perf2/*.py` (no longer on disk) | **a new client, `scratchpad/perf3/{lspclient,bench}.py`** — same shape, written from take 2's §1 description |
| Guard | — | **every server, `lucisv` and `cargo` run went through `tools/guard.sh -m 8 -t 1800`. No guard kill occurred.** |
### 1a. The one corpus difference, and it matters for two columns
`hw/ip/aes/dv/tb/tb.sv` is still modified in the checkout, but **the
modification is no longer the trailing-space edit take 2 measured against — the
file has since been reformatted by lucisv**, and is now lucisv-clean. Two
consequences, both of which make take-3 columns *not* comparable to take 2's:
- `textDocument/diagnostic` (pull) returns **0 items** at every scope in take 3,
where take 2 quoted "one `no-trailing-whitespace` item".
- `textDocument/codeAction` on the `aes` instantiation and on a comment line
returns **0 actions** in take 3, where take 2 recorded 1 at each. That one
action was the `source.fixAll.lucisv` quick fix the trailing-space diagnostic
raised; with no diagnostic there is nothing to fix. The *timings* are
unaffected — the cost is the port-refactoring fan-out, not the quick fix
(§6a proves this: the numbers track the fan-out, and the comment-line row is
0.7 ms in both takes).
The other two modified files (`hw/top_{darjeeling,earlgrey}/ip/ast/rtl/ast.sv`)
are unchanged from take 2 and are not in any scenario.
### 1b. The client, and what it does differently
The take-2 scripts were gone from the scratchpad, so take 3's client was
rewritten from take 2's §1 description. It is the same shape: framed
JSON-RPC over the server's stdio, `workspace/configuration` answered with a
per-session scope word, cache warmth controlled through
`initializationOptions.storagePath` (take 2's methodology fix, kept), positions
resolved from the file text at run time, every request timed from send to
response. Three deliberate differences:
1. **Client capabilities are settable per session.** A "VS Code-style" session
advertises `textDocument.codeAction.resolveSupport.properties: ["edit"]`
and gets §37.1's lazy offer; a session without it gets the eager shape.
Both are measured everywhere `codeAction` appears.
2. **A `--verbose` variant** of the codeAction sessions (§0).
3. **`.clk_i` is the one in the `aes` port list, 0-based 45:5.** Take 2's §1
says "line 49", which is `.output_valid_o()` in this file; the first
`.clk_i` in the file is on 0-based line 34, in a different instantiation.
Take 3 states its position rather than inheriting an ambiguous one, so the
two `references`-on-`.clk_i` rows below compare cost, not result sets.
---
## 2. Summary table — worst first, take 2 → take 3
Workspace scope, warm cache, unless the row says otherwise. "Repeats" is the
range over the 2nd–4th identical request in the same session; the "first" column
is that request issued as the first real request of a dedicated session.
| Action | T2 first | T2 repeats | **0.43.0 first** | **0.43.0 repeats** | 0.39.0 first | 0.39.0 repeats |
|---|---:|---:|---:|---:|---:|---:|
| Workspace scan, **cold** cache (didOpen → 3976 indexed) | 2 958 ms | 2 919 – 2 955 | **2 867 ms** | 2 754 – 2 773 | 2 764 ms | 2 752 – 2 756 |
| `textDocument/codeAction`, `prim_flop_2sync` (fan-out 128), **client without `resolveSupport`** | 200.7 ms | 184.9 – 186.2 | **270.2 ms** | 252.9 – 255.2 | 267.5 ms | 230.7 – 246.4 |
| `textDocument/rename` on `aes` (edits computed, not applied) | 115 ms | 107 – 121 (7 files) | **151.8 ms** | 139.1 – 140.7 (**9 files**) | 147.4 ms | 137.4 – 139.1 (9 files) |
| — anything queued behind that rename | 108 ms | — | **160.8 ms** | — | 162.0 ms | — |
| `textDocument/codeAction`, `prim_alert_sender` (67), no `resolveSupport` | 163.6 ms | 138.8 – 139.8 | **213.4 ms** | 196.0 – 196.5 | 210.3 ms | 191.7 – 194.6 |
| `textDocument/codeAction`, `prim_lc_sync` (42), no `resolveSupport` | 123.5 ms | 94.4 – 95.3 | **148.0 ms** | 128.9 – 130.4 | 137.7 ms | 125.4 – 126.8 |
| `codeAction/resolve` at the one cursor that offers an action (`aes_wrap.sv`, 6) | — | — | **119.5 ms** | 119.5 – 121.9 | *n/a* — no resolve at 0.39.0 | |
| Workspace scan, **warm** cache | 1 476 ms | 1 495 – 1 558 | **1 229.8 ms** | 1 220.5 – 1 229.7 | 1 227.9 ms | 1 218.1 – 1 225.1 |
| First `didOpen` of an RTL file **at the default scope** (`aes.sv`, widens to `hw/ip`) | 1 731 ms cold | 1 411 – 1 568 warm | **1 081.6 ms cold** | **365.1 ms warm** | 1 078.6 cold | 355.5 warm |
| diagnostics **publish** after a `didChange` (new row; ~150 ms of it is the debounce) | — | — | **161.1 ms** | 159.6 – 163.4 | 153.4 ms | 153.2 – 160.9 |
| `textDocument/codeAction`, `prim_flop_2sync` (128), **client with `resolveSupport`** (the lazy offer) | *n/a* | | **24.0 ms** | **15.6 – 16.9** | *n/a* — no lazy offer before 0.41.0 | |
| `codeAction` offer at the `aes_wrap.sv` cursor, lazy | — | — | **33.3 ms** | 21.2 – 26.8 | 119.7 ms (eager) | 117.4 – 119.3 |
| `codeAction` **on the `aes` instantiation**, lazy | 39.2 ms | 36.4 – 37.6 | **5.15 ms** | **4.05 – 4.24** | 59.7 ms (eager) | 45.8 – 46.1 |
| — definition pipelined behind that codeAction | 37.7 ms | 37.2 | **5.15 ms** | — | 59.7 ms | — |
| `codeAction`, `aes_reg_top` (fan-out 1), lazy | 19.8 ms | 13.2 – 17.4 | **27.1 ms** | 16.4 – 20.6 | 16.9 ms *(eager)* | 13.2 – 14.3 |
| `workspace/symbol "aes"` (256 results) | 6.6 ms | 6.6 – 7.4 | **8.8 ms** | 7.2 – 7.9 | 9.0 ms | 8.4 – 8.7 |
| — anything queued behind it | 6.9 ms | — | 11.0 ms | — | 11.9 ms | — |
| `textDocument/completion` at 0 typed characters (512 items) | 14.8 – 18.6 ms | — | **9.5 ms** | **2.3 – 2.8** | 5.2 ms | 3.0 – 3.3 |
| `textDocument/completion` at 1 typed character | 15.3 ms | 14.2 – 19.4 | **3.2 ms** | **2.5 – 2.7** | 3.8 ms | 3.0 – 3.1 |
| `textDocument/completion` at `aes_reg` | 0.59 ms (20 items) | 0.36 – 0.63 | **3.8 ms (512 items)** | 2.9 – 3.0 | 3.9 ms (512) | 2.6 – 2.9 |
| `codeAction` on a **comment line** (contrast) | 0.70 ms | 0.47 – 0.49 | 1.69 ms | 0.66 – 0.81 | 4.50 ms | 0.56 – 0.87 |
| `textDocument/references` on `aes` | 0.66 ms (7 hits) | 0.38 – 0.43 | **0.85 ms (14 hits)** | 0.54 – 0.61 | 0.92 ms (14) | 0.55 – 0.58 |
| `textDocument/signatureHelp` inside the port list | 0.57 ms | 0.44 – 0.58 | 0.70 ms | 0.57 – 0.62 | 0.67 ms | 0.64 – 0.74 |
| `textDocument/references` on `.clk_i` | 0.62 ms (10 hits) | 0.48 – 0.55 | 0.56 ms (12 hits) | 0.51 – 0.72 | 0.55 ms (12) | 0.61 – 0.65 |
| `didChange` flush (measured with a `foldingRange` barrier) | 0.48 ms | 0.33 – 0.45 | 0.95 ms | 0.58 – 0.80 | 0.77 ms | 0.60 – 0.91 |
| `textDocument/inlayHint` (whole file, 4 hints) | 0.38 ms | 0.23 – 0.34 | 0.49 ms | 0.26 – 0.43 | 0.45 ms | 0.25 – 0.27 |
| `textDocument/prepareRename` on `aes` (pressing F2) | 0.07 ms | 0.05 – 0.09 | 0.31 ms | 0.08 – 0.16 | 0.18 ms | 0.07 – 0.08 |
| — anything queued behind that prepareRename | 0.1 ms | — | 0.37 ms | — | 0.50 ms | — |
| `textDocument/diagnostic` (pull, 0 items — §1a) | 0.11 ms | 0.06 | 0.34 ms | 0.17 – 0.19 | 0.31 ms | 0.16 – 0.20 |
| `textDocument/definition` on `aes` | 0.27 ms | 0.05 – 0.11 | **0.19 ms** | 0.07 – 0.09 | 0.41 ms | 0.06 – 0.08 |
| `textDocument/semanticTokens/full` (251 tokens) | 0.16 ms | 0.14 – 0.16 | 0.21 ms | 0.19 – 0.25 | 0.21 ms | 0.16 – 0.19 |
| `textDocument/hover` on `aes` | 0.13 ms | 0.08 – 0.13 | 0.18 ms | 0.06 – 0.08 | 0.13 ms | 0.05 – 0.08 |
| `textDocument/documentSymbol` | 0.16 ms | 0.11 – 0.48 | 0.18 ms | 0.12 – 0.15 | 0.18 ms | 0.12 – 0.13 |
| `textDocument/foldingRange` | 0.05 ms | 0.04 – 0.08 | 0.10 ms | 0.05 – 0.07 | 0.05 ms | 0.05 – 0.06 |
| `textDocument/selectionRange` | 0.08 ms | 0.04 – 0.05 | 0.09 ms | 0.05 | 0.09 ms | 0.05 |
| `textDocument/documentHighlight` (1 result) | 0.04 ms | 0.04 – 0.07 | 0.10 ms | 0.04 – 0.05 | 0.05 ms | 0.04 – 0.05 |
| `textDocument/codeLens` | 0.05 ms | 0.04 – 0.06 | 0.07 ms | 0.04 – 0.05 | 0.06 ms | 0.04 |
| `textDocument/typeDefinition` on `aes` | 0.07 ms | 0.05 – 0.06 | 0.06 ms | 0.05 – 0.06 | 0.08 ms | 0.05 – 0.07 |
| `textDocument/documentLink` | 0.09 ms | 0.05 – 0.07 | 0.06 ms | 0.04 – 0.05 | 0.05 ms | 0.04 – 0.05 |
| `initialize` → response | 2.1 – 8.9 ms | — | 2.3 – 4.4 ms | — | 2.1 – 4.9 ms | — |
| *transport baseline (does no work)* | *0.019 – 0.14 ms* | — | *0.06 – 0.24 ms* | — | *0.06 – 0.31 ms* | — |
**The one-line reading of that table:** 0.43.0 and 0.39.0 are the same server
on almost every row. The single structural difference between them is
`codeAction` for a client that can resolve — §37.1 — and it is worth **11.8×**
on the hot path (59.7 → 5.15 ms at the `aes` cursor, 246 → 16 ms at a 128-file
fan-out). Everything else that moved since take 2 moved *before* 0.39.0, and
some of it moved the wrong way (§8).
---
## 3. The queue-blocking analysis — `codeAction` finally leaves the list
The server still runs a single-threaded request loop, so the latency a user
feels for request *R* is *R*'s cost plus everything queued ahead of it. Each
slow request was sent, then — back to back, no wait — the three requests a real
editor fires on every cursor move.
| Sent first (the blocker) | Its own cost, T2 | **0.43.0** | 0.39.0 | `definition` behind it, T2 | **0.43.0** | 0.39.0 |
|---|---:|---:|---:|---:|---:|---:|
| `codeAction` on the `aes` token | 37.4 ms | **5.07 ms** | 59.6 ms | 37.4 ms | **5.15 ms** | 59.7 ms |
| `prepareRename` on `aes` | 0.1 ms | 0.34 ms | 0.35 ms | 0.1 ms | 0.37 ms | 0.50 ms |
| `rename` on `aes` | 107.7 ms | 160.8 ms | 162.0 ms | 107.7 ms | 160.8 ms | 162.1 ms |
| `workspace/symbol "aes"` | 6.9 ms | 11.0 ms | 11.9 ms | 7.0 ms | 11.1 ms | 12.0 ms |
`hover` and `documentSymbol` behind each leader land 0.05–0.5 ms after the
definition, as in both earlier takes: the queue is still strictly serial and
the follower still pays the leader's bill almost exactly.
Take 1 and take 2 both named `codeAction` as the worst thing on the hot path —
take 2 called it "the single worst thing" and asked for memoisation or an
index-only answer. §37.1 did the second of those for the *offer*, and the row
is now 5 ms: **under the 16 ms frame budget, on a request that fires on every
cursor move.** Take 2's two structural conclusions survive with one amendment:
1. The absolute number still matters more than the ratio.
2. `codeAction` and `completion` were "the only slow requests on the hot path".
Both are now inside the frame budget for a modern client (5 ms and 2–3 ms).
**The hot path is clean.** What is left slow is user-initiated
(`rename`, 160 ms), once-per-session (the scan, 1.2–2.9 s), or paid only by
a client that cannot resolve a code action (§6a).
---
## 4. Startup and scan, per scope config and cache state
Methodology unchanged: `didOpen tb.sv` → the last `$/progress` `end`, followed
by 1.5 s of silence, three runs per cell. "Cold" = the `storagePath` directory
was `rm -rf`'d immediately before; "warm" = it carries a previous session's
store.
| Scope config | Cache | T2 didOpen → settled | **0.43.0** | 0.39.0 | files |
|---|---|---:|---:|---:|---|
| **default** (`[{}]` — no opinion at all) | cold | 94.0 ms | **81.9 / 92.5 / 93.1 ms** | 94.6 / 94.6 / 87.0 ms | 124 |
| **default** | warm | 51.2 – 58.6 ms | **39.4 / 40.3 / 41.8 ms** | 31.7 / 35.8 / 40.2 ms | 124, 123 from cache |
| `{"index":{}}` (the "empty" reply) | cold | 94.6 – 100.0 ms | **88.8 / 90.1 / 94.5 ms** | 91.1 / 92.1 / 92.4 ms | 124 |
| `{"index":{}}` | warm | *n/a* | **34.7 / 39.1 / 39.3 ms** | 37.9 / 38.0 / 40.2 ms | 124 |
| explicit `scopeDepth: 0` | cold | 98.9 ms | **93.5 / 101.6 / 105.5 ms** | 98.7 / 103.2 / 104.6 ms | 1 (after a ~90 ms 124-file scan is thrown away) |
| explicit `scopeDepth: 0` | warm | 55.0 ms | **42.3 / 49.3 / 49.6 ms** | 41.6 / 47.1 / 50.5 ms | 1 |
| `workspace` | cold | 2 918 – 2 958 ms | **2 754 / 2 773 / 2 867 ms** | 2 752 / 2 756 / 2 764 ms | 3976, 3 skipped |
| `workspace` | warm | 1 476 – 1 558 ms (+ outliers to 3 073) | **1 220.5 / 1 229.7 / 1 229.8 ms** | 1 218.1 / 1 225.1 / 1 227.9 ms | 3975 from cache |
- `initialize` is still 2–5 ms and still does no scanning. (One 231 ms outlier,
on the first server process this session ever spawned — a cold `exec`, not a
measurement of anything.)
- **The 0.39.0 column is why this table needed a baseline.** The warm workspace
scan reads 1 476 ms in take 2 and 1 220 ms tonight — a 1.21× "improvement"
that is *entirely* machine and page cache, because 0.39.0 measures 1 228 ms
on the same night. No code change is responsible; take 2's own §9 warned
about exactly this and said to quote the band, not the number. **Take 3's
band for the warm workspace scan is 1 218 – 1 230 ms, and it is much tighter
than take 2's** (12 ms spread across six runs and two binaries, against take
2's 1 476–3 073) because tonight's machine was quieter.
- **Persistence buys ~57%** on the workspace scan (2 800 → 1 225 ms) and ~57%
on the default scope (90 → 39 ms). Take 2 measured 48% / 44%.
- **A cold workspace scan is not fully cold**, and this is a shape both earlier
takes had without recording it: the pulled `scope: "workspace"` arrives after
the default-scope scan is already in flight, so the trace is `0 files → 124
files (83–92 ms) → 3976 files`, and the workspace bar reports "123 from
cache" even on a wiped store — those 123 are the default scan's own writes,
read back seconds later. It costs 83–92 ms of the workspace total.
- Both binaries emit ~1 100 `$/progress` reports and ~4 100 `indexing:` log
lines on a cold workspace scan, as take 2 recorded.
### 4b. What each scope answers, at 0.43.0
Take 2's §4b table, re-taken. The `aes` instantiation in `tb.sv`:
| Request | default | explicit `scopeDepth 0` | workspace |
|---|---|---|---|
| `definition` | **1 result**, 0.18 ms | 0 results, 0.15 ms | 1 result, 0.19 ms |
| `typeDefinition` | 1 result | 0 results | 1 result |
| `hover` | 1 result | 0 results | 1 result |
| `references` | **11 results**, 0.44 ms | 0 results | **14 results**, 0.85 ms |
| `documentHighlight` | 1 result | 0 results | 1 result |
| `signatureHelp` | 1 signature, 0.83 ms | 0 results | 1 signature, 0.70 ms |
| `workspace/symbol "aes"` | 256, 3.0 ms | 0 results, 0.04 ms | 256, 8.8 ms |
| `completion` at a fresh line | 512 items, 3.3 ms | 276 items, 2.0 ms | 512 items, 3.3 ms |
| `inlayHint` (whole file) | **0** | 0 | **4** |
Everything take 2 found here still holds, and two counts grew: `references` at
workspace scope is 14 rather than take 2's 7, and at the default scope 11
rather than 4. 0.39.0 returns the same 14 and 11, so the growth predates it;
it costs 0.85 ms against take 2's 0.66 ms for half the results, which is the
right direction.
**`inlayHint` still returns 0 at the default scope and 4 at workspace, and
§37.2 ruled that correct.** The four hints `tb.sv` can carry come from
`pins_if` instantiations; `pins_if` is declared in
`hw/dv/sv/common_ifs/pins_if.sv`, which is nowhere under `hw/ip/aes` — the
default scope's root for this buffer. At that scope `definition`, `hover` and
`signatureHelp` answer nothing about `pins_if` either, so inlay is not missing
a lookup its neighbours have: the zero is a scope-reach result, not an
inlay-hint defect. Take 2's §8 item 9 ("a correctness gap") is **closed as
investigated, not as a bug**.
---
## 5. The `didOpen` widen
### 5a. At `scopeDepth 0` — apples to apples with take 1 and take 2
`tb.sv` open, then RTL files opened one at a time; the request sent immediately
afterwards waits for the widen.
| Widening `didOpen` | T2 cold | T2 warm | **0.43.0 cold** | **0.43.0 warm** | 0.39.0 cold | 0.39.0 warm |
|---|---:|---:|---:|---:|---:|---:|
| `hw/ip/aes/rtl/aes.sv` | 22.3 ms | 22.0 ms | **19.3 ms** | **18.5 ms** | 18.7 ms | 16.5 ms |
| `hw/ip/kmac/rtl/kmac.sv` | 33.5 ms | 18.1 ms | 32.9 ms | 25.9 ms | 32.5 ms | 23.9 ms |
| `hw/ip/hmac/rtl/hmac.sv` | 18.2 ms | 12.2 ms | 30.4 ms | 20.4 ms | 32.1 ms | 22.1 ms |
| `hw/ip/spi_device/rtl/spi_device.sv` | 83.4 ms | 45.7 ms | 85.2 ms | 37.0 ms | 84.0 ms | 35.8 ms |
`spi_device` is still the ceiling for the reason take 1 gave. The `hmac` row is
the one that moved the wrong way (12.2 → 20.4 ms warm) and 0.39.0 shows the
same 22.1, so it is not a 0.43.0 change; see §8.4.
### 5b. At the default scope — take 2's headline regression is 4× smaller
| Widening `didOpen` | T2 cold | T2 warm | **0.43.0 cold** | **0.43.0 warm** | 0.39.0 cold | 0.39.0 warm |
|---|---:|---:|---:|---:|---:|---:|
| `aes.sv` (widens `hw/ip/aes` → **`hw/ip`, 1 807 files**) | 1 731 ms | 1 411 – 1 568 ms | **1 081.6 ms** | **365.1 ms** | 1 078.6 ms | 355.5 ms |
| `kmac.sv` (already in scope) | 3.9 ms | 2.7 ms | 24.3 ms | 31.1 ms | 23.9 ms | 30.0 ms |
| `hmac.sv` (already in scope) | 3.6 ms | 2.1 ms | 22.6 ms | 21.1 ms | 24.8 ms | 22.1 ms |
| `spi_device.sv` (already in scope) | 3.6 ms | 4.0 ms | 47.6 ms | 51.2 ms | 46.3 ms | 49.4 ms |
**The first row is the best news in this document.** Take 2 called the ~1.5 s
first-RTL-open at the shipped default "the wave's one real regression" and "a
real 1.5-second hang on the single most common navigation a Verilog user
performs". It is now **365 ms warm** — a 3.9× improvement — and the warm case
finally beats the cold one, which take 2's did not (1 411 warm vs 1 731 cold
there; 365 warm vs 1 082 cold here). The index cache now serves the widen.
0.39.0 shows the same number, so the credit belongs to whatever landed between
`ee1efe3` and 0.39.0, not to §37 or §41–§43.
The other three rows moved the wrong way and are §8.4.
### 5c. What the widen does to the slow requests
Take 2's §5c shape: `aes.sv` is the *only* buffer opened, so the scope is
whatever that one file raises, and the same requests are asked at all three
configs. 0.43.0, lazy client, first / repeats:
| | T2 `depth0` | T2 default | T2 workspace | **0.43 `depth0`** | **0.43 default** | **0.43 workspace** |
|---|---:|---:|---:|---:|---:|---:|
| `codeAction` on the `prim_lc_sync` instantiation | 4.7 ms | 7.0 ms | 39.2 ms | **3.5 / 3.0–3.3** | **4.6 / 4.1–4.9** | **7.2 / 5.5–6.6** |
| `codeAction` on the `aes_reg_top` instantiation | — | — | — | 21.1 / 14.6–15.8 | 21.4 / 15.5–18.1 | 25.1 / 17.5–20.4 |
| `prepareRename` on `module aes` | 0.09 ms | 0.08 ms | 0.07 ms | **0.09 / 0.05–0.06** | 0.08 / 0.04–0.10 | 0.10 / 0.04–0.06 |
| `rename` on `module aes` | 10.5 ms | 15.8 ms | 115 ms | **10.7 / 10.1–10.6** | 21.0 / 19.9–20.8 | 141.6 / 139.7–156.9 |
| `workspace/symbol "aes"` (256 each) | 4.0 ms | 7.8 ms | 6.6 ms | 1.8 / 1.5–1.6 | 4.0 / 3.3–3.6 | 7.3 / 6.3–6.8 |
Take 2's cursor for the first row was "the instantiation" in a table whose
client is gone; take 3 names two instantiations in `aes.sv` and gives both,
because they differ by 5× for a reason worth seeing.
`prepareRename` is still flat in scope size — 0.04–0.10 ms at 40 files, at
1 807 and at 3 976 — which was the wave's aim. `rename` still scales with the
fan-out (10.7 → 141.6 ms), exactly as take 2 described. **The lazy
`codeAction` is nearly flat too**: 3.5 → 7.2 ms across a 100× scope range for
`prim_lc_sync`, against the eager path's 39 ms at workspace scope in take 2.
The `aes_reg_top` row is the counter-example and the shape of what is left:
21–25 ms, barely moving with scope, because the whole bill is reading and
parsing that module's own 1 945-line declaration file — a per-cursor cost the
offer cannot avoid without caching the declaration parse.
---
## 6. `codeAction`, offer and resolve — the round's main result
### 6a. Cost against the module's fan-out, three shapes
Workspace scope, warm cache, cursor on a module instantiation, four tries each.
"Lazy" is a client that advertises
`textDocument.codeAction.resolveSupport.properties: ["edit"]` (what VS Code
sends); "eager" is a client that does not.
| Module at the cursor | Files instantiating it | T2 (eager only) | 0.39.0 eager | **0.43.0 eager** | **0.43.0 lazy offer** | Actions |
|---|---:|---:|---:|---:|---:|---:|
| `aes_reg_top` (in `aes.sv`) | 1 | 19.8 / 13.2–17.4 | 16.9 / 13.2–14.3 | 27.7 / 16.3–21.8 | **27.1 / 16.4–20.6** | 0 |
| `aes` (in `tb.sv`) | 6 | 39.2 / 36.4–38.2 | 59.7 / 45.8–46.1 | 66.1 / 45.7–48.2 | **5.15 / 4.05–4.24** | 0 |
| `prim_lc_sync` (in `aes.sv`) | 42 | 123.5 / 94.4–95.3 | 137.7 / 125.4–126.8 | 148.0 / 128.9–130.4 | **17.3 / 7.2–8.6** | 0 |
| `prim_alert_sender` (in `aes.sv`) | 67 | 163.6 / 138.8–139.8 | 210.3 / 191.7–194.6 | 213.4 / 196.0–196.5 | **14.8 / 8.6–10.8** | 0 |
| `prim_flop_2sync` (in `aon_timer.sv`) | 128 | 200.7 / 184.9–186.2 | 267.5 / 230.7–246.4 | 270.2 / 252.9–255.2 | **24.0 / 15.6–16.9** | 0 |
| *(contrast) a comment line* | — | 0.70 / 0.47–0.49 | 4.50 / 0.56–0.87 | 1.80 / 0.71–0.78 | **1.69 / 0.66–0.81** | 0 |
| **`aes` in `aes_wrap.sv` — the one cursor that offers** | 6 | — | 119.7 / 117.4–119.3 | 143.8 / 123.9–124.4 | **33.3 / 21.2–26.8** | **1** |
Two results, and they point in opposite directions.
**The lazy offer works, and it is the round's headline.** At a 128-file fan-out
the offer is **15.6–16.9 ms against the eager path's 252.9–255.2 ms — 16×** —
and, unlike the eager path, it does not track the fan-out at all: 4 ms at 6
files, 8 ms at 42, 9 ms at 67, 16 ms at 128. What cost remains is the cursor's
*own* file plus the instantiated module's declaration file, which is why the
outlier is `aes_reg_top` (16–21 ms): that declaration is a 1 945-line, 51 KB
autogenerated register file, and reading one of those is the whole bill.
Take 2's "reads as a hang" line at ~200 ms is no longer crossed anywhere.
**`aes_reg_top` is the one cursor where the lazy shape is not a win**, and it
is worth saying plainly: 27.1 / 16.4–20.6 ms at 0.43.0 against 0.39.0's eager
16.9 / 13.2–14.3 ms. At a fan-out of 1 there is nothing for laziness to skip —
the eager path reads one instantiating file, the lazy path reads the module's
declaration, and here the declaration is the bigger of the two. It is one
frame, on the cheapest fan-out there is, and it does not change the direction
of the row above it; it is recorded so nobody re-derives it as a regression.
**The eager path got ~1.37× slower between take 2 and 0.39.0**, and 0.43.0
holds that level. 95 → 126 ms at 42 files, 139 → 193 at 67, 185 → 246 at 128 —
a consistent factor across four fan-out points, on a night whose scan rows are
*faster* than take 2's, so it is not the machine. It is filed as §8.2. Note who
pays it: only a client without `resolveSupport`, which since 0.41.0 is a
shrinking population, but Vim/Neovim setups and simple clients are in it.
**The measured offer is now `O(1)` in the fan-out, and the resolve is `O(fan-out)`
paid only on click.** For the one opentitan cursor that offers an action:
| | offer | resolve | total, if the user clicks | one-shot (eager client) |
|---|---:|---:|---:|---:|
| `aes_wrap.sv` 0-based 78:2, "lucisv: connect 2 missing ports" | 33.3 / 21.2–26.8 ms | **119.5 / 119.5–121.9 ms** | ~145 ms | 143.8 / 123.9–124.4 ms |
The `data`/`edit` split behaves exactly as §37.1 specifies: the lazy offer
carries `data` and **no** `edit`; `codeAction/resolve` returns the same title
with a 1-file `WorkspaceEdit`; the eager offer carries the edit inline. Both
titles are byte-identical (`lucisv: connect 2 missing ports`).
### 6b. How rare an offer actually is — a new measurement
Take 2 recorded "0 actions after 95–186 ms of work" as a surprise and asked for
a cheap pre-check. Take 3 measured how common that is. A sweep of every
instantiation-shaped line in **205 RTL files** — all 165 of `hw/ip/prim/rtl`
and all 40 of `hw/ip/aes/rtl` — found **exactly one position that offers a port
refactoring**: `hw/ip/aes/rtl/aes_wrap.sv` at 0-based 78:2. A separate sweep of *every*
identifier position in `hw/ip/prim/rtl/prim_lc_sync.sv` (557 identifier starts) found
zero.
That is the real shape of the problem take 2 pointed at, and it is the
strongest argument for §37.1 that exists: on this corpus the eager path spent
95–255 ms per cursor move to answer "no" essentially always. The two
refactorings are refused for structural reasons, not accidental ones —
`remove port` refuses when the module's own body still uses the port (real RTL
always does), and `connect missing ports` needs an instantiation that omits
one (real RTL rarely does). Nothing is broken; the lightbulb is simply almost
never lit, which is why computing its edit eagerly was the wrong trade.
### 6c. `prepareRename` and `rename`
`prepareRename` remains flat and free: 0.05–0.16 ms at every scope, on both
binaries, with the byte-identical answer take 2 pinned
(`{"placeholder":"aes","range":{"start":{"line":44,"character":2},"end":{"line":44,"character":5}}}`).
`rename` is 151.8 ms first / 139.1–140.7 repeats at 0.43.0 and
147.4 / 137.4–139.1 at 0.39.0, against take 2's 115 / 107.5–121.4. **It now
edits 9 files rather than take 2's 7**, so the per-edited-file cost is
16.9 ms against take 2's 16.4 — flat. The extra two files are the same
reference-set growth §4b sees. Variance stays tight (1.09× across repeats;
take 1's was 2.4×).
### 6d. `completion`
| Typed prefix | T2 items | T2 | **0.43.0** | 0.39.0 | 0.43 items |
|---|---:|---:|---:|---:|---:|
| `` (empty) | 512 | 14.8 – 18.6 ms | **9.5 / 2.3 – 2.8 ms** | 5.2 / 3.0 – 3.3 ms | 512 |
| `a` | 512 | 15.9 – 19.4 ms | **3.2 / 2.5 – 2.7 ms** | 3.8 / 3.0 – 3.1 ms | 512 |
| `ae` | 483 | 16.8 – 18.5 ms | **4.0 / 2.6 – 2.9 ms** | 3.9 / 2.8 – 2.9 ms | 512 |
| `aes` | 482 | 16.1 – 17.5 ms | 10.4 / 7.8 – 9.2 ms | 9.6 / 7.1 – 8.2 ms | 512 |
| `aes_` | 476 | 15.9 – 17.4 ms | 7.5 / 6.8 – 8.2 ms | 8.1 / 6.5 – 7.0 ms | 512 |
| `prim_` | 339 | 6.1 – 6.9 ms | 5.1 / 4.0 – 4.4 ms | 4.8 / 3.6 – 3.8 ms | 512 |
| `clk` | 512 | 2.8 – 3.0 ms | 4.4 / 3.3 – 3.9 ms | 4.7 / 3.4 – 3.6 ms | 512 |
| `aes_reg` | 20 | 0.36 – 0.63 ms | 3.8 / 2.9 – 3.0 ms | 3.9 / 2.6 – 2.9 ms | **512** |
| `zzzz` | 1 | 0.11 – 0.13 ms | 1.4 / 0.31 – 0.34 ms | 1.4 / 0.32 – 0.59 ms | 1 |
**Take 2's 15–18 ms plateau at 0–4 typed characters is gone: the whole curve is
2–10 ms**, another change that landed before 0.39.0. Take 2's §8 item 3
("four dropped frames per identifier typed") is closed.
Two honest caveats on this table. The item counts changed — `aes_reg` returns
512 rather than 20, and `ae`/`aes`/`aes_` return 512 rather than 476–483 —
so the two `aes_reg` numbers are not measuring the same work, and the row
that reads "slower" (0.6 → 3.0 ms) is answering 25× as many items. And the
curve's shape inverted again: `aes`/`aes_` (7–9 ms) are now the *worst*
prefixes, above the empty one (2.5 ms), where take 2 had them roughly level.
---
## 7. The CLI sweeps — first time measured
`format --check` and `check` over five trees, three binaries, three tries each,
wall clock and peak RSS from `/usr/bin/time -l`, everything under
`tools/guard.sh`. The formatter cache lives in a scratch `--cache-dir` outside
the opentitan tree; nothing was ever written into the corpus.
| Tree | files | command | 0.39.0 wall (first / repeats) | 0.41.0 | **0.43.0** | peak RSS, 0.39 → 0.43 |
|---|---:|---|---:|---:|---:|---:|
| `hw/ip` | 1 807 | `format --check`, cold cache | 0.67 / 0.59–0.62 s | 0.66 / 0.61–0.64 | **0.63 / 0.61–0.66** | 211 → 233 MB |
| `hw/ip` | | `format --check`, warm cache | 0.65 / 0.60–0.62 | 0.67 / 0.61–0.64 | **0.61 / 0.63–0.68** | 220 → 225 MB |
| `hw/ip` | | `check` (default rules) | 0.37 / 0.36–0.37 | 0.39 / 0.37–0.39 | **0.40 / 0.39–0.41** | 191 → 194 MB |
| `hw/ip` | | `check --select error,warning,style` | 0.42 / 0.41–0.43 | 0.43 / 0.43 | **0.45 / 0.47** | 187 → 198 MB |
| `hw/top_earlgrey/ip` | 46 | `format --check`, cold / warm | 0.04 / 0.04 | 0.04 / 0.03 | **0.04 / 0.03** | 34 → 39 MB |
| `hw/top_earlgrey/ip` | | `check` / `--select …` | 0.03 / 0.02 | 0.02 / 0.02 | **0.02 / 0.03** | 35 → 37 MB |
| `hw/top_darjeeling/ip` | 49 | `format --check`, cold / warm | 0.03 / 0.03 | 0.03 / 0.03 | **0.02 / 0.03** | 23 → 26 MB |
| `hw/top_darjeeling/ip` | | `check` / `--select …` | 0.02 / 0.02 | 0.02 / 0.02 | **0.02 / 0.02** | 28 → 29 MB |
| `hw/dv` | 365 | `format --check`, cold / warm | 0.06 / 0.06 | 0.07 / 0.06 | **0.07 / 0.07** | 32 → 30 MB |
| `hw/dv` | | `check` / `--select …` | 0.05 / 0.06 | 0.05 / 0.07 | **0.06 / 0.07** | 33 → 33 MB |
| `hw/vendor` | 287 | `format --check`, cold / warm | 0.11 / 0.10 | 0.11 / 0.11 | **0.12 / 0.11** | 51 → 48 MB |
| `hw/vendor` | | `check` / `--select …` | 0.07 / 0.08 | 0.07 / 0.09 | **0.08 / 0.10** | 53 → 58 MB |
- **The CLI is fast and essentially unchanged.** The biggest tree, 1 807 files,
is checked for formatting in 0.6 s and linted in 0.4 s, on ten cores, at
~200–230 MB.
- **`check` is 6–10% slower at 0.43.0 than at 0.39.0** on the two trees big
enough to measure it (`hw/ip` 0.367 → 0.400 s default rules, 0.420 → 0.463 s all
classes; `hw/vendor` 0.070 → 0.083 s). Consistent across all three tries and
both rule sets, and 0.41.0 sits between. Small in absolute terms; filed as
§8.5.
- **The formatter cache buys nothing on opentitan, and that is expected.** The
cold and warm rows are within noise of each other everywhere, because the
cache remembers *already-formatted* files and opentitan has almost none:
30 of 1 806 in `hw/ip`, 3 of 365 in `hw/dv`, 12 of 287 in `hw/vendor`. The
stores written are 4–8 KB. A tree that lucisv already formats would see the
opposite.
- Peak RSS scales with the tree, not the version: 23–58 MB for the four small
trees, 183–249 MB for `hw/ip`. No version is more than ~10% off any other on
the same row, and the ordering is not consistent, so nothing is claimed.
### 7a. Failure counts per tree, and every per-file outcome that changed
`format --check --no-cache` and `check`, full runs, both binaries:
| Tree | 0.39.0 `format --check` | **0.43.0** |
|---|---|---|
| `hw/ip` | 1773 would reformat, 30 unchanged, **4 failed** | **1772** would reformat, 30 unchanged, 4 failed |
| `hw/top_earlgrey/ip` | 46 would reformat | 46 would reformat |
| `hw/top_darjeeling/ip` | 48 would reformat, 1 failed | 48 would reformat, 1 failed |
| `hw/dv` | 361 would reformat, 3 unchanged, **1 failed** | **362** would reformat, 3 unchanged, **0 failed** |
| `hw/vendor` | 270 would reformat, 12 unchanged, **5 failed** | **271** would reformat, 12 unchanged, **4 failed** |
`check` findings: `hw/ip` 446 → **445**; `hw/top_earlgrey/ip` 14;
`hw/top_darjeeling/ip` 23; `hw/dv` 85; `hw/vendor` 231 + 1 file that cannot be
checked — every one of those unchanged. With `--select error,warning,style`:
`hw/ip` 7 735 → **7 734**, and 551 / 382 / 1 158 / 1 666 unchanged.
**Exactly three per-file outcomes changed since 0.39.0, and all three were
predicted:**
1. `hw/dv/sv/jtag_agent/jtag_if.sv` — was `parse error: 163:1: expected
\`endinterface\` (found "<eof>")`, now **would reformat**. §38.1, the rival
headers in a conditional region.
2. `hw/vendor/pulp_riscv_dbg/tb/unused/SimDTM.sv` — was `parse error: 40:15:
expected identifier (found "#")`, now **would reformat**. §38.2, the net
delay after the type.
3. `hw/ip/tlul/rtl/tlul_adapter_vh.sv` — was reported *beside* its symlink
alias `tlul_adapter_shim.sv`; now only the alias (the first spelling seen)
is reported, and the target is deduplicated away. §41.2, dedup by canonical
identity. The same one line disappears from `check`
(`tlul_adapter_vh.sv:43:101: style: line is 101 characters`), which is where
the 446 → 445 and 7 735 → 7 734 come from.
**Nothing else moved**, on any tree, for either command, at any rule set.
0.41.0's outcomes are byte-identical to 0.39.0's, which places all three
changes in 0.42.0/0.43.0 exactly as their sections say.
The seven files that still fail to parse, for the record:
`hw/ip/edn/dv/env/edn_env_cfg.sv`, `hw/ip/kmac/fpv/tb/keccak_2share_fpv.sv`,
`hw/ip/kmac/pre_dv/kmac_reduced_tb/rtl/kmac_reduced_tb.sv`,
`hw/ip/spi_device/dv/env/spi_device_scoreboard.sv`,
`hw/top_darjeeling/ip/ast/rtl/ast.sv` (a locally modified file),
`hw/vendor/lowrisc_ibex/dv/formal/check/peek/compare_helper.sv`,
`hw/vendor/lowrisc_ibex/dv/uvm/core_ibex/riscv_dv_extension/riscv_core_setting.tpl.sv`
(a template, not SystemVerilog), `hw/vendor/lowrisc_ibex/syn/rtl/latch_map.v`,
`hw/vendor/lowrisc_ibex/vendor/google_riscv-dv/src/riscv_instr_cover_group.sv`.
---
## 8. Findings — filed, not fixed
Ordered by how much they matter. Nothing in this list was fixed in this round.
### 8.1 CREDIT, not a finding — the five things that got faster
Stated first so the rest reads in proportion.
| What | take 2 | take 3 | Credit |
|---|---:|---:|---|
| `codeAction` at the `aes` cursor, resolving client | 39.2 / 36.4–37.6 ms | **5.15 / 4.05–4.24 ms** | **§37.1** (0.41.0) |
| `codeAction` at a 128-file fan-out, resolving client | 200.7 / 184.9–186.2 ms | **24.0 / 15.6–16.9 ms** | **§37.1** |
| The first RTL `didOpen` at the default scope, warm | 1 411–1 568 ms | **365 ms** | pre-0.39.0 (take 2's §8.1 regression) |
| `completion` at 0–4 typed characters | 14.8–19.4 ms | **2.3–4.0 ms** | pre-0.39.0 (take 2's §8.3 residual) |
| `definition` on `aes`, first try | 0.27 ms | 0.19 ms (0.39.0: 0.41 ms) | §37.3's index-only `locate`, ~2× on the first try; repeats were already at the floor |
Two of those close take-2 findings outright (its §8 items 1 and 3), and §37.2's
ruling closes its item 9.
### 8.2 FINDING (medium) — the eager `codeAction` path is ~1.37× slower than take 2
**What.** For a client that does *not* advertise
`codeAction.resolveSupport.properties: ["edit"]`, `codeAction` on a module
instantiation costs 1.35–1.40× what take 2 measured, at every fan-out:
| fan-out | take 2 repeats | 0.39.0 repeats | 0.43.0 repeats | factor vs T2 |
|---:|---:|---:|---:|---:|
| 42 | 94.4 – 95.3 ms | 125.4 – 126.8 ms | 128.9 – 130.4 ms | 1.37× |
| 67 | 138.8 – 139.8 ms | 191.7 – 194.6 ms | 196.0 – 196.5 ms | 1.40× |
| 128 | 184.9 – 186.2 ms | 230.7 – 246.4 ms | 252.9 – 255.2 ms | 1.37× |
**Reproduce.** `bench.py codeaction eager`; cursor on `prim_flop_2sync #(` in
`hw/ip/aes/../aon_timer/rtl/aon_timer.sv` at 0-based 83:2, workspace scope,
warm store, `tb.sv` also open; four tries. Server-side `--verbose` lines agree
with the wire to 0.3 ms (§0), so this is server work, not transport.
**Where it landed.** Between `ee1efe3` (take 2) and 0.39.0 — 0.39.0 already
shows it and 0.43.0 only adds ~3%. Not bisected; the candidates are §29–§35,
of which the linter expansion (§33–§35, 73 rules) is the one that touched
per-file work. Not attributed here.
**Why it is medium, not high.** It is paid only by clients without
`resolveSupport`, it crosses take 2's 200 ms "reads as a hang" line only at
fan-outs above ~67, and the same cursors cost 8–17 ms for a client that can
resolve. But it is still a per-cursor-move request and the trend is the wrong
way.
### 8.3 FINDING (low) — `rename` and its followers are ~1.4× slower in absolute terms
151.8 / 139.1–140.7 ms against take 2's 115 / 107.5–121.4, and anything queued
behind it pays 160.8 ms. **Half the difference is more work**: the edit set is
9 files rather than 7 (16.9 ms per edited file against 16.4 — flat). 0.39.0
measures the same, so nothing in 0.41.0–0.43.0 caused it. Reproduce:
`bench.py rename`, `textDocument/rename` on `aes` at `tb.sv` 44:2, newName
`aes_renamed`, workspace scope; the edits are discarded.
### 8.4 FINDING (low–medium) — a `didOpen` of a file already in scope costs 21–51 ms before the next request is answered
**What.** At the default scope, take 2 measured 2.1–4.0 ms for the request
following a `didOpen` of `kmac.sv` / `hmac.sv` / `spi_device.sv` — files
already inside `hw/ip` after the `aes.sv` widen, so no rescan happens. Take 3
measures 21–51 ms for the same three, on both binaries.
| file | size | T2 warm | 0.43.0 warm | 0.39.0 warm |
|---|---:|---:|---:|---:|
| `hmac.sv` | 33 KB | 2.1 ms | 21.1 ms | 22.1 ms |
| `kmac.sv` | 53 KB | 2.7 ms | 31.1 ms | 30.0 ms |
| `spi_device.sv` | 67 KB | 4.0 ms | 51.2 ms | 49.4 ms |
**It is the open, not the request.** A *second* `definition` at the same
position, issued right after the first, costs **0.07–0.21 ms** in every one of
these cells. So the 21–51 ms is work the `didOpen` queues (parse and analysis
of the newly opened buffer) that the next request waits behind, and it scales
with the file, which take 2's flat 2–4 ms did not.
**Caveat, stated plainly.** Take 2's client is gone from disk, so I cannot
prove its follow-up request was the same one at the same position. If it used a
cheaper barrier the comparison is not like-for-like. What take 3 *can* assert
without reference to take 2: opening a 67 KB file that is already indexed
delays the next request by 51 ms, three frames.
**Reproduce.** `bench.py widen default`, warm store; `didOpen spi_device.sv`
then immediately `textDocument/definition` at the first `module ` token.
**Fixed in 0.44.0 (TODO §46), and the finding understated it.** The delay is
not the widen, the diagnostics plumbing or §42's lint-run construction: it is
one rule. `undriven-net` asked the workspace census
(`WorkspaceIndex::files_mentioning`, a walk over every indexed file) once per
declaration in the buffer, *before* its own local guards had a chance to
silence it — so a file with four thousand declarations asked four thousand
questions and threw away four thousand answers. `unused-signal`, the twin
rule with the same oracle, has always asked last; `undriven-net` now does
too. At the whole-workspace scope, where the census covers 3 976 files rather
than this section's ~124, the same three files measured 51 / 70 / 95 ms
before and **4.6 / 7.3 / 7.8 ms** after, and opentitan's largest file,
`hw/top_darjeeling/ip_autogen/pinmux/rtl/pinmux_reg_top.sv` (42 192 lines),
went from **1 742 ms to 117 ms** (QA re-derived 1 805–1 825 → 104–108). The
take-2 comparison in this section should be read as "take 2's session
probably did not have the workspace rules on", not as a regression: 0.39.0
measures the same as 0.43.0 on every cell. Breakdown and method in
`docs/features/didopen-cost/README.md`.
### 8.5 FINDING (low) — `lucisv check` is 6–10% slower than 0.39.0
`hw/ip`: 0.367 → 0.400 s mean of three (default rules), 0.420 → 0.463 s
(`--select error,warning,style`); `hw/vendor`: 0.070 → 0.083 s and
0.083 → 0.097 s. Consistent
across three tries per cell, with 0.41.0 between the two, so it accumulated
across 0.41–0.43 rather than in one release. `format --check` did not move
(0.61 → 0.63 s on `hw/ip`, inside the spread). Candidates in that window
include §41.2's `fs::canonicalize` per existing file in `dedup` and §42's
config plumbing; not bisected. 40 ms on the largest tree in opentitan is not a
user-visible cost — filed so the next round can see if it keeps accumulating.
### 8.6 FINDING (low) — `workspace/symbol` keeps drifting up
6.6 (take 1) → 6.6–7.4 (take 2) → **7.2–7.9 (0.43.0)**, 8.4–8.7 at 0.39.0, for
the same 256 results. Take 2 already flagged this row as "~13% up and worth one
glance". 0.43.0 is *better* than 0.39.0 here, so the drift is not monotonic,
but the row has now moved in three consecutive takes and nothing in the
document explains it.
### 8.7 SURPRISE — the port refactorings are offered at 1 of 205 RTL files
Detailed in §6b. Not a defect: both refactorings refuse for structural reasons
that real RTL always satisfies. Recorded because it is the measurement that
justifies §37.1 after the fact, and because a future round asking "why is
`codeAction` slow" should know that it is almost always slow to say no.
### 8.8 STILL SLOW — the cold workspace scan at ~2.8 s
Essentially unmoved across three takes (3 003 → 2 958 → 2 767 mean), and still
the largest absolute number in the document. Once per session per cold cache;
never any round's target.
### 8.9 Movements inside the noise, listed and dismissed
`prepareRename` 0.07 → 0.31 ms first try, `documentHighlight` 0.04 → 0.10,
`foldingRange` 0.05 → 0.10, `diagnostic` 0.11 → 0.34, `didChange` flush
0.48 → 0.95, `inlayHint` 0.38 → 0.49, `semanticTokens` 0.16 → 0.21. Every one
of these is within 0.3 ms of take 2 and sits on a transport floor that is
0.04 ms fatter in this harness (§0); 0.39.0 measures the same as 0.43.0 on all
of them. **No conclusion should be drawn from any of them.** The `diagnostic`
row additionally answers 0 items rather than take 2's 1 (§1a).
---
## 9. Methodology and caveats — read before quoting any number
Take 1's and take 2's caveats still apply. The take-3-specific ones:
- **Three tries per row, first try and repeat range both reported.** "First" is
the request issued as the first real request of a dedicated session, after
the scan settled; "repeats" is the 2nd–4th identical request in that same
session. Where a row needed its own session (`codeAction`, `rename`,
`prepareRename`, each fan-out cursor, each scope/cache cell) it got one.
- **There *is* a server-side column this time**, from the shipped `--verbose`
flag, and it confirms the wire (§0). Nothing was instrumented for this round;
no code in the lucisv repo was modified except the creation of this file, the
`docs/perf/README.md` entry and `TODO.md`'s §40 ticks. No `cargo` command ran
in the main tree.
- **The comparison is binary-to-binary.** 0.43.0 is the packaged release build
at `73799f3`; 0.39.0 was built for this round from the `v0.39.0` tag in a
scratch `git worktree` under the scratchpad (`cargo build --release -p
lucisv_server`), which was removed afterwards. The main tree was never
checked out, reset or stashed.
- **Machine state.** Apple M1 Max, 10 cores, 64 GB, macOS 27.0 (26A5425a).
**The first 20 minutes of the session were contended** — two `rustc`
processes from an unrelated build ran at 99% CPU, load average 6–13 — and the
only measurements taken in that window were the untimed per-file outcome
sweeps of §7a, which are correctness, not timing. Every timed number in this
document was taken after those processes exited, at load average 2–4 with
only the editor and this agent running. No `cargo` build of this repo ran
during any timed measurement.
- **The guard.** Every server session, every `lucisv` invocation and the one
`cargo build` went through `tools/guard.sh -m 8 -t 1800`. **No guard kill
occurred**, and the largest resident set any command reached was 249 MB
(`lucisv format --check hw/ip`), 3% of the 8 GB limit.
- **The opentitan checkout was never written.** `git status --porcelain` was
checked after every phase and after the last run, and reports the same three
pre-existing modified files throughout: `hw/ip/aes/dv/tb/tb.sv`,
`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`.
`rename`, `codeAction/resolve` and `willRenameFiles`-shaped requests return
edits; the client discarded every one. The formatter cache was directed to a
scratch `--cache-dir` and the index cache to a scratch
`initializationOptions.storagePath`; neither default (`.lucisv_cache` in the
*current* directory, `~/Library/Caches/lucisv/index/<key>`) lands inside the
corpus, and both were overridden anyway.
- **One corpus difference from take 2** — `tb.sv` has been reformatted since,
so it raises no diagnostic and offers no `source.fixAll` action (§1a). Two
take-2 columns are therefore not comparable, and both are called out where
they appear.
- **Take 2's client no longer exists on disk**, so take 3's is a
reimplementation from take 2's description, not the same code. Its transport
floor is ~0.04 ms fatter (§0). Every sub-0.3 ms comparison against take 2
should be read with that in mind, and §8.9 dismisses the lot.
- **Page cache is hot and hotter than ever** — opentitan has now been walked by
three measurement sessions and by tonight's outcome sweeps. "Cold cache"
means *lucisv's* store was deleted, not that the OS file cache was dropped.
- **Sub-millisecond results were stable to ±0.05 ms** across ~60 sessions;
ten-to-hundred-millisecond ones should be read as ±10% (tighter than take
2's ±20%, because the machine was quieter); the multi-second scan rows as
±5% (take 3's six warm workspace scans span 12 ms).
- **The fan-out counts in §6a are `grep`-derived**
(`grep -rlE '^\s*<module>( |#|$)'` over `*.sv`), reproducing take 2's counts
exactly (1 / 6 / 42 / 67 / 128).
- **`--select error,warning,style` is not "all rules"** — it is the three rule
classes by name, which is what §40 asked for; a rule outside those classes
would not run.
---
## 10. Raw logs
All under `…/7b09ba01-…/scratchpad/perf3/` (removed after this document was
written; the numbers here are the record):
| File | What |
|---|---|
| `lspclient.py` | the LSP client — framing, the configuration pull, per-session capabilities, `--verbose` capture |
| `bench.py` | phases `startup` / `nav` / `codeaction` / `portaction` / `rename` / `blockers` / `completion` / `widen` / `diagnostics` |
| `verbose_probe.py` | §0 — the server's own timing lines beside the wire |
| `realfolder.py` | §5c — the slow requests with only `aes.sv` open, per scope |
| `probe_offer.py`, `probe_ws.py` | §6b — the sweeps that found one offered action in 205 files |
| `sweep.sh`, `sweeptable.py` | §7 — the timed CLI sweeps and their table |
| `outcomes.sh` | §7a — the per-file outcome runs for the 0.39.0 → 0.43.0 diff |
| `results.jsonl`, `logs/*.log` | every measurement, machine-readable |
+122 -147
View File
@@ -1,175 +1,150 @@
# Repository analysis
Audited 2026-09-04 against HEAD `d5abf81`. The manifest still declares
**v0.41.0**; HEAD includes the accepted parser-skips work intended for
v0.42.0. This is a source and documentation audit, not a new performance or
full language-conformance measurement.
Refreshed **2026-09-05**. Latest release: **v0.44.0** (`66f3898`). This
review uses committed snapshot **`9ef1058`**, which also includes accepted
type-name-spans and package-reexports work intended for v0.45.0. The active
hierarchical-tail changes are described separately; their QA is still open.
## Assessment
## Assessment and current status
lucisv is a complete developer-tool stack, with eight Rust crates (six
libraries and two binaries), a VS Code extension, Neovim/Vim configuration,
release/corpus scripts, and an Astro/Starlight documentation site. Its strongest
architectural choices are shared language engines, runtime formatter checks,
conservative semantic resolution, and a single owner for mutable LSP state.
lucisv remains an eight-crate toolchain: six reusable Rust libraries, CLI and
LSP binaries, editor integration, corpus/release tools, and a static docs site.
The architecture still separates syntax, formatting, semantics, linting,
refactoring, and project inputs. The three issues raised by the September 4
audit have been fixed; they should no longer be treated as open priorities.
The most consequential remaining issues found in this audit are coordination
between atomic writers and disagreement between project-file and editor lint
selection. The test suite passes, but neither result establishes those contracts:
the atomic tests exercise sequential replacement, and editor rule-selection
tests exercise client settings. Documentation had also fallen behind the
recent implementation rounds.
| Change | Status at this refresh | Implementation and contract |
|---|---|---|
| External waiver files | Released in v0.42.0 | `ExternalWaivers`, `WaiverUse`, and `lint_with`; CLI, project config and editor paths add together; inline/external suppression is a union; unused external waivers are reported only after a complete CLI run |
| Rival conditional headers and net-delay position | Released in v0.42.0 | Split units stay verbatim; delays print before or after the type according to their original position |
| Atomic-write coordination | Released in v0.43.0 | Exclusive per-operation temp files, permissions applied before bytes, CLI dedup by canonical path; separate processes remain last-writer-wins |
| Project/editor lint agreement | Released in v0.43.0 | Non-empty editor select/ignore lists override project lists independently; rejected project entries log once with file and line; valid entries continue to apply |
| Cycle-aware walks and net-delay comment slots | Released in v0.43.0 | Directory identity prevents cycles; comments around a delay's `#` are preserved |
| Walk warnings, editor rule-name warnings, aggregate overrides and delay-list comments | Released in v0.44.0 | Recoverable walk problems warn and continue; editor name typos log once; aggregate override expressions and delay-list comment slots are handled |
| didOpen cost | Released in v0.44.0 | `undriven-net` asks the workspace mention oracle after local guards; findings and synchronous request ordering stay unchanged |
| Type-name spans | Committed, accepted for v0.45.0 | `DataType::name_span()` / `segments()` and disable-target spans replace semantic name scanning; `scan.rs` is deleted |
| Package re-exports | Committed, accepted for v0.45.0 | Export name halves are references; the shared member walk follows cycle-guarded re-export edges; persisted facts gain `RX`, codec **18** |
| Hierarchical tails | **Working tree, QA pending** | Proposed codec **19**, tagged member/reference surfaces, instance-tail resolution and completion, and cross-file rename updates |
The current source of truth for feature acceptance is each feature's QA/review
log and [TODO.md](../TODO.md). The [topology](topo.md) records the interfaces
that future changes must preserve. A missing documented edge is not proof that
two edits have disjoint ownership.
## Repository map
| Location | Responsibility and starting point |
|---|---|
| `crates/vlog_parser` | Lexer and trivia, strict/tolerant recursive descent, AST and source coordinates; start at `src/lib.rs`, then `parser/` and `ast/` |
| `crates/vlog_formatter` | AST → document IR → printer, alignment, fences, ranges, token equivalence and convergence; start at `src/format/mod.rs` and `src/verify.rs` |
| `crates/vlog_semantic` | File binding/resolution and workspace facts; start at `src/lib.rs`, `bind/`, `workspace/`, and `facts.rs` |
| `crates/vlog_linter` | 73-rule registry, lazy analysis, options, severity, inline waivers and fixes; start at `src/lib.rs`, `context.rs`, and `registry.rs` |
| `crates/vlog_refactor` | Rename/references, port edits and instance plans; shared `src/scope.rs`, whole-edit checks in `check.rs` |
| `crates/lucisv_core` | Config, filelists, walking, format cache and atomic replacement; no language-engine dependency |
| `crates/lucisv` | CLI argument handling, discovery, worker pool, reports and writes; `src/main.rs`, `args.rs`, `lint.rs` |
| `crates/lucisv_server` | Synchronous LSP transport, workspace state, overlays, scans and capability handlers; `src/main.rs`, `server/`, `state.rs` |
| `editors/` | VS Code client/grammar/settings/hierarchy UI, plus configuration examples for other editors |
| `tools/`, `scripts/`, `.gitea/workflows/` | Resource guard, corpus evaluation, artifact audits and release automation |
| `docs/features/` | Feature-specific contracts, implementation history, QA and review; 135 READMEs at audit time |
| `crates/vlog_parser` | Lexer/trivia, strict and tolerant recursive descent, AST/spans; `src/lib.rs`, `parser/`, `ast/` |
| `crates/vlog_formatter` | AST → document IR → printer, alignment, fences/ranges, equivalence and convergence; `format/mod.rs`, `verify.rs` |
| `crates/vlog_semantic` | File binding/resolution, workspace facts and member lookup; `bind/`, `resolve.rs`, `workspace/`, `facts.rs`; committed `workspace/reexport.rs`, active `workspace/hierarchy.rs` |
| `crates/vlog_linter` | 73-rule registry, lazy semantics, options, severities, inline/external waivers and fixes; `lib.rs`, `context.rs`, `registry.rs`, `waiver_file.rs` |
| `crates/vlog_refactor` | Rename/references, port edits, instance plans; shared `scope.rs`, whole-edit verification in `check.rs` |
| `crates/lucisv_core` | Config, filelists, cycle-aware walks and warning channel, format cache, atomic replacement; no language-engine dependency |
| `crates/lucisv` | Argument handling, input discovery/dedup, worker pool, reports and source writes |
| `crates/lucisv_server` | Ordered LSP loop and workspace overlays; `server/`, `state.rs`, capability handlers; project lint validation/logging in `lint/project.rs` |
| `editors/` | VS Code client/grammar/settings/hierarchy UI and configuration for other editors |
| `tools/`, `scripts/`, `.gitea/workflows/` | Resource guard, corpus evaluation, artifact checks and releases |
| `docs/features/` | Implementation contracts, dated measurements, QA and acceptance records |
| `docs/site/` | User-facing static documentation and tracked generated output |
[topo.md](topo.md) gives dependency directions, recent cross-crate contracts,
shared interfaces, and numbered open handshakes. The manifests are authoritative
for crate edges; an absent documented edge alone does not prove two edits safe
to perform concurrently.
The crate dependency graph is unchanged. Parser and core have no dependencies;
formatter and semantics each depend on parser; linter and refactor depend on
parser and semantics. The linter depends on the formatter only in tests.
The CLI composes core/parser/formatter/linter; the server composes all six
libraries. External Rust dependencies stay in the CLI worker pool and server
LSP/JSON stack.
## Runtime behavior and limits
## Runtime contracts worth preserving
**Formatting.** `format_source` strictly parses input, renders a document tree,
re-lexes both versions and compares normalized tokens (including comments),
then parses/formats the output again and checks convergence. A failed check
returns an error instead of a candidate string. The CLI leaves the affected
source file alone. This protects lexical fidelity and stable layout; it does
not elaborate SystemVerilog or prove hardware equivalence. Fenced text still
has to parse. Ranges select items; fences can additionally protect statements
and class members.
**Formatting:** strict parse, layout, normalized token comparison (including
comments), then a second parse/format and convergence check. Failure returns
an error, not a candidate output. These are lexical/layout checks, not design
elaboration or proof of hardware equivalence. Fenced text must still parse;
ranges select items, while fences also protect statement and class scopes.
**Linting.** `ParsedSource` shares a tokenization and tolerant parse, and
`LintContext` computes semantics lazily. Rules consume text, tokens, AST, and
optional project facts; malformed AST elements remain opaque. Inline waivers
filter findings, and severity is stamped centrally. The CLI/server filter
fixes through the formatter's fence API: `apply_fixes` alone does not provide
that protection. `always-comb` offers an unsafe fix; editor actions offer only
safe fixes.
**Linting:** one prepared tokenization/tolerant parse feeds rules and lazy
semantics. Malformed AST elements remain opaque. Front ends call `lint_with`
when applying external waivers and filter automatic edits through the formatter's
fence API; `apply_fixes` alone does not protect fenced bytes. Editor actions
continue to offer only safe fixes. The mention oracle is a pure predicate;
asking it after cheap local guards avoids repeated workspace scans.
**Refactoring and editor state.** Refactors use resolved source spans and check
the whole edit; source selectors must remain supersets of every file an engine
could edit or refuse over. The LSP loop owns workspace mutation, open documents
overlay disk facts, and stepped scans publish related index/include/completion
state together. Facts persist under `FACTS_FORMAT = 17`. Lazy port code actions
compute their edits on selection for capable clients. Recorded UTF-16 positions
avoid reads for closed-file file-scope definitions; members and open buffers
still use text-based locations.
**Editor and refactors:** one loop owns workspace mutation; buffers overlay
disk facts and scans publish related index/include/completion state together.
Lazy port actions defer edits until selection. File-scope definition positions
can come from the index; members and open buffers use text-based positions.
Refactor source selectors must include every file an engine might edit or
refuse over, even when completion or navigation can answer from fewer files.
**Intentional scope.** Neither parser mode performs cross-file macro expansion
or compiler elaboration. Missing definitions outside an index scope can mean
missing hints or conservative lint silence. Rootless indexing never climbs;
with depth 0 it reads siblings flat, while positive depth walks descendants.
The published 814/820 frozen-corpus result is historical feature QA evidence,
not a new corpus sweep performed by this audit. Performance reports under
`docs/performance*.md` and `docs/perf/` likewise remain dated measurements.
**New committed semantic contracts:** a type-name segment is derived from AST
span data and verified against the source by `Binder::exact_or_empty`. The
source parameter to analysis remains necessary even though `scan.rs` is gone.
A package re-export records reference edges without adding a local import.
`export *::*` expands the package's imports into re-export facts; member lookup
follows those edges with cycle guards. Cache codec 18 prevents older stores
from silently omitting this information.
## Findings and follow-up priorities
## Active work and remaining limits
### 1. Coordinate writes to a shared target
TODO §49 owns hierarchical-tail resolution. At this refresh, its working tree
adds `Surface::{Connection, Hierarchical}`, a second member table, surface tags
on persisted declarations/references, and codec 19. Connection completion and
port propagation retain the existing ports/parameters view; paths behind an
instance can additionally reach internal nets, variables and nested instances.
Member completion and rename fan-out are part of the same contract. The feature
README reports development checks; independent QA is still pending, so topology
handshake 23 remains open. No working-tree API is treated as released here.
Evidence: [atomic.rs](../crates/lucisv_core/src/atomic.rs) canonicalizes the
target, then derives a temp name from the target filename and process ID.
`fs::write` opens that predictable path without exclusive creation.
[CLI dedup](../crates/lucisv/src/main.rs) folds lexical path components but
intentionally leaves symlinks unresolved. Two rayon jobs reaching one target
through different spellings can therefore share a temporary file.
Remaining constraints include generate-block-scoped hierarchical paths,
cross-file macro expansion, and compiler elaboration. Package re-export support
does not bind a DPI-export function name; that residue is now separated into
topology handshake 31. Shared path normalization (1) and structured formatter
error output (11) also remain open. Inline aggregate override arguments are
supported, but instance templates still omit a type default written across
multiple lines. These are narrower limits than the old audit's unresolved
entries 2, 16 and 17 suggested.
A disposable probe compiled the actual `atomic.rs` and used two barrier-started
threads per round to write different 1 MiB buffers to one target. Across
**100 rounds / 200 calls, 100 writes failed**. The final file in every round
was a complete one-writer buffer; **no mixed final bytes were observed**. This
reproduces the helper's collision, not an end-to-end formatter corruption.
The probe used only `/tmp` files and ran under the resource guard.
## Historical audit findings and evidence
Recommended follow-up: exclusive, unique per-operation temp files; coordinate
or deduplicate writes by target identity; add a concurrent alias regression.
The existing temp-and-rename helper is useful for sequential replacement, but
its tests do not justify a same-target concurrency guarantee. Tracked as
[topology handshake 26](topo.md).
The **2026-09-04** audit reproduced a temp-file collision at the old revision:
100 errors in 200 concurrent helper calls, with no mixed final bytes observed.
That is historical evidence, not a current failure. The
[atomic-write-coordination QA](features/atomic-write-coordination/README.md)
records the committed regression test and successful 2/4/8-thread checks.
[Lint-config-contract](features/lint-config-contract/README.md) records CLI/LSP
selection parity and once-only logging checks.
[Walk-cycles](features/walk-cycles/README.md) and
[small-items-4](features/small-items-4/README.md) record cycle handling, recoverable
warnings and the closed delay-comment gaps.
### 2. Define a consistent project lint configuration contract
[Performance take 3](performance_take3.md) measures v0.43.0 and predates the
v0.44.0 fix. The later [didOpen-cost report](features/didopen-cost/README.md)
records 1,742 ms → 117 ms on the large pinmux file at workspace scope, with
unchanged diagnostics. These are feature measurements on one machine, not
fresh measurements by this documentation refresh. The 814/820 frozen-corpus
result likewise remains attributed to feature QA; no corpus or OpenTitan sweep
is part of this refresh.
Evidence: [server linting](../crates/lucisv_server/src/lint.rs) selects rules in
`enabled_rules` from `ClientSettings` only. Its `configured` function discovers
`lucisv.toml` but reads `lint_options` and line length, not `lint_select` or
`lint_ignore`. In contrast, [CLI linting](../crates/lucisv/src/lint.rs) consumes
project selection. The server also discards invalid project option entries
with `let _ = options.set_raw(...)`; only invalid *editor* option settings
receive the corresponding per-entry log.
## Validation of this refresh
The docs now describe the implemented behavior: project selection controls CLI
runs; editor selection requires `lucisv.lint.*` settings; valid project rule
options are shared. Recommended follow-up: specify and test project/editor
selection precedence and surface rejected project rule options. Tracked as
topology handshake 28. This finding is from source inspection; no dedicated
wire-level configuration reproduction was run in this audit.
### 3. Keep traversal and semantic gaps explicit
The shared [directory walker](../crates/lucisv_core/src/walk.rs) recursively
follows `Path::is_dir()` with no visited-directory set. Symlink cycles remain
an existing open issue (topology handshake 8); eventual filesystem refusal is
not an explicit traversal budget or cycle policy. Prioritize a deliberate
cycle policy before broadening traversal.
Other concrete open contracts include missing type spans (handshake 2),
package re-export resolution (16), inline aggregate type arguments (17), and
cross-file rename of an internal module net (23). The parser-skips regression
suite also retains a refusal for comments immediately before a net-delay `#`
(27). These limitations should remain visible when widening grammar or index
coverage; formatter verification must continue to reject unsupported output.
## Documentation changes from this audit
- Expanded the README's architecture to cover all eight crates and documented
the runtime checks, actual indexing behavior, documentation entry points,
and guarded verification commands.
- Updated topology facts to codec 17, corrected moved module paths, recorded
recent recovery/lint/fence/atomic/LSP contracts, and closed the stale `program`
linked-editing request using the existing module-shaped AST path.
- Updated site configuration, formatter/linter guides, CLI, language tools,
architecture and API navigation for current behavior. The API index now
explicitly defers to rustdoc for exhaustive signatures and fields.
- Removed the stale `0.9.0` product version from site structured metadata;
release versions remain owned by the workspace/release files.
The parser-skips changes were already present when the audit started and were
committed by another workflow during the audit. Their QA log now records PASS;
the topology reflects that final state. This audit made no Rust implementation
changes and did not modify their feature log or backlog checkboxes.
## Validation
Checks ran against an isolated archive of committed `9ef1058`, with a separate
build directory and the repository resource guard. This avoids the live agents'
target directory and does not certify their uncommitted changes.
- `cargo fmt --all -- --check`: passed.
- `cargo clippy --workspace --all-targets -- -D warnings`: passed.
- `tools/guard.sh -- cargo test --workspace`: **3,745 passed, 0 failed,
44 ignored**, summed across 48 test/doc-test harnesses. Counts include the
post-v0.41.0 parser-skip cases and one passing doctest; ignored measurement
tests were not enabled.
- Documentation build: `ASTRO_TELEMETRY_DISABLED=1 npm run build` in
`docs/site` passed; 13 pages, Pagefind index and sitemaps generated.
- Generated-site verification: 817 local links, assets and anchors checked,
zero failures; relative links in the repository documentation checked.
`git diff --check` passed.
- Atomic-write probe: collision reproduced as described above, no repository
source files written.
- `cargo clippy --offline --workspace --all-targets -- -D warnings`: passed.
- `cargo test --offline --workspace`: **3,829 passed, 0 failed, 44 ignored**,
across 49 harnesses, under `tools/guard.sh`. The archive did not include the
ignored/untracked corpus checkout, and ignored measurement tests were not run.
- `ASTRO_TELEMETRY_DISABLED=1 npm run build` in `docs/site`: passed;
13 pages, Pagefind search and sitemaps rebuilt.
- Generated-site validation: **820** local links, assets and anchors checked,
zero errors. Relative links in the root analysis/topology/coverage docs also
passed. `git diff --check` passed for these documentation changes.
The first test attempt was stopped because sandboxed `ps` prevented the guard
from measuring memory; the successful rerun used an approved environment where
monitoring worked. No corpus sweep, OpenTitan sweep, ignored benchmark run,
release packaging, or external publishing was performed by this audit.
The previous audit's 3,745 passing tests describe its September 4 snapshot;
they are not reused as the test result for this revision. This refresh changes
documentation only and leaves feature QA logs and backlog checkboxes to their
owners. No corpus/OpenTitan sweep, new benchmark, release packaging or
publishing was performed.
+4 -4
View File
@@ -110,10 +110,10 @@ CLI and the editor), and the editor setting <code dir="auto">lucisv.lint.waivers
the first workspace folder). External and inline waivers are a union: a
finding either covers is suppressed, and one both cover leaves neither
reported as dead. A missing file or an unparsable directive fails <code dir="auto">lucisv check</code> with <code dir="auto">&lt;file&gt;:&lt;line&gt;: &lt;message&gt;</code> and exit 2; in an editor the bad line
is dropped and the rest of the file applies — a bad line in a file named by
the editor setting is written once to the lucisv log, one named by
<code dir="auto">lucisv.toml</code> is not (run <code dir="auto">lucisv check</code> to see it). Unused external waivers
is dropped and the rest of the file applies, and the bad line is written once
to the lucisv log whether the file was named by the editor setting or by
<code dir="auto">lucisv.toml</code>. Unused external waivers
are reported under <code dir="auto">unused-waiver</code> at their line of the waiver file, by
<code dir="auto">lucisv check</code> only and only after the whole run.</p>
<p>See the <a href="/reference/rules/">complete rule reference</a>.</p>
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/guides/linter.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T04:37:55.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/guides/formatter/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Formatter</span></span></a><a href="/guides/editors/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Editors &amp; LSP</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/guides/linter.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T06:45:48.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/guides/formatter/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Formatter</span></span></a><a href="/guides/editors/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Editors &amp; LSP</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loaded 100 of 123 files, more files were not shown because too many files have changed in this diff. Show more