Add spans: byte ranges on every token and AST node, plus LineIndex
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 <[email protected]>
This commit is contained in:
1 parent
481cce2a3e
commit
901a78ccb2
11 files changed
+1831
-128
No files matched your search
@@ -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<T>(&self, message: impl Into<String>) -> PResult<T> {
|
||||
let t = self.cur();
|
||||
let shown = if t.kind == TokenKind::Eof { "<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<ExprItem> {
|
||||
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<Item> {
|
||||
// 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<ItemKind> {
|
||||
@@ -660,6 +706,7 @@ impl Parser {
|
||||
}
|
||||
|
||||
fn parse_param_port(&mut self) -> PResult<ParamPort> {
|
||||
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<AnsiPort> {
|
||||
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<Vec<Dim>> {
|
||||
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<Expr> {
|
||||
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<Vec<Declarator>> {
|
||||
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<Expr> {
|
||||
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<Connection> {
|
||||
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<GenIf> {
|
||||
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<GenFor> {
|
||||
@@ -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<GenBlock> {
|
||||
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<Stmt> {
|
||||
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<StmtKind> {
|
||||
@@ -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<Expr> {
|
||||
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<ExprItem> = 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<Expr> {
|
||||
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");
|
||||
|
||||
Reference in new issue
Block a user