20 KiB
20 KiB
Parser Syntax Fixes & Parse-Once --style auto / Multi-Instance Layout (Round 5B)
Goal
Deliver the Round 5B parser and formatter accuracy, throughput, and hygiene fixes across vlog_parser and vlog_formatter:
- Parse-once
--style auto(crates/vlog_formatter/src/{auto.rs, format/mod.rs, verify.rs, selection/mod.rs}): Lex/parsesourceand collect fenced regions once across allPRESETS, reuse the verified output AST/fences inresolve_style'scanonicallookup, avoid redundant re-parses informat_range/format_selection, preserve fullverify.rsequivalence and convergence invariants, and preserve byte-identical outputs. - Parser & formatter edge fixes:
#44: Support comments (including trailing////* ... */ // ...after labelled generateend : label) between generateendandelse/else if.#45: Support`ifdef/ conditional directives betweenendandelsein both proceduralifand generateif(both balanced intervening directives and conditionalelsearms).#46: Support SystemVerilog attributes ((* keep *), multiple attributes, interleaved comments, directionless/typed/modport ANSI ports) on ANSI ports and round-trip cleanly.#42: Tighten parser leniency on invalid constructs ({d,, d},{, d},{d,},{N{a,, b}},'{N{a,, b}},{<<{a,, b}},case a,, b:,f(.a(x),)), and verify#42atrailing,in named connection lists and#42ctype(x)'(y)againstscripts/score.shand OpenTitanhw/without regressing814corpus or4,039/4,046OpenTitan pass counts.#47: Format multi-instance declarations (p1 u8 (...), u9 (...);) symmetrically underPortLists::OnePerLinestyles (google,lowrisc,microsoft,nxp) so every instance opens and closes at the same indented column instead of falling back to the asymmetric hanging layout, while preservingPortLists::Fit(lucisv,ansi) default output.
- Production safety & size hygiene: Zero
.unwrap(),.expect(),panic!(), orunsafein non-test production code ofvlog_parser/src/**andvlog_formatter/src/**, and keep all modified/added production files<= 600non-blank non-comment lines before#[cfg(test)]/mod tests.
Assumptions
- Downstream crates (
vlog_semantic,vlog_refactor,vlog_linter,lucisv_server,lucisv_mcp) pattern-matchGenElse::If(_, _)andGenElse::Block(_); keepingGenElse's two tuple/struct-free signatures unchanged and adding fields toGenIf(then_trailing,else_directives,else_comments) preserves cross-crate compatibility. - Under
PortLists::OnePerLine, ordered/empty multi-instance declarations (p1 u8 (), u9 ();,p1 u8 (a), u9 (b);) stay flat on one line when they fit and break symmetrically (p1\n u8 ...,\n u9 ...;) whenever any instance's named connection list or line width breaks the declaration. - Positional call omitted arguments (
f(a, , b), OpenTitanflash_ctrl_default_region_cfg(,,,scr_en, ecc_en)) and ordered instance trailing commas (u(a, b,)) are preserved per IEEE 1800 andqa_port_entry_grace.
Handshakes
vlog_parser::ast::{GenIf, StmtKind::If}↔vlog_formatter::format::{branch, stmt}:GenIfaddsthen_trailing,else_directives, andelse_comments;StmtKind::Ifaddselse_directives(staying withinast::size_pinsbounds:StmtKind <= 392,Stmt <= 552).vlog_formatter::verify↔vlog_formatter::{auto, format/mod.rs, selection/mod.rs}:verify::stream_from_tokensandverify::verify_equivalence_itemsreuse pre-lexed token streams without alteringpub fn verify_equivalence.vlog_refactor::check::qa_implicit↔vlog_parser: Tolerant error-element recovery for.d(type(q)'(q))and strict/tolerant trailing-comma rules fromport_entry_recovery(14213f6) stay intact.- Strict disjoint file ownership maintained: touched only
crates/vlog_parser/{src,tests}/**,crates/vlog_formatter/{src,tests}/**, anddocs/features/parser-formatter-r5/README.md.
Status / TODO
- Refactor
auto.rs/format/mod.rs/verify.rs/selection/mod.rsfor parse-once--style auto,resolve_style,format_range, andformat_selection - Fix
#44comments (including trailing//after labelled generateend : label) between generateendandelse - Fix
#45`ifdefand conditional directives betweenendandelse(procedural and generateif) - Fix
#46attributes on ANSI ports invlog_parserandvlog_formatter - Tighten
#42bempty brace/case elements +f(.a(x),)and verify#42a/#42cagainst corpus and OpenTitanhw/ - Fix
#47multi-instance declarations underPortLists::OnePerLine - Eliminate remaining non-test
.unwrap()calls informat/decl.rsandformat/item.rsand verify<= 600production line counts - Add regression suites
crates/vlog_parser/tests/parser_r5.rsandcrates/vlog_formatter/tests/formatter_r5.rsand pass all CI/OpenTitan gates
Work log
2026-11-26 — dev (Round 5B)
- Baseline (
6d1c689):- OpenTitan
/Users/lucio/repo/opentitan/hw(4,046 files,--style auto --check --no-cache):5.040 swall (39.06 suser,3.03 ssys,835%CPU);3967would reformat,72unchanged,7failed (4,039 passing, 0 verification failures). - OpenTitan default (
--style lucisv):0.981 swall (6.80 suser,0.63 ssys);3967reformatted,72unchanged,7failed. Snapshotted all 4,039 formatted outputs to/tmp/r5b_base_ot_defaultbefore editing. - Corpus (
./tools/gates.sh --only corpus):PASS(814/6,2 s).
- OpenTitan
- Parse-once
--style auto(auto.rs,format/mod.rs,verify.rs,selection/mod.rs):- Added
format::parse_once,format::render_parsed,format::verify_rendered,verify::stream_from_tokens, andverify::verify_equivalence_items; switchedFmt::{regions, splits}to borrowed slices. - Updated
auto::closest_innerto lex/parsesourceonce, render all 6PRESETSon the shared(file, regions), short-circuit onoutput == source, rank remaining candidates using reusableLineCounter(total_a + total_b - 2*matched), verify only the winning candidate (preserving earliest-preset error priority if all fail), and reuse(out_file, out_regions)incanonical_parsed. - Updated
format_rangeandformat_selectionviaauto::resolve_concreteto reuse the parsed input AST underauto. - Post-change OpenTitan
--style auto --check --no-cachebenchmark (3 runs):2.991 s,2.758 s,2.660 s(17.55 suser,1.81 ssys,727%CPU) — ~1.9x wall / ~2.2x user CPU faster than6d1c689(5.040 s/39.06 s) and ~2.05x faster than historical5.46 s, with 0 diff lines on stdout/stderr vs6d1c689.
- Added
#44-(ast/{module,stmt}.rs,parser/{directive,item,stmt,split}.rs,format/{branch,stmt}.rs):- Added
GenIf::{then_trailing, else_directives, else_comments}andStmtKind::If::else_directives; addedParser::take_else_preamble,has_else_past_directives, andtake_else_directivesindirective.rs. - Added
Parser::{at_conditional_else_ahead, at_conditional_else_split, scan_if_conditional_else_extent}insplit.rsto capture conditionalelseinside`ifdef/`ifndef(balanced blocks/brackets/`endifs, rival`elsearms, optional trailing unconditionalelse) verbatim while leaving unterminated/unbalanced cases rejected and non-else`ifdefs separate. - Updated
format/branch.rswith sharedpush_else_keywordandgen_then_branch(detecting merged/* a */ // bline-ending trailing comments on generate blocks).
- Added
#46(parser/{cursor,decl,module,item,stmt,instance}.rs,format/module.rs):- Extracted
Parser::take_attrs(draining both same-linepending_trailingand next-linetok.leadingintometa.leading), reused acrossitem,stmt,instance, andparse_ansi_port. - Added
at_typed_declarator_atandat_modport_port_atsoparse_port_listskips leading(* ... *)attributes when detecting ANSI port lists (including directionless,pkg::type, andintf.modportports). - Updated
format/module.rs(ansi_port_item,ansi_port_cells,ansi_port_plain) to render ANSI port attributes and preserve any comments interleaved between/after attributes without breaking token order or joining alignment groups.
- Extracted
#42(parser/{primary,instance,randsequence}.rs):- #42b: Tightened
Parser::parse_expr_item/parse_expr_listviaparse_expr_item_with(allow_omitted: bool)so empty elements are accepted only in parenthesized argument lists (close == ")"and not afterNamedArg), rejecting{d,, d},{, d},{d,},{4{d,, d}},{<<{d,, d}},'{4{d,, d}},case a,, b:, andf(.a(x),)while preserving{}and omitted positional call args (f(a, , b)). - #42a: Confirmed named port/override trailing commas (
.a(x),),#(.W(1),)) are already refused strictly and reported tolerantly bynote_trailing_comma(port_entry_recovery.rs); tightenedf(.a(x),)named call trailing commas, keepingdirectives_in_lists,before`ifdefand IEEE 1800 positionalu(a, b,)untouched (0matches in OpenTitan/corpus for dangling,before`ifdef ... `endif )). - #42c: Confirmed malformed
type(x)'(y)in connections, overrides, and expressions (sub u (.a(type(x)'(y))),sub #(.T(type(x)'(y))),assign w = type(x)'(y)) is already rejected strictly (unexpected keyword 'type' in expression) and diagnosed tolerantly (qa_implicit.rspins.d(type(q)'(q))recovery).
- #42b: Tightened
#47(format/instance.rs):- Under
PortLists::OnePerLine, placed multi-instance declarations insidegroup(vec![indent(inner)])starting withDoc::Line(!on_fresh_line), so broken multi-instance statements indent every instance (u8,u9, ...) uniformly and align each instance's closing)with its own opening line (google2/4/8,lowrisc/nxp2/4/6,microsoft4/8/12) while keepingPortLists::Fit(lucisv,ansi) byte-identical.
- Under
- Safety & file-size audit: Eliminated the remaining 2 non-test
.unwrap()calls informat/decl.rsandformat/item.rsusingTryFrom<[ListItem; 1]>andsaturating_sub; verified0.unwrap(),.expect(),panic!(), orunsafein non-test production code acrossvlog_parser/src/**andvlog_formatter/src/**, and verified all production files remain<= 600non-blank non-comment lines (item.rs589,module.rs568,instance.rs565,stmt.rs564).
2026-11-26 — dev QA-fix (Round 5B)
- Fixed QA
#45defect 1 (crates/vlog_parser/src/parser/split.rs+directive.rs): unifiedelse_past_directives_atindirective.rs, changedscan_uncond_branchto return(usize, bool /* is_if */), and madescan_if_conditional_else_extentloop acrosscond_else_at(i), optional balanced directives beforeelse, and any chainedelse if (...) ... else ...branches while stopping cleanly on non-else`ifdefs or a non-ifelseterminator. - Fixed QA
#45defect 2 (crates/vlog_parser/src/parser/split.rs::scan_cond_else_region,scan_uncond_branch): added explicitouter_open: boolstate (distinct from nestedconddepth) and nested`else/`elsifskipping atcond > 0so balanced nested`ifdef ... `endifdirectives inside a sharedelsetail scan cleanly through the closingend/;instead of exiting prematurely when nestedcondreturns to0. - Added regression tests covering both procedural and generate variants, balanced intervening directives inside
else if ... elsechains, nested`ifdef ... `else ... `endifinside shared tails, and negative/unterminated bounds incrates/vlog_parser/tests/parser_r5.rsandcrates/vlog_formatter/tests/formatter_r5.rs.
QA log
2026-11-26 — dev verification (self-check)
crates/vlog_parser/tests/parser_r5.rs: 6/6 passed (#44,#45directives + conditionalelse+ negatives,#46,#42a/b/c).crates/vlog_formatter/tests/formatter_r5.rs: 5/5 passed (all 6 presets +autoverification/idempotency/layout pins +resolve_style/format_range/format_selection).auto_sweepover/Users/lucio/repo/opentitan/hw:4,047files scanned,7refused (pre-existing parse errors),0crashes,0non-idempotent,0second-run preset renames (lucisv: 3379,lowrisc: 526,microsoft: 80,google: 30,nxp: 21,ansi: 4).- Default-style (
--style lucisv) OpenTitan diff against pre-edit snapshot (/tmp/r5b_base_ot_defaultvs/tmp/r5b_new_ot_default):0differing files across all 4,039 passing files;--style autooutput0diff lines vs baseline. ./tools/gates.sh --only corpus:PASS(814/6,2 s).cargo fmt --all -- --check,python3 tools/stamp_author.py --check,cargo clippy -p vlog_parser -p vlog_formatter --all-targets -- -D warnings,./tools/guard.sh -m 8 -t 600 -- cargo test -p vlog_parser -p vlog_formatter -p vlog_semantic -p vlog_refactor -p vlog_linter --all-targets: see final gate run after README addition.
2026-11-26 — Round 5 Lane 5B QA audit (FAIL)
- Verdict:
FAIL(two edge-case defects found in#45conditional-elseextent scanning incrates/vlog_parser/src/parser/split.rs; all invariants, gates, OpenTitan/corpus benchmarks, parse-once--style auto,#44,#46,#42, and#47passed). - Defects found in
crates/vlog_parser/src/parser/split.rs:scan_if_conditional_else_extent(split.rs:640-655): When a conditional`ifdef/`ifndefelsearm is followed by an unconditionalelse if (...)branch that is itself followed by an unconditionalelse(either generateifor proceduralif),scan_uncond_branchstops after theelse ifbranch at the trailingelse, andscan_if_conditional_else_extentonly continues the loop whenself.cond_else_at(i)is true, leaving the trailingelseorphaned and failing withunsupported construct/statement starting with keyword 'else'.scan_cond_else_region(split.rs:657-698): When a conditionalelseregion opens a block/bracket in its first arm and hits`else/`elsifwithblocks > 0orbrackets > 0(settingcond = 0atsplit.rs:683to scan past`endifto the closingend/;), any nested balanced`ifdef ... `endifinside that shared tail incrementscondto1and decrements back to0, hittingif cond == 0 { return (brackets == 0 && blocks == 0).then_some(i + 1); }(split.rs:675-677) and returningNoneprematurely instead of continuing to the branch closer (failing cleanly withconditional 'else' after 'if').
- Checks verified in worktree (HEAD
6d1c689):- Ownership & invariants: Only Lane 5B paths modified/created (
crates/vlog_parser/{src,tests}/**,crates/vlog_formatter/{src,tests}/**,docs/features/parser-formatter-r5/README.md). All 23 changed library.rsfiles are<= 600non-blank non-comment production lines before#[cfg(test)]/mod tests(max589incrates/vlog_parser/src/parser/item.rs).0occurrences of.unwrap(),.expect(),panic!, orunsafein non-test production code acrosscrates/vlog_parser/src/**andcrates/vlog_formatter/src/**. cargo fmt --all -- --check: PASS.python3 tools/stamp_author.py --check: PASS (would stamp 0 files; left 249 untouched).cargo clippy -p vlog_parser -p vlog_formatter --all-targets -- -D warnings: PASS../tools/guard.sh -m 8 -t 600 -- cargo test -p vlog_parser -p vlog_formatter -p vlog_semantic -p vlog_refactor -p vlog_linter --all-targets: PASS (2,787passed,0failed,12ignored —vlog_formatter:381,vlog_linter:672,vlog_parser:527+2ignored,vlog_refactor:769+6ignored,vlog_semantic:438+4ignored)../tools/gates.sh --only corpus: PASS (814/820,0verification errors,0crashes,3 s).- OpenTitan
/Users/lucio/repo/opentitan/hw(target/release/lucisv): default--check --no-cache(3,967would reformat,72unchanged,7pre-existing lex/parse failures =4,039/4,046pass,0verification failures);--style auto --check --no-cache(3,967would reformat,72unchanged,7pre-existing lex/parse failures =4,039/4,046pass,0verification failures);auto_sweep(4,047files,7refused,0crashes,0non-idempotent,0second-run renames;lucisv: 3379, lowrisc: 526, microsoft: 80, google: 30, nxp: 21, ansi: 4)./Users/lucio/repo/opentitangit status --porcelainis empty. - Parse-once
--style auto,#44,#46,#42,#47: All explicit requirements and adversarial stdin probes passed (apart from the two#45split.rsedge cases above).
- Ownership & invariants: Only Lane 5B paths modified/created (
2026-11-26 — Round 5 Lane 5B QA re-audit (PASS)
- Verdict:
PASS(both prior#45defects incrates/vlog_parser/src/parser/split.rsanddirective.rsare fixed and verified; all invariants, tests, corpus, and OpenTitan gates pass). - Re-audit of
#45fixes (crates/vlog_parser/src/parser/{split.rs,directive.rs},crates/vlog_parser/tests/parser_r5.rs,crates/vlog_formatter/tests/formatter_r5.rs):scan_if_conditional_else_extent(split.rs:640-660) +else_past_directives_at(directive.rs:218-247) +scan_uncond_branch(split.rs:720-779): Confirmed unconditionalelse if (...) ... else ...chains (with or without balanced directives beforeelse) after conditional`ifdef/`ifndefelsearms parse and format idempotently across both procedural and generateif, while outerelsebranches (if (outer) if (inner) ...) and trailing non-else`ifdefblocks remain unswallowed.scan_cond_else_region(split.rs:662-718): Confirmedouter_opentracking and nested`else/`elsifskipping atcond > 0allow balanced nested`ifdef ... `else ... `endifinside sharedelsetails to scan cleanly through the closingend/;while rejecting stray`else/`endif, unbalanced directives, and unmatchedend/else.
- Invariants & gates verified in worktree (HEAD
6d1c689):- Ownership & sizes: Strictly Lane 5B files (
crates/vlog_parser/{src,tests}/**,crates/vlog_formatter/{src,tests}/**,docs/features/parser-formatter-r5/README.md). All 23 changed library.rsfiles remain<= 600production LOC (item.rs589,stmt.rs570,module.rs568,instance.rs565,split.rs554,directive.rs265).0non-test.unwrap(),.expect(),panic!, orunsafeacrosscrates/vlog_parser/src/**andcrates/vlog_formatter/src/**. cargo fmt --all -- --check: PASS.python3 tools/stamp_author.py --check: PASS (would stamp 0 files; left 249 untouched).cargo clippy -p vlog_parser -p vlog_formatter --all-targets -- -D warnings: PASS../tools/guard.sh -m 8 -t 600 -- cargo test -p vlog_parser -p vlog_formatter -p vlog_semantic -p vlog_refactor -p vlog_linter --all-targets: PASS (2,787passed,0failed,12ignored —vlog_formatter:381,vlog_linter:672,vlog_parser:527+2ignored,vlog_refactor:769+6ignored,vlog_semantic:438+4ignored)../tools/gates.sh --only corpus: PASS (814/820,0verification errors,0crashes,3 s).- OpenTitan
/Users/lucio/repo/opentitan/hw(target/release/lucisv --style auto --check --no-cache):3,967would reformat,72unchanged,7failed (pre-existing lex/parse errors =4,039/4,046pass,0verification failures);/Users/lucio/repo/opentitangit status --porcelainis empty.
- Ownership & sizes: Strictly Lane 5B files (
Review
Lead Self-Inspect (2026-11-26): APPROVED for trunk commit.
- Merged Lane 5B onto trunk after Round 5B QA Re-Audit PASS (including
#45split.rsconditional-elsefixes for trailingelse if ... else ...chains and nested`ifdefinside shared tails). - Verified parse-once
--style auto(~2.66-3.01 svs5.04-5.46 sbaseline across 4,046 OpenTitanhw/files,0verification failures, default--style lucisvbyte-identity on all4,039passing OpenTitan files,0non-test.unwrap()calls acrossvlog_parser&vlog_formatter, and814/6corpus PASS). - Updated
crates/lucisv_mcp/src/tools/place.rstestwhat_a_placement_cannot_see_or_would_change_is_refusedafter#46:(* keep *) bnow parses cleanly as an attributed port inheriting direction froma, while123 bexercises the unreadableListElem::Errorrefusal path.