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]>
46 KiB
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
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
analyzetakessrcas well as the tree. Originally because most declarations kept their name as a plainStringinside a construct-wide span, so the name's range — the thing an editor highlights — was not recoverable from the tree at all;scan.rsfound 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) putname_spanon every declaring node,type-name-spans(2026-09-05, TODO §47) putDataType::name_span()/segments()andStmtKind::Disable's span on the last two, andscan.rsis deleted.srcstays, in a different role:Binder::exact_or_emptychecks 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 . mpwritten 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 assertssrc[name_span] == namefor 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: Resolutioninstead ofresolved: Option<SymbolId>. The task asked for both anOption<SymbolId>and anExternalCandidatestate carrying the import path; one enum says that once.Reference::resolved() -> Option<SymbolId>is kept as the accessor the sketch names, plusis_external_candidate().Symbol.child_scopewas added: the outline needs "what does this declaration contain", andp::xresolution needs "which scope is packagep".references_ofdoes not include the declaration. It returns uses only; the declaration issymbol.name_span, and an LSP honoringincludeDeclaration: trueappends 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.
- 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-lessclassor a cross-filetypedefis 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 anextendseither miss is anInheritedCandidate(carrying the base, and the paths it collected); everywhere else anExternalCandidate, orNotFoundwhen it has no path at all. - Ports and parameters are module-scope names, so a module body sees
them; a
function/task/block scope sees them through its parents. - 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 bothstate_eandIDLEin 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. - Struct members land in a
Structscope 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 (aStructscope 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 thetypedefthat names the body, off the declarator of an anonymousstruct {…} s;, or off an inline nested field, andresolve.rsaccepts any symbol whose child scope is aStructscope. Fields carry their own declared type, sos.hdr.addrhops 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. - Imports.
import p::*;/import p::x;is recorded as anImporton the scope that wrote it (module header imports land on the module scope). Resolution consults it only whenpis a package declared in this file; otherwise the use becomesExternalCandidate { paths: ["p::*"] }— every import in the chain that could supply the name, in scope order, for the workspace index to try. An explicitimport p::xis offered only for the namex. - Package-scoped names.
p::xrecords two references: the headp(target: a file-scope package) and the tailx(looked up inp's scope only, never in the lexical chain). Ifpis not in this file, both become external candidates and the tail carries the full pathp::x. Ifpis in this file but has no memberx, the tail isResolution::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:xnames something insidep, and sweeping the unit table for a barexwould discard the qualifier and answer a different question. The same holds for the class spelling —c::xwherecis an in-file class with anextendsis anInheritedCandidatewith no paths at all. - Instantiations. The module name is a reference to a file-scope module,
else an external candidate naming the module. A named connection's
.portresolves 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. - Hierarchical names.
a.b.cresolvesaand stops: no reference is recorded for.bor.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-deephead.memberwhose 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 itsextendschain. 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 — sou.port,u.internal_sigandtb.dut_i.u_core.sigresolve too; atypedefthat 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 ofthis/super(this.a.brecordsaand stops). A tail this crate cannot answer is recorded as no reference at all, not as aNotFound— 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 enumtypedef, 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, sou.internal_siganswers 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: astruct/uniontypedef is no longer one of the "no members" answers — see rule 4.bus_t s; s.addrresolves in-file,pkg::bus_t s; s.addracross files, andreg2hw.ctrl.tx.qwalks four links through two levels of inline nested aggregate. The rule is untouched, and is what still refuses a stranger: a file that declaresbus_tas a struct answerss.fielditself, and an unrelated classbus_telsewhere is never asked. - 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. - 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 oneasymbol (the header port) and one use (the body declaration) — and it keepsreferences_ofhonest everywhere else. - 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
forgenerate opens a scope for its header, sofor (genvar i = 0; ...)does not leakiinto the module; the body block nests inside it.genvar i;written at module scope binds there instead, as the LRM says. - A
for/foreachstatement opens a scope for the same reason (for (int i = 0; ...)). - A
struct/unionbody opens aStructscope 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/forkopens 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::xover 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;insidefunction fresolves to the function symbol, which is where go-to-definition should land anyway. Changed 2026-08-24 by refactor-rename (lead-authorized): an end label (endmodule : mand other end labels record nothing.endmodule/endinterface/endpackage/endfunction/endtask/endclass: name, andend : label/join : labelon a named block or generate block) is recorded as a use of the declaration it closes, through the newTarget::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.endclockingis unaffected: a clocking block is opaque to this crate and declares no symbol. The parser already carriedend_label_spanon every one of these nodes, sovlog_parserneeded no change.defparampaths,disabletargets and event names are resolved with the ordinary lexical rule (disable blkfinds the named block).- Ordering inside a scope is not modeled:
symbol_atand 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
`includefollowing, no workspace scan. External names are reported, never resolved. - No macro expansion.
`NAMEand`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
srcpassed toanalyzeis 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 (Retired 2026-09-05 bymodule 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.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: aMember/Scopetail, a classextendshead and tail, an instance module name, an end label, the::/.segments of a type name, and adisabletarget. 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::SourceFileand the whole node tree, includingItemKind::Error/StmtKind::Errorfromparse_source_tolerant— treated as opaque leaves.span::TextRangeon 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):
analyzenever panics and never fails, on any input, tolerant tree or not.Symbol.name_span/Reference.name_spanare exact byte ranges of the name as written, or empty when the source does not spell the name literally. Empty ranges never matchcontains, so a query never returns one.- Every
ReferencewhoseResolutionisExternalCandidatecarries the workspace-level paths that could finish it; the workspace index may rewrite those references and nothing else. AnInheritedCandidatecarries paths too and may be answered by the index without being rewritten — itsbaseis 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):
name_span: TextRangeon the nodes whose name is a bareString: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 incrates/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 byname-spans— every declaration listed here now carries its range; seedocs/features/name-spans/README.md.- A span for
DataType(and forExprKind::Cast::ty), so a type reference does not need a window computed from its neighbours' spans. Delivered 2026-09-05 bytype-name-spans(TODO §47) —DataTypecarriesname_span()andsegments(),StmtKind::Disablecarries its target's span,bind_data_typelost itswindowparameter, andcrates/vlog_semantic/src/scan.rsis deleted; seedocs/features/type-name-spans/README.md. - Nice to have, much smaller: the byte range of
Member/Scopetails, which is today derived asspan.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-lessclass, a file-scopetypedef. 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.mdreports the composite). - What is left under
NotFoundis what belongs there: names a`definewould 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, andthis.xwith no base. These are value positions, and a value position is never swept through the unit table — a one-letterimust not find amodule iin another file, least of all whenrenameis 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
- New crate
crates/vlog_semantic, workspace member, no dependency beyondvlog_parser+ std - Scope tree with parent links (file / module / package / function / task / block / generate / struct)
- Symbols for all 15 kinds, with
name_span,decl_span,scope,child_scope - References for expression identifiers, type names, hierarchical heads,
instantiated module names,
.portconnections, package heads and tails, import paths - Two-pass bind-then-resolve (forward references)
- Imports: in-file packages resolved, others kept as
ExternalCandidatewith their paths - Queries:
symbol_at,reference_at,definition_of,references_of,document_symbols - 2026-08-27: declaration/reference cursor queries use start-sorted position tables and binary search rather than scanning every symbol/use
Errornodes are opaque; tolerant trees analyze without panicking- Tests: 19 behavior tests + 6 scanner unit tests + corpus smoke test
- TODO.md §6
vlog_semanticcheckbox - 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
ExternalCandidates - Deferred: interfaces/modports — the parser does not accept them.
Classes delivered 2026-08-19 by
class-semantics - Deferred:
Symboltype 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), notanalyze(file). Discovered while mapping the AST that onlyDeclarator,EnumMember,Instance,NonAnsiPortand the expression nodes place their name at a span I can compute; everything else keeps the name as aStringinside 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
Resolutionenum instead ofOption<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 twoasymbols 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
fieldresolve to a struct member, which is wrong. - The scanner skips a backtick plus its identifier as one token, so
`WIDTHnever answers a search forWIDTH; anduse_namedrops 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).
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()orpanic!anywhere insrc/*.rs.cargo fmt -p vlog_semantic -- --check: clean.cargo tree -p vlog_semantic: exactlyvlog_semantic -> vlog_parser, no other dependency. Confirms "no deps beyond vlog_parser + std."- Root
Cargo.tomldiff: themembersline gainsvlog_semantic, as claimed. (The diff also carries an unrelated[workspace.dependencies] rayon = "=1.12.0"hunk — that belongs to the concurrently-workedparallel-files/lucisvfeature, 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 incrates/lucisv(a_deeply_nested_file_formats_on_a_worker_thread,deeply_nested_file_does_not_kill_the_batch) — outside my gate (-p vlog_semanticis green) and inside the area another QA agent owns concurrently. Flagging only so "workspace green" isn't taken at face value right now; not avlog_semanticfinding.SymbolKindhas exactly 15 variants,ScopeKindexactly 8, matching the claim (counted inmodel.rs).- TODO.md §6's
vlog_semanticline 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 realmodule foo, not the comment); a port name that is a whole-word prefix of a sibling port (wvsww—NameScannercompares whole tokens, not substrings, so this class of bug is structurally excluded, not just untriggered here); agenvar ideclared amidii/i_delaylookalikes 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 whosename_spansits 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'sname_spanare distinct, non-overlapping ranges. - resolution (claim 3): three-deep shadowing (module net / function arg /
block var all named
x) —references_ofon each binding contains only its own use, verified for all three; an enum variant used textually before itstypedef enum— resolves (two-pass forward reference, as designed);import p::*where packagepis declared below the import in the same file — resolves (two-pass);importof 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::xwherepis an in-file package butxis not a member of it — resolves toResolution::NotFound, notExternalCandidate. 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 "pnot in this file" case. Filed as a documentation gap, not a bug (see Findings below); a named connection.clk(clk)— confirmed the.clktoken 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 nestedif-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 orphanedendmodulewith no matchingmodule, an unterminated string, garbage tokens mid-body, mismatchedbegin/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-emptyname_span/Reference.name_spanproduced still slices back to exactly the name it claims, even on these malformed trees. - queries (claim 5):
definition_of/symbol_at/reference_atcalled 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:pexternal (both refs becomeExternalCandidate), or implicitlypin-file andxfound. It doesn't say what happens whenpis in-file butxis not one of its members. Actual (and, on inspection, correct) behavior perresolve.rs'sTarget::PackageMemberarm: the tail resolves toResolution::NotFound. Recommend adding one sentence to rule 6. Repro:b6_package_member_missing_from_an_in_file_packagein the now-deleted scratch suite —package p; localparam int K = 1; endpackage module m; assign w = p::MISSING; wire w; endmodules.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:
- 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.
Resolutionas 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.scan.rsis 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. Thename_span-in-parser handshake is hereby approved for the next parser-touching round.- 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— aconstraint c { ... }name. It is exported by a class on the same terms a method is, andFACTS_FORMATis bumped 10 → 11 for it (the brief said 9 → 10; member-completion'sLocalParamhad 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 outsidemodel.rsmatchesScopeKindexhaustively, so the variant cost no arms.Target::InlineConstraint { head, mids }— an unqualified name in anobj.randomize() with { ... }block. It resolves as a member ofobjfirst (IEEE 1800 §18.7), through the samemember_ofchaseTarget::MemberOfuses, 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— acovergroup g ... endgroupname, declared wherever the covergroup is written. A package or class exports it on the same terms it exports a class;member_scopeopens it for a., andcollect_membersrecurses into it, socg_inst.cpreaches a coverpoint declared in another file.SymbolKind::Coverpoint/SymbolKind::Cross— a labelledcp : coverpoint eandcr : 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, itssamplemethod 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.