From 901a78ccb2e24fa5767f949525d772e692f13e6b Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Wed, 19 Aug 2026 04:44:51 -0700 Subject: [PATCH] Add spans: byte ranges on every token and AST node, plus LineIndex MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The LSP cornerstone (TODO §6) and the prerequisite for format-off fences and range formatting. Convention: node span = code extent (first to last token; attributes included, comments excluded and carrying their own spans) — chosen because it makes child-nests-in- parent a total, assertable invariant. Expr became {kind, span}; element structs carry spans; payload structs whose extent equals their wrapper's deliberately don't (one fact, one place). LineIndex maps offset <-> 1-based line:col in UTF-8 bytes, with clamping. A token-level losslessness test asserts every source byte is covered by token/trivia spans (whitespace aside) and concatenation reconstructs the input — it immediately surfaced and documented two pre-existing lexer normalizations (sized-literal tick spacing, merged same-line trailing comments), both whitespace-only. Zero behavior change, proven: corpus TSV md5-identical, and QA diffed formatter output on all 820 corpus files against a pre-spans worktree binary — no differences. Mutation-tested by dev and QA; one unpinned span QA found (GenIf content) is now pinned by a lead-added slice test. 161 workspace tests. Dev: Opus agent; QA: Sonnet agent; review in docs/features/spans/README.md. Co-Authored-By: Claude Fable 5 --- TODO.md | 10 +- crates/vlog_formatter/src/format.rs | 68 +-- crates/vlog_parser/src/ast.rs | 67 ++- crates/vlog_parser/src/lexer.rs | 70 ++- crates/vlog_parser/src/lib.rs | 4 + crates/vlog_parser/src/line_index.rs | 154 +++++++ crates/vlog_parser/src/parser.rs | 336 +++++++++++---- crates/vlog_parser/src/span.rs | 83 ++++ crates/vlog_parser/src/token.rs | 10 + crates/vlog_parser/tests/spans.rs | 618 +++++++++++++++++++++++++++ docs/features/spans/README.md | 539 +++++++++++++++++++++++ 11 files changed, 1831 insertions(+), 128 deletions(-) create mode 100644 crates/vlog_parser/src/line_index.rs create mode 100644 crates/vlog_parser/src/span.rs create mode 100644 crates/vlog_parser/tests/spans.rs create mode 100644 docs/features/spans/README.md diff --git a/TODO.md b/TODO.md index 3a0472c..b7a03ab 100644 --- a/TODO.md +++ b/TODO.md @@ -73,11 +73,13 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both. ## 3. CLI / UX (mostly ruff) -- [ ] **[R] Config file discovery.** Search upward from each input file for +- [x] **[R] Config file discovery.** Search upward from each input file for `vfmt.toml` / `.vfmt.toml` (analog of `ruff.toml` / `pyproject.toml`). Keys: `line-length`, `indent`, `exclude` globs. CLI flags override file config. Keep Verible's philosophy of *few* knobs — don't grow a clang-format-sized option surface. + → `crates/vfmt/src/config.rs`; discovery rule, TOML subset and + precedence in `docs/features/config-discovery/README.md`. - [ ] **[R] Parallel file processing.** ruff's speed story is embarrassing parallelism over files. `main.rs` formats serially; use `rayon` par_iter over the collected file list (formatting is already pure). @@ -199,10 +201,14 @@ Vim/Neovim via built-in LSP config); no editor-specific logic below the protocol layer. Foundation decisions that are cheap now and expensive later: -- [ ] **Byte spans on every token and AST node.** Prerequisite for +- [x] **Byte spans on every token and AST node.** Prerequisite for everything in this section (and for §2 fences/range formatting). `token.rs` / `ast.rs` should carry `TextRange { start, end }` offsets; add a line-index utility (ruff's `ruff_source_file`) for offset↔line:col. + → `docs/features/spans/README.md`. `vlog_parser::span::TextRange` on every + token, comment and node; `vlog_parser::line_index::LineIndex` for + offset↔line:col; token-level losslessness is a test + (`crates/vlog_parser/tests/spans.rs`). - [ ] **Error-tolerant parsing mode.** A formatter may refuse broken input; an LSP cannot — code is mid-edit most of the time. Add recovery in `parser.rs`: on statement-level error, record a diagnostic, skip to a diff --git a/crates/vlog_formatter/src/format.rs b/crates/vlog_formatter/src/format.rs index f718747..77668f7 100644 --- a/crates/vlog_formatter/src/format.rs +++ b/crates/vlog_formatter/src/format.rs @@ -604,23 +604,23 @@ impl<'a> Fmt<'a> { /// operators lose their surrounding spaces (`[WIDTH-1:0]`), and no line /// breaks are introduced. fn expr_compact(&self, e: &Expr) -> Doc { - match e { - Expr::Binary { lhs, op, rhs, .. } => { + match &e.kind { + ExprKind::Binary { lhs, op, rhs, .. } => { let tight = Self::binary_prec(op) >= 8; let sep = if tight { op.clone() } else { format!(" {op} ") }; concat(vec![self.expr_compact(lhs), text(sep), self.expr_compact(rhs)]) } - Expr::Ternary { cond, then, els, .. } => concat(vec![ + ExprKind::Ternary { cond, then, els, .. } => concat(vec![ self.expr_compact(cond), text(" ? "), self.expr_compact(then), text(" : "), self.expr_compact(els), ]), - Expr::Paren { inner, .. } => { + ExprKind::Paren { inner, .. } => { concat(vec![text("("), self.expr_compact(inner), text(")")]) } - Expr::Unary { op, expr } => concat(vec![text(op.clone()), self.expr_compact(expr)]), + ExprKind::Unary { op, expr } => concat(vec![text(op.clone()), self.expr_compact(expr)]), _ => self.expr(e), } } @@ -962,7 +962,7 @@ impl<'a> Fmt<'a> { } match &c.expr { None => text(format!(".{}", c.name)), - Some(Expr::Empty(comments)) => { + Some(Expr { kind: ExprKind::Empty(comments), .. }) => { let mut docs = vec![text(format!(".{}(", c.name))]; let mut ends_line = false; for cm in comments { @@ -1594,15 +1594,15 @@ impl<'a> Fmt<'a> { } fn expr(&self, e: &Expr) -> Doc { - match e { - Expr::Ident(s) => text(s.clone()), - Expr::Number(s) => text(s.clone()), - Expr::Str(s) => text(s.clone()), + match &e.kind { + ExprKind::Ident(s) => text(s.clone()), + ExprKind::Number(s) => text(s.clone()), + ExprKind::Str(s) => text(s.clone()), // Only reachable through `connection`, which handles the comments. - Expr::Empty(_) => text(""), - Expr::Unary { op, expr } => concat(vec![text(op.clone()), self.expr(expr)]), - Expr::Binary { .. } => self.binary_chain(e), - Expr::Ternary { cond, then, els, comments } => { + ExprKind::Empty(_) => text(""), + ExprKind::Unary { op, expr } => concat(vec![text(op.clone()), self.expr(expr)]), + ExprKind::Binary { .. } => self.binary_chain(e), + ExprKind::Ternary { cond, then, els, comments } => { if comments.is_empty() { return group(vec![ self.expr(cond), @@ -1618,13 +1618,13 @@ impl<'a> Fmt<'a> { } self.ternary_with_comments(cond, then, els, comments) } - Expr::Call { callee, args } => { + ExprKind::Call { callee, args } => { concat(vec![self.expr(callee), self.expr_list("(", args, ")")]) } - Expr::Index { base, index } => { + ExprKind::Index { base, index } => { concat(vec![self.expr(base), text("["), self.expr_compact(index), text("]")]) } - Expr::Range { base, op, msb, lsb } => concat(vec![ + ExprKind::Range { base, op, msb, lsb } => concat(vec![ self.expr(base), text("["), self.expr_compact(msb), @@ -1632,10 +1632,14 @@ impl<'a> Fmt<'a> { self.expr_compact(lsb), text("]"), ]), - Expr::Member { base, name } => concat(vec![self.expr(base), text(format!(".{name}"))]), - Expr::Scope { base, name } => concat(vec![self.expr(base), text(format!("::{name}"))]), - Expr::Concat(items) => self.expr_list("{", items, "}"), - Expr::Repl { count, inner } => { + ExprKind::Member { base, name } => { + concat(vec![self.expr(base), text(format!(".{name}"))]) + } + ExprKind::Scope { base, name } => { + concat(vec![self.expr(base), text(format!("::{name}"))]) + } + ExprKind::Concat(items) => self.expr_list("{", items, "}"), + ExprKind::Repl { count, inner } => { let inner_docs: Vec = inner.iter().map(|i| self.expr(i)).collect(); concat(vec![ text("{"), @@ -1645,7 +1649,7 @@ impl<'a> Fmt<'a> { text("}}"), ]) } - Expr::Paren { inner, before, after } => { + ExprKind::Paren { inner, before, after } => { if before.is_empty() && after.is_empty() { return self.parens(inner); } @@ -1667,10 +1671,10 @@ impl<'a> Fmt<'a> { outer.push(text(")")); group(outer) } - Expr::Cast { ty, expr } => { + ExprKind::Cast { ty, expr } => { concat(vec![text(format!("{ty}'(")), self.expr(expr), text(")")]) } - Expr::AssignPattern(items) => { + ExprKind::AssignPattern(items) => { let items: Vec = items .iter() .map(|pi| { @@ -1685,15 +1689,15 @@ impl<'a> Fmt<'a> { .collect(); self.delimited("'{", items, "}", false) } - Expr::Postfix { expr, op } => concat(vec![self.expr(expr), text(op.clone())]), - Expr::Inside { lhs, ranges } => { + ExprKind::Postfix { expr, op } => concat(vec![self.expr(expr), text(op.clone())]), + ExprKind::Inside { lhs, ranges } => { concat(vec![self.expr(lhs), text(" inside "), self.expr_list("{", ranges, "}")]) } - Expr::ValueRange { lo, hi } => { + ExprKind::ValueRange { lo, hi } => { concat(vec![text("["), self.expr(lo), text(":"), self.expr(hi), text("]")]) } - Expr::Type(ty) => self.data_type(ty).unwrap_or_else(|| text("")), - Expr::MinTypMax { min, typ, max } => { + ExprKind::Type(ty) => self.data_type(ty).unwrap_or_else(|| text("")), + ExprKind::MinTypMax { min, typ, max } => { concat(vec![self.expr(min), text(":"), self.expr(typ), text(":"), self.expr(max)]) } } @@ -1732,7 +1736,7 @@ impl<'a> Fmt<'a> { /// carrying comments (written after the operand before it) starts its own /// line, so the comment stays last on the line it was written on. fn binary_chain(&self, e: &Expr) -> Doc { - let Expr::Binary { op, .. } = e else { unreachable!() }; + let ExprKind::Binary { op, .. } = &e.kind else { unreachable!() }; let prec = Self::binary_prec(op); let mut operands: Vec<&Expr> = Vec::new(); let mut ops: Vec> = Vec::new(); @@ -1742,8 +1746,8 @@ impl<'a> Fmt<'a> { operands: &mut Vec<&'e Expr>, ops: &mut Vec>, ) { - match e { - Expr::Binary { lhs, op, rhs, comments } if Fmt::binary_prec(op) == prec => { + match &e.kind { + ExprKind::Binary { lhs, op, rhs, comments } if Fmt::binary_prec(op) == prec => { walk(lhs, prec, operands, ops); ops.push(BinaryOp { op, before: &comments.before, after: &comments.after }); operands.push(rhs); diff --git a/crates/vlog_parser/src/ast.rs b/crates/vlog_parser/src/ast.rs index 46e41db..ddfac0e 100644 --- a/crates/vlog_parser/src/ast.rs +++ b/crates/vlog_parser/src/ast.rs @@ -3,7 +3,14 @@ //! Nodes that begin a line carry a [`Meta`] with leading comments, an //! optional trailing comment, and a blank-line-before flag so the formatter //! can reproduce vertical structure the way ruff's formatter does. +//! +//! Spans: a node's `span` is its **code extent** — from the first to the last +//! token of the construct itself. Attached comments are *not* part of it and +//! carry their own spans on [`Comment`]; attribute instances `(* ... *)` are +//! real tokens and *are* inside it. See `docs/features/spans/README.md` for +//! which node types carry a span and why the rest do not. +use crate::span::TextRange; use crate::token::Comment; #[derive(Debug, Clone, Default)] @@ -23,6 +30,8 @@ pub struct Meta { pub struct RawText { pub text: String, pub col: u32, + /// Byte extent of the passed-through token. + pub span: TextRange, } /// A macro invocation standing where a module item or a statement belongs @@ -43,12 +52,16 @@ pub struct SourceFile { pub items: Vec, /// Comments at the very end of the file. pub dangling: Vec, + /// The whole source text: `0..len`. + pub span: TextRange, } #[derive(Debug)] pub struct Item { pub meta: Meta, pub kind: ItemKind, + /// Code extent of the item, its `(* ... *)` attributes included. + pub span: TextRange, } #[derive(Debug)] @@ -133,6 +146,8 @@ pub enum PortList { pub struct NonAnsiPort { pub meta: Meta, pub name: String, + /// Code extent of the port name. + pub span: TextRange, } #[derive(Debug)] @@ -144,6 +159,8 @@ pub struct AnsiPort { pub name: String, pub unpacked: Vec, pub default: Option, + /// Code extent of the port declaration. + pub span: TextRange, } #[derive(Debug)] @@ -156,6 +173,8 @@ pub struct ParamPort { pub name: String, pub unpacked: Vec, pub default: Option, + /// Code extent of the parameter port. + pub span: TextRange, } /// A data type: keyword or user-defined name, plus signing and packed dims. @@ -178,6 +197,8 @@ impl DataType { pub struct Dim { pub a: Expr, pub b: Option, + /// Code extent including the brackets. + pub span: TextRange, } #[derive(Debug)] @@ -206,6 +227,8 @@ pub struct EnumMember { pub meta: Meta, pub name: String, pub value: Option, + /// Code extent of the member. + pub span: TextRange, } #[derive(Debug)] @@ -223,6 +246,8 @@ pub struct StructMember { pub meta: Meta, pub ty: DataType, pub declarators: Vec, + /// Code extent of the member, its `;` included. + pub span: TextRange, } #[derive(Debug)] @@ -261,6 +286,8 @@ pub struct Declarator { /// `=` for variables; net declarations also use this for the initial /// continuous assignment. pub init: Option, + /// Code extent of the declarator. + pub span: TextRange, } #[derive(Debug)] @@ -278,6 +305,8 @@ pub struct AssignPair { /// Comments written between the `=` and the right-hand side. Kept here so /// they print on the `=`'s side of the value instead of drifting into it. pub rhs_comments: Vec, + /// Code extent of `lhs = rhs`. + pub span: TextRange, } #[derive(Debug)] @@ -328,6 +357,8 @@ pub struct Instance { pub name: String, pub dims: Vec, pub conns: Connections, + /// Code extent of the instance, its connection list included. + pub span: TextRange, } #[derive(Debug)] @@ -340,6 +371,8 @@ pub enum Connections { pub struct OrderedConn { pub meta: Meta, pub expr: Option, + /// Code extent of the connection; empty for an omitted one. + pub span: TextRange, } #[derive(Debug)] @@ -350,6 +383,8 @@ pub struct Connection { /// `None` for `.name` (implicit) and `.*`; `Some` for `.name(expr)`. /// An explicitly empty connection `.name()` is `Some(Expr::Empty)`. pub expr: Option, + /// Code extent of the connection. + pub span: TextRange, } #[derive(Debug)] @@ -365,6 +400,8 @@ pub struct GateInstance { pub meta: Meta, pub name: Option, pub args: Vec, + /// Code extent of the gate instance. + pub span: TextRange, } #[derive(Debug)] @@ -372,6 +409,8 @@ pub struct GenIf { pub cond: Expr, pub then: GenBlock, pub els: Option>, + /// Code extent of the whole `if`, its `else` branch included. + pub span: TextRange, } #[derive(Debug)] @@ -403,6 +442,8 @@ pub struct GenCaseItem { /// it, so a comment between two labels stays between them. pub labels: Vec, pub body: GenBlock, + /// Code extent of the case item, its body included. + pub span: TextRange, } /// A single generate block: either a labeled/unlabeled begin..end with items, @@ -415,6 +456,8 @@ pub struct GenBlock { pub dangling: Vec, /// Label after `end :`. pub end_label: Option, + /// Code extent of the block or of the single item it holds. + pub span: TextRange, } #[derive(Debug)] @@ -452,12 +495,16 @@ pub struct TfArg { pub name: String, pub unpacked: Vec, pub default: Option, + /// Code extent of the argument declaration. + pub span: TextRange, } #[derive(Debug)] pub struct Stmt { pub meta: Meta, pub kind: StmtKind, + /// Code extent of the statement, its `(* ... *)` attributes included. + pub span: TextRange, } #[derive(Debug)] @@ -579,6 +626,8 @@ pub struct CaseItem { /// it, so a comment between two labels stays between them. pub labels: Vec, pub stmt: Stmt, + /// Code extent of the case item, its body included. + pub span: TextRange, } #[derive(Debug)] @@ -601,8 +650,20 @@ pub enum ForStep { Expr(Expr), } +/// An expression: its code extent plus what it is. +/// +/// The span sits on this wrapper rather than on each [`ExprKind`] variant so +/// that "the span of any expression" is one field access no matter which +/// variant it is — the same shape [`Item`] and [`Stmt`] already have. #[derive(Debug, Clone)] -pub enum Expr { +pub struct Expr { + pub kind: ExprKind, + /// Code extent of the expression. + pub span: TextRange, +} + +#[derive(Debug, Clone)] +pub enum ExprKind { Ident(String), Number(String), Str(String), @@ -737,6 +798,8 @@ pub struct PatternItem { /// `key: value` (key may be `default`, a type, or an expression). pub key: Option, pub value: Expr, + /// Code extent of the pattern element. + pub span: TextRange, } /// One element of a bracketed expression list (a concatenation, a call @@ -746,4 +809,6 @@ pub struct PatternItem { pub struct ExprItem { pub meta: Meta, pub expr: Expr, + /// Code extent of the element. + pub span: TextRange, } diff --git a/crates/vlog_parser/src/lexer.rs b/crates/vlog_parser/src/lexer.rs index ab26f3b..9ae802d 100644 --- a/crates/vlog_parser/src/lexer.rs +++ b/crates/vlog_parser/src/lexer.rs @@ -6,6 +6,7 @@ //! leading/trailing trivia and records blank-line information. The parser and //! formatter then never have to think about interleaved comment tokens. +use crate::span::TextRange; use crate::token::{is_keyword, Comment, Token, TokenKind}; #[derive(Debug, Clone)] @@ -29,6 +30,8 @@ struct RawTok { text: String, line: u32, col: u32, + /// Byte extent in the source text. + span: TextRange, /// Number of newlines seen between the previous raw token and this one. newlines_before: u32, } @@ -96,6 +99,19 @@ impl<'a> RawLexer<'a> { String::from_utf8_lossy(&self.src[start..self.pos]).into_owned() } + /// The byte extent from `start` to the cursor. + fn span_from(&self, start: usize) -> TextRange { + TextRange::new(start as u32, self.pos as u32) + } + + /// The extent of a token whose text was trimmed at the end (a line + /// comment, a compiler directive): the trailing whitespace the trim + /// dropped is not part of the token, so the span stops where its text + /// does and `source[span] == text` still holds. + fn span_of_trimmed(&self, start: usize, text: &str) -> TextRange { + TextRange::new(start as u32, (start + text.len()) as u32) + } + /// Skip spaces/tabs/newlines, returning how many newlines were skipped. fn skip_whitespace(&mut self) -> u32 { let mut newlines = 0; @@ -122,6 +138,7 @@ impl<'a> RawLexer<'a> { text: String::new(), line, col, + span: self.span_from(start), newlines_before, }); } @@ -134,12 +151,28 @@ impl<'a> RawLexer<'a> { self.bump(); } let text = self.text_from(start).trim_end().to_string(); - return Ok(RawTok { kind: RawKind::LineComment, text, line, col, newlines_before }); + let span = self.span_of_trimmed(start, &text); + return Ok(RawTok { + kind: RawKind::LineComment, + text, + line, + col, + span, + newlines_before, + }); } if c == b'/' && self.peek_at(1) == b'*' { self.skip_block_comment()?; let text = self.text_from(start); - return Ok(RawTok { kind: RawKind::BlockComment, text, line, col, newlines_before }); + let span = self.span_from(start); + return Ok(RawTok { + kind: RawKind::BlockComment, + text, + line, + col, + span, + newlines_before, + }); } // Compiler directives: capture through end of line, honoring `\` @@ -169,11 +202,13 @@ impl<'a> RawLexer<'a> { .take_while(|ch| ch.is_ascii_alphanumeric() || *ch == '_') .collect(); if is_line_directive(&first_word) { + let span = self.span_of_trimmed(start, &text); return Ok(RawTok { kind: RawKind::Real(TokenKind::Directive), text, line, col, + span, newlines_before, }); } @@ -196,6 +231,7 @@ impl<'a> RawLexer<'a> { text, line, col, + span: self.span_from(start), newlines_before, }); } @@ -221,6 +257,7 @@ impl<'a> RawLexer<'a> { text, line, col, + span: self.span_from(start), newlines_before, }); } @@ -234,6 +271,7 @@ impl<'a> RawLexer<'a> { text, line, col, + span: self.span_from(start), newlines_before, }); } @@ -250,6 +288,7 @@ impl<'a> RawLexer<'a> { text, line, col, + span: self.span_from(start), newlines_before, }); } @@ -266,11 +305,14 @@ impl<'a> RawLexer<'a> { text, line, col, + span: self.span_from(start), newlines_before, }); } - // Number literals. + // Number literals. The text is normalized (whitespace around the tick + // of `8 'hFF` is dropped), so this is the one token kind whose text + // can be shorter than `source[span]`; the span is the real extent. if c.is_ascii_digit() { let text = self.lex_number()?; return Ok(RawTok { @@ -278,6 +320,7 @@ impl<'a> RawLexer<'a> { text, line, col, + span: self.span_from(start), newlines_before, }); } @@ -291,6 +334,7 @@ impl<'a> RawLexer<'a> { text, line, col, + span: self.span_from(start), newlines_before, }); } @@ -302,7 +346,15 @@ impl<'a> RawLexer<'a> { } let text = self.text_from(start); let kind = if is_keyword(&text) { TokenKind::Keyword } else { TokenKind::Ident }; - return Ok(RawTok { kind: RawKind::Real(kind), text, line, col, newlines_before }); + let span = self.span_from(start); + return Ok(RawTok { + kind: RawKind::Real(kind), + text, + line, + col, + span, + newlines_before, + }); } // Operators, longest match first. @@ -316,6 +368,7 @@ impl<'a> RawLexer<'a> { text: (*op).to_string(), line, col, + span: self.span_from(start), newlines_before, }); } @@ -327,6 +380,7 @@ impl<'a> RawLexer<'a> { text: (c as char).to_string(), line, col, + span: self.span_from(start), newlines_before, }); } @@ -619,14 +673,21 @@ pub fn tokenize(source: &str) -> Result, LexError> { blank_before: raw.newlines_before > 1 || pending_blank, line: raw.line, col: raw.col, + span: raw.span, }; if same_line_as_prev { // Trailing comment for the previous real token. let prev = tokens.last_mut().unwrap(); match &mut prev.trailing { Some(existing) => { + // Two comments on one line become one node, so its + // span has to cover both — the merge normalizes + // the gap between them to a single space, which is + // why a merged comment is the one comment whose + // text can differ from `source[span]`. existing.text.push(' '); existing.text.push_str(&comment.text); + existing.span = TextRange::new(existing.span.start, comment.span.end); } None => prev.trailing = Some(comment), } @@ -649,6 +710,7 @@ pub fn tokenize(source: &str) -> Result, LexError> { text: raw.text, line: raw.line, col: raw.col, + span: raw.span, leading: std::mem::take(&mut pending), trailing: None, blank_before, diff --git a/crates/vlog_parser/src/lib.rs b/crates/vlog_parser/src/lib.rs index 92b4db9..005eb5d 100644 --- a/crates/vlog_parser/src/lib.rs +++ b/crates/vlog_parser/src/lib.rs @@ -6,11 +6,15 @@ pub mod ast; pub mod lexer; +pub mod line_index; pub mod parser; +pub mod span; pub mod token; pub use lexer::{tokenize, LexError}; +pub use line_index::LineIndex; pub use parser::{parse, ParseError}; +pub use span::TextRange; /// Convenience: lex and parse in one step. pub fn parse_source(source: &str) -> Result { diff --git a/crates/vlog_parser/src/line_index.rs b/crates/vlog_parser/src/line_index.rs new file mode 100644 index 0000000..35eef39 --- /dev/null +++ b/crates/vlog_parser/src/line_index.rs @@ -0,0 +1,154 @@ +//! Offset ↔ line:column conversion for one source file. +//! +//! The lexer records line/col as it goes, which is all a parse diagnostic +//! needs. A language server needs the opposite direction too — an editor sends +//! positions and expects byte ranges back — so this builds the table once and +//! answers both. It is the analog of ruff's `ruff_source_file::LineIndex`. + +use crate::span::TextRange; + +/// Byte offsets of the start of every line in one source text. +/// +/// Lines and columns are **1-based**; a column is a **UTF-8 byte** offset +/// within its line, the same unit [`TextRange`] uses, so `col - 1` bytes +/// separate the line start from the position. +#[derive(Debug, Clone)] +pub struct LineIndex { + /// `line_starts[n]` is the offset of line `n + 1`. Never empty. + line_starts: Vec, + len: u32, +} + +impl LineIndex { + /// Build the index for `text`. + pub fn new(text: &str) -> Self { + let mut line_starts = vec![0u32]; + for (i, b) in text.bytes().enumerate() { + if b == b'\n' { + line_starts.push(i as u32 + 1); + } + } + LineIndex { line_starts, len: text.len() as u32 } + } + + /// How many lines the text has. A trailing newline opens a last, empty + /// line, so `"a\n"` has two. + pub fn line_count(&self) -> u32 { + self.line_starts.len() as u32 + } + + /// The 1-based line and column of a byte offset. An offset past the end + /// of the text is clamped to the end. + pub fn line_col(&self, offset: u32) -> (u32, u32) { + let offset = offset.min(self.len); + // The last line whose start is <= offset. + let line = self.line_starts.partition_point(|&s| s <= offset); + (line as u32, offset - self.line_starts[line - 1] + 1) + } + + /// The byte offset of a 1-based line and column, or `None` if the text + /// has no such line. A column past the end of its line is clamped to the + /// line's end, so the result never lands on another line. + pub fn offset(&self, line: u32, col: u32) -> Option { + if line == 0 || line > self.line_count() { + return None; + } + let start = self.line_starts[line as usize - 1]; + let end = self.line_end(line); + Some((start + col.max(1) - 1).min(end)) + } + + /// The byte range of a 1-based line, excluding its terminating newline. + pub fn line_range(&self, line: u32) -> Option { + if line == 0 || line > self.line_count() { + return None; + } + Some(TextRange::new(self.line_starts[line as usize - 1], self.line_end(line))) + } + + /// Offset of the end of a line, excluding its `\n`. Assumes `line` is in + /// range. + fn line_end(&self, line: u32) -> u32 { + match self.line_starts.get(line as usize) { + // The next line starts one past this line's `\n`. + Some(&next) => next - 1, + None => self.len, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn empty_file() { + let idx = LineIndex::new(""); + assert_eq!(idx.line_count(), 1); + assert_eq!(idx.line_col(0), (1, 1)); + assert_eq!(idx.offset(1, 1), Some(0)); + assert_eq!(idx.offset(2, 1), None); + assert_eq!(idx.line_range(1), Some(TextRange::new(0, 0))); + } + + #[test] + fn no_trailing_newline() { + let src = "module m;\nendmodule"; + let idx = LineIndex::new(src); + assert_eq!(idx.line_count(), 2); + assert_eq!(idx.line_col(0), (1, 1)); + assert_eq!(idx.line_col(9), (1, 10)); // the `;` + assert_eq!(idx.line_col(10), (2, 1)); // `e` of endmodule + assert_eq!(idx.offset(2, 1), Some(10)); + assert_eq!(idx.line_range(2), Some(TextRange::new(10, src.len() as u32))); + } + + #[test] + fn trailing_newline_opens_an_empty_last_line() { + let idx = LineIndex::new("a\n"); + assert_eq!(idx.line_count(), 2); + assert_eq!(idx.line_col(2), (2, 1)); + assert_eq!(idx.offset(2, 1), Some(2)); + assert_eq!(idx.line_range(2), Some(TextRange::new(2, 2))); + } + + #[test] + fn crlf_puts_the_carriage_return_in_the_line() { + // `\r` is an ordinary byte of the line it ends; only `\n` breaks. + let src = "ab\r\ncd\r\n"; + let idx = LineIndex::new(src); + assert_eq!(idx.line_count(), 3); + assert_eq!(idx.line_col(2), (1, 3)); // the `\r` + assert_eq!(idx.line_col(4), (2, 1)); // `c` + assert_eq!(idx.offset(2, 1), Some(4)); + assert_eq!(idx.line_range(1), Some(TextRange::new(0, 3))); + } + + #[test] + fn multibyte_utf8_columns_are_byte_offsets() { + // `λ` and `äöü` are 2 bytes each per char. + let src = "// λ comment\nwire ω; // äöü\n"; + let idx = LineIndex::new(src); + let lambda = src.find('λ').unwrap() as u32; + assert_eq!(idx.line_col(lambda), (1, 4)); + assert_eq!(idx.offset(1, 4), Some(lambda)); + let omega = src.find('ω').unwrap() as u32; + assert_eq!(idx.line_col(omega), (2, 6)); + // Round-trip every byte offset in the file, multi-byte or not. + for off in 0..=src.len() as u32 { + let (l, c) = idx.line_col(off); + assert_eq!(idx.offset(l, c), Some(off), "round trip at byte {off}"); + } + } + + #[test] + fn out_of_range_positions_are_clamped() { + let src = "abc\nde"; + let idx = LineIndex::new(src); + assert_eq!(idx.line_col(999), (2, 3), "past the end clamps to the end"); + assert_eq!(idx.offset(1, 99), Some(3), "a long column stops before the newline"); + assert_eq!(idx.offset(2, 99), Some(6)); + assert_eq!(idx.offset(0, 1), None); + assert_eq!(idx.offset(3, 1), None); + } +} diff --git a/crates/vlog_parser/src/parser.rs b/crates/vlog_parser/src/parser.rs index e3c9fde..526ae9d 100644 --- a/crates/vlog_parser/src/parser.rs +++ b/crates/vlog_parser/src/parser.rs @@ -14,6 +14,7 @@ //! ordinary [`ParseError`]. use crate::ast::*; +use crate::span::TextRange; use crate::token::{Comment, Token, TokenKind}; #[derive(Debug, Clone)] @@ -173,6 +174,42 @@ impl Parser { Ok(()) } + // ------------------------------------------------------------------ + // Spans + // + // A node's span runs from the first token of the construct to the last + // one consumed for it. Comments are not in the token stream the parser + // walks — the lexer hung them off tokens as trivia — so they fall out of + // node spans for free, which is the convention documented in + // `docs/features/spans/README.md`. + // ------------------------------------------------------------------ + + /// Byte offset where the token at the cursor starts: the `start` of the + /// span of whatever construct is about to be parsed. + fn here(&self) -> u32 { + self.cur().span.start + } + + /// Byte offset just past the last token consumed. + fn last_end(&self) -> u32 { + match self.pos.checked_sub(1) { + Some(i) => self.tokens[i].span.end, + None => 0, + } + } + + /// Span from `start` through the last token consumed. A construct that + /// consumed nothing gets the empty span at `start`. + fn span_from(&self, start: u32) -> TextRange { + TextRange::new(start, self.last_end()) + } + + /// An expression node spanning from `start` through the last token + /// consumed. + fn expr_at(&self, start: u32, kind: ExprKind) -> Expr { + Expr { kind, span: self.span_from(start) } + } + fn error(&self, message: impl Into) -> PResult { let t = self.cur(); let shown = if t.kind == TokenKind::Eof { "" } else { t.text.as_str() }; @@ -261,9 +298,10 @@ impl Parser { /// One element of a bracketed expression list, with the comments written /// before it. The caller harvests the trailing comment after the comma. fn parse_expr_item(&mut self) -> PResult { + let start = self.here(); let meta = self.take_meta(); let expr = self.parse_expr()?; - Ok(ExprItem { meta, expr }) + Ok(ExprItem { meta, expr, span: self.span_from(start) }) } /// Continue a comma-separated expression list whose first element is @@ -289,7 +327,8 @@ impl Parser { /// started in. fn take_raw_text(&mut self) -> RawText { let col = self.cur().col; - RawText { text: self.bump().text, col } + let span = self.cur().span; + RawText { text: self.bump().text, col, span } } /// True when the macro usage at the cursor stands on its own as an item or @@ -406,7 +445,10 @@ impl Parser { items.push(self.parse_item()?); } let dangling = self.take_dangling(); - Ok(SourceFile { items, dangling }) + // The cursor is on the EOF token, whose empty span sits at the end of + // the source, so this covers the whole file. + let span = TextRange::new(0, self.cur().span.end); + Ok(SourceFile { items, dangling, span }) } /// Items nest through generate blocks and package bodies. Gated. @@ -418,6 +460,9 @@ impl Parser { } fn parse_item_inner(&mut self) -> PResult { + // Before the attribute loop: `(* keep *)` is code, not trivia, so it + // belongs inside the item's span. + let start = self.here(); let mut meta = self.take_meta(); while self.cur().kind == TokenKind::Attribute { meta.attrs.push(self.take_raw_text()); @@ -425,10 +470,11 @@ impl Parser { meta.leading.append(&mut tok.leading); } let kind = self.parse_item_kind()?; + let span = self.span_from(start); if meta.trailing.is_none() { meta.trailing = self.take_trailing(); } - Ok(Item { meta, kind }) + Ok(Item { meta, kind, span }) } fn parse_item_kind(&mut self) -> PResult { @@ -660,6 +706,7 @@ impl Parser { } fn parse_param_port(&mut self) -> PResult { + let start = self.here(); let mut meta = self.take_meta(); let kw = if self.cur().is_kw("parameter") || self.cur().is_kw("localparam") { Some(self.bump().text) @@ -669,6 +716,7 @@ impl Parser { if self.eat_kw("type") { let name = self.expect_ident()?; let default = if self.eat_sym("=") { Some(self.parse_type_expr()?) } else { None }; + let span = self.span_from(start); meta.trailing = self.take_trailing(); return Ok(ParamPort { meta, @@ -678,14 +726,16 @@ impl Parser { name, unpacked: Vec::new(), default, + span, }); } let ty = self.parse_opt_data_type()?; let name = self.expect_ident()?; let unpacked = self.parse_dims()?; let default = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None }; + let span = self.span_from(start); meta.trailing = self.take_trailing(); - Ok(ParamPort { meta, kw, ty, is_type: false, name, unpacked, default }) + Ok(ParamPort { meta, kw, ty, is_type: false, name, unpacked, default, span }) } /// The header port list plus the comments written before its closing `)`. @@ -735,11 +785,13 @@ impl Parser { } else { let mut ports = Vec::new(); loop { + let start = self.here(); let mut meta = self.take_meta(); let name = self.expect_ident()?; + let span = self.span_from(start); let more = self.eat_sym(","); meta.trailing = self.take_trailing(); - ports.push(NonAnsiPort { meta, name }); + ports.push(NonAnsiPort { meta, name, span }); if !more { break; } @@ -751,6 +803,7 @@ impl Parser { } fn parse_ansi_port(&mut self) -> PResult { + let start = self.here(); let mut meta = self.take_meta(); let dir = { let t = self.cur(); @@ -773,8 +826,9 @@ impl Parser { let name = self.expect_ident()?; let unpacked = self.parse_dims()?; let default = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None }; + let span = self.span_from(start); meta.trailing = self.take_trailing(); - Ok(AnsiPort { meta, dir, net, ty, name, unpacked, default }) + Ok(AnsiPort { meta, dir, net, ty, name, unpacked, default, span }) } /// Parse a possibly-implicit data type. Stops before the declarator name. @@ -819,25 +873,27 @@ impl Parser { fn parse_dims(&mut self) -> PResult> { let mut dims = Vec::new(); while self.cur().is_sym("[") { + let start = self.here(); self.bump(); let a = self.parse_expr()?; let b = if self.eat_sym(":") { Some(self.parse_expr()?) } else { None }; self.expect_sym("]")?; - dims.push(Dim { a, b }); + dims.push(Dim { a, b, span: self.span_from(start) }); } Ok(dims) } fn parse_type_expr(&mut self) -> PResult { + let start = self.here(); let ty = self.parse_opt_data_type()?; if ty.is_implicit() { // Fall back: a plain identifier type (e.g. `= my_type_t`). let name = self.expect_ident()?; let mut t = DataType { name, ..DataType::default() }; t.packed = self.parse_dims()?; - return Ok(Expr::Type(t)); + return Ok(self.expr_at(start, ExprKind::Type(t))); } - Ok(Expr::Type(ty)) + Ok(self.expr_at(start, ExprKind::Type(ty))) } // ------------------------------------------------------------------ @@ -855,17 +911,19 @@ impl Parser { fn parse_declarators(&mut self) -> PResult> { let mut out = Vec::new(); loop { + let start = self.here(); let mut meta = self.take_meta(); let name = self.expect_ident()?; let unpacked = self.parse_dims()?; let init = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None }; + let span = self.span_from(start); let more = self.eat_sym(","); // Harvested on the last declarator too: a comment written before // the `;` (`logic x /* verilator split_var */;`) belongs to the // declaration, and the `;` has not been consumed yet, so nothing // written after it can be picked up here. meta.trailing = self.take_trailing(); - out.push(Declarator { meta, name, unpacked, init }); + out.push(Declarator { meta, name, unpacked, init, span }); if !more { break; } @@ -934,13 +992,15 @@ impl Parser { self.expect_sym("{")?; let mut members = Vec::new(); loop { + let start = self.here(); let mut meta = self.take_meta(); let name = self.expect_ident()?; // Enum member ranges (`VAL[4]`) are rare; unsupported. let value = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None }; + let span = self.span_from(start); let more = self.eat_sym(","); meta.trailing = self.take_trailing(); - members.push(EnumMember { meta, name, value }); + members.push(EnumMember { meta, name, value, span }); if !more { break; } @@ -967,12 +1027,14 @@ impl Parser { self.expect_sym("{")?; let mut members = Vec::new(); while !self.cur().is_sym("}") && !self.at_eof() { + let start = self.here(); let mut meta = self.take_meta(); let ty = self.parse_opt_data_type()?; let declarators = self.parse_declarators()?; self.expect_sym(";")?; + let span = self.span_from(start); meta.trailing = self.take_trailing(); - members.push(StructMember { meta, ty, declarators }); + members.push(StructMember { meta, ty, declarators, span }); } let dangling = self.take_dangling(); self.expect_sym("}")?; @@ -1006,17 +1068,19 @@ impl Parser { }; let mut assigns = Vec::new(); loop { + let start = self.here(); let mut meta = self.take_meta(); let lhs = self.parse_unary()?; let mark = self.pending_trailing.len(); self.expect_sym("=")?; let rhs_comments = self.take_around(mark); let rhs = self.parse_expr()?; + let span = self.span_from(start); let more = self.eat_sym(","); if more { meta.trailing = self.take_trailing(); } - assigns.push(AssignPair { meta, lhs, rhs, rhs_comments }); + assigns.push(AssignPair { meta, lhs, rhs, rhs_comments, span }); if !more { break; } @@ -1027,18 +1091,30 @@ impl Parser { fn parse_delay_value(&mut self) -> PResult { if self.cur().is_sym("(") { + let start = self.here(); self.bump(); + let inner_start = self.here(); let first = self.parse_expr()?; let expr = if self.eat_sym(":") { let typ = self.parse_expr()?; self.expect_sym(":")?; let max = self.parse_expr()?; - Expr::MinTypMax { min: Box::new(first), typ: Box::new(typ), max: Box::new(max) } + self.expr_at( + inner_start, + ExprKind::MinTypMax { + min: Box::new(first), + typ: Box::new(typ), + max: Box::new(max), + }, + ) } else { first }; self.expect_sym(")")?; - Ok(Expr::Paren { inner: Box::new(expr), before: Vec::new(), after: Vec::new() }) + Ok(self.expr_at( + start, + ExprKind::Paren { inner: Box::new(expr), before: Vec::new(), after: Vec::new() }, + )) } else { self.parse_primary() } @@ -1074,17 +1150,19 @@ impl Parser { } let mut instances = Vec::new(); loop { + let start = self.here(); let mut meta = self.take_meta(); let name = self.expect_ident()?; let dims = self.parse_dims()?; self.expect_sym("(")?; let conns = self.parse_connections()?; self.expect_sym(")")?; + let span = self.span_from(start); let more = self.eat_sym(","); if more { meta.trailing = self.take_trailing(); } - instances.push(Instance { meta, name, dims, conns }); + instances.push(Instance { meta, name, dims, conns, span }); if !more { break; } @@ -1120,18 +1198,22 @@ impl Parser { } else { let mut conns = Vec::new(); loop { + let start = self.here(); let meta = self.take_meta(); let expr = if self.cur().is_sym(",") || self.cur().is_sym(")") { None } else { Some(self.parse_expr()?) }; + // An omitted connection (`u (a, , c)`) consumed no token, so + // this is the empty span where it would have started. + let span = self.span_from(start); let more = self.eat_sym(","); let mut meta = meta; if more { meta.trailing = self.take_trailing(); } - conns.push(OrderedConn { meta, expr }); + conns.push(OrderedConn { meta, expr, span }); if !more { break; } @@ -1143,20 +1225,23 @@ impl Parser { /// `.name(expr)`, `.name()`, `.name`, `.*`, or (for parameter lists and /// ordered parameter overrides) a bare expression. fn parse_connection(&mut self) -> PResult { + let start = self.here(); let mut meta = self.take_meta(); if self.eat_sym(".") { if self.eat_sym("*") { - return Ok(Connection { meta, name: "*".to_string(), expr: None }); + let span = self.span_from(start); + return Ok(Connection { meta, name: "*".to_string(), expr: None, span }); } let name = self.expect_ident()?; let mark = self.pending_trailing.len(); + let paren_start = self.here(); let expr = if self.eat_sym("(") { if self.cur().is_sym(")") { // `.name(/* unused */)`: the comments were written inside // these parens and are printed back inside them. let inside = self.take_around(mark); self.bump(); - Some(Expr::Empty(inside)) + Some(self.expr_at(paren_start, ExprKind::Empty(inside))) } else { let e = self.parse_expr_or_type()?; self.expect_sym(")")?; @@ -1165,12 +1250,14 @@ impl Parser { } else { None }; + let span = self.span_from(start); meta.trailing = self.take_trailing(); - Ok(Connection { meta, name, expr }) + Ok(Connection { meta, name, expr, span }) } else { let e = self.parse_expr_or_type()?; + let span = self.span_from(start); meta.trailing = self.take_trailing(); - Ok(Connection { meta, name: String::new(), expr: Some(e) }) + Ok(Connection { meta, name: String::new(), expr: Some(e), span }) } } @@ -1196,6 +1283,7 @@ impl Parser { }; let mut instances = Vec::new(); loop { + let start = self.here(); let mut meta = self.take_meta(); let name = if self.cur().kind == TokenKind::Ident { Some(self.bump().text) } else { None }; @@ -1210,11 +1298,12 @@ impl Parser { } } self.expect_sym(")")?; + let span = self.span_from(start); let more = self.eat_sym(","); if more { meta.trailing = self.take_trailing(); } - instances.push(GateInstance { meta, name, args }); + instances.push(GateInstance { meta, name, args, span }); if !more { break; } @@ -1236,6 +1325,7 @@ impl Parser { } fn parse_gen_if_inner(&mut self) -> PResult { + let start = self.here(); self.expect_kw("if")?; self.expect_sym("(")?; let cond = self.parse_expr()?; @@ -1253,7 +1343,7 @@ impl Parser { } else { None }; - Ok(GenIf { cond, then, els }) + Ok(GenIf { cond, then, els, span: self.span_from(start) }) } fn parse_gen_for(&mut self) -> PResult { @@ -1280,6 +1370,7 @@ impl Parser { self.expect_sym(")")?; let mut items = Vec::new(); while !self.cur().is_kw("endcase") && !self.at_eof() { + let start = self.here(); let mut meta = self.take_meta(); let labels = if self.eat_kw("default") { let _ = self.eat_sym(":"); @@ -1291,8 +1382,9 @@ impl Parser { labels }; let body = self.parse_gen_block()?; + let span = self.span_from(start); meta.trailing = self.take_trailing(); - items.push(GenCaseItem { meta, labels, body }); + items.push(GenCaseItem { meta, labels, body, span }); } let dangling = self.take_dangling(); self.expect_kw("endcase")?; @@ -1300,6 +1392,7 @@ impl Parser { } fn parse_gen_block(&mut self) -> PResult { + let start = self.here(); if self.cur().is_kw("begin") { self.bump(); let label = if self.eat_sym(":") { Some(self.expect_ident()?) } else { None }; @@ -1310,15 +1403,24 @@ impl Parser { let dangling = self.take_dangling(); self.expect_kw("end")?; let end_label = self.parse_end_label()?; - Ok(GenBlock { label, is_block: true, items, dangling, end_label }) + Ok(GenBlock { + label, + is_block: true, + items, + dangling, + end_label, + span: self.span_from(start), + }) } else { let item = self.parse_item()?; + let span = item.span; Ok(GenBlock { label: None, is_block: false, items: vec![item], dangling: Vec::new(), end_label: None, + span, }) } } @@ -1379,6 +1481,7 @@ impl Parser { return Ok(args); } loop { + let start = self.here(); let mut meta = self.take_meta(); let dir = { let t = self.cur(); @@ -1392,9 +1495,10 @@ impl Parser { let name = self.expect_ident()?; let unpacked = self.parse_dims()?; let default = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None }; + let span = self.span_from(start); let more = self.eat_sym(","); meta.trailing = self.take_trailing(); - args.push(TfArg { meta, dir, ty, name, unpacked, default }); + args.push(TfArg { meta, dir, ty, name, unpacked, default, span }); if !more { break; } @@ -1430,6 +1534,7 @@ impl Parser { } fn parse_stmt_inner(&mut self) -> PResult { + let start = self.here(); let mut meta = self.take_meta(); while self.cur().kind == TokenKind::Attribute { meta.attrs.push(self.take_raw_text()); @@ -1437,10 +1542,11 @@ impl Parser { meta.leading.append(&mut tok.leading); } let kind = self.parse_stmt_kind()?; + let span = self.span_from(start); if meta.trailing.is_none() { meta.trailing = self.take_trailing(); } - Ok(Stmt { meta, kind }) + Ok(Stmt { meta, kind, span }) } fn parse_stmt_kind(&mut self) -> PResult { @@ -1594,12 +1700,15 @@ impl Parser { "foreach" => { self.bump(); self.expect_sym("(")?; + let target_start = self.here(); let mut name = self.expect_ident()?; while self.cur().is_sym(".") { self.bump(); name.push('.'); name.push_str(&self.expect_ident()?); } + // The target's span stops at the name, before the `[`. + let target = self.expr_at(target_start, ExprKind::Ident(name)); self.expect_sym("[")?; let mut vars = Vec::new(); if !self.cur().is_sym("]") { @@ -1611,7 +1720,7 @@ impl Parser { self.expect_sym("]")?; self.expect_sym(")")?; let body = Box::new(self.parse_stmt()?); - Ok(StmtKind::Foreach { target: Expr::Ident(name), vars, body }) + Ok(StmtKind::Foreach { target, vars, body }) } "return" => { self.bump(); @@ -1728,6 +1837,7 @@ impl Parser { // `case (x) inside` is not supported; plain case kinds only. let mut items = Vec::new(); while !self.cur().is_kw("endcase") && !self.at_eof() { + let start = self.here(); let mut meta = self.take_meta(); let labels = if self.eat_kw("default") { let _ = self.eat_sym(":"); @@ -1739,10 +1849,11 @@ impl Parser { labels }; let stmt = self.parse_stmt()?; + let span = self.span_from(start); if meta.trailing.is_none() { meta.trailing = self.take_trailing(); } - items.push(CaseItem { meta, labels, stmt }); + items.push(CaseItem { meta, labels, stmt, span }); } let dangling = self.take_dangling(); self.expect_kw("endcase")?; @@ -1808,12 +1919,10 @@ impl Parser { } if self.cur().kind == TokenKind::Ident { // `@ident` without parens. + let start = self.here(); let name = self.expect_ident()?; - return Ok(SensList::List(vec![SensItem { - sep: None, - edge: None, - expr: Expr::Ident(name), - }])); + let expr = self.expr_at(start, ExprKind::Ident(name)); + return Ok(SensList::List(vec![SensItem { sep: None, edge: None, expr }])); } if self.cur().is_sym("(") && self.nth(1).is_sym("*") { // `@( /* c */ * /* d */ )`: the comments belong to the star, not @@ -1875,6 +1984,7 @@ impl Parser { fn parse_ternary_inner(&mut self) -> PResult { let mark = self.pending_trailing.len(); + let start = self.here(); let cond = self.parse_binary(1)?; if self.cur().is_sym("?") { // Each of the four gaps inside a `? :` can hold comments; kept @@ -1887,17 +1997,20 @@ impl Parser { self.expect_sym(":")?; let after_colon = self.take_around(mark); let els = self.parse_ternary()?; - Ok(Expr::Ternary { - cond: Box::new(cond), - then: Box::new(then), - els: Box::new(els), - comments: Box::new(TernaryComments { - before_question, - after_question, - before_colon, - after_colon, - }), - }) + Ok(self.expr_at( + start, + ExprKind::Ternary { + cond: Box::new(cond), + then: Box::new(then), + els: Box::new(els), + comments: Box::new(TernaryComments { + before_question, + after_question, + before_colon, + after_colon, + }), + }, + )) } else { Ok(cond) } @@ -1950,6 +2063,7 @@ impl Parser { self.expect_sym("{")?; let mut ranges: Vec = Vec::new(); loop { + let item_start = self.here(); let mut meta = self.take_meta(); let expr = if self.cur().is_sym("[") { self.bump(); @@ -1957,15 +2071,19 @@ impl Parser { self.expect_sym(":")?; let hi = self.parse_expr()?; self.expect_sym("]")?; - Expr::ValueRange { lo: Box::new(lo), hi: Box::new(hi) } + self.expr_at( + item_start, + ExprKind::ValueRange { lo: Box::new(lo), hi: Box::new(hi) }, + ) } else { self.parse_expr()? }; + let item_span = self.span_from(item_start); let more = self.eat_sym(","); if more { meta.trailing = self.take_trailing(); } - ranges.push(ExprItem { meta, expr }); + ranges.push(ExprItem { meta, expr, span: item_span }); if !more { break; } @@ -1977,7 +2095,8 @@ impl Parser { } self.expect_sym("}")?; self.link()?; - lhs = Expr::Inside { lhs: Box::new(lhs), ranges }; + let start = lhs.span.start; + lhs = self.expr_at(start, ExprKind::Inside { lhs: Box::new(lhs), ranges }); continue; } // Comments between the operand and the operator belong to this @@ -1989,12 +2108,16 @@ impl Parser { let after = self.take_around(mark); let rhs = self.parse_binary(prec + 1)?; self.link()?; - lhs = Expr::Binary { - lhs: Box::new(lhs), - op, - rhs: Box::new(rhs), - comments: Box::new(BinaryComments { before, after }), - }; + let start = lhs.span.start; + lhs = self.expr_at( + start, + ExprKind::Binary { + lhs: Box::new(lhs), + op, + rhs: Box::new(rhs), + comments: Box::new(BinaryComments { before, after }), + }, + ); } Ok(lhs) } @@ -2016,9 +2139,10 @@ impl Parser { "!" | "~" | "+" | "-" | "&" | "|" | "^" | "~&" | "~|" | "~^" | "^~" | "++" | "--" ) { + let start = self.here(); let op = self.bump().text; let expr = self.parse_unary()?; - return Ok(Expr::Unary { op, expr: Box::new(expr) }); + return Ok(self.expr_at(start, ExprKind::Unary { op, expr: Box::new(expr) })); } self.parse_postfix() } @@ -2049,15 +2173,18 @@ impl Parser { let mut expr = self.parse_primary()?; while self.at_postfix_segment() { self.link()?; + // Every segment wraps what came before, so each new node starts + // where the expression so far started. + let start = expr.span.start; let t = self.cur(); if t.is_sym(".") { self.bump(); let name = self.expect_ident()?; - expr = Expr::Member { base: Box::new(expr), name }; + expr = self.expr_at(start, ExprKind::Member { base: Box::new(expr), name }); } else if t.is_sym("::") { self.bump(); let name = self.expect_ident()?; - expr = Expr::Scope { base: Box::new(expr), name }; + expr = self.expr_at(start, ExprKind::Scope { base: Box::new(expr), name }); } else if t.is_sym("[") { self.bump(); let a = self.parse_expr()?; @@ -2066,53 +2193,72 @@ impl Parser { let op = self.bump().text; let b = self.parse_expr()?; self.expect_sym("]")?; - expr = Expr::Range { - base: Box::new(expr), - op, - msb: Box::new(a), - lsb: Box::new(b), - }; + expr = self.expr_at( + start, + ExprKind::Range { + base: Box::new(expr), + op, + msb: Box::new(a), + lsb: Box::new(b), + }, + ); } else { self.expect_sym("]")?; - expr = Expr::Index { base: Box::new(expr), index: Box::new(a) }; + expr = self.expr_at( + start, + ExprKind::Index { base: Box::new(expr), index: Box::new(a) }, + ); } } else if t.is_sym("(") { self.bump(); let mut args = Vec::new(); if !self.cur().is_sym(")") { + let arg_start = self.here(); let meta = self.take_meta(); - let first = ExprItem { meta, expr: self.parse_expr_or_type()? }; + let first_expr = self.parse_expr_or_type()?; + let first = + ExprItem { meta, expr: first_expr, span: self.span_from(arg_start) }; args = self.parse_expr_list(first)?; } self.expect_sym(")")?; - expr = Expr::Call { callee: Box::new(expr), args }; + expr = self.expr_at(start, ExprKind::Call { callee: Box::new(expr), args }); } else if t.is_sym("'") && self.nth(1).is_sym("(") { // Cast: `expr'(x)` where expr is a simple name or size. - let ty = match &expr { - Expr::Ident(n) => n.clone(), - Expr::Number(n) => n.clone(), + let ty = match &expr.kind { + ExprKind::Ident(n) => n.clone(), + ExprKind::Number(n) => n.clone(), _ => return self.error("unsupported cast base expression"), }; self.bump(); // ' self.bump(); // ( let inner = self.parse_expr()?; self.expect_sym(")")?; - expr = Expr::Cast { ty, expr: Box::new(inner) }; + expr = self.expr_at(start, ExprKind::Cast { ty, expr: Box::new(inner) }); } else { // `++` / `--`, the only remaining segment kind. let op = self.bump().text; - expr = Expr::Postfix { expr: Box::new(expr), op }; + expr = self.expr_at(start, ExprKind::Postfix { expr: Box::new(expr), op }); } } Ok(expr) } fn parse_primary(&mut self) -> PResult { + let start = self.here(); let t = self.cur(); match t.kind { - TokenKind::Number => Ok(Expr::Number(self.bump().text)), - TokenKind::String => Ok(Expr::Str(self.bump().text)), - TokenKind::Ident | TokenKind::SystemIdent => Ok(Expr::Ident(self.bump().text)), + TokenKind::Number => { + let text = self.bump().text; + Ok(self.expr_at(start, ExprKind::Number(text))) + } + TokenKind::String => { + let text = self.bump().text; + Ok(self.expr_at(start, ExprKind::Str(text))) + } + TokenKind::Ident | TokenKind::SystemIdent => { + let text = self.bump().text; + Ok(self.expr_at(start, ExprKind::Ident(text))) + } TokenKind::Keyword => { let kw = t.text.clone(); // Type keyword casts: `int'(x)`, `signed'(y)`. @@ -2128,7 +2274,7 @@ impl Parser { self.bump(); // ( let inner = self.parse_expr()?; self.expect_sym(")")?; - return Ok(Expr::Cast { ty, expr: Box::new(inner) }); + return Ok(self.expr_at(start, ExprKind::Cast { ty, expr: Box::new(inner) })); } // Type keyword used as an argument (e.g. `$bits(int)`). if TYPE_KEYWORDS.contains(&kw.as_str()) { @@ -2146,22 +2292,29 @@ impl Parser { self.bump(); before.append(&mut self.take_leading_here()); let mark = self.pending_trailing.len(); + let inner_start = self.here(); let inner = self.parse_expr()?; let inner = if self.eat_sym(":") { let typ = self.parse_expr()?; self.expect_sym(":")?; let max = self.parse_expr()?; - Expr::MinTypMax { - min: Box::new(inner), - typ: Box::new(typ), - max: Box::new(max), - } + self.expr_at( + inner_start, + ExprKind::MinTypMax { + min: Box::new(inner), + typ: Box::new(typ), + max: Box::new(max), + }, + ) } else { inner }; let after = self.take_around(mark); self.expect_sym(")")?; - Ok(Expr::Paren { inner: Box::new(inner), before, after }) + Ok(self.expr_at( + start, + ExprKind::Paren { inner: Box::new(inner), before, after }, + )) } "{" => { self.bump(); @@ -2178,21 +2331,25 @@ impl Parser { } self.expect_sym("}")?; self.expect_sym("}")?; - return Ok(Expr::Repl { count: Box::new(first.expr), inner }); + return Ok(self.expr_at( + start, + ExprKind::Repl { count: Box::new(first.expr), inner }, + )); } let items = self.parse_expr_list(first)?; self.expect_sym("}")?; - Ok(Expr::Concat(items)) + Ok(self.expr_at(start, ExprKind::Concat(items))) } "'{" => { self.bump(); let mut items = Vec::new(); if !self.cur().is_sym("}") { loop { + let item_start = self.here(); let mut meta = self.take_meta(); let key_or_val = if self.cur().is_kw("default") { self.bump(); - Expr::Ident("default".to_string()) + self.expr_at(item_start, ExprKind::Ident("default".to_string())) } else { self.parse_expr_or_type()? }; @@ -2201,11 +2358,12 @@ impl Parser { } else { (None, key_or_val) }; + let item_span = self.span_from(item_start); let more = self.eat_sym(","); if more { meta.trailing = self.take_trailing(); } - items.push(PatternItem { meta, key, value }); + items.push(PatternItem { meta, key, value, span: item_span }); if !more { break; } @@ -2217,7 +2375,7 @@ impl Parser { } } self.expect_sym("}")?; - Ok(Expr::AssignPattern(items)) + Ok(self.expr_at(start, ExprKind::AssignPattern(items))) } _ => self.error("expected expression"), } @@ -2640,7 +2798,7 @@ mod tests { parse_ok("module m;\nassign y = c /* a */ ? /* b */ x /* c */ : /* d */ z;\nendmodule"); let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; let ItemKind::ContAssign(a) = &m.items[0].kind else { panic!("expected an assign") }; - let Expr::Ternary { comments, .. } = &a.assigns[0].rhs else { + let ExprKind::Ternary { comments, .. } = &a.assigns[0].rhs.kind else { panic!("expected a ternary") }; assert_eq!(comments.before_question.len(), 1); @@ -2654,7 +2812,7 @@ mod tests { let file = parse_ok("module m;\nassign y = a /* pre */ && /* post */ b;\nendmodule"); let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; let ItemKind::ContAssign(a) = &m.items[0].kind else { panic!("expected an assign") }; - let Expr::Binary { comments, .. } = &a.assigns[0].rhs else { + let ExprKind::Binary { comments, .. } = &a.assigns[0].rhs.kind else { panic!("expected a binary expression") }; assert_eq!(comments.before.len(), 1, "one comment before the operator"); diff --git a/crates/vlog_parser/src/span.rs b/crates/vlog_parser/src/span.rs new file mode 100644 index 0000000..14b315f --- /dev/null +++ b/crates/vlog_parser/src/span.rs @@ -0,0 +1,83 @@ +//! Byte spans into the source text. +//! +//! Every token and every AST node carries one, which is what lets a consumer +//! that is not the formatter — an LSP server, a `verilog_format: off` fence, a +//! `--lines M-N` range — go from a node back to the exact bytes it came from. + +/// A half-open byte range `[start, end)` into the source text. +/// +/// Offsets are **bytes**, not characters, so slicing `source[range]` is exact +/// for multi-byte UTF-8. See `docs/features/spans/README.md` for the +/// conventions (in particular: a node's span is its code extent; comments are +/// not part of it and carry spans of their own). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct TextRange { + /// Byte offset of the first byte. + pub start: u32, + /// Byte offset one past the last byte. + pub end: u32, +} + +impl TextRange { + /// A range from `start` to `end`; `end` is clamped up to `start` so a + /// range is never inverted. + pub fn new(start: u32, end: u32) -> Self { + TextRange { start, end: end.max(start) } + } + + /// The empty range at `offset`. + pub fn empty(offset: u32) -> Self { + TextRange { start: offset, end: offset } + } + + /// Length in bytes. + pub fn len(&self) -> u32 { + self.end - self.start + } + + /// True when the range covers no bytes. + pub fn is_empty(&self) -> bool { + self.start == self.end + } + + /// True when `offset` falls inside the range (`end` is excluded). + pub fn contains(&self, offset: u32) -> bool { + self.start <= offset && offset < self.end + } + + /// The range as a `usize` range, for slicing the source text. + pub fn as_range(&self) -> std::ops::Range { + self.start as usize..self.end as usize + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn basics() { + let r = TextRange::new(3, 7); + assert_eq!(r.len(), 4); + assert!(!r.is_empty()); + assert!(r.contains(3)); + assert!(r.contains(6)); + assert!(!r.contains(7), "end is excluded"); + assert!(!r.contains(2)); + assert_eq!(&"0123456789"[r.as_range()], "3456"); + } + + #[test] + fn empty_range_contains_nothing() { + let r = TextRange::empty(5); + assert!(r.is_empty()); + assert_eq!(r.len(), 0); + assert!(!r.contains(5)); + } + + #[test] + fn an_inverted_range_is_clamped_to_empty() { + let r = TextRange::new(9, 4); + assert_eq!((r.start, r.end), (9, 9)); + } +} diff --git a/crates/vlog_parser/src/token.rs b/crates/vlog_parser/src/token.rs index 75e444f..b8529e5 100644 --- a/crates/vlog_parser/src/token.rs +++ b/crates/vlog_parser/src/token.rs @@ -1,5 +1,7 @@ //! Token definitions for the Verilog/SystemVerilog lexer. +use crate::span::TextRange; + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum TokenKind { /// Identifier, including escaped identifiers (`\foo`). @@ -40,6 +42,10 @@ pub struct Comment { /// before re-indenting them, which is what keeps re-formatting a fixed /// point. pub col: u32, + /// Byte extent in the source text, markers included. Trivia spans live + /// here rather than on AST nodes: a node's span is its code extent, and + /// the comments attached to it are outside that. + pub span: TextRange, } #[derive(Debug, Clone)] @@ -50,6 +56,10 @@ pub struct Token { pub line: u32, /// 1-based source column of the first character. pub col: u32, + /// Byte extent in the source text. `source[span] == text` for every kind + /// except [`TokenKind::Number`], whose text drops the whitespace a sized + /// literal may write around its tick (`8 'hFF` → `8'hFF`). + pub span: TextRange, /// Comments that appeared before this token (on their own lines, or on /// earlier lines). pub leading: Vec, diff --git a/crates/vlog_parser/tests/spans.rs b/crates/vlog_parser/tests/spans.rs new file mode 100644 index 0000000..c371bbf --- /dev/null +++ b/crates/vlog_parser/tests/spans.rs @@ -0,0 +1,618 @@ +//! Span invariants: the token stream tiles the source, and every AST node's +//! span slices back to the construct it came from. +//! +//! This is the token-level half of the `reconstruct(tree) == input` invariant +//! TODO.md §6 asks for. The AST-level half needs a printer that walks the tree +//! emitting spans, which does not exist yet; what is testable today is that no +//! source byte is unreachable from the token stream, and that node spans nest. + +use vlog_parser::ast::*; +use vlog_parser::span::TextRange; +use vlog_parser::token::TokenKind; +use vlog_parser::{parse_source, tokenize}; + +/// Sources covering every construct the parser supports, plus the shapes that +/// make spans interesting: multi-byte UTF-8, CRLF, a string across a line +/// break, whitespace inside a number, two comments on one line. +const SOURCES: &[&str] = &[ + "", + "\n", + " \n\t\n", + "// just a comment", + "// no trailing newline\nmodule m; endmodule", + "module m;\nendmodule\n", + "module m (input wire a, output logic [7:0] b);\n assign b = {8{a}};\nendmodule\n", + "module m #(parameter int W = 8, localparam W2 = W*2) (\n input clk\n);\nendmodule\n", + "module m (a, b);\n input a;\n output reg b;\n always @(a or b) b <= ~a;\nendmodule\n", + "package p;\n typedef enum logic [1:0] {A = 2'b00, B, C} state_e;\n typedef struct packed {\n logic [3:0] hi;\n logic lo;\n } s_t;\nendpackage : p\n", + "module m;\n initial begin : b\n for (int i = 0; i < 4; i++) begin\n $display(\"%d\", i);\n end\n case (x)\n 2'b00: y = 1;\n default: y = 0;\n endcase\n end\nendmodule\n", + "module m;\n function automatic logic [7:0] f(input logic [7:0] a, int b = 3);\n return a + b[3:0];\n endfunction\n task t; begin @(posedge clk) x <= 1; end endtask\nendmodule\n", + "module m;\n generate\n if (W > 1) begin : g\n sub #(.W(W)) u (.a(a), .b(), .*);\n end else if (W == 1) begin\n wire w;\n end else begin\n wire v;\n end\n endgenerate\nendmodule\n", + "module m;\n for (genvar i = 0; i < 4; i++) begin : loop\n and g1 (o, a, b);\n end\n case (W)\n 1: wire w1;\n default: wire wd;\n endcase\nendmodule\n", + "`timescale 1ns / 1ps\n`define WIDE 8\nmodule m;\n wire [`WIDE-1:0] w;\nendmodule\n", + "module m;\n `ASSERT_INIT(CheckW_A, W > 0)\n `uvm_info(\"id\", \"msg\", UVM_LOW);\n initial `MY_MACRO(a,\n b);\nendmodule\n", + "(* keep = \"true\" *)\nmodule m;\n (* dont_touch *) wire w;\n initial (* x *) x = 1;\nendmodule\n", + // Whitespace inside a sized literal: the one token whose text is not its + // source slice. + "module m;\n localparam A = 8 'h FF;\n localparam B = 'd 10;\nendmodule\n", + // Two comments on one line after a token: they merge into one node. + "module m;\n wire w; /* a */ /* b */\nendmodule\n", + // Comments everywhere. + "// header\n\n// second\nmodule m ( // after paren\n input a // trailing\n);\n /* block\n comment */\n wire w;\n // dangling\nendmodule\n// tail\n", + // Multi-byte UTF-8 in comments and strings. + "// λ αβγ — em dash\nmodule m;\n initial $display(\"λ = %d ünïcode\", x); // träiling ✓\nendmodule\n", + // CRLF. + "module m;\r\n wire w; // comment\r\nendmodule\r\n", + // A string literal that spans a physical line. + "module m;\n initial $display(\"line one\n line two\");\nendmodule\n", + "module m;\n assign y = a inside {[0:3], 4} ? int'(b) + {2{c}} : '{default: 0};\n assign z = pkg::t'(v.field[3:0][2 +: 2]);\nendmodule\n", +]; + +/// A token or a comment, in source order. +struct Piece { + span: TextRange, + text: String, + /// `None` for a comment. + kind: Option, +} + +/// Every token and every comment the lexer produced, in source order. +fn pieces(src: &str) -> Vec { + let mut out = Vec::new(); + for t in tokenize(src).expect("lex error") { + for c in &t.leading { + out.push(Piece { span: c.span, text: c.text.clone(), kind: None }); + } + if t.kind != TokenKind::Eof { + out.push(Piece { span: t.span, text: t.text.clone(), kind: Some(t.kind) }); + } + if let Some(c) = &t.trailing { + out.push(Piece { span: c.span, text: c.text.clone(), kind: None }); + } + } + out +} + +/// The losslessness invariant, asserted for one source: +/// +/// 1. pieces are in source order and never overlap; +/// 2. every byte outside a piece is whitespace; +/// 3. concatenating the pieces and the whitespace between them reproduces the +/// source exactly; +/// 4. each piece's own `text` is its source slice — except for the two +/// normalizations the lexer performs, which may only differ by whitespace. +fn assert_covers_source(src: &str) { + let pieces = pieces(src); + let mut rebuilt = String::new(); + let mut at = 0u32; + for p in &pieces { + assert!(p.span.end <= src.len() as u32, "span past the end of {src:?}: {:?}", p.span); + assert!( + p.span.start >= at, + "pieces out of order or overlapping in {src:?}: {:?} after byte {at}", + p.span + ); + let gap = &src[at as usize..p.span.start as usize]; + assert!( + gap.chars().all(char::is_whitespace), + "non-whitespace {gap:?} is not covered by any token in {src:?}" + ); + let slice = &src[p.span.as_range()]; + if slice != p.text { + // Two normalizations are allowed to rewrite whitespace: a sized + // literal's tick spacing (`8 'hFF` → `8'hFF`), and the single + // space that joins two same-line trailing comments into one node. + let is_number = p.kind == Some(TokenKind::Number); + let is_comment = p.kind.is_none(); + assert!( + is_number || is_comment, + "token text {:?} is not its source slice {slice:?} in {src:?}", + p.text + ); + assert_eq!( + despace(slice), + despace(&p.text), + "a {} changed more than whitespace in {src:?}", + if is_number { "number" } else { "comment" } + ); + } + rebuilt.push_str(gap); + rebuilt.push_str(slice); + at = p.span.end; + } + rebuilt.push_str(&src[at as usize..]); + assert_eq!(rebuilt, src, "the token stream does not reconstruct the source"); +} + +fn despace(s: &str) -> String { + s.chars().filter(|c| !c.is_whitespace()).collect() +} + +#[test] +fn the_token_stream_covers_every_source_byte() { + for src in SOURCES { + assert_covers_source(src); + } +} + +#[test] +fn the_token_stream_covers_the_formatter_fixtures() { + // The repo's real Verilog lives next door; lexing it here is the closest + // thing to a corpus this crate has. If the fixtures ever move, this test + // says so rather than quietly passing on nothing. + let dir = + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../vlog_formatter/tests/fixtures"); + let entries = std::fs::read_dir(&dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display())); + let mut seen = 0; + for entry in entries { + let path = entry.expect("dir entry").path(); + if !matches!(path.extension().and_then(|e| e.to_str()), Some("sv") | Some("v")) { + continue; + } + let src = std::fs::read_to_string(&path).expect("read fixture"); + assert_covers_source(&src); + seen += 1; + } + assert!(seen > 0, "no fixtures found in {}", dir.display()); +} + +#[test] +fn spans_are_byte_offsets_not_character_counts() { + let src = "// λλλ\nwire w;\n"; + let toks = tokenize(src).expect("lex error"); + let comment = &toks[0].leading[0]; + assert_eq!(&src[comment.span.as_range()], "// λλλ"); + assert_eq!(comment.span.len(), 9, "3 ASCII + 6 bytes of λ"); + let wire = &toks[0]; + assert_eq!(&src[wire.span.as_range()], "wire"); + assert_eq!(wire.span.start, 10, "one byte past the newline after a 9-byte comment"); +} + +#[test] +fn a_trimmed_token_span_stops_where_its_text_does() { + // Trailing whitespace is not part of a line comment or a directive. + let src = "`define A 1 \nwire w; // c \n"; + let toks = tokenize(src).expect("lex error"); + assert_eq!(&src[toks[0].span.as_range()], "`define A 1"); + let comment = toks.iter().find_map(|t| t.trailing.as_ref()).expect("trailing comment"); + assert_eq!(&src[comment.span.as_range()], "// c"); +} + +// ------------------------------------------------------------------ +// AST node spans +// ------------------------------------------------------------------ + +fn slice(src: &str, span: TextRange) -> &str { + &src[span.as_range()] +} + +#[test] +fn node_spans_slice_back_to_the_construct() { + let src = "module m;\n wire [1:0] w = a + b;\n always_ff @(posedge clk) q <= d;\nendmodule\n"; + let file = parse_source(src).expect("parse error"); + assert_eq!(slice(src, file.span), src); + assert_eq!(slice(src, file.items[0].span), src.trim_end()); + + let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; + assert_eq!(slice(src, m.items[0].span), "wire [1:0] w = a + b;"); + assert_eq!(slice(src, m.items[1].span), "always_ff @(posedge clk) q <= d;"); + + let ItemKind::DataDecl(d) = &m.items[0].kind else { panic!("expected a declaration") }; + assert_eq!(slice(src, d.ty.packed[0].span), "[1:0]"); + assert_eq!(slice(src, d.declarators[0].span), "w = a + b"); + let init = d.declarators[0].init.as_ref().expect("an initializer"); + assert_eq!(slice(src, init.span), "a + b"); + let ExprKind::Binary { lhs, rhs, .. } = &init.kind else { panic!("expected a binary") }; + assert_eq!(slice(src, lhs.span), "a"); + assert_eq!(slice(src, rhs.span), "b"); + + let ItemKind::Always { stmt, .. } = &m.items[1].kind else { panic!("expected an always") }; + assert_eq!(slice(src, stmt.span), "@(posedge clk) q <= d;"); +} + +#[test] +fn a_gen_if_span_slices_back_to_its_text() { + // QA's mutation test showed containment alone doesn't pin GenIf.span's + // content; this slice-check does. + let src = "module m;\nif (A) begin\nwire x;\nend else if (B) begin\nwire y;\nend\nendmodule\n"; + let file = parse_source(src).expect("parse error"); + let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; + let ItemKind::GenIf(gi) = &m.items[0].kind else { panic!("expected a generate if") }; + assert_eq!(slice(src, gi.span), "if (A) begin\nwire x;\nend else if (B) begin\nwire y;\nend"); + let Some(els) = &gi.els else { panic!("expected an else branch") }; + let GenElse::If(_, inner) = &**els else { panic!("expected an else-if") }; + assert_eq!(slice(src, inner.span), "if (B) begin\nwire y;\nend"); +} + +#[test] +fn a_node_span_is_code_only_and_excludes_its_comments() { + let src = "module m;\n // leading\n wire w; // trailing\nendmodule\n"; + let file = parse_source(src).expect("parse error"); + let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; + let decl = &m.items[0]; + assert_eq!(slice(src, decl.span), "wire w;"); + let leading = &decl.meta.leading[0]; + assert_eq!(slice(src, leading.span), "// leading"); + assert!( + !decl.span.contains(leading.span.start), + "a leading comment is trivia, not part of the node's span" + ); + assert!(leading.span.end < decl.span.start, "the comment's own span locates it"); +} + +#[test] +fn attribute_instances_are_inside_the_item_span() { + // `(* ... *)` is a real token, not trivia, so it is part of the item. + let src = "module m;\n (* keep *) wire w;\nendmodule\n"; + let file = parse_source(src).expect("parse error"); + let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; + assert_eq!(slice(src, m.items[0].span), "(* keep *) wire w;"); + assert_eq!(slice(src, m.items[0].meta.attrs[0].span), "(* keep *)"); +} + +#[test] +fn a_multi_byte_source_gives_exact_node_spans() { + let src = "module m;\n // ünïcode ✓\n assign y = \"λ\" ;\nendmodule\n"; + let file = parse_source(src).expect("parse error"); + let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; + assert_eq!(slice(src, m.items[0].span), "assign y = \"λ\" ;"); + let ItemKind::ContAssign(a) = &m.items[0].kind else { panic!("expected an assign") }; + assert_eq!(slice(src, a.assigns[0].rhs.span), "\"λ\""); +} + +#[test] +fn a_macro_item_span_covers_the_whole_invocation() { + let src = "module m;\n `ASSERT(A,\n x > 0)\n `uvm_info(\"i\", \"m\", LOW);\nendmodule\n"; + let file = parse_source(src).expect("parse error"); + let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; + assert_eq!(slice(src, m.items[0].span), "`ASSERT(A,\n x > 0)"); + let ItemKind::MacroItem(call) = &m.items[0].kind else { panic!("expected a macro item") }; + assert_eq!(slice(src, call.raw.span), "`ASSERT(A,\n x > 0)"); + // The `;` is not part of the raw text but is part of the item. + assert_eq!(slice(src, m.items[1].span), "`uvm_info(\"i\", \"m\", LOW);"); +} + +#[test] +fn every_node_span_nests_inside_its_parent() { + for src in SOURCES { + let Ok(file) = parse_source(src) else { continue }; + for item in &file.items { + check_item(src, item, file.span); + } + } + // And on something that exercises every container at once. + let src = "package p;\n typedef struct packed { logic a; } s_t;\nendpackage\nmodule m #(parameter W = 1) (input a, output b);\n generate for (genvar i = 0; i < W; i++) begin : g\n if (i > 0) begin\n sub u (.x(a), .y());\n end\n end endgenerate\n always @(*) begin\n case (a)\n 1'b0: b = 1;\n default: b = 0;\n endcase\n end\n function f(input int q); return q; endfunction\nendmodule\n"; + let file = parse_source(src).expect("parse error"); + for item in &file.items { + check_item(src, item, file.span); + } +} + +fn assert_inside(src: &str, what: &str, inner: TextRange, outer: TextRange) { + assert!( + outer.start <= inner.start && inner.end <= outer.end, + "{what} {:?} ({:?}) escapes its parent {:?} ({:?})", + inner, + slice(src, inner), + outer, + slice(src, outer), + ); +} + +fn check_item(src: &str, item: &Item, parent: TextRange) { + assert_inside(src, "item", item.span, parent); + for attr in &item.meta.attrs { + assert_inside(src, "attribute", attr.span, item.span); + } + let here = item.span; + match &item.kind { + ItemKind::Module(m) => { + if let Some(params) = &m.param_ports { + for p in params { + assert_inside(src, "parameter port", p.span, here); + check_opt_expr(src, p.default.as_ref(), p.span); + } + } + match &m.ports { + PortList::Ansi(ports) => { + for p in ports { + assert_inside(src, "port", p.span, here); + } + } + PortList::NonAnsi(ports) => { + for p in ports { + assert_inside(src, "port", p.span, here); + } + } + PortList::None | PortList::Empty => {} + } + for i in &m.items { + check_item(src, i, here); + } + } + ItemKind::Package { items, .. } | ItemKind::GenerateRegion { items, .. } => { + for i in items { + check_item(src, i, here); + } + } + ItemKind::Directive(raw) | ItemKind::MacroItem(MacroCall { raw, .. }) => { + assert_inside(src, "raw text", raw.span, here); + } + ItemKind::Typedef(t) => { + if let TypedefKind::Enum(e) = &t.kind { + for member in &e.members { + assert_inside(src, "enum member", member.span, here); + } + } + if let TypedefKind::Struct(s) = &t.kind { + for member in &s.members { + assert_inside(src, "struct member", member.span, here); + for d in &member.declarators { + assert_inside(src, "declarator", d.span, member.span); + } + } + } + } + ItemKind::ParamDecl(p) => check_declarators(src, &p.declarators, here), + ItemKind::DataDecl(d) => check_declarators(src, &d.declarators, here), + ItemKind::PortDecl(p) => check_declarators(src, &p.declarators, here), + ItemKind::ContAssign(a) => { + for pair in &a.assigns { + assert_inside(src, "assignment", pair.span, here); + check_expr(src, &pair.lhs, pair.span); + check_expr(src, &pair.rhs, pair.span); + } + } + ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => { + check_stmt(src, stmt, here); + } + ItemKind::Instantiation(inst) => { + for c in inst.params.iter().flatten() { + assert_inside(src, "parameter override", c.span, here); + check_opt_expr(src, c.expr.as_ref(), c.span); + } + for i in &inst.instances { + assert_inside(src, "instance", i.span, here); + match &i.conns { + Connections::Named(cs) => { + for c in cs { + assert_inside(src, "connection", c.span, i.span); + check_opt_expr(src, c.expr.as_ref(), c.span); + } + } + Connections::Ordered(cs) => { + for c in cs { + assert_inside(src, "connection", c.span, i.span); + check_opt_expr(src, c.expr.as_ref(), c.span); + } + } + } + } + } + ItemKind::GateInstantiation(g) => { + for i in &g.instances { + assert_inside(src, "gate instance", i.span, here); + for a in &i.args { + check_expr(src, a, i.span); + } + } + } + ItemKind::GenIf(gi) => check_gen_if(src, gi, here), + ItemKind::GenFor(gf) => { + check_expr(src, &gf.cond, here); + check_gen_block(src, &gf.body, here); + } + ItemKind::GenCase(gc) => { + check_expr(src, &gc.expr, here); + for i in &gc.items { + assert_inside(src, "generate case item", i.span, here); + check_gen_block(src, &i.body, i.span); + } + } + ItemKind::Function(f) => { + for a in &f.args { + assert_inside(src, "argument", a.span, here); + } + for s in &f.stmts { + check_stmt(src, s, here); + } + } + ItemKind::Task(t) => { + for a in &t.args { + assert_inside(src, "argument", a.span, here); + } + for s in &t.stmts { + check_stmt(src, s, here); + } + } + ItemKind::Defparam(pairs) => { + for (lhs, rhs) in pairs { + check_expr(src, lhs, here); + check_expr(src, rhs, here); + } + } + ItemKind::Import(_) | ItemKind::Timeunit(_) | ItemKind::Genvar(_) => {} + } +} + +fn check_gen_if(src: &str, gi: &GenIf, parent: TextRange) { + assert_inside(src, "generate if", gi.span, parent); + check_expr(src, &gi.cond, gi.span); + check_gen_block(src, &gi.then, gi.span); + match gi.els.as_deref() { + Some(GenElse::If(_, inner)) => check_gen_if(src, inner, gi.span), + Some(GenElse::Block(b)) => check_gen_block(src, b, gi.span), + None => {} + } +} + +fn check_gen_block(src: &str, b: &GenBlock, parent: TextRange) { + assert_inside(src, "generate block", b.span, parent); + for i in &b.items { + check_item(src, i, b.span); + } +} + +fn check_declarators(src: &str, declarators: &[Declarator], parent: TextRange) { + for d in declarators { + assert_inside(src, "declarator", d.span, parent); + check_opt_expr(src, d.init.as_ref(), d.span); + for dim in &d.unpacked { + assert_inside(src, "dimension", dim.span, d.span); + } + } +} + +fn check_stmt(src: &str, stmt: &Stmt, parent: TextRange) { + assert_inside(src, "statement", stmt.span, parent); + let here = stmt.span; + match &stmt.kind { + StmtKind::Block { stmts, .. } | StmtKind::ForkJoin { stmts, .. } => { + for s in stmts { + check_stmt(src, s, here); + } + } + StmtKind::If { cond, then, els, .. } => { + check_expr(src, cond, here); + check_stmt(src, then, here); + if let Some(e) = els { + check_stmt(src, e, here); + } + } + StmtKind::Case { expr, items, .. } => { + check_expr(src, expr, here); + for i in items { + assert_inside(src, "case item", i.span, here); + for l in &i.labels { + assert_inside(src, "case label", l.span, i.span); + check_expr(src, &l.expr, i.span); + } + check_stmt(src, &i.stmt, i.span); + } + } + StmtKind::For { cond, body, .. } => { + check_opt_expr(src, cond.as_ref(), here); + check_stmt(src, body, here); + } + StmtKind::While { cond, body } | StmtKind::DoWhile { body, cond } => { + check_expr(src, cond, here); + check_stmt(src, body, here); + } + StmtKind::Repeat { count: e, body } | StmtKind::Foreach { target: e, body, .. } => { + check_expr(src, e, here); + check_stmt(src, body, here); + } + StmtKind::Forever { body } => check_stmt(src, body, here), + StmtKind::Assign { lhs, rhs, .. } => { + check_expr(src, lhs, here); + check_expr(src, rhs, here); + } + StmtKind::ForceRelease { lhs, rhs, .. } => { + check_expr(src, lhs, here); + check_opt_expr(src, rhs.as_ref(), here); + } + StmtKind::Timing { stmt, .. } => { + if let Some(s) = stmt { + check_stmt(src, s, here); + } + } + StmtKind::Wait { cond, stmt } => { + check_expr(src, cond, here); + if let Some(s) = stmt { + check_stmt(src, s, here); + } + } + StmtKind::ExprStmt(e) | StmtKind::EventTrigger(e) => check_expr(src, e, here), + StmtKind::VarDecl(d) => check_declarators(src, &d.declarators, here), + StmtKind::ParamDecl(p) => check_declarators(src, &p.declarators, here), + StmtKind::PortDecl(p) => check_declarators(src, &p.declarators, here), + StmtKind::Return(e) => check_opt_expr(src, e.as_ref(), here), + StmtKind::Directive(raw) | StmtKind::MacroStmt(MacroCall { raw, .. }) => { + assert_inside(src, "raw text", raw.span, here); + } + StmtKind::Assert { cond, then, els, .. } => { + check_expr(src, cond, here); + for s in then.iter().chain(els.iter()) { + check_stmt(src, s, here); + } + } + StmtKind::Break | StmtKind::Continue | StmtKind::Disable(_) | StmtKind::Null => {} + } +} + +fn check_opt_expr(src: &str, e: Option<&Expr>, parent: TextRange) { + if let Some(e) = e { + check_expr(src, e, parent); + } +} + +fn check_expr(src: &str, e: &Expr, parent: TextRange) { + assert_inside(src, "expression", e.span, parent); + let here = e.span; + match &e.kind { + ExprKind::Unary { expr, .. } + | ExprKind::Postfix { expr, .. } + | ExprKind::Cast { expr, .. } + | ExprKind::Paren { inner: expr, .. } => check_expr(src, expr, here), + ExprKind::Binary { lhs, rhs, .. } => { + check_expr(src, lhs, here); + check_expr(src, rhs, here); + } + ExprKind::Ternary { cond, then, els, .. } => { + check_expr(src, cond, here); + check_expr(src, then, here); + check_expr(src, els, here); + } + ExprKind::Call { callee, args } => { + check_expr(src, callee, here); + for a in args { + assert_inside(src, "argument", a.span, here); + check_expr(src, &a.expr, here); + } + } + ExprKind::Index { base, index } => { + check_expr(src, base, here); + check_expr(src, index, here); + } + ExprKind::Range { base, msb, lsb, .. } => { + check_expr(src, base, here); + check_expr(src, msb, here); + check_expr(src, lsb, here); + } + ExprKind::Member { base, .. } | ExprKind::Scope { base, .. } => check_expr(src, base, here), + ExprKind::Concat(items) | ExprKind::Inside { ranges: items, .. } => { + for i in items { + assert_inside(src, "element", i.span, here); + check_expr(src, &i.expr, here); + } + } + ExprKind::Repl { count, inner } => { + check_expr(src, count, here); + for i in inner { + check_expr(src, i, here); + } + } + ExprKind::AssignPattern(items) => { + for i in items { + assert_inside(src, "element", i.span, here); + check_opt_expr(src, i.key.as_ref(), here); + check_expr(src, &i.value, here); + } + } + ExprKind::ValueRange { lo, hi } => { + check_expr(src, lo, here); + check_expr(src, hi, here); + } + ExprKind::MinTypMax { min, typ, max } => { + check_expr(src, min, here); + check_expr(src, typ, here); + check_expr(src, max, here); + } + ExprKind::Type(ty) => { + for d in &ty.packed { + assert_inside(src, "dimension", d.span, here); + } + } + ExprKind::Ident(_) | ExprKind::Number(_) | ExprKind::Str(_) | ExprKind::Empty(_) => {} + } +} diff --git a/docs/features/spans/README.md b/docs/features/spans/README.md new file mode 100644 index 0000000..7ae3783 --- /dev/null +++ b/docs/features/spans/README.md @@ -0,0 +1,539 @@ +# spans + +## Goal + +Give every token, every comment and every AST node a byte range into the +source text, plus a utility that converts byte offsets to and from +line:column. This is pure data plumbing — no formatter behavior changes — but +it is the prerequisite TODO.md §6 names for the whole LSP effort (semantic +tokens, hover, go-to-definition, diagnostics all speak in ranges) and for the +two §2 formatter features that must splice original source by position: +`// verilog_format: off` fences and `--lines M-N` range formatting. Today the +parser records only 1-based line/col on tokens, which is enough to *print* a +diagnostic and useless for going the other way: from a node back to its bytes, +or from an editor position into the tree. + +## The span convention + +> **A node's span is its code extent: the first byte of its first token +> through the last byte of its last token. Comments are not part of it.** + +Rationale, since the alternative (span includes attached trivia) is what some +formatters do: + +- Every LSP request is about code. `textDocument/definition` on a signal must + highlight the declaration, not the paragraph of comment above it; range + formatting on "lines 10-20" must not drag in a doc comment that happens to + sit on line 9 because it is attached to the item on line 10. +- Trivia is *not* lost by this choice: `Comment` carries its own `span`, and + a comment is always reachable — it is attached to the node (`Meta.leading`, + `Meta.trailing`) or to a token (`Token.leading` / `Token.trailing`). A + consumer that wants "node plus its comments" takes the union; a consumer + that wants the code cannot recover it from a trivia-inclusive span. +- It composes: with trivia excluded, a child's span always nests inside its + parent's, which is asserted for every node type in + `every_node_span_nests_inside_its_parent`. Trivia-inclusive spans overlap + between siblings as soon as a comment sits between them. + +Two consequences worth stating explicitly: + +- **Attribute instances `(* ... *)` are inside the span.** They are real + tokens, not comments, so an `Item`/`Stmt` span starts at the `(*`. This + matters for format-off/range splicing: emitting the original bytes of an + item must reproduce its attributes. +- **A span is a byte range, never a char range.** `source[span.as_range()]` + is exact for multi-byte UTF-8 (tested: `λ`/`ü`/`✓` in comments, strings and + identifiers-adjacent positions). + +## Where spans live + +| carrier | span covers | +|---|---| +| `Token` | the token; `source[span] == text` for every kind but `Number` | +| `Comment` | `//` or `/* */` including the markers, excluding trailing whitespace | +| `RawText` | a directive, an attribute, or a macro invocation, verbatim | +| `SourceFile` | `0..len` — the whole text | +| `Item`, `Stmt`, `Expr` | the construct, attributes included, comments excluded | +| `GenIf`, `GenBlock`, `Dim` | as written, brackets/`begin`…`end` included | +| the 16 `Meta`-carrying element structs | the element, its separator comma excluded | + +The "element structs" are `NonAnsiPort`, `AnsiPort`, `ParamPort`, +`EnumMember`, `StructMember`, `Declarator`, `AssignPair`, `Instance`, +`OrderedConn`, `Connection`, `GateInstance`, `GenCaseItem`, `CaseItem`, +`TfArg`, `PatternItem`, `ExprItem` — i.e. exactly the nodes that already +carry a `Meta`, which is this codebase's existing notion of "an addressable +thing on its own line or list slot". + +### `Expr` became a wrapper struct + +`Expr` was an enum; it is now `Expr { kind: ExprKind, span: TextRange }` with +the old enum renamed to `ExprKind`. The alternatives considered: + +1. **A `span` field on each of the 22 variants.** Rejected: "the span of this + expression" would be a 22-arm match at every call site, and every new + variant is a new place to forget it. +2. **`Spanned` at every use site.** Rejected: it turns `Box` into + `Box>` in ~30 places, reads worse, and is a third shape in a + tree that already uses `{ meta, kind }` twice. +3. **The wrapper struct (shipped).** One field access for any expression, + the same shape `Item` and `Stmt` already have, and the compiler finds + every construction site. Cost: 62 mechanical edits (33 in `parser.rs`, 29 + in `format.rs`), all of them `Expr::X` → `ExprKind::X` plus `match e` → + `match &e.kind`. + +### Nodes deliberately *without* a span, and why + +- **The payload structs of `ItemKind` / `StmtKind` / `TypedefKind` variants** + — `Module`, `Typedef`, `ParamDecl`, `DataDecl`, `PortDecl`, `ContAssign`, + `Instantiation`, `GateInstantiation`, `GenFor`, `GenCase`, `FunctionDecl`, + `TaskDecl`, `MacroCall`, `EnumType`, `StructType`. Each is the sole payload + of one wrapping `Item`/`Stmt`, so its extent is *by construction* that + node's span; storing it twice would be two fields to keep in sync and one + more way to be subtly wrong. Take the enclosing `Item`/`Stmt` span. + (`GenIf` is the exception that proves the rule: a nested `else if` lives in + `GenElse::If(Meta, GenIf)` with no `Item` around it, so it needs its own.) +- **`DataType`** — an implicit type (`input [7:0] x`) has *no tokens of its + own*; a span would have to be a lie (`0..0`) or an `Option`, and `DataType` + is `Default`-constructed in five places where a default `TextRange` would + silently mean "byte 0". Its packed dimensions are `Dim`s, which do carry + spans. Known gap: hover over a type keyword resolves to the enclosing + declarator's span, not to the type alone. Revisit when `vlog_semantic` + needs it — the fix is a real `Option`, not a default. +- **Glue enums and helper structs** — `SensList`, `SensItem`, + `TimingControl`, `SimpleAssign`, `ForInit`, `ForStep`, `GenElse`, + `Connections`, `PortList`, `Meta`. They hold nodes that carry spans and are + not things an editor request addresses on its own. + +Nothing was found where a span is *impossible*; the list above is all +"redundant" or "would have to be a lie". + +## The two normalizations that break `source[span] == text` + +The lexer rewrites token text in exactly two places, both pre-existing, both +whitespace-only, and both now documented and pinned by the losslessness test: + +1. **A sized literal's tick spacing.** `8 'h FF` lexes as one `Number` whose + text is `8'hFF`. The span is the real extent (`8 'h FF`), so the span is + right and the text is normalized. +2. **Two same-line trailing comments merge into one `Comment`**, joined by a + single space (`/* a */ /* b */` → `/* a */ /* b */`). The merged node's + span covers both, so no byte is left unaccounted for. + +The test asserts that any piece whose text differs from its slice (a) is one +of those two kinds and (b) differs *only* in whitespace. + +## Losslessness + +`crates/vlog_parser/tests/spans.rs` asserts, over 24 hand-written sources and +every `.sv`/`.v` fixture in `crates/vlog_formatter/tests/fixtures/`: + +1. tokens and comments come out in source order and never overlap; +2. every byte not inside one of them is whitespace; +3. concatenating them with the whitespace between them reproduces the input + byte-for-byte; +4. each piece's `text` is its own source slice, modulo the two normalizations + above. + +That is the token-level half of TODO.md §6's `reconstruct(tree) == input`. +The AST-level half is not claimed: it needs a tree walker that emits nodes and +trivia in order, which does not exist yet. What this round establishes is that +no source byte is unreachable from the token stream — so if the AST-level +walker ever finds a gap, the gap is in the *tree*, not in the lexer. + +Both assertions were mutation-tested rather than assumed: giving `Number` +tokens the trimmed-text span makes assertion 4 fail (`"8'h"` vs `"8'hFF"`), +and starting a postfix segment's span at the segment instead of at the base +makes the nesting assertion fail (`$display` escaping `("%d", i)`). + +## LineIndex + +`vlog_parser::line_index::LineIndex` — built once from the source text, then +`line_col(offset) -> (line, col)` and `offset(line, col) -> Option`, +1-based, columns in **UTF-8 bytes** (the same unit as everything else here, +and what the lexer's existing `col` already counts). `line_range(line)` gives +a line's extent for range formatting. Nothing consumes it yet — it is the +half of the conversion that diagnostics don't need and every LSP request +does. + +Decisions, all unit-tested: + +- A trailing newline opens a last, empty line, so `"a\n"` has two lines. This + is what ruff and every editor do, and it is what makes `offset(2, 1)` at + end-of-file addressable. +- `\r` is an ordinary byte of the line it ends; only `\n` breaks a line. So a + CRLF line's last column is the `\r`. Anything else would make columns + disagree with byte offsets. +- Out-of-range input is clamped, not panicked: an offset past the end gives + the position at the end, and a column past the end of its line stops at the + line's end rather than wrapping onto the next one. A line number out of + range is `None` — that one is a caller error, not a rounding. +- Round-tripping every byte offset of a multi-byte file back through + `offset(line_col(o))` returns `o`. + +## Assumptions + +- **Files are under 4 GiB.** Offsets are `u32`, as in ruff and + rust-analyzer. A 4 GiB Verilog file is not a use case; `u32` halves the + size cost of putting a span on every node. Nothing enforces this: a larger + file would truncate offsets rather than fail, which is worth a guard if + vfmt ever grows an entry point that does not read the whole file into a + `String` first (today `usize`→`u32` conversion happens only in the lexer, + from offsets into a `&str` the CLI already read whole). +- **One file, no virtual sources.** A `TextRange` has no file identity; + cross-file navigation (TODO.md §6's workspace index) will need + `(FileId, TextRange)` pairs, which is the index's job, not this type's. +- **Spans are only meaningful for the exact text they were lexed from.** The + parser never rewrites source, so this holds trivially today. +- **The formatter does not read spans.** It is span-oblivious after this + change, which is what makes "no behavior change" checkable rather than + argued. + +## Handshakes + +**Consumed from `vlog_parser::lexer`:** nothing new. The lexer already +tracked `pos` while lexing; a span is that position pair recorded, and +line/col are untouched (still used by `LexError`/`ParseError` and by the +formatter's raw-text dedent). + +**Promised to `vlog_formatter`:** + +- Every AST node listed above carries `span: TextRange`. The formatter is not + required to use them and does not: this round changed exactly two things in + `format.rs`, both mechanical (`Expr::X` → `ExprKind::X`, and `match e` → + `match &e.kind` in `expr`, `expr_compact` and `binary_chain`'s `walk`). +- **`RawText.col` is unchanged and still load-bearing.** The macro-items + contract (`docs/features/macro-items/README.md`) — `raw.col` is what + `Fmt::raw_lines` dedents continuation lines by — is untouched; `RawText` + gained a `span` *alongside* `col`, it did not replace it. A span cannot + replace `col` in that role: `col` is a column, and the dedent needs the + column, not the offset. +- **`verify.rs` is untouched.** No normalization was added, broadened, or + weakened, so CLAUDE.md hard invariant #4 does not apply to this round — + and the corpus TSV being byte-identical is the evidence that the safety net + sees exactly what it saw before. + +**Recursion/chain budgets +(`docs/features/recursion-limit/README.md`):** no new budget is charged and +none is needed. `TextRange` is a `Copy` pair of `u32`s stored *inside* +existing nodes — it adds no root-to-leaf depth, no `Box`, and no new +recursion. The `Expr` wrapper adds one struct layer to the *type*, not to the +tree: `ExprKind::Binary` still holds `Box`, so the walk depth per +operator is what it was. The deep-nesting tests (`deep_nesting.rs`, the +parser's boundary tests at 62/63 and 256/257) pass unchanged, which is the +check that matters. + +**Requested of nobody.** No other module needs a change for this feature. + +## Status / TODO + +- [x] `span.rs`: `TextRange { start, end }` with `new`/`empty`/`len`/ + `is_empty`/`contains`/`as_range`, and nothing else. +- [x] Lexer: `span` on `RawTok`, `Token` and `Comment`; line/col kept. +- [x] Trimmed tokens (line comments, directives) span only their kept text. +- [x] Merged trailing comments span both comments. +- [x] AST: `Expr` → `Expr { kind: ExprKind, span }`; `span` on `SourceFile`, + `Item`, `Stmt`, `RawText`, `GenIf`, `GenBlock`, `Dim` and the 16 + `Meta`-carrying element structs. +- [x] Parser: `here()` / `last_end()` / `span_from()` / `expr_at()`, one + pattern used everywhere; separator commas excluded from element spans. +- [x] `line_index.rs`: `LineIndex` with both directions + `line_range`. +- [x] `tests/spans.rs`: token-stream losslessness (24 sources + the + formatter fixtures), node-span slicing, trivia exclusion, attribute + inclusion, multi-byte, CRLF, parent/child nesting over every node type. +- [x] Formatter untouched in behavior: full `.cases`/fixture/idempotency + suite green with zero snapshot churn. +- [x] Corpus TSV byte-identical before/after. +- [x] TODO.md §6 spans item checked. +- [ ] **Not done, deliberately:** AST-level `reconstruct(tree) == input`. + Needs a tree walker that emits nodes and trivia in order; the token + level is what spans alone can prove. Left as the open half of §6's + "keep the CST lossless" item. +- [ ] **Not done:** spans on `DataType` (see the gap list above) and on the + glue enums. Both are one-line additions if a consumer appears; adding + them now would be building for a second user that does not exist. + +## Work log + +### 2026-08-19 — dev agent + +- Read `CLAUDE.md`, `README.md`, TODO.md §2/§6, and the Handshakes of + `recursion-limit` and `macro-items` before touching code. Baseline: + `cargo test --workspace` **111 passed**, clippy silent, fmt clean, corpus + TSV md5 `3fab114f4f00626b254259e9dafe0ed7` (820 files, 468 parsed, 0 + verification errors, 0 crashes). +- **Chose "span = code extent" over "span includes attached trivia" before + writing anything**, because the choice is expensive to reverse once + consumers exist. The deciding argument is the nesting property: with + trivia excluded, a child's span always sits inside its parent's, so + `every_node_span_nests_inside_its_parent` is a total invariant over the + tree. With trivia included it is not even *true* — a comment between two + siblings belongs to one of them and the spans overlap — so there would be + nothing to assert. +- **Attributes go the other way** (inside the span) for the same practical + reason range formatting exists: they are tokens, and splicing an item's + source without its `(* keep *)` would drop code. +- **`Expr` wrapper vs. per-variant span**: went with the wrapper. Recorded + the three options and the reasoning above; the deciding factor was that a + per-variant span makes "span of this expression" a 22-arm match, which is + the operation every future consumer performs most. +- **The span/text divergences were found by the test, not predicted.** The + first run of the losslessness test failed on `8 'h FF` (number + normalization) and on two block comments on one line (the merge in the + attachment phase). Both are pre-existing lexer behavior that the formatter + depends on, so the fix was to make the *spans* right — the real extent for + the number, the union for the merged comment — and to state the divergence + in the test's assertion rather than paper over it. Line comments and + directives went the other way: they are `trim_end`-ed, so their span stops + where their text does and the dropped whitespace counts as inter-token + gap. +- **Mutation-tested both halves of the test** rather than trusting a green + first run: gave `Number` the trimmed span (assertion 4 fails as designed), + and started a postfix segment's span at the segment rather than at its base + (`$display` escapes `("%d", i)`). Reverted both; the working tree is clean + of them. +- **Element spans deliberately stop before the separator comma.** In the + parser the comma is eaten in the same loop iteration that builds the + element, so the naive placement of `span_from` would have swallowed it. + Every list site now takes the span *before* `eat_sym(",")`. An omitted + ordered connection (`u (a, , c)`) consumes no token at all and gets the + empty span where it would have started — `TextRange::new` clamps rather + than producing an inverted range. +- **`LineIndex` has no consumer yet**, so its semantics are fixed by tests + instead of by a caller: trailing newline opens an empty last line, `\r` + belongs to its line, offsets clamp and line numbers don't, and every byte + offset of a multi-byte file round-trips. +- Did not touch `verify.rs`, `tools/`, `corpus/`, or the formatter's + behavior. Did not run `git commit`/`git push`. +- **Concurrency note:** another agent's `config-discovery` work landed in the + same working tree during this round (`crates/vfmt/src/config.rs`, + `crates/vfmt/tests/cli.rs`, `args.rs`, `main.rs`, `README.md`, TODO.md §3). + Mid-round its `a_config_file_is_found_by_searching_upward` was failing at + `cli.rs:317` (with `indent = 4` in the config it expected `WIDE_SPLIT`, a + constant written with 2-space indent). Confirmed it was theirs and not this + feature's — reproduced end-to-end with the release binary, which correctly + emits 4-space indent for that config — and left it alone per CLAUDE.md's + "do not touch files outside your feature's stated scope". It was fixed on + their side before this round ended; the workspace is green as of the final + run below. + +**Results:** `cargo test --workspace` **158 passed, 0 failed** — of which +this feature's two crates are **99 passed** (up from 80: +3 unit tests in +`span.rs`, +6 in `line_index.rs`, +10 in `tests/spans.rs`; no existing test +changed, no snapshot or `.cases` churn). `cargo clippy +--workspace --all-targets` silent (0 warnings). `cargo fmt --all --check` +clean. Corpus: `tools/corpus_check.sh corpus` (read-only) produced a TSV with +md5 `3fab114f4f00626b254259e9dafe0ed7` — **byte-identical** to the +pre-change baseline; 820 files, 466 would-reformat, 2 ok-unchanged, 352 +parse-error, **0 verification errors, 0 crashes**. All four corpus repos +`git status --porcelain` clean apart from the pre-existing untracked +`.vfmt-corpus-rev` stamps. Files touched: +`crates/vlog_parser/src/{span,line_index}.rs` (new), +`crates/vlog_parser/src/{lib,token,lexer,ast,parser}.rs`, +`crates/vlog_parser/tests/spans.rs` (new), +`crates/vlog_formatter/src/format.rs` (mechanical only), `TODO.md` (§6 +checkbox), this README. + +## QA log + +### 2026-08-19 — QA agent + +Read `CLAUDE.md`, this README, and the diff (`span.rs`, `line_index.rs`, +`token.rs`, `lexer.rs`, `ast.rs`, `parser.rs`, `tests/spans.rs`, and the +`format.rs` renames) before probing. All probe files were written to +`crates/vlog_parser/tests/qa_*.rs` and deleted before this entry; none are +part of the final diff. No commits made. + +**Tool results — all green:** +- `cargo test --workspace`: **158 passed, 0 failed** at the time of this + round (later observed at 160 as the concurrent `config-discovery` agent's + work landed two more `vfmt` unit tests in the same tree — unrelated to + this feature, confirmed by re-diffing; this feature's own crates stayed at + 47 (`vlog_parser` unit) + 10 (`tests/spans.rs`) throughout). +- `cargo clippy --workspace --all-targets`: 0 warnings. +- `cargo fmt --all --check`: clean. +- `git diff --stat` on `format.rs`: read every hunk (68 lines). All of it is + `Expr::X` → `ExprKind::X` / `match e` → `match &e.kind`, plus one + struct-pattern change (`Some(Expr::Empty(comments))` → + `Some(Expr { kind: ExprKind::Empty(comments), .. })`) that is the same + mechanical substitution in pattern-match form. **Confirmed genuinely + mechanical, no behavior hunks found.** + +**Claim 1 (nesting is a total invariant) — PASS, independently verified.** +Wrote a from-scratch recursive checker (not copied from the dev's +`tests/spans.rs`) over 8 adversarial sources the dev's `SOURCES`/nesting test +does not use: a 10-way generate `if`/`else if` chain, 4-deep labeled +`begin`/`end` nesting, multi-line macro invocations with commas and parens +*inside* string arguments, a non-ANSI header with mixed port kinds and +stacked attributes, instance arrays (`u_arr [3:0]`) and multi-instance +statements, 8-deep parenthesized/cast expression nesting, a labeled +generate-for containing a nested case, and attributes on a statement inside +a function. All nested correctly. Also asserted an invariant the dev's test +does not check — **sibling spans within the same list are non-overlapping +and in non-decreasing source order** (ports, declarators, connections, +instances, gen-case items, block statements, case items, call args) — passed +on all 8 sources. `ItemKind`/`StmtKind`/`ExprKind` matches in both the dev's +checker and mine are compiler-enforced exhaustive (no wildcard arms), so no +variant is silently unchecked. + +**Claim 2 (coverage) — PASS.** Cross-checked the 16-element-struct list and +the "deliberately without a span" list against `ast.rs` mechanically: wrote +a small script that extracts each named struct/enum's full body text and +searches for a `span` field. Confirmed all 16 claimed element structs carry +`span`, and all of `DataType`, the payload structs (`Module`, `Typedef`, +`ParamDecl`, `DataDecl`, `PortDecl`, `ContAssign`, `Instantiation`, +`GateInstantiation`, `GenFor`, `GenCase`, `FunctionDecl`, `TaskDecl`, +`MacroCall`, `EnumType`, `StructType`) and the glue enums/structs +(`SensList`, `SensItem`, `TimingControl`, `SimpleAssign`, `ForInit`, +`ForStep`, `GenElse`, `Connections`, `PortList`, `Meta`) do **not**. Matches +the README's table and gap list exactly. + +**Claim 3 (LineIndex) — PASS, independently probed beyond the dev's own +unit tests.** Wrote 6 adversarial cases not in `line_index.rs`'s own +`#[cfg(test)]`: offset landing mid-multi-byte-character (byte 1 of `λ`) — +does not panic, returns a byte-precise column, and round-trips via +`offset()`; a file of only `\n\n\n` (4 lines, all empty, matches the +"trailing newline opens an empty line" rule applied recursively); a lone +`\r` not followed by `\n` — confirmed treated as an ordinary byte of its +line, only `\n` breaks (`"a\rb\n"` is one line, 4 columns); `line == 0` on a +real (non-empty) file still `None`; `line_range` on the file's last, +newline-less partial line excludes nothing extra; full round-trip over +every byte offset of a CRLF + multi-byte file. All 6 passed as documented. + +**Claim 4 (losslessness) — PASS, independently probed.** Wrote 6 additional +sources (CRLF plus multi-byte comment/string/identifier text together, a +lone mid-file `\r`, a sized literal with an unusual base-letter case and +underscores adjacent to a leading multi-byte comment, a multi-byte comment +glued directly to a token with no whitespace, two merged block comments both +containing multi-byte text, and an escaped identifier next to a `\u`-escaped +string) and asserted `token.text == source[span]` for every token/comment +except the two documented normalizations, and that those two differ only in +whitespace. All passed — no third divergence found. + +**Claim 5 (zero behavior change) — PASS, re-verified independently rather +than trusted from the work log.** +- Re-ran `tools/corpus_check.sh corpus`: TSV md5 **`3fab114f4f00626b254259e9dafe0ed7`** + — byte-identical to the dev's reported baseline. (Built from the current + tree, which also includes the now-committed `config-discovery` change; + the match confirms neither feature altered corpus-visible output.) +- Built a second `vfmt` release binary from a `git worktree` at `HEAD` + (`481cce2`, i.e. immediately pre-spans, config-discovery already + committed) and diffed its `--stdin-filename f - < f` output against the + working-tree binary (spans included) over **all 820 `.sv`/`.v` corpus + files**, not just 3-4: **0 differences**. Worktree removed after. +- Corpus repos' `git status --porcelain`: clean apart from the pre-existing + untracked `.vfmt-corpus-rev` stamps, confirmed again. +- No `.cases`/fixture/snapshot files under `crates/vlog_formatter/tests/` + show as modified in `git status`. + +**Claim 6 (mutation testing) — one additional claim mutation-tested beyond +the dev's two, with a genuine finding.** Mutated `parse_gen_if_inner` in +`parser.rs` (line ~1327) to compute `GenIf.span`'s `start` **after** +consuming the `if` keyword instead of before it (`let start = self.here();` +moved past `self.expect_kw("if")?;`), so the span would start at the `(` +instead of the `if`. Ran `cargo test -p vlog_parser`: **all 57 tests +(47 unit + 10 `tests/spans.rs`) still passed** — the mutation is +**undetected**. Reverted; `git diff crates/vlog_parser/src/parser.rs` +confirmed byte-identical to the dev's diff before and after (diffed the two +patches directly, exit 0). + - **Why this isn't a nesting-invariant violation (not BLOCKING under the + stated rule):** `every_node_span_nests_inside_its_parent` (and my + independent version) only assert *containment*, and a `GenIf` span + truncated at the front still nests fully inside its parent `Item` + span, and its children (`cond`, `then`) still nest inside the + (now-narrower) `GenIf` span, since they all start at or after `(`. + Containment survives; the total-nesting claim itself is not falsified + by this mutation. + - **What it does expose:** none of the existing tests slice-check + `GenIf.span`'s literal *content* (no test asserts + `slice(src, gi.span)` starts with `"if"` or matches the whole `if (...) + then [else ...]` construct the way `node_spans_slice_back_to_the_construct` + does for `Item`/`Declarator`/`Stmt` spans). The "as written, brackets/ + `begin`…`end` included" convention for `GenIf` (README's span table) is + therefore asserted by inspection and by the containment test, but not + by a test that would catch *this specific class* of off-by-one-token + start bug the way the dev's two mutation tests (`Number` trimmed span, + postfix segment start) do for their respective claims. + - **Severity: low, non-blocking.** Not a nesting violation, not a + formatting-behavior change (the formatter is span-oblivious), and the + actual shipped code is correct (`start = self.here()` before + `expect_kw("if")`, verified by reading `parser.rs:1327-1329` and by + `node_spans_slice_back_to_the_construct`-style spot checks in my own + probe). Recommend, as a follow-up and not a blocker: add one assertion + to `tests/spans.rs` that slices `gi.span` and checks it equals the + source text of the `if (...) ... [else ...]` construct verbatim (the + same style already used for `Item`/`Declarator`/`Stmt` in + `node_spans_slice_back_to_the_construct`), which would have caught this + mutation and gives the same content-level confidence the dev already + has for the node types that test covers. + +**Claim 7 (CLAUDE.md compliance) — PASS.** +- `u32`/4 GiB assumption: documented explicitly in README's Assumptions + section, including the "nothing enforces this" caveat and where a guard + would need to go. +- No `unwrap()`/`expect()`/`panic!` in the new library code: grepped + `span.rs`, `line_index.rs` (outside `#[cfg(test)]`), and every `+` line of + the `lexer.rs`/`parser.rs`/`ast.rs`/`token.rs` diffs — none found. +- Public items documented: every `pub fn`/`pub struct` in `span.rs` and + `line_index.rs` carries a doc comment (scripted check). New `pub span: + TextRange` fields on existing structs each carry a one-line doc comment + in the diff. `Expr.kind` has none, but this matches pre-existing style — + `Item.meta`/`Item.kind` and `Stmt.meta`/`Stmt.kind` were undocumented + fields before this change too (checked `git show HEAD:.../ast.rs`), so + this is "match the style of the surrounding code," not a new gap. +- README sections: all seven required sections present and non-empty + (Goal, Assumptions, Handshakes, Status/TODO, Work log, QA log, Review). +- `TODO.md` §6 spans checkbox: checked, with an honest annotation pointing + at the exact deliverables and explicitly not overclaiming + ("token-level losslessness is a test") — matches the README's own + "AST-level reconstruct not done" caveat. Not dishonest. +- `verify.rs` / `tests/verification.rs`: confirmed untouched by this diff + (`git status`/`git diff --stat` show no changes relative to `HEAD`, + which already includes the unrelated, separately-committed + `config-discovery` change) — matches the Handshakes claim that CLAUDE.md + invariant #4 does not apply to this round. + +**Overall: no BLOCKING findings.** One low-severity, non-blocking test- +coverage gap found and documented above (Claim 6). All other claims verified +independently and pass, including two claims (losslessness sources and +LineIndex edge cases) probed with adversarial inputs disjoint from the +dev's own test list, and the full 820-file corpus diffed byte-for-byte +against a pre-spans binary rather than sampled. + +## Review + +**2026-08-19 — lead. Verdict: accepted and committed, with one lead-added +test. This is the LSP track's cornerstone, done the boring way.** + +The three design calls are all right, and all for stated reasons: + +1. **Code-extent spans (trivia excluded)** because it makes child-nests- + in-parent a *total, assertable* invariant — the argument that decided + it is exactly the kind of reasoning these READMEs exist to record. + Attributes inside the span (they're tokens), comments outside with + their own spans: correct on both counts. +2. **`Expr { kind, span }`** over per-variant spans or `Spanned` — + least invasive shape that answers "span of any node" in one field + access; 62 mechanical edits was the honest price. +3. **Skipping payload structs whose extent equals their wrapper's** — + storing a fact twice is two things to desync. The `DataType` + implicit-type gap is real and correctly documented rather than + papered over with a lying span. + +The losslessness test earning its keep before the feature even shipped — +surfacing the sized-literal and merged-trailing-comment normalizations +nobody had written down — is the pattern to notice: invariant tests find +facts, not just bugs. QA's verification was thorough where it counted +(all-820-file output diff, from-scratch nesting checker with an extra +sibling-ordering invariant, mutation tests both directions). + +Lead addition on acceptance: QA's mutation test proved `GenIf.span`'s +content was unpinned (containment held, content didn't) — added +`a_gen_if_span_slices_back_to_its_text` to `tests/spans.rs` so the +mutation now fails. The remaining mutation-coverage question (which +other node spans are content-pinned only transitively?) can ride along +whenever the next spans consumer (fences, range formatting, LSP) starts +exercising them for real. + +Unblocked by this feature: format-off fences and `--lines` range +formatting (TODO §2), and every §6 LSP capability. Next foundations: +error-tolerant parsing, then the `` `define`` table.