Files
lucioandClaude Fable 5.1 4d59e80568
ci / checks (push) Successful in 1m3s
ci / corpus (push) Successful in 33s
Type-name spans on the AST; vlog_semantic/src/scan.rs retired
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

793 lines
46 KiB
Markdown

# 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 reference_id_at(&self, offset: u32) -> Option<ReferenceId>;
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, detail_span,
type_name: Option<String>, // class-member-access
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> },
InheritedCandidate { base: String, paths: Vec<String> }, // class-semantics
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.** 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.
`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. A miss on a name
written in a **type** position leaves carrying **the use's own name as its
last path**, after any import paths collected on the way out: an unqualified
type nothing here binds is how a file-scope `interface`, a package-less
`class` or a cross-file `typedef` is written, and the workspace's unit table
is the only layer that can say (`docs/features/overlay-promotion/README.md`,
2026-08-26). A miss on an identifier in a **value** position gets no such
path — nothing about a bare expression name claims a file-scope declaration,
and a mere collision with a workspace unit name is not a reason to rewrite
another file. Inside a class with an `extends` either miss is an
`InheritedCandidate` (carrying the base, and the paths it collected);
everywhere else an `ExternalCandidate`, or `NotFound` when it has no path at
all.
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.
**Amended 2026-09-01 by struct-members**: so do an **anonymous** enum's
(`enum {A, B} x;`) and those of an enum standing as a struct field's type,
which declared nothing at all before — one binder function now serves all
three spellings.
4. **Struct members land in a `Struct` scope of their own**, hung under the
typedef. Nothing ever *looks up* into it, so members cannot be reached as
bare names — which is correct — but they are still symbols, so the outline
can show them.
**Amended 2026-09-01 by struct-members** (`docs/features/struct-members/
README.md`), which delivers §2.9-13 and strikes the paragraph that used to
stand here (a `Struct` scope was "deliberately not one of the scopes member
access reaches into", pending the anonymous forms). A member access **does**
reach into one now, and consistently across every spelling: the scope hangs
off the `typedef` that names the body, off the *declarator* of an anonymous
`struct {…} s;`, or off an **inline nested** field, and `resolve.rs` accepts
any symbol whose child scope is a `Struct` scope. Fields carry their own
declared type, so `s.hdr.addr` hops through one. Bare-name lookup still
never enters a struct scope, and no pending use is ever recorded inside one
— a field's type, dimensions and initializer are bound in the scope the body
is *written* in.
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.) A
qualified miss is **never** given the bare name rule 1 gives an unqualified
one: `x` names something inside `p`, and sweeping the unit table for a bare
`x` would discard the qualifier and answer a different question. The same
holds for the class spelling — `c::x` where `c` is an in-file class with an
`extends` is an `InheritedCandidate` with *no* paths at all.
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.
**Amended 2026-09-01 by class-member-access** (`docs/features/
class-member-access/README.md`), in two rounds. **Round 1**: a
**one-deep** `head.member` whose head is a plain identifier this file
declares *with a declared type* — `c1 in_item; ... in_item.user_id` —
records the tail as well, resolved in that type's scope and up its
`extends` chain. **Round 2**: a whole chain of identifiers is walked
(`a.b.c.d`), each link looked up in the declared type of the link before
it, and a **module instance is a typed head** — its declared type is the
module it instantiates — so `u.port`, `u.internal_sig` and
`tb.dut_i.u_core.sig` resolve too; a `typedef` that names a type
(`typedef c1 my_t;`) is followed to it. A chain that leaves this file
arrives at the workspace as one composed path (`item_t::hdr::addr`), which
the index walks member by member through each declaration's recorded type.
What is still head-only: an indexed head (`a[i].b`), a call (`f().b`), a
cast, an instance *array* (`bank[0].x`), and anything past one member of
`this`/`super` (`this.a.b` records `a` and stops). A tail this crate cannot
answer is recorded as **no reference at all**, not as a `NotFound` — the
two claims are different and only the first is honest here — and **a link
that cannot be resolved honestly stops the chain**, so nothing is recorded
for it or for anything after it. That covers: a type name **this file
declares as something with no members** (an enum `typedef`, an alias of a
built-in, a parameter, a shadowing variable), a member absent from a class
or struct this file declares whole, and — across files — a hop through a
type name the workspace declares more than once. This file has answered
what the type is, and asking the index for a same-named class elsewhere
would answer a question the source never asked (QA finding 1 of round 1).
Across files a module still exports only its **ports and parameters**, so
`u.internal_sig` answers only when the module is in the same file (round
2's ruling, with the measurement, in the feature README).
**Amended 2026-09-01 by struct-members**: a `struct`/`union` typedef is no
longer one of the "no members" answers — see rule 4. `bus_t s; s.addr`
resolves in-file, `pkg::bus_t s; s.addr` across files, and
`reg2hw.ctrl.tx.q` walks four links through two levels of inline nested
aggregate. The **rule** is untouched, and is what still refuses a stranger:
a file that declares `bus_t` as a struct answers `s.field` itself, and an
unrelated class `bus_t` elsewhere is never asked.
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 bare-name lookup never
enters — and which, since 2026-09-01, a `.` member access does (rule 4).
### 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.**~~ **Changed
2026-08-24 by refactor-rename (lead-authorized):** an end label
(`endmodule`/`endinterface`/`endpackage`/`endfunction`/`endtask`/`endclass`
`: name`, and `end : label` / `join : label` on a named block or generate
block) is recorded as a *use* of the declaration it closes, through the new
`Target::Declaration(SymbolId)` — bound directly to that symbol, never
looked up, so a label can never attach to a same-named declaration
elsewhere. A label that does not spell the declared name, or whose
declaration was a redeclaration that bound no symbol of its own, still
records nothing. `endclocking` is unaffected: a clocking block is opaque to
this crate and declares no symbol. The parser already carried
`end_label_span` on every one of these nodes, so `vlog_parser` needed no
change.
- **`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. *(Since closed for classes:
`docs/features/class-semantics/README.md` — `ScopeKind::Class`, member
binding, `extends`/`this`/`super`, `Resolution::InheritedCandidate`.
Constraints and covergroups stay opaque verbatim leaves.)*
## 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.~~ 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.
- 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
**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** (`lucisv_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. An `InheritedCandidate` carries paths too
and may be *answered* by the index without being rewritten — its `base` is
this crate's answer and stays (`docs/features/overlay-promotion/README.md`).
**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. **Delivered 2026-08-19 by `name-spans`** — every
declaration listed here now carries its range; see
`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()`.
## 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 | inherited 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 %** |
**Re-measured 2026-08-26** (`overlay-promotion`), same command, same corpus.
The table above had gone stale by several rounds — class support and the
parser rounds since moved both the reference count and the clean-file
population — so the "before" row is a fresh measurement of `3bc61f9`, not a
quote:
| population | files | symbols | references | resolved in-file | external candidates | inherited candidates | unresolved |
|---|---:|---:|---:|---:|---:|---:|---:|
| every file, before | 860 | 26 812 | 94 685 | 73.2 % | 17.1 % (16 152) | 8.3 % (7 841) | 1.5 % (1 418) |
| every file, after | 860 | 26 812 | 94 685 | 73.2 % | **17.2 % (16 314)** | 8.3 % (7 841) | **1.33 % (1 256)** |
| clean files, before | 853 | 26 752 | 94 384 | 73.3 % | 17.1 % (16 133) | 8.3 % (7 841) | 1.3 % (1 224) |
| clean files, after | 853 | 26 752 | 94 384 | 73.3 % | **17.3 % (16 286)** | 8.3 % (7 841) | **1.13 % (1 071)** |
The promotion fires on **type positions only** — a name written where a type
goes, which is every use that reaches `bind_data_type`. An identifier in a
value position keeps the spelling it always had. The round first promoted both
and had to give the value half back: an unbound expression identifier that
happens to match a workspace unit name is a coincidence, and `rename` acted on
it across files (`docs/features/overlay-promotion/README.md`, QA finding 1 and
the fix round under it). So 162 references over all files (153 on clean files)
moved `NotFound` → `ExternalCandidate`, not the 1 418 the unrestricted version
moved. **`InheritedCandidate` is 7 841 in every one of the three states** — the
promotion never reclassified a reference, it only lengthened `paths`.
No panics, and every name span built across the corpus slices back to exactly
the name it claims (0 unplaced), before and after.
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.
- **The unresolved bucket shrank by a re-spelling, not a discovery.** The
references that left it are the ones written in a *type* position with
nothing in the file or its imports to bind them: a cross-file `interface`,
a package-less `class`, a file-scope `typedef`. Those really could be held by
the workspace, so they now say so. Moving a reference between buckets answers
nothing by itself — what the workspace layer actually gained is **418
references on clean files that now have somewhere to jump, and none that lost
one** (`docs/features/workspace-index/README.md` reports the composite).
- **What is left under `NotFound` is what belongs there**: names a `` `define``
would have produced (`XLEN`, `ENABLE_IRQ`), a genvar used outside its loop,
hierarchical/member tails reached through a path this crate stops at, members
of a locally-declared package, and `this.x` with no base. These are value
positions, and a value position is never swept through the unit table — a
one-letter `i` must not find a `module i` in another file, least of all when
`rename` is the caller.
- Only 7 of 860 corpus files still fail to parse cleanly, which is why the two
populations now barely differ.
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] 2026-08-27: declaration/reference cursor queries use start-sorted
position tables and binary search rather than scanning every symbol/use
- [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
- [x] 2026-08-26 (`overlay-promotion`): an unqualified **type**-position miss
carries the bare name to the workspace layer, in both spellings
(`Target::Type`); a value-position miss keeps the spelling it had
- [ ] Deferred to the workspace index: resolving `ExternalCandidate`s
- [ ] Deferred: interfaces/modports — the parser does not accept them.
Classes delivered 2026-08-19 by `class-semantics`
- [ ] Deferred: `Symbol` type information (needed for hover text richer than
"port, declared at line N")
## 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;
their public answers and half-open span rules are unchanged.
**2026-08-26 — overlay-promotion dev agent (lead-authorized, cross-module).**
`bind.rs` gains `Target::Type`, emitted by `bind_data_type`'s unqualified arm
and nowhere else, so pass two can tell a type window from an expression.
`resolve.rs::lexical` pushes the use's own name onto the candidate paths for
that target only, so a type-position miss reaches the workspace layer in both
its spellings while a value-position miss stays exactly what it was;
`workspace.rs::resolve_external` answers an `InheritedCandidate` from those
paths when one lands. Strictly additive to what a reference *says*: no target,
span, symbol or variant was removed, and `InheritedCandidate.base` is
untouched, which is why no consumer needed a change. Full rationale, the
consumer audit, the QA-found value-position regression and the before/after
corpus measurement: `docs/features/overlay-promotion/README.md`.
**2026-08-24 — refactor-rename dev agent (lead-authorized, cross-module).**
End labels are now references. `bind.rs` gains `Target::Declaration(SymbolId)`
and `Binder::use_end_label`, called from the module, package, class, function,
task, generate-block and statement-block/fork-join arms; `resolve.rs` answers
it with `Resolution::Resolved(id)` directly. Strictly additive: no existing
target, span or symbol changed, and no `vlog_parser` change was needed
(`end_label_span` was already on every node). The reason is
`docs/features/refactor-rename/README.md`: a rename that leaves
`endmodule : old_name` behind produces non-compiling SystemVerilog, and
fixing it by text matching would have broken the "every edit comes from a
resolved reference" rule. Three tests added to `tests/semantics.rs`
(all six labelled constructs; a label never attaching to a same-named
declaration elsewhere; a mismatched label recording nothing).
**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.
**2026-08-28 — `WorkspaceIndex::files_spelling`, lead-authorized, additive.**
One new query, requested by refactor-rename's performance round after QA found
a lost refusal in it; the second authorized cross-module change that feature
has made (M2's `Target::Declaration` was the first).
```rust
pub fn files_spelling(&self, name: &str) -> impl Iterator<Item = FileId> + '_
```
Every file holding an **external reference fact** spelling `name`, whether or
not it resolved. Nothing was renamed, removed, re-spanned or re-ordered; no
new state, no new field, and **`FACTS_FORMAT` is untouched** — it reads the
`FileFacts::references` records the index already keeps, which is why it can
answer at all. A linear walk over those records in `FileId` order.
Why it belongs here rather than in the caller: `reference_sites` is keyed by
`DefinitionKey`, so a use that resolved to **nothing** is in no posting — the
right shape for "who refers to this declaration", the wrong one for "which
files would notice if this name started meaning something". The second
question is what a rename must ask about the name it renames *to*, and the
records that answer it are `pub(crate)`. The alternative was for the server to
re-derive it by reading and analyzing every file, which is the workspace read
that round exists to remove.
The property callers now depend on, stated so it moves under supervision:
`facts_from_analysis` records a `ReferenceFact::External` for every
`ExternalCandidate`/`InheritedCandidate` with a non-empty path list,
*including the ones the index cannot resolve*. `merge_references` then drops
the unresolvable ones when building postings — that drop is what
`files_spelling` exists to see past. If the recording rule narrows, say so in
`docs/features/refactor-rename/README.md`'s Handshakes, whose rung 6 rests on
it. Tested by `tests/workspace.rs::files_spelling_finds_the_uses_no_posting_can_be_keyed_by`.
## 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`/`lucisv` 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/lucisv`
(`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 lucisv
deep-nesting tests) — timing overlap with the parallel-files QA's
deliberate stack-sabotage check, verified restored before the joint
commit.
---
## Amendment — 2026-09-02, `constraint-bodies` (TODO.md §20)
Two new kinds and one new target:
- `SymbolKind::Constraint` — a `constraint c { ... }` name. It is exported
by a class on the same terms a method is, and `FACTS_FORMAT` is bumped
**10 → 11** for it (the brief said 9 → 10; member-completion's
`LocalParam` had already taken 10).
- `ScopeKind::Constraint` — a constraint body. Its lookup rules are a
block's; it is its own kind so "am I inside a constraint" is answerable
without walking back to the owning symbol. Nothing outside `model.rs`
matches `ScopeKind` exhaustively, so the variant cost no arms.
- `Target::InlineConstraint { head, mids }` — an unqualified name in an
`obj.randomize() with { ... }` block. It resolves as a member of `obj`
first (IEEE 1800 §18.7), through the same `member_of` chase
`Target::MemberOf` uses, and falls back to the scope the block is written
in **only** when the object's own class settles the miss. A candidate for
another file is left alone: it may still be the member, and preferring
the writing scope over it would be the wrong answer this crate refuses
to give.
Corpus effect (860 files, both layers): references 99,553 → 101,199, of
which 1,646 are new names inside constraint bodies that bound nothing at
all before. See `docs/features/constraint-bodies/README.md`.
---
## Amendment — 2026-09-02, `covergroup-bodies` (TODO.md §21)
Three new symbol kinds and one new scope kind:
- `SymbolKind::Covergroup` — a `covergroup g ... endgroup` name, declared
wherever the covergroup is written. A package or class exports it on the
same terms it exports a class; `member_scope` opens it for a `.`, and
`collect_members` recurses into it, so `cg_inst.cp` reaches a coverpoint
declared in another file.
- `SymbolKind::Coverpoint` / `SymbolKind::Cross` — a **labelled** `cp :
coverpoint e` and `cr : cross a, b`. Both are exported by the covergroup
that declares them. An unlabelled one declares nothing.
- `ScopeKind::Covergroup` — the body. Its lookup rules are a block's, its
parent is the scope the covergroup is written in, and it declares the
covergroup's formals, its `sample` method and that method's arguments
alongside the coverpoint and cross names.
`FACTS_FORMAT` is bumped **11 → 12** for the three kinds. Nothing outside
`model.rs` matches `ScopeKind` exhaustively, so that variant cost no arms.
One implicit declaration: `item` inside a bin's `with ( ... )` filter
(IEEE 1800 §19.5.1.1) is bound in a `Block` scope of its own, so a class
property called `item` cannot capture it. It is never written as a
declaration, so the declaration points at the **first use of it inside the
filter** — every name this crate records must slice back to itself, which the
corpus test's "0 names unplaced" assertion enforces.
Corpus effect (860 files, both layers): references 101,199 → 102,338, of which
1,139 are new names inside covergroup bodies that bound nothing at all before,
and 1,135 of those are answered. See
`docs/features/covergroup-bodies/README.md`.