Files
lucisv/crates/vlog_semantic/src/model.rs
T
lucioandClaude Fable 5 2734885f2b Covergroup bodies: coverpoints, bins, transitions and crosses are real code - 544 of 544 on opentitan, zero fallbacks
TODO section 21, round 2 of coverage_gaps C1, closing it. A covergroup
was a flat token scan into verbatim text; now ItemKind::Covergroup with
CoverItemKind::{Coverpoint, Cross, Option, Directive, Empty}, BinDecl
(wildcard, kind, array, spec: Values / Transitions / Default /
DefaultSequence / Select, with, iff) and SelectExpr for binsof ...
intersect ... && !binsof - behind the same Rewind fallback as
constraints (v0.27.0's scan re-run character for character on any
failure), no keywords reserved. The bin '(' ambiguity is settled by
position, the LRM's own rule, which replaced a lookahead scan and took
the fallback count to zero. Two guards in shared expression machinery -
an index cannot begin with *, -> or =; a bin's own with (...) filter is
not an array-method iterator argument - both attacked across the corpus
and the opentitan tree. Canonical layout, verify.rs untouched, thirteen
attack pairs. Every sampled expression binds to the class's properties;
cg_inst.cp resolves cross-file; FACTS_FORMAT 11 -> 12. The gap fuzzer
was built in from day one and its classification is asserted, not
claimed.

Opentitan: 544/544 structured, 87/87 DV covergroup files idempotent
with comment streams byte-identical, sweep and per-file diagnostics
identical. Corpus +1139 references, 1135 answered.

docs/features/covergroup-bodies/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 06:01:48 -07:00

355 lines
16 KiB
Rust

//! The tables `analyze` fills in: scopes, symbols and references.
use std::collections::HashMap;
use vlog_parser::span::TextRange;
/// Index of a [`Scope`] in [`Semantics::scopes`](crate::Semantics::scopes).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ScopeId(pub u32);
/// Index of a [`Symbol`] in [`Semantics::symbols`](crate::Semantics::symbols).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct SymbolId(pub u32);
/// Index of a [`Reference`] in
/// [`Semantics::references`](crate::Semantics::references). The workspace
/// index keys its overlay by this.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ReferenceId(pub u32);
/// What kind of declaration a [`Symbol`] came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SymbolKind {
Module,
/// An `interface … endinterface`. The parser models it as a
/// [`vlog_parser::ast::Module`] with a different keyword, and everything an
/// instantiation, a connection or a hierarchical name may do to a module it
/// may do to an interface — so this kind travels beside `Module` almost
/// everywhere ([`SymbolKind::is_instantiable`]). What it buys is the two
/// places the two really differ: an editor label that says "interface", and
/// an export rule that lets another file reach an interface's *signals*,
/// which is what a `virtual bus_if vif; vif.sig` needs and what a module
/// never grants. `program … endprogram` is still a `Module` — see
/// `docs/features/interface-semantics/README.md`.
Interface,
/// A `modport mp (...)` inside an interface (IEEE 1800 §25.5): a named view
/// of the interface's signals.
Modport,
/// A **named** `clocking cb @(...); … endclocking` block (IEEE 1800 §14.3).
/// An anonymous `default clocking @(...)` declares no name and so no
/// symbol.
Clocking,
Package,
/// A module port, from either header style.
Port,
/// A net declaration (`wire`, `tri`, ...).
Net,
/// A variable declaration (`logic`, `reg`, `int`, ...).
Var,
Param,
/// A `localparam` — a constant the module derives for itself, written
/// either in the body or inside the `#( … )` header after the keyword.
///
/// Parted from [`SymbolKind::Param`] on 2026-09-02 for one reason, and it
/// is a *correctness* one rather than a labelling one: a `localparam` in a
/// header is **not overridable**, so it must never be offered in a
/// `#(.` override list, and the only place that fact survives is the
/// keyword the source wrote. (QA found `prim_fifo_sync`'s header
/// `localparam int DepthW = $clog2(Depth)` offered as an override.)
/// Everything else a parameter can do a localparam can do too — it is read
/// hierarchically (`u_fifo.DepthW` is legal and resolves), it is exported
/// by the same units, it hovers and highlights the same way — so every
/// other site treats the two alike and says so out loud.
/// See `docs/features/member-completion/README.md`.
LocalParam,
Genvar,
Typedef,
/// A name introduced by an `enum` body, visible in the enclosing scope.
EnumVariant,
Function,
Task,
/// A function or task argument.
TfArg,
/// A module or gate instance.
Instance,
/// A named `begin`/`fork`/generate block.
Block,
/// A member of a `struct`/`union` body.
StructMember,
/// A `class` declaration.
Class,
/// A `constraint c { ... }` (IEEE 1800 §18.5) — a named member of a
/// class, and the one thing in a class body that is neither data nor
/// code. `constraint-bodies` gave it a symbol so that the block is
/// navigable at all: before it, the parsed name was discarded and a
/// rename of a `rand` property left every constraint that reads it
/// untouched.
Constraint,
/// A `covergroup g ... endgroup` (IEEE 1800 §19.3) — a named member of a
/// class, a module or a package, and the container `cg.cp` reaches
/// through. `covergroup-bodies` gave it a symbol for the same reason
/// `constraint-bodies` gave a constraint one: before it, the parsed name
/// was discarded and nothing inside bound.
Covergroup,
/// A labelled `cp : coverpoint expr` inside a covergroup. An
/// *unlabelled* coverpoint declares nothing, which is exactly what the
/// LRM says: there is no name to reach it by.
Coverpoint,
/// A labelled `cr : cross a, b` inside a covergroup.
Cross,
}
impl SymbolKind {
/// True for the kinds an *instantiation* may name: a `module` and an
/// `interface`. An interface is instantiated exactly as a module is
/// (`bus_if u_bus ();`), connected exactly as a module is, and shows up in
/// the design hierarchy and the code lens on exactly the same terms — so
/// every filter that used to spell `kind == Module` for "a thing you can
/// instantiate" asks this instead, and answers what it always did.
pub fn is_instantiable(self) -> bool {
matches!(self, SymbolKind::Module | SymbolKind::Interface)
}
}
/// A declaration: a name bound in one scope.
#[derive(Debug, Clone)]
pub struct Symbol {
pub name: String,
pub kind: SymbolKind,
/// Byte range of the declared name itself — what an editor highlights.
pub name_span: TextRange,
/// Byte range of the construct that owns the name (the whole `module`,
/// the whole declarator, the whole port declaration).
pub decl_span: TextRange,
/// Where the *complete* declaration is written, when that is not
/// `decl_span`: a non-ANSI port's header names it and a body `input
/// signed [31:0] data_in;` finishes it, so hover and go-to-definition
/// point here — the line that carries the direction, the type and the
/// width — while `name_span`/`decl_span` stay in the header. `None` for
/// every declaration that is complete where it is named.
pub detail_span: Option<TextRange>,
/// The declared type **as written**, for the declarations that have one:
/// `c1` for `c1 in_item`, `pkg::c1` for a qualified spelling,
/// `clk_rst_if` for `virtual clk_rst_if vif`. `None` for a built-in type
/// (`logic`, `bit`, `int` — a keyword names no declaration) and for every
/// declaration that has no type at all (a module, a block label, an
/// instance). It is a *name*, not a resolved type: what member access
/// (`handle.member`) needs is the spelling to look the type up with, and
/// resolving it is `resolve.rs`'s business, on the same lexical chain the
/// type reference itself takes. See
/// `docs/features/class-member-access/README.md`.
pub type_name: Option<String>,
/// The scope the name is bound in.
pub scope: ScopeId,
/// The scope this declaration opens, for the kinds that open one
/// (module, package, function, task, named block, struct body).
pub child_scope: Option<ScopeId>,
}
/// What a [`Reference`] turned out to name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Resolution {
/// Bound to a declaration in this file.
Resolved(SymbolId),
/// Nothing in this file binds it, but a named external unit could: a
/// package imported with `import p::*` / `import p::x`, a package written
/// as `p::x`, a module instantiated but declared in another file, or an
/// unqualified **type** name — an `interface`, a package-less `class` —
/// that only a file-scope declaration somewhere else can be. `paths` names
/// those units — a path containing `::` is a package path, a bare name is a
/// module, package or class name — in the order they are tried, the use's
/// own name last. The workspace index (TODO.md §6) is what finishes these.
ExternalCandidate { paths: Vec<String> },
/// A use inside a class that nothing lexical binds, where the class's
/// `extends` could: `base` is the base-class path as written
/// (`uvm_component`, `pkg::base`), and `paths` are the import paths the
/// lexical walk collected — plus the use's own name when it was written in
/// a type position — any of which could supply it. The single-file layer
/// never chases `base`; the workspace overlay now does, upward through
/// [`crate::WorkspaceIndex::base_of`] after its `paths` miss, without
/// displacing what this says — a base resolved *in this file* would have
/// been `Resolved` already. See `docs/features/class-semantics/README.md`,
/// `docs/features/overlay-promotion/README.md` and
/// `docs/features/class-member-access/README.md`.
InheritedCandidate { base: String, paths: Vec<String> },
/// Nothing in this file binds it and no external unit could: a member of a
/// package this file fully declares, a `.port` of a module it declares, a
/// `this.x`/`super.x` with no class or base to blame, or a plain
/// value-position identifier with no import in scope. An unqualified miss
/// in a **type** position is never this — the workspace's unit table could
/// hold it — so that one is an `ExternalCandidate` carrying its own name.
NotFound,
}
/// Where the `.name` after a head is looked up: a scope this file holds, or
/// the composed workspace path the index answers by.
///
/// This is the **prefix** of a member resolution, split out so that a caller
/// wanting the *list* of members (completion) and the caller wanting one of
/// them (hover, definition, references) walk the same steps —
/// [`Semantics::member_site`](crate::Semantics::member_site) is what
/// `resolve::member_of` itself runs before looking the tail up, and
/// [`Semantics::unit_site`](crate::Semantics::unit_site) is what
/// `resolve::unit_member` runs. A second answer to "where do this head's
/// members live" would eventually disagree with the first, which is the one
/// thing the member-resolution rounds forbid.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MemberSite {
/// A class, module, interface or `struct` body **this file declares**.
/// The members are the scope's own symbols, plus — for a class — those of
/// every scope [`Semantics::member_scopes`](crate::Semantics::member_scopes)
/// adds from the `extends` chain.
Scope(ScopeId),
/// A type this file does not declare, as the unit name plus any member
/// names already selected from it — `pkt_t`, `pkt_t::hdr` — in exactly the
/// spelling [`crate::WorkspaceIndex`]'s member lookup walks. The tail
/// resolution appends `::<name>` to it and hands the result to
/// `follow_one`; the *list* is
/// [`WorkspaceIndex::members_of_chain`](crate::WorkspaceIndex::members_of_chain).
Unit(String),
}
/// A *use* of a name: an expression identifier, a type name, an instantiated
/// module's name, a `.port` in a connection list, a package in an `import`.
#[derive(Debug, Clone)]
pub struct Reference {
pub name: String,
/// Byte range of the identifier as written.
pub name_span: TextRange,
/// The scope the use is written in.
pub scope: ScopeId,
pub resolution: Resolution,
}
impl Reference {
/// The symbol this use names, if it is declared in this file.
pub fn resolved(&self) -> Option<SymbolId> {
match self.resolution {
Resolution::Resolved(id) => Some(id),
_ => None,
}
}
/// True when only a workspace-wide index can finish this reference.
pub fn is_external_candidate(&self) -> bool {
matches!(self.resolution, Resolution::ExternalCandidate { .. })
}
/// True when the name could only come through the class's `extends`.
pub fn is_inherited_candidate(&self) -> bool {
matches!(self.resolution, Resolution::InheritedCandidate { .. })
}
}
/// What construct a [`Scope`] came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScopeKind {
File,
/// A `module`, an `interface` or a `program` body. One kind for all three
/// because a scope's kind governs *lookup rules*, and those are identical:
/// names bind in declaration order, imports are consulted, the enclosing
/// scope is the file. What differs between a module and an interface is
/// which of its members another file may reach, and that is a property of
/// the declaration ([`SymbolKind::Interface`]), not of the scope.
Module,
Package,
Function,
Task,
/// A `begin`/`end`, `fork`/`join`, `for` or `foreach` body.
Block,
/// A generate region, a generate block, or a `for` generate's header.
Generate,
/// A `struct`/`union` body. Never searched by name lookup — members are
/// reached through `x.field`, which this crate does not resolve.
Struct,
/// A `class` body.
Class,
/// A `constraint c { ... }` body. Its lookup rules are a block's — the
/// enclosing class scope is the parent, so every property is in scope
/// with `this.` implicit — and it declares nothing but `foreach` loop
/// variables. It is its own kind so that "am I inside a constraint" is
/// answerable without walking back to the owning symbol.
Constraint,
/// A `covergroup g ... endgroup` body. Its parent is the enclosing class
/// (or module, or package) scope, so every sampled expression reaches a
/// property with `this.` implicit; it declares the covergroup's formal
/// arguments, its `sample` method and that method's arguments, and one
/// symbol per *labelled* coverpoint and cross.
Covergroup,
}
/// One `import p::x;` / `import p::*;` recorded in the scope that wrote it.
#[derive(Debug, Clone)]
pub struct Import {
/// The package name written before `::`.
pub package: String,
/// The imported name; `None` for a `::*` wildcard.
pub item: Option<String>,
/// The package's scope when the package is declared in this file.
pub scope: Option<ScopeId>,
/// Byte range of the package name as written.
pub name_span: TextRange,
}
impl Import {
/// The import path as written, e.g. `pkg::*`.
pub fn path(&self) -> String {
match &self.item {
Some(item) => format!("{}::{}", self.package, item),
None => format!("{}::*", self.package),
}
}
/// True when this import could supply `name`.
pub fn supplies(&self, name: &str) -> bool {
match &self.item {
Some(item) => item == name,
None => true,
}
}
}
/// A lexical scope: a set of names plus a link to the scope enclosing it.
#[derive(Debug, Clone)]
pub struct Scope {
pub kind: ScopeKind,
pub parent: Option<ScopeId>,
/// The symbol whose declaration opened this scope; `None` for the file
/// scope and for unnamed blocks.
pub owner: Option<SymbolId>,
/// Byte range of the construct the scope covers.
pub span: TextRange,
/// Symbols bound here, in declaration order.
pub symbols: Vec<SymbolId>,
pub children: Vec<ScopeId>,
pub imports: Vec<Import>,
/// For a [`ScopeKind::Class`] scope: the `extends` path as written, when
/// the class has one. What an inheritance miss reports as its `base`.
pub(crate) extends: Option<String>,
/// Name → symbol, first declaration wins (see the README's shadowing
/// rules). Kept separate from `symbols` so a redeclaration is still
/// visible in the outline.
pub(crate) names: HashMap<String, SymbolId>,
}
impl Scope {
/// The symbol this scope binds `name` to, ignoring enclosing scopes.
pub fn lookup_local(&self, name: &str) -> Option<SymbolId> {
self.names.get(name).copied()
}
/// The `extends` path this class scope was written with, as written.
/// `None` for every other scope, and for a class that extends nothing.
pub fn extends(&self) -> Option<&str> {
self.extends.as_deref()
}
}
/// One node of the outline tree returned by
/// [`Semantics::document_symbols`](crate::Semantics::document_symbols).
#[derive(Debug, Clone)]
pub struct DocumentSymbol {
pub symbol: SymbolId,
pub children: Vec<DocumentSymbol>,
}