Files
lucisv/crates/vlog_semantic/src/bind/expr.rs
T
lucioandClaude Opus 5.5 9dc567c72a
ci / checks (push) Successful in 1m42s
ci / corpus (push) Successful in 32s
TODO §65.4: a hierarchical path rooted at a top-level module resolves through the workspace (conservative)
`tb.dut.g_sw[0].buf_q` written in a file that does not declare `tb` now
resolves like an instance path: the binder marks a dotted path's head
(Target::PathHead), resolve/root.rs answers a plain lexical miss with a
hierarchical external candidate, head_site roots the spine there, and
fold_path walks it — every hop a module/interface surface. find_references,
LSP references and rename see every segment; $root.tb works; a local `tb`
shadows. FACTS_FORMAT 22.

Rooted only when the root is provable (owner's ruling: conservative): not
when the head has an import candidate (so `import uvm_pkg::*` with uvm_pkg
outside the project stays warned — opentitan's DV force paths behave as
before), not from inside a class, not beside a macro that stands where a
declaration could (item, statement, port list), not when the root name is
also a package or ambiguous. The LSP rename set adds the files of the
path's root and middle hops (sources.rs, WorkspaceIndex::path_units_to).
An unresolved path is warned once.

QA (Opus) x2: F1-F4 and R1 silent-wrong-rename shapes fixed with tests;
QA's attack cases 1-6 each warned or correctly renamed; lucisv check hw
byte-identical to master. Completion after `tb.` deferred (TODO §65.8).
tools/gates.sh: PASS, 15 steps, 5 180 tests, corpus 814/820.
docs/features/top-rooted-paths.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 15:34:45 -07:00

288 lines
13 KiB
Rust

//! Expressions: the `ExprKind` dispatch and everything it records — a bare
//! identifier as a lexical use, a member tail against the spine before it, a
//! `p::x` against its unit, a cast's type as a type — plus dimensions, which
//! are expressions wherever they are written.
use vlog_parser::ast::*;
use vlog_parser::span::TextRange;
use vlog_parser::token::is_keyword;
use crate::model::ScopeId;
use super::{Binder, Target};
impl<'a> Binder<'a> {
pub(super) fn bind_opt_expr(&mut self, e: Option<&Expr>, scope: ScopeId) {
if let Some(e) = e {
self.bind_expr(e, scope);
}
}
pub(super) fn bind_dims(&mut self, dims: &[Dim], scope: ScopeId) {
for d in dims {
match &d.kind {
DimKind::Range { a, b } => {
self.bind_expr(a, scope);
self.bind_opt_expr(b.as_ref(), scope);
}
// `[]` and `[*]` hold no expressions — nothing to bind.
DimKind::Dynamic | DimKind::Wildcard => {}
}
}
}
pub(super) fn bind_expr(&mut self, e: &Expr, scope: ScopeId) {
match &e.kind {
ExprKind::Ident(name) => self.use_name(scope, name, e.span, Target::Lexical),
// `Verbatim` is a region whose value depends on a `` `ifdef ``
// this crate never evaluates: opaque bytes record nothing. Nor
// does `Error`, the text a tolerant parse could not read as a
// statement header's condition — the same call `bind/item.rs`
// makes for an `ItemKind::Error`.
ExprKind::Number(_)
| ExprKind::Str(_)
| ExprKind::Empty(_)
| ExprKind::Verbatim(_)
| ExprKind::Error(_) => {}
ExprKind::Unary { expr, .. } | ExprKind::Postfix { expr, .. } => {
self.bind_expr(expr, scope)
}
ExprKind::Binary { lhs, rhs, .. } => {
self.bind_expr(lhs, scope);
self.bind_expr(rhs, scope);
}
ExprKind::Ternary { cond, then, els, .. } => {
self.bind_expr(cond, scope);
self.bind_expr(then, scope);
self.bind_expr(els, scope);
}
ExprKind::Call { callee, args, .. } => {
self.bind_expr(callee, scope);
for a in args {
self.bind_expr(&a.expr, scope);
}
}
// `new src` — the source handle is an ordinary reference.
ExprKind::New(src) => self.bind_expr(src, scope),
ExprKind::Index { base, index, .. } => {
self.bind_expr(base, scope);
self.bind_expr(index, scope);
}
ExprKind::Range { base, msb, lsb, .. } => {
self.bind_expr(base, scope);
self.bind_expr(msb, scope);
self.bind_expr(lsb, scope);
}
// `a.b`, `a.b.c`, `tb.dut.u_core.sig`: every link is bound —
// the head as a path root (`Target::PathHead`), each `.name` as a
// tail against the type of what precedes it (`Target::MemberOf`) —
// because the
// recursion below meets each `Member` node in turn. `this.b` and
// `super.b` go to the enclosing class instead, and a spine that
// starts at one of them stops there: `this.a.b` records `a` and
// nothing more (`this` is not a name this crate binds, so there
// is no head to walk from). A called head (`f().b`) still
// resolves its own head and stops. An **indexed** link
// (`g_lane[0].lane_q`, `u_x.g[1].sig`) is walked as the name it
// indexes — see [`spine`] for why that is never a wrong answer.
ExprKind::Member { base, name, .. } => match &base.kind {
ExprKind::Ident(head) if head == "this" => {
self.use_member(scope, name, member_tail(e.span, name), Target::ThisMember)
}
ExprKind::Ident(head) if head == "super" => {
self.use_member(scope, name, member_tail(e.span, name), Target::SuperMember)
}
_ => {
// A bare head is a path's root: a miss there names a
// top-level module (`Target::PathHead`), where any other
// bare identifier's miss names nothing.
match &base.kind {
ExprKind::Ident(head) => {
self.use_name(scope, head, base.span, Target::PathHead)
}
_ => self.bind_expr(base, scope),
}
if let Some((head, mids)) = spine(base) {
// The tail's range is derived from the whole
// expression's, so it is verified before use: a
// spelling this crate cannot place costs a reference,
// never a wrong span.
let tail = self.exact_or_empty(member_tail(e.span, name), name);
if !tail.is_empty() {
self.use_member(scope, name, tail, Target::MemberOf { head, mids });
}
}
}
},
ExprKind::Scope { base, name, .. } => self.bind_scoped(base, name, e.span, scope),
// The `#( ... )` is verbatim text this crate makes no claims
// about; the name it parameterizes is still an ordinary use.
ExprKind::Parameterized { base, .. } => self.bind_expr(base, scope),
ExprKind::Concat(items) => {
for i in items {
self.bind_expr(&i.expr, scope);
}
}
ExprKind::Inside { lhs, ranges, .. } => {
self.bind_expr(lhs, scope);
for i in ranges {
self.bind_expr(&i.expr, scope);
}
}
ExprKind::Repl { count, inner } | ExprKind::AssignPatternRepl { count, inner } => {
self.bind_expr(count, scope);
for i in inner {
self.bind_expr(&i.expr, scope);
}
}
// The slice size of a streaming concatenation is a constant
// expression or a type; both are ordinary uses.
ExprKind::Stream { slice, inner, .. } => {
if let Some(s) = slice {
self.bind_expr(s, scope);
}
for i in inner {
self.bind_expr(&i.expr, scope);
}
}
// The set is a macro invocation this crate makes no claims about.
ExprKind::InsideMacro { lhs, .. } => self.bind_expr(lhs, scope),
ExprKind::With { base, arg, .. } => {
self.bind_expr(base, scope);
self.bind_expr(arg, scope);
}
// `a with [i +: n]` — the base and both range operands are
// ordinary uses, exactly as a part select's are.
ExprKind::StreamWith { base, range } => {
self.bind_expr(base, scope);
self.bind_expr(&range.msb, scope);
if let Some(lsb) = &range.lsb {
self.bind_expr(lsb, scope);
}
}
ExprKind::WithConstraint { base, block, .. } => {
self.bind_with_constraint(base, block, scope)
}
ExprKind::Dist { expr, weights, .. } => {
self.bind_expr(expr, scope);
for w in weights {
self.bind_expr(&w.value, scope);
self.bind_opt_expr(w.weight.as_ref(), scope);
}
}
ExprKind::Paren { inner, .. } => self.bind_expr(inner, scope),
// Both halves of a cast are bound: the operand as an ordinary
// expression, the casting type as a *type* — which
// `bind_data_type` has resolved since `overlay-promotion`.
ExprKind::Cast { ty, expr, .. } => {
self.bind_type_expr(ty, scope);
self.bind_expr(expr, scope);
}
ExprKind::AssignPattern(items) => {
for i in items {
self.bind_opt_expr(i.key.as_ref(), scope);
self.bind_expr(&i.value, scope);
}
}
ExprKind::ValueRange { lo, hi, .. } => {
self.bind_expr(lo, scope);
self.bind_expr(hi, scope);
}
// A named call argument: the value is an ordinary use; the name
// is the callee's formal, which this crate does not model (the
// same rule connection port names follow).
ExprKind::NamedArg { value, .. } => self.bind_expr(value, scope),
ExprKind::Type(ty) => self.bind_data_type(ty, scope),
ExprKind::MinTypMax { min, typ, max, .. } => {
self.bind_expr(min, scope);
self.bind_expr(typ, scope);
self.bind_expr(max, scope);
}
}
}
/// The **casting type** of a `ty'(expr)`, bound as a type reference.
///
/// The parser keeps a `casting_type` (IEEE 1800 §6.24.1) as an
/// expression, because that is the only shape wide enough for everything
/// the grammar spells there. Three of those shapes name a type and bind
/// as one; the rest are values, and bind as values:
///
/// - a bare name — `state_t'(0)` — is a [`Target::Type`], the same
/// binding `bind_data_type` gives a declaration's type name. A type
/// *keyword* (`int'(x)`) names nothing declared and binds to nothing,
/// which is what `bind_data_type` does with one too.
/// - `pkg::t'(x)` is a [`Target::Unit`] plus a [`Target::UnitMember`] —
/// again exactly what `bind_data_type` records for `pkg::t x;`.
/// - a size, a parenthesized constant expression (`(N)'(x)`) or a system
/// function call (`$bits(t)'(x)`) is an *expression* standing in for a
/// width. Its operands are ordinary uses and are bound as such.
fn bind_type_expr(&mut self, ty: &Expr, scope: ScopeId) {
match &ty.kind {
ExprKind::Ident(name) => {
if !is_keyword(name) {
self.use_name(scope, name, ty.span, Target::Type);
}
}
ExprKind::Scope { base, name, .. } => self.bind_scoped(base, name, ty.span, scope),
// A number is a size (`4'(x)`) and names nothing at all.
ExprKind::Number(_) => {}
_ => self.bind_expr(ty, scope),
}
}
/// `p::x`: the head names a unit (package or class), the tail is looked
/// up inside it.
fn bind_scoped(&mut self, base: &Expr, name: &str, span: TextRange, scope: ScopeId) {
let tail = TextRange::new(span.end.saturating_sub(name.len() as u32), span.end);
match &base.kind {
ExprKind::Ident(unit) => {
self.use_name(scope, unit, base.span, Target::Unit);
self.use_member(scope, name, tail, Target::UnitMember(unit.clone()));
}
_ => self.bind_expr(base, scope),
}
}
}
/// The chain of names written before a member access's tail: the plain
/// identifier it starts at, and the members already selected from it, in the
/// order they are written (`a.b.c`'s tail `c` gives `("a", ["b"])`).
///
/// An element select is transparent: `g[0].x` walks as `g.x`. Every link the
/// walk can continue from is one an index selects *another of the same* from
/// — a generate block (an element of a `for` generate is an instance of the
/// same block, IEEE 1800 §27.4), or a declaration whose recorded type is the
/// element's (a packed array of a struct). An unpacked declarator records no
/// type at all (`declare_typed`), and an instance array none either, so
/// `q[i].m` and `u[0].sig` still stop at their head exactly as before.
///
/// `None` for a spine this crate cannot start walking — a call, a cast, a
/// part select, or `this`/`super`, which name no declaration to take a type
/// from.
fn spine(base: &Expr) -> Option<(String, Vec<String>)> {
let mut mids = Vec::new();
let mut current = base;
loop {
match &current.kind {
ExprKind::Ident(name) if matches!(name.as_str(), "this" | "super") => return None,
ExprKind::Ident(name) => {
mids.reverse();
return Some((name.clone(), mids));
}
ExprKind::Member { base, name, .. } => {
mids.push(name.clone());
current = base;
}
ExprKind::Index { base, .. } => current = base,
_ => return None,
}
}
}
/// The byte range of a member access's tail: the construct's last token, so
/// its range is exactly the last `name.len()` bytes of the whole span.
fn member_tail(span: TextRange, name: &str) -> TextRange {
TextRange::new(span.end.saturating_sub(name.len() as u32), span.end)
}