Add dynamic-types and one-parse (round 19)

dynamic-types: queues ($ as an expression primary -- one grammar
addition and [$], [$:N], q[$-1] all fall out of existing machinery),
dynamic [] and wildcard [*] dims (DimKind, the round's one
non-additive AST change: three consumers, all updated), empty {}
literals, named call arguments f(.a(x)) as ExprKind::NamedArg,
case ... inside with range labels, bare @event sensitivities (also
fixing a pre-existing invented-parens refusal), and macro items
before ident-dot statements. Everything structural, nothing
verbatim; verify.rs and fence.rs byte-identical. Corpus 578 ->
636/820 formattable (70.5% -> 77.6%), parse-error 242 -> 184, 58
gained / 0 lost by path, all 636 round-tripped, all 578 previously-
formattable files byte-compared old-vs-new with zero differences.
Two newly-reachable comment drops fixed in-round (one pre-existing,
one this round's own new code -- split documented honestly post-QA).
New top blockers: interface (25), the `else head-swap (13).

one-parse: LintContext::from_parse accepts pre-built parse products
(Backing enum forced by SourceFile: !Clone; new() stays a one-line
wrapper -- all 12 rule files byte-untouched); ParsedSource::parse
lexes once; vfmt check parses once per file; the server lints from
Document's own products, eliminating the per-keystroke second parse.
Behavior identity proven at the byte level (2.4MB corpus JSON, 13
server publishes, corpus-wide --fix); check --threads 1 20% faster,
server didChange latency roughly halved. protected_regions left
alone per its documented anti-drift signature. Lead fixes on
acceptance: the from_parse contract-cost doc sentence, and a stale-
tree guard test in the server (QA's sabotage passed all 773 tests --
nothing pinned text/tree agreement; now one test does, through the
merged diagnostics path where the stale warning actually lives).

791 workspace tests. Dev: 2 Fable agents; QA: 2 Opus agents; reviews
in docs/features/{dynamic-types,one-parse}/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-19 20:22:18 -07:00
1 parent e9008b680c
commit da1448ecd0
20 files changed
+2478 -96

No files matched your search

+305 -20
View File
@@ -687,10 +687,64 @@ impl<'a> Parser<'a> {
fn parse_expr_item(&mut self) -> PResult<ExprItem> {
let start = self.here();
let meta = self.take_meta();
let expr = self.parse_expr()?;
// Two element-only shapes no expression can start with: a named call
// argument (`.value(x)`, `.name()`) and a `[lo:hi]` value range (a
// `case ... inside` label). Both are recognized here, in the shared
// element parse, because rejecting them in the lists that cannot
// legally hold them would gain nothing — vfmt checks legality
// nowhere else either, and a wrong guess emits the same tokens.
let expr = if self.cur().is_sym(".") && self.nth(1).kind == TokenKind::Ident {
self.parse_named_arg()?
} else if self.cur().is_sym("[") {
self.parse_value_range()?
} else {
self.parse_expr()?
};
Ok(ExprItem { meta, expr, span: self.span_from(start) })
}
/// `.name(expr)` / `.name()` — a named call argument. The cursor is on
/// the `.` and the next token is an identifier.
fn parse_named_arg(&mut self) -> PResult<Expr> {
let start = self.here();
self.bump(); // .
let Name { text: name, span: name_span } = self.expect_name()?;
let mark = self.pending_trailing.len();
let paren_start = self.here();
self.expect_sym("(")?;
let (value, close_comments) = if self.cur().is_sym(")") {
// `.name()` — explicitly empty, keeping any comments written
// between the parens, exactly as an empty connection does. The
// span covers the `( )` pair.
let comments = self.take_around(mark);
self.bump();
(self.expr_at(paren_start, ExprKind::Empty(comments)), Vec::new())
} else {
let value = self.parse_expr()?;
// A comment before the closing `)` (`.src(5'd0 /* x0 */)`)
// stays inside the parens, as a connection's does.
let close = self.take_around(mark);
self.expect_sym(")")?;
(value, close)
};
Ok(self.expr_at(
start,
ExprKind::NamedArg { name, name_span, value: Box::new(value), close_comments },
))
}
/// `[lo:hi]` — a value range standing as a list element (a
/// `case ... inside` label). The cursor is on the `[`.
fn parse_value_range(&mut self) -> PResult<Expr> {
let start = self.here();
self.bump(); // [
let lo = self.parse_expr()?;
self.expect_sym(":")?;
let hi = self.parse_expr()?;
self.expect_sym("]")?;
Ok(self.expr_at(start, ExprKind::ValueRange { lo: Box::new(lo), hi: Box::new(hi) }))
}
/// Continue a comma-separated expression list whose first element is
/// already parsed, harvesting the comment written after each comma and
/// the ones before `close` — the token that ends the list, which the
@@ -759,7 +813,12 @@ impl<'a> Parser<'a> {
match next.kind {
TokenKind::Symbol => false,
TokenKind::Ident if !next.is_macro() => {
self.cur().has_macro_args() || (self.nth(2).is_sym("#") && self.nth(3).is_sym("("))
self.cur().has_macro_args()
|| (self.nth(2).is_sym("#") && self.nth(3).is_sym("("))
// `` `WAIT_FOR_RESET `` ⏎ `cov.cg.sample(...);` — a
// declarator name is never followed by `.`, so the macro
// stands alone and the identifier opens a statement.
|| self.nth(2).is_sym(".")
}
_ => true,
}
@@ -1075,8 +1134,15 @@ impl<'a> Parser<'a> {
if self.tokens.get(p + 2).is_some_and(|t| t.is_sym("(")) {
let name = self.scan_matching(p + 2, "(", ")");
let after = self.tokens.get(name + 1);
if self.tokens.get(name).is_some_and(|t| t.kind == TokenKind::Ident)
&& !after.is_some_and(|t| t.is_sym("(") || t.is_sym("["))
// `[` after the declarator is an instance array range only
// when a connection list follows it; `item #(A, B) q[$];`
// is a declaration whose declarator has an unpacked dim.
let is_instance = after.is_some_and(|t| t.is_sym("("))
|| (after.is_some_and(|t| t.is_sym("[")) && {
let end = self.scan_matching(name + 1, "[", "]");
self.tokens.get(end).is_some_and(|t| t.is_sym("("))
});
if self.tokens.get(name).is_some_and(|t| t.kind == TokenKind::Ident) && !is_instance
{
return self.parse_data_decl().map(ItemKind::DataDecl);
}
@@ -1637,10 +1703,21 @@ impl<'a> Parser<'a> {
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 };
let kind = if self.eat_sym("]") {
// `[]` — a dynamic array.
dims.push(Dim { kind: DimKind::Dynamic, span: self.span_from(start) });
continue;
} else if self.cur().is_sym("*") && self.nth(1).is_sym("]") {
// `[*]` — a wildcard-keyed associative array.
self.bump();
DimKind::Wildcard
} else {
let a = self.parse_expr()?;
let b = if self.eat_sym(":") { Some(self.parse_expr()?) } else { None };
DimKind::Range { a, b }
};
self.expect_sym("]")?;
dims.push(Dim { a, b, span: self.span_from(start) });
dims.push(Dim { kind, span: self.span_from(start) });
}
Ok(dims)
}
@@ -2794,7 +2871,9 @@ impl<'a> Parser<'a> {
self.expect_sym("(")?;
let expr = self.parse_expr()?;
self.expect_sym(")")?;
// `case (x) inside` is not supported; plain case kinds only.
// `case (x) inside` — the same statement with one extra token, whose
// labels may be `[lo:hi]` ranges (handled by `parse_expr_item`).
let inside = self.eat_kw("inside");
let mut items = Vec::new();
while !self.at_body_end("endcase") {
let start = self.here();
@@ -2817,7 +2896,7 @@ impl<'a> Parser<'a> {
}
let dangling = self.take_dangling();
self.expect_closer("endcase")?;
Ok(StmtKind::Case { qualifier, kw, expr, items, dangling })
Ok(StmtKind::Case { qualifier, kw, expr, inside, items, dangling })
}
fn parse_for_step(&mut self) -> PResult<ForStep> {
@@ -2854,12 +2933,20 @@ impl<'a> Parser<'a> {
return Ok(StmtKind::VarDecl(d));
}
}
// The statement's own meta drained the pending comments, so anything
// trailing from here on was written inside this statement.
let mark = self.pending_trailing.len();
let lhs = self.parse_unary()?;
let op = self.cur().text.clone();
let is_assign = self.cur().kind == TokenKind::Symbol
&& (ASSIGN_OPS.contains(&op.as_str()) || op == "<=");
if is_assign {
// Comments on either side of the operator stay on their side of
// it (`x[6:0] /* opcode */ = v;`); left in the pending buffers
// they would be lost and the safety net would refuse the file.
let op_comments = self.take_around(mark);
self.bump();
let rhs_comments = self.take_around(mark);
let timing = if self.cur().is_sym("#") {
self.bump();
Some(TimingControl::Delay(self.parse_delay_value()?))
@@ -2871,7 +2958,7 @@ impl<'a> Parser<'a> {
};
let rhs = self.parse_expr()?;
self.expect_sym(";")?;
Ok(StmtKind::Assign { lhs, op, timing, rhs })
Ok(StmtKind::Assign { lhs, op, op_comments, rhs_comments, timing, rhs })
} else {
self.expect_sym(";")?;
Ok(StmtKind::ExprStmt(lhs))
@@ -2886,16 +2973,18 @@ impl<'a> Parser<'a> {
return Ok(SensList::Star { before, after: Vec::new() });
}
if self.cur().kind == TokenKind::Ident {
// `@ident` without parens.
// `@ident` / `@a.b` without parens; recorded as `Bare` so the
// formatter prints no parens back — inventing them is a
// token-stream change the safety net refuses.
let start = self.here();
let name = self.expect_ident()?;
let expr = self.expr_at(start, ExprKind::Ident(name));
return Ok(SensList::List(vec![SensItem {
meta: Meta::default(),
sep: None,
edge: None,
expr,
}]));
let mut expr = self.expr_at(start, ExprKind::Ident(name));
while self.cur().is_sym(".") && self.nth(1).kind == TokenKind::Ident {
self.bump();
let member = self.expect_ident()?;
expr = self.expr_at(start, ExprKind::Member { base: Box::new(expr), name: member });
}
return Ok(SensList::Bare(expr));
}
if self.cur().is_sym("(") && self.nth(1).is_sym("*") {
// `@( /* c */ * /* d */ )`: the comments belong to the star, not
@@ -3205,7 +3294,16 @@ impl<'a> Parser<'a> {
if !self.cur().is_sym(")") {
let arg_start = self.here();
let meta = self.take_meta();
let first_expr = self.parse_expr_or_type()?;
// A named first argument (`csr_wr(.ptr(x), ...)`) takes
// the same dispatch later elements get in
// `parse_expr_item`; anything else may be a type
// (`$bits(int)`).
let first_expr =
if self.cur().is_sym(".") && self.nth(1).kind == TokenKind::Ident {
self.parse_named_arg()?
} else {
self.parse_expr_or_type()?
};
let first =
ExprItem { meta, expr: first_expr, span: self.span_from(arg_start) };
args = self.parse_expr_list(first, ")")?;
@@ -3275,6 +3373,15 @@ impl<'a> Parser<'a> {
TokenKind::Symbol => {
let sym = t.text.clone();
match sym.as_str() {
// A bare `$` — the upper bound of a queue (`q[$]`,
// `q[$-1]`, `int q[$]`). Kept an ordinary name, like
// `new`/`this`/`super`: one leaf makes every position
// work through the existing expression grammar, and vfmt
// checks legality nowhere else either.
"$" => {
self.bump();
Ok(self.expr_at(start, ExprKind::Ident("$".to_string())))
}
"(" => {
// Comments written just inside the parens stay there;
// anything else would move them across a token.
@@ -3309,7 +3416,11 @@ impl<'a> Parser<'a> {
"{" => {
self.bump();
if self.cur().is_sym("}") {
return self.error("empty concatenation");
// `{}` — the empty queue/dynamic-array literal
// (`q = {};`). Illegal as a Verilog concatenation,
// but vfmt is not a legality checker.
self.bump();
return Ok(self.expr_at(start, ExprKind::Concat(Vec::new())));
}
let first = self.parse_expr_item()?;
if self.cur().is_sym("{") {
@@ -4333,4 +4444,178 @@ mod tests {
assert!(parse_deep(deep(MAX_NESTING_DEPTH as usize - 1)).is_ok());
assert_too_deep(deep(MAX_NESTING_DEPTH as usize + 1));
}
// ------------------------------------------------------------------
// Dynamic types (queues, dynamic/associative arrays, named args)
// ------------------------------------------------------------------
fn first_decl(file: &SourceFile) -> &DataDecl {
let ItemKind::DataDecl(d) = &file.items[0].kind else { panic!("expected a declaration") };
d
}
#[test]
fn a_queue_dim_is_a_range_whose_bound_is_a_dollar_ident() {
let f = parse_ok("module m;\n string q[$];\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::DataDecl(d) = &m.items[0].kind else { panic!("expected a declaration") };
let [dim] = &d.declarators[0].unpacked[..] else { panic!("expected one dim") };
let DimKind::Range { a, b } = &dim.kind else { panic!("expected a range dim") };
assert!(matches!(&a.kind, ExprKind::Ident(n) if n == "$"));
assert!(b.is_none());
}
#[test]
fn a_bounded_queue_keeps_its_bound() {
let f = parse_ok("int q[$:8];\n");
let [dim] = &first_decl(&f).declarators[0].unpacked[..] else { panic!("one dim") };
let DimKind::Range { a, b } = &dim.kind else { panic!("expected a range dim") };
assert!(matches!(&a.kind, ExprKind::Ident(n) if n == "$"));
assert!(matches!(&b.as_ref().expect("bound").kind, ExprKind::Number(n) if n == "8"));
}
#[test]
fn a_dynamic_array_dim_is_empty_and_a_wildcard_dim_is_a_star() {
let f = parse_ok("int a[];\nlogic b[*];\n");
let [dim] = &first_decl(&f).declarators[0].unpacked[..] else { panic!("one dim") };
assert!(matches!(dim.kind, DimKind::Dynamic));
let ItemKind::DataDecl(d) = &f.items[1].kind else { panic!("expected a declaration") };
assert!(matches!(d.declarators[0].unpacked[0].kind, DimKind::Wildcard));
}
#[test]
fn a_multi_dim_declarator_may_end_in_a_queue_or_dynamic_dim() {
let f = parse_ok("payload_t q[NumInp-1:0][$];\nseq_t s[NUM_HARTS][];\n");
let dims = &first_decl(&f).declarators[0].unpacked;
assert_eq!(dims.len(), 2);
assert!(matches!(&dims[0].kind, DimKind::Range { b: Some(_), .. }));
assert!(matches!(&dims[1].kind, DimKind::Range { a, b: None }
if matches!(&a.kind, ExprKind::Ident(n) if n == "$")));
let ItemKind::DataDecl(d) = &f.items[1].kind else { panic!("expected a declaration") };
assert!(matches!(d.declarators[0].unpacked[1].kind, DimKind::Dynamic));
}
#[test]
fn a_parameterized_type_with_a_queue_declarator_is_a_declaration_not_an_instance() {
let f = parse_ok("class c;\n item_t #(A, B) q[$];\nendclass\n");
let c = class_of(&f);
let ItemKind::DataDecl(d) = &c.items[0].kind else { panic!("expected a declaration") };
assert_eq!(d.ty.name, "item_t");
assert!(d.ty.params.is_some());
assert_eq!(d.declarators[0].name, "q");
}
#[test]
fn an_empty_brace_pair_is_an_empty_concat() {
let f = parse_ok("module m;\n initial q = {};\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected initial") };
let StmtKind::Assign { rhs, .. } = &stmt.kind else { panic!("expected an assignment") };
assert!(matches!(&rhs.kind, ExprKind::Concat(items) if items.is_empty()));
}
#[test]
fn dollar_indexes_parse_as_ordinary_expressions() {
// `q[$]` and `q[$-1]` — the `$` is an expression leaf, so member
// access and arithmetic around it need no special cases.
let f = parse_ok("module m;\n initial q[$].label = q2[$-1];\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected initial") };
let StmtKind::Assign { lhs, .. } = &stmt.kind else { panic!("expected an assignment") };
let ExprKind::Member { base, name } = &lhs.kind else { panic!("expected a member") };
assert_eq!(name, "label");
assert!(matches!(&base.kind, ExprKind::Index { .. }));
}
#[test]
fn named_call_arguments_keep_their_names_and_values() {
let f = parse_ok(
"module m;\n initial csr_wr(.ptr(ral.ovrd), .value(x), .flag());\nendmodule\n",
);
let src = "module m;\n initial csr_wr(.ptr(ral.ovrd), .value(x), .flag());\nendmodule\n";
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected initial") };
let StmtKind::ExprStmt(call) = &stmt.kind else { panic!("expected a call statement") };
let ExprKind::Call { args, .. } = &call.kind else { panic!("expected a call") };
let names: Vec<&str> = args
.iter()
.map(|a| match &a.expr.kind {
ExprKind::NamedArg { name, name_span, .. } => {
assert_eq!(&src[name_span.start as usize..name_span.end as usize], name);
name.as_str()
}
other => panic!("expected a named argument, got {other:?}"),
})
.collect();
assert_eq!(names, ["ptr", "value", "flag"]);
let ExprKind::NamedArg { value, .. } = &args[2].expr.kind else { unreachable!() };
assert!(matches!(value.kind, ExprKind::Empty(_)), "`.flag()` is explicitly empty");
}
#[test]
fn case_inside_records_the_keyword_and_takes_range_labels() {
let f = parse_ok(
"module m;\n initial case (x) inside\n [A:B], C: y = 1;\n default: y = 0;\n endcase\nendmodule\n",
);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected initial") };
let StmtKind::Case { inside, items, .. } = &stmt.kind else { panic!("expected a case") };
assert!(*inside);
assert!(matches!(&items[0].labels[0].expr.kind, ExprKind::ValueRange { .. }));
assert!(matches!(&items[0].labels[1].expr.kind, ExprKind::Ident(n) if n == "C"));
assert!(items[1].labels.is_empty(), "default has no labels");
}
#[test]
fn a_plain_case_is_not_inside() {
let f = parse_ok("module m;\n initial case (x)\n 1: y = 1;\n endcase\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected initial") };
let StmtKind::Case { inside, .. } = &stmt.kind else { panic!("expected a case") };
assert!(!*inside);
}
#[test]
fn a_bare_event_control_is_recorded_without_parens() {
let f = parse_ok("module m;\n task t;\n @ev;\n @a.b.c;\n endtask\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Task(task) = &m.items[0].kind else { panic!("expected a task") };
let StmtKind::Timing { control: TimingControl::Event(SensList::Bare(e)), .. } =
&task.stmts[0].kind
else {
panic!("expected a bare event control")
};
assert!(matches!(&e.kind, ExprKind::Ident(n) if n == "ev"));
let StmtKind::Timing { control: TimingControl::Event(SensList::Bare(e)), .. } =
&task.stmts[1].kind
else {
panic!("expected a bare event control")
};
assert!(matches!(&e.kind, ExprKind::Member { name, .. } if name == "c"));
}
#[test]
fn a_parenthesized_event_control_stays_a_list() {
// `@(ev)` and `@ev` are different token streams; each keeps its own.
let f = parse_ok("module m;\n task t;\n @(ev);\n endtask\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Task(task) = &m.items[0].kind else { panic!("expected a task") };
assert!(matches!(
&task.stmts[0].kind,
StmtKind::Timing { control: TimingControl::Event(SensList::List(_)), .. }
));
}
#[test]
fn a_macro_followed_by_a_hierarchical_call_stands_alone() {
// `` `WAIT_FOR_RESET `` ⏎ `cov.cg.sample(a);` — a declarator name is
// never followed by `.`, so the macro is a standalone statement.
let f = parse_ok(
"module m;\n task t;\n `WAIT_FOR_RESET\n cov.cg.sample(a);\n endtask\nendmodule\n",
);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Task(task) = &m.items[0].kind else { panic!("expected a task") };
assert!(matches!(&task.stmts[0].kind, StmtKind::MacroStmt(_)));
assert!(matches!(&task.stmts[1].kind, StmtKind::ExprStmt(_)));
}
}