From da1448ecd0b31acfa322b6f3e52b413a379917e1 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Wed, 19 Aug 2026 20:22:07 -0700 Subject: [PATCH] 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 --- README.md | 20 +- TODO.md | 23 +- crates/vfmt/src/lint.rs | 10 +- crates/vfmt_server/src/diagnostics.rs | 18 + crates/vfmt_server/src/lint.rs | 26 +- crates/vfmt_server/src/state.rs | 23 +- crates/vlog_formatter/src/format.rs | 81 +- .../tests/cases/dynamic_types.cases | 421 ++++++++++ crates/vlog_formatter/tests/verification.rs | 58 ++ crates/vlog_linter/src/context.rs | 195 ++++- crates/vlog_linter/src/lib.rs | 2 +- crates/vlog_linter/tests/rules.rs | 12 + crates/vlog_parser/src/ast.rs | 45 +- crates/vlog_parser/src/parser.rs | 325 +++++++- crates/vlog_parser/tests/spans.rs | 8 + crates/vlog_semantic/src/bind.rs | 16 +- docs/features/dynamic-types/README.md | 760 ++++++++++++++++++ docs/features/linter-core/README.md | 8 +- docs/features/one-parse/README.md | 515 ++++++++++++ docs/features/server-lint/README.md | 8 +- 20 files changed, 2478 insertions(+), 96 deletions(-) create mode 100644 crates/vlog_formatter/tests/cases/dynamic_types.cases create mode 100644 docs/features/dynamic-types/README.md create mode 100644 docs/features/one-parse/README.md diff --git a/README.md b/README.md index d9aacd4..f4c9fc0 100644 --- a/README.md +++ b/README.md @@ -341,6 +341,15 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset: c { ... }` and `covergroup … endgroup` are **passed through verbatim** — two grammars with no layout convention worth inventing. See `docs/features/classes/README.md` +- Dynamic types: queues (`string q[$]`, bounded `[$:N]`), dynamic arrays + (`int a[]`), associative arrays (`[*]`, `[string]`, `[key_t]`) — in + declarations, class properties, typedefs and function/task arguments; the + empty literal (`q = {};`), `new[expr]`, `$`-bound indexing (`q[$]`, + `q[$-1]`) and queue method calls. See + `docs/features/dynamic-types/README.md` +- Named function/task call arguments (`csr_wr(.ptr(p), .value(v))`, + `.flag()`), `case (expr) inside` with `[lo:hi]` range labels, and bare + event controls (`@ev;`, `@hier.name;`) - Expressions: the full operator precedence table, ternaries, concatenation/replication, slices (`+:`/`-:`), casts (`int'(x)`), assignment patterns (`'{...}`), `inside`, hierarchical and package-scoped @@ -380,8 +389,15 @@ corpus baseline this ordering comes from: format; the other 70 advanced to a second blocker, 34 of them to item 4 below, which is now the top blocker 3. `bind` directives -4. Dynamic arrays and queues — now the top blocker at 41 files (`bit x[$]`, - `int q[]`) +4. ~~Dynamic arrays and queues — now the top blocker at 41 files (`bit x[$]`, + `int q[]`)~~ — **done**; see `docs/features/dynamic-types/README.md`. + Queues (`x[$]`, `q[$]`/`q[$-1]` indexing, `[$:N]`), dynamic arrays + (`int q[]`), wildcard associative arrays (`[*]`), `= {}` initializers, + named call arguments (`f(.a(x))`) and `case (expr) inside` — unblocked 58 + corpus files and moved the parse rate from 70.5% to 77.6%. All 7 + `inside`-blocked files format; 28 of the 41 `$`-blocked and 17 of the 21 + `.`-blocked do too, the rest advancing to named next blockers + (`interface` at 25 files is now the top one — item 8 below) 5. Declarations with identifier (typedef'd) types in some positions (`my_t [N-1:0] x;`) 6. ~~`` `ifdef``/`` `define``/`` `include`` inside a port, parameter or enum diff --git a/TODO.md b/TODO.md index d075186..af29065 100644 --- a/TODO.md +++ b/TODO.md @@ -169,12 +169,21 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both. Design it ruff-style from day one (shared parse, fix model), with Verible's rule ergonomics (waivers, configurable rules). -- [ ] **[R] One parse, two tools.** `vfmt check` and `vfmt format` must +- [x] **[R] One parse, two tools.** `vfmt check` and `vfmt format` must share `vlog_parser` output in a single invocation (`vfmt check --fix - --format` style workflows come free later). *Not done:* `vfmt check` + --format` style workflows come free later). ~~*Not done:* `vfmt check` re-parses today (tolerantly, which the formatter does not), and nothing in `vlog_linter`'s API prevents sharing a tree later — only `LintContext` would - change. + change.~~ + → Delivered on the linter side (`docs/features/one-parse/README.md`): + `LintContext::from_parse` accepts pre-built products, `ParsedSource` is the + owned bundle, `vfmt check` parses once per file (one lex instead of two — + corpus check 266 → 208 ms single-threaded), and `vfmt_server` lints from the + `Document` it already analyzed (didChange→publish 18 → 11 ms on picorv32.v). + Byte-identical output proven against a HEAD-worktree binary. The formatter + half stands unchanged by design: `vfmt format` needs the *strict* parse its + safety net is defined over, so a combined `check --fix --format` workflow + remains a future feature — but nothing in the API blocks it anymore. - [x] **[V+R] Rule trait + registry.** Each rule: stable kebab-case name, one-line summary, longer doc with style-guide rationale (Verible links each rule to a style-guide section — do the same), and a @@ -291,6 +300,14 @@ Adapt each: path. 72 of the 142 `extends`-blocked files now format; the other 70 advanced to a second blocker, and the new top blocker is dynamic arrays and queues (README roadmap item 4, 41 files). + → Dynamic types (`docs/features/dynamic-types/README.md`) then took it + from 578/820 to **636/820 (77.6%)** — 58 files gained, 0 lost, 0 + verification errors, 0 crashes, all 636 round-tripped individually. + Queues/dynamic arrays, named call arguments and `case ... inside` are + done; the new top blocker is `interface` declarations (25 files, + README roadmap item 8), then `` `else`` inside an element (13, the + documented directives-in-lists non-goal) and `` `uvm_field_int `` (11, + the documented macro-items lexer gap). - [ ] **[R] Fuzzing.** ruff fuzzes its parser. `cargo-fuzz` targets: (a) parser must never panic on arbitrary bytes, (b) for inputs that parse, format must satisfy equivalence + convergence. diff --git a/crates/vfmt/src/lint.rs b/crates/vfmt/src/lint.rs index d7e353b..d3e4ac8 100644 --- a/crates/vfmt/src/lint.rs +++ b/crates/vfmt/src/lint.rs @@ -11,7 +11,7 @@ use std::process::ExitCode; use rayon::prelude::*; use vlog_formatter::fence::{self, Region}; use vlog_formatter::Config; -use vlog_linter::{apply_fixes, lint, Fix, LintContext, Rule, Violation}; +use vlog_linter::{apply_fixes, lint, Fix, ParsedSource, Rule, Violation}; use vlog_parser::LineIndex; use crate::args::{Options, OutputFormat}; @@ -111,9 +111,15 @@ fn run_rules( config: &Config, rules: &[&'static dyn Rule], ) -> Vec { + // One parse per file (TODO §4): the products are built here, once, and + // lent to the context. Under `--fix` each *round* re-enters through this + // function with rewritten text — that re-parse is inherent (the old + // products describe text that no longer exists), so only the first round + // saves a parse; a plain `vfmt check` always does. + let parsed = ParsedSource::parse(src); // The indent width the formatter would use is also the width a tab // expands to, so `--indent 4` fixes tabs into four spaces. - let ctx = LintContext::new(src, path).with_tab_width(config.indent_width); + let ctx = parsed.context(path).with_tab_width(config.indent_width); lint(&ctx, rules) } diff --git a/crates/vfmt_server/src/diagnostics.rs b/crates/vfmt_server/src/diagnostics.rs index 9ab92c6..1961c49 100644 --- a/crates/vfmt_server/src/diagnostics.rs +++ b/crates/vfmt_server/src/diagnostics.rs @@ -65,6 +65,24 @@ mod tests { assert!(diagnostics(ws.document(&uri).expect("open")).is_empty()); } + /// Guard for the one-parse QA finding: `Document.tree` is a cached + /// derivation of `Document.text`, and nothing else asserts they agree. + /// If `set_document` ever stops rebuilding the tree, the stale + /// `module-filename` warning below survives the rename and this fails. + #[test] + fn set_document_rebuilds_the_tree_so_diagnostics_track_the_text() { + let (mut ws, uri) = doc_of("module wrong;\nendmodule\n"); + let before = all(ws.document(&uri).expect("open")); + assert!( + before.iter().any(|d| matches!(&d.code, + Some(lsp_types::NumberOrString::String(s)) if s == "module-filename")), + "premise: the mismatched name must warn, got {before:?}" + ); + ws.set_document(uri.clone(), "module m;\nendmodule\n".to_string()); + let after = all(ws.document(&uri).expect("open")); + assert!(after.is_empty(), "a stale tree survived the rename: {after:?}"); + } + #[test] fn a_broken_file_reports_at_the_right_line() { let (ws, uri) = doc_of("module m;\n wire ;\nendmodule\n"); diff --git a/crates/vfmt_server/src/lint.rs b/crates/vfmt_server/src/lint.rs index 915b1da..7efc649 100644 --- a/crates/vfmt_server/src/lint.rs +++ b/crates/vfmt_server/src/lint.rs @@ -8,21 +8,26 @@ use lsp_types::{Diagnostic, DiagnosticSeverity, NumberOrString}; use vlog_formatter::fence::{self, Region}; -use vlog_linter::{default_rules, lint, run, LintContext, Violation}; +use vlog_linter::{default_rules, lint, LintContext, Violation}; use crate::convert::Positions; use crate::diagnostics::SOURCE; use crate::state::Document; +/// The document's own parse products, lent to the linter — "one parse, two +/// tools" (`docs/features/one-parse/README.md`): the buffer was tokenized and +/// tolerantly parsed once, in `Document::new`, and the lint pass reads those +/// products instead of parsing the same text again. +fn context(doc: &Document) -> LintContext<'_> { + LintContext::from_parse(&doc.text, &doc.tokens, &doc.tree, &doc.line_index, doc.path.clone()) +} + /// Every violation the default rules find in a buffer. /// /// This is the diagnostics path, which never looks at a fix, so the width a /// `no-tabs` fix would expand a tab to is left at the linter's own default. -/// The linter re-parses the text the document already parsed — the duplicated -/// parse is `linter-core`'s own "one parse, two tools" TODO, not something to -/// work around here. pub fn violations(doc: &Document) -> Vec { - run(&doc.text, doc.path.clone(), &default_rules()) + lint(&context(doc), &default_rules()) } /// The findings a code action may offer a fix for, with their fixes built for @@ -40,11 +45,12 @@ pub fn violations(doc: &Document) -> Vec { /// [`fence::protected_regions`]' answer, the one the CLI asks too; see /// `docs/features/shared-fence-filter/README.md`. pub fn fixable(doc: &Document, tab_width: usize) -> Vec { - let ctx = LintContext::new(&doc.text, doc.path.clone()).with_tab_width(tab_width); - let found = lint(&ctx, &default_rules()); - // One tolerant parse per code-action request, on top of the one - // `LintContext` just did. The diagnostics path — the per-keystroke one — - // pays neither, because it never reads a fix. + let found = lint(&context(doc).with_tab_width(tab_width), &default_rules()); + // One tolerant parse per code-action request: `protected_regions` takes + // text and parses internally, on purpose — one fence answer for every + // front end, none of which can feed it a stale tree (see + // `docs/features/shared-fence-filter/README.md`). The per-keystroke + // diagnostics path pays nothing, because it never reads a fix. let regions = fence::protected_regions(&doc.text); found.into_iter().filter(|violation| !fix_touches_fence(violation, ®ions)).collect() } diff --git a/crates/vfmt_server/src/state.rs b/crates/vfmt_server/src/state.rs index 3048aa3..d939b98 100644 --- a/crates/vfmt_server/src/state.rs +++ b/crates/vfmt_server/src/state.rs @@ -8,9 +8,10 @@ use std::fs; use std::path::{Path, PathBuf}; use lsp_types::Uri; +use vlog_parser::ast::SourceFile; use vlog_parser::defines::{collect_defines, DefineTable}; use vlog_parser::token::Token; -use vlog_parser::{parse_source_tolerant, tokenize, LineIndex, ParseDiagnostic}; +use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex, ParseDiagnostic}; use vlog_semantic::{analyze, resolve_external, ExternalResolutions, Semantics, WorkspaceIndex}; use vfmt_core::config::Discovery; @@ -33,6 +34,10 @@ pub struct Document { pub line_index: LineIndex, /// Empty when the file does not lex — the lexer is all-or-nothing. pub tokens: Vec, + /// The tolerant parse of `text` — the tree `semantics` was analyzed from, + /// kept so the lint pass reads it instead of parsing the buffer again + /// ("one parse, two tools", `docs/features/one-parse/README.md`). + pub tree: SourceFile, pub diagnostics: Vec, pub semantics: Semantics, pub defines: DefineTable, @@ -43,13 +48,23 @@ pub struct Document { impl Document { /// Analyze a buffer from scratch against the current workspace index. pub fn new(path: Option, text: String, index: &WorkspaceIndex) -> Document { - let tokens = tokenize(&text).unwrap_or_default(); + // One lex: the tree is built from a clone of the token stream instead + // of re-lexing the buffer (`parse_source_tolerant` is exactly + // `tokenize` + `parse_tolerant`, so the tree is identical). A buffer + // that does not lex keeps the old path, so its all-error tree and its + // lex diagnostic are byte-for-byte what they always were. + let (tokens, (tree, diagnostics)) = match tokenize(&text) { + Ok(tokens) => { + let parsed = parse_tolerant(tokens.clone(), &text); + (tokens, parsed) + } + Err(_) => (Vec::new(), parse_source_tolerant(&text)), + }; let defines = collect_defines(&tokens); - let (tree, diagnostics) = parse_source_tolerant(&text); let semantics = analyze(&tree, &text); let external = resolve_external(&semantics, index); let line_index = LineIndex::new(&text); - Document { path, text, line_index, tokens, diagnostics, semantics, defines, external } + Document { path, text, line_index, tokens, tree, diagnostics, semantics, defines, external } } /// This document's position converter. diff --git a/crates/vlog_formatter/src/format.rs b/crates/vlog_formatter/src/format.rs index 1d55d3b..d0b07d0 100644 --- a/crates/vlog_formatter/src/format.rs +++ b/crates/vlog_formatter/src/format.rs @@ -1226,13 +1226,19 @@ impl<'a> Fmt<'a> { } fn dim(&self, d: &Dim) -> Doc { - let mut docs = vec![text("["), self.expr_compact(&d.a)]; - if let Some(b) = &d.b { - docs.push(text(":")); - docs.push(self.expr_compact(b)); + match &d.kind { + DimKind::Range { a, b } => { + let mut docs = vec![text("["), self.expr_compact(a)]; + if let Some(b) = b { + docs.push(text(":")); + docs.push(self.expr_compact(b)); + } + docs.push(text("]")); + concat(docs) + } + DimKind::Dynamic => text("[]"), + DimKind::Wildcard => text("[*]"), } - docs.push(text("]")); - concat(docs) } /// Compact rendering used inside `[...]` brackets: arithmetic and shift @@ -2092,6 +2098,9 @@ impl<'a> Fmt<'a> { fn sens_list(&self, sens: &SensList) -> Doc { match sens { + // Written without parens, printed without parens: `@ev`, + // `@a.b` — inventing a `( ... )` changes the token stream. + SensList::Bare(e) => concat(vec![text("@"), self.expr(e)]), SensList::Star { before, after } => { if before.is_empty() && after.is_empty() { return text("@(*)"); @@ -2175,7 +2184,7 @@ impl<'a> Fmt<'a> { concat(docs) } StmtKind::If { qualifier, cond, then, els } => self.if_stmt(qualifier, cond, then, els), - StmtKind::Case { qualifier, kw, expr, items, dangling } => { + StmtKind::Case { qualifier, kw, expr, inside, items, dangling } => { let mut head = String::new(); if let Some(q) = qualifier { head.push_str(q); @@ -2184,6 +2193,9 @@ impl<'a> Fmt<'a> { head.push_str(kw); head.push(' '); let mut docs = vec![text(head), self.parens(expr)]; + if *inside { + docs.push(text(" inside")); + } let mut body = Vec::new(); for item in items { body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); @@ -2259,15 +2271,34 @@ impl<'a> Fmt<'a> { ]); self.stmt_as_body(head, body) } - StmtKind::Assign { lhs, op, timing, rhs } => { - let mut docs = vec![self.expr(lhs), text(format!(" {op}"))]; + StmtKind::Assign { lhs, op, op_comments, rhs_comments, timing, rhs } => { + let mut docs = vec![self.expr(lhs)]; + // Comments written before the operator print before it, each + // kept on its own side (`x[6:0] /* opcode */ = v;`). + if self.inline_comments(op_comments, &mut docs) { + docs.push(Doc::HardLine); + docs.push(text(op.clone())); + } else { + docs.push(text(format!(" {op}"))); + } let mut rhs_docs = Vec::new(); if let Some(tc) = timing { rhs_docs.push(self.timing_control(tc)); rhs_docs.push(text(" ")); } rhs_docs.push(self.expr(rhs)); - docs.push(self.assign_rhs(concat(rhs_docs))); + if rhs_comments.is_empty() { + docs.push(self.assign_rhs(concat(rhs_docs))); + } else { + // As in a continuous assignment: the comments stay on the + // operator's line, and a line comment pushes the value + // onto the next one. + let mut inner = Vec::new(); + let ends_line = self.inline_comments(rhs_comments, &mut inner); + inner.push(if ends_line { Doc::HardLine } else { text(" ") }); + inner.push(concat(rhs_docs)); + docs.push(indent(inner)); + } concat(vec![group(docs), text(";")]) } StmtKind::ForceRelease { kw, lhs, rhs } => { @@ -2543,6 +2574,36 @@ impl<'a> Fmt<'a> { ExprKind::Inside { lhs, ranges } => { concat(vec![self.expr(lhs), text(" inside "), self.expr_list("{", ranges, "}")]) } + // A named call argument, printed the way a named connection is: + // `.name(value)`, tight, with a break opportunity inside. + ExprKind::NamedArg { name, value, close_comments, .. } => match &value.kind { + ExprKind::Empty(comments) => { + let mut docs = vec![text(format!(".{name}("))]; + let mut ends_line = false; + for cm in comments { + if ends_line { + docs.push(Doc::HardLine); + } + docs.push(self.comment(cm)); + ends_line = is_line_comment(&cm.text); + } + if ends_line { + docs.push(Doc::HardLine); + } + docs.push(text(")")); + concat(docs) + } + _ => { + let mut inner = vec![Doc::SoftLine, self.expr(value)]; + let ends_line = self.inline_comments(close_comments, &mut inner); + let close = if ends_line { Doc::HardLine } else { Doc::SoftLine }; + concat(vec![ + text(format!(".{name}(")), + group(vec![indent(inner), close]), + text(")"), + ]) + } + }, ExprKind::ValueRange { lo, hi } => { concat(vec![text("["), self.expr(lo), text(":"), self.expr(hi), text("]")]) } diff --git a/crates/vlog_formatter/tests/cases/dynamic_types.cases b/crates/vlog_formatter/tests/cases/dynamic_types.cases new file mode 100644 index 0000000..30d7d29 --- /dev/null +++ b/crates/vlog_formatter/tests/cases/dynamic_types.cases @@ -0,0 +1,421 @@ +# queue-typed class properties, with and without qualifiers +class c; + string instr_names[$]; + rand riscv_reg_field fld[$]; +endclass +---- +class c; + string instr_names [$]; + rand riscv_reg_field fld [$]; +endclass +==== +# queue locals inside a function body +class c; + function void gen(); + string instr[$]; + byte chars_q[$]; + endfunction +endclass +---- +class c; + function void gen(); + string instr [$]; + byte chars_q [$]; + endfunction +endclass +==== +# a queue initialized with the empty literal {} +module m; + bit [63:0] mem_states[$] = {}; +endmodule +---- +module m; + bit [63:0] mem_states [$] = {}; +endmodule +==== +# a queue initialized with a one-element concat +package p; + riscv_csr_t default_include_csr_write[$] = {MSCRATCH}; +endpackage +---- +package p; + riscv_csr_t default_include_csr_write [$] = {MSCRATCH}; +endpackage +==== +# a queue initialized with an assignment pattern +class c; + bit [6:0] legal_opcode[$] = '{7'b0000011, 7'b0001111}; +endclass +---- +class c; + bit [6:0] legal_opcode [$] = '{7'b0000011, 7'b0001111}; +endclass +==== +# a bounded queue [$:8] (no corpus file writes one; same dim grammar) +module m; + int bounded[$:8]; +endmodule +---- +module m; + int bounded [$:8]; +endmodule +==== +# a queue behind two unpacked ranges +module m; + payload_t data_fifo[NumInp-1:0][NumOut-1:0][$]; +endmodule +---- +module m; + payload_t data_fifo [NumInp-1:0][NumOut-1:0][$]; +endmodule +==== +# a queue of a parameterized class type +class c; + push_pull_item #(HostDataWidth, DeviceDataWidth) req_q[$]; +endclass +---- +class c; + push_pull_item #(HostDataWidth, DeviceDataWidth) req_q [$]; +endclass +==== +# dynamic arrays as class properties +class c; + rand int offset[]; + int unsigned num_of_page_table[]; +endclass +---- +class c; + rand int offset []; + int unsigned num_of_page_table []; +endclass +==== +# a dynamic array behind an unpacked range +class c; + riscv_instr_sequence sub_program[NUM_HARTS][]; +endclass +---- +class c; + riscv_instr_sequence sub_program [NUM_HARTS][]; +endclass +==== +# a file-scope dynamic array with an initializer (riscv_core_setting shape) +privileged_mode_t supported_privileged_mode[] = {MACHINE_MODE, USER_MODE}; +---- +privileged_mode_t supported_privileged_mode [] = {MACHINE_MODE, USER_MODE}; +==== +# a wildcard-keyed associative array [*] +module m; + logic control_array[*]; +endmodule +---- +module m; + logic control_array [*]; +endmodule +==== +# associative arrays: string, user-type and two-level string keys +class c; + string register_alias_lookup[string]; + csr_excl_s exclusions[my_key_t]; + protected uvm_severity m_changed_sev[string][string]; +endclass +---- +class c; + string register_alias_lookup [string]; + csr_excl_s exclusions [my_key_t]; + protected uvm_severity m_changed_sev [string][string]; +endclass +==== +# typedefs of a queue and of a dynamic array +package p; + typedef bit [3:0] nibble_q_t[$]; + typedef int dyn_t[]; +endpackage +---- +package p; + typedef bit [3:0] nibble_q_t [$]; + typedef int dyn_t []; +endpackage +==== +# queue and dynamic-array dims on function arguments, every direction +class c; + virtual function void update(string operands[$], output string instrs[$], ref field_t flds[]); + endfunction +endclass +---- +class c; + virtual function void update(string operands [$], output string instrs [$], ref field_t flds []); + endfunction +endclass +==== +# [$] and [$-1] as expression indexes +class c; + function void f(); + instr_list[$].label = trigger_label; + x = q[$-1]; + endfunction +endclass +---- +class c; + function void f(); + instr_list[$].label = trigger_label; + x = q[$-1]; + endfunction +endclass +==== +# new[expr] resizes a dynamic array (already parsed; pinned) +class c; + function void f(); + data_valid = new[num_ways]; + bytes = new[s.len()]; + endfunction +endclass +---- +class c; + function void f(); + data_valid = new[num_ways]; + bytes = new[s.len()]; + endfunction +endclass +==== +# queue methods are ordinary member calls (already parsed; pinned) +class c; + function void f(); + q.push_back(item); + q.delete(); + n = q.size(); + endfunction +endclass +---- +class c; + function void f(); + q.push_back(item); + q.delete(); + n = q.size(); + endfunction +endclass +==== +# named call arguments in task statements +class c; + task t; + csr_rd(.ptr(ptr), .value(rdata)); + clear_fifos(.clear_tx_fifo(1), .clear_rx_fifo(0)); + endtask +endclass +---- +class c; + task t; + csr_rd(.ptr(ptr), .value(rdata)); + clear_fifos(.clear_tx_fifo(1), .clear_rx_fifo(0)); + endtask +endclass +==== +# named call arguments on a package-scoped callee +module m; + initial dv_test_status_pkg::dv_test_status(.passed(err === '0 && test_done === '1)); +endmodule +---- +module m; + initial dv_test_status_pkg::dv_test_status(.passed(err === '0 && test_done === '1)); +endmodule +==== +# an explicitly empty named argument +class c; + task t; + g(.a()); + endtask +endclass +---- +class c; + task t; + g(.a()); + endtask +endclass +==== +# a named argument whose value is a concatenation +class c; + task t; + csr_wr(.ptr(ral.ovrd), .value({txval, en_ovrd})); + endtask +endclass +---- +class c; + task t; + csr_wr(.ptr(ral.ovrd), .value({txval, en_ovrd})); + endtask +endclass +==== +# a named-argument list that does not fit breaks one per line +class c; + task t; + drive_rx_error_byte(.parity_err($urandom_range(0, 9) == 0), .frame_err(some_long_name), .max_glitch_ps(core_clk_period_ps * 4)); + endtask +endclass +---- +class c; + task t; + drive_rx_error_byte( + .parity_err($urandom_range(0, 9) == 0), + .frame_err(some_long_name), + .max_glitch_ps(core_clk_period_ps * 4) + ); + endtask +endclass +==== +# case (x) inside, with a [lo:hi] range label and a default +class c; + function void init_reg(reg_t reg_name); + case (reg_name) inside + MISA: privil_level = M_LEVEL; + [MHPMCOUNTER3:MHPMCOUNTER31], MCYCLE: privil_level = M_LEVEL; + default: privil_level = U_LEVEL; + endcase + endfunction +endclass +---- +class c; + function void init_reg(reg_t reg_name); + case (reg_name) inside + MISA: privil_level = M_LEVEL; + [MHPMCOUNTER3:MHPMCOUNTER31], MCYCLE: privil_level = M_LEVEL; + default: privil_level = U_LEVEL; + endcase + endfunction +endclass +==== +# case (x) inside with several plain labels per item +module m; + always_comb begin + case (instr_name) inside + BCLR, BEXT, BINV, BSET: opcode = 7'b0010011; + SH1ADD, SH2ADD: opcode = 7'b0110011; + endcase + end +endmodule +---- +module m; + always_comb begin + case (instr_name) inside + BCLR, BEXT, BINV, BSET: opcode = 7'b0010011; + SH1ADD, SH2ADD: opcode = 7'b0110011; + endcase + end +endmodule +==== +# bare event controls keep their spelling: @ev and @hier.name +module m; + task t; + @ev; + @p_sequencer.monitor_tick; + endtask +endmodule +---- +module m; + task t; + @ev; + @p_sequencer.monitor_tick; + endtask +endmodule +==== +# a bodyless macro invocation before a hierarchical call statement +class c; + task t; + forever begin + `WAIT_FOR_RESET + cov.cg.sample(a, b); + end + endtask +endclass +---- +class c; + task t; + forever begin + `WAIT_FOR_RESET + cov.cg.sample(a, b); + end + endtask +endclass +==== +# an ifdef between queue declarations in a class body +class c; +`ifdef SIM + string dbg_q[$]; +`endif + int live_q[$]; +endclass +---- +class c; + `ifdef SIM + string dbg_q [$]; + `endif + int live_q [$]; +endclass +==== +# comments around a queue declaration stay put +class c; + // the pending grants, oldest first + bit [63:0] pending_grants[$]; // drained by the monitor +endclass +---- +class c; + // the pending grants, oldest first + bit [63:0] pending_grants [$]; // drained by the monitor +endclass +==== +# assigning the empty literal empties a queue +class c; + function void reset(); + q = {}; + endfunction +endclass +---- +class c; + function void reset(); + q = {}; + endfunction +endclass +==== +# two queue declarators in one declaration +module m; + data_t app_queue[$], acq_queue[$]; +endmodule +---- +module m; + data_t app_queue [$], acq_queue [$]; +endmodule +==== +# static and local queue properties +class c; + static riscv_instr_name_t instr_names[$]; + local dv_base_reg_field lockable_flds[$]; +endclass +---- +class c; + static riscv_instr_name_t instr_names [$]; + local dv_base_reg_field lockable_flds [$]; +endclass +==== +# comments on either side of a procedural assignment operator stay on their side +class c; + function automatic logic [31:0] cm_ret_ra(); + instr[6:0] /* opcode */ = OPCODE_JALR; + instr[14:12] /* funct3 */ = 3'b000; // jalr + x = /* immediate */ 12'd0; + endfunction +endclass +---- +class c; + function automatic logic [31:0] cm_ret_ra(); + instr[6:0] /* opcode */ = OPCODE_JALR; + instr[14:12] /* funct3 */ = 3'b000; // jalr + x = /* immediate */ 12'd0; + endfunction +endclass +==== +# a comment before a named argument's closing paren stays inside it +module m; + initial x = cm_mv_reg(.src(5'd0 /* x0 */), .dst(5'd10 /* a0 */)); +endmodule +---- +module m; + initial x = cm_mv_reg(.src(5'd0 /* x0 */), .dst(5'd10 /* a0 */)); +endmodule diff --git a/crates/vlog_formatter/tests/verification.rs b/crates/vlog_formatter/tests/verification.rs index 1cf77a7..3204718 100644 --- a/crates/vlog_formatter/tests/verification.rs +++ b/crates/vlog_formatter/tests/verification.rs @@ -856,3 +856,61 @@ endmodule assert_eq!(once, src, "a group with no alignment hint must not gain one"); assert_eq!(once, again); } + +// ------------------------------------------------------------------ +// Dynamic types: attack pairs for the shapes this round made reachable. +// Nothing new is verbatim and `verify.rs` is untouched, but these pin the +// net's strictness against the corruptions this plumbing could plausibly +// produce (CLAUDE.md invariant #4 discipline, applied voluntarily). +// ------------------------------------------------------------------ + +#[test] +fn a_dropped_queue_dollar_is_rejected() { + let input = "class c;\n string q[$];\nendclass\n"; + let output = "class c;\n string q[];\nendclass\n"; + expect_divergence(input, output); +} + +#[test] +fn a_dynamic_dim_widened_to_a_wildcard_is_rejected() { + let input = "module m;\n int a[];\nendmodule\n"; + let output = "module m;\n int a[*];\nendmodule\n"; + expect_divergence(input, output); +} + +#[test] +fn a_dropped_named_argument_name_is_rejected() { + let input = "module m;\n initial csr_wr(.ptr(p), .value(v));\nendmodule\n"; + let output = "module m;\n initial csr_wr(p, v);\nendmodule\n"; + expect_divergence(input, output); +} + +#[test] +fn a_dropped_case_inside_keyword_is_rejected() { + let input = "module m;\n initial case (x) inside\n [1:2]: y = 1;\n endcase\nendmodule\n"; + let output = "module m;\n initial case (x)\n [1:2]: y = 1;\n endcase\nendmodule\n"; + expect_divergence(input, output); +} + +#[test] +fn parens_invented_around_a_bare_event_are_rejected() { + let input = "module m;\n task t;\n @ev;\n endtask\nendmodule\n"; + let output = "module m;\n task t;\n @(ev);\n endtask\nendmodule\n"; + expect_divergence(input, output); +} + +#[test] +fn an_emptied_queue_initializer_is_rejected() { + let input = "module m;\n bit q[$] = {A, B};\nendmodule\n"; + let output = "module m;\n bit q[$] = {};\nendmodule\n"; + expect_divergence(input, output); +} + +#[test] +fn a_reindented_dynamic_type_declaration_is_accepted() { + // The legitimate transformation — whitespace only — still passes, so the + // six rejections above are not vacuous. + let input = "class c;\nstring q[$]={};\nrand int offset[];\nendclass\n"; + let output = "class c;\n string q [$] = {};\n rand int offset [];\nendclass\n"; + verify_equivalence(input, output).expect("whitespace is not part of the token stream"); +} diff --git a/crates/vlog_linter/src/context.rs b/crates/vlog_linter/src/context.rs index 03df70f..84400eb 100644 --- a/crates/vlog_linter/src/context.rs +++ b/crates/vlog_linter/src/context.rs @@ -5,23 +5,91 @@ use std::path::{Path, PathBuf}; use vlog_parser::ast::SourceFile; use vlog_parser::span::TextRange; use vlog_parser::token::{Comment, Token, TokenKind}; -use vlog_parser::{parse_source_tolerant, tokenize, LineIndex}; +use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex}; /// The default tab stop used when a fix expands a tab, matching vfmt's /// default indent. `LintContext::with_tab_width` follows `--indent`. const DEFAULT_TAB_WIDTH: usize = 2; +/// One text, parsed once: the products a lint run reads. +/// +/// This is the owned half of "one parse, two tools" (TODO §4): a caller with +/// no products of its own — `vfmt check` per file, [`LintContext::new`] — +/// parses here and lends the results to [`LintContext::from_parse`] via +/// [`ParsedSource::context`]. A caller that already holds the products (the +/// language server's per-buffer document) skips this type and calls +/// `from_parse` directly. +pub struct ParsedSource { + source: String, + tokens: Vec, + file: SourceFile, + line_index: LineIndex, +} + +impl ParsedSource { + /// Lex and tolerantly parse `source`, once. + /// + /// The token stream and the tree are two products of one lex: the parser + /// consumes its tokens, so the tree is built from a clone of the stream + /// rather than by lexing the text a second time (which is what + /// `parse_source_tolerant` would do — it is exactly `tokenize` + + /// `parse_tolerant`, so the tree is identical). A text that fails to lex + /// is the rare exception: it keeps the old path so the all-error tree is + /// byte-for-byte the one every consumer already handles. + /// + /// The parse diagnostics are deliberately not kept: no rule reads them, + /// and the one consumer that publishes them (the language server) holds + /// its own. + pub fn parse(source: &str) -> ParsedSource { + let (tokens, file) = match tokenize(source) { + Ok(tokens) => { + let (file, _diagnostics) = parse_tolerant(tokens.clone(), source); + (tokens, file) + } + // A lex error leaves no tokens (the lexer is all-or-nothing) and + // the whole file becomes one error leaf. Text rules still work, + // which is the point of not failing here. + Err(_) => (Vec::new(), parse_source_tolerant(source).0), + }; + ParsedSource { + source: source.to_string(), + tokens, + file, + line_index: LineIndex::new(source), + } + } + + /// A lint context borrowing this parse. `path` is the file the text came + /// from, or `None` for a buffer (stdin) — rules that need a filename skip. + pub fn context(&self, path: Option) -> LintContext<'_> { + LintContext::from_parse(&self.source, &self.tokens, &self.file, &self.line_index, path) + } +} + +/// Where a context's products live: parsed by the context itself +/// ([`LintContext::new`]) or lent by a caller that parsed once and keeps the +/// products for other uses too ([`LintContext::from_parse`]). +/// +/// A hand-rolled maybe-owned rather than `std::borrow::Cow` because +/// `SourceFile` is not `Clone`, which `Cow` requires. +enum Backing<'a> { + Owned(ParsedSource), + Borrowed { + source: &'a str, + tokens: &'a [Token], + file: &'a SourceFile, + line_index: &'a LineIndex, + }, +} + /// One file, prepared once and shared by every rule in the run. /// /// The parse is the **tolerant** one: a file that does not fully parse still /// gets linted, with the parts that failed sitting in the tree as /// `ItemKind::Error` / `StmtKind::Error` leaves that AST rules simply do not /// match. Token- and text-level rules are unaffected by parse errors. -pub struct LintContext { - source: String, - tokens: Vec, - file: SourceFile, - line_index: LineIndex, +pub struct LintContext<'a> { + backing: Backing<'a>, path: Option, tab_width: usize, /// Byte ranges of string literals, ascending — the one place text rules @@ -29,55 +97,81 @@ pub struct LintContext { strings: Vec, } -impl LintContext { - /// Prepare `source` for linting. `path` is the file the text came from, - /// or `None` for a buffer (stdin) — rules that need a filename skip. - pub fn new(source: &str, path: Option) -> LintContext { - // A lex error leaves no tokens (the lexer is all-or-nothing), and - // the tolerant parse turns the whole file into one error leaf. Text - // rules still work, which is the point of not failing here. - let tokens = tokenize(source).unwrap_or_default(); - let (file, _diagnostics) = parse_source_tolerant(source); - let strings = tokens - .iter() - .filter(|t| t.kind == TokenKind::String) - .map(|t| t.span) - .collect::>(); - LintContext { - source: source.to_string(), - tokens, - file, - line_index: LineIndex::new(source), - path, - tab_width: DEFAULT_TAB_WIDTH, - strings, - } +impl<'a> LintContext<'a> { + /// Prepare `source` for linting, parsing it here. `path` is the file the + /// text came from, or `None` for a buffer (stdin) — rules that need a + /// filename skip. + /// + /// This is the convenience wrapper over [`LintContext::from_parse`] for a + /// caller with nothing pre-parsed; both go through the same assembly. + pub fn new(source: &str, path: Option) -> LintContext<'static> { + LintContext::assemble(Backing::Owned(ParsedSource::parse(source)), path) + } + + /// Prepare a file the caller already parsed — "one parse, two tools" + /// (TODO §4). The products must describe the same text: `tokens` lexed + /// from `source` (empty if it does not lex), `file` the tolerant parse of + /// those tokens, `line_index` built over `source`. + /// + /// Breaking that contract costs *wrong findings* — possibly with spans + /// past the end of `source` — never memory unsafety and never a bad + /// write: `apply_fixes` independently rejects edits that fall outside + /// the text it is given (measured by the one-parse QA round). + pub fn from_parse( + source: &'a str, + tokens: &'a [Token], + file: &'a SourceFile, + line_index: &'a LineIndex, + path: Option, + ) -> LintContext<'a> { + LintContext::assemble(Backing::Borrowed { source, tokens, file, line_index }, path) + } + + /// The one place a context is put together, whoever owns the products. + fn assemble(backing: Backing<'a>, path: Option) -> LintContext<'a> { + let mut ctx = + LintContext { backing, path, tab_width: DEFAULT_TAB_WIDTH, strings: Vec::new() }; + ctx.strings = + ctx.tokens().iter().filter(|t| t.kind == TokenKind::String).map(|t| t.span).collect(); + ctx } /// Sets the tab stop a fix expands a tab to (the run's indent width). - pub fn with_tab_width(mut self, tab_width: usize) -> LintContext { + pub fn with_tab_width(mut self, tab_width: usize) -> LintContext<'a> { self.tab_width = tab_width.max(1); self } /// The source text being linted. pub fn source(&self) -> &str { - &self.source + match &self.backing { + Backing::Owned(parsed) => &parsed.source, + Backing::Borrowed { source, .. } => source, + } } /// The token stream, comments attached as leading/trailing trivia. pub fn tokens(&self) -> &[Token] { - &self.tokens + match &self.backing { + Backing::Owned(parsed) => &parsed.tokens, + Backing::Borrowed { tokens, .. } => tokens, + } } /// The tolerant parse of the source. pub fn file(&self) -> &SourceFile { - &self.file + match &self.backing { + Backing::Owned(parsed) => &parsed.file, + Backing::Borrowed { file, .. } => file, + } } /// Offset ↔ line:column for this file. pub fn line_index(&self) -> &LineIndex { - &self.line_index + match &self.backing { + Backing::Owned(parsed) => &parsed.line_index, + Backing::Borrowed { line_index, .. } => line_index, + } } /// The file this text came from, if it came from one. @@ -92,8 +186,8 @@ impl LintContext { /// The text of a 1-based line, without its newline. pub fn line_text(&self, line: u32) -> &str { - match self.line_index.line_range(line) { - Some(range) => self.source.get(range.as_range()).unwrap_or(""), + match self.line_index().line_range(line) { + Some(range) => self.source().get(range.as_range()).unwrap_or(""), None => "", } } @@ -109,7 +203,7 @@ impl LintContext { /// any comment-shaped rule finds them. pub fn comments(&self) -> Vec<&Comment> { let mut out: Vec<&Comment> = Vec::new(); - for token in &self.tokens { + for token in self.tokens() { out.extend(token.leading.iter()); out.extend(token.trailing.iter()); } @@ -150,4 +244,31 @@ mod tests { assert_eq!(LintContext::new("", None).with_tab_width(4).tab_width(), 4); assert_eq!(LintContext::new("", None).with_tab_width(0).tab_width(), 1); } + + #[test] + fn a_borrowed_context_reads_exactly_what_an_owned_one_does() { + // The property the whole round rests on: products in == source in. + let src = "module m;\n\twire a; // note\n string s = \"x\ty\";\nendmodule\n"; + let parsed = ParsedSource::parse(src); + let borrowed = parsed.context(Some(PathBuf::from("/rtl/m.sv"))); + let owned = LintContext::new(src, Some(PathBuf::from("/rtl/m.sv"))); + assert_eq!(borrowed.source(), owned.source()); + assert_eq!(borrowed.tokens().len(), owned.tokens().len()); + assert_eq!(format!("{:?}", borrowed.file()), format!("{:?}", owned.file())); + assert_eq!(borrowed.path(), owned.path()); + assert_eq!(borrowed.comments().len(), owned.comments().len()); + assert_eq!(borrowed.strings, owned.strings); + } + + #[test] + fn a_text_that_does_not_lex_still_parses_to_the_error_tree() { + // The lex-error fallback must produce the same all-error tree the old + // double-lex path did: one error item covering the whole text. + let src = "module m;\n wire a; /* unterminated\n"; + let parsed = ParsedSource::parse(src); + let ctx = parsed.context(None); + assert!(ctx.tokens().is_empty(), "the lexer is all-or-nothing"); + let (old_tree, _) = parse_source_tolerant(src); + assert_eq!(format!("{:?}", ctx.file()), format!("{old_tree:?}")); + } } diff --git a/crates/vlog_linter/src/lib.rs b/crates/vlog_linter/src/lib.rs index b25b146..70bc9a2 100644 --- a/crates/vlog_linter/src/lib.rs +++ b/crates/vlog_linter/src/lib.rs @@ -31,7 +31,7 @@ mod waiver; use std::path::PathBuf; -pub use context::LintContext; +pub use context::{LintContext, ParsedSource}; pub use registry::{all_rules, default_rules, rule_by_name, select_rules, Rule}; pub use rule_docs::rules_markdown; pub use violation::{apply_fixes, Applicability, Fix, Fixed, Violation}; diff --git a/crates/vlog_linter/tests/rules.rs b/crates/vlog_linter/tests/rules.rs index e8d4111..0119cb0 100644 --- a/crates/vlog_linter/tests/rules.rs +++ b/crates/vlog_linter/tests/rules.rs @@ -31,6 +31,18 @@ fn assert_lint_with(rules: &[&'static dyn vlog_linter::Rule], path: Option<&str> let violations = run(src, path.map(PathBuf::from), rules); let index = vlog_parser::LineIndex::new(src); + // "One parse, two tools" property, checked over every rule test input: + // a context built from pre-parsed products must find exactly what one + // built from the source does — rule, message, span and fix alike (the + // Debug form carries all four). + let parsed = vlog_linter::ParsedSource::parse(src); + let via_products = vlog_linter::lint(&parsed.context(path.map(PathBuf::from)), rules); + assert_eq!( + format!("{violations:?}"), + format!("{via_products:?}"), + "products in must equal source in\nsource:\n{src}" + ); + let mut actual: Vec<(u32, String)> = violations.iter().map(|v| (index.line_col(v.span.start).0, v.rule.to_string())).collect(); let mut expected = expectations(src); diff --git a/crates/vlog_parser/src/ast.rs b/crates/vlog_parser/src/ast.rs index cf21924..20decb6 100644 --- a/crates/vlog_parser/src/ast.rs +++ b/crates/vlog_parser/src/ast.rs @@ -338,15 +338,27 @@ impl DataType { } } -/// A dimension: `[expr]` or `[a:b]`. +/// A dimension: `[expr]`, `[a:b]`, `[]`, or `[*]`. #[derive(Debug, Clone)] pub struct Dim { - pub a: Expr, - pub b: Option, + pub kind: DimKind, /// Code extent including the brackets. pub span: TextRange, } +/// What stands between a dimension's brackets. +#[derive(Debug, Clone)] +pub enum DimKind { + /// `[expr]` or `[a:b]` — also `[$]`, `[$:N]` (a bare `$` is an ordinary + /// expression) and `[string]` / `[key_t]` (a type or name used as an + /// associative-array key parses as an expression). + Range { a: Expr, b: Option }, + /// `[]` — a dynamic array. + Dynamic, + /// `[*]` — a wildcard-keyed associative array. + Wildcard, +} + #[derive(Debug)] pub struct Typedef { pub name: String, @@ -482,6 +494,10 @@ pub enum SensList { after: Vec, }, List(Vec), + /// `@name` or `@a.b` written without parens; printed back without them — + /// inventing a `( ... )` would be a token-stream change the safety net + /// refuses. + Bare(Expr), } #[derive(Debug)] @@ -834,6 +850,9 @@ pub enum StmtKind { qualifier: Option, kw: String, expr: Expr, + /// True for `case (expr) inside`, whose labels may be `[lo:hi]` + /// value ranges. + inside: bool, items: Vec, dangling: Vec, }, @@ -867,6 +886,13 @@ pub enum StmtKind { Assign { lhs: Expr, op: String, + /// Comments written between the left-hand side and the operator + /// (`instr[6:0] /* opcode */ = ...;`). Kept here so they print on + /// the operator's left instead of being lost. + op_comments: Vec, + /// Comments written between the operator and the right-hand side, + /// kept on the operator's line as a continuous assignment's are. + rhs_comments: Vec, /// Intra-assignment timing control (e.g. `#1`, `@(posedge clk)`). timing: Option, rhs: Expr, @@ -1052,6 +1078,19 @@ pub enum ExprKind { lhs: Box, ranges: Vec, }, + /// A named call argument: the `.ptr(ral.ovrd)` of + /// `csr_wr(.ptr(ral.ovrd), .value(x))`. `value` is [`ExprKind::Empty`] + /// for `.name()`, exactly as an empty connection is. + NamedArg { + name: String, + /// Byte range of `name`. + name_span: TextRange, + value: Box, + /// Comments written between the value and the closing `)` + /// (`.src(5'd0 /* x0 */)`), printed back inside the parens — the + /// same slot a connection has. + close_comments: Vec, + }, /// `[a:b]` inside an `inside` range list or value range. ValueRange { lo: Box, diff --git a/crates/vlog_parser/src/parser.rs b/crates/vlog_parser/src/parser.rs index 5f737db..688f6ca 100644 --- a/crates/vlog_parser/src/parser.rs +++ b/crates/vlog_parser/src/parser.rs @@ -687,10 +687,64 @@ impl<'a> Parser<'a> { fn parse_expr_item(&mut self) -> PResult { 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 { + 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 { + 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 { @@ -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(_))); + } } diff --git a/crates/vlog_parser/tests/spans.rs b/crates/vlog_parser/tests/spans.rs index 16f8201..fc23b12 100644 --- a/crates/vlog_parser/tests/spans.rs +++ b/crates/vlog_parser/tests/spans.rs @@ -63,6 +63,10 @@ const SOURCES: &[&str] = &[ "virtual class base #(parameter int W = 8) extends pkg::top #(.A(1), b) implements i, j;\n rand bit [W-1:0] v;\n local int n;\n virtual my_if h;\n pure virtual function void f();\n extern task t(int x);\nendclass : base\n", "class c;\n port_t #(bit [3:0]) p;\n constraint x {\n a == 0; // why\n } // after\n covergroup g;\n coverpoint a;\n endgroup : g\n function new(string name);\n super.new(name);\n x = db#(virtual bus_if)::get(this);\n endfunction : new\nendclass\n", "typedef class fwd;\npackage p;\n class inner extends fwd;\n endclass\nendpackage\nfunction void inner::configure(int x);\nendfunction\n", + // Dynamic types: queues, dynamic and associative arrays, `$` indexes, + // named call arguments, `case ... inside`, a bare event control. + "class c;\n string q[$] = {};\n rand int offset[];\n logic hits[*];\n string lut[string];\n item_t #(A, B) rq[NumInp-1:0][$:8];\n function void f(string ops[$], output int outs[]);\n q[$].label = ops[$-1];\n offset = new[n];\n endfunction\nendclass\n", + "module m;\n typedef bit [3:0] q_t[$];\n task t;\n csr_wr(.ptr(ral.ovrd), .value({a, b}), .flag());\n @hier.tick;\n case (x) inside\n [A:B], C: y = 1;\n default: y = 0;\n endcase\n endtask\nendmodule\n", ]; /// A token or a comment, in source order. @@ -743,6 +747,10 @@ fn check_expr(src: &str, e: &Expr, parent: TextRange) { | ExprKind::Postfix { expr, .. } | ExprKind::Cast { expr, .. } | ExprKind::Paren { inner: expr, .. } => check_expr(src, expr, here), + ExprKind::NamedArg { name, name_span, value, .. } => { + check_name(src, "named argument", name, *name_span, here); + check_expr(src, value, here); + } ExprKind::Binary { lhs, rhs, .. } => { check_expr(src, lhs, here); check_expr(src, rhs, here); diff --git a/crates/vlog_semantic/src/bind.rs b/crates/vlog_semantic/src/bind.rs index 9e7a956..2e20e73 100644 --- a/crates/vlog_semantic/src/bind.rs +++ b/crates/vlog_semantic/src/bind.rs @@ -693,6 +693,8 @@ impl<'a> Binder<'a> { } } TimingControl::Event(SensList::Star { .. }) => {} + // `@name;` without parens — the expression is an ordinary use. + TimingControl::Event(SensList::Bare(e)) => self.bind_expr(e, scope), } } @@ -708,8 +710,14 @@ impl<'a> Binder<'a> { fn bind_dims(&mut self, dims: &[Dim], scope: ScopeId) { for d in dims { - self.bind_expr(&d.a, scope); - self.bind_opt_expr(d.b.as_ref(), scope); + match &d.kind { + DimKind::Range { a, b } => { + self.bind_expr(a, scope); + self.bind_opt_expr(b.as_ref(), scope); + } + // `[]` and `[*]` hold no expressions — nothing to bind. + DimKind::Dynamic | DimKind::Wildcard => {} + } } } @@ -780,6 +788,10 @@ impl<'a> Binder<'a> { self.bind_expr(lo, scope); self.bind_expr(hi, scope); } + // A named call argument: the value is an ordinary use; the name + // is the callee's formal, which this crate does not model (the + // same rule connection port names follow). + ExprKind::NamedArg { value, .. } => self.bind_expr(value, scope), ExprKind::Type(ty) => self.bind_data_type(ty, e.span, scope), ExprKind::MinTypMax { min, typ, max } => { self.bind_expr(min, scope); diff --git a/docs/features/dynamic-types/README.md b/docs/features/dynamic-types/README.md new file mode 100644 index 0000000..fbf92ed --- /dev/null +++ b/docs/features/dynamic-types/README.md @@ -0,0 +1,760 @@ +# dynamic-types + +## Goal + +Parse and format the dynamic-type declarations and the call syntax that are the +corpus's top remaining parse blockers after the classes round: queues +(`T name[$]`), dynamic arrays (`T name[]`), associative arrays +(`T name[string]`, `T name[*]`), named function/task call arguments +(`f(.a(x), .b(y))`), and `case (expr) inside`. The whole-corpus first-blocker +histogram going in: `$` 41 files, `]` 23, `.` 21, `inside` 7 — together 92 of +the 242 parse errors. All of it is DV/UVM code under `ibex/dv`, +`google_riscv-dv`, `lowrisc_ip/dv` and `common_cells/test`; every shape below +is taken from a real blocked file, cited. + +## What is structural, and what is verbatim + +Everything in this round is **structural** — real AST, canonical layout. +Nothing new is captured verbatim, so no new normalization was needed and +`verify.rs` is untouched (see Handshakes). + +| construct | corpus evidence | +|---|---| +| `T q[$]` in class properties, module/function locals | `riscv_instr.sv:23`, `str_utils_pkg.sv:80`, `uart_scoreboard.sv:34` | +| `[$]` after multi-dim unpacked dims (`x [A][B][$]`) | `stream_xbar_tb.sv:52`, `rr_arb_tree_tb.sv:224` | +| queue of parameterized type (`item #(A, B) q[$]`) | `push_pull_device_seq.sv:54` | +| `[$]` in function/task args, all directions (`output string instrs[$]`, `ref ... flds[$]`) | `riscv_privileged_common_seq.sv:37`, `dv_base_reg_pkg.sv:90` | +| `q[$]` / `q[$-1]` as an expression index (`instr_list[$].label = x`) | `ibex_directed_instr_lib.sv:43`, `riscv_directed_instr_lib.sv:34` | +| bounded queue `T q[$:N]` | **zero corpus hits** (`grep -rEn '\[\$:'`), taken anyway — it is the same `Range` dim the unbounded spelling produces, zero extra grammar | +| `T a[]` dynamic arrays, same positions | `riscv_amo_instr_lib.sv:22`, `riscv_pmp_cfg.sv:62`, `riscv_asm_program_gen.sv:32` (`[NUM_HARTS][]`) | +| `= {}` / `= {A, B}` queue/dyn-array initializers | `ibex_icache_scoreboard.sv:31` (`= {}`), `riscv_core_setting.sv:27` (×12 targets), `riscv_instr_pkg.sv:1214` | +| `T a[*]` wildcard associative | `cb_filter_tb.sv:51` | +| named call arguments `f(.a(x))`, incl. scoped callees and multi-line lists | `uart_base_vseq.sv:156`, `prim_lfsr_tb.sv:297`, `uart_noise_filter_vseq.sv:42` | +| `case (expr) inside` with `[lo:hi]` and plain labels | `riscv_privil_reg.sv:28,189`, `riscv_zbs_instr.sv:42` (7 files, 40 occurrences) | +| `@hier.name;` event control without parens | `ibex_mem_intf_response_seq_lib.sv:60` | + +**Verified already parsing (no work needed, pinned by cases):** +`T a[string]` and `T a[user_key_t]` associative arrays (`string` is a +TYPE_KEYWORD and parses as a type expression inside the brackets; an +identifier key parses as an expression — both round-trip); `x = new[expr]` +(`new` is deliberately not a keyword, so this is an index on an ordinary +name — `core_ibex_test_lib.sv:475`, `str_utils_pkg.sv:169`); queue method +calls (`q.push_back(x)`, `q.size()`) are ordinary member calls. + +## Assumptions + +- **`$` is an ordinary primary expression, not a keyword.** In real code a + bare `$` stands only where a queue bound belongs (`q[$]`, `[$:N]`, + `q[$-1]`), but vfmt does not check legality anywhere else either, and one + `ExprKind::Ident("$")` leaf makes every position — dims, indexes, ranges, + arithmetic — work through the existing expression grammar. This follows the + `new`/`this`/`super` precedent from the classes round. The lexer already + emits a lone `$` as a one-char Symbol token; nothing lexes differently. +- **`{}` is accepted as an empty concatenation** (`ExprKind::Concat(vec![])`) + because SystemVerilog's empty queue literal is spelled that way + (`mem_states[$] = {};`). Plain Verilog forbids `{}`; vfmt is a formatter, + not a compiler, and refusing it would keep a real corpus file blocked. +- **A named call argument is recognized by `.` + identifier at an expression + *element* start.** `parse_expr_item` is shared by call arguments, concats, + replications and case labels; the `.name(...)` prefix is only legal in the + first, but accepting it in the others changes no existing parse (no + expression can start with `.` today) and cannot corrupt (same tokens out). + Same argument for `[lo:hi]` value-range elements, which `case ... inside` + labels need and no expression could previously start with. +- **`case (x) inside` is the same statement with one extra token.** The + `inside` flag is stored on `StmtKind::Case` and printed back; item labels + are the ordinary label list plus `[lo:hi]` ranges. vfmt does not restrict + range labels to inside-mode cases — a plain `case` with a `[1:2]:` label is + not legal SV but parses; same tokens out, no corruption possible. +- **A bare `@name;` (no parens) is printed back without parens.** Before this + round the parser accepted `@ev;` and the formatter printed `@(ev)` — a + token-stream change the net *refused* (pre-existing, zero corpus files hit + it, found while extending the arm). `SensList::Bare` records the spelling; + `@(ev)` stays a `List`. The bare arm now also takes a `.`-chain + (`@p_sequencer.monitor_tick;`). +- **A macro invocation followed by `ident.` is standalone.** `at_macro_item`'s + identifier arm gains one clause (next-next token `.`), mirroring the `#(` + clause the classes round added: `` `WAIT_FOR_RESET`` ⏎ `cov.cg.sample(...)` + is a standalone macro and a call statement, never a declaration — a + declarator name is never followed by `.`. Wrong guesses still cannot + corrupt: both readings emit the same tokens. +- **Two comment drops were fixed mid-round** (the classes-round protocol: a + refusal the corpus can now hit is fixed, not documented away). They are + not the same category, stated precisely per QA-1: + - **pre-existing** — a comment beside a procedural assignment's operator + (`instr[6:0] /* opcode */ = OPCODE_JALR;`, both sides) reproduces on + HEAD with no new syntax: it was left in the pending buffers and the net + refused the file. `StmtKind::Assign` gained `op_comments`/`rhs_comments`, + captured with the same `take_around` marks a continuous assignment's + `rhs_comments` use. Found by `ibex_compressed_decoder.sv:89` the moment + its earlier blocker (named call args at line 62) was gone. + - **this round's own new code** — a comment before a named argument's + closing `)` (`.src(5'd0 /* x0 */)`) cannot reproduce at HEAD because + `NamedArg` did not exist there (the `Connection` analog it is modelled + on formats cleanly on HEAD). The first `NamedArg` version lacked the + before-`)` slot a `Connection` has; `close_comments` was added when the + corpus caught it (same file, line 139) — a gap caught and fixed inside + the round. +- **Blocked-but-out-of-scope shapes stay parse errors**, with evidence: + `` `uvm_field_int (x, y)`` (space before `(`) is the documented macro-items + lexer gap, 10 files, not touched; `interface` declarations (25 files) are + README roadmap item 8; the `wait(...)` / `with` / DPI shapes are single + files each and listed in the corpus results below. + +## Handshakes + +**Changed in `vlog_parser::ast` (consumed by `vlog_formatter`):** + +- `Dim` is now `{ kind: DimKind, span }` with + `DimKind::Range { a: Expr, b: Option }` (every pre-existing dim, plus + `[$]`/`[$:N]`/`[string]`/`[key_t]` via ordinary exprs), `DimKind::Dynamic` + (`[]`) and `DimKind::Wildcard` (`[*]`). This is the one **non-additive** + change of the round; every consumer was found by grep and updated: + `Fmt::dim` (format.rs), `bind_dims` (`vlog_semantic/src/bind.rs`, see + below), and the spans walker (reads only `span`, unchanged). +- `ExprKind::NamedArg { name, name_span, value: Box, close_comments }` + — a named call argument. `value` is `ExprKind::Empty(comments)` for + `.a()`, exactly as a connection's empty `()` is; `close_comments` is the + before-`)` slot a `Connection` has. Printed tight: `.name(value)`. +- `SensList::Bare(Expr)` — `@name` / `@a.b` with no parens, printed back + without parens. `SensList::List` still always prints `@( ... )`. +- `StmtKind::Case` gained `inside: bool`; `StmtKind::Assign` gained + `op_comments` / `rhs_comments` (see Assumptions). Additive for every `..` + match; `Fmt::stmt_kind` (exhaustive) updated in the same change. +- `ExprKind::Concat(items)` may now be empty (`{}`); `Fmt::expr_list` → + `delimited` already prints an empty list as `{}`. +- `parse_ident_item`'s parameterized-type lookahead refined: `[` after the + declarator is an instance array range only when its matching `]` is + followed by `(`, so `item_t #(A, B) q[$];` is a declaration while + `sub #(8) u[3:0] (...);` stays an instance. The statement-level twin in + `parse_assign_or_expr_stmt` already read it correctly. + +**Consumed from / required of `vlog_semantic` (minimal, documented):** +`bind.rs` is expression- and dim-exhaustive, so three small arms were +required to compile; each is the semantically correct minimum, not a stub: + +- `bind_dims` matches `DimKind::Range` (binds `a`/`b` exactly as before) and + skips `Dynamic`/`Wildcard` (no expressions to bind — nothing skipped). +- `ExprKind::NamedArg { value, .. }` binds `value`; the argument *name* is + the callee's formal, which this crate does not model (same rule as + `Connection` port names). +- `TimingControl::Event(SensList::Bare(e))` binds `e`. + +**Required of `vlog_linter`: nothing.** `visit.rs` walks items/statements +only (no expression walk) and its `StmtKind::Case` matches use `..`; the +crate compiles unmodified. Not touched — the concurrent one-parse-two-tools +round owns it. + +**`verify.rs` is untouched** (`git diff --quiet -- crates/vlog_formatter/src/verify.rs` +exits 0). Nothing new is verbatim and no normalization was added, so hard +invariant #4 does not bind. Six rejection tests went into +`tests/verification.rs` anyway (a dropped `$`, `[]` widened to `[*]`, a +dropped named-arg name, a dropped `inside` keyword, parens invented around a +bare event, an emptied `{}` initializer — all asserted rejected; the +legitimate re-indent asserted accepted). + +**Recursion/chain budgets:** nothing new to charge. `$` is a leaf; +`NamedArg` wraps its value once and is built inside the existing +argument-list loop (not a postfix chain); `DimKind` adds no depth. The dim +loop and label loop were already flat. + +**Spans:** every new node carries a span. `NamedArg` keeps +`src[name_span] == name` (checked by the walker's new arm); +`ValueRange`/`Bare` reuse existing walker arms; two dynamic-type sources were +added to `SOURCES`. + +**Not touched, by scope:** `crates/vfmt`, `crates/vfmt_core`, +`crates/vfmt_server`, `crates/vlog_linter`, `verify.rs`, `fence.rs`, +`editors/`, `tools/`, `corpus/`. A concurrent agent owns `vlog_linter` / +`vfmt` / `vfmt_server` this round; `cargo fmt` was run per-package +(`-p vlog_parser -p vlog_formatter -p vlog_semantic`), never `--all`. + +## Status / TODO + +- [x] `$` as a primary expression (`q[$]`, `q[$-1]`, `[$]`, `[$:N]`). +- [x] `DimKind::{Range, Dynamic, Wildcard}`; every consumer updated. +- [x] `{}` empty concatenation/queue literal. +- [x] Named call arguments (`ExprKind::NamedArg`), `.a()` empty value, + multi-line lists, scoped callees. +- [x] `case (expr) inside` with `[lo:hi]` labels (`StmtKind::Case.inside`). +- [x] `SensList::Bare` — `@name;` / `@a.b;` without parens (also fixes the + pre-existing `@ev;` refusal). +- [x] `at_macro_item`: identifier followed by `.` means the macro stands + alone. +- [x] Comments beside a procedural assignment's operator and before a named + argument's `)` (the two newly-reachable pre-existing drops; see + Assumptions). +- [x] Verified already parsing, pinned by cases: `[string]`, `[key_t]`, + `new[expr]`, queue method calls. +- [x] 34 cases in `crates/vlog_formatter/tests/cases/dynamic_types.cases` + (397 → 431 overall). +- [x] 13 parser unit tests, 7 `tests/verification.rs` tests (6 rejection, + 1 acceptance), 2 new `spans.rs` sources + the `NamedArg` walker arm + (name-span exactness checked). +- [x] Corpus re-run: by-path diff, 0 regressions, round-trip of **all 636** + formattable files, TSV deterministic across three runs (two before + the final `cargo fmt`, one after — byte-identical). +- [x] `README.md` roadmap item 4 struck + supported-syntax updated; TODO.md + corpus annotation. +- [ ] **Not done — `interface` declarations** (25 files, the new top + blocker). Roadmap item 8; a header-and-modport grammar of its own. +- [ ] **Not done — a directive inside an element** (13 files now show + `` `else`` as their first blocker, 12 of them the + `riscv_core_setting.sv` copies advancing past `[]`): the shape is + `` `ifdef DSIM`` ⏎ `privileged_reg_t implemented_csr[] = {` ⏎ + `` `else`` ⏎ `const ... = {` ⏎ `` `endif`` ⏎ *shared elements* — two + alternative declaration *heads* over one initializer body + (`target/ml/riscv_core_setting.sv:98-102`). This is the + directives-in-lists round's documented non-goal ("a directive inside + an element stays a parse error"), now measured at 13 files; unparking + it is a design round of its own, not a list-machinery patch. +- [ ] **Not done — `` `uvm_field_int (x, y)``** (11 files): the documented + macro-items lexer gap (space before `(`); its fix lives in the lexer + and has a known expression-position side effect. Still not this + feature's to make. +- [ ] **Not done — `randomize() with { ... }`** (7 files, e.g. + `cb_filter_tb.sv:272`, `ibex_mem_intf_response_driver.sv:94`): an + inline-constraint clause — the constraint sub-language again, so the + classes round's verbatim treatment is the natural vehicle when a + round takes it. +- [ ] **Not done — `foreach` over a hierarchical index** (2 files, both + advanced from `]`): `foreach (program_h[id].sub_program_id[k])` + (`riscv_callstack_gen.sv:183`) and `foreach (page_table[i].pte[j])` + (`riscv_page_table_list.sv:130`). The `foreach` header grammar takes a + plain name plus loop variables, not a member chain with per-level + indexes — its own small construct, not dim machinery. These two are why + the `.` *token* still appears as a first blocker (QA-2). +- [ ] **Not done — a `[lo:hi]` value range as the *first* call argument** + (`f([1:2])` is a parse error while `f(x, [1:2])` parses): the postfix + `(` branch's first-argument dispatch gained the `.` case but not the + `[` case. No legal SystemVerilog is affected — a value range is not a + call argument — and `case … inside` labels go through + `parse_expr_item` at every position including the first. Recorded per + QA-8 so the asymmetry is not mistaken for a bug later. +- [ ] **Not done — associative-array *typed* keys beyond what already + parses** (e.g. `[bit [31:0]]`): zero corpus hits. Parked until a file + demands it. + +## Corpus results + +`./tools/corpus_check.sh corpus` over the same pinned 820-file corpus, release +build, exit 0. Three runs (two mid-round, one after the final `cargo fmt`): +byte-identical TSVs, md5 `e6f12eb7964e22e452655cf517cae766`. All four corpus +repos verified unmodified afterwards (`git status --porcelain` clean apart +from the pre-existing untracked `.vfmt-corpus-rev` stamps). + +| metric | before | after | +|---|---|---| +| **parsed & formattable** | 578/820 (**70.5%**) | **636/820 (77.6%)** | +| would-reformat | 568 | 626 | +| ok-unchanged | 10 | 10 | +| parse-error | 242 (29.5%) | **184 (22.4%)** | +| verification-error | 0 | **0** | +| crash | 0 | **0** | + +**Diffed by path against the baseline TSV, not just by count:** + +| transition | files | +|---|---| +| parse-error → would-reformat | 58 | +| would-reformat → would-reformat | 568 | +| ok-unchanged → ok-unchanged | 10 | +| parse-error → parse-error | 184 | +| **any regression** | **0** | + +58 files gained, 0 lost, no already-parsing file changed status. Gained by +tree: `google_riscv-dv` 24, `lowrisc_ip` 14, `opentitan/hw/ip` 8, +`common_cells/test` 7, `ibex/dv/uvm` 4, `ibex/rtl` 1 +(`ibex_compressed_decoder.sv` — an RTL file, blocked on named call args). + +**Per target blocker, the honest ledger** (each baseline-blocked file's +after-status checked individually): + +| blocker | files | now format | advanced | their next blockers | +|---|---|---|---|---| +| `$` (queues) | 41 | **28** | 13 | `with` 3, one each: `assert` (`fifo_tb.sv:155`), `@` (`stream_register_tb.sv:75`), `;` (`ibex_cosim_scoreboard.sv:307`), `,` (`ibex_debug_triggers_overrides.sv:116`), `::` (`riscv_instr.sv:156`), `cp_sign_cross` (`riscv_instr_cover_group.sv:514`, a covergroup cross), `` `else`` (`riscv_instr_pkg.sv:1252`), `import` (`dv_base_reg_field.sv:97`), `` `TX_IGNORED_PERIOD`` (`uart_scoreboard.sv:155`) | +| `]` (dynamic arrays) | 23 | **6** | 17 | `` `else`` 12 (the `riscv_core_setting` head-swap shape, see Status/TODO), `::` 2, `.` 2, `with` 1 | +| `.` (named args) | 21 | **17** | 4 | `randcase` 3 (its weight labels are the reported `1`/`5` tokens), `with` 1 | +| `inside` | 7 | **7** | 0 | — | + +**New whole-corpus first-blocker histogram:** `interface` 25, `` `else`` 13, +`` `uvm_field_int `` 11, `with` 7, `"DPI-C"` 7, `'` 7 (lex, `` '` `` in +macro bodies and unbased literals), `$error` 6, `virtual` 4, `export` 4. +No *shape* this round targeted remains a first blocker anywhere; the `.` +*token* remains first in 2 files, whose blocker is a different shape — +`foreach` over a hierarchical index (`foreach (a[i].b[j])`), parked under +Status/TODO with the evidence. + +**Every formattable file was round-tripped, not sampled:** all 636 copied to +a scratch directory, formatted in place, then re-checked with `--check` — +exit 0 both passes, so every one is a verified fixed point. + +**Two verification errors appeared mid-round and both were fixed, not +documented away** (both pre-existing comment drops reproducible without any +new syntax; see Assumptions): the corpus count went 1 → 1 → **0** as the +assignment-operator fix exposed the named-arg-paren drop in the same file. + +## Work log + +### 2026-08-19 — dev agent + +- Read `CLAUDE.md`, `README.md`, `TODO.md`, and the `classes`, + `directives-in-lists` and `directives-in-instances` READMEs before touching + code. Baseline measured on this working tree, not taken from any README: + `cargo test --workspace` **768 passed** (verified suite-by-suite), clippy + silent, fmt clean; corpus 578/820 formattable, 242 parse-error, 0 + verification errors, 0 crashes — matching the brief exactly. +- **Read the actual blocked lines of all 92 target files first** (a script + pulled each parse error's line from its file), and the reading changed the + design three times over: + (a) `[string]`, `[key_t]` and `new[expr]` **already parse** — `string` is + a TYPE_KEYWORD that goes through `parse_type_expr`, and `new` is + deliberately not a keyword, so `new[n]` is an ordinary index. Half of + "associative arrays" was already done and just needed pinning. + (b) The `.` blocker is *named call arguments* in 17 of 21 files, plus one + `@hier.name` event control and one macro-then-`cov.` shape — three + different fixes, not one. + (c) `inside` is `case (expr) inside` in all 7 files — the expression + operator was never the problem. +- **`$` became one `ExprKind::Ident` leaf, not a keyword and not a dim + special case.** The first sketch had a `DimKind::Queue` variant; reading + `instr_list[$].label = x` killed it — `$` stands in *expression* position + there, so a dim-only spelling would have needed a second rule for indexes. + One primary-expression arm makes `[$]`, `[$:N]`, `q[$]` and `q[$-1]` all + fall out of the existing grammar, following the classes round's + `new`/`this`/`super` precedent. `[$:N]` ships tested with zero corpus + demand because it is literally the same `Range` dim. +- **`DimKind` is the round's one non-additive AST change**, and its blast + radius was measured before the edit: grep found exactly three consumers + reading `Dim`'s fields (`Fmt::dim`, `bind_dims`, and the spans walker, + which reads only `span`). The alternative — sentinel expressions for `[]` + and `[*]` — would have made the formatter print from lies. +- **Named args went into `parse_expr_item`, the shared element parse**, plus + one dispatch in the postfix `(` branch (the *first* argument does not go + through `parse_expr_item`; found when `csr_wr(.ptr(p), ...)` parsed its + first arg as an error). Value-range labels (`[lo:hi]`) ride the same + dispatch, which is what makes `case ... inside` labels work at every + position without touching `parse_expr_list`. Accepting both shapes in + lists that cannot legally hold them is recorded under Assumptions: no + expression could previously start with `.` or `[`, so nothing re-parses. +- **The bare-event fix started as a parse extension and became a formatter + bug fix.** Extending `@ident` to `@a.b` was two lines — and then the probe + showed plain `@ev;` had *always* been refused at runtime (the parser + accepted it, the formatter printed `@(ev)`, the net refused the invented + parens; zero corpus files hit it, which is why it survived). Hence + `SensList::Bare`: record the spelling, print the spelling. +- **`parse_ident_item`'s `#(` heuristic said `[` means instance; a queue + declarator disproved it.** `item_t #(A, B) q[$];` read as an instance + array and died at `;`. The refinement — `[` is an instance range only when + its matching `]` is followed by `(` — is the same after-the-brackets test + the plain-ident branch already used. The classes README's "a wrong guess + cannot corrupt" argument still holds, and the statement-level twin already + did this correctly. +- **Two verification errors surfaced at the first corpus runs and both were + fixed rather than parked** (details under Assumptions). Both reproduce on + inputs with no dynamic-type syntax whatsoever, i.e. they are pre-existing + drops this round made reachable — the exact situation the classes round + hit with the `` `define`` lexer bug, resolved the same way: fix, pin with + cases, state it. `StmtKind::Assign` gained the comment slots a + `ContAssign`'s pairs already had; `NamedArg` gained the `close_comments` a + `Connection` already had. Neither touched `verify.rs`. +- **The case table was generated from real formatter output and then + reviewed**, not hand-typed: every expected block is the binary's own + output for the crafted input (each already runtime-verified for + equivalence + convergence by the format call itself), eyeballed against + house style before committing. 34 cases, every shape in the Goal table, in + module/class/package/typedef/function positions, with comments and an + `` `ifdef`` interleaved. +- **Corpus delta verified by path** (58 gained, 0 lost, 0 category changes), + per-target ledgers computed by joining the two TSVs, all 636 formattable + files round-tripped individually, TSVs byte-identical across three runs, + corpus repos confirmed clean. The `` `else`` 13 and `with` 7 next-blockers + were read at their sites and filed under Status/TODO with the evidence. +- **Scope discipline:** did not touch `verify.rs`, `fence.rs`, + `crates/vfmt*`, `crates/vlog_linter` (its `visit.rs` needed no arm — it + has no expression walk and its `Case` matches use `..`), `tools/`, + `corpus/`. The concurrent one-parse-two-tools agent's files churned in the + same tree throughout; `cargo fmt` was run per-package + (`-p vlog_parser -p vlog_formatter -p vlog_semantic`), never `--all`, and + the one transient `vfmt_server` test failure observed mid-round was + re-run and confirmed to be their in-flight edit, not this diff. Did not + run `git commit` / `git push`. +- **Session note:** the session was interrupted by a usage limit mid-way + through the `vlog_semantic` compile fixes and resumed; the tree state was + re-verified from disk before continuing (the missing piece was the + `bind_expr` `NamedArg` arm). + +**Results:** `cargo test --workspace` **791 passed, 0 failed** (768 baseline ++ 13 `vlog_parser` unit + 7 `vlog_formatter` verification, + 3 the +concurrent agent landed mid-round; the case table grew 397 → 431 inside its +single test). `cargo clippy --workspace --all-targets` silent, 0 warnings. +`cargo fmt -p vlog_parser -p vlog_formatter -p vlog_semantic -- --check` +clean. Corpus: **636/820 formattable (77.6%**, up from 578/70.5%), **184 +parse-error** (down from 242), **0 verification errors, 0 crashes, 0 +regressions by path**; `tools/corpus_check.sh` exits 0. + +Files touched: `crates/vlog_parser/src/{ast,parser}.rs`, +`crates/vlog_parser/tests/spans.rs`, `crates/vlog_formatter/src/format.rs`, +`crates/vlog_formatter/tests/verification.rs`, +`crates/vlog_formatter/tests/cases/dynamic_types.cases` (new), +`crates/vlog_semantic/src/bind.rs` (three small arms, documented under +Handshakes), `README.md`, `TODO.md`, this README. + +### 2026-08-19 — dev agent, post-QA corrections (all four LOW findings) + +- **QA-1 correction, for the record:** the earlier entry's claim that *both* + comment-drop fixes "reproduce on inputs with no dynamic-type syntax + whatsoever" was half-true. Only the assignment-operator drop is + pre-existing on HEAD. The named-argument `close_comments` gap was in this + round's own new code — `NamedArg` did not exist at HEAD, and the + `Connection` analog it is modelled on formats cleanly there. One + pre-existing bug fixed, one own-code gap caught and fixed inside the + round; the Assumptions section now states the split precisely. The earlier + entry above stands as written, per the append-don't-rewrite rule. +- **QA-2:** "no token this round targeted remains a first blocker" reworded + to "no *shape*" — `.` remains first in 2 files whose real blocker is + `foreach` over a hierarchical index; parked under Status/TODO with both + file:line cites. +- **QA-3:** the `$` row's next-blocker enumeration completed to all 13 + (adding `import` at `dv_base_reg_field.sv:97` and `` `TX_IGNORED_PERIOD`` + at `uart_scoreboard.sv:155`) and the phantom "lex error" removed — all 13 + are parse errors. +- **QA-4:** every header in `dynamic_types.cases` was off by one for cases + 1–32 (a 0- vs 1-indexed array slip in the generation script: case 1 had an + empty header, each later header described the case above it, case 32 had + none). Realigned all 32 and verified each header against its case's actual + content pair by pair, not by blind shifting; cases 33–34 were already + correct. `cargo test -p vlog_formatter` green after the edit + (`case_tables` still 431 cases), fmt clean. +- Also recorded QA-8's first-call-argument `[lo:hi]` dispatch asymmetry as a + parked item. No code changed in this pass — the four fixes are one test + data file and this README. + +## QA log + +### 2026-08-19 — QA + +**Setup.** Verified in the merged working tree (the concurrent one-parse round +is uncommitted here too; its files were attributed, not flagged — see +*Attribution* below). Baseline binary: the dev's HEAD worktree at +`scratchpad/head-wt`, provenance re-verified — `git rev-parse HEAD` = +`e9008b680c2df86c7bea6d29095250958c132306`, `git status --porcelain` empty, +`cargo build --release` a no-op (binary genuinely fresh at `e9008b6`, md5 +`feaa240d`). "New" binary: this tree's `target/release/vfmt` (md5 `957e2ad6`), +also confirmed up to date. `corpus/` never written to; all four corpus repos +`git status --porcelain` clean afterwards apart from the pre-existing +untracked `.vfmt-corpus-rev` stamps. + +**Claim-by-claim.** + +1. *All-structural; `verify.rs` / `fence.rs` untouched* — **PASS.** + `git diff --quiet` exits 0 for both, and md5 equality against + `git show HEAD:` confirms it independently + (`verify.rs` `18797ffb…`, `fence.rs` `b119bb8c…`). Nothing new is captured + verbatim, so hard invariant #4 does not bind. Verified anyway that the net + is load-bearing for every new shape — see *Sabotage* below. +2. *Corpus* — **PASS, reproduced end to end, every number.** + `./tools/corpus_check.sh corpus` (release, exit 0): **636/820 (77.6 %)** + formattable, 626 would-reformat, 10 ok-unchanged, **184 parse-error**, 0 + verification-error, 0 other-error, 0 crash. HEAD-binary baseline over the + same corpus: **578/820 (70.5 %)**, 242 parse-error. TSV md5 + **`e6f12eb7964e22e452655cf517cae766`** — exactly the README's value, and + byte-identical across **three** independent runs on this machine. + - **By path** (joined on the path column, all 820 rows matched): + `parse-error → would-reformat` **58**, `would-reformat → would-reformat` + **568**, `ok-unchanged → ok-unchanged` **10**, + `parse-error → parse-error` **184**, **any regression 0**. + - **Gained by tree**: `google_riscv-dv` 24, `lowrisc_ip` 14, + `opentitan/hw/ip` 8, `common_cells/test` 7, `ibex/dv/uvm` 4, `ibex/rtl` 1 + — every figure reproduces. + - **Per-target ledger**, recomputed from the two TSVs: `$` 41 baseline- + blocked → **28 format, 13 advance**; `]` 23 → **6 / 17**; `.` 21 → + **17 / 4**; `inside` 7 → **7 / 0**. All four match. + - **New histogram** reproduces exactly: `interface` 25, `` `else`` 13, + `` `uvm_field_int`` 11, `'` 7, `with` 7, `"DPI-C"` 7, `$error` 6, + `virtual` 4, `export` 4. + - **Round-trip of all 636**, not sampled: copied to a scratch directory, + `vfmt format` in place (0 failures), then `vfmt --check` (0 failures) — + every one a verified fixed point. + - **Stronger than asked: all 578 previously-formattable files were + compared byte-for-byte old-vs-new**, not a 20-file sample. + `differing = 0` over 578 files (stdout and exit code both compared). No + regression by path *or* by bytes. +3. *The two comment-drop fixes* — **PASS on substance, with a documentation + correction (QA-1).** + - Assignment operator: **genuinely pre-existing, zero new syntax.** + `module m;\n initial begin\n instr[6:0] /* opcode */ = OPCODE_JALR;\n + end\nendmodule` refuses on the HEAD binary (`token stream diverges … + input has comment "/* opcode */"`) and formats cleanly now. Same for the + non-blocking twin `a /* l */ <= /* r */ b;`, and for multi-comment and + line-comment variants (`q[6:0] /* p1 */ /* p2 */ = /* r1 */ /* r2 */ 5;`, + `n /* nl */ = // rl` ⏎ `6;`) — all clean, all idempotent. + - Named-argument `close_comments`: **not reproducible without new syntax.** + The `Connection` analog `sub u (.src(5'd0 /* x0 */));` already formats + cleanly on the HEAD binary. See finding QA-1. +4. *`bind.rs` three arms; `vlog_linter` untouched* — **PASS.** + `git diff crates/vlog_semantic/src/bind.rs` is exactly three arms: + `TimingControl::Event(SensList::Bare(e))`, the `bind_dims` `DimKind` match + (`Range` binds `a`/`b` as before, `Dynamic`/`Wildcard` bind nothing — + correct, they hold no expressions), and + `ExprKind::NamedArg { value, .. }`. Nothing else in the crate changed. + **Attribution:** `crates/vlog_linter/{src/context.rs,src/lib.rs,tests/rules.rs}`, + `crates/vfmt/src/lint.rs`, `crates/vfmt_server/{lint,state}.rs` are the + one-parse round's own file list (its README §Handshakes / §Work log), and + `crates/vfmt_server/src/diagnostics.rs` is the lead's QA-1 fix recorded in + that round's Review §4. `git diff crates/vlog_linter/` contains **no** + dynamic-types symbol (`DimKind`/`NamedArg`/`SensList`/`inside`/ + `op_comments`) — this feature really did not touch it. +5. *Gates* — **PASS.** `cargo test --workspace` **791 passed, 0 failed** + (re-run after all sabotage was reverted: still 791/0). + `cargo clippy --workspace --all-targets` **zero warnings** — re-run after + `touch`ing all four changed source files so it could not be a cache + replay. `cargo fmt -p vlog_parser -p vlog_formatter -p vlog_semantic -- + --check` clean, and `cargo fmt --all -- --check` clean too. The case table + holds **34** cases (33 `====` separators + 1). Seven new + `tests/verification.rs` tests (6 rejection + 1 acceptance) present and + green; the spans walker's `NamedArg` arm and both new `SOURCES` entries are + present and exercised — proven load-bearing by sabotage 5 below. + +**Attacks (release binary; every probe formatted, re-formatted and, where it +succeeded, re-parsed by the net's own equivalence + convergence check).** + +- *The `$` primary.* `q[$]`, `q[$-1]`, `q[$:2]`, `q[0:$]`, `[$:8]`, + `q[$][$][$]`, `{$, $}`, `[$]` behind three unpacked ranges — all format and + are idempotent. **Illegal positions are accepted and round-trip losslessly**: + `assign x = $;`, `x = $ + 1;`, `x = $$;`, `f($, $)`, `logic [$:0] w;` all + emit the same tokens back. That is consistent with the documented + Assumption ("vfmt does not check legality anywhere else either") and cannot + corrupt. **No identifier collision:** `int $;` is a parse error + (`expected identifier (found "$")`), so `$` cannot be declared. + `$display`/`$bits(int)`/`$error`/`$time`/`$finish` are byte-unaffected. +- *`DimKind`.* `[]`, `[*]`, `[8]`, `[7:0]`, `[string]` and the nested + combinations `[][$][7:0]`, `[$][*][]`, `[][][][][$][*][7:0]` in **every** + declaration position — module net, class property, class-function local, + `typedef`, function/task argument in every direction, module parameter port, + ANSI port, `localparam`. All format, all idempotent, HEAD parse-errors every + one of them. The spacing (`wire d [7:0];`) is **pre-existing house style**, + confirmed byte-identical old-vs-new on a plain `[7:0]`/`[3][4]` declaration. +- *`NamedArg`.* `f(.a(x), .b())`, `.a()` empty, named-in-`$display` + (`$display(.fmt("%d"), .v(x))`), scoped callees, and **mixed positional + + named in both orders** (`g(x, .b(y))`, `h(.a(x), y)`) all parse — SV forbids + the mix, vfmt accepts it and emits the same tokens, matching the documented + "vfmt is not a legality checker" stance. A nested `k(.a(.b(x)))` is a parse + error (refusal, safe). **Disambiguation holds:** `sub #(.W(8), .D()) u0 + (.clk(clk), .d(), .q(q));`, `sub u1 (.*);` and `sub u2 (.a(1), .b);` are + byte-identical old-vs-new — instantiation connections still take the + `Connection` path. Comment slots: see QA-6. +- *`case … inside`.* Range labels, mixed `[1:5], 7, [9:11]`, plain labels, + `default`, `casex … inside`, `unique case … inside`, + `priority casez … inside`, inside a class method, and a plain `case` with a + `[1:2]:` label (illegal SV, accepted, same tokens out) — all format and + re-parse. Head-trailing, item-leading, item-trailing and dangling comments + all survive in source order. `[1:2][3:4]:` is a parse error (safe). +- *`SensList::Bare`.* `@ev;` and `@hier.a.b;` format without parens; `@(ev)`, + `@(posedge clk)` and `@(*)` keep their own spellings; `x = @ev y;` + (intra-assignment) works. **The old refusal is real and is fixed:** on the + HEAD binary the whole probe file dies at `@hier.a.b`, and `@ev` alone was + the invented-parens refusal the work log describes. Noted in passing: + `always @* y = x;` still prints `@(*)` and is **accepted** — that is a + pre-existing `verify.rs` normalization, byte-identical on the HEAD binary, + untouched by this round. +- *`at_macro_item` ident-dot.* The `` `WAIT_FOR_RESET`` ⏎ `cov.cg.sample(a, b);` + shape formats (HEAD: `expected ';' (found ".")`). Counter-cases all keep + their old reading: `` `MY_TYPE x = 1;``, `` `MY_TYPE y;``, `` `M2 #(1) n;``. + The clause can only fire where HEAD had a parse error, and a wrong guess + emits the same tokens (`` `M3 z.w = 2;`` round-trips). +- *`parse_ident_item` bracket lookahead — the highest-risk edit, attacked + hardest.* `sub #(8) u [3:0] (.a(x), .b(y));`, `sub2 v [1:0] (.c(z));` and + `sub3 #(.W(4)) w [N-1:0] ();` are **byte-identical old-vs-new** — instance + arrays are untouched. **Comments between `]` and `(` do not fool the + lookahead** (`sub #(8) u [3:0] /* c */ (.a(x));` and the `// c` ⏎ `(...)` + variant are both byte-identical old-vs-new): the token vector holds no + comment tokens, so `scan_matching`'s "next token is `(`" test is safe. + `sub #(8) u [3:0];` and `item_t #(A, B) r[3:0];` move from parse-error to a + declaration — strict gains, same tokens out. The 578-file byte-identity run + is the empirical proof that nothing already parsing changed reading. +- *Empty `{}` and value ranges.* `{}`, `{{}}`, `{{}, {}}`, `'{}`, `{3{{}}}`, + `{} + 1`, `{[1:2]}`, `{3{[1:2]}}`, `y inside {[1:2], 3}` — all format and + are idempotent; nonsense in, same nonsense out. +- *Everything at once, three passes.* A 35-line file combining queues, bounded + queues, dynamic/wildcard/string/typed-key associative arrays, a + parameterized-type queue declarator, `$`-indexing, `new[n]`, `{}`, + assignment-operator comments on both sides, named args with `close_comments`, + `case … inside`, both bare event controls, the macro-then-`cov.` shape, and + an `` `ifndef``/`` `endif`` wrapper: **format(format(format(x))) == format(x)**, + and all six embedded comments present in the output. +- *Lint path over the new syntax.* `vfmt check` over the probe files runs + clean and `case-missing-default` correctly fires on `case … inside`. See + QA-7 for the corpus-wide `vfmt check` delta. + +**Sabotage (each applied, caught, reverted, and the revert proven by `cmp` +against a pre-sabotage byte copy).** + +1. `op_comments` not printed → `cases.rs` fails at `dynamic_types.cases:397` + with the net's own message (`input has comment "/* opcode */"`). +2. `close_comments` not printed → fails at `:414` + (`input has comment "/* x0 */"`). +3. `inside` not printed → fails at `:264` and `:285` + (`input has keyword "inside"`). +4. `DimKind::Dynamic` printed as `[*]` → fails at five separate cases + (`:81`, `:92`, `:101`, `:128`, `:139`). +5. `NamedArg::name_span` shifted one byte left → `spans.rs` + `every_node_span_nests_inside_its_parent` fails with *"the named argument + span does not slice back to its name", left: `".ptr"`* — the new walker arm + is genuinely load-bearing, not decorative. + +Every one is caught by the **runtime safety net** (equivalence/convergence +inside `format_source`), not merely by an expected-output mismatch — which is +the property that matters for invariants #1 and #3. After the last revert: +`format.rs` md5 `90530948…` and `parser.rs` md5 `37323362…` both equal their +pre-sabotage copies, and `cargo test --workspace` is back to **791 passed, 0 +failed**. + +**Findings.** + +- **QA-1 (LOW — documentation accuracy).** Assumptions says of the two comment + drops: *"Both reproduce on inputs with no new syntax in them."* Only the + first does. The second — a comment before a named argument's `)` — cannot + reproduce at HEAD, because `ExprKind::NamedArg` did not exist there; the + `Connection` analog it is modelled on (`sub u (.src(5'd0 /* x0 */));`) + formats **cleanly** on the HEAD binary (verified both binaries, identical + output, exit 0). Accurate framing: *one* pre-existing drop was fixed + (the assignment operator), and *one* gap in this round's own new code was + caught and fixed inside the round — which is good practice, just not the + same category. Worth correcting because invariant #3's history is exactly + what CLAUDE.md asks agents to keep honest. +- **QA-2 (LOW — documentation accuracy).** Corpus results claims *"No token + this round targeted remains a first blocker anywhere."* `.` remains the + first blocker in **2** files, both advanced from `]`: + `corpus/ibex/vendor/google_riscv-dv/src/riscv_callstack_gen.sv:183` + (`foreach(program_h[id].sub_program_id[k])`) and + `.../riscv_page_table_list.sv:130` (`foreach(page_table[i].pte[j])`). The + *shape* this round targeted (named call arguments) is indeed gone + everywhere; the token is not. Suggested wording: "no *shape* this round + targeted". +- **QA-3 (LOW — documentation accuracy).** The `$` row's next-blocker + enumeration ("`with` 3, one each: `assert`, `@`, `;`, `,`, `::`, + `` `else``, a covergroup cross, a lex error") accounts for 11 of the 13 + advanced files, and the "lex error" is not among them — all 13 are parse + errors. The full recomputed set is: `with` 3; and one each of `assert` + (`fifo_tb.sv:155`), `@` (`stream_register_tb.sv:75`), `;` + (`ibex_cosim_scoreboard.sv:307`), `,` + (`ibex_debug_triggers_overrides.sv:116`), `::` (`riscv_instr.sv:156`), + `cp_sign_cross` (`riscv_instr_cover_group.sv:514` — the covergroup cross), + `` `else`` (`riscv_instr_pkg.sv:1252`), **`import`** + (`dv_base_reg_field.sv:97`) and **`` `TX_IGNORED_PERIOD``** + (`uart_scoreboard.sv:155`). The last two are unlisted. +- **QA-4 (LOW — test hygiene, not fixed: outside this agent's write scope).** + Every case header in `crates/vlog_formatter/tests/cases/dynamic_types.cases` + is **off by one** for cases 1–32: case 1 carries an empty `# ` header, and + each subsequent `#` line describes the *previous* case (line 12 "queue-typed + class properties, with and without qualifiers" sits above the + function-locals case; line 264 "a named-argument list that does not fit + breaks one per line" sits above a `case … inside` case; and so on). Cases 33 + and 34 are labelled correctly, and case 32 (the `static`/`local` queue + properties) has no description at all. Harmless to behavior — the harness + ignores the text — but the labels are what a future failure prints, and + sabotage 3 above duly reported a `case … inside` failure under the + named-argument-list heading. Mechanical fix: shift headers 2–32 up one slot + and write one for case 32. +- **QA-5 (INFORMATIONAL — pre-existing, byte-identical on HEAD, out of + scope).** Two comment shapes adjacent to the fixed one still refuse, and + refuse *identically* on the HEAD binary, so this round neither caused nor + widened them: + - `assign a /* l */ = /* r */ b;` — a **continuous** assignment has + `rhs_comments` but no `op_comments`, so the operator-side comment is still + dropped and the net refuses. This is the exact twin of what landed on + `StmtKind::Assign`; worth naming because Assumptions describes the fix as + mirroring "a continuous assignment's `rhs_comments` use", which may read as + if the continuous form were already whole. + - `w <= #1 /* d */ 3;` and `v = @(posedge clk) /* e */ 4;` — `rhs_comments` + is taken immediately after the operator, *before* the intra-assignment + timing control is parsed, so a comment between the timing control and the + RHS is still lost and refused. +- **QA-6 (INFORMATIONAL — parity confirmed, not a new refusal class).** + `f(.a(/* in */ x))` (comment between `(` and the value) and + `f(.a /* mid */ (x))` (comment between the name and `(`) are refused by the + net — comments relocated across a token, never dropped from the output. + Both refuse **byte-identically** in the `Connection` form on the HEAD binary + (`sub u (.a(/* in */ x));`, `sub u (.a /* mid */ (x));`, same divergence + indices). So `NamedArg` inherits `Connection`'s comment behavior exactly, as + Handshakes promises — including its pre-existing limitation. The shapes that + *do* work in a connection also work in a named argument (`.a(x /* post */)`, + `.a(/* only */)`, `.a(x // line` ⏎ `)`). +- **QA-7 (INFORMATIONAL — cross-round note for the lead).** `vfmt check + corpus` differs from the HEAD binary by **10 lines, net +6 findings** (7921 + → 7927), entirely as a consequence of files that now parse: 7 new, correct + `case-missing-default` findings on `case … inside` statements, and at + `corpus/ibex/vendor/google_riscv-dv/src/isa/riscv_zbb_instr.sv` one + **spurious** old finding (`187:5: generate 'case' has no 'default'` — line + 187 is an `endcase`, i.e. an error-recovery artifact) replaced by three + correct ones (`26:5`, `140:5`, `195:9`). Strictly an improvement, and + Handshakes' "Required of `vlog_linter`: nothing" is correct *at the + compilation level*. Flagged only because the concurrent one-parse round + proved its lint output byte-identical against a tree that did not contain + this round: in the merged tree `vfmt check` output is no longer identical to + `e9008b6`'s, and those 10 lines are why. +- **QA-8 (INFORMATIONAL).** A `[lo:hi]` value range is accepted at every + expression-element position **except the first call argument**: + `f([1:2])` is a parse error while `f(x, [1:2])` parses, because the postfix + `(` branch's first-argument dispatch gained the `.` case but not the `[` + case. No legal SystemVerilog is affected (a value range is not a call + argument), and `case … inside` labels are unaffected — their list goes + through `parse_expr_item` at **every** position including the first, which + probes confirm (`[1:5]:` as the first label of the first item formats). + Noted so the asymmetry is not mistaken for a bug later. + +**Verdict: no BLOCKING findings.** No regression by path (0/820) and none by +bytes (578/578 previously-formattable files byte-identical old-vs-new); no +comment loss anywhere — every comment-adjacent shape either round-trips or is +refused by the untouched safety net, and five sabotages confirm the net, not +luck, is what holds invariants #1 and #3 for the new shapes; no `$` misparse — +`$` is a leaf that cannot collide with an identifier and emits the same token +wherever it stands. All five claims verified independently, including the +corpus TSV md5 `e6f12eb7964e22e452655cf517cae766` reproduced three times. The +findings above are four documentation/hygiene corrections and four notes; none +of them change the shipped behavior. + +## Review + +**2026-08-19 — lead. Verdict: accepted after one fix pass; commits +jointly with one-parse (round 19). Corpus 70.5% → 77.6% formattable — +the second-largest jump in the project — with everything structural +and nothing verbatim.** + +Points reviewed and accepted: + +1. **`$` as an expression primary** is the round's insight: one + grammar addition and queues, bounds, and `$`-arithmetic indexes all + fall out of machinery that already existed. QA attacked it at + illegal positions and found no identifier collision and lossless + round-trips. `DimKind` as the one non-additive AST change had + exactly three consumers, all updated — blast radius measured before + the cut. +2. **Fixing the newly-reachable comment drops instead of parking + them** — with the honest post-QA split: one was genuinely + pre-existing on HEAD, the other was this round's own new code + caught inside the round. The dated correction entry (rather than + rewriting the work log) is how the record should be amended. +3. **The QA-4 root cause** (a 0-vs-1-indexed array slip in a header + generation script) was traced, not patched around, and the + realignment verified against case *content* including the four + ambiguous `task t;` quartuplets. Tooling that generates test + artifacts is code too. +4. **By-path discipline throughout**: 58 gained / 0 lost / 0 category + changes, all 636 round-tripped, all 578 previously-formattable + files byte-compared old-vs-new with zero differences — the + regression bar at its strongest. +5. **QA-7's cross-round interaction recorded here**: this round's + `case inside` support correctly grew the lint corpus baseline by + net +6 (real case-missing-default findings in newly-parsing code, + plus a recovery-artifact swap for the better). one-parse's + byte-identity claim was measured before this round landed; both + claims are true at their respective tree states. + +Parked with evidence and cites: `foreach` over hierarchical indexes +(2 files), the `f([1:2])` first-argument dispatch asymmetry (no legal +SV affected), `randomize() with` (7 files, the constraint-verbatim +vehicle when taken), and the new top blockers — `interface` (25) and +the `` `else`` head-swap shape (13) — which are the next parse +frontier when wanted. diff --git a/docs/features/linter-core/README.md b/docs/features/linter-core/README.md index 2c5887d..b79b631 100644 --- a/docs/features/linter-core/README.md +++ b/docs/features/linter-core/README.md @@ -95,6 +95,10 @@ existed. tools" is **not** done; `check` and `format` each call the parser. Nothing in this crate's API prevents sharing a parse later — `LintContext` is the only thing that would need to accept a pre-built tree. + ~~is **not** done~~ **Delivered by one-parse (round 19): + `LintContext::from_parse` accepts pre-built products, `ParsedSource::parse` + is the parse-once bundle, and both `vfmt check` and the server lint from + one parse — see `docs/features/one-parse/README.md`.** ## Status / TODO @@ -125,7 +129,9 @@ existed. of scope this round; needs a file format, a discovery rule and a precedence story against inline waivers. - [ ] `lint` config key in `vfmt.toml` — handshake above. -- [ ] One parse shared by `check` and `format` — handshake above. +- [x] One parse shared by `check` and `format` — handshake above. + **Delivered by one-parse (round 19)** for the linter's consumers; + `format` keeps its own strict parse by design. - [ ] Naming rules by regex, `--generate_markdown` rule reference, `--explain` (`Rule::doc` exists so these can be generated, but nothing generates them yet). diff --git a/docs/features/one-parse/README.md b/docs/features/one-parse/README.md new file mode 100644 index 0000000..22342db --- /dev/null +++ b/docs/features/one-parse/README.md @@ -0,0 +1,515 @@ +# one-parse + +## Goal + +TODO §4's "one parse, two tools", delivered on the linter side: parse a file +once and lint from those products, instead of every consumer re-lexing and +re-parsing text somebody already parsed. `LintContext` gains a constructor +that accepts pre-built parse products; `vfmt check` builds the products once +per file; and `vfmt_server` — which already holds a fully analyzed `Document` +per buffer — lints from that document's own tokens and tree rather than +paying two extra lexes and an extra tolerant parse per keystroke. Behavior is +the hard gate: every finding, position, fix, diagnostic and exit code is +byte-identical to before; only duplicated work is removed. + +## Assumptions + +- **Behavior identity over speed.** Anywhere "share the parse" and "identical + output" could conflict, identity wins. Concretely: on a file that fails to + *lex*, the shared-parse paths fall back to `parse_source_tolerant` (which + re-lexes the rare broken file once more) rather than hand-rolling the + lex-error tree, so the tree and diagnostics are the old code path's own. +- **The token stream and the tree are two products, and the parser consumes + its tokens.** `parse_tolerant(tokens, source)` takes `Vec` by value, + so a consumer that needs both (the linter does: waivers and text rules read + tokens, AST rules read the tree) clones the token vector once. One clone is + cheaper than the lex it replaces, and changing `vlog_parser`'s signature is + out of scope (that crate is another round's). +- **`SourceFile` is not `Clone`.** This is what forces the borrowing design + below: the server's `Document` owns one tree that must serve semantics, + diagnostics *and* linting, so the lint context has to borrow it — + `std::borrow::Cow` cannot hold a non-`Clone` type, and a per-request tree + clone is exactly the duplicated work this round removes. +- **Parse diagnostics are not a lint product.** No rule reads them + (`LintContext::new` always discarded them), so `from_parse` does not take + them and `ParsedSource` does not store them. The server, which does publish + them, keeps them where they always were: on `Document`. +- **The `--fix` loop's per-round re-parse is inherent.** Each round rewrites + the text, and products of the old text describe nothing. Only the *first* + round of `vfmt check --fix` (and all of a plain `vfmt check`) saves work. +- **Per-change recompute stays the server's model.** This round removes + duplicate work *within* one change/request; it adds no caching or + invalidation machinery beyond what `Document` already is (TODO §6: + "per-file recompute is fine at Verilog file sizes"). + +## Handshakes + +**Promised by `vlog_linter`** (additive; everything previously public is +unchanged in behavior): + +- `LintContext` is now `LintContext<'a>`. Rule authors are untouched: the + `Rule::check(&self, ctx: &LintContext)` signature, and every accessor + (`source()`, `tokens()`, `file()`, `line_index()`, ...), read exactly as + before — the lifetime elides. +- `pub fn LintContext::from_parse(source: &'a str, tokens: &'a [Token], + file: &'a SourceFile, line_index: &'a LineIndex, path: Option) + -> LintContext<'a>` — the pre-built-products constructor linter-core's + Handshakes predicted. Borrows everything big; `path` stays owned because a + `PathBuf` clone per lint run is noise. **Caller contract (documented at the + item): the four products must describe the same text** — tokens lexed from + `source`, `file` the tolerant parse of those tokens, `line_index` built + over `source`. `Document` and `ParsedSource` both satisfy it by + construction. +- `pub struct ParsedSource` + `ParsedSource::parse(source) -> ParsedSource` + + `ParsedSource::context(&self, path) -> LintContext<'_>` — the owned bundle + of products for callers with no `Document` of their own (`vfmt check`, and + `run`/`LintContext::new` internally). `parse` lexes **once** and builds the + tree from a clone of the token stream. +- `LintContext::new(source, path)` **stays**, as the convenience wrapper the + task requires: it is one line, `Backing::Owned(ParsedSource::parse(source))` + through the same private assembly `from_parse` uses — a single code path + derives the string-literal spans and defaults. (`new` cannot literally call + `from_parse` and then own the products — that would be a self-borrow — so + "single code path" is the shared assembly function, and `ParsedSource::parse` + is the single place the parse recipe lives.) +- Dependency list unchanged: `vlog_parser` + std. + +**Consumed** + +- `vlog_parser::parse_tolerant(tokens, source)` — newly consumed by + `vlog_linter` and `vfmt_server` (both already depended on the crate; it was + already `pub`). Relied on: with the same tokens it returns exactly the tree + `parse_source_tolerant(source)` would (that function *is* `tokenize` + + `parse_tolerant`), and on a well-formed file the tree equals `parse`'s. +- `vlog_formatter::fence::protected_regions(&str)` — still called with text, + still re-parses internally, **on purpose**; see the decision below. + +**Changed call sites** + +- `crates/vfmt/src/lint.rs::run_rules` — parses once via `ParsedSource` and + hands the products to the context. +- `crates/vfmt_server/src/state.rs::Document` — gains the `tree: SourceFile` + field (it was parsed and thrown away after `analyze`), and `Document::new` + lexes once instead of twice. +- `crates/vfmt_server/src/lint.rs::{violations, fixable}` — the one call site + server-lint's README predicted: both lint from the document's own products + via `from_parse` instead of re-parsing `doc.text`. + +## The server's redundant-work catalog + +Every place the server re-tokenized or re-parsed text it already held +products for, per request, as of the start of this round: + +| Site | Duplicate work per request | Verdict | +|---|---|---| +| `lint::violations` (every didOpen/didChange/didSave publish) | 2 lexes + 1 tolerant parse of `doc.text` (via `vlog_linter::run` → `LintContext::new`) | **Eliminated** — `from_parse` over `Document`'s products | +| `lint::fixable` (every codeAction request) | 2 lexes + 1 tolerant parse (via `LintContext::new`) | **Eliminated** — same | +| `lint::fixable` → `fence::protected_regions(&doc.text)` | 1 lex + 1 tolerant parse inside `vlog_formatter` | **Kept** — see the protected_regions decision below | +| `Document::new` (every buffer change) | the text lexed twice: `tokenize` for `doc.tokens`, then `parse_source_tolerant`'s internal `tokenize` | **Eliminated** — one lex, tree built by `parse_tolerant` over a clone of the tokens; the lex-error fallback still goes through `parse_source_tolerant` so the error tree and diagnostic are byte-identical | +| `format::formatting` / `range_formatting` | `format_source`/`format_range` lex+parse strictly inside `vlog_formatter` | **Kept** — the formatter's parse is the *strict* one (a tree `Document` does not hold), and the runtime safety net (equivalence + convergence) is defined over `format_source` doing its own work; sharing would need `vlog_formatter` API changes, which is the concurrent round's crate and a different feature | +| `Workspace::rebuild_index` (initialize + every didSave) | re-reads and re-parses every workspace file inside `WorkspaceIndex::build`, open unchanged buffers included | **Kept** — the documented full-scan index model (TODO §6 defers incrementality to salsa); making it incremental is invalidation machinery this round explicitly must not build | +| `semanticTokens`, `hover`, `definition`, `references`, `documentSymbol`, `workspace/symbol`, `diagnostics::diagnostics` | none — all already read `doc.tokens` / `doc.semantics` / `doc.defines` / `doc.diagnostics` | already clean (verified by grep for `tokenize`/`parse` over `crates/vfmt_server/src`) | + +## The protected_regions decision: left alone + +`fence::protected_regions` takes `&str` and re-parses internally. +shared-fence-filter's Assumptions choose that signature deliberately: a +products-accepting variant would let the two front ends feed different trees +and get different fence answers, which is the exact drift that feature exists +to end. Could this round argue both callers "always hold the same tree by +construction"? Almost — the server would pass `doc.tree` and the CLI its +current round's tree — but "almost" is the problem: the CLI's `--fix` loop +rebuilds text every round, and a future caller passing last round's tree is +precisely the bug the `&str` signature makes unwritable. The cost lands only +on fix-application paths (`vfmt check --fix`, `textDocument/codeAction`), +never on the per-keystroke diagnostics path. Two further reasons to leave +it: it is `vlog_formatter`'s code, which belongs to the concurrent +dynamic-types round this session; and the interior parse is of the *current* +text by construction, which is the property being bought. **Decision: keep +the double parse there, documented as the acceptable price of one fence +answer.** + +## Status / TODO + +- [x] `vlog_linter`: `LintContext<'a>`, `from_parse`, `ParsedSource`, + `new` kept as the wrapper; single-lex parse recipe in one place. +- [x] Rules, visitors, waivers untouched (they compile and read unchanged). +- [x] `crates/vfmt/src/lint.rs`: `run_rules` parses once via `ParsedSource`. +- [x] `crates/vfmt_server`: `Document.tree` kept; `Document::new` single-lex; + `lint::violations`/`fixable` lint from the document's products. +- [x] Server catalog above; semanticTokens/hover verified already clean. +- [x] protected_regions decision written (left alone). +- [x] Tests: products-in == source-in property over rule-test inputs; + lex-error and broken-file paths; existing CLI + server suites green + **unmodified**. +- [x] Byte-identity: corpus `vfmt check` (text + JSON) vs a HEAD worktree + binary; server diagnostics vs a HEAD worktree binary over a real stdio + session. +- [x] Timing before/after. +- [x] TODO §4 checkbox + linter-core / server-lint annotation lines. +- [ ] **Not done, deliberately:** `vfmt format` sharing the parse. The + formatter requires a *strict* parse and runs its safety net over its own + products; wiring `vfmt check --fix --format` workflows is a future + feature and is not blocked by anything here. +- [ ] **Not done, deliberately:** any caching/invalidation in the server + beyond `Document`'s per-change recompute. + +## Work log + +### 2026-08-19 — dev + +- Read `CLAUDE.md`, TODO §4, and the linter-core / server-lint / + shared-fence-filter READMEs in full (QA logs and Reviews included) before + writing anything, then the code: `vlog_linter`'s `context.rs`/`lib.rs`, + `crates/vfmt/src/lint.rs`, and every file in `crates/vfmt_server/src`. +- **The design was forced by one fact: `SourceFile` is not `Clone`.** The + server's `Document` owns one tree that must serve semantics, published + diagnostics *and* linting, so the products constructor has to borrow — + and the task's requirement that `LintContext::new(source, path)` survive + as a self-contained convenience means the context must also be able to + own. Hence the private `Backing` enum (`Owned(ParsedSource)` / + `Borrowed { .. }`) rather than `Cow` fields (`Cow` needs `Clone`) or a + lifetime-only struct (which would have killed `new`). Every accessor + signature is unchanged, so the twelve rule files, `visit.rs` and + `waiver.rs` compile byte-for-byte untouched — verified by `git diff` + (only `context.rs`, `lib.rs`'s one `pub use` line, and the test helper + changed in the crate). +- **`new` cannot literally call `from_parse`** — that would borrow a local + and return it — so the single code path is `assemble` (one place derives + string-literal spans and defaults) plus `ParsedSource::parse` (one place + holds the parse recipe). Recorded here so nobody "fixes" it into a + self-borrow later. +- **The single-lex recipe and its one deliberate exception.** Today's + `LintContext::new` lexed the text twice (its own `tokenize`, then + `parse_source_tolerant`'s internal one). `ParsedSource::parse` and + `Document::new` now lex once and build the tree via + `parse_tolerant(tokens.clone(), source)` — identical tree by definition, + since `parse_source_tolerant` *is* `tokenize` + `parse_tolerant`. A text + that fails to lex keeps the old `parse_source_tolerant` path (a second lex + of a rare broken file) because `parser::error_file` is `pub(crate)` and + hand-rolling the all-error tree here is how two subtly different trees + are born. The recipe exists in exactly two places because they need + different outputs: `ParsedSource` discards diagnostics (no rule reads + them), `Document` publishes them. +- Server: `Document` gained the `tree: SourceFile` field it was already + paying to build (it parsed, analyzed, and threw the tree away); + `lint::violations` and `lint::fixable` now share a four-line `context(doc)` + helper over `from_parse`. `vlog_linter::run` is no longer imported there. + The catalog above was compiled by grepping `tokenize|parse` over + `crates/vfmt_server/src` and reading each hit. +- **Tests.** The products-in == source-in property was put where it covers + the most ground: inside the rule-test harness's `assert_lint_with`, so all + 55 inline-marker cases (every rule × fires/quiet/waived/unused-waiver, + plus the fence and class-body cases) assert that `ParsedSource` products + produce a `Debug`-identical violation list — rule, message, span and fix. + Two new unit tests in `context.rs`: borrowed-vs-owned accessor equality, + and the lex-error fallback producing the exact old error tree. Existing + CLI and server suites pass **unmodified** (`git diff` on + `crates/vfmt/tests`, `crates/vfmt_server` tests: empty). +- Did not touch `vlog_parser`, `vlog_formatter`, `vlog_semantic`, + `vfmt_core`, `editors/**`, or any `Cargo.toml`/`Cargo.lock` (no dependency + moved; `parse_tolerant` was already `pub`). Did not run + `git commit`/`git push`. +- **Concurrency note.** A dynamic-types round was announced live in + `vlog_parser`/`vlog_formatter` this session. `git status` stayed clean of + their crates for the whole round (only this feature's files are modified), + so the scratchpad-copy fallback was prepared but never needed; the HEAD + worktree used for baselines doubles as the clean snapshot. Gates below are + from the real tree. + +**Results.** + +- `cargo test -p vlog_linter`: 118 unit + 55 integration + 1 doctest, green + (118 was 116: the two new `context.rs` tests). `cargo test -p vfmt`: + green including all 69 CLI integration tests, unmodified. + `cargo test -p vfmt_server`: 115 unit + 6 e2e, green, unmodified. + `cargo test --workspace`: **770 passed, 0 failed**. +- `cargo clippy --workspace --all-targets`: silent. `cargo fmt -p + vlog_linter -p vfmt -p vfmt_server -- --check`: clean (scoped, per the + concurrency rule). No `#[allow]`, no `unwrap`/`expect`/`panic!`/`unsafe` + outside `#[cfg(test)]` in anything touched. +- **Byte-identity, CLI** (HEAD worktree binary at `e9008b6` vs this tree, + both release): + - `vfmt check corpus/`: stdout, stderr and exit code (1) identical. + - `vfmt check corpus/ --output-format json`: **2 418 071 bytes of JSON, + byte-identical**, stderr identical, exit identical. + - `check --fix` over ten crafted shapes in twin directories (tabs + + trailing whitespace, fence, fence-in-broken-file, waiver, lex failure, + case-missing-default, module-filename mismatch, multi-byte + tab, + unclosed fence, empty file): every rewritten file byte-identical, + stdout/stderr identical (paths normalized), exit 1 from both. +- **Byte-identity, server**: a real stdio session (hand-framed JSON-RPC, + `scratchpad/lsp_probe.py`) over three scratch files — lint-only, parse + error + lint + module-filename, and error-recovery + fence + lex-error — + each opened and then edited once (edits flip the filename rule, add a + waiver, and heal the lex error). All **6 published diagnostic lists + byte-identical** between the two binaries, canonicalized only by + stripping the differing scratch-dir prefix from the URI. +- **Timing, CLI** (release, median of 7, 860-file corpus): + `vfmt check corpus/` **265.5 → 207.9 ms** at `--threads 1` (−22 %), + **79.7 → 70.5 ms** at the default thread count (−12 %). The single-thread + number is the honest one (the pool hides latency); the saving matches the + arithmetic — the lint pipeline did 2 lexes + 1 parse per file and now does + 1 lex + 1 token-clone + 1 parse. +- **Timing, server** (informational): didChange → publishDiagnostics, + median of 15 full-text changes, empty workspace root: + `picorv32.v` (3049 lines) **18.0 → 11.0 ms**, `ibex_core.sv` (2026 lines) + **7.6 → 3.4 ms**. Larger than the CLI's relative win because the server + was paying the duplicate work twice over — `Document::new`'s double lex + *and* the lint path's full re-lex-and-parse — and now pays one lex, one + clone, one parse per change. + +### 2026-08-19 — dev (post-interruption verification) + +- The session was cut by a usage limit after the results above were captured; + on resume, disk state was re-verified intact (all six code files, this + README, TODO §4, both annotation files — nothing lost). +- Mid-resume the concurrent dynamic-types round landed in-progress edits to + `vlog_parser`/`vlog_formatter`/`vlog_semantic` that briefly broke the + workspace *test* build (`tests/spans.rs` vs their new `ExprKind::NamedArg` + — their crate, their fix). Gates were therefore re-run with the + scratchpad-copy technique: a fresh worktree at HEAD `e9008b6` with **only + this round's six files** overlaid — `cargo test --workspace` **770 passed, + 0 failed**, `cargo clippy --workspace --all-targets` **silent**, scoped + `cargo fmt -- --check` **clean**. Identical numbers to the pre-drift + merged run recorded above. +- The merged tree recovered while this was running (the other agent fixed + their spans test): merged `cargo test --workspace` **770 passed, 0 + failed**, clippy clean, as of this writing — noted with the caveat that + their round is still in motion, so the isolated-copy numbers are this + feature's own evidence. +- Provenance of the identity/timing evidence above: captured **before** any + concurrent drift existed — at capture time `git status` showed only this + round's files modified, so the "new" binaries were exactly HEAD + + one-parse, vs. the HEAD-worktree baseline binaries. That evidence stands + as recorded. + +## QA log + +### 2026-08-19 — QA + +**Setup / isolation.** The concurrent dynamic-types round had by now modified +`vlog_parser/src/{ast,parser}.rs`, `vlog_parser/tests/spans.rs`, +`vlog_formatter/src/format.rs`, `vlog_formatter/tests/verification.rs` and +`vlog_semantic/src/bind.rs` in the shared tree, so every gate and every +identity run below was done in an **isolated copy**: `scratchpad/qa-new` = +a byte copy of the dev's HEAD worktree (`scratchpad/head-wt`, verified clean +at `e9008b6`) with **exactly this round's six code files** overlaid. +`diff -rq head-wt qa-new` reports those six files and nothing else. The +baseline binaries are `head-wt/target/release/{vfmt,vfmt-server}`; the "new" +ones were rebuilt from `qa-new`. `corpus/` was never written to — the `--fix` +runs used copies. + +**Claim-by-claim.** + +1. *Constructor design* — **PASS.** `SourceFile` is `#[derive(Debug)]` only at + `e9008b6:crates/vlog_parser/src/ast.rs:125`, so `Cow` is genuinely + unavailable and the `Backing` enum is forced. `git diff --name-only HEAD -- + crates/vlog_linter` returns exactly `src/context.rs`, `src/lib.rs`, + `tests/rules.rs` — all twelve rule files, `visit.rs`, `waiver.rs`, + `registry.rs`, `naming.rs`, `violation.rs`, `rule_docs.rs` byte-untouched. + `crates/vlog_linter/Cargo.toml` still lists `vlog_parser` and nothing else. + Diagnostics genuinely unread by any rule: `grep -rn diagnostic + crates/vlog_linter/src` hits only doc comments, the discarded binding at + `context.rs:46`, and `visit.rs`'s own `#[cfg(test)]` block. `new` → + `assemble` is the single path, and `parse_source_tolerant`'s Ok arm at + `e9008b6:crates/vlog_parser/src/lib.rs:37` is literally + `parse_tolerant(tokens, source)`, so the substitution is exact by + definition, not by hope. +2. *`ParsedSource::parse` lexes once; lex errors fall back* — **PASS.** + Independent probe (scratch `tests/qa_probe.rs`, deleted after the run) over + four lex-failing texts — unterminated block comment, unterminated string, + a bare `"`, a `/*` at EOF: tokens empty in every case, the `Debug` form of + `ParsedSource::parse(src).context(None).file()` equal to + `parse_source_tolerant(src).0`, and `run(src, …)` equal to + `lint(&parsed.context(None), …)`. End to end the same fallback shows up in + the server session below (`f1 v4 lex error` publishes + `unterminated block comment` + `no-tabs`, identical on both binaries). +3. *Server catalog complete* — **PASS.** `grep -rn + 'tokenize|parse_source_tolerant|parse_tolerant|format_source|format_range| + rebuild_index' crates/vfmt_server/src` returns exactly the sites the + catalog names: `state.rs:56-61` (`Document::new`, one lex), + `format.rs:57,87` (kept, strict parse), `state.rs:123/137` + + `server.rs:251` (`rebuild_index`, kept), `lint.rs:54` + (`protected_regions`, kept). The only other `vlog_linter::run` left in the + crate is at `code_action.rs:157`, inside `#[cfg(test)]` — not a per-request + parse. **No uncataloged redundant parse survives.** `doc.tree` is read (not + dead): `lint.rs`'s `context(doc)` and `state.rs:64`'s `analyze(&tree, …)`. +4. *`protected_regions` left alone* — **PASS.** + `git diff --name-only -- crates/vlog_formatter/src/fence.rs` is empty; the + file is untouched by this round (and by the concurrent one). +5. *Behavior identity* — **PASS, re-run from scratch, not taken on trust.** + - `vfmt check corpus/` (820 files): stdout **692 198 bytes identical**, + stderr identical, exit 1 both. + - `--output-format json`: **2 418 071 bytes identical** (matches the dev's + figure exactly), stderr identical, exit 1 both. + - Flag matrix on a 13-file crafted directory, stdout+stderr+exit compared + each time: `--select`, `--ignore`, `--select a,b --output-format json`, + `--indent 4`, `--threads 1`, an unknown rule name (exit 2 both), a + missing file (exit 2 both), `--unsafe-fixes`, a single file, an empty + file, `check - --stdin-filename`, and `--select + case-missing-default,module-filename` over the whole corpus. **12/12 + identical.** + - `check --fix` over 13 crafted shapes (multi-round tab+trailing, a real + `// verilog_format: off/on` fence, the `// vfmt: off/on` alias, an + unclosed fence, `// vfmt: waive`, unused + malformed + unknown-rule + waivers, a lex-error file, a filename mismatch, CRLF, multi-byte + + emoji + tab, an empty file, a class body, a parse-error file): every + rewritten file byte-identical, stdout (path-normalized) and stderr + identical, exit 1 both. Fenced regions provably untouched — the tab and + the trailing run inside the fence survive byte-for-byte while the + violations are still *reported*. + - **`check --fix` over a full copy of `corpus/` (820 files, 48 rewritten): + every file byte-identical old-vs-new**, stdout (309 lines) and stderr + identical, exit 1 both. This is a much wider `--fix` net than the ten + shapes in the work log and it holds. + - Server: an independent hand-written stdio driver (`scratchpad/qa_lsp.py`, + not the dev's) over 3 scratch files and **13 publishes** — + parseable → parse-error → clean → lex-error → healed → empty → back; + a filename-rule flip; a fence + error-recovery file losing its fence then + being fixed. All 13 diagnostic lists **byte-identical** between the two + binaries after stripping the scratch-dir prefix. + - Server, `fixable`/codeAction (the other `from_parse` call site, which the + work log did not exercise): `textDocument/codeAction` over the whole + buffer for 6 shapes (plain, fenced, waived, parse-error, lex-error, + multi-byte) — **16 379 bytes of diagnostics + actions, identical**, + including the fence filter correctly withholding quick fixes. +6. *Timing direction* — **PASS.** Release, median of 9, 820-file corpus, warm + cache: `--threads 1` **294.7 → 235.3 ms (−20.2 %)**; default threads + **98.6 → 87.2 ms (−11.6 %)**. Absolute numbers run ~10 % above the dev's on + this machine's load, the *direction and magnitude* reproduce. Server + didChange → publishDiagnostics, median of 15 full-text changes: + `picorv32.v` (3049 lines) **20.1 → 12.6 ms**, `ibex_core.sv` (2026 lines) + **8.2 → 3.7 ms** (informational; dev reported 18.0 → 11.0 and 7.6 → 3.4). +7. *Gates* — **PASS.** In the isolated tree: `cargo test --workspace` + **770 passed, 0 failed** (27 result lines; vlog_linter 118 unit + 55 + integration + 1 doctest, vfmt 30 unit + 69 CLI, vfmt_server 115 unit + 6 + e2e — every count the work log claims). `cargo clippy --workspace + --all-targets` exit 0, **zero warnings**. `cargo fmt --all -- --check` + clean (not just the scoped set). In the *merged* tree the scoped crates are + also green (`cargo test -p vlog_linter -p vfmt -p vfmt_server`: 30/69/115/ + 6/118/55/1) with scoped clippy and fmt clean. Test churn is zero: + `git diff --numstat crates/vlog_linter/tests/rules.rs` is **12 added, 0 + removed**, and no other test file in `vfmt`/`vfmt_server`/`vlog_linter` is + touched. No `unwrap`/`expect`/`panic!`/`unsafe`/`#[allow]` outside + `#[cfg(test)]` in any of the six files. + +**Attacks.** + +- *Borrowed vs Owned, beyond the shipped property test.* 14 inputs (plain, + tabs+trailing, fence, waiver, unused waiver, class body, parse-error, two + lex-error shapes, CRLF, CJK+emoji+combining, empty, whitespace-only, + case-without-default) × 3 path values (none, matching, mismatching) × 4 + construction routes (`LintContext::new`, `ParsedSource::context`, a + hand-built `from_parse` with independently produced products, and `run`). + All `Debug`-identical violation lists — rule, message, span, fix, + applicability — plus equal `source()`, `tokens().len()`, `Debug` of + `file()`, and `comments().len()`. **No divergence.** +- *The four-products contract, violated on purpose.* Five mismatch shapes + (tree of B over text A, tokens of B over text A, line index of B over text + A, everything-but-the-text from B, and short products over long text), with + A deliberately 14 bytes and B 111. Result: **no panic, no abort, no + unsoundness** — the crate contains no `unsafe`, so it cannot be otherwise. + The cost is exactly *wrong findings*: `module-filename` reported a module + name that is not in the text, and its **reported span (7..33) pointed past + the end of a 14-byte buffer**. Corruption is nonetheless impossible even + then: `apply_fixes` (`crates/vlog_linter/src/violation.rs:118`) already + skips any edit with `end > source.len()` or a non-char-boundary start, and + all five shapes applied cleanly with in-bounds output. See finding QA-2 for + the one thing the README should add. +- *The `--fix` loop.* Multi-round convergence survives the parse-once first + round: `\twire a;\t\n` converges to ` wire a;\n` (tab expanded in one + round, the trailing run removed in a later one), and a second `--fix` + invocation over the already-fixed directory is a **no-op** (`diff -rq` + clean), i.e. the loop still terminates at a fixed point. Fenced fixes are + still refused, for both fence spellings and for an unclosed fence. +- *Server, stale-tree.* The `parseable → broken → parseable` cycle tracks + correctly: the parse diagnostic appears at v2 and is **gone** at v3, the lex + diagnostic appears at v4 and is gone at v5, `module-filename` clears the + moment the module is renamed, a waiver added at v3 clears the lint. Nothing + from an older version leaks into a newer publish. `Document` is rebuilt + whole per change (`Workspace::set_document` → `Document::new`), so there is + no reuse point to go stale. +- *Sabotage.* Made `Workspace::set_document` keep the previous version's tree + (`doc.tree = old.tree`) while everything else refreshed — the exact bug this + round newly makes possible. It **is** a real, user-visible bug: the stdio + session immediately diverges (a stale `module-filename` warning for the old + module name survives the rename and persists into the next version). But see + finding QA-1. Sabotage reverted; `diff` against the working tree's + `state.rs` clean, and a rebuilt server reproduces the baseline 13-publish + log byte-for-byte. The scratch `qa_probe.rs` was deleted; `diff -rq head-wt + qa-new` is back to exactly the six feature files. + +**Findings.** + +- **QA-1 (MEDIUM — missing coverage, not a defect in shipped behavior).** + The stale-tree bug that this round newly makes possible is caught by **no + test in the workspace**. With the sabotage above in place, `cargo test -p + vfmt_server` passes **115 unit + 6 e2e, 0 failed**, and `cargo test + --workspace` passes **773, 0 failed** (770 + 3 scratch probes). Only a live + stdio session caught it. `Document.tree` is now a cached derivation of + `Document.text`, and nothing asserts they agree. The cheapest guard is one + `#[cfg(test)]` case in `crates/vfmt_server/src/lint.rs` or `state.rs`: + `set_document` a buffer whose module name mismatches the filename, then + `set_document` the renamed text, and assert `violations` no longer contains + `module-filename` — an AST-rule finding, which is exactly the class that + reads `doc.tree`. Reported rather than fixed: writing a new test into + another feature's crate is the dev's call, not QA's. +- **QA-2 (LOW — documentation).** `from_parse`'s caller contract says what the + caller must supply but not what breaking it costs. The measured answer is + worth one sentence at the item and in Assumptions: *violating it yields + wrong findings and spans that may point outside the text; it is never + unsound (no `unsafe`) and never corrupts a file, because `apply_fixes` + independently bounds-checks every edit.* Left for the dev to word, since + Assumptions is theirs. +- **QA-3 (INFORMATIONAL).** `LintContext::new` is declared inside `impl<'a> + LintContext<'a>` but returns `LintContext<'static>`, so its `'a` is unused. + Compiles, clippy-clean, callers unaffected; noted only so a later reader + does not mistake it for an accident. +- **QA-4 (INFORMATIONAL, pre-existing, out of scope).** On CRLF input, + `no-trailing-whitespace` does not fix the run before `\r\n` (observed on a + crafted `crlf.sv`: `wire a; \r\n` survives `--fix`). Byte-identical on + both binaries, so it predates this round entirely — recorded here only + because the CRLF shape was part of the identity matrix and someone will + otherwise re-find it. + +**Verdict: no BLOCKING findings.** No behavior divergence old-vs-new was found +anywhere — 820-file corpus check (text and JSON), 820-file corpus `--fix`, a +12-case flag matrix, 13 crafted `--fix` shapes, 13 server publishes and 6 +codeAction rounds all byte-identical. No stale-tree reuse in the shipped code. +No memory unsafety is reachable, by construction. The one thing this round +leaves behind is an untested invariant (QA-1), not a broken one. + +## Review + +**2026-08-19 — lead. Verdict: accepted; commits with round 19. The +duplicated-parse debt is paid: check is 20% faster single-threaded and +the editor's per-keystroke latency roughly halved, with behavior +identity proven at the byte level.** + +Points reviewed and accepted: + +1. **The Backing enum was forced, not chosen** — SourceFile is !Clone, + so borrowing was the only non-duplicating shape, and QA verified the + constraint at the type level. Keeping `new()` as a one-line wrapper + through the same private assemble is what kept all 12 rule files + byte-untouched: an API migration with zero consumer churn. +2. **The four-products contract was violated on purpose and the cost + measured**: wrong findings, possibly out-of-text spans, never + unsoundness, never a bad write (apply_fixes independently rejects + out-of-range edits). That measured answer is now in the doc comment + (lead fix, QA-2). +3. **The server catalog is complete** — QA's grep found no uncataloged + redundant parse, and the kept-with-reasons list (protected_regions' + anti-drift signature, the strict format parse, the documented + rebuild-on-save index) shows restraint where restraint was correct. +4. **QA-1 closed by lead fix**: the sabotage that kept a stale tree + passed all 773 tests — nothing pinned text/tree agreement. The new + `set_document_rebuilds_the_tree_so_diagnostics_track_the_text` + guard in diagnostics.rs fails on exactly that sabotage (premise + asserted through the merged all() path, where the stale lint + warning actually lives — the first draft checked the parse-only + path and was corrected before landing). +5. QA-3 (the unused 'a on new()) stands as a noted quirk; QA-4 (CRLF + trailing-whitespace fix gap) is pre-existing and joins the linter's + known-gaps list. diff --git a/docs/features/server-lint/README.md b/docs/features/server-lint/README.md index 89dba5f..c4b1296 100644 --- a/docs/features/server-lint/README.md +++ b/docs/features/server-lint/README.md @@ -47,6 +47,9 @@ this is protocol-layer wiring, which is all `vfmt_server` is allowed to be. already redoes per keystroke by design (TODO §6, "per-file recompute is fine at Verilog file sizes"). When the shared-parse work lands, exactly one call site here changes. + ~~parsed twice per change~~ **Delivered by one-parse (round 19): `lint.rs` + now lints from the `Document`'s own products via `LintContext::from_parse` + — see `docs/features/one-parse/README.md`.** - **Only Safe fixes are ever offered.** `--unsafe-fixes` is a flag a CLI user types on purpose; a lightbulb is not that, and a fix that can change what the circuit does must not be one click away. No rule ships an Unsafe fix today, so @@ -137,6 +140,8 @@ user setting, not an extension one. caller with a reason to want `LintContext` to accept a pre-built `SourceFile`. Nothing here blocks on it; when it lands, `lint.rs` is the one file that changes. + **Delivered by one-parse (round 19) — `lint.rs` was indeed the one file + (plus `Document` gaining its `tree` field).** 2. *linter-core / config-discovery*: **a `lint` key in `vfmt.toml`.** The server runs `default_rules()` and nothing else, because there is no configured rule set to read — `--select`/`--ignore` are CLI-only. When `lint = [...]` lands, @@ -224,7 +229,8 @@ TODO §2 `--lines`), `completion`, `rename`, `signatureHelp`, and cross-file not.~~ Delivered by **shared-fence-filter** (round 14). - [ ] **Not done:** `codeAction/resolve`. Every action is cheap to build in full; lazy resolution is a payload optimization for actions that are not. -- [ ] **Not done:** sharing one parse with the linter (Handshake 1). +- [x] ~~**Not done:** sharing one parse with the linter (Handshake 1).~~ + Delivered by **one-parse** (round 19). ## Work log