Files
lucisv/docs/features/name-spans

name-spans

Goal

The parser sits on the token that spells a declared name at the moment it reads it, so recording that token's byte range costs one expression per site. Before this feature it threw the range away: ~15 AST node kinds kept a declared name as a bare String inside a construct-wide span, which forced crates/vlog_semantic/src/scan.rs — ~150 lines of comment/string/macro-aware source scanning — to re-find every name in the source text. That scan is right in practice (95 193 spans verified against the corpus) but cannot be right by construction: it is a search for a string inside a window, and any node whose name is a substring of a neighbour, or is written twice inside its own span, is a bug waiting for the right file. This feature moves the fact to where it is known. Symbol.name_span is what textDocument/definition, documentSymbol, references and hover all point at, so it is on the critical path of every LSP feature in TODO.md §6.

Nothing else changes: the formatter never reads the new fields, its output is byte-identical, and the corpus TSV md5 is unmoved.

The convention

A declared name keeps its String and gains a sibling TextRange field that is the exact byte range of the identifier spelling it, so src[name_span] == name. Where a node holds a list of names, the pair is bundled into Name { text, span } instead.

Sibling fields are named after the name they range over: name_span for the declared name, label_span / end_label_span for begin : l … end : l, module_span for the module an Instantiation names. An optional name gets an Option<TextRange>, and the two are always Some/None together (the walker test asserts this rather than trusting it).

Why siblings and not a Name newtype everywhere

A Name { text, span } replacing every name: String was the other candidate and reads better in the abstract. It was rejected on churn and on risk:

  • Read sites, not construction sites, dominate. format.rs reads a declared name in ~35 places — text(p.name.clone()), names.join(", "), format!(".{}(", c.name), closing(&str, &Option<String>). Every one would need either an edit or a Deref/Display/PartialEq<str> impl to paper over, and the ones needing an edit (clone() returning the wrong type, join on a Vec<Name>, the Option<String> helper signature) would not all be caught by inference — they would be rewritten by hand, in the one file this round is required to leave behaviorally untouched.
  • Sibling fields are pure additions. A new field on a struct breaks only struct-literal construction, which lives entirely in parser.rs. The formatter and vlog_semantic compiled unchanged against every one of the 24 sibling-field additions; only the four list-shaped changes needed an edit anywhere else. "Zero behavior change" is then a claim about a diff that barely touches the printer, which is checkable rather than argued.
  • The cost is a two-field invariant (name and name_span must agree), which is exactly what the walker test asserts on every node of every source it parses — including the error-recovery trees.

Why lists are the exception

ItemKind::Genvar, StmtKind::Foreach::vars and the two import-path lists hold n names, so the sibling shape would be a parallel Vec<TextRange> that nothing keeps in step: a push to one and not the other compiles, and the lengths only disagree at runtime. Vec<Name> makes that unrepresentable. This is one rule with one stated exception, not two conventions — the exception is where the sibling shape stops being sound, not where it stops being convenient.

import p::x needed a shape either way: the path used to be stored pre-joined as "p::x", and vlog_semantic resolves the two halves against different scopes, so a single span over the whole path would not have answered the question. ImportPath { pkg: Name, item: Name } carries both, with ImportPath::text() rebuilding the "p::x" spelling the formatter prints. A wildcard is item.text == "*" with the * token's span.

Fields added

28 in all. Sibling TextRange unless noted.

node field(s)
Module name_span, end_label_span
ItemKind::Package name_span, end_label_span
ItemKind::Import payload is now Vec<ImportPath> (2 spans per path)
HeaderImport paths is now Vec<ImportPath>
ItemKind::Genvar payload is now Vec<Name>
Typedef name_span
EnumMember name_span
Declarator name_span
AnsiPort name_span
ParamPort name_span
TfArg name_span
Instantiation module_span
Instance name_span
Connection name_span
GateInstance name_span: Option<TextRange>
GenBlock label_span, end_label_span
FunctionDecl name_span, end_label_span
TaskDecl name_span, end_label_span
StmtKind::Block label_span, end_label_span
StmtKind::ForkJoin label_span, end_label_span
StmtKind::Foreach vars is now Vec<Name>

Deliberately not added:

  • NonAnsiPort — its span already is the name's range (module m (a, b); writes nothing else), so a name_span would store the same fact twice. Documented on the struct. The walker test checks src[span] == name there too, so the equality is asserted rather than assumed.
  • ExprKind::Member::name / ExprKind::Scope::name (handshake item 3). The name is the construct's last token, so its range is exactly span.end - name.len() .. span.end — derivable, and bind.rs already derives it without calling scan.rs. Same reasoning as the spans feature's "payload structs whose extent equals their wrapper's".
  • DataType (handshake item 2). A type name is a use, not a declaration, and an implicit type has no tokens at all, so the honest fix is an Option<TextRange> on DataType — a separate decision, already recorded as an open gap in docs/features/spans/README.md.
  • StmtKind::Disable — a use, not a declaration.

Assumptions

  • A declared name is one token. True for every name in the list above: expect_name reads a single Ident, and its span is that token's. The one multi-token exception is called out below.
  • Instantiation.module may be scope-qualified. pkg::mod is parsed as three tokens and stored with the :: glued ("pkg::mod"), so src[module_span] equals module modulo the whitespace a source may write around the ::. This is the same class of divergence the lexer's sized-literal normalization already has (8 'h FF → 8'hFF, spans README): the span is the real extent and the text is normalized. The walker asserts the despaced equality for this one field and exact equality everywhere else. Everything else in the tree that can be scope-qualified is a use, not a declaration.
  • Escaped identifiers are ordinary names. The lexer reads \a+b as one Ident, so its span is exact and may cover multi-byte text; nothing here inspects the bytes.
  • The formatter still prints from the String. The new fields are write- only as far as vlog_formatter is concerned, which is what makes "no behavior change" a property of the diff rather than a test result.
  • Spans are only meaningful for the exact text they were lexed from, as for every other span (spans README).

Handshakes

Consumed from vlog_parser itself: Parser::here() and the token stream. Two new private helpers do all the work — expect_name() -> PResult<Name> (the identifier at the cursor plus its range; expect_ident now delegates to it) and parse_label() -> PResult<Option<Name>> (an optional : name after begin/fork or after a closing keyword; it replaces parse_end_label and now serves both the opening and the closing label, which used to be parsed by two different snippets).

Promised to vlog_semantic (and to the workspace index, and to lucisv_server when it exists):

  • Every field in the table above is the exact byte range of the name as written: src[name_span] == name, with the one documented Instantiation.module_span whitespace caveat.
  • Each range nests inside the span of the node that declares the name (the spans-feature nesting invariant is unchanged and now covers these too).
  • Option name and Option span are always Some/None together.
  • These hold on error-tolerant trees as well: the ranges come from real tokens, so a recovered file's names are placed exactly like a clean file's.

scan.rs deletion unblocked; vlog_semantic should switch to these fields in its next round. Every scan.rs consumer in bind.rs now has a parser-supplied span to read instead: name_after_kw (module/package), NameScanner (genvar, imports, foreach vars, typedef name), and name_span(...) (declarators, enum members, instances, module names, connections, gate instances, block labels). What is not covered is bind_data_type's type-name window — that needs handshake item 2 (DataType span), which this round deliberately did not do. So scan.rs shrinks to the type-name case now and disappears when item 2 lands.

Promised to vlog_formatter: nothing new. It ignores every field added here; see the three compile-fixes below, all of which rebuild a string the parser used to store pre-joined.

Recursion/chain budgets (docs/features/recursion-limit/README.md): no new budget, none needed. TextRange is a Copy pair of u32s stored inside existing nodes; Name and ImportPath are leaves with no children. No new recursion, no new Box, no added root-to-leaf depth.

Compile-fixes outside vlog_parser

Both crates are outside this feature's scope, so each edit is listed:

crates/vlog_formatter/src/format.rs — 8 lines, all forced by a payload type change, none behavioral:

  1. ItemKind::Package { .. } and four StmtKind::Block/ForkJoin patterns gain .. for the new fields (5 lines).
  2. ItemKind::Import(paths) and the header-import line: paths.join(", ") → join_paths(paths) (2 lines).
  3. ItemKind::Genvar(names) and StmtKind::Foreach's vars.join(", ") → join_names(names) (2 lines).

The two new private helpers join_names / join_paths produce exactly the strings the old Vec<String> held (ImportPath::text() is the same format!("{pkg}::{sym}") the parser used to store), which is why the corpus TSV is byte-identical.

crates/vlog_semantic/src/bind.rs — 7 lines, mechanical, no logic touched. NameScanner is still used exactly as before; only the way the name string is reached changed:

  1. ItemKind::Genvar arm: name → &name.text (2 lines).
  2. bind_imports takes &[ImportPath], and both its loop and the header- import loop pass &path.text() (3 lines).
  3. StmtKind::Foreach arm: v → &v.text (2 lines).

No other vlog_semantic file was touched (the concurrent workspace-index work owns workspace.rs, lib.rs, model.rs, tests/workspace.rs). The crate's corpus test reports the identical numbers afterwards — 21 485 symbols, 73 708 references, 0 names unplaced.

Status / TODO

  • Convention chosen and justified: sibling TextRange, Name for lists.
  • Name and ImportPath in ast.rs, with the module-level doc stating the rule.
  • 28 fields across 21 node kinds (table above).
  • expect_name / parse_label / split_label in parser.rs; 24 expect_name call sites (one of them expect_ident's delegation) and 11 split_label call sites.
  • src[name_span] == name and nesting asserted for every new field in the exhaustive walker (every_node_span_nests_inside_its_parent, recovered_error_nodes_nest_inside_their_parent, and a new fixture sweep).
  • Content-pin test on a dense source naming every field by hand.
  • Multi-byte names, a name behind attributes and comments, and a label whose text repeats as its own end label.
  • Mutation-tested: three deliberate mis-wirings, all caught.
  • Formatter output unchanged: corpus TSV md5 aa982463f68c1a3568c02a0fc5e0c455, byte-identical to the baseline; no .cases/fixture/snapshot churn.
  • cargo fmt clean, cargo clippy --workspace --all-targets silent, cargo test --workspace 299 passed / 0 failed.
  • Not done, deliberately: DataType span (handshake item 2) and the Member/Scope tails (item 3) — reasoning above.
  • Left to vlog_semantic: switch bind.rs to these fields and delete the declaration half of scan.rs.
  • No TODO.md item covers this feature; nothing there was checked.

Work log

2026-08-19 — dev agent

  • Read CLAUDE.md, the spans and vlog-semantic READMEs (the latter's Handshake request #1 and the lead's approval of it) before touching code. Baseline: working tree clean at 7cf657a, corpus TSV md5 aa982463f68c1a3568c02a0fc5e0c455.
  • Picked the convention by counting read sites, not construction sites. The task framed the choice as "whichever minimizes churn at the ~28 construction sites"; both candidates are one line each there, so the decision actually lives in format.rs's ~35 reads. Sibling fields make those zero. Recorded in full above because it is the reversible-only-at-cost decision of this round.
  • Lists forced the one exception. Found while wiring ItemKind::Genvar: a Vec<String> has no sibling to hang a range off, and a parallel Vec<TextRange> is an invariant the compiler cannot hold. Vec<Name> it is, for genvars, foreach variables, and both import-path lists.
  • import needed a real shape, not just a span. The path was stored pre-joined (format!("{pkg}::{sym}")) and vlog_semantic resolves p and x in different scopes, so one span over "p::x" would have answered neither question. ImportPath { pkg, item } + text() keeps the formatter printing the identical string.
  • parse_end_label became parse_label and now parses both ends. The opening label of begin : l was an inline if self.eat_sym(":") snippet duplicated in three places with the same body as parse_end_label; giving the labels spans meant editing all four anyway, so they collapsed into one function. split_label turns its Option<Name> into the (Option<String>, Option<TextRange>) pair the sibling convention stores.
  • parse_tf_body kept returning an Option<Name> rather than the split pair: the four-element tuple tripped clippy::type_complexity, and the two callers split it themselves in one line.
  • The one honest divergence is Instantiation.module_span. pkg::mod is three tokens stored as one glued string, so exact slice equality is false whenever a source writes pkg :: mod. Rather than special-case the parser I documented it as the same normalization class the lexer already has for sized literals, and made the walker assert despaced equality only for that field — exact everywhere else, so the weaker assertion cannot leak.
  • Mutation-tested the new assertions before believing the green run, since the whole feature is one property:
    1. expect_name recording the next token's span instead of the current one → 3 tests fail (the multi-byte, attribute and label tests).
    2. Connection.name_span set to the whole connection's span → 3 fail (dense, fixtures, walker).
    3. Instantiation.module_span collapsed to an empty range → 3 fail. Reverted all three; git diff verified byte-identical before and after.
  • Did not touch verify.rs or tests/verification.rs: no normalization was added, broadened or weakened, so CLAUDE.md invariant #4 does not apply to this round, and the byte-identical corpus TSV is the evidence the safety net sees exactly what it saw before. Did not run git commit/git push.
  • Concurrency note. The workspace-index agent was live in crates/vlog_semantic throughout (workspace.rs, tests/workspace.rs, lib.rs, model.rs, docs/features/workspace-index/). I touched only bind.rs, which they did not (git diff on it shows my 7 compile-fix lines and nothing else). One transient failure of their an_empty_workspace_answers_nothing_and_panics_nowhere was observed mid-round; it was their file being edited between my two runs (the panic message and line number did not match the file on disk) and was green on re-run. A pre-existing clippy::cmp_owned warning in their tests/workspace.rs is theirs and was left alone.

Results. cargo test --workspace 299 passed, 0 failed, of which tests/spans.rs went from 12 to 17. One existing assertion was rewritten, not added to: parser.rs's header_imports_stay_separate_statements unit test compared Vec<&[String]> of header-import paths, which the ImportPath payload change makes ill-typed; it now compares ImportPath::text() against the same expected strings. Nothing else in any existing test moved. cargo clippy --workspace --all-targets silent apart from the concurrent feature's own warning. cargo fmt --all --check clean. tools/corpus_check.sh corpus (read-only): 820 files, 0 verification errors, 0 crashes, TSV md5 aa982463f68c1a3568c02a0fc5e0c455 — byte-identical to the baseline. Corpus repos clean apart from the pre-existing untracked .lucisv-corpus-rev stamps. cargo test -p vlog_semantic --test corpus: 21 485 symbols, 73 708 references, 0 names unplaced, unchanged in every digit.

Files touched: crates/vlog_parser/src/{ast,parser}.rs, crates/vlog_parser/tests/spans.rs, crates/vlog_formatter/src/format.rs (8 lines, listed above), crates/vlog_semantic/src/bind.rs (7 lines, listed above), this README, and one line in docs/features/vlog-semantic/README.md's Handshakes.

QA log

2026-08-19 — QA agent

Scope: -p vlog_parser, -p vlog_formatter, -p vlog_semantic (workspace run at the end only). Did not touch crates/vlog_semantic/src/workspace.rs or docs/features/workspace-index/ (concurrent agent's territory). No commit/push.

Gates — all green, exact numbers.

  • cargo test -p vlog_parser: 24+19+17 = 60 passed (unit 24, error_recovery 19, tests/spans.rs 17, up from 12 as claimed).
  • cargo test -p vlog_formatter, -p vlog_semantic, --workspace: all green. Per-crate counts summed to 299 passed, 0 failed, matching the work log exactly (50+30+8+1+4+6+2+39 lucisv/vlog_formatter, 53+24+19+17 vlog_parser, 6+1+19+20 vlog_semantic).
  • cargo clippy --workspace --all-targets: silent (forced a re-check with touch on parser.rs first, since a cached Finished line proves nothing). cargo fmt --check: clean, exit 0.
  • tools/corpus_check.sh corpus: TSV md5 aa982463f68c1a3568c02a0fc5e0c455 — byte-identical to the claimed baseline. verification-error: none, crash: none.
  • cargo test -p vlog_semantic --test corpus -- --nocapture: 21485 symbols, 73708 references, 0 names unplaced for "every file"; exact match to the claim.

Claim 2 (despaced equality can't leak). Read the full walker in tests/spans.rs. despace( appears at lines 118/119 (an unrelated number/comment-normalization check) and 462/463 (Instantiation.module_span only). Every other name assertion goes through check_name/check_names/ check_opt_name/check_import_paths, which all do exact assert_eq!(slice, name). Confirmed the weaker rule cannot leak — it is syntactically isolated to one call site.

Claim 3 (skips). Confirmed in ast.rs + bind.rs: NonAnsiPort has no name_span field and the walker checks p.span itself as the name range (spans.rs:399). ExprKind::Member/Scope carry no name-range field, and bind.rs:735-736 derive the tail directly from e.span/base.span without scan.rs, as claimed. DataType (ast.rs:259-263) has no span field. StmtKind::Disable untouched.

Field/helper counts, independently recomputed, not just read off the README: summed the sibling-TextRange additions in the ast.rs diff by hand — 24 non-list fields + 4 list-shaped conversions (Import, HeaderImport, Genvar, Foreach::vars) = 28, across 21 node kinds, matching the table. grep -c 'expect_name()' parser.rs = 24 (one of them expect_ident's delegation, as claimed). grep -c 'split_label(' = 12, i.e. 11 call sites plus the one fn split_label definition — matches "11 split_label call sites" exactly.

Attack tests (scratch, crates/vlog_parser/tests/attack_spans.rs, deleted after — git status on tests/ shows only the pre-existing spans.rs diff). 10 tests, all green on first correct attempt (two early versions failed for reasons in my own test setup, not the feature — see below), then rm'd:

  1. Escaped identifiers in a module name and a non-ANSI port (\a+b, \x!y) — spans exact.
  2. begin : same … end : same — label_span != end_label_span, both slice back to "same".
  3. import p::*, import p::x, and import q::a, r::b at both body-item and module-header position — every pkg/item span exact, including the wildcard's * token.
  4. genvar gi, gj, gk; — 3 Names, order and spans exact.
  5. foreach (arr[i, j]) — 2 vars, spans exact.
  6. Instantiation.module_span for sub (plain), pkg :: mod (spaces around ::, span covers the whole glued extent including the spaces, despaced-equal to "pkg::mod"), and pkg::mod (tight) — all three as claimed.
  7. One and statement with two comma-separated instances, one named one not — Option name/name_span handling confirmed on both arms of the same GateInstantiation.
  8. (* x *) wire w; — name_span slices to "w" and excludes the attribute's own byte range.
  9. CRLF file — module and declarator name spans still exact under \r\n.
  10. Module keyword at byte 0 — name_span.start == 7, exact slice.

My first draft of tests 1, 3 and 7 failed for reasons in the test, not the parser: test 1 put an input declaration in the module body and asserted it against PortList::NonAnsi (there was no port list at all); test 3 checked m.imports (header imports only) for body-level import items, which live in m.items as ItemKind::Import; test 7 wrote two separate and statements and expected them to share one GateInstantiation, when each statement is its own item. Fixed all three and re-ran; all 10 green. No feature defect found by any of the ten attacks.

Mutation re-verification (claim 5). Re-collapsed Instantiation.module_span to TextRange::empty(module_start) at parser.rs:1467. Result: 3 test failures (every_name_span_slices_back_to_its_name, every_node_span_nests_inside_its_parent, name_spans_hold_across_the_formatter_fixtures), matching the work log's claim exactly. Reverted; git diff on parser.rs before and after the mutate/revert cycle is byte-identical (diffed the two git diff outputs directly).

Formatter byte-identity beyond the corpus TSV (claim 4). Built a baseline lucisv release binary from a git worktree at HEAD (7cf657a, the dev's stated baseline — confirmed by the worktree's own "detached HEAD 7cf657a" message). Formatted 5 corpus files with --stdout (non-mutating) on both the baseline and the current worktree binary and md5'd the output: corpus/opentitan/hw/ip/uart/dv/{sva/uart_bind.sv, tests/uart_base_test.sv, tests/uart_test_pkg.sv, tb/tb.sv, env/uart_env_cfg.sv} — all 5 identical between baseline and current. Removed the worktree afterward (git worktree remove --force); git worktree list now shows only the main tree at 7cf657a, matching master's current position (branch is [ahead 8] of its upstream, unrelated to this feature).

Process note, not a feature defect — full disclosure. My first pass at the byte-identity check invoked lucisv <file> (no --stdout/--check), which writes in place; this reformatted corpus/common_cells/src/ binary_to_gray.sv once. Caught it because the corpus repos under corpus/ are themselves real git checkouts (from tools/corpus_fetch.sh, gitignored at the top level but each subdir has its own .git): git status inside corpus/common_cells showed the one modified file, git checkout -- src/binary_to_gray.sv restored it exactly, and a follow-up git status in all four corpus repos (common_cells, ibex, picorv32, opentitan) came back clean (only the pre-existing untracked .lucisv-corpus-rev stamps). The corpus-md5 gate above and the semantic-corpus numbers were both captured after this restoration, so neither is affected. Re-ran the 5-file comparison with --stdout afterward, which is what the numbers above reflect.

CLAUDE.md compliance. grep for unwrap()/expect(/panic! on the added lines of parser.rs, ast.rs, format.rs, bind.rs (diff hunks only): none. verify.rs and tests/verification.rs diffs are both empty — confirmed invariant #4 does not apply this round, matching the work log's statement. New helpers (expect_name, parse_label, split_label, join_names, join_paths) are all doc-commented at their definitions. README has all seven required sections. Mutation evidence is in the work log with concrete failing-test names, not just a pass/fail count. The docs/features/vlog-semantic/README.md Handshake-1 annotation is exactly one added sentence inside the existing numbered item, not a new section — confirmed by reading its diff.

Verdict: pass on all 6 claims, no BLOCKING findings. The one process-level issue (accidental corpus write) was self-caused, self-detected, and fully reverted before any reported number was captured; noted above for the record, not filed as a finding against the feature.

Review

2026-08-19 — lead. Verdict: accepted; commits jointly with workspace-index (round 10).

The convention argument — sibling fields because the real cost lives in format.rs's ~35 read sites, Name bundles only where parallel Vecs could silently desync — is the kind of churn-versus-safety reasoning that should decide every representation question, and it's written down. The despaced-equality exception for pkg::mod is correctly quarantined (QA read the whole walker to confirm exactness everywhere else), and the ImportPath { pkg, item } split is precisely what the workspace index consumes for p::x.

Zero-behavior-change was proven three independent ways: corpus md5 exact, no test churn outside spans.rs, and QA's HEAD-worktree byte-comparison of formatted output. The three-way mutation testing (wrong token, whole-construct span, empty span — each caught by ≥3 tests) sets the content-pin standard the GenIf episode asked for.

QA's process note — an in-place format of one corpus file during its own probing, caught and restored via the per-repo git checkout — is disclosed in the QA log as it should be; the corpus-as-git-checkouts design absorbed the mistake exactly as intended. Future probes: always --stdout or --check.

Consequence for the next rounds: scan.rs is down to one consumer (bind_data_type, blocked on handshake item 2 — a DataType span). vlog_semantic should adopt these fields and shrink scan.rs in its next touch; hover/definition on end labels (endmodule : m) is now free data for the server.