From 4d59e805680dd51e767d489cacc889c6c3045ca6 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Sat, 5 Sep 2026 09:24:19 -0500 Subject: [PATCH] Type-name spans on the AST; vlog_semantic/src/scan.rs retired MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- TODO.md | 2 +- crates/lucisv_server/src/nav.rs | 45 ++ crates/vlog_formatter/src/format/stmt.rs | 2 +- .../src/rules/disable_statement.rs | 2 +- crates/vlog_parser/src/ast/decl.rs | 77 ++- crates/vlog_parser/src/ast/stmt.rs | 11 +- crates/vlog_parser/src/parser/decl.rs | 38 +- crates/vlog_parser/src/parser/keyword_stmt.rs | 7 +- crates/vlog_parser/src/parser/module.rs | 9 +- crates/vlog_parser/tests/spans.rs | 118 ++++- crates/vlog_semantic/src/bind/class.rs | 2 +- crates/vlog_semantic/src/bind/decl.rs | 122 ++--- crates/vlog_semantic/src/bind/expr.rs | 2 +- crates/vlog_semantic/src/bind/item.rs | 14 +- crates/vlog_semantic/src/bind/stmt.rs | 26 +- crates/vlog_semantic/src/lib.rs | 1 - crates/vlog_semantic/src/scan.rs | 193 -------- docs/features/type-name-spans/README.md | 453 ++++++++++++++++++ docs/features/vlog-semantic/README.md | 60 ++- docs/topo.md | 6 +- 20 files changed, 855 insertions(+), 335 deletions(-) delete mode 100644 crates/vlog_semantic/src/scan.rs create mode 100644 docs/features/type-name-spans/README.md diff --git a/TODO.md b/TODO.md index 8921584..bae6817 100644 --- a/TODO.md +++ b/TODO.md @@ -4798,7 +4798,7 @@ census, 21 485 symbols). clean; release server smoke OK; census 27 486 symbols / 103 870 references / 0 unplaced, identical to a `v0.44.0` scratch worktree; 200 `definition` positions over opentitan identical old vs new -- [ ] QA: census re-derived; escaped and scoped type names; `iface.mp` +- [x] QA: census re-derived; escaped and scoped type names; `iface.mp` ports; implicit types; definition/hover on type names over opentitan (read-only) diff --git a/crates/lucisv_server/src/nav.rs b/crates/lucisv_server/src/nav.rs index 97b9642..40b1c12 100644 --- a/crates/lucisv_server/src/nav.rs +++ b/crates/lucisv_server/src/nav.rs @@ -552,6 +552,51 @@ mod tests { assert_eq!(locations[0].range.start.line, 1); } + /// A qualified type name is two references, each addressable on its own + /// half: the parser spans `pkg::t` and `DataType::segments` splits it, so + /// F12 on the *item* lands on the typedef rather than on the package. + #[test] + fn a_scoped_type_name_jumps_from_its_item_half() { + let text = "\ +package pkg; + typedef logic [1:0] t; +endpackage +module m; + pkg::t x; +endmodule +"; + let (ws, uri) = document(text); + let item = definition(&ws, &uri, at(text, "pkg::t x") + 5); + assert_eq!(item.len(), 1, "the typedef"); + assert_eq!(item[0].range.start.line, 1, "the `typedef ... t;` line"); + assert_eq!(item[0].range.start.character, 22, "the name `t`, not the keyword"); + let unit = definition(&ws, &uri, at(text, "pkg::t x")); + assert_eq!(unit.len(), 1, "the package"); + assert_eq!(unit[0].range.start.line, 0); + } + + /// `bus_if.mp bus` — the interface is the type, so the head range is what + /// F12 answers from; the modport tail is a member of it. + #[test] + fn an_interface_port_type_jumps_from_its_head() { + let text = "\ +interface bus_if; + logic clk; + modport mp (input clk); +endinterface +module m (bus_if.mp bus); +endmodule +"; + let (ws, uri) = document(text); + let head = definition(&ws, &uri, at(text, "bus_if.mp bus") + 2); + assert_eq!(head.len(), 1, "the interface"); + assert_eq!(head[0].range.start.line, 0); + assert_eq!(head[0].range.start.character, 10, "the interface name"); + let tail = definition(&ws, &uri, at(text, "bus_if.mp bus") + 7); + assert_eq!(tail.len(), 1, "the modport"); + assert_eq!(tail[0].range.start.line, 2); + } + #[test] fn a_macro_use_jumps_to_its_define_in_the_same_file() { let text = "`define WIDTH 8\nmodule m;\n logic [`WIDTH-1:0] a;\nendmodule\n"; diff --git a/crates/vlog_formatter/src/format/stmt.rs b/crates/vlog_formatter/src/format/stmt.rs index 38cd72e..ab169bc 100644 --- a/crates/vlog_formatter/src/format/stmt.rs +++ b/crates/vlog_formatter/src/format/stmt.rs @@ -482,7 +482,7 @@ impl<'a> Fmt<'a> { }, StmtKind::Break => concat(vec![text("break"), self.semi(before_semi)]), StmtKind::Continue => concat(vec![text("continue"), self.semi(before_semi)]), - StmtKind::Disable(name) => { + StmtKind::Disable { name, .. } => { concat(vec![text(format!("disable {}", named(name))), self.semi(before_semi)]) } StmtKind::WaitFork => concat(vec![text("wait fork"), self.semi(before_semi)]), diff --git a/crates/vlog_linter/src/rules/disable_statement.rs b/crates/vlog_linter/src/rules/disable_statement.rs index 326f5e9..fad040c 100644 --- a/crates/vlog_linter/src/rules/disable_statement.rs +++ b/crates/vlog_linter/src/rules/disable_statement.rs @@ -58,7 +58,7 @@ impl Rule for DisableStatement { let targets = disableable(ctx.file()); let mut out = Vec::new(); walk_all_stmts(ctx.file(), &mut |stmt| { - let StmtKind::Disable(name) = &stmt.kind else { return }; + let StmtKind::Disable { name, .. } = &stmt.kind else { return }; // `disable fork` is the keyword form, not a label. if name == "fork" || targets.contains(name.as_str()) { return; diff --git a/crates/vlog_parser/src/ast/decl.rs b/crates/vlog_parser/src/ast/decl.rs index 0360f90..b0152e5 100644 --- a/crates/vlog_parser/src/ast/decl.rs +++ b/crates/vlog_parser/src/ast/decl.rs @@ -5,7 +5,10 @@ use super::*; /// A data type: keyword or user-defined name, plus signing and packed dims. -/// `name` may be empty for implicit types (`input [7:0] x`). +/// `name` may be empty for implicit types (`input [7:0] x`), and is the whole +/// chain a qualified type reference writes: `pkg::item`, `bus_if.mp`. +/// [`DataType::name_span`] says where it is written and +/// [`DataType::segments`] splits it. #[derive(Debug, Clone, Default)] pub struct DataType { /// The `virtual` / `virtual interface` prefix of a virtual interface type @@ -22,6 +25,14 @@ pub struct DataType { /// so a rare field must not widen the common case. pub virt: Option, pub name: String, + /// Where [`DataType::name`] is written. Read it through + /// [`DataType::name_span`], which pairs it with the name's own length. + /// + /// Four bytes rather than a whole [`TextRange`] because they fit in the + /// padding this struct already has: an eight-byte span pushes `DataType` + /// to 96 and, through [`ExprKind::Type`], every `Expr` to 104, past the + /// 96-byte pin in `size_pins`. + pub(crate) name_start: u32, /// The rare tail of a type: parameterization or an anonymous aggregate /// body. See [`TypeExtra`]; read it through [`DataType::params`] / /// [`DataType::inline`]. @@ -57,6 +68,70 @@ impl DataType { _ => None, } } + + /// The byte range [`DataType::name`] occupies: `src[name_span] == name` + /// for every name the source spells the way the AST joined it, which is + /// every name but the pathological spacings [`DataType::segments`] + /// documents. An implicit type has no name, so this is the empty range at + /// the position a name would have been written — the same convention an + /// unnamed DPI formal's `name_span` uses. + pub fn name_span(&self) -> TextRange { + TextRange::new(self.name_start, self.name_start.saturating_add(self.name.len() as u32)) + } + + /// The `::`- and `.`-separated segments of the name — `pkg`, `item` of + /// `pkg::item`; `bus_if`, `mp` of `bus_if.mp` — each with the byte range + /// it occupies. + /// + /// Derived from [`DataType::name_span`] and the name's own text: the + /// construct is never rescanned. So a source that spells the name + /// differently from the way the parser joined it — an escaped segment + /// terminated by a newline rather than a space, a `bus_if . mp` written + /// apart — hands back ranges that do not slice back to their segment. + /// A caller that must not mislocate checks the slice and drops the + /// segment; `vlog_semantic`'s binder does. + pub fn segments(&self) -> impl Iterator + '_ { + let base = self.name_start; + let mut rest = Some((0usize, self.name.as_str())); + std::iter::from_fn(move || { + let (at, text) = rest.take()?; + let (seg, tail) = match separator(text) { + Some((i, len)) => (&text[..i], Some((at + i + len, &text[i + len..]))), + None => (text, None), + }; + rest = tail; + let start = base.saturating_add(at as u32); + Some((seg, TextRange::new(start, start.saturating_add(seg.len() as u32)))) + }) + .filter(|(seg, _): &(&str, TextRange)| !seg.is_empty()) + } +} + +/// Where the first `::`/`.` that separates two name segments starts, and how +/// many bytes it is. +/// +/// An escaped identifier swallows both spellings (`\a.b ::x` is two segments, +/// not three), so one that leads the text runs to its terminating whitespace — +/// which the parser keeps in the joined name (§29) — before the search for a +/// separator begins. +fn separator(text: &str) -> Option<(usize, usize)> { + let bytes = text.as_bytes(); + let mut i = 0; + if bytes.first() == Some(&b'\\') { + while i < bytes.len() && !bytes[i].is_ascii_whitespace() { + i += 1; + } + // The terminator belongs to the segment; anything else is a separator. + i = (i + 1).min(bytes.len()); + } + while i < bytes.len() { + match bytes[i] { + b':' if bytes.get(i + 1) == Some(&b':') => return Some((i, 2)), + b'.' => return Some((i, 1)), + _ => i += 1, + } + } + None } /// What a type carries beyond its name, signing and packed dimensions. A type diff --git a/crates/vlog_parser/src/ast/stmt.rs b/crates/vlog_parser/src/ast/stmt.rs index f71b7d2..af4b388 100644 --- a/crates/vlog_parser/src/ast/stmt.rs +++ b/crates/vlog_parser/src/ast/stmt.rs @@ -266,7 +266,14 @@ pub enum StmtKind { }, Break, Continue, - Disable(String), + /// `disable blk;`, `disable fork;` — the label or task the statement + /// names, with the range it is written in. A *use*, not a declaration, + /// but it is addressable all the same, so it carries a span like every + /// other name (`disable fork` spans the `fork` keyword). + Disable { + name: String, + name_span: TextRange, + }, Directive(RawText), /// Macro invocation used as a statement. MacroStmt(MacroCall), @@ -323,7 +330,7 @@ impl StmtKind { | StmtKind::Return { .. } | StmtKind::Break | StmtKind::Continue - | StmtKind::Disable(_) + | StmtKind::Disable { .. } | StmtKind::WaitFork | StmtKind::DoWhile { .. } => true, StmtKind::Timing { stmt, .. } => stmt.is_none(), diff --git a/crates/vlog_parser/src/parser/decl.rs b/crates/vlog_parser/src/parser/decl.rs index 94dba42..6820e60 100644 --- a/crates/vlog_parser/src/parser/decl.rs +++ b/crates/vlog_parser/src/parser/decl.rs @@ -10,14 +10,26 @@ use super::item::MEMBER_QUALIFIERS; use super::*; impl<'a> Parser<'a> { + /// A type with nothing written for it, spanning the empty range at the + /// cursor: what a `parameter type T` and an implicit `input [7:0] x` + /// both carry. Distinct from [`DataType::default`] only in that its + /// `name_span` points at the source rather than at offset zero. + pub(super) fn implicit_type(&self) -> DataType { + DataType { name_start: self.here(), ..DataType::default() } + } + /// Parse a possibly-implicit data type. Stops before the declarator name. pub(super) fn parse_opt_data_type(&mut self) -> PResult { - let mut ty = DataType::default(); + // An implicit type writes no name at all, so its `name_span` is the + // empty range where a name would have gone: right here, before + // anything of the type has been consumed. + let mut ty = self.implicit_type(); // `property p(sequence a, property b);` — inside a property's or a // sequence's formal list, and nowhere else, the two keywords name a // formal's *type* (IEEE 1800 §16.8). `untyped` needs no case: it is // an ordinary identifier and already reads as a user-defined type. if self.sva_formals && (self.cur().is_kw("sequence") || self.cur().is_kw("property")) { + ty.name_start = self.here(); ty.name = self.bump().text; return Ok(ty); } @@ -35,7 +47,9 @@ impl<'a> Parser<'a> { // Glued onto the interface name exactly as an interface *port*'s // modport is, so every consumer still sees one type-name string. if self.at_modport_port() { - ty.name = self.parse_modport_port_type()?.name; + let head = self.parse_modport_port_type()?; + ty.name = head.name; + ty.name_start = head.name_start; return Ok(ty); } } @@ -53,18 +67,15 @@ impl<'a> Parser<'a> { return Ok(ty); } if t.kind == TokenKind::Keyword && TYPE_KEYWORDS.contains(&t.text.as_str()) { + ty.name_start = self.here(); ty.name = self.bump().text; } else if t.kind == TokenKind::Ident { // User-defined type only if what follows still leaves an // identifier for the declarator name. if self.at_typed_declarator() { - let mut name = self.expect_ident()?; - while self.cur().is_sym("::") { - self.bump(); - let segment = self.expect_ident()?; - Self::push_scope_segment(&mut name, &segment); - } + let (name, span) = self.parse_scoped_name()?; ty.name = name; + ty.name_start = span.start; if self.at_type_params() { ty.extra = Some(Box::new(TypeExtra::Params(self.parse_type_params()?))); } @@ -187,7 +198,7 @@ impl<'a> Parser<'a> { // parameter outside the `#( ... )` list // (lossy_valid_to_stream_tb.sv:26). Its default is a type, not a value. let is_type = self.eat_kw("type"); - let ty = if is_type { DataType::default() } else { self.parse_opt_data_type()? }; + let ty = if is_type { self.implicit_type() } else { self.parse_opt_data_type()? }; let declarators = self.parse_declarator_list(is_type)?; Ok(ParamDecl { kw, after_kw, is_type, ty, declarators }) } @@ -474,13 +485,8 @@ impl<'a> Parser<'a> { if !ty.is_implicit() || self.cur().kind != TokenKind::Ident { return Ok(ty); } - let mut name = self.expect_ident()?; - while self.cur().is_sym("::") { - self.bump(); - let segment = self.expect_ident()?; - Self::push_scope_segment(&mut name, &segment); - } - let mut ty = DataType { name, ..DataType::default() }; + let (name, span) = self.parse_scoped_name()?; + let mut ty = DataType { name, name_start: span.start, ..DataType::default() }; if self.at_type_params() { ty.extra = Some(Box::new(TypeExtra::Params(self.parse_type_params()?))); } diff --git a/crates/vlog_parser/src/parser/keyword_stmt.rs b/crates/vlog_parser/src/parser/keyword_stmt.rs index 01f573a..6a85059 100644 --- a/crates/vlog_parser/src/parser/keyword_stmt.rs +++ b/crates/vlog_parser/src/parser/keyword_stmt.rs @@ -167,18 +167,21 @@ impl<'a> Parser<'a> { // `disable fork;` kills every process the enclosing `fork` // started; `fork` is a keyword, not a block name. if self.cur().is_kw("fork") { + let name_span = self.cur().span; self.bump(); self.expect_stmt_semi()?; - return Ok(StmtKind::Disable("fork".to_string())); + return Ok(StmtKind::Disable { name: "fork".to_string(), name_span }); } + let start = self.here(); let mut name = self.expect_ident()?; while self.cur().is_sym(".") { self.bump(); name.push('.'); name.push_str(&self.expect_ident()?); } + let name_span = self.span_from(start); self.expect_stmt_semi()?; - Ok(StmtKind::Disable(name)) + Ok(StmtKind::Disable { name, name_span }) } "wait" => { self.bump(); diff --git a/crates/vlog_parser/src/parser/module.rs b/crates/vlog_parser/src/parser/module.rs index a3ead93..92b00ff 100644 --- a/crates/vlog_parser/src/parser/module.rs +++ b/crates/vlog_parser/src/parser/module.rs @@ -412,7 +412,7 @@ impl<'a> Parser<'a> { meta, kw, after_kw, - ty: DataType::default(), + ty: self.implicit_type(), is_type: true, before_name, name, @@ -624,12 +624,15 @@ impl<'a> Parser<'a> { /// The `bus_if.mp` of an interface port, as its type. The modport is glued /// onto the interface name exactly as a `pkg::` qualifier is, so every - /// consumer that prints or scans a type name still sees one string. + /// consumer that prints a type name still sees one string; + /// [`DataType::segments`] splits it back into its two halves and their + /// ranges. pub(super) fn parse_modport_port_type(&mut self) -> PResult { + let name_start = self.here(); let mut name = self.expect_ident()?; self.expect_sym(".")?; name.push('.'); name.push_str(&self.expect_ident()?); - Ok(DataType { name, ..DataType::default() }) + Ok(DataType { name, name_start, ..DataType::default() }) } } diff --git a/crates/vlog_parser/tests/spans.rs b/crates/vlog_parser/tests/spans.rs index 97c7f75..849949b 100644 --- a/crates/vlog_parser/tests/spans.rs +++ b/crates/vlog_parser/tests/spans.rs @@ -1011,10 +1011,12 @@ fn check_stmt(src: &str, stmt: &Stmt, parent: TextRange) { check_stmt(src, inner, here); } StmtKind::Import(paths) => check_import_paths(src, paths, here), + StmtKind::Disable { name, name_span } => { + check_name(src, "disable target", name, *name_span, here) + } StmtKind::Break | StmtKind::Continue | StmtKind::WaitFork - | StmtKind::Disable(_) | StmtKind::Null | StmtKind::Error(_) => {} StmtKind::Assertion(a) => check_assertion(src, a, here), @@ -1669,3 +1671,117 @@ fn check_constraint_set(src: &str, set: &ConstraintSet, parent: TextRange) { } } } + +// ---------------------------------------------------------------------- +// Type-name spans (TODO.md §47) +// ---------------------------------------------------------------------- + +/// Every `DataType` a source file writes, in item order, with the declarator +/// it belongs to left behind — enough to reach each construction site by hand. +fn module_types(file: &SourceFile) -> Vec<&DataType> { + let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; + let mut out = Vec::new(); + if let PortList::Ansi(ports) = &m.ports { + out.extend(ports.iter().filter_map(ListElem::ok).map(|p| &p.ty)); + } + for item in &m.items { + match &item.kind { + ItemKind::DataDecl(d) => out.push(&d.ty), + ItemKind::Typedef(t) => { + if let TypedefKind::Alias(ty) = &t.kind { + out.push(ty); + } + } + _ => {} + } + } + out +} + +#[test] +fn a_type_name_span_slices_back_to_the_name_as_written() { + let src = "\ +module m (input bus_if.mp bus, input [7:0] raw); + typedef pkg_a::state_t alias_t; + logic [3:0] plain; + my_type_t user; + virtual clk_rst_if vif; +endmodule +"; + let file = parse_source(src).expect("parse error"); + let types = module_types(&file); + let seen: Vec<&str> = types.iter().map(|ty| slice(src, ty.name_span())).collect(); + assert_eq!(seen, ["bus_if.mp", "", "pkg_a::state_t", "logic", "my_type_t", "clk_rst_if"]); + for ty in &types { + assert_eq!(slice(src, ty.name_span()), ty.name, "a type-name span moved off its name"); + } + + // The implicit `input [7:0] raw` has no name, so its span is the empty + // range where one would have been written — at the `[`. + let implicit = types[1].name_span(); + assert!(implicit.is_empty()); + assert_eq!(&src[implicit.start as usize..implicit.start as usize + 1], "["); +} + +#[test] +fn segments_split_a_qualified_type_name_without_rescanning() { + let src = "\ +module m (input bus_if.mp bus); + pkg_a::state_t s; + logic plain; +endmodule +"; + let file = parse_source(src).expect("parse error"); + let types = module_types(&file); + let split = |ty: &DataType| -> Vec<(String, String)> { + ty.segments().map(|(seg, span)| (seg.to_string(), slice(src, span).to_string())).collect() + }; + assert_eq!(split(types[0]), [("bus_if".into(), "bus_if".into()), ("mp".into(), "mp".into())]); + assert_eq!( + split(types[1]), + [("pkg_a".into(), "pkg_a".into()), ("state_t".into(), "state_t".into())] + ); + assert_eq!(split(types[2]), [("logic".to_string(), "logic".to_string())]); + + // An implicit type has no name and so no segments at all. + let empty = DataType::default(); + assert_eq!(empty.segments().count(), 0); +} + +#[test] +fn an_escaped_segment_keeps_its_terminating_space_in_span_and_segment() { + // §29: the parser joins `\a+b ::state_t` with the space the escaped + // identifier needs, so the joined name is what the source spells and the + // first segment carries the terminator. + let src = "module m;\n \\a+b ::state_t s;\nendmodule\n"; + let file = parse_source(src).expect("parse error"); + let types = module_types(&file); + assert_eq!(types[0].name, "\\a+b ::state_t"); + assert_eq!(slice(src, types[0].name_span()), "\\a+b ::state_t"); + let segs: Vec<&str> = types[0].segments().map(|(_, span)| slice(src, span)).collect(); + assert_eq!(segs, ["\\a+b ", "state_t"]); +} + +#[test] +fn a_disable_names_its_target_with_a_span() { + let src = "\ +module m; + initial begin : blk + disable blk; + disable fork; + end +endmodule +"; + let file = parse_source(src).expect("parse error"); + let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; + let ItemKind::Initial(outer) = &m.items[0].kind else { panic!("expected an initial") }; + let StmtKind::Block { stmts, .. } = &outer.kind else { panic!("expected a block") }; + let targets: Vec<&str> = stmts + .iter() + .map(|s| { + let StmtKind::Disable { name_span, .. } = &s.kind else { panic!("expected a disable") }; + slice(src, *name_span) + }) + .collect(); + assert_eq!(targets, ["blk", "fork"]); +} diff --git a/crates/vlog_semantic/src/bind/class.rs b/crates/vlog_semantic/src/bind/class.rs index 300ec23..d30285a 100644 --- a/crates/vlog_semantic/src/bind/class.rs +++ b/crates/vlog_semantic/src/bind/class.rs @@ -352,7 +352,7 @@ impl<'a> Binder<'a> { // Return type, arguments and body all resolve from inside the class, // as the LRM says an out-of-body declaration does. if let Some(ret) = ret { - self.bind_data_type(ret, TextRange::new(span.start, name_span.start), body); + self.bind_data_type(ret, body); } self.bind_tf_args(args, body); self.bind_stmts(stmts, body); diff --git a/crates/vlog_semantic/src/bind/decl.rs b/crates/vlog_semantic/src/bind/decl.rs index 53a27fe..2bd2fa2 100644 --- a/crates/vlog_semantic/src/bind/decl.rs +++ b/crates/vlog_semantic/src/bind/decl.rs @@ -9,7 +9,6 @@ use vlog_parser::span::TextRange; use vlog_parser::token::is_keyword; use crate::model::{ScopeId, ScopeKind, SymbolId, SymbolKind}; -use crate::scan::NameScanner; use super::{type_name_of, Binder, Target}; @@ -39,7 +38,7 @@ impl<'a> Binder<'a> { if let Some(written) = &p.kw { kw.clone_from(written); } - self.bind_data_type(&p.ty, TextRange::new(p.span.start, p.name_span.start), scope); + self.bind_data_type(&p.ty, scope); let ty = p.unpacked.is_empty().then_some(&p.ty); self.declare_typed(scope, &p.name, param_kind(&kw), p.name_span, p.span, ty); self.bind_dims(&p.unpacked, scope); @@ -51,7 +50,7 @@ impl<'a> Binder<'a> { /// in [`Binder::bind_param_ports`]. pub(super) fn bind_tf_args(&mut self, args: &'a [ListElem], scope: ScopeId) { for a in args.iter().filter_map(ListElem::ok) { - self.bind_data_type(&a.ty, TextRange::new(a.span.start, a.name_span.start), scope); + self.bind_data_type(&a.ty, scope); let ty = a.unpacked.is_empty().then_some(&a.ty); self.declare_typed(scope, &a.name, SymbolKind::TfArg, a.name_span, a.span, ty); self.bind_dims(&a.unpacked, scope); @@ -68,13 +67,13 @@ impl<'a> Binder<'a> { // a container, not a value of the type, and is left untyped on // the same rule every other unpacked declarator follows. TypedefKind::Alias(ty) => { - self.bind_data_type(ty, TextRange::new(span.start, ns.start), scope); + self.bind_data_type(ty, scope); let ty = t.unpacked.is_empty().then_some(ty); self.declare_typed(scope, &t.name, SymbolKind::Typedef, ns, span, ty); } TypedefKind::Enum(e) => { self.declare(scope, &t.name, SymbolKind::Typedef, ns, span); - self.bind_enum_body(e, TextRange::new(span.start, ns.start), scope); + self.bind_enum_body(e, scope); } TypedefKind::Struct(s) => { let inner = self.declare_with_scope( @@ -103,9 +102,9 @@ impl<'a> Binder<'a> { /// which is why `IDLE` is written bare. One function for all three /// spellings that can write one: `typedef enum {…} e_t;`, an anonymous /// `enum {…} x;`, and an anonymous enum standing as a struct member's type. - fn bind_enum_body(&mut self, e: &EnumType, window: TextRange, scope: ScopeId) { + fn bind_enum_body(&mut self, e: &EnumType, scope: ScopeId) { if let Some(base) = &e.base { - self.bind_data_type(base, window, scope); + self.bind_data_type(base, scope); } self.bind_enum_members(&e.members, scope); } @@ -130,8 +129,7 @@ impl<'a> Binder<'a> { /// rather than once per declarator. fn bind_struct_uses(&mut self, s: &StructType, scope: ScopeId) { for m in &s.members { - let first = m.declarators.first().map(|d| d.span.start).unwrap_or(m.span.end); - self.bind_data_type(&m.ty, TextRange::new(m.span.start, first), scope); + self.bind_data_type(&m.ty, scope); for d in &m.declarators { self.bind_dims(&d.unpacked, scope); self.bind_opt_expr(d.init.as_ref(), scope); @@ -177,10 +175,10 @@ impl<'a> Binder<'a> { } } - pub(super) fn bind_data_decl(&mut self, d: &DataDecl, span: TextRange, scope: ScopeId) { + pub(super) fn bind_data_decl(&mut self, d: &DataDecl, scope: ScopeId) { let kind = if d.net.is_some() { SymbolKind::Net } else { SymbolKind::Var }; self.bind_opt_expr(d.delay.as_ref().map(|n| &n.expr), scope); - self.bind_declarators(&d.declarators, kind, &d.ty, span, scope); + self.bind_declarators(&d.declarators, kind, &d.ty, scope); } pub(super) fn bind_port_decl(&mut self, p: &PortDecl, span: TextRange, scope: ScopeId) { @@ -222,7 +220,7 @@ impl<'a> Binder<'a> { symbol.type_name = type_name; } } - self.bind_declarators(&p.declarators, kind, &p.ty, span, scope); + self.bind_declarators(&p.declarators, kind, &p.ty, scope); } pub(super) fn bind_declarators( @@ -230,11 +228,9 @@ impl<'a> Binder<'a> { declarators: &[Declarator], kind: SymbolKind, ty: &DataType, - span: TextRange, scope: ScopeId, ) { - let first = declarators.first().map(|d| d.span.start).unwrap_or(span.end); - self.bind_data_type(ty, TextRange::new(span.start, first), scope); + self.bind_data_type(ty, scope); for d in declarators { let plain = d.unpacked.is_empty(); let id = @@ -254,49 +250,12 @@ impl<'a> Binder<'a> { } } - /// A user-defined type name is a use like any other. `window` is the - /// source range the name was written in — everything before the declared - /// name, which is where a data type always sits. A `DataType` has no span - /// of its own (vlog-semantic handshake item 2, still open), so this is - /// the one declaration surface still located by scanning. - pub(super) fn bind_data_type(&mut self, ty: &DataType, window: TextRange, scope: ScopeId) { + /// A user-defined type name is a use like any other, and the parser hands + /// over where every segment of it is written + /// ([`DataType::segments`]), so nothing here rescans the source. + pub(super) fn bind_data_type(&mut self, ty: &DataType, scope: ScopeId) { if !ty.name.is_empty() && !is_keyword(&ty.name) { - match ty.name.split_once("::") { - Some((unit, item)) => { - let mut scanner = NameScanner::new(self.src, window); - let unit_span = scanner.find(unit).unwrap_or(TextRange::empty(window.start)); - let item_span = scanner.find(item).unwrap_or(TextRange::empty(window.start)); - self.use_name(scope, unit, unit_span, Target::Unit); - self.use_name(scope, item, item_span, Target::UnitMember(unit.to_string())); - } - // `bus_if.mp bus`, `virtual bus_if.mp vif` — the parser glues - // an interface port's modport onto the type name (IEEE 1800 - // §25.4, §25.9). The interface is the type and the modport is - // a **member** of it, so both halves are bound: the head as - // any other type name, the tail against the interface's own - // scope (or, cross-file, as `bus_if::mp` in the workspace's - // member table). "The tail is where to bind them" — - // `docs/features/ansi-first-port/README.md`. - None => { - let (name, modport) = match ty.name.split_once('.') { - Some((iface, modport)) => (iface, Some(modport)), - None => (ty.name.as_str(), None), - }; - let ns = crate::scan::name_span(self.src, window, name); - self.use_name(scope, name, ns, Target::Type); - if let Some(modport) = modport { - let tail = self.modport_tail(ns, modport); - if !tail.is_empty() { - self.use_member( - scope, - modport, - tail, - Target::TypeMember { unit: name.to_string() }, - ); - } - } - } - } + self.bind_type_name(ty, scope); } self.bind_dims(&ty.packed, scope); // An anonymous aggregate written where a type name would go. Its @@ -305,27 +264,50 @@ impl<'a> Binder<'a> { // is written here is every use inside it, recorded once for the type // however many declarators share it. match ty.inline() { - Some(TypeExtra::Enum(e)) => self.bind_enum_body(e, window, scope), + Some(TypeExtra::Enum(e)) => self.bind_enum_body(e, scope), Some(TypeExtra::Struct(s)) => self.bind_struct_uses(s, scope), _ => {} } } - /// The byte range of the `mp` in a glued `bus_if.mp` type name, given the - /// range the interface half was located at. + /// The segments of a written type name, each recorded as a use. /// - /// Derived rather than received — a `DataType` carries no spans at all — - /// so it is verified twice over: the byte after the interface half must be - /// a literal `.`, and the bytes after that must spell the modport exactly. - /// A source that wrote the two apart, or a name a macro produced, costs the + /// `pkg::item` is a unit and a member of it. `bus_if.mp bus`, + /// `virtual bus_if.mp vif` — the parser glues an interface port's modport + /// onto the type name (IEEE 1800 §25.4, §25.9) — is the interface as the + /// type plus the modport as a **member** of it, bound against the + /// interface's own scope (or, cross-file, as `bus_if::mp` in the + /// workspace's member table). "The tail is where to bind them" — + /// `docs/features/ansi-first-port/README.md`. + /// + /// Every span is checked against the source before it is recorded, the + /// rule the modport tail has always followed: a name the source spells + /// differently from the way the parser joined it — an escaped segment + /// terminated by a newline, a `bus_if . mp` written apart — costs the /// reference and never mislocates it. - fn modport_tail(&self, iface: TextRange, modport: &str) -> TextRange { - if iface.is_empty() || self.src.as_bytes().get(iface.end as usize) != Some(&b'.') { - return TextRange::empty(iface.end); + fn bind_type_name(&mut self, ty: &DataType, scope: ScopeId) { + let scoped = ty.name.contains("::"); + let mut head: Option<&str> = None; + for (seg, span) in ty.segments() { + // A segment whose derived range does not read back as its own + // text (`pkg :: item`, a comment inside the name) is recorded + // with the empty range at its start, never dropped: an empty + // range is what the corpus census counts as *unplaced*, so a + // parser regression in the join would trip that alarm instead of + // silently lowering the resolution rate (§47's QA). + let span = self.exact_or_empty(span, seg); + match (head, scoped) { + (None, true) => self.use_name(scope, seg, span, Target::Unit), + (None, false) => self.use_name(scope, seg, span, Target::Type), + (Some(unit), true) => { + self.use_name(scope, seg, span, Target::UnitMember(unit.to_string())) + } + (Some(unit), false) => { + self.use_member(scope, seg, span, Target::TypeMember { unit: unit.to_string() }) + } + } + head = Some(seg); } - let start = iface.end.saturating_add(1); - let span = TextRange::new(start, start.saturating_add(modport.len() as u32)); - self.exact_or_empty(span, modport) } } diff --git a/crates/vlog_semantic/src/bind/expr.rs b/crates/vlog_semantic/src/bind/expr.rs index 666f1ee..6635993 100644 --- a/crates/vlog_semantic/src/bind/expr.rs +++ b/crates/vlog_semantic/src/bind/expr.rs @@ -174,7 +174,7 @@ impl<'a> Binder<'a> { // 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, e.span, 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); diff --git a/crates/vlog_semantic/src/bind/item.rs b/crates/vlog_semantic/src/bind/item.rs index c678625..96b6b7f 100644 --- a/crates/vlog_semantic/src/bind/item.rs +++ b/crates/vlog_semantic/src/bind/item.rs @@ -88,9 +88,9 @@ impl<'a> Binder<'a> { } ItemKind::Typedef(t) => self.bind_typedef(t, item.span, scope), ItemKind::ParamDecl(p) => { - self.bind_declarators(&p.declarators, param_kind(&p.kw), &p.ty, item.span, scope) + self.bind_declarators(&p.declarators, param_kind(&p.kw), &p.ty, scope) } - ItemKind::DataDecl(d) => self.bind_data_decl(d, item.span, scope), + ItemKind::DataDecl(d) => self.bind_data_decl(d, scope), ItemKind::PortDecl(p) => self.bind_port_decl(p, item.span, scope), ItemKind::ContAssign(c) => { self.bind_opt_expr(c.delay.as_ref(), scope); @@ -212,11 +212,7 @@ impl<'a> Binder<'a> { // declares nothing, exactly as an `ItemKind::Error` does. PortList::Ansi(ports) => { for p in ports.iter().filter_map(ListElem::ok) { - self.bind_data_type( - &p.ty, - TextRange::new(p.span.start, p.name_span.start), - inner, - ); + self.bind_data_type(&p.ty, inner); self.declare_typed( inner, &p.name, @@ -419,7 +415,7 @@ impl<'a> Binder<'a> { return; } if let Some(ret) = &f.ret { - self.bind_data_type(ret, TextRange::new(span.start, f.name_span.start), scope); + self.bind_data_type(ret, scope); } let inner = self.declare_with_scope( scope, @@ -487,7 +483,7 @@ impl<'a> Binder<'a> { fn bind_modport_prototype(&mut self, p: &'a TfPrototype, span: TextRange, scope: ScopeId) { self.use_name(scope, &p.name, p.name_span, Target::InScope); if let Some(ret) = &p.ret { - self.bind_data_type(ret, TextRange::new(span.start, p.name_span.start), scope); + self.bind_data_type(ret, scope); } let inner = self.new_scope(ScopeKind::Block, scope, span); self.bind_tf_args(&p.args, inner); diff --git a/crates/vlog_semantic/src/bind/stmt.rs b/crates/vlog_semantic/src/bind/stmt.rs index e4aa7f1..24a613b 100644 --- a/crates/vlog_semantic/src/bind/stmt.rs +++ b/crates/vlog_semantic/src/bind/stmt.rs @@ -4,10 +4,8 @@ //! covergroups and property specs share with them. use vlog_parser::ast::*; -use vlog_parser::span::TextRange; use crate::model::{ScopeId, ScopeKind, SymbolKind}; -use crate::scan::name_after_kw; use super::decl::param_kind; use super::{Binder, Target}; @@ -66,11 +64,7 @@ impl<'a> Binder<'a> { match &i.ty { Some(ty) => { if let ExprKind::Ident(name) = &i.assign.lhs.kind { - self.bind_data_type( - ty, - TextRange::new(stmt.span.start, i.assign.lhs.span.start), - scope, - ); + self.bind_data_type(ty, scope); self.declare( inner, name, @@ -140,21 +134,25 @@ impl<'a> Binder<'a> { } } StmtKind::ExprStmt(e) | StmtKind::EventTrigger(e) => self.bind_expr(e, scope), - StmtKind::VarDecl(d) => self.bind_data_decl(d, stmt.span, scope), + StmtKind::VarDecl(d) => self.bind_data_decl(d, scope), // A block-scoped type binds exactly as an item-level one does; the // scope it lands in is the enclosing block's, which is what // IEEE 1800 §6.18 asks for. StmtKind::Typedef(t) => self.bind_typedef(t, stmt.span, scope), StmtKind::ParamDecl(p) => { - self.bind_declarators(&p.declarators, param_kind(&p.kw), &p.ty, stmt.span, scope) + self.bind_declarators(&p.declarators, param_kind(&p.kw), &p.ty, scope) } StmtKind::PortDecl(p) => self.bind_port_decl(p, stmt.span, scope), StmtKind::Return { expr: e, .. } => self.bind_opt_expr(e.as_ref(), scope), - StmtKind::Disable(name) => { - // A use, not a declaration, so name-spans deliberately gave it - // no range — the one statement still located by scanning. - let ns = name_after_kw(self.src, stmt.span, "disable", name); - self.use_name(scope, name, ns, Target::Lexical); + StmtKind::Disable { name, name_span } => { + // A use, not a declaration, but the parser spans it like any + // other name. Checked before it is recorded, the rule every + // derived span here follows: `disable a . b` written apart + // costs the reference rather than mislocating it. + let ns = self.exact_or_empty(*name_span, name); + if !ns.is_empty() { + self.use_name(scope, name, ns, Target::Lexical); + } } StmtKind::Assert { cond, then, els, .. } => { self.bind_expr(cond, scope); diff --git a/crates/vlog_semantic/src/lib.rs b/crates/vlog_semantic/src/lib.rs index 3609d47..c36bb83 100644 --- a/crates/vlog_semantic/src/lib.rs +++ b/crates/vlog_semantic/src/lib.rs @@ -22,7 +22,6 @@ mod facts; pub mod instantiations; mod model; mod resolve; -mod scan; pub mod words; mod workspace; diff --git a/crates/vlog_semantic/src/scan.rs b/crates/vlog_semantic/src/scan.rs deleted file mode 100644 index b1f7970..0000000 --- a/crates/vlog_semantic/src/scan.rs +++ /dev/null @@ -1,193 +0,0 @@ -//! Recovering the byte range of a name the AST kept only as a `String`. -//! -//! Most declarations in `vlog_parser`'s AST store their name as a plain -//! `String` and give a span only for the whole construct (`module m ... `, -//! `input logic [W-1:0] d`). A language server needs the range of the *name*, -//! so this scans the construct's own source text for it. See the README's -//! Handshakes section: once the parser carries `name_span` on those nodes, -//! this module goes away. - -use vlog_parser::span::TextRange; - -/// A cursor over one source window that hands out the ranges of successive -/// identifiers, skipping comments, strings and macro invocations. -pub(crate) struct NameScanner<'a> { - src: &'a [u8], - pos: usize, - end: usize, -} - -impl<'a> NameScanner<'a> { - /// A scanner over `window` of `src`. - pub(crate) fn new(src: &'a str, window: TextRange) -> Self { - let end = (window.end as usize).min(src.len()); - let pos = (window.start as usize).min(end); - NameScanner { src: src.as_bytes(), pos, end } - } - - /// The range of the next whole-word `name`, or `None` if the window holds - /// no more. The cursor moves past what it returns, so repeated calls walk - /// a list (`genvar i, j;`) left to right. - pub(crate) fn find(&mut self, name: &str) -> Option { - while let Some(word) = self.next_word() { - if &self.src[word.as_range()] == name.as_bytes() { - return Some(word); - } - } - None - } - - /// The range of the next identifier of any spelling. - fn next_word(&mut self) -> Option { - while self.pos < self.end { - let b = self.src[self.pos]; - match b { - b'/' if self.peek(1) == Some(b'/') => self.skip_line(), - b'/' if self.peek(1) == Some(b'*') => self.skip_block_comment(), - b'"' => self.skip_string(), - // A macro invocation is one opaque token: `` `WIDTH `` must - // not answer a search for the identifier `WIDTH`. - b'`' => { - self.pos += 1; - self.skip_word(); - } - _ if is_ident_start(b) => { - let start = self.pos; - self.skip_word(); - return Some(TextRange::new(start as u32, self.pos as u32)); - } - _ => self.pos += 1, - } - } - None - } - - fn peek(&self, n: usize) -> Option { - self.src.get(self.pos + n).copied() - } - - fn skip_word(&mut self) { - // An escaped identifier (`\a+b `) runs to the next whitespace. - if self.src.get(self.pos) == Some(&b'\\') { - self.pos += 1; - while self.pos < self.end && !self.src[self.pos].is_ascii_whitespace() { - self.pos += 1; - } - return; - } - while self.pos < self.end && is_ident_continue(self.src[self.pos]) { - self.pos += 1; - } - } - - fn skip_line(&mut self) { - while self.pos < self.end && self.src[self.pos] != b'\n' { - self.pos += 1; - } - } - - fn skip_block_comment(&mut self) { - self.pos += 2; - while self.pos < self.end { - if self.src[self.pos] == b'*' && self.peek(1) == Some(b'/') { - self.pos += 2; - return; - } - self.pos += 1; - } - } - - fn skip_string(&mut self) { - self.pos += 1; - while self.pos < self.end { - match self.src[self.pos] { - b'\\' => self.pos += 2, - b'"' => { - self.pos += 1; - return; - } - _ => self.pos += 1, - } - } - } -} - -fn is_ident_start(b: u8) -> bool { - b.is_ascii_alphabetic() || b == b'_' || b == b'$' || b == b'\\' -} - -fn is_ident_continue(b: u8) -> bool { - b.is_ascii_alphanumeric() || b == b'_' || b == b'$' -} - -/// The range of `name` inside `window`, or an empty range at the window start -/// when the scan comes up empty (a name the source spells differently — an -/// escaped identifier, or text a macro produced). -pub(crate) fn name_span(src: &str, window: TextRange, name: &str) -> TextRange { - NameScanner::new(src, window).find(name).unwrap_or(TextRange::empty(window.start)) -} - -/// The range of `name` written *after* the first `kw` in `window`. Used where -/// the construct starts with a keyword and the name follows it, possibly -/// past qualifiers (`function automatic int f`). -pub(crate) fn name_after_kw(src: &str, window: TextRange, kw: &str, name: &str) -> TextRange { - let mut scanner = NameScanner::new(src, window); - if scanner.find(kw).is_none() { - return TextRange::empty(window.start); - } - scanner.find(name).unwrap_or(TextRange::empty(window.start)) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn whole(src: &str) -> TextRange { - TextRange::new(0, src.len() as u32) - } - - #[test] - fn finds_a_name_after_its_keyword() { - let src = "module top (input a);"; - let span = name_after_kw(src, whole(src), "module", "top"); - assert_eq!(&src[span.as_range()], "top"); - assert_eq!(span.start, 7); - } - - #[test] - fn skips_comments_and_strings() { - let src = "/* d */ \"d\" // d\n d;"; - let span = name_span(src, whole(src), "d"); - assert_eq!(span.start, 18); - } - - #[test] - fn matches_whole_words_only() { - let src = "input wire [W-1:0] w;"; - let span = name_span(src, whole(src), "w"); - assert_eq!(&src[span.as_range()], "w"); - assert_eq!(span.start, 19); - } - - #[test] - fn a_macro_invocation_is_one_opaque_token() { - let src = "`WIDTH WIDTH"; - let span = name_span(src, whole(src), "WIDTH"); - assert_eq!(span.start, 7); - } - - #[test] - fn a_name_that_is_not_there_gives_an_empty_range() { - let src = "module m;"; - let span = name_span(src, whole(src), "nope"); - assert!(span.is_empty()); - } - - #[test] - fn successive_finds_walk_a_list() { - let src = "genvar i, j;"; - let mut scanner = NameScanner::new(src, whole(src)); - assert_eq!(scanner.find("i").map(|s| s.start), Some(7)); - assert_eq!(scanner.find("j").map(|s| s.start), Some(10)); - } -} diff --git a/docs/features/type-name-spans/README.md b/docs/features/type-name-spans/README.md new file mode 100644 index 0000000..bc1c55e --- /dev/null +++ b/docs/features/type-name-spans/README.md @@ -0,0 +1,453 @@ +# Type-name spans + +## Goal + +TODO.md §47 / `docs/topo.md` §2.9-2. `vlog_semantic/src/scan.rs` (193 lines) +recovered the byte range of a name the AST kept only as a `String` by scanning +the construct's own source text. Every declared name got a real `name_span` +from the parser in the 2026-08-19 `name-spans` round; two *uses* did not, and +they were the module's only remaining callers — the type name of a declaration +(`DataType::name`, split as `pkg::item` or `iface.modport`) and `disable +