Add vlog_semantic and parallel-files (jointly: shared root manifest)

vlog_semantic (new crate): single-file symbol tables and reference
resolution -- the layer that powers go-to-definition, references,
hover and document outline, and later the semantic lint rules.
Two-pass bind-then-resolve (Verilog forward references), 15 symbol
kinds, scope tree, and a three-state Resolution (Resolved /
ExternalCandidate carrying import paths for the future workspace
index / NotFound). scan.rs recovers name spans the AST lacks (95k
corpus spans verified; handshake filed and approved to move
name_span into the parser, which deletes the module). Corpus
baseline: 79.5% in-file resolution, 0.9% unresolved on clean files,
zero panics including tolerant-parse trees.

parallel-files (vfmt): rayon-parallel per-file formatting -- first
dependency, exact-pinned with written justification. 8 MiB worker
stacks discharge the recursion-limit handshake (sabotage-verified);
single-install panic hook discharges the cli-polish handshake;
deterministic input-order output (one stdout/stderr hash across 14
corpus runs at 4 thread counts); --threads flag; hand-rolled
.gitignore subset with 16/16 differential agreement against git
check-ignore. 3.6x wall-clock on the 860-file corpus.

Dev: 2 Opus agents; QA: 2 Sonnet agents; reviews in
docs/features/{vlog-semantic,parallel-files}/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-19 06:39:51 -07:00
1 parent 982e37063b
commit 7cf657a538
19 files changed
+3909 -65

No files matched your search

+487
View File
@@ -0,0 +1,487 @@
# parallel-files
## Goal
Make `vfmt` format a whole RTL tree on all cores instead of one, and stop
walking into directories the repository already declares generated. Two
`TODO.md` §3 items in one change, because they touch the same loop:
formatting is a pure function of `(source, config)`, so the per-file loop in
`crates/vfmt/src/main.rs` parallelises with `rayon::par_iter` once panic
containment and output ordering are reworked for concurrency; and
`.gitignore` support is the other half of the file-discovery item whose
`--exclude` half already shipped with cli-polish. The user-visible contract
does not change: same stdout/stderr split, same exit codes, same per-file
error messages, and — critically — the same *byte-identical* output for the
same invocation, regardless of thread count.
## Assumptions
- **Formatting one file has no cross-file state.** `format_source` reads a
`&str` and a `Config` and returns a `String`; config discovery happens in
full before any file is formatted (`gather`), and each file's write targets
only itself. Nothing is shared between jobs but immutable data.
- **Determinism comes from ordering the *reporting*, not the work.** Files are
formatted in whatever order rayon's work-stealing picks. Every per-file
outcome (stdout text, error line, counter bucket) is captured into a value
and rendered afterwards in input order. Two runs of the same invocation
therefore produce byte-identical stdout and stderr.
- **Output is buffered until the run ends.** The price of ordered reporting is
that `--diff` / `--stdout` text is held in memory until every file is done,
rather than streaming. For the sizes vfmt targets (a large RTL tree is tens
of MiB of source) this is acceptable; it is the reason `--stdout` over a
huge tree is no longer incremental.
- **8 MiB of worker stack is enough.** Taken from
`docs/features/recursion-limit/README.md`, which measured the worst-case
full-pipeline peak at ~3.9 MiB in a debug build and ~0.5 MiB in release.
The pool is built with exactly that number; rayon's own default is 2 MiB,
which would silently reintroduce the stack-overflow crash that feature
fixed.
- **The `.gitignore` support is a documented subset, not git.** It is the
`--exclude` matcher plus anchoring, directory-only and negation. See
"gitignore subset" below for exactly what is and is not honoured. It is
not consulted for paths named directly on the command line, and it does
not know whether the tree is a git repository at all.
- **`.gitignore` files above the walk root are not read.** Only files at or
below a directory named on the command line participate.
- **stdin mode stays serial.** One buffer, one thread; nothing to parallelise.
## Behavior
### `--threads <N>`
- `--threads 0` or the flag absent: rayon's default, one worker per logical
CPU.
- `--threads 1`: a single worker. Useful for CI reproducibility, for
profiling, and for bisecting a suspected concurrency bug.
- Any `N`: that many workers. The value only changes *speed*: the bytes on
stdout and stderr and the exit code are identical for every `N`.
- Ignored in stdin mode.
### `.gitignore`
Honoured by default while walking directories; disabled with
`--no-gitignore`. Each directory the walk enters is checked for a
`.gitignore`, and its rules apply to that directory's subtree. Rules from a
deeper `.gitignore` are considered after (and so override) shallower ones,
and within one file the last matching line wins — git's own precedence.
Supported syntax:
| Form | Meaning |
|---|---|
| `# comment`, blank line | skipped |
| `build` | a file *or* directory named `build`, at any depth below this `.gitignore` |
| `*_gen.sv` | `*` matches any run of characters inside one path component; never crosses `/` |
| `/build`, `gen/rtl` | a `/` at the start or in the middle anchors the pattern to this `.gitignore`'s own directory |
| `build/` | trailing `/`: matches directories only |
| `!keep.sv` | negation: re-includes a path an earlier rule ignored |
Not supported (deliberately, and silently — these forms are matched
literally or as plain `*`, they are not errors):
- `**` has no special meaning; it is two `*`s inside one component, so
`a/**/z.sv` matches only `a/<one component>/z.sv`.
- `?` and character classes `[a-z]` are literal characters.
- `\` escapes (so a pattern cannot contain a literal `!`, `#` or trailing
space).
- The global ignore file (`core.excludesFile`), `.git/info/exclude`, and
`$GIT_DIR/info/exclude`.
- Git's "already-tracked files are not ignored" rule: vfmt has no index, so
a tracked file matching an ignore rule *is* skipped.
- Re-including a path inside an ignored directory. An ignored directory is
never descended into, so a `!` rule underneath it cannot bring anything
back. (Git behaves the same way, for the same reason.)
A path named directly on the command line is never ignored, exactly as with
`--exclude`.
## Handshakes
- **Consumes `docs/features/recursion-limit/README.md`'s request:** that
README asks whoever lands parallelism to build the rayon pool with
`stack_size(8 * 1024 * 1024)` or larger, because a 2 MiB worker cannot
reach `MAX_NESTING_DEPTH` in a debug build (~3.9 MiB measured). Done in
`main.rs::build_pool`, with a test (`deep_file_formats_under_the_pool`)
that fails if the stack size is ever removed.
- **Discharges `docs/features/cli-polish/README.md`'s handshake:** that
feature's `catch_panic` swapped the process-global panic hook with
`take_hook`/`set_hook` around every call, and flagged it as sound only
while single-threaded. It is replaced by a single hook installed at
startup, before the pool exists, that consults a thread-local flag; the
flag is set by `catch_panic` on the thread that is about to run contained
work. No hook is ever swapped again, so nothing races. **Anyone editing
`catch_panic` must keep it that way.**
- **Consumes `vlog_formatter::{format_source, Config}`** unchanged. Both are
`Send`/`Sync`-clean (`Config` is two `usize`s; `format_source` takes
`&str`). Nothing in `vlog_parser` / `vlog_formatter` was touched.
- **Promises to TODO.md §3's content-hash cache item:** the per-file unit of
work is `process_file(&Path, &Config, &Options) -> Outcome` in `main.rs`,
a pure-ish function whose only side effect is writing its own file. A cache
lookup belongs at the top of it; the `Outcome` enum is where a "cached,
unchanged" bucket would go.
- **Promises to CI users:** the exit-code contract frozen by cli-polish is
unchanged, and `--threads` does not affect it.
## Status / TODO
- [x] `rayon` as the workspace's first third-party dependency, pinned
exactly, justified below.
- [x] Global pool built once at startup with an 8 MiB worker stack.
- [x] One panic hook installed at startup; `catch_panic` uses a thread-local
flag instead of swapping hooks.
- [x] Per-file loop parallelised; outcomes reported in input order.
- [x] `--threads N`, documented in `--help` and `README.md`.
- [x] `.gitignore` support in `walk.rs` with `--no-gitignore`.
- [x] Tests: parallel-vs-`--threads 1` byte equality, contained panic under
parallelism, deep-nesting file under the pool, `--diff` ordering,
gitignore unit + CLI tests, per-file config under parallelism.
- [x] `TODO.md` §3 parallel + `.gitignore` boxes.
- [x] `cargo fmt`, `cargo clippy --all-targets`, `cargo test --workspace`.
## Dependency justification: `rayon = "=1.12.0"`
CLAUDE.md requires a written justification for every dependency; `TODO.md` §3
pre-sanctions this one by name. It is the workspace's first third-party
dependency, and `vfmt`'s only one.
**Why not hand-rolled threads.** The obvious alternative is *N* `std::thread`s
each draining a shared `Mutex<vec::IntoIter>`, about 30 lines. Three things
make that the worse choice here:
1. **Work stealing.** vfmt's per-file cost varies by two orders of magnitude
(a 20-line header vs. a 10 000-line generated netlist). A static chunking
leaves cores idle behind one slow file; a shared-queue design fixes that
but then contends on the mutex for short files. rayon's per-worker deques
with stealing get both, and this is the entire point of the feature.
2. **Panic propagation.** A panic on a hand-rolled worker either poisons the
shared mutex or is silently swallowed by a detached `JoinHandle`. rayon
propagates a worker panic to the thread that called `par_iter` — which
matters because vfmt's own containment (`catch_panic`) is the *inner*
layer, and anything that escapes it must still surface as a crash rather
than as a quietly missing file.
3. **Maintenance.** Thread count, stack size, worker naming, and clean
shutdown are all one builder call. The content-hash cache in TODO.md §3
and any future `par_bridge` over a streaming walk get the same machinery
for free.
**Cost.** Five transitive crates (`rayon-core`, `crossbeam-deque`,
`crossbeam-epoch`, `crossbeam-utils`, `either`), all from the same
well-maintained ecosystem, no build scripts, no `unsafe` in vfmt itself, and
~9 s of cold release compile time. The version is pinned with `=` rather than
a caret: a work-stealing scheduler is exactly the kind of dependency whose
minor releases can change thread behavior, and vfmt's determinism claim is
worth an explicit bump.
## Work log
### 2026-08-19 — dev agent
- Read CLAUDE.md, `TODO.md` §3, `docs/features/cli-polish/README.md`
(the panic-hook handshake), `docs/features/recursion-limit/README.md`
(Handshakes: the 8 MiB request) and all of `crates/vfmt/src` before
writing anything.
- **Blocked on the workspace for most of the run.** Another agent was
mid-flight creating `crates/vlog_semantic`; its `Cargo.toml` was in the
`[workspace] members` list before its `src/lib.rs` existed, so
`cargo build` failed to load the workspace manifest. Iterated in a
scratchpad copy of the workspace (that member removed) and re-ran
everything against the real tree at the end. My edit to the root
`Cargo.toml` is additive only (`[workspace.dependencies]`); the
`members` line was left exactly as the other agent wrote it.
**Pool and stacks.** `build_pool` (`main.rs`) calls
`ThreadPoolBuilder::new().num_threads(opts.thread_count()).stack_size(8 MiB)
.build_global()` once, right after `gather` and before any file is touched.
`--threads 0`/absent passes 0, which is rayon's "one per logical CPU".
The recursion-limit handshake asked for ≥ 8 MiB because a debug build needs
~3.9 MiB to reach `MAX_NESTING_DEPTH`. That is honoured, and pinned by a
test: `a_deeply_nested_file_formats_on_a_worker_thread` formats a 28-level
`if … begin` nest (a nested `if … begin` costs two depth levels, so 28 sits
just under the limit of 64). **Verified load-bearing**: with `WORKER_STACK`
temporarily set back to rayon's 2 MiB default in the scratchpad copy, that
test kills the process outright (no exit code at all — a stack overflow, not
a panic), exactly the failure mode recursion-limit was built to remove.
**Correction to the brief, worth recording.** The task assumed rayon's
`par_iter` also runs work on the calling thread, so the main thread's stack
would matter too. That is not how rayon 1.12 behaves when `par_iter` is
called from *outside* the pool: `Registry::in_worker` takes the cold path,
injects the job, and **blocks** the caller. A probe binary (scratchpad,
4 workers, 2000 jobs) saw work on exactly the four pool threads and never on
`"main"`, and `rayon::current_thread_index()` on the main thread is `None`.
The 2 MiB experiment above independently confirms it: if the main thread
formatted anything, the deep file would sometimes have landed on its 8 MiB
stack and the test would be flaky rather than deterministically fatal. So
**every** file is formatted on a pool worker with the configured stack, and
the main thread's own stack is irrelevant to this feature. That is the
stronger guarantee, so nothing needed to change — only the reasoning.
**Determinism.** The parallel pass produces no output at all. Each job
returns an `Outcome` (`Unchanged` / `Printed` / `Changed(text)` /
`Failed(message)`) carrying the exact bytes it wants printed;
`jobs.par_iter().map(process_file).collect::<Vec<_>>()` is an *indexed*
parallel iterator, so the collect restores input order; `run_files` then
walks that vector serially, printing and counting. Diff hunks and error
lines therefore cannot interleave, and the summary counters are derived
from the ordered vector rather than from shared counters. Verified at
corpus scale: `vfmt --diff` over the 860-file corpus produces 2 424 208
bytes of stdout and 66 019 bytes of stderr that are **byte-identical**
across `--threads 1`, `2`, `8`, the default, and a repeat run.
The one real cost is that stdout is now buffered to the end of the run
instead of streaming; recorded under Assumptions.
**Panic hook.** cli-polish's `catch_panic` took and re-set the process-global
hook around every call and flagged the race. Replaced by:
`install_panic_hook()` (a `std::sync::Once`, called from `main` before the
pool is built) installs one hook that consults a `thread_local!`
`CONTAINED: Cell<bool>`; `catch_panic` sets that flag on its own thread,
runs `catch_unwind`, clears it. No hook is ever swapped again, so there is
nothing to race on, and a panic *outside* `catch_panic` still gets the real
default hook and its backtrace — which the old blanket silencing would have
eaten if it were ever left installed. Verified both halves in the scratchpad:
- Sabotaged `format_source` (panic on a `SABOTAGE_<id>` marker), 44-file
tree, 4 panicking files. Parallel run: all four reported as
`error: …/boomNN.sv: panicked while formatting: sabotaged formatter: NN`
in input order with their own distinct payloads, `40 files reformatted,
4 files failed to format`, exit 2, the four files byte-identical
afterwards, zero `thread '…' panicked` noise. stderr **byte-identical**
to the same tree under `--threads 1`.
- A deliberate `panic!` in the driver *outside* `catch_panic` still prints
the full `thread 'main' panicked at … note: run with RUST_BACKTRACE=1`.
**`.gitignore`.** ~80 lines in `walk.rs`, no new dependency. The walk became
a small `Walk` struct because it now carries three things down the
recursion: the components of the current directory relative to the walk
root, the stack of `.gitignore` rule sets seen so far, and the base depth of
each of those sets. Rules reuse the existing `glob_component` matcher
unchanged, so `--exclude` and `.gitignore` glob identically.
Anchoring follows git's actual rule rather than a leading-`/`-only rule,
because git's rule *is* the `--exclude` split generalised: a `/` at the
start **or in the middle** anchors to the `.gitignore`'s own directory; no
`/` at all means "match this name at any depth below". Precedence is
implemented by concatenating the stack root-to-leaf and letting the last
matching rule win, which gives both "a deeper file overrides a shallower
one" and "the last line in a file wins" from one loop.
**Differential-tested against real git**, not just against my own
expectations: a scratchpad `git init` tree with a root `.gitignore`
(`build/`, `*_gen.sv`, `/anchored.sv`, `gen/rtl`, `sub/*.sv`, a comment) and
a nested `sub/.gitignore` (`!keep_gen.sv`, `drop.sv`) over 13 `.sv` files.
`git check-ignore` and vfmt agree on **every** file.
On the real corpus (28 `.gitignore` files across ibex, OpenTitan, PULP
common_cells and picorv32) the honoured rules change nothing: the same 860
files are visited with and without `--no-gitignore`, because those files
name build artifacts, not RTL. That is the right outcome and a useful
negative result — the subset does not over-ignore real repositories.
**Speedup** (informational; release build, 10 logical cores, warm cache,
best of 3, `--check` over the 860-file corpus):
| `--threads` | wall | speedup |
|---|---|---|
| 1 | 0.389 s | 1.00× |
| 2 | 0.232 s | 1.68× |
| 4 | 0.150 s | 2.60× |
| 8 | 0.108 s | 3.60× |
| default (10) | 0.107 s | 3.62× |
Below linear, and honestly so: 359 of the 860 corpus files fail to parse
early (unsupported syntax, tracked in corpus-check), so a large fraction of
the run is the serial directory walk plus 359 cheap early exits. The
parallel fraction is the 501 files that actually format.
**Not done, deliberately.** `gather` (the walk plus config discovery) stays
serial: it is I/O-bound, it owns a `&mut` discovery cache, and at corpus
scale it is a small share of a run that is now 0.1 s. Parallelising it is
the natural next step if profiling ever says so.
## QA log
### 2026-08-19 — QA agent
Read CLAUDE.md, this README, the diff (`main.rs`/`args.rs`/`walk.rs`/`cli.rs`,
root `Cargo.toml` + `Cargo.lock`, README.md, TODO.md §3), and the two
handshake documents it cites (`docs/features/recursion-limit/README.md`,
`docs/features/cli-polish/README.md`) — both handshakes are quoted
accurately; nothing fabricated. Did not touch `crates/vlog_semantic`
(another agent's work, now complete and compiling). No commits made.
**Verdict: pass on all seven claims, no blocking findings.**
1. **Pool.** `build_pool` (`main.rs:182`) is one `ThreadPoolBuilder` call,
`stack_size(8 MiB)`, called once from `run_files` before any file is
touched. Independently reproduced the "no work on the calling thread"
claim with a standalone probe (rayon 1.12.0, 4 workers, 2000 jobs,
`scratchpad/probe/main.rs`): `rayon::current_thread_index()` on `main` is
`None`, and the set of thread names that actually ran `for_each` work
never contains `"main"` — only unnamed pool workers. **Sabotage-checked**
the 2 MiB claim myself: temporarily changed `WORKER_STACK` to
`2 * 1024 * 1024`, rebuilt, ran
`a_deeply_nested_file_formats_on_a_worker_thread` — it fails with the
child process losing its exit code entirely (`panicked at
cli.rs:81:23: exit code`), i.e. a hard crash, not a graceful error;
restored the file and confirmed `git diff crates/vfmt/src/main.rs`
byte-identical to before the experiment (`diff` of the two captured
diffs was empty). **Pass.**
2. **Hook.** Single `Once`-guarded `install_panic_hook` (`main.rs:266`);
grepped the whole file for `take_hook`/`set_hook` — both appear exactly
once, inside that function. Reproduced both halves live: (a) a
sabotaged build (magic-marker panic injected into
`vlog_formatter::format_source` in a scratchpad copy of the repo) run
against a 44-file tree with 4 panicking files reports all four by name
in input order, exit 2, zero `thread '…' panicked` noise, and is
byte-identical between `--threads 1` and the default pool, both as a
single comparison and across 20 repeated parallel runs (one stdout hash,
one stderr hash, all 20). (b) Added a `panic!()` immediately after
`install_panic_hook()` in `main()` (outside `catch_panic`) in the same
scratchpad build: it still prints the full `thread 'main' panicked at
… note: run with RUST_BACKTRACE=1`, exit 101 — the default hook is
intact for real bugs. **Pass.**
3. **Determinism.** Ran `vfmt --diff` over the full 860-file corpus (not
just ~100) at `--threads` 1/2/8/default, 3 repeats each (12 runs) plus 2
more default-thread repeats (5 total for that setting): stdout hashes to
one value across all 12, stderr to one value across all 12 —
2,424,208 bytes stdout / 66,019 bytes stderr, matching the work log's
own numbers exactly once I used the same absolute-path invocation (my
first pass used a relative `corpus` argument, which shortens every diff
header and shrinks the totals — a harness artifact on my end, not a
product issue, resolved and reconciled). Also re-ran the 20×
panicking-scenario race hunt from claim 2 as the nondeterminism probe
for this claim too. Zero variance anywhere. **Pass.**
4. **`.gitignore`.** Built my own probe tree under a real `git init`
(`scratchpad/gitprobe/`) covering all four requested tricky cases plus
extras: a `!secret.sv` inside `build/` (ignored by the parent `build/`
rule — git prunes the directory before reading its `.gitignore`, and so
does vfmt); `/x.sv` anchored inside a *nested* `anchor_test/.gitignore`
(correctly scoped to that directory only, not its `sub2/`); `!keepdir/`
negating a directory while `*.sv` still catches the file inside it
(git: ignored; vfmt: ignored — negating the directory doesn't negate the
per-file pattern); and the `build/` vs. bare `build` directory-only
distinction (already covered by the existing unit test
`a_trailing_slash_matches_directories_only`, confirmed still green).
Ran `git check-ignore -q` against every `.sv` file in the tree, compared
to which files vfmt actually visited (16 files, 6 not ignored) —
**exact agreement, 0 discrepancies.** Corpus visited-set check: `--diff`
with and without `--no-gitignore` over the real 860-file corpus (28
`.gitignore` files) produced byte-identical stdout and stderr, matching
the "negative result" claim. `--threads 1000` (pool larger than the
3-file tree it ran on, and separately against a single file) and
`--threads 1000` against the full corpus all completed quickly and
correctly (no hang, no resource exhaustion). A directory whose
`.gitignore` contains only `*` yields `error: no Verilog files found
(extensions: v, sv, vh, svh)`, exit 2 — sane, and `--no-gitignore`
recovers the files as expected. `.gitignore` + `--exclude` together:
both apply simultaneously (verified with one pattern from each). **Pass.**
5. **Deps.** `cargo tree -p vfmt` shows exactly `rayon` → `either`,
`rayon-core` → `crossbeam-deque` → `crossbeam-epoch`/`crossbeam-utils`
(5 transitive crates as documented); `cargo metadata` confirms none of
the six packages (rayon included) declare a build script. `rayon` is
pinned `=1.12.0` in both `Cargo.toml` and `Cargo.lock`. Justification
section present and specific. **Pass.**
6. **Tools.** `cargo test -p vfmt`: 50 unit + 30 CLI, all green (0.01s +
0.14–0.21s). `cargo clippy -p vfmt --all-targets` and
`cargo fmt -p vfmt -- --check`: both silent/clean. Workspace-wide (now
that `vlog_semantic` compiles): `cargo build --workspace`,
`cargo clippy --workspace --all-targets` clean, `cargo test --workspace`
green across all crates. Note: workspace-wide `cargo fmt --check` is
*not* clean, but all 8 offending diffs are in
`crates/vlog_semantic/tests/qa_attack.rs` — outside this feature's scope
and outside the directive not to touch that crate; not a
parallel-files finding, flagging for whoever owns that crate.
Panic-under-parallelism scenario: see claim 2, reproduced with the exact
shape asked for (4 of 44 files panicking) and race-hunted 20× with zero
deviation. **Pass** (with the fmt note above filed separately, not
against this feature).
7. **Exit codes / stdin / per-file config.** Exit-code contract (0/1/2)
unchanged, exercised throughout the CLI suite and my own ad hoc runs.
`run_stdin` never calls `build_pool` — read from the source, confirmed:
stdin mode never touches rayon at all, not just "runs on one thread of
it". Per-file config under parallelism: exercised by
`every_file_keeps_its_own_config_when_formatted_in_parallel` (12 files ×
3 config layers) and `each_file_gets_the_config_of_its_own_directory`,
both green; did not find it necessary to add a third manual
two-dirs-two-configs run since these already cover more directories and
more files than that would. **Pass.**
**Race-hunting, beyond re-verifying the claims:**
- Panicking scenario (4/44) run 20× in parallel mode: one stdout hash, one
stderr hash across all 20, both identical to the `--threads 1` baseline.
- Corpus `--diff` run 5× at default threads plus 3× each at 1/2/8: 12 runs,
one hash each for stdout/stderr.
- `--threads 1000`: pool larger than the file count, both on a 3-file tree
and a single file, and separately against the full 860-file corpus
(0.2s wall, no anomalies).
- `.gitignore` that ignores everything: sane error, not a crash or silent
success.
- `.gitignore` + `--exclude` together: both filters active simultaneously.
- Deep-nesting file + panicking file + 10 good files in one parallel run
(`scratchpad/combo_tree`): all three outcome kinds correct at once — the
10 good files "would reformat" in input order, the deep file parses and
"would reformat"s normally (proving the pool's stack size, not luck, is
what saves it), the sabotaged file reports as a contained panic; exit 2
(error outranks would-reformat), no interleaving.
**One methodology note, not a product finding:** immediately after the
`WORKER_STACK` sabotage-and-restore in item 1, `cargo build -p vfmt`
reported "Finished in 0.01s" and silently kept serving the *stale* 2 MiB
binary — restoring the file with `mv` from a `sed -i.bak` backup left its
mtime older than the already-rebuilt (sabotaged) target, so Cargo's
mtime fast-path skipped recompilation despite the content being back to
the original 8 MiB source. This briefly made `cargo test --workspace`
report `a_deeply_nested_file_formats_on_a_worker_thread` and
`deeply_nested_file_does_not_kill_the_batch` as crashing. `touch`ing
`crates/vfmt/src/main.rs` and rebuilding made both pass again immediately,
and `git diff` on the file was unaffected throughout (content never
changed). Recorded here in case anyone else sees the same thing after a
`sed -i.bak` / `mv` round-trip on this codebase — it is a Cargo caching
quirk local to that workflow, not a vfmt bug.
**Severity summary:** no BLOCKING findings (zero nondeterminism observed
across ~40 varied repeated runs), no should-fix gitignore/git
disagreements (0 of many probe files disagreed). CLAUDE.md compliance:
no `unwrap`/`expect`/`panic!` in library code paths in `main.rs`/`args.rs`/
`walk.rs` outside `#[cfg(test)]` (grepped directly); all `pub` items carry
a one-line doc comment; feature stayed inside `crates/vfmt` +
`docs/features/parallel-files` as scoped, confirmed via `git status`/`git
diff --stat` against `HEAD`. README.md and TODO.md claims read as
accurate against what I independently measured.
## Review
**2026-08-19 — lead. Verdict: accepted; commits jointly with
vlog-semantic (both touch the root manifest).**
The project's first dependency, taken the right way: pre-sanctioned in
TODO §3, exact-pinned, five transitive crates audited for build
scripts, written justification. Three things stood out:
1. **The dev corrected the brief with evidence.** My premise that
rayon runs work on the calling thread is false for 1.12 — probed,
documented, and the conclusion (every file formats on an 8 MiB
worker) is *stronger* than the guarantee I asked for. Briefs are
hypotheses; this is the correct way to falsify one. QA then
independently re-proved it, and sabotage-verified that 2 MiB
workers die exactly as the handshake predicted.
2. **Both standing handshakes discharged on schedule**: the
recursion-limit stack requirement (8 MiB workers) and cli-polish's
single-install panic hook (Once + thread_local flag; uncontained
panics still get the real hook — verified live both ways).
3. **Determinism by construction** (collect indexed outcomes, print
serially in input order) held under a real race hunt: one stdout
hash and one stderr hash across 14 corpus-scale runs at four
thread counts. The buffered-stdout trade-off is documented.
The gitignore subset earning a 16/16 differential agreement with real
`git check-ignore` — including negation-inside-ignored-dir, the rule
most hand-rolled implementations get wrong — is the acceptance
evidence that matters. 3.6× wall-clock on the corpus is honest about
its sub-linearity (early parse failures).
QA's methodology note (Cargo mtime fingerprinting silently serving a
stale sabotaged build) is preserved in the QA log — future sabotage
checks should `touch` after restore.
+500
View File
@@ -0,0 +1,500 @@
# vlog-semantic
## Goal
`crates/vlog_semantic` is the analog of ruff's `ruff_python_semantic`: it takes
the AST `vlog_parser` produced for **one** file and builds the tables a
language server needs — a tree of scopes, a symbol per declaration, and a
reference per identifier *use*, each resolved to the declaration it names.
That is what `textDocument/definition`, `references`, `hover` and
`documentSymbol` are made of (TODO.md §6), and later what semantic lint rules
(unused signal, undriven net) will read — the rules Verible structurally
cannot write because it is syntax-only. This crate is deliberately
**single-file**: a name only another file can supply is not an error, it is an
`ExternalCandidate` carrying the import path, left for the workspace index
(the next feature in §6) to finish.
`analyze` never fails and never panics. It is written against the
error-tolerant tree, where `ItemKind::Error` / `StmtKind::Error` leaves are
opaque — the same treatment macro invocations and directives already get.
## API as built
```rust
pub fn analyze(file: &SourceFile, src: &str) -> Semantics;
impl Semantics {
fn scopes(&self) -> &[Scope]; // index 0 is the file scope
fn symbols(&self) -> &[Symbol];
fn references(&self) -> &[Reference];
fn scope(&self, ScopeId) -> Option<&Scope>;
fn symbol(&self, SymbolId) -> Option<&Symbol>;
// the LSP queries
fn symbol_at(&self, offset: u32) -> Option<SymbolId>;
fn reference_at(&self, offset: u32) -> Option<&Reference>;
fn definition_of(&self, offset: u32) -> Option<&Symbol>;
fn references_of(&self, SymbolId) -> Vec<&Reference>;
fn document_symbols(&self) -> Vec<DocumentSymbol>;
fn resolution_counts(&self) -> (usize, usize); // (resolved, total)
}
struct Symbol { name, kind: SymbolKind, name_span, decl_span, scope: ScopeId,
child_scope: Option<ScopeId> }
struct Reference{ name, name_span, scope: ScopeId, resolution: Resolution }
struct Scope { kind: ScopeKind, parent, owner: Option<SymbolId>, span,
symbols: Vec<SymbolId>, children, imports: Vec<Import> }
enum Resolution { Resolved(SymbolId), ExternalCandidate { paths: Vec<String> }, NotFound }
```
`SymbolKind` is the list the task named: `Module`, `Package`, `Port`, `Net`,
`Var`, `Param`, `Genvar`, `Typedef`, `EnumVariant`, `Function`, `Task`,
`TfArg`, `Instance`, `Block`, `StructMember`. `ScopeKind` is `File`,
`Module`, `Package`, `Function`, `Task`, `Block`, `Generate`, `Struct`.
### 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.
- **`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.
`Reference::resolved() -> Option<SymbolId>` is kept as the accessor the
sketch names, plus `is_external_candidate()`.
- **`Symbol.child_scope`** was added: the outline needs "what does this
declaration contain", and `p::x` resolution needs "which scope is package
`p`".
- **`references_of` does not include the declaration.** It returns *uses*
only; the declaration is `symbol.name_span`, and an LSP honoring
`includeDeclaration: true` appends it. Stated because the task asked for the
choice to be documented.
## Resolution rules
Two passes. Pass one (`bind.rs`) walks the tree, opens scopes, binds every
declaration and records every use as *pending*. Pass two (`resolve.rs`)
resolves the pending uses against the finished tables. Nothing resolves during
the walk, which is what makes **forward references** work: a net or parameter
used above its declaration resolves exactly like one used below it, as
Verilog requires at module scope — and as an editor needs mid-edit anywhere.
1. **Lexical chain.** From the scope the use is written in, outward through
parents to the file scope. In each scope: names declared there first, then
the packages that scope imports, then on to the parent.
2. **Ports and parameters are module-scope names**, so a module body sees
them; a `function`/`task`/block scope sees them through its parents.
3. **Enum variants land in the scope holding the enum**, per the LRM — not
inside the typedef. `typedef enum { IDLE } state_e;` in a module binds both
`state_e` and `IDLE` in that module.
4. **Struct members land in a `Struct` scope of their own**, hung under the
typedef. Nothing ever *looks up* into it (member access `x.field` is not
resolved, see below), so members cannot be reached as bare names — which is
correct — but they are still symbols, so the outline can show them.
5. **Imports.** `import p::*;` / `import p::x;` is recorded as an `Import` on
the scope that wrote it (module header imports land on the module scope).
Resolution consults it **only when `p` is a package declared in this
file**; otherwise the use becomes
`ExternalCandidate { paths: ["p::*"] }` — every import in the chain that
could supply the name, in scope order, for the workspace index to try. An
explicit `import p::x` is offered only for the name `x`.
6. **Package-scoped names.** `p::x` records two references: the head `p`
(target: a file-scope package) and the tail `x` (looked up in `p`'s scope
only, never in the lexical chain). If `p` is not in this file, both become
external candidates and the tail carries the full path `p::x`. If `p` *is*
in this file but has no member `x`, the tail is `Resolution::NotFound` —
not an external candidate, because the package is fully known locally and
no workspace index could change the answer. (QA find, lead-documented.)
7. **Instantiations.** The module name is a reference to a file-scope module,
else an external candidate naming the module. A named connection's
`.port` resolves **against that module's scope** — so `.data_i(x)` jumps to
the port declaration when the module is in the same file, and is an
external candidate when it is not. `.*` records nothing. Parameter
overrides `#(.W(8))` resolve the same way.
8. **Hierarchical names.** `a.b.c` resolves `a` and stops: no reference is
recorded for `.b` or `.c`. Resolving a tail needs instance elaboration,
which is a non-goal.
9. **Type names are uses.** A declaration written with a user-defined type
(`my_t x;`, `pkg::word_t y;`) records a reference for the type, so
go-to-definition works on it. Built-in type keywords record nothing.
10. **Redeclaration binds once.** A name already bound in a scope does not
create a second symbol; the second occurrence becomes a *reference* to the
first. This is what makes a non-ANSI port work — `module m(a); input a;`
has one `a` symbol (the header port) and one use (the body declaration) —
and it keeps `references_of` honest everywhere else.
11. **Not recorded at all:** system tasks (`$display`), anything spelled with
a leading backtick (a macro standing where a name belongs), and keywords
the parser left in an identifier slot.
### Scope tree
`File > module | package > function | task | named or unnamed block | generate
region | generate block | for-generate header | for/foreach statement`.
- A `for` generate opens a scope for its **header**, so `for (genvar i = 0;
...)` does not leak `i` into the module; the body block nests inside it.
`genvar i;` written at module scope binds there instead, as the LRM says.
- A `for`/`foreach` *statement* opens a scope for the same reason
(`for (int i = 0; ...)`).
- A `struct`/`union` body opens a `Struct` scope that lookup never enters.
### Simplifications (deliberate, all of them LRM-inexact)
- **Every `begin`/`fork` opens a scope, named or not.** The LRM gives an
unnamed block a scope only when it declares something; the difference is
invisible unless a program declares a name in an unnamed block *and* relies
on it leaking outward, which is illegal anyway.
- **Forward references are accepted everywhere**, including inside functions
and blocks where the LRM requires declaration-before-use. Being more
permissive than the language costs an editor nothing and buys mid-edit
robustness; a future lint rule can flag the strict violation.
- **First declaration wins on a duplicate name** (rule 10). The LRM makes a
true duplicate an error; reporting it belongs to the linter, not here.
- **Explicit imports do not outrank wildcard imports.** Imports are consulted
in the order written. The LRM prefers an explicit `import p::x` over a
wildcard from another package; a file that needs that distinction is
already ambiguous to a human reader.
- **A function's name is not also a variable.** `f = expr;` inside `function
f` resolves to the function symbol, which is where go-to-definition should
land anyway.
- **`endmodule : m` and other end labels record nothing.**
- **`defparam` paths, `disable` targets and event names** are resolved with
the ordinary lexical rule (`disable blk` finds the named block).
- **Ordering inside a scope is not modeled**: `symbol_at` and lookup are
position-independent. There is no "this name was not yet visible here".
## Non-goals
- **No type checking, no width inference, no elaboration.** Nothing here knows
what a symbol's *type* is beyond the kind of declaration it came from.
- **No cross-file anything.** No `` `include`` following, no workspace scan.
External names are reported, never resolved.
- **No macro expansion.** `` `NAME `` and `` `NAME(...) `` are opaque tokens;
a name a macro would have produced is invisible to this crate, which is the
same contract the formatter and the define table keep (TODO.md §7).
- **No classes/constraints/UVM.** The parser does not accept them yet; when it
does, they will need scope kinds of their own.
## Assumptions
- `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
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.
- 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.
## Handshakes
**Consumed from `vlog_parser`** (nothing here requires a change to work):
- `ast::SourceFile` and the whole node tree, including `ItemKind::Error` /
`StmtKind::Error` from `parse_source_tolerant` — treated as opaque leaves.
- `span::TextRange` on items, statements, expressions, declarators, ports,
parameters, instances, enum members, struct members, dims and blocks.
- `token::is_keyword` — to tell a built-in type keyword from a user type name,
and to drop keywords the parser left in identifier slots.
**Promised to consumers** (`vfmt_server`, the workspace index, future lint
rules):
- `analyze` never panics and never fails, on any input, tolerant tree or not.
- `Symbol.name_span` / `Reference.name_span` are exact byte ranges of the name
as written, or empty when the source does not spell the name literally.
Empty ranges never match `contains`, so a query never returns one.
- Every `Reference` whose `Resolution` is `ExternalCandidate` carries the
workspace-level paths that could finish it; the workspace index may rewrite
those references and nothing else.
**Requested of `vlog_parser`** (not done here — out of scope for this
feature, and the crate works without it):
1. **`name_span: TextRange` on the nodes whose name is a bare `String`**:
`Module`, `ItemKind::Package`, `FunctionDecl`, `TaskDecl`, `AnsiPort`,
`ParamPort`, `TfArg`, `Typedef`, `Instantiation::module`,
`Connection::name`, `ItemKind::Genvar`, `ItemKind::Import`,
`GenBlock::label`, `StmtKind::Block::label`, `StmtKind::Foreach::vars`,
`ExprKind::Member::name`, `ExprKind::Scope::name`. Every one of those is
currently recovered by re-scanning source text in
`crates/vlog_semantic/src/scan.rs`, which is ~150 lines this crate should
not own and which cannot be right by construction — only right in
practice, as the corpus test shows. This is the single change that would
most simplify this crate.
2. **A span for `DataType`** (and for `ExprKind::Cast::ty`), so a type
reference does not need a window computed from its neighbours' spans.
3. Nice to have, much smaller: the byte range of `Member`/`Scope` tails, which
is today derived as `span.end - name.len()`.
## Corpus baseline
`cargo test -p vlog_semantic --test corpus -- --nocapture`, over the 860
`.v`/`.sv`/`.svh` files in `corpus/` (Ibex, OpenTitan, PULP common_cells,
picorv32), 2026-08-19:
| population | files | symbols | references | resolved in-file | external candidates | unresolved |
|---|---:|---:|---:|---:|---:|---:|
| every file | 860 | 21 485 | 73 708 | 73.4 % | 19.4 % | 7.2 % |
| files that parse with zero errors | 502 | 12 900 | 46 408 | 79.5 % | 19.6 % | **0.9 %** |
No panics, and every one of the 95 193 name spans built across the corpus
slices back to exactly the name it claims (0 unplaced).
Reading the numbers honestly:
- **~20 % external candidates is the expected steady state, not a defect.**
RTL of this size lives on `import prim_pkg::*` and instantiates modules
declared elsewhere; those references are *supposed* to leave this crate
unfinished. The workspace index converts this bucket, and it is the single
biggest lever on perceived LSP quality.
- **0.9 % genuinely unresolved on clean files** is the interesting number. A
sample of what is in it: names a `` `define`` would have produced (`XLEN`,
`ENABLE_IRQ`), class/UVM constructs in files that parse only because their
broken parts became error nodes (`this`, `super`, `null`, `new`), and
hierarchical/member tails reached through a path this crate stops at.
- **The 7.2 % over *all* files is dominated by the 42 % of corpus files that
still hit a parse error** (classes, `bind`, queues — README's "not yet
supported" list): a declaration swallowed by an error node cannot bind, so
every use of it counts unresolved. That number will move when the parser
moves, not when this crate does.
The test asserts the two properties, not the percentages: zero unplaced names
anywhere, and under 3 % unresolved on cleanly-parsed files.
## Status / TODO
- [x] New crate `crates/vlog_semantic`, workspace member, no dependency
beyond `vlog_parser` + std
- [x] Scope tree with parent links (file / module / package / function / task /
block / generate / struct)
- [x] Symbols for all 15 kinds, with `name_span`, `decl_span`, `scope`,
`child_scope`
- [x] References for expression identifiers, type names, hierarchical heads,
instantiated module names, `.port` connections, package heads and tails,
import paths
- [x] Two-pass bind-then-resolve (forward references)
- [x] Imports: in-file packages resolved, others kept as `ExternalCandidate`
with their paths
- [x] Queries: `symbol_at`, `reference_at`, `definition_of`, `references_of`,
`document_symbols`
- [x] `Error` nodes are opaque; tolerant trees analyze without panicking
- [x] Tests: 19 behavior tests + 6 scanner unit tests + corpus smoke test
- [x] TODO.md §6 `vlog_semantic` checkbox
- [ ] Deferred to the workspace index: resolving `ExternalCandidate`s
- [ ] Deferred: interfaces/modports, classes — the parser does not accept them
- [ ] Deferred: `Symbol` type information (needed for hover text richer than
"port, declared at line N")
## Work log
**2026-08-19 — dev agent.** Built the crate: `model.rs` (tables), `bind.rs`
(pass one), `resolve.rs` (pass two), `scan.rs` (name-span recovery),
`lib.rs` (`analyze` + queries). Key decisions, all argued above:
- **`analyze(file, src)`**, not `analyze(file)`. Discovered while mapping the
AST that only `Declarator`, `EnumMember`, `Instance`, `NonAnsiPort` and the
expression nodes place their name at a span I can compute; everything else
keeps the name as a `String` inside a construct-wide span. Rather than park
go-to-definition for modules, ports, functions, tasks, parameters, block
labels, genvars and connections — most of the feature — I took the source
text and scan for the name inside a window narrowed by the spans that do
exist. Handshake request #1 filed to make this unnecessary.
- **One `Resolution` enum** instead of `Option<SymbolId>` plus a parallel
external state; `resolved()` keeps the sketch's accessor.
- **Redeclaration becomes a reference** (rule 10). Found while binding
non-ANSI ports: `module m(a); input [7:0] a;` would otherwise produce two
`a` symbols and split its references between them.
- **Struct members get a scope lookup never enters.** The alternative — put
them in the enclosing scope — would make a bare `field` resolve to a struct
member, which is wrong.
- The scanner skips a backtick plus its identifier as one token, so `` `WIDTH ``
never answers a search for `WIDTH`; and `use_name` drops names that start
with a backtick, which is how `` `PICORV32_REGS regs (...) `` (a macro used
as a module name, twice in picorv32) stopped being an unplaceable reference.
That took corpus unplaced names from 2 to 0.
- Corpus numbers are reported for two populations because the all-files number
is mostly a statement about parser coverage, not about resolution.
Checks at the end: `cargo test -p vlog_semantic` 26 tests green (19 + 6 + 1),
`cargo clippy -p vlog_semantic --all-targets` silent, `cargo fmt` clean,
`cargo test --workspace` green.
## QA log
**2026-08-19 — QA agent.** Verified against `crates/vlog_semantic/src/{lib,model,bind,resolve,scan}.rs`
and this README. Scope: `-p vlog_semantic` only.
Gates:
- `cargo test -p vlog_semantic`: **26 passed** (6 scan unit + 1 corpus + 19
behavior), 0 failed, matching the claimed count exactly.
- `cargo clippy -p vlog_semantic --all-targets`: silent. No `#[allow]`,
`unwrap()`, `expect()` or `panic!` anywhere in `src/*.rs`.
- `cargo fmt -p vlog_semantic -- --check`: clean.
- `cargo tree -p vlog_semantic`: exactly `vlog_semantic -> vlog_parser`, no
other dependency. Confirms "no deps beyond vlog_parser + std."
- Root `Cargo.toml` diff: the `members` line gains `vlog_semantic`, as
claimed. (The diff also carries an unrelated `[workspace.dependencies]
rayon = "=1.12.0"` hunk — that belongs to the concurrently-worked
`parallel-files`/`vfmt` feature, out of my scope, noted only so the
"members-line-only" claim for *this* feature isn't misread against the
whole file.)
- `cargo test --workspace`: **2 failures**, both in `crates/vfmt`
(`a_deeply_nested_file_formats_on_a_worker_thread`,
`deeply_nested_file_does_not_kill_the_batch`) — outside my gate
(`-p vlog_semantic` is green) and inside the area another QA agent owns
concurrently. Flagging only so "workspace green" isn't taken at face
value right now; not a `vlog_semantic` finding.
- `SymbolKind` has exactly 15 variants, `ScopeKind` exactly 8, matching the
claim (counted in `model.rs`).
- TODO.md §6's `vlog_semantic` line is checked and its numbers (79.5% /
19.6% / 0.9%) match the corpus re-run below verbatim.
Corpus re-run (`cargo test -p vlog_semantic --test corpus -- --nocapture`),
reproduced **exactly**, not just within noise:
```
corpus (every file): 860 files, 21485 symbols, 73708 references — 73.4% resolved in-file, 19.4% external candidates, 7.2% unresolved, 0 names unplaced
corpus (files that parse cleanly): 502 files, 12900 symbols, 46408 references — 79.5% resolved in-file, 19.6% external candidates, 0.9% unresolved, 0 names unplaced
```
Wall time 0.73s (well under the 2s claim). 0 panics, 0 unplaced names, both
populations match the README table exactly.
**Attack suite.** Wrote a scratch integration test
(`crates/vlog_semantic/tests/qa_attack.rs`, 20 `#[test]` fns, deleted after
this pass — not part of the shipped suite) exercising the crate only
through its public API. All 20 attacks passed; no BLOCKING findings. Cases
covered:
- *scan.rs / name_span (claim 2):* module name shadowed by an identical
string in a leading `//` comment (correctly skipped — lands on the real
`module foo`, not the comment); a port name that is a whole-word prefix
of a sibling port (`w` vs `ww` — `NameScanner` compares whole tokens, not
substrings, so this class of bug is structurally excluded, not just
untriggered here); a `genvar i` declared amid `ii`/`i_delay` lookalikes
used throughout a generate-for body; a construct where the name sits at
byte 0 of its window and another where it ends exactly at the window's
last byte (`package p;endpackage`); a block comment full of multi-byte
UTF-8 sitting between a module's keyword and its ports; an escaped
identifier (`` \a+b ``) — the lexer passes these through, and both its
declaration and its later use land on exactly `\a+b` (4 bytes), correctly
resolved; a non-ANSI port used twice in the body, confirming exactly one
symbol exists and both body occurrences are *uses* whose `name_span`
sits at the body text, not the header; an instantiation where the
instance name and the module type name are the same token
(`dff dff (...)`) — the module-name reference and the instance symbol's
`name_span` are distinct, non-overlapping ranges.
- *resolution (claim 3):* three-deep shadowing (module net / function arg /
block var all named `x`) — `references_of` on each binding contains only
its own use, verified for all three; an enum variant used textually
before its `typedef enum` — resolves (two-pass forward reference, as
designed); `import p::*` where package `p` is declared *below* the
import in the same file — resolves (two-pass); `import` of a package not
in this file — `ExternalCandidate { paths: ["nowhere_pkg::*"] }`, exact
path confirmed; two wildcard imports of different in-file packages that
both define the same name — the first-written import wins (matches the
README's documented "consulted in the order written" rule); `p::x`
where `p` **is** an in-file package but `x` is not a member of it —
resolves to `Resolution::NotFound`, *not* `ExternalCandidate`. This
distinction is correct (the workspace index can't help — the package is
fully known locally) but **is not stated in the README's rule 6**, which
only describes the "`p` not in this file" case. Filed as a documentation
gap, not a bug (see Findings below); a named connection `.clk(clk)` —
confirmed the `.clk` token resolves into the instantiated module's port
scope (`SymbolKind::Port`) while the `(clk)` argument resolves against
the local net (`SymbolKind::Net`), two different symbols from one
connection, as documented; an instance array (`sub u[3:0] (...)`) binds
and resolves its connections without confusion; a recursive function
(`fact`) — both the self-assignment (`fact = ...`) and the recursive
call (`fact(n - 1)`) resolve to the function's own symbol; a reference to
a generate-for's genvar from inside a nested `if`-generate two levels
deep — resolves through the header scope as designed.
- *tolerant-tree safety (claim 4):* 10 broken files, including the exact
header-distortion repro from `docs/features/error-recovery/README.md`
(`module m #(parameter W = , parameter X = 4) (input a); wire ok;
endmodule` — module body re-parses as file-scope items) plus a broken
port list, an orphaned `endmodule` with no matching `module`, an
unterminated string, garbage tokens mid-body, mismatched `begin`/`end`,
a broken for-generate header, an empty file, a dangling backtick macro
with broken arguments, and two broken module headers back to back. No
panics; every non-empty `name_span`/`Reference.name_span` produced still
slices back to exactly the name it claims, even on these malformed
trees.
- *queries (claim 5):* `definition_of`/`symbol_at`/`reference_at` called at
every byte offset (0..=len) of a small multi-construct file — no panic
at any offset, including offsets that land on whitespace, punctuation,
or mid-token.
**Findings.**
- *Should-fix (documentation gap, not a bug), LOW.* README rule 6
("Package-scoped names") describes only two outcomes for `p::x`: `p`
external (both refs become `ExternalCandidate`), or implicitly `p`
in-file and `x` found. It doesn't say what happens when `p` is in-file
but `x` is not one of its members. Actual (and, on inspection, correct)
behavior per `resolve.rs`'s `Target::PackageMember` arm: the tail
resolves to `Resolution::NotFound`. Recommend adding one sentence to
rule 6. Repro: `b6_package_member_missing_from_an_in_file_package` in the
now-deleted scratch suite —
```
package p; localparam int K = 1; endpackage
module m; assign w = p::MISSING; wire w; endmodule
```
`s.reference_at(<the "MISSING" span>).resolution == Resolution::NotFound`.
- No BLOCKING findings. No wrong `name_span` (pointing at a comment, a use,
or the wrong occurrence) and no panic were produced by any attack above,
including the specific risky shapes named in the QA brief (comment
shadowing, substring siblings, UTF-8 preceding a name, escaped
identifiers, same-name instance/module, header-distortion trees).
Everything else (claims 1, 3's remaining rules, 4, 5) verified as
documented: `analyze` never panicked across the full corpus or the 10
broken-file probe; the 15 `SymbolKind`/8 `ScopeKind` counts are exact;
`references_of` round-trips (pre-existing test plus the shadowing probe
above); `document_symbols` nesting was not independently re-probed beyond
the existing `document_symbols_nest_declarations_under_what_declares_them`
test, which already covers module > function > block and passes.
## Review
**2026-08-19 — lead. Verdict: accepted; commits jointly with
parallel-files (both touch the root manifest). The differentiation
feature has arrived: this is the layer Verible doesn't have.**
What earned it:
1. **Two-pass bind-then-resolve** was the only correct answer to
Verilog's forward references, and taking it from the start avoided
the incremental-resolution trap. The redeclaration-becomes-reference
rule for non-ANSI ports is the kind of language-specific judgment
that makes references_of actually useful.
2. **`Resolution` as a three-state enum** (Resolved / ExternalCandidate
carrying paths / NotFound) is the right interface for the workspace
index: the index gets exactly the worklist it needs, and QA's
documentation find — in-file package misses are NotFound *because no
index could change the answer* — shows the semantics were thought
through, now stated in rule 6.
3. **`scan.rs` is honest scaffolding**: 95k spans verified against
source, every QA attack defeated (comments, substrings,
decl-vs-use, escaped identifiers), and a filed handshake whose
acceptance deletes the module. The `name_span`-in-parser handshake
is hereby approved for the next parser-touching round.
4. The corpus baseline (79.5% in-file resolution, 0.9% unresolved on
clean files, 19.6% waiting on the index) is exactly the honest
number the workspace-index feature will be measured against.
The workspace-green gate was transiently false during QA (two vfmt
deep-nesting tests) — timing overlap with the parallel-files QA's
deliberate stack-sabotage check, verified restored before the joint
commit.