Decomposition, lane A: vlog_parser's parser.rs and ast.rs become twenty-seven modules, a pure move

TODO section 28, lane A (the file-size rule in CLAUDE.md).
parser.rs (8 786 production + 5 044 test lines) becomes parser/{mod,
cursor, recover, directive, split, verbatim, item, module, decl, tf,
instance, stmt, keyword_stmt, expr, primary, class, covergroup,
assertion, sva}.rs with the tests regrouped into parser/tests/ (14
files, 309 tests, same names and bodies); ast.rs (3 313) becomes
ast/{mod, module, decl, stmt, expr, class, covergroup, sva}.rs, every
type re-exported so vlog_parser::ast::X is unchanged. Nothing over 800
production lines; the two keyword dispatch tables kept whole and
documented as such, parse_keyword_stmt in a file of its own. Carved by
a line-range manifest that had to concatenate back to the original
byte for byte before writing; 149 methods and 18 items pub(super) as
the compiler demanded. Proof: per-binary test counts identical
(workspace 3 215 / 48), 4 807 corpus + opentitan files byte-identical
to the v0.33.0 binary, cargo doc item list unchanged, and a multiset +
signature census done by the dev, redone by QA, re-run by the lead.

docs/features/decomposition-parser/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-09-02 21:13:32 -07:00
1 parent 159f6a0bd8
commit 9b93f33ae3
45 files changed
+17999 -17241

No files matched your search

+370
View File
@@ -0,0 +1,370 @@
//! Expressions: primaries, casts, patterns, calls and their arguments.
use super::*;
#[test]
fn expressions() {
parse_ok(
"module e;
assign x = a ? {b, c[3:0], {4{d}}} : (e + f) * g;
assign y = data[base +: 8] | pkg::CONST;
assign z = int'(w) + 8'hFF + $clog2(DEPTH);
endmodule",
);
}
/// `instr_h = new instr_template[name];` — IEEE 1800 §8.12 shallow copy
/// (corpus `ibex/vendor/google_riscv-dv/src/isa/riscv_instr.sv:238`).
#[test]
fn new_followed_by_a_name_is_a_shallow_copy() {
let file = parse_ok(
"class c;\n\
function void f();\n\
instr_h = new instr_template[name];\n\
endfunction\n\
endclass",
);
let ItemKind::Class(c) = &file.items[0].kind else { panic!("expected a class") };
let ItemKind::Function(f) = &c.items[0].kind else { panic!("expected a function") };
let StmtKind::Assign { rhs, .. } = &f.stmts[0].kind else { panic!("expected an assign") };
let ExprKind::New(src) = &rhs.kind else { panic!("expected a shallow copy: {:?}", rhs.kind) };
assert!(matches!(src.kind, ExprKind::Index { .. }), "got {:?}", src.kind);
}
/// The constructor, the bare handle and the dynamic-array resize are all
/// followed by a symbol, so they keep parsing as they always did.
#[test]
fn the_other_spellings_of_new_keep_their_old_parse() {
let file = parse_ok(
"class c;\n\
function void f();\n\
a = new;\n\
b = new(x, y);\n\
d = new[n];\n\
new = 1;\n\
endfunction\n\
endclass",
);
let ItemKind::Class(c) = &file.items[0].kind else { panic!("expected a class") };
let ItemKind::Function(f) = &c.items[0].kind else { panic!("expected a function") };
let rhs_kinds: Vec<&ExprKind> = f
.stmts
.iter()
.map(|s| {
let StmtKind::Assign { rhs, .. } = &s.kind else { panic!("expected an assign") };
&rhs.kind
})
.collect();
assert!(matches!(rhs_kinds[0], ExprKind::Ident(n) if n == "new"));
assert!(matches!(rhs_kinds[1], ExprKind::Call { .. }));
assert!(matches!(rhs_kinds[2], ExprKind::Index { .. }));
// `new` used as an ordinary variable name is still an ordinary name.
assert!(matches!(rhs_kinds[3], ExprKind::Number(_)));
}
/// `` 32'h`DM_ADDR `` — the lexer stops the number at the base, and the
/// parser joins the pair back into one literal.
#[test]
fn a_macro_digit_number_is_one_primary_expression() {
let file = parse_ok("module m;\nlocalparam int A = 32'h`DM_ADDR;\nendmodule");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let ItemKind::ParamDecl(p) = &m.items[0].kind else { panic!("expected a localparam") };
let init = p.declarators[0].init.as_ref().expect("a value");
assert!(
matches!(&init.kind, ExprKind::Number(n) if n == "32'h`DM_ADDR"),
"got {:?}",
init.kind
);
}
/// A base with no digits and no macro after it stays an error: the macro
/// must be the very next token.
#[test]
fn a_base_only_number_without_a_macro_is_a_parse_error() {
let src = "module m;\nlocalparam int A = 32'h`ifdef;\nendmodule";
let toks = tokenize(src).expect("lex error");
assert!(parse(toks, src).is_err(), "a directive is not the number's digits");
}
#[test]
fn a_parameterized_class_reference_is_one_expression_segment() {
let f = parse_ok("class c;\n function void f();\n \
x = uvm_config_db#(virtual bus_if)::get(this);\n endfunction\nendclass\n");
let ItemKind::Function(g) = &class_of(&f).items[0].kind else { panic!("expected a function") };
let StmtKind::Assign { rhs, .. } = &g.stmts[0].kind else { panic!("expected an assignment") };
// call( scope( parameterized( ident ) ) )
let ExprKind::Call { callee, .. } = &rhs.kind else { panic!("expected a call") };
let ExprKind::Scope { base, name, .. } = &callee.kind else { panic!("expected a scope") };
assert_eq!(name, "get");
let ExprKind::Parameterized { base, params } = &base.kind else {
panic!("expected a parameterized reference")
};
assert_eq!(params.text, "#(virtual bus_if)");
assert!(matches!(&base.kind, ExprKind::Ident(n) if n == "uvm_config_db"));
}
#[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 a_name_that_contains_a_new_keyword_is_still_a_name() {
// The keyword/identifier boundary: only the whole word is reserved.
let f = parse_ok(
"module checker_x;\n wire config_reg;\n logic library_sel;\n assign config_reg = library_sel;\nendmodule\n",
);
assert_eq!(module_of(&f).name, "checker_x");
}
/// Run `check` on the right-hand side of `src`'s first continuous
/// assignment. A closure rather than a getter: the parsed file owns the
/// expression and must outlive the borrow.
fn with_assign_rhs(src: &str, check: impl FnOnce(&Expr)) {
let f = parse_ok(src);
let ItemKind::ContAssign(a) = &module_of(&f).items[0].kind else {
panic!("expected an assign")
};
check(&a.assigns[0].rhs);
}
#[test]
fn a_cast_base_may_be_parenthesized_or_scoped() {
// corpus/common_cells/src/lzc.sv:67 and
// corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_lc_sender.sv:32.
with_assign_rhs("module m;\n assign a = (NumLevels)'(unsigned'(j));\nendmodule\n", |e| {
let ExprKind::Cast { ty, .. } = &e.kind else { panic!("expected a cast") };
assert!(matches!(ty.kind, ExprKind::Paren { .. }), "base is the parenthesized expression");
});
with_assign_rhs("module m;\n assign a = lc_ctrl_pkg::TxWidth'(x);\nendmodule\n", |e| {
let ExprKind::Cast { ty, .. } = &e.kind else { panic!("expected a cast") };
assert!(matches!(ty.kind, ExprKind::Scope { .. }), "base is the scoped name");
});
}
#[test]
fn a_cast_base_that_is_not_a_constant_primary_is_still_rejected() {
let msg = parse_err("module m;\n assign a = f(1)'(x);\nendmodule\n");
assert!(msg.contains("unsupported cast base expression"), "unexpected: {msg}");
}
#[test]
fn the_implication_operators_are_right_associative_and_bind_loosest() {
// `a ? b : c -> d` is `(a ? b : c) -> d`; `a -> b -> c` is
// `a -> (b -> c)` (IEEE 1800 §11.3.2).
with_assign_rhs("module m;\n assign y = a ? b : c -> d;\nendmodule\n", |e| {
let ExprKind::Binary { lhs, op, .. } = &e.kind else { panic!("expected an implication") };
assert_eq!(op, "->");
assert!(matches!(lhs.kind, ExprKind::Ternary { .. }), "the `? :` is the left operand");
});
with_assign_rhs("module m;\n assign y = a -> b -> c;\nendmodule\n", |e| {
let ExprKind::Binary { rhs, .. } = &e.kind else { panic!("expected an implication") };
assert!(matches!(rhs.kind, ExprKind::Binary { .. }), "the chain nests to the right");
});
}
#[test]
fn only_a_brace_after_the_first_element_makes_an_assignment_pattern_a_replication() {
// corpus/opentitan/hw/ip/uart/rtl/uart.sv:17.
with_assign_rhs("module m;\n assign y = '{NumRegs{0}};\nendmodule\n", |e| {
assert!(matches!(e.kind, ExprKind::AssignPatternRepl { .. }));
});
for src in [
"module m;\n assign y = '{a: 0, b: 1};\nendmodule\n",
"module m;\n assign y = '{x, y};\nendmodule\n",
"module m;\n assign y = '{{a, b}};\nendmodule\n",
"module m;\n assign y = '{default: 0};\nendmodule\n",
] {
with_assign_rhs(src, |e| {
assert!(matches!(e.kind, ExprKind::AssignPattern(_)), "not a replication: {src:?}");
});
}
}
#[test]
fn a_streaming_concatenation_keeps_its_direction_and_optional_slice_size() {
// corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_sha2_pkg.sv:123.
with_assign_rhs("module m;\n assign y = {<<8{v}};\nendmodule\n", |e| {
let ExprKind::Stream { dir, slice, inner } = &e.kind else { panic!("expected a stream") };
assert_eq!(dir, "<<");
assert!(matches!(slice.as_deref().map(|s| &s.kind), Some(ExprKind::Number(_))));
assert_eq!(inner.len(), 1);
});
with_assign_rhs("module m;\n assign y = {>>{a, b}};\nendmodule\n", |e| {
let ExprKind::Stream { dir, slice, inner } = &e.kind else { panic!("expected a stream") };
assert_eq!(dir, ">>");
assert!(slice.is_none(), "no slice size was written");
assert_eq!(inner.len(), 2);
});
}
#[test]
fn an_array_method_with_argument_is_an_ordinary_expression() {
let f =
parse_ok("module m;\n initial begin\n n = q.sum() with (item.w);\n end\nendmodule\n");
let StmtKind::Assign { rhs, .. } = &initial_stmts(&f)[0].kind else {
panic!("expected an assignment")
};
let ExprKind::With { base, arg, .. } = &rhs.kind else {
panic!("expected a with-expression, got {:?}", rhs.kind)
};
assert!(matches!(base.kind, ExprKind::Call { .. }));
assert!(matches!(arg.kind, ExprKind::Paren { .. }));
}
#[test]
fn the_comments_around_a_calls_brackets_and_a_with_are_kept() {
// QA round-1: four positions with no node of their own — before the
// `(`, inside an empty `()`, before `with`, and after it.
let f = parse_ok(
"module m;\n initial begin\n x = o.randomize /*c1*/ ( /*c2*/ ) /*c3*/ with /*c4*/ {\n y > 1;\n };\n end\nendmodule\n",
);
let StmtKind::Assign { rhs, .. } = &initial_stmts(&f)[0].kind else {
panic!("expected an assignment")
};
let ExprKind::WithConstraint { base, comments, .. } = &rhs.kind else {
panic!("expected a with-constraint, got {:?}", rhs.kind)
};
assert_eq!(texts(&comments.before_kw), ["/*c3*/"]);
assert_eq!(texts(&comments.after_kw), ["/*c4*/"]);
let ExprKind::Call { comments, .. } = &base.kind else { panic!("expected a call") };
assert_eq!(texts(&comments.before_open), ["/*c1*/"]);
assert_eq!(texts(&comments.dangling), ["/*c2*/"]);
}
#[test]
fn an_argument_carries_its_own_comments_and_the_call_carries_none() {
// A list with elements has somewhere to put them, so the call's own
// slots stay empty — two homes for one comment would print it twice.
let f = parse_ok("module m;\n initial begin\n f( /*c*/ a);\n end\nendmodule\n");
let StmtKind::ExprStmt(e) = &initial_stmts(&f)[0].kind else {
panic!("expected an expression statement, got {:?}", initial_stmts(&f)[0].kind)
};
let ExprKind::Call { args, comments, .. } = &e.kind else { panic!("expected a call") };
assert!(comments.is_empty(), "the call kept comments the argument owns");
assert_eq!(texts(&args[0].meta.leading), ["/*c*/"]);
}
#[test]
fn a_with_that_opens_neither_a_paren_nor_a_brace_is_not_a_postfix_segment() {
// The stream expression's `with [range]` is still unsupported, and
// still fails where it always did rather than being mis-read.
assert!(parse_err("module m;\n initial x = {<<{a with [0:1]}};\nendmodule\n").contains("with"));
}
#[test]
fn an_omitted_call_argument_is_an_empty_element_that_still_holds_its_place() {
let f = parse_ok("module m;\n initial x = f(a, , b);\nendmodule\n");
let ItemKind::Initial(stmt) = &module_of(&f).items[0].kind else {
panic!("expected an initial block")
};
let StmtKind::Assign { rhs, .. } = &stmt.kind else { panic!("expected an assignment") };
let ExprKind::Call { args, .. } = &rhs.kind else { panic!("expected a call") };
assert_eq!(args.len(), 3);
assert!(matches!(args[1].expr.kind, ExprKind::Empty(_)));
}
#[test]
fn a_system_function_call_may_be_a_casting_type() {
// hw/top_earlgrey/ip_autogen/pinmux/rtl/pinmux.sv:490 and
// hw/vendor/pulp_riscv_dbg/debug_rom/debug_rom.sv:67.
for src in [
"module m;\n assign y = $bits(x)'({a, b});\nendmodule\n",
"module m;\n assign y = $clog2(RomSize)'(RomSize);\nendmodule\n",
] {
let f = parse_ok(src);
let m = module_of(&f);
let ItemKind::ContAssign(a) = &m.items[0].kind else { panic!("expected an assign") };
let ExprKind::Cast { ty, pattern, .. } = &a.assigns[0].rhs.kind else {
panic!("expected a cast in {src:?}")
};
assert!(!pattern, "the `'(...)` spelling");
assert!(matches!(&ty.kind, ExprKind::Call { .. }), "the casting type is the call");
}
// An *ordinary* call is still not a casting type: the net stays as
// narrow as the corpus needs it.
assert!(parse_err("module m;\n assign y = f(x)'(z);\nendmodule\n")
.contains("unsupported cast base expression"));
}
#[test]
fn a_cast_may_be_applied_to_an_assignment_pattern() {
// hw/dv/sv/cip_lib/cip_base_scoreboard.sv:442.
let f = parse_ok("module m;\n assign y = expected_alert_t'{1, is_fatal};\nendmodule\n");
let m = module_of(&f);
let ItemKind::ContAssign(a) = &m.items[0].kind else { panic!("expected an assign") };
let ExprKind::Cast { ty, expr, pattern, .. } = &a.assigns[0].rhs.kind else {
panic!("expected a cast")
};
assert!(*pattern, "the `'{{...}}` spelling");
assert!(matches!(&ty.kind, ExprKind::Ident(n) if n == "expected_alert_t"));
assert!(matches!(&expr.kind, ExprKind::AssignPattern(items) if items.len() == 2));
}
#[test]
fn the_two_cast_spellings_over_a_pattern_stay_distinct() {
// `ty'('{...})` and `ty'{...}` are different token streams; only the
// `pattern` flag keeps the printer from collapsing one into the other.
let f = parse_ok("module m;\n assign y = bar_t'('{a: 1});\nendmodule\n");
let m = module_of(&f);
let ItemKind::ContAssign(a) = &m.items[0].kind else { panic!("expected an assign") };
let ExprKind::Cast { expr, pattern, .. } = &a.assigns[0].rhs.kind else {
panic!("expected a cast")
};
assert!(!pattern, "the parens are the cast's, not the pattern's");
assert!(matches!(&expr.kind, ExprKind::AssignPattern(_)));
// And a bare pattern is still a whole expression, not a cast.
let f = parse_ok("module m;\n assign y = '{a: 1};\nendmodule\n");
let m = module_of(&f);
let ItemKind::ContAssign(a) = &m.items[0].kind else { panic!("expected an assign") };
assert!(matches!(&a.assigns[0].rhs.kind, ExprKind::AssignPattern(_)));
}
#[test]
fn a_repeat_bracket_never_steals_an_ordinary_index() {
// The `[`-guard `at_repeat_bracket` installs must not change how any
// other expression parses.
let f = parse_ok("module m;\n assign y = q[3] + r[a:b] + s[i +: 2];\nendmodule\n");
assert!(matches!(f.items[0].kind, ItemKind::Module(_)));
}