From a0c290ccc20a6529dd545f67b54f528519c86bde Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Wed, 2 Sep 2026 11:32:16 -0700 Subject: [PATCH] Comment slots in shared machinery: an owner for every gap, four fuzzers at zero, and the small-correctness residue TODO section 25; closes docs/topo.md 2.9-20, 2.9-21, 2.9-22; opens 2.9-23. A comment written where no AST node had a field was never deleted: bump queued it and take_meta handed it to the next node, so it printed one node later and verify.rs refused the whole file. About seventy named comment fields now own those gaps - SegmentComments on member/scope/ index/range segments (one parse_postfix_segment replacing three hand-copied loops), one [a:b] grammar, BinaryComments on inside, casts, unary/postfix, if/case/for/foreach/do-while headers, @ and # timing, Stmt::before_semi with StmtKind::takes_semi() as the single owner of the ; (debug_assert enforced), labels on ten nodes, qualifier runs as Vec, function/task/module/package/class/typedef/enum/struct headers, declarators, ports, connections, instantiations. Each prints through Fmt::slot_comments, a no-op when empty: 860 corpus and 3 975 opentitan files are byte-identical to v0.30.0 (QA reproduced from an independent baseline build). Four exhaustive gap fuzzers at zero - covergroup 329, fragment 153, constraint 395 (committed at last), RTL 352 (new) - are the regression gate. verify.rs untouched, ten attack pairs. Expression slots are boxed so Expr stays 96 bytes; ast::size_pins asserts it (QA's one finding). Also: nav::definition gains the macro branch hover already had (H5); a cast's type binds as a type via bind_type_expr, FACTS_FORMAT 13 -> 14 (M11); rename reports the candidate references that stayed unresolved through the overlay, one line per file and unit (2.9-20); the scoped name join keeps an escaped segment's terminator (2.9-21). One flagged edit outside scope: a .. in vlog_linter/src/signals.rs patterns. docs/features/comment-slots/README.md. Co-Authored-By: Claude Fable 5 --- CHANGELOG.md | 43 + Cargo.lock | 16 +- Cargo.toml | 2 +- TODO.md | 19 +- crates/lucisv_server/src/hover.rs | 4 +- crates/lucisv_server/src/nav.rs | 119 ++ crates/lucisv_server/src/type_def.rs | 43 + crates/lucisv_server/tests/e2e.rs | 68 + crates/vlog_formatter/src/format.rs | 1242 +++++++++++++---- .../tests/cases/comment_slots.cases | 424 ++++++ .../tests/cases/escaped_identifiers.cases | 11 +- crates/vlog_formatter/tests/verification.rs | 537 ++++--- crates/vlog_linter/src/signals.rs | 7 +- crates/vlog_parser/src/ast.rs | 564 +++++++- crates/vlog_parser/src/parser.rs | 1105 +++++++++++---- crates/vlog_parser/tests/error_recovery.rs | 2 +- crates/vlog_parser/tests/spans.rs | 22 +- crates/vlog_refactor/src/rename.rs | 83 ++ crates/vlog_refactor/tests/rename.rs | 105 +- crates/vlog_semantic/src/bind.rs | 93 +- crates/vlog_semantic/src/facts.rs | 10 +- crates/vlog_semantic/tests/semantics.rs | 87 ++ docs/features/comment-slots/README.md | 544 ++++++++ docs/features/constraint-bodies/README.md | 9 +- docs/features/covergroup-bodies/README.md | 28 +- docs/features/escaped-identifiers/README.md | 37 +- docs/features/fragment-mode/README.md | 16 +- docs/features/overlay-promotion/README.md | 15 +- docs/features/refactor-rename/README.md | 19 + docs/features/type-definition/README.md | 13 + docs/topo.md | 8 +- editors/vscode/CHANGELOG.md | 18 + editors/vscode/README.md | 10 +- editors/vscode/package.json | 2 +- 34 files changed, 4309 insertions(+), 1016 deletions(-) create mode 100644 crates/vlog_formatter/tests/cases/comment_slots.cases create mode 100644 docs/features/comment-slots/README.md diff --git a/CHANGELOG.md b/CHANGELOG.md index c5492e8..f2d7e44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,49 @@ All notable changes to lucisv are recorded here. Versions follow [semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes (see `README.md`) are the only frozen contract. +## 0.31.0 — 2026-09-02 + +### Comments are never dropped — now at every gap + +A comment written between two tokens that no AST node owned was never +deleted, but it was printed one node later, and the safety net refused +the whole file for it (exit 2, no output). Three rounds had filed their +leftovers (52 covergroup gaps, 41 fragment gaps, 40 constraint gaps) and +plain RTL had never been measured. This release gives every such gap an +owner: about seventy named comment slots across expressions (`q[/*c*/ i]`, +`pkg /*c*/ ::name`, `x /*c*/ inside {…}`, casts, unary/postfix operators), +statements (`if`/`case`/`for`/`foreach`/`do…while` headers, `@`/`#` +timing, the gap before every `;`, block and generate labels) and +declarations (qualifier runs like `pure /*c*/ static`, function/task +headers and ports, module/package/class headers, typedefs, enums, +structs, declarators, port lists, connections, instantiations). + +Four exhaustive gap fuzzers — a `/*C*/` in every inter-token gap of +fixture sets for covergroups (329 gaps), fragments (153), constraints +(395) and ordinary RTL (352) — all format and re-format identically, and +are the regression gate from here on. The formatter's output for every +comment-free construct is unchanged: all 860 corpus files and 3 975 +opentitan files are byte-identical to 0.30.0. `verify.rs` is untouched; +ten new attack pairs assert a comment moved across any newly slotted +token is still refused. + +- **Escaped names inside scoped names** (`\my-pkg ::\state-t` as a + type, an instantiated module, a `bind` target) now keep their + terminating space instead of being refused. + +### Editor + +- **Go to definition on a macro use** (`` `WIDTH ``, `` `uvm_info ``) + jumps to the `` `define`` — the file's own definition first, otherwise + every workspace candidate the include graph cannot rule out; nothing + for a macro nothing defines. +- **A cast's type is a reference.** `state_t'(0)` and `pkg::t'(x)` now + light up find-all-references, go-to-type-definition and rename of + the typedef (`FACTS_FORMAT` 13 → 14: the index rebuilds once). +- **Rename warns about what it could not finish.** A `u_x.sig` whose + module is indexed nowhere is left unchanged and now *named* — one + line per file and unit — instead of silently skipped. + ## 0.30.0 — 2026-09-02 Two lanes, run in parallel: semantic lints on by default, and the diff --git a/Cargo.lock b/Cargo.lock index 1c4c4cb..4df4f7a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -97,7 +97,7 @@ dependencies = [ [[package]] name = "lucisv" -version = "0.30.0" +version = "0.31.0" dependencies = [ "lucisv_core", "rayon", @@ -108,11 +108,11 @@ dependencies = [ [[package]] name = "lucisv_core" -version = "0.30.0" +version = "0.31.0" [[package]] name = "lucisv_server" -version = "0.30.0" +version = "0.31.0" dependencies = [ "lsp-server", "lsp-types", @@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] name = "vlog_formatter" -version = "0.30.0" +version = "0.31.0" dependencies = [ "vlog_parser", ] [[package]] name = "vlog_linter" -version = "0.30.0" +version = "0.31.0" dependencies = [ "vlog_formatter", "vlog_parser", @@ -264,11 +264,11 @@ dependencies = [ [[package]] name = "vlog_parser" -version = "0.30.0" +version = "0.31.0" [[package]] name = "vlog_refactor" -version = "0.30.0" +version = "0.31.0" dependencies = [ "vlog_parser", "vlog_semantic", @@ -276,7 +276,7 @@ dependencies = [ [[package]] name = "vlog_semantic" -version = "0.30.0" +version = "0.31.0" dependencies = [ "vlog_parser", ] diff --git a/Cargo.toml b/Cargo.toml index 98b3bbc..b0825b3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ members = [ ] [workspace.package] -version = "0.30.0" +version = "0.31.0" authors = ["Guoliang Chen"] edition = "2021" license = "MIT" diff --git a/TODO.md b/TODO.md index 964fa75..56e108d 100644 --- a/TODO.md +++ b/TODO.md @@ -2750,13 +2750,18 @@ comment-slots/README.md (new), amendments in escaped-identifiers / overlay-promotion / type-definition / refactor-rename / the three fuzzer READMEs, docs/topo.md rows 20/21/22 struck (lead), TODO §25. Runs AFTER §23 (parser/format/bind collide), in parallel with §24. -- [ ] G1 · [ ] G2 · [ ] G3 · [ ] G4 · [ ] G5 (+§2.9-21) · [ ] G6 -- [ ] fuzzers to zero; the analogue tests deleted; constraint fuzzer - committed; corpus 814/820 unchanged; opentitan sweep unchanged -- [ ] H5 define definition (in-file + cross-file + include-narrowed) -- [ ] M11 cast type reference (hover/definition/rename/typeDefinition) -- [ ] §2.9-20 rename warning + pin inverted -- [ ] QA: fuzz 5 fresh fixtures to zero failures; comment-stream +- [x] G1 · [x] G2 · [x] G3 · [x] G4 · [x] G5 (+§2.9-21) · [x] G6 +- [x] fuzzers to zero (covergroup 329, fragment 153, constraint 395, + RTL 352 — all 0 failing); both analogue tests deleted; constraint + fuzzer committed; RTL fuzzer added; corpus 814/820 unchanged and + byte-identical over all 860 files; opentitan sweep unchanged + (3 975 files, 0 output differences, the same 10 failures) +- [x] H5 define definition (in-file + cross-file + include-narrowed + + a define inside a fragment file; unit + e2e) +- [x] M11 cast type reference (`bind_type_expr`; semantic, typeDefinition + and rename pins; `FACTS_FORMAT` 13 → 14) +- [x] §2.9-20 rename warning + pin inverted +- [x] QA: fuzz 5 fresh fixtures to zero failures; comment-stream equality over 48 opentitan DV files + 20 RTL files; rename of a typedef used in casts; `define` definition on opentitan macros (`uvm_*` absent → nothing, project macros → the define site). diff --git a/crates/lucisv_server/src/hover.rs b/crates/lucisv_server/src/hover.rs index ae9cf31..2b0bd0c 100644 --- a/crates/lucisv_server/src/hover.rs +++ b/crates/lucisv_server/src/hover.rs @@ -82,7 +82,7 @@ fn macro_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option { /// several reachable files do — the honest all-candidates list from before /// this feature stands: an empty include graph must never make hover worse /// than it was (`docs/features/include-nav/README.md`). -fn narrowed_to_the_include_graph<'a>( +pub(crate) fn narrowed_to_the_include_graph<'a>( ws: &Workspace, doc: &Document, candidates: Vec<(FileId, &'a Define)>, @@ -106,7 +106,7 @@ fn narrowed_to_the_include_graph<'a>( } /// The macro's name: the identifier after the backtick, argument list excluded. -fn macro_name(token: &Token) -> Option<&str> { +pub(crate) fn macro_name(token: &Token) -> Option<&str> { let rest = token.text.strip_prefix('`')?; let end = rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '$'); let name = match end { diff --git a/crates/lucisv_server/src/nav.rs b/crates/lucisv_server/src/nav.rs index ff097ad..851187f 100644 --- a/crates/lucisv_server/src/nav.rs +++ b/crates/lucisv_server/src/nav.rs @@ -24,6 +24,14 @@ pub fn definition(ws: &Workspace, uri: &Uri, offset: u32) -> Vec { if let Some(location) = includes::definition(ws, doc, offset) { return vec![location]; } + // A macro *use* is one token with no `Reference` behind it, so neither + // layer below can answer for it. Hover has always known where a + // `` `define`` lives; this is the same lookup, returning places to jump + // to instead of text to read. + let macro_defs = macro_definition(ws, doc, uri, offset); + if !macro_defs.is_empty() { + return macro_defs; + } match doc.external.definition_of(&doc.semantics, offset) { Some(Definition::Local(symbol)) => { if symbol.name_span.is_empty() { @@ -59,6 +67,40 @@ pub fn definition(ws: &Workspace, uri: &Uri, offset: u32) -> Vec { } } +/// Where the `` `define`` under the cursor was written, when the cursor is on +/// a macro use. +/// +/// The same two-step lookup [`crate::hover`] does, and deliberately so: a +/// definition this file wrote itself wins outright, and otherwise every +/// workspace candidate the include graph could not rule out is offered. An +/// unknown macro (`` `uvm_info`` with no UVM in the index) yields nothing, +/// which is the same answer as "not a macro" and the right one either way. +fn macro_definition(ws: &Workspace, doc: &Document, uri: &Uri, offset: u32) -> Vec { + let Some(token) = doc.token_at(offset).filter(|token| token.is_macro()) else { + return Vec::new(); + }; + let Some(name) = crate::hover::macro_name(token) else { return Vec::new() }; + + if let Some(define) = doc.defines.latest(name) { + if define.name_span.is_empty() { + return Vec::new(); + } + let Some(target) = path_to_uri_or_self(ws, uri) else { return Vec::new() }; + let range = doc.positions().range(define.name_span); + return vec![Location { uri: target, range }]; + } + + let candidates = + crate::hover::narrowed_to_the_include_graph(ws, doc, ws.index().find_define(name)); + candidates + .iter() + .filter_map(|(file, define)| { + let path = ws.index().path(*file)?; + location(ws, path, define.name_span) + }) + .collect() +} + /// The URI to report a local definition against — the document's own. fn path_to_uri_or_self(ws: &Workspace, uri: &Uri) -> Option { match ws.document(uri).and_then(|d| d.path.clone()) { @@ -508,6 +550,83 @@ mod tests { assert_eq!(locations[0].range.start.line, 1); } + #[test] + fn a_macro_use_jumps_to_its_define_in_the_same_file() { + let text = "`define WIDTH 8\nmodule m;\n logic [`WIDTH-1:0] a;\nendmodule\n"; + let (ws, uri) = document(text); + let locations = definition(&ws, &uri, at(text, "`WIDTH-1") + 2); + assert_eq!(locations.len(), 1, "the `define` this file wrote"); + assert_eq!(locations[0].range.start.line, 0); + assert_eq!(locations[0].range.start.character, 8, "the name, not the backtick"); + } + + #[test] + fn a_macro_nothing_defines_has_no_definition() { + // `uvm_info` with no UVM in the index: the same empty answer a name + // nothing declares gets, and no invented location. + let text = "module m;\n initial `uvm_info(\"x\", \"y\", UVM_LOW)\nendmodule\n"; + let (ws, uri) = document(text); + assert!(definition(&ws, &uri, at(text, "`uvm_info") + 2).is_empty()); + } + + #[test] + fn a_macro_use_jumps_across_files_to_the_define() { + let dir = temp_dir("macro_xfile"); + fs::write(dir.join("defs.svh"), "`define BUS_W 32\n").expect("write"); + let top_path = dir.join("top.sv"); + let top_text = "module top;\n logic [`BUS_W-1:0] bus;\nendmodule\n"; + fs::write(&top_path, top_text).expect("write"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + + let locations = definition(&ws, &uri, at(top_text, "`BUS_W") + 2); + assert_eq!(locations.len(), 1, "the one file that defines it"); + assert!(locations[0].uri.as_str().ends_with("defs.svh"), "{:?}", locations[0].uri); + assert_eq!(locations[0].range.start.line, 0); + } + + #[test] + fn two_defines_of_one_macro_are_narrowed_by_the_include_graph() { + let dir = temp_dir("macro_narrow"); + fs::write(dir.join("a.svh"), "`define MODE 1\n").expect("write"); + fs::write(dir.join("b.svh"), "`define MODE 2\n").expect("write"); + let top_path = dir.join("top.sv"); + // Only `a.svh` is reachable from this file, so only its definition is + // offered — the narrowing `hover` already does, shared. + let top_text = "`include \"a.svh\"\nmodule top;\n logic [`MODE:0] m;\nendmodule\n"; + fs::write(&top_path, top_text).expect("write"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + + let locations = definition(&ws, &uri, at(top_text, "`MODE:0") + 2); + assert_eq!(locations.len(), 1, "the include graph picks one: {locations:?}"); + assert!(locations[0].uri.as_str().ends_with("a.svh"), "{:?}", locations[0].uri); + } + + #[test] + fn a_define_inside_a_fragment_file_is_still_a_jump_target() { + // A `.svh` that is a *fragment* — no module, no package — is indexed + // for its defines like any other file (`fragment-mode`). + let dir = temp_dir("macro_fragment"); + fs::write(dir.join("frag.svh"), "CUSTOM_1,\n`define TAIL 7\nCUSTOM_2\n").expect("write"); + let top_path = dir.join("top.sv"); + let top_text = "module top;\n logic [`TAIL:0] t;\nendmodule\n"; + fs::write(&top_path, top_text).expect("write"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + + let locations = definition(&ws, &uri, at(top_text, "`TAIL") + 2); + assert_eq!(locations.len(), 1, "the fragment's define: {locations:?}"); + assert!(locations[0].uri.as_str().ends_with("frag.svh"), "{:?}", locations[0].uri); + assert_eq!(locations[0].range.start.line, 1); + } + #[test] fn a_name_nothing_declares_has_no_definition() { let text = "module m;\n assign x = 1;\nendmodule\n"; diff --git a/crates/lucisv_server/src/type_def.rs b/crates/lucisv_server/src/type_def.rs index aef8ac7..eb19662 100644 --- a/crates/lucisv_server/src/type_def.rs +++ b/crates/lucisv_server/src/type_def.rs @@ -389,6 +389,49 @@ mod tests { dir } + // ------------------------------------------------------------------ + // casts — `docs/features/comment-slots/README.md` (M11) + // + // The doc comment on `type_name` has always claimed case 2 "is what + // reaches a cast (`state_t'(0)`)". It only became true when `bind_expr` + // started binding the casting type; these pin it. + // ------------------------------------------------------------------ + + #[test] + fn a_cast_reaches_the_typedef_it_names() { + let text = "\ +module m; + typedef logic [1:0] state_t; + logic [1:0] s; + initial s = state_t'(0); +endmodule +"; + let (ws, uri) = document(text); + let cursor = text.rfind("state_t'").expect("the cast") as u32 + 2; + assert_eq!(jumps(&ws, &uri, cursor), vec![(1, 22)], "the `typedef` line's name"); + } + + #[test] + fn a_keyword_cast_asks_nothing_of_the_index() { + let text = "module m;\n initial x = int'(y);\nendmodule\n"; + let (ws, uri) = document(text); + assert!(jumps(&ws, &uri, at(text, "int'") + 1).is_empty(), "`int` declares nothing"); + } + + #[test] + fn a_sized_or_computed_cast_answers_for_its_own_operand() { + // `$bits(t)'(x)` and `(N)'(x)` are widths, not type names: the cursor + // inside them is on an ordinary use, and answers as one. + let text = "\ +module m; + typedef logic [3:0] nib_t; + initial a = $bits(nib_t)'(x); +endmodule +"; + let (ws, uri) = document(text); + assert_eq!(jumps(&ws, &uri, at(text, "nib_t)") + 1), vec![(1, 22)], "the typedef"); + } + // ------------------------------------------------------------------ // in-file types // ------------------------------------------------------------------ diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index ccf92ce..3909ebe 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -2843,6 +2843,74 @@ fn include_nav_round_trips_in_a_workspace_whose_directory_has_a_space() { /// cannot fully settle, since it never proves what URI actually lands in the /// client's hands. `top.sv` writes `` `include "defs.svh"``, but the file on /// disk (and in the filelist) is `Defs.svh`. Both `documentLink`'s target and +/// F12 on a macro *use* lands on the `` `define`` that wrote it, in this file +/// and across the workspace. +/// +/// A macro use is one token with no `Reference` behind it, so before +/// `docs/features/comment-slots/README.md` the request answered `null` while +/// hover had known the answer all along. +#[test] +fn go_to_definition_on_a_macro_use_lands_on_its_define() { + let dir = temp_dir("macrodef"); + let defs = dir.join("defs.svh"); + std::fs::write(&defs, "`define BUS_W 32\n").expect("write"); + let top = dir.join("top.sv"); + let top_text = "`define LOCAL_W 8\nmodule top;\n logic [`BUS_W-1:0] a;\n logic [`LOCAL_W-1:0] b;\n initial `uvm_info(\"x\")\nendmodule\n"; + std::fs::write(&top, top_text).expect("write"); + + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", top.display()); + let defs_uri = format!("file://{}", defs.display()); + + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(top_text).expect("json") + )), + // The cross-file macro, the in-file one, and one nothing defines. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":12}}}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":3,"character":12}}}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":4,"character":14}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&session); + let response = |id: u32| -> &serde_json::Value { + messages.iter().find(|m| m["id"] == id).unwrap_or_else(|| panic!("no {id}: {messages:#?}")) + }; + + let cross = response(2)["result"].as_array().expect("a location list"); + assert_eq!(cross.len(), 1, "{cross:#?}"); + assert_eq!(cross[0]["uri"], defs_uri.as_str(), "the workspace's own `defs.svh`"); + assert_eq!(cross[0]["range"]["start"]["line"], 0); + + let local = response(3)["result"].as_array().expect("a location list"); + assert_eq!(local.len(), 1, "{local:#?}"); + assert_eq!(local[0]["uri"], uri.as_str(), "a define this file wrote wins outright"); + assert_eq!(local[0]["range"]["start"]["line"], 0); + assert_eq!(local[0]["range"]["start"]["character"], 8, "the name, not the backtick"); + + let unknown = &response(4)["result"]; + assert!( + unknown.is_null() || unknown.as_array().is_some_and(|a| a.is_empty()), + "an unknown macro invents nothing: {unknown:#?}" + ); + + let _ = std::fs::remove_dir_all(&dir); +} + /// F12 (`textDocument/definition`) must carry the *index's* spelling /// (`Defs.svh`), not the as-written one — otherwise an editor that diffs URIs /// against its own open-buffer list (most do, to decide whether a jump lands diff --git a/crates/vlog_formatter/src/format.rs b/crates/vlog_formatter/src/format.rs index 1e4ed86..0b0d5e2 100644 --- a/crates/vlog_formatter/src/format.rs +++ b/crates/vlog_formatter/src/format.rs @@ -178,6 +178,18 @@ struct BinaryOp<'e> { /// A list element ready for comma-list layout. Blank lines between elements /// are deliberately dropped, so only the comments ride along. +/// The pieces of a `begin … end` block a printer needs, gathered so the +/// two spellings (a statement, and a body cuddled onto a header) pass one +/// argument instead of six. +struct BlockDoc<'a> { + label_comments: &'a LabelComments, + label: &'a Option, + stmts: &'a [Stmt], + dangling: &'a [Comment], + end_label_comments: &'a LabelComments, + end_label: &'a Option, +} + struct ListItem { leading: Vec, doc: Doc, @@ -326,6 +338,37 @@ impl<'a> Fmt<'a> { } } + /// The same, with the comments the source wrote in the label's two gaps + /// (`endgroup /*a*/ : /*b*/ cg`). The common case — no comment — is + /// [`Fmt::closing`] verbatim. + fn closing_labeled(&self, kw: &str, label: &Option, c: &LabelComments) -> Doc { + if c.is_empty() { + return Self::closing(kw, label); + } + let mut docs = vec![text(kw.to_string())]; + self.label_tail(label, c, &mut docs); + concat(docs) + } + + /// ` : name`, with the comments written in its two gaps. A no-op when no + /// label was written. + fn label_tail(&self, label: &Option, c: &LabelComments, docs: &mut Vec) { + let Some(l) = label else { + // A comment before a `:` that was never written belongs to + // whatever follows, and `gap_before` never took it. + debug_assert!(c.is_empty()); + return; + }; + self.slot_comments(&c.before_colon, docs); + docs.push(text(if c.before_colon.is_empty() { " :" } else { ":" })); + if c.after_colon.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&c.after_colon, docs); + } + docs.push(text(named(l))); + } + // ------------------------------------------------------------------ // Format-off fences // ------------------------------------------------------------------ @@ -513,6 +556,137 @@ impl<'a> Fmt<'a> { } } + /// The `pkg::cls::` written in front of an out-of-body definition's name, + /// one segment at a time so a comment beside a `::` prints where it was + /// written — and so an escaped segment keeps the space that terminates + /// it, which `named` supplies. + fn scope_prefix(&self, scope: &[ScopeSeg], docs: &mut Vec) { + for seg in scope { + docs.push(text(named(&seg.name.text))); + self.slot_comments(&seg.before_sep, docs); + docs.push(text("::")); + self.slot_comments(&seg.after_sep, docs); + } + } + + /// The `; ` between two sections of a `for` header, carrying whatever the + /// source wrote in the two gaps around it. + fn for_semi(&self, before: &[Comment], after: &[Comment], docs: &mut Vec) { + self.slot_comments(before, docs); + docs.push(text(";")); + if after.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(after, docs); + } + } + + /// `for` plus its `(`, with the gap between them. + fn for_open(&self, comments: &ForComments, docs: &mut Vec) { + docs.push(text("for")); + if comments.after_kw.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&comments.after_kw, docs); + } + docs.push(text("(")); + self.slot_comments(&comments.after_open, docs); + } + + /// The `lhs op rhs` of a `for` header's initialiser or step. + fn simple_assign(&self, a: &SimpleAssign, docs: &mut Vec) { + docs.push(self.expr(&a.lhs)); + self.slot_comments(&a.op_comments.before, docs); + docs.push(text(if a.op_comments.before.is_empty() { + format!(" {}", a.op) + } else { + a.op.clone() + })); + if a.op_comments.after.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&a.op_comments.after, docs); + } + docs.push(self.expr(&a.rhs)); + } + + /// `= value`, with the comments written on either side of the `=`. + fn eq_default(&self, comments: &BinaryComments, value: Doc, docs: &mut Vec) { + self.slot_comments(&comments.before, docs); + docs.push(text(if comments.before.is_empty() { " =" } else { "=" })); + if comments.after.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&comments.after, docs); + } + docs.push(value); + } + + /// A keyword and whatever the source wrote between it and what follows — + /// a space when that is nothing. + fn word_then(&self, word: &str, comments: &[Comment], docs: &mut Vec) { + docs.push(text(word.to_string())); + if comments.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(comments, docs); + } + } + + /// A run of qualifier keywords, each followed by the space or the comment + /// the source wrote after it (`local /*c*/ static `). Always ends in a + /// separator, so the caller writes what follows without one of its own. + fn qualifier_run(&self, run: &[Qualifier], docs: &mut Vec) { + for q in run { + docs.push(text(q.text.clone())); + if q.after.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&q.after, docs); + } + } + } + + /// One named comment slot between two tokens the caller emits either side + /// of it, spaced off both — and a no-op when the slot is empty, so a + /// construct with no comment in it is laid out exactly as it was before + /// the slot existed. + /// + /// This is what every slot of [`SegmentComments`] is printed with, and it + /// is why the empty case of a `.`, a `::` or a `[` costs nothing. + fn slot_comments(&self, comments: &[Comment], docs: &mut Vec) { + if comments.is_empty() { + return; + } + self.inline_comments_spaced(comments, docs); + } + + /// `[ … ]` with the comments written in a segment's or a dimension's own + /// slots printed back between the same two tokens the source wrote them + /// between. `rest` is the `: lsb` half of a range, absent for an index. + /// + /// The opener's own slot (`base /*c*/ [`) belongs to whoever emitted the + /// base, so it is not printed here. + fn bracket_slots( + &self, + comments: &SegmentComments, + first: Doc, + rest: Option<(&str, Doc)>, + ) -> Doc { + let mut docs = vec![text("[")]; + self.slot_comments(&comments.after_open, &mut docs); + docs.push(first); + if let Some((op, second)) = rest { + self.slot_comments(&comments.before_op, &mut docs); + docs.push(text(op.to_string())); + self.slot_comments(&comments.after_op, &mut docs); + docs.push(second); + } + self.slot_comments(&comments.before_close, &mut docs); + docs.push(text("]")); + concat(docs) + } + fn with_meta(&self, meta: &Meta, doc: Doc) -> Doc { let mut docs = self.leading(meta); docs.push(doc); @@ -797,6 +971,9 @@ impl<'a> Fmt<'a> { if !decl.meta.leading.is_empty() || !decl.meta.before_sep.is_empty() || decl.meta.trailing.is_some() + // A comment after the keyword makes this row a width no other row + // shares, so it never joins an alignment group. + || !d.after_kw.is_empty() { return None; } @@ -852,6 +1029,17 @@ impl<'a> Fmt<'a> { group(vec![text("("), indent(vec![Doc::SoftLine, self.expr(e)]), Doc::SoftLine, text(")")]) } + /// `( cond )` with the comments a header kept in its own slots. The + /// `after_kw` half is written by the caller, which owns the keyword. + fn header_slots(&self, cond: &Expr, comments: &HeaderComments) -> Doc { + if comments.after_open.is_empty() && comments.before_close.is_empty() { + return self.parens(cond); + } + let before: Vec<&Comment> = comments.after_open.iter().collect(); + let after: Vec<&Comment> = comments.before_close.iter().collect(); + self.paren_comments(cond, &before, &after) + } + /// `( expr )` with the comments the source wrote just inside the /// parentheses. A comment there forces them open, the same way a comment /// inside a port list does. @@ -1103,7 +1291,7 @@ impl<'a> Fmt<'a> { // so the trailing comment must not be printed a second time. Some(range) => docs.push(self.slice(range)), None => { - docs.push(Self::tail_doc(&item.kind)?); + docs.push(self.tail_doc(&item.kind)?); docs.extend(self.trailing(&item.meta)); } } @@ -1114,16 +1302,22 @@ impl<'a> Fmt<'a> { fn head_doc(&self, kind: &ItemKind, depth: usize) -> Option { match kind { ItemKind::Module(m) => Some(self.module_head(m, depth)), - ItemKind::Package { kw, name, .. } => Some(text(format!("{kw} {};", named(name)))), + ItemKind::Package { kw, before_name, name, before_semi, .. } => { + Some(self.package_head(kw, before_name, name, before_semi)) + } _ => None, } } /// A split item's closing keyword, laid out. - fn tail_doc(kind: &ItemKind) -> Option { + fn tail_doc(&self, kind: &ItemKind) -> Option { match kind { - ItemKind::Module(m) => Some(Self::closing(m.end_kw(), &m.end_label)), - ItemKind::Package { end_label, .. } => Some(Self::closing("endpackage", end_label)), + ItemKind::Module(m) => { + Some(self.closing_labeled(m.end_kw(), &m.end_label, &m.end_label_comments)) + } + ItemKind::Package { end_label, end_label_comments, .. } => { + Some(self.closing_labeled("endpackage", end_label, end_label_comments)) + } _ => None, } } @@ -1131,8 +1325,18 @@ impl<'a> Fmt<'a> { fn item_kind(&self, kind: &ItemKind, align: Option<&Align>, depth: usize) -> Doc { match kind { ItemKind::Module(m) => self.module(m, depth), - ItemKind::Package { kw, name, items, dangling, end_label, .. } => { - let mut docs = vec![text(format!("{kw} {};", named(name)))]; + ItemKind::Package { + kw, + before_name, + name, + before_semi, + items, + dangling, + end_label, + end_label_comments, + .. + } => { + let mut docs = vec![self.package_head(kw, before_name, name, before_semi)]; let mut body = Vec::new(); if !items.is_empty() { body.push(Doc::HardLine); @@ -1141,7 +1345,7 @@ impl<'a> Fmt<'a> { body.extend(self.dangling(dangling)); docs.push(indent(body)); docs.push(Doc::HardLine); - docs.push(Self::closing("endpackage", end_label)); + docs.push(self.closing_labeled("endpackage", end_label, end_label_comments)); concat(docs) } ItemKind::Directive(d) => self.raw_text(d), @@ -1216,6 +1420,25 @@ impl<'a> Fmt<'a> { // Module // ------------------------------------------------------------------ + /// `package p;` — the two comment slots a package header owns. + fn package_head( + &self, + kw: &str, + before_name: &[Comment], + name: &str, + before_semi: &[Comment], + ) -> Doc { + let mut docs = vec![text(kw.to_string())]; + if before_name.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(before_name, &mut docs); + } + docs.push(text(named(name))); + docs.push(self.semi(before_semi)); + concat(docs) + } + fn module(&self, m: &Module, depth: usize) -> Doc { let mut docs = vec![self.module_head(m, depth)]; let mut body = Vec::new(); @@ -1226,7 +1449,7 @@ impl<'a> Fmt<'a> { body.extend(self.dangling(&m.dangling)); docs.push(indent(body)); docs.push(Doc::HardLine); - docs.push(Self::closing(m.end_kw(), &m.end_label)); + docs.push(self.closing_labeled(m.end_kw(), &m.end_label, &m.end_label_comments)); concat(docs) } @@ -1235,7 +1458,13 @@ impl<'a> Fmt<'a> { /// Split out from the body so a range run can keep one and lay out the /// other (`range.rs`); a whole-file run always emits both. fn module_head(&self, m: &Module, depth: usize) -> Doc { - let mut docs = vec![text(format!("{} {}", m.kw, named(&m.name)))]; + let mut docs = vec![text(m.kw.clone())]; + if m.before_name.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&m.before_name, &mut docs); + } + docs.push(text(named(&m.name))); let has_imports = !m.imports.is_empty(); if has_imports { // One line per `import` statement the header wrote: folding two of @@ -1264,6 +1493,7 @@ impl<'a> Fmt<'a> { let items = self.list_entries(items, &m.param_directives); let broken = !m.param_directives.is_empty(); docs.push(text(if on_fresh_line { "#" } else { " #" })); + self.slot_comments(&m.param_after_hash, &mut docs); docs.push(self.delimited_dangling("(", items, &m.param_dangling, ")", broken)); on_fresh_line = false; } @@ -1273,7 +1503,7 @@ impl<'a> Fmt<'a> { // the same code. let mut broken = !m.port_directives.is_empty(); match &m.ports { - PortList::None => docs.push(text(";")), + PortList::None => docs.push(self.semi(&m.before_semi)), PortList::Empty | PortList::Ansi(_) | PortList::NonAnsi(_) => { let items: Vec = match &m.ports { PortList::Ansi(ports) => { @@ -1303,36 +1533,37 @@ impl<'a> Fmt<'a> { docs.push(text(" ")); } docs.push(self.delimited_dangling("(", items, &m.port_dangling, ")", broken)); - docs.push(text(";")); + docs.push(self.semi(&m.before_semi)); } } concat(docs) } fn param_port(&self, p: &ParamPort) -> Doc { - let mut parts: Vec = Vec::new(); + let mut docs = Vec::new(); if let Some(kw) = &p.kw { - parts.push(kw.clone()); + self.word_then(kw, &p.after_kw, &mut docs); + } else { + self.slot_comments(&p.after_kw, &mut docs); } if p.is_type { - parts.push("type".to_string()); + docs.push(text("type ")); } - let mut docs = Vec::new(); - let ty = self.data_type(&p.ty); - let prefix = parts.join(" "); - if !prefix.is_empty() { - docs.push(text(prefix)); - docs.push(text(" ")); - } - if let Some(t) = ty { - docs.push(t); - docs.push(text(" ")); + match self.data_type(&p.ty) { + Some(t) => { + docs.push(t); + if p.before_name.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&p.before_name, &mut docs); + } + } + None => self.slot_comments(&p.before_name, &mut docs), } docs.push(name_doc(&p.name)); docs.extend(self.unpacked_dims(&p.unpacked)); if let Some(d) = &p.default { - docs.push(text(" = ")); - docs.push(group(vec![self.expr(d)])); + self.eq_default(&p.eq_comments, group(vec![self.expr(d)]), &mut docs); } concat(docs) } @@ -1346,6 +1577,12 @@ impl<'a> Fmt<'a> { /// port with no prefix at all (a continuation port, `output a, b`) is one /// cell, which is what takes it out of every alignment group. fn ansi_port_cells(&self, p: &AnsiPort) -> Vec { + // A comment in one of the port's own gaps makes the row a width no + // other row shares, so it is one cell and joins no alignment group — + // the rule an attributed connection already follows. + if !p.after_dir.is_empty() || !p.before_name.is_empty() { + return vec![self.ansi_port_plain(p)]; + } let mut prefix = Vec::new(); if let Some(dir) = &p.dir { prefix.push(text(format!("{dir} "))); @@ -1367,8 +1604,7 @@ impl<'a> Fmt<'a> { let mut docs = vec![name_doc(&p.name)]; docs.extend(self.unpacked_dims(&p.unpacked)); if let Some(d) = &p.default { - docs.push(text(" = ")); - docs.push(self.expr(d)); + self.eq_default(&p.eq_comments, self.expr(d), &mut docs); } if prefix.is_empty() { return vec![concat(docs)]; @@ -1376,6 +1612,35 @@ impl<'a> Fmt<'a> { vec![concat(prefix), concat(docs)] } + /// An ANSI port written out in one piece, for the rows that carry a + /// comment in one of their own gaps and so cannot be aligned. + fn ansi_port_plain(&self, p: &AnsiPort) -> Doc { + let mut docs = Vec::new(); + if let Some(dir) = &p.dir { + self.word_then(dir, &p.after_dir, &mut docs); + } + if let Some(net) = &p.net { + docs.push(text(format!("{net} "))); + } + match self.data_type(&p.ty) { + Some(t) => { + docs.push(t); + if p.before_name.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&p.before_name, &mut docs); + } + } + None => self.slot_comments(&p.before_name, &mut docs), + } + docs.push(name_doc(&p.name)); + docs.extend(self.unpacked_dims(&p.unpacked)); + if let Some(d) = &p.default { + self.eq_default(&p.eq_comments, self.expr(d), &mut docs); + } + concat(docs) + } + // ------------------------------------------------------------------ // Types and declarations // ------------------------------------------------------------------ @@ -1417,7 +1682,8 @@ impl<'a> Fmt<'a> { need_space = true; } if !ty.packed.is_empty() { - if need_space { + // A dimension that opens with a comment writes its own space. + if need_space && ty.packed[0].comments.opens_clean() { docs.push(text(" ")); } for d in &ty.packed { @@ -1447,19 +1713,29 @@ impl<'a> Fmt<'a> { } fn dim(&self, d: &Dim) -> Doc { - match &d.kind { + let c = &d.comments; + let brackets = 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) + let rest = b.as_ref().map(|b| (":", self.expr_compact(b))); + self.bracket_slots(c, self.expr_compact(a), rest) } - DimKind::Dynamic => text("[]"), - DimKind::Wildcard => text("[*]"), + // `[]` and `[*]` have no operand, so the one inner slot they own + // is the gap before the `]`, which is where `parse_dims` puts + // anything written between the brackets. + DimKind::Dynamic => self.bracket_slots(c, text(""), None), + DimKind::Wildcard => self.bracket_slots(c, text("*"), None), + }; + if c.opens_clean() { + return brackets; } + // `logic /*c*/ [3:0]` — the gap before the `[` belongs to the + // dimension, since nothing to its left has a slot for it. The space + // in front is the dimension's own: a caller that would have written + // one asks [`SegmentComments::opens_clean`] and leaves it out. + let mut docs = Vec::new(); + self.inline_comments_spaced(&c.before_open, &mut docs); + docs.push(brackets); + concat(docs) } /// Compact rendering used inside `[...]` brackets: arithmetic and shift @@ -1483,17 +1759,22 @@ impl<'a> Fmt<'a> { docs.push(self.expr_compact(rhs)); concat(docs) } - ExprKind::Ternary { cond, then, els, .. } => concat(vec![ + // The compact spelling has nowhere to put a comment written + // inside the `? :` or just inside the parentheses, so a shape + // that carries one falls back to the ordinary layout, which does. + ExprKind::Ternary { cond, then, els, comments } if comments.is_empty() => concat(vec![ self.expr_compact(cond), text(" ? "), self.expr_compact(then), text(" : "), self.expr_compact(els), ]), - ExprKind::Paren { inner, .. } => { + ExprKind::Paren { inner, before, after } if before.is_empty() && after.is_empty() => { concat(vec![text("("), self.expr_compact(inner), text(")")]) } - ExprKind::Unary { op, expr } => concat(vec![text(op.clone()), self.expr_compact(expr)]), + ExprKind::Unary { op, comments, expr } if comments.is_empty() => { + concat(vec![text(op.clone()), self.expr_compact(expr)]) + } _ => self.expr(e), } } @@ -1501,7 +1782,9 @@ impl<'a> Fmt<'a> { fn unpacked_dims(&self, dims: &[Dim]) -> Vec { let mut docs = Vec::new(); if !dims.is_empty() { - docs.push(text(" ")); + if dims[0].comments.opens_clean() { + docs.push(text(" ")); + } for d in dims { docs.push(self.dim(d)); } @@ -1516,8 +1799,14 @@ impl<'a> Fmt<'a> { let mut docs = vec![name_doc(&d.name)]; docs.extend(self.unpacked_dims(&d.unpacked)); if let Some(init) = &d.init { - docs.push(text(" =")); - docs.push(group(vec![self.assign_rhs(self.expr(init))])); + self.slot_comments(&d.eq_comments.before, &mut docs); + docs.push(text(if d.eq_comments.before.is_empty() { " =" } else { "=" })); + if d.eq_comments.after.is_empty() { + docs.push(group(vec![self.assign_rhs(self.expr(init))])); + } else { + self.inline_comments_spaced(&d.eq_comments.after, &mut docs); + docs.push(group(vec![self.expr(init)])); + } } ListItem::from_meta(&d.meta, concat(docs)) }) @@ -1585,7 +1874,8 @@ impl<'a> Fmt<'a> { ); } } - let mut docs = vec![text(d.kw.clone()), text(" ")]; + let mut docs = Vec::new(); + self.word_then(&d.kw, &d.after_kw, &mut docs); if d.is_type { docs.push(text("type ")); } @@ -1627,9 +1917,7 @@ impl<'a> Fmt<'a> { docs.push(self.expr(delay)); docs.push(text(" ")); } - for q in &d.qualifiers { - docs.push(text(format!("{q} "))); - } + self.qualifier_run(&d.qualifiers, &mut docs); if let Some(t) = self.data_type(&d.ty) { docs.push(t); docs.push(text(" ")); @@ -1652,30 +1940,29 @@ impl<'a> Fmt<'a> { } fn typedef(&self, t: &Typedef) -> Doc { - match &t.kind { - TypedefKind::ForwardClass => text(format!("typedef class {};", named(&t.name))), - TypedefKind::Alias(ty) => { - let mut docs = vec![text("typedef ")]; - if let Some(d) = self.data_type(ty) { - docs.push(d); + let mut docs = Vec::new(); + self.word_then("typedef", &t.after_kw, &mut docs); + let base = match &t.kind { + TypedefKind::ForwardClass => Some(text("class")), + TypedefKind::Alias(ty) => self.data_type(ty), + TypedefKind::Enum(e) => Some(self.enum_type(e)), + TypedefKind::Struct(s) => Some(self.struct_type(s)), + }; + match base { + Some(d) => { + docs.push(d); + if t.before_name.is_empty() { docs.push(text(" ")); + } else { + self.inline_comments_spaced(&t.before_name, &mut docs); } - docs.push(name_doc(&t.name)); - docs.extend(self.unpacked_dims(&t.unpacked)); - docs.push(text(";")); - concat(docs) } - TypedefKind::Enum(e) => concat(vec![ - text("typedef "), - self.enum_type(e), - text(format!(" {};", named(&t.name))), - ]), - TypedefKind::Struct(s) => concat(vec![ - text("typedef "), - self.struct_type(s), - text(format!(" {};", named(&t.name))), - ]), + None => self.slot_comments(&t.before_name, &mut docs), } + docs.push(name_doc(&t.name)); + docs.extend(self.unpacked_dims(&t.unpacked)); + docs.push(self.semi(&t.before_semi)); + concat(docs) } /// `enum [base] { A, B }` — one line if it fits, else one member per line. @@ -1683,13 +1970,27 @@ impl<'a> Fmt<'a> { /// type name would (`enum logic [1:0] {IDLE, STOP} state;`). fn enum_type(&self, e: &EnumType) -> Doc { let mut docs = vec![text("enum")]; + let mut spaced = false; + if !e.after_kw.is_empty() { + self.inline_comments_spaced(&e.after_kw, &mut docs); + spaced = true; + } if let Some(base) = &e.base { if let Some(d) = self.data_type(base) { - docs.push(text(" ")); + if !spaced { + docs.push(text(" ")); + } docs.push(d); + spaced = false; } } - docs.push(text(" ")); + if e.before_open.is_empty() { + if !spaced { + docs.push(text(" ")); + } + } else { + self.inline_comments_spaced(&e.before_open, &mut docs); + } let items = self.list_entries(self.enum_member_items(&e.members), &e.directives); // `e.dangling` — comments written before the closing `}` — is printed // inside the braces; the enum has no other place to put it, and @@ -1710,7 +2011,13 @@ impl<'a> Fmt<'a> { // range, not a name with a dimension beside it. d.extend(m.range.iter().map(|r| self.dim(r))); if let Some(v) = &m.value { - d.push(text(" = ")); + self.slot_comments(&m.eq_comments.before, &mut d); + d.push(text(if m.eq_comments.before.is_empty() { " =" } else { "=" })); + if m.eq_comments.after.is_empty() { + d.push(text(" ")); + } else { + self.inline_comments_spaced(&m.eq_comments.after, &mut d); + } d.push(self.expr(v)); } ListItem::from_meta(&m.meta, concat(d)).with_comma(m.comma) @@ -1723,27 +2030,27 @@ impl<'a> Fmt<'a> { /// type name would, and a struct member whose own type is an inline /// struct — the recursion is what indents a nested body one more level. fn struct_type(&self, s: &StructType) -> Doc { - let mut header = s.kw.clone(); - // `union tagged packed`, in the LRM's order. + let c = &s.header_comments; + // `union tagged packed`, in the LRM's order, each word followed by + // whatever the source wrote after it. + let mut head = Vec::new(); + self.word_then(&s.kw, &c.after_kw, &mut head); if s.tagged { - header.push_str(" tagged"); + self.word_then("tagged", &c.after_tagged, &mut head); } if s.packed { - header.push_str(" packed"); + self.word_then("packed", &c.after_packed, &mut head); } if let Some(sig) = &s.signing { - header.push(' '); - header.push_str(sig); + self.word_then(sig, &c.after_signing, &mut head); } - header.push_str(" {"); + head.push(text("{")); let mut inner = Vec::new(); for m in &s.members { inner.push(Doc::HardLine); inner.extend(self.leading(&m.meta)); let mut d = Vec::new(); - for q in &m.qualifiers { - d.push(text(format!("{q} "))); - } + self.qualifier_run(&m.qualifiers, &mut d); if let Some(ty) = self.data_type(&m.ty) { d.push(ty); d.push(text(" ")); @@ -1754,7 +2061,7 @@ impl<'a> Fmt<'a> { inner.extend(self.trailing(&m.meta)); } inner.extend(self.dangling(&s.dangling)); - concat(vec![text(header), indent(inner), Doc::HardLine, text("}")]) + concat(vec![concat(head), indent(inner), Doc::HardLine, text("}")]) } // ------------------------------------------------------------------ @@ -1764,18 +2071,32 @@ impl<'a> Fmt<'a> { /// `lhs = rhs`, with any comments written after the `=` printed on the /// `=`'s line so they stay on that side of the value. fn assign_pair(&self, p: &AssignPair) -> Doc { + // `y /*c*/ =` — the comments stay on the operator's left. + let mut head = vec![self.expr(&p.lhs)]; + self.slot_comments(&p.op_comments, &mut head); + head.push(text(if p.op_comments.is_empty() { " =" } else { "=" })); if p.rhs_comments.is_empty() { - return group(vec![self.expr(&p.lhs), text(" ="), self.assign_rhs(self.expr(&p.rhs))]); + head.push(self.assign_rhs(self.expr(&p.rhs))); + return group(head); } let mut inner = Vec::new(); let ends_line = self.inline_comments(&p.rhs_comments, &mut inner); inner.push(if ends_line { Doc::HardLine } else { text(" ") }); inner.push(self.expr(&p.rhs)); - group(vec![self.expr(&p.lhs), text(" ="), indent(inner)]) + head.push(indent(inner)); + group(head) } fn cont_assign(&self, a: &ContAssign) -> Doc { - let mut docs = vec![text("assign ")]; + // `assign /*c*/ y = x;` — the first pair's own leading comments were + // written after the keyword, and print there. + let lead = a.assigns.first().map(|p| p.meta.leading.as_slice()).unwrap_or(&[]); + let mut docs = vec![text("assign")]; + if lead.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(lead, &mut docs); + } if let Some(s) = &a.strength { docs.push(text(format!("{} ", drive_strength(s)))); } @@ -1784,8 +2105,19 @@ impl<'a> Fmt<'a> { docs.push(self.expr(delay)); docs.push(text(" ")); } - let items: Vec = - a.assigns.iter().map(|p| ListItem::from_meta(&p.meta, self.assign_pair(p))).collect(); + let items: Vec = a + .assigns + .iter() + .enumerate() + .map(|(i, p)| { + // The first pair's leading comments are printed above, after + // the keyword; printing them twice would duplicate them. + let skip = usize::from(i == 0) * lead.len(); + let mut item = ListItem::from_meta(&p.meta, self.assign_pair(p)); + item.leading.drain(..skip.min(item.leading.len())); + item + }) + .collect(); if items.len() == 1 { let item = items.into_iter().next().unwrap(); docs.push(item.doc); @@ -1859,6 +2191,7 @@ impl<'a> Fmt<'a> { let items = self.list_entries(items, &inst.param_directives); let broken = !inst.param_directives.is_empty(); docs.push(text(if on_fresh_line { "#" } else { " #" })); + self.slot_comments(&inst.after_hash, &mut docs); docs.push(self.delimited("(", items, ")", broken)); on_fresh_line = false; } @@ -1900,7 +2233,7 @@ impl<'a> Fmt<'a> { } docs.push(group(vec![indent(inner)])); } - docs.push(text(";")); + docs.push(self.semi(&inst.before_semi)); concat(docs) } @@ -1908,7 +2241,9 @@ impl<'a> Fmt<'a> { fn instance(&self, instance: &Instance, depth: usize) -> Doc { let mut docs = vec![name_doc(&instance.name)]; if !instance.dims.is_empty() { - docs.push(text(" ")); + if instance.dims[0].comments.opens_clean() { + docs.push(text(" ")); + } for d in &instance.dims { docs.push(self.dim(d)); } @@ -1973,6 +2308,11 @@ impl<'a> Fmt<'a> { if c.name.is_empty() || c.name == "*" || !c.meta.attrs.is_empty() { return plain(); } + // A comment written in one of the connection's own gaps makes the row + // a width no other row shares, so it never joins an alignment group. + if !c.after_dot.is_empty() || !c.before_open.is_empty() || !c.after_open.is_empty() { + return plain(); + } let Some(e) = &c.expr else { return plain() }; if matches!(e.kind, ExprKind::Empty(_)) { return plain(); @@ -2006,7 +2346,13 @@ impl<'a> Fmt<'a> { /// `.name`, `.*`, or a positional value. fn connection_bare(&self, c: &Connection) -> Doc { if c.name == "*" { - return text(".*"); + if c.after_dot.is_empty() { + return text(".*"); + } + let mut docs = vec![text(".")]; + self.slot_comments(&c.after_dot, &mut docs); + docs.push(text("*")); + return concat(docs); } if c.name.is_empty() { // Positional parameter value. @@ -2015,10 +2361,24 @@ impl<'a> Fmt<'a> { None => text(""), }; } + // `.` then the name, with whatever the source wrote between them. + let head = |f: &Self| { + let mut docs = vec![text(".")]; + f.slot_comments(&c.after_dot, &mut docs); + docs.push(text(named(&c.name))); + docs + }; + // …and the `(` that follows the name, with its two gaps. + let open = |f: &Self, docs: &mut Vec| { + f.slot_comments(&c.before_open, docs); + docs.push(text("(")); + f.slot_comments(&c.after_open, docs); + }; match &c.expr { - None => text(format!(".{}", named(&c.name))), + None => concat(head(self)), Some(Expr { kind: ExprKind::Empty(comments), .. }) => { - let mut docs = vec![text(format!(".{}(", named(&c.name)))]; + let mut docs = head(self); + open(self, &mut docs); let mut ends_line = false; for cm in comments { if ends_line { @@ -2037,11 +2397,11 @@ impl<'a> Fmt<'a> { let mut inner = vec![Doc::SoftLine, self.expr(e)]; let ends_line = self.inline_comments(&c.close_comments, &mut inner); let close = if ends_line { Doc::HardLine } else { Doc::SoftLine }; - concat(vec![ - text(format!(".{}(", named(&c.name))), - group(vec![indent(inner), close]), - text(")"), - ]) + let mut docs = head(self); + open(self, &mut docs); + docs.push(group(vec![indent(inner), close])); + docs.push(text(")")); + concat(docs) } } } @@ -2118,9 +2478,21 @@ impl<'a> Fmt<'a> { /// `else` can cuddle). fn gen_block(&self, docs: &mut Vec, b: &GenBlock, depth: usize) -> bool { if b.is_block { - match &b.label { - Some(l) => docs.push(text(format!(" begin : {}", named(l)))), - None => docs.push(text(" begin")), + if b.before_kw.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&b.before_kw, docs); + } + docs.push(text("begin")); + if let Some(l) = &b.label { + self.slot_comments(&b.before_colon, docs); + docs.push(text(if b.before_colon.is_empty() { " :" } else { ":" })); + if b.after_colon.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&b.after_colon, docs); + } + docs.push(text(named(l))); } let mut body = Vec::new(); if !b.items.is_empty() { @@ -2130,7 +2502,7 @@ impl<'a> Fmt<'a> { body.extend(self.dangling(&b.dangling)); docs.push(indent(body)); docs.push(Doc::HardLine); - docs.push(Self::closing("end", &b.end_label)); + docs.push(self.closing_labeled("end", &b.end_label, &b.end_label_comments)); true } else { let item = &b.items[0]; @@ -2140,17 +2512,22 @@ impl<'a> Fmt<'a> { } fn gen_for(&self, g: &GenFor, depth: usize) -> Doc { - let mut header = vec![text("for (")]; + let mut header = Vec::new(); + self.for_open(&g.comments, &mut header); if g.init_genvar { - header.push(text("genvar ")); + header.push(text("genvar")); + if g.after_genvar.is_empty() { + header.push(text(" ")); + } else { + self.inline_comments_spaced(&g.after_genvar, &mut header); + } } - header.push(self.expr(&g.init.lhs)); - header.push(text(format!(" {} ", g.init.op))); - header.push(self.expr(&g.init.rhs)); - header.push(text("; ")); + self.simple_assign(&g.init, &mut header); + self.for_semi(&g.comments.before_first_semi, &g.comments.after_first_semi, &mut header); header.push(self.expr(&g.cond)); - header.push(text("; ")); + self.for_semi(&g.comments.before_second_semi, &g.comments.after_second_semi, &mut header); header.push(self.for_step(&g.step)); + self.slot_comments(&g.comments.before_close, &mut header); header.push(text(")")); let mut docs = vec![concat(header)]; self.gen_block(&mut docs, &g.body, depth); @@ -2163,7 +2540,7 @@ impl<'a> Fmt<'a> { for item in &g.items { body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); body.extend(self.leading(&item.meta)); - let mut item_docs = vec![self.case_labels(&item.labels, item.span)]; + let mut item_docs = vec![self.case_labels(&item.labels, &item.before_colon, item.span)]; self.gen_block(&mut item_docs, &item.body, depth + 1); body.push(concat(item_docs)); body.extend(self.trailing(&item.meta)); @@ -2178,7 +2555,9 @@ impl<'a> Fmt<'a> { fn for_step(&self, step: &ForStep) -> Doc { match step { ForStep::Assign(a) => { - concat(vec![self.expr(&a.lhs), text(format!(" {} ", a.op)), self.expr(&a.rhs)]) + let mut docs = Vec::new(); + self.simple_assign(a, &mut docs); + concat(docs) } ForStep::Expr(e) => self.expr(e), } @@ -2188,46 +2567,66 @@ impl<'a> Fmt<'a> { // Functions and tasks // ------------------------------------------------------------------ - fn tf_args(&self, args: &[TfArg]) -> Doc { + fn tf_args(&self, args: &[TfArg], dangling: &[Comment]) -> Doc { let items: Vec = args .iter() .map(|a| { let mut docs = Vec::new(); if let Some(dir) = &a.dir { - docs.push(text(format!("{dir} "))); + docs.push(text(dir.clone())); + if a.after_dir.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&a.after_dir, &mut docs); + } } if let Some(t) = self.data_type(&a.ty) { docs.push(t); - docs.push(text(" ")); + if a.before_name.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&a.before_name, &mut docs); + } + } else { + self.slot_comments(&a.before_name, &mut docs); } docs.push(name_doc(&a.name)); docs.extend(self.unpacked_dims(&a.unpacked)); if let Some(d) = &a.default { - docs.push(text(" = ")); + self.slot_comments(&a.eq_comments.before, &mut docs); + docs.push(text(if a.eq_comments.before.is_empty() { " =" } else { "=" })); + if a.eq_comments.after.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&a.eq_comments.after, &mut docs); + } docs.push(self.expr(d)); } ListItem::from_meta(&a.meta, concat(docs)) }) .collect(); - self.delimited("(", items, ")", false) + self.delimited_dangling("(", items, dangling, ")", false) } /// A class: header on one line (its parameter and `extends` override /// lists break like any other list when they do not fit), body items at /// one more indent level, `endclass` with the label the source wrote. fn class(&self, c: &ClassDecl, depth: usize) -> Doc { - let mut head = String::new(); - for q in &c.prefix { - head.push_str(q); - head.push(' '); + let mut docs = Vec::new(); + self.qualifier_run(&c.prefix, &mut docs); + docs.push(text("class")); + // `class /*c*/ c` — and, when a lifetime was written, whatever stood + // on either side of it; both gaps land in the one slot, which prints + // between the keyword run and the name. + if c.before_name.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&c.before_name, &mut docs); } - head.push_str("class "); if let Some(lifetime) = &c.lifetime { - head.push_str(lifetime); - head.push(' '); + docs.push(text(format!("{lifetime} "))); } - head.push_str(&named(&c.name)); - let mut docs = vec![text(head)]; + docs.push(text(named(&c.name))); let on_fresh_line = self.bracket_comments(&c.param_comments, &mut docs, false); if let Some(params) = &c.param_ports { let items: Vec = params @@ -2237,6 +2636,7 @@ impl<'a> Fmt<'a> { let items = self.list_entries(items, &c.param_directives); let broken = !c.param_directives.is_empty(); docs.push(text(if on_fresh_line { "#" } else { " #" })); + self.slot_comments(&c.param_after_hash, &mut docs); docs.push(self.delimited_dangling("(", items, &c.param_dangling, ")", broken)); } if let Some(ext) = &c.extends { @@ -2250,13 +2650,14 @@ impl<'a> Fmt<'a> { let items = self.list_entries(items, &ext.param_directives); let broken = !ext.param_directives.is_empty(); docs.push(text(if fresh { "#" } else { " #" })); + self.slot_comments(&ext.after_hash, &mut docs); docs.push(self.delimited("(", items, ")", broken)); } } if !c.implements.is_empty() { docs.push(text(format!(" implements {}", join_names(&c.implements)))); } - docs.push(text(";")); + docs.push(self.semi(&c.before_semi)); let mut body = Vec::new(); if !c.items.is_empty() { body.push(Doc::HardLine); @@ -2265,7 +2666,7 @@ impl<'a> Fmt<'a> { body.extend(self.dangling(&c.dangling)); docs.push(indent(body)); docs.push(Doc::HardLine); - docs.push(Self::closing("endclass", &c.end_label)); + docs.push(self.closing_labeled("endclass", &c.end_label, &c.end_label_comments)); concat(docs) } @@ -2346,7 +2747,7 @@ impl<'a> Fmt<'a> { docs.push(indent(body)); if c.has_end { docs.push(Doc::HardLine); - docs.push(Self::closing("endclocking", &c.end_label)); + docs.push(self.closing_labeled("endclocking", &c.end_label, &c.end_label_comments)); } concat(docs) } @@ -2413,7 +2814,7 @@ impl<'a> Fmt<'a> { fn let_decl(&self, l: &LetDecl) -> Doc { let mut docs = vec![text(format!("let {}", named(&l.name)))]; if l.has_parens { - docs.push(self.tf_args(&l.ports)); + docs.push(self.tf_args(&l.ports, &[])); } docs.push(text(" =")); docs.push(self.assign_rhs(self.expr(&l.value))); @@ -2425,27 +2826,37 @@ impl<'a> Fmt<'a> { if let Some(d) = &f.dpi { header.push(text(dpi_import_prefix(d))); } - for q in &f.prefix { - header.push(text(format!("{q} "))); - } - header.push(text("function ")); - for q in &f.qualifiers { - header.push(text(format!("{q} "))); + self.qualifier_run(&f.prefix, &mut header); + header.push(text("function")); + if f.after_kw.is_empty() { + header.push(text(" ")); + } else { + self.inline_comments_spaced(&f.after_kw, &mut header); } + self.qualifier_run(&f.qualifiers, &mut header); + let mut named_ret = false; if let Some(ret) = &f.ret { if let Some(t) = self.data_type(ret) { header.push(t); - header.push(text(" ")); + named_ret = true; } } - if let Some(scope) = &f.scope { - header.push(text(format!("{}::", named(scope)))); + if named_ret { + if f.before_name.is_empty() { + header.push(text(" ")); + } else { + self.inline_comments_spaced(&f.before_name, &mut header); + } + } else { + self.slot_comments(&f.before_name, &mut header); } + self.scope_prefix(&f.scope, &mut header); header.push(name_doc(&f.name)); if f.has_parens { - header.push(self.tf_args(&f.args)); + self.slot_comments(&f.before_args, &mut header); + header.push(self.tf_args(&f.args, &f.args_dangling)); } - header.push(text(";")); + header.push(self.semi(&f.before_semi)); // A prototype (`extern`/`pure virtual`) is the header and nothing // else: no body, no `endfunction`. if f.is_prototype { @@ -2461,7 +2872,7 @@ impl<'a> Fmt<'a> { concat(header), indent(body), Doc::HardLine, - Self::closing("endfunction", &f.end_label), + self.closing_labeled("endfunction", &f.end_label, &f.end_label_comments), text(if f.end_semi { ";" } else { "" }), ]) } @@ -2471,21 +2882,22 @@ impl<'a> Fmt<'a> { if let Some(d) = &t.dpi { header.push(text(dpi_import_prefix(d))); } - for q in &t.prefix { - header.push(text(format!("{q} "))); - } - header.push(text("task ")); - for q in &t.qualifiers { - header.push(text(format!("{q} "))); - } - if let Some(scope) = &t.scope { - header.push(text(format!("{}::", named(scope)))); + self.qualifier_run(&t.prefix, &mut header); + header.push(text("task")); + if t.after_kw.is_empty() { + header.push(text(" ")); + } else { + self.inline_comments_spaced(&t.after_kw, &mut header); } + self.qualifier_run(&t.qualifiers, &mut header); + self.slot_comments(&t.before_name, &mut header); + self.scope_prefix(&t.scope, &mut header); header.push(name_doc(&t.name)); if t.has_parens { - header.push(self.tf_args(&t.args)); + self.slot_comments(&t.before_args, &mut header); + header.push(self.tf_args(&t.args, &t.args_dangling)); } - header.push(text(";")); + header.push(self.semi(&t.before_semi)); if t.is_prototype { return concat(header); } @@ -2499,7 +2911,7 @@ impl<'a> Fmt<'a> { concat(header), indent(body), Doc::HardLine, - Self::closing("endtask", &t.end_label), + self.closing_labeled("endtask", &t.end_label, &t.end_label_comments), text(if t.end_semi { ";" } else { "" }), ]) } @@ -2519,20 +2931,12 @@ impl<'a> Fmt<'a> { /// it is navigable, one canonical shape is worth exactly what canonical /// shapes are always worth. fn constraint(&self, c: &ConstraintDecl) -> Doc { - let mut head = String::new(); - for q in &c.qualifiers { - head.push_str(q); - head.push(' '); - } - head.push_str("constraint"); - let mut docs = vec![text(head)]; + let mut docs = Vec::new(); + self.qualifier_run(&c.qualifiers, &mut docs); + docs.push(text("constraint")); self.inline_comments_spaced(&c.before_name, &mut docs); - let mut name = String::new(); - if let Some(scope) = &c.scope { - name.push_str(&named(scope)); - name.push_str("::"); - } - name.push_str(&named(&c.name.text)); + self.scope_prefix(&c.scope, &mut docs); + let name = named(&c.name.text); // `named` already wrote the space an escaped identifier needs; a // second one would be a gratuitous re-spacing of the header. let escaped = name.ends_with(' '); @@ -2693,7 +3097,7 @@ impl<'a> Fmt<'a> { } concat(docs) } - ConstraintItemKind::Foreach { array, vars, comments, set } => { + ConstraintItemKind::Foreach { array, vars, var_comments, comments, set } => { let mut head = vec![text("foreach")]; self.inline_comments_spaced(&comments.after_kw, &mut head); head.push(text("(")); @@ -2702,7 +3106,7 @@ impl<'a> Fmt<'a> { head.push(text(" ")); } head.push(self.expr(array)); - head.push(text(format!("[{}]", join_names(vars)))); + head.push(self.foreach_vars(vars, var_comments)); if self.inline_comments(&comments.before_close, &mut head) { head.push(Doc::HardLine); } else if !comments.before_close.is_empty() { @@ -2877,20 +3281,16 @@ impl<'a> Fmt<'a> { /// further indent, and `endgroup` back at the header's column with /// whatever label the source wrote. fn covergroup(&self, c: &CovergroupDecl) -> Doc { - let mut head = String::new(); - for q in &c.qualifiers { - head.push_str(q); - head.push(' '); - } - head.push_str("covergroup"); - let mut docs = vec![text(head)]; + let mut docs = Vec::new(); + self.qualifier_run(&c.qualifiers, &mut docs); + docs.push(text("covergroup")); self.inline_comments_spaced(&c.before_name, &mut docs); docs.push(name_doc(&c.name.text)); if let Some(args) = &c.args { if !c.before_args.is_empty() { self.inline_comments_spaced(&c.before_args, &mut docs); } - docs.push(self.tf_args(args)); + docs.push(self.tf_args(args, &[])); } match &c.event { Some(CoverageEvent::Sample(s)) => { @@ -2904,7 +3304,7 @@ impl<'a> Fmt<'a> { if !s.before_args.is_empty() { self.inline_comments_spaced(&s.before_args, &mut docs); } - docs.push(self.tf_args(&s.args)); + docs.push(self.tf_args(&s.args, &[])); } } Some(CoverageEvent::Clocking { before, sens }) => { @@ -2925,10 +3325,8 @@ impl<'a> Fmt<'a> { body.extend(self.dangling(&c.dangling)); docs.push(indent(body)); docs.push(Doc::HardLine); - docs.push(match &c.end_label { - Some(l) => text(format!("endgroup : {}", named(&l.text))), - None => text("endgroup"), - }); + let end_label = c.end_label.as_ref().map(|l| l.text.clone()); + docs.push(self.closing_labeled("endgroup", &end_label, &c.end_label_comments)); if c.end_semi { if self.inline_comments(&c.before_end_semi, &mut docs) { docs.push(Doc::HardLine); @@ -3284,7 +3682,25 @@ impl<'a> Fmt<'a> { // ------------------------------------------------------------------ fn stmt(&self, s: &Stmt) -> Doc { - self.with_meta(&s.meta, self.stmt_kind(&s.kind)) + self.with_meta(&s.meta, self.stmt_kind(&s.kind, &s.before_semi)) + } + + /// The `;` that ends a statement, with whatever the source wrote in front + /// of it (`x = 1 /* inclusive */ ;`). [`StmtKind::takes_semi`] is what + /// says which kinds reach this; every other one prints its own `;` as + /// part of a body it does not own the end of. + fn semi(&self, before_semi: &[Comment]) -> Doc { + if before_semi.is_empty() { + return text(";"); + } + let mut docs = Vec::new(); + if self.inline_comments(before_semi, &mut docs) { + docs.push(Doc::HardLine); + } else { + docs.push(text(" ")); + } + docs.push(text(";")); + concat(docs) } /// Prefix (e.g. `always_ff`, `if (...)`) followed by a body statement: @@ -3299,10 +3715,25 @@ impl<'a> Fmt<'a> { /// [`Fmt::header_parens`]. fn stmt_as_body_from(&self, prefix: Doc, s: &Stmt, skip: usize) -> Doc { match &s.kind { - StmtKind::Block { label, stmts, dangling, end_label, .. } => { + StmtKind::Block { + label_comments, + label, + stmts, + dangling, + end_label_comments, + end_label, + .. + } => { let mut docs = vec![prefix, text(" ")]; docs.extend(self.leading_from(&s.meta, skip)); - docs.push(self.block_doc(label, stmts, dangling, end_label)); + docs.push(self.block_doc(BlockDoc { + label_comments, + label, + stmts, + dangling, + end_label_comments, + end_label, + })); docs.extend(self.trailing(&s.meta)); concat(docs) } @@ -3318,39 +3749,36 @@ impl<'a> Fmt<'a> { // The same three parts `stmt` prints, with the skip applied. _ => { let mut body = self.leading_from(&s.meta, skip); - body.push(self.stmt_kind(&s.kind)); + body.push(self.stmt_kind(&s.kind, &s.before_semi)); body.extend(self.trailing(&s.meta)); group(vec![prefix, indent(vec![Doc::Line, concat(body)])]) } } } - fn block_doc( - &self, - label: &Option, - stmts: &[Stmt], - dangling: &[Comment], - end_label: &Option, - ) -> Doc { - let mut docs = vec![match label { - Some(l) => text(format!("begin : {}", named(l))), - None => text("begin"), - }]; + fn block_doc(&self, b: BlockDoc<'_>) -> Doc { + let mut docs = vec![text("begin")]; + self.label_tail(b.label, b.label_comments, &mut docs); let mut body = Vec::new(); - if !stmts.is_empty() { + if !b.stmts.is_empty() { body.push(Doc::HardLine); - body.extend(self.stmt_seq(stmts)); + body.extend(self.stmt_seq(b.stmts)); } - body.extend(self.dangling(dangling)); + body.extend(self.dangling(b.dangling)); docs.push(indent(body)); docs.push(Doc::HardLine); - docs.push(Self::closing("end", end_label)); + docs.push(self.closing_labeled("end", b.end_label, b.end_label_comments)); concat(docs) } fn timing_control(&self, tc: &TimingControl) -> Doc { match tc { - TimingControl::Delay(e) => concat(vec![text("#"), self.expr(e)]), + TimingControl::Delay { after_hash, expr } => { + let mut docs = vec![text("#")]; + self.slot_comments(after_hash, &mut docs); + docs.push(self.expr(expr)); + concat(docs) + } TimingControl::Event(sens) => self.sens_list(sens), } } @@ -3359,7 +3787,12 @@ impl<'a> Fmt<'a> { 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::Bare { expr, after_at } => { + let mut docs = vec![text("@")]; + self.slot_comments(after_at, &mut docs); + docs.push(self.expr(expr)); + concat(docs) + } SensList::Star { before, after } => { if before.is_empty() && after.is_empty() { return text("@(*)"); @@ -3386,7 +3819,7 @@ impl<'a> Fmt<'a> { } concat(vec![text("@("), indent(inner), text(")")]) } - SensList::List(items) => { + SensList::List { items, after_at } => { // Each separator is printed as it was written: `,` and `or` // mean the same thing but are different tokens, and rewriting // one as the other is a token change the safety net rejects. @@ -3406,7 +3839,12 @@ impl<'a> Fmt<'a> { }); } if let Some(e) = &i.edge { - parts.push(text(format!("{e} "))); + parts.push(text(e.clone())); + if i.after_edge.is_empty() { + parts.push(text(" ")); + } else { + self.inline_comments_spaced(&i.after_edge, &mut parts); + } } parts.push(self.expr(&i.expr)); // `posedge clk iff enable` — the gate belongs to this @@ -3419,7 +3857,9 @@ impl<'a> Fmt<'a> { parts.push(Doc::HardLine); } } - let mut docs = vec![text("@(")]; + let mut docs = vec![text("@")]; + self.slot_comments(after_at, &mut docs); + docs.push(text("(")); docs.push(group(vec![indent(vec![Doc::SoftLine, concat(parts)]), Doc::SoftLine])); docs.push(text(")")); concat(docs) @@ -3427,16 +3867,36 @@ impl<'a> Fmt<'a> { } } - fn stmt_kind(&self, kind: &StmtKind) -> Doc { + fn stmt_kind(&self, kind: &StmtKind, before_semi: &[Comment]) -> Doc { match kind { - StmtKind::Block { label, stmts, dangling, end_label, .. } => { - self.block_doc(label, stmts, dangling, end_label) - } - StmtKind::ForkJoin { label, join_kw, stmts, dangling, end_label, .. } => { - let mut docs = vec![match label { - Some(l) => text(format!("fork : {}", named(l))), - None => text("fork"), - }]; + StmtKind::Block { + label_comments, + label, + stmts, + dangling, + end_label_comments, + end_label, + .. + } => self.block_doc(BlockDoc { + label_comments, + label, + stmts, + dangling, + end_label_comments, + end_label, + }), + StmtKind::ForkJoin { + label_comments, + label, + join_kw, + stmts, + dangling, + end_label_comments, + end_label, + .. + } => { + let mut docs = vec![text("fork")]; + self.label_tail(label, label_comments, &mut docs); let mut body = Vec::new(); if !stmts.is_empty() { body.push(Doc::HardLine); @@ -3445,25 +3905,23 @@ impl<'a> Fmt<'a> { body.extend(self.dangling(dangling)); docs.push(indent(body)); docs.push(Doc::HardLine); - docs.push(Self::closing(join_kw, end_label)); + docs.push(self.closing_labeled(join_kw, end_label, end_label_comments)); concat(docs) } - StmtKind::If { qualifier, cond, then, else_comments, els } => { - self.if_stmt(qualifier, cond, then, else_comments, els) + StmtKind::If { qualifier, after_kw, cond, then, else_comments, els } => { + self.if_stmt(qualifier, after_kw, cond, then, else_comments, els) } - StmtKind::Case { qualifier, kw, expr, inside, items, dangling } => { - let mut head = String::new(); + StmtKind::Case { qualifier, kw, after_kw, expr, inside, items, dangling } => { + let mut docs = Vec::new(); if let Some(q) = qualifier { - head.push_str(q); - head.push(' '); + docs.push(text(format!("{q} "))); } - head.push_str(kw); - head.push(' '); + self.word_then(kw, after_kw, &mut docs); let (parens, taken) = match items.first() { Some(first) => self.header_parens(expr, &first.meta), None => (self.parens(expr), 0), }; - let mut docs = vec![text(head), parens]; + docs.push(parens); if *inside { docs.push(text(" inside")); } @@ -3475,8 +3933,9 @@ impl<'a> Fmt<'a> { StmtKind::RandCase { items, dangling } => { concat(vec![text("randcase"), self.case_body(items, dangling, 0)]) } - StmtKind::For { init, cond, step, body } => { - let mut header = vec![text("for (")]; + StmtKind::For { init, cond, step, comments, body } => { + let mut header = Vec::new(); + self.for_open(comments, &mut header); let init_parts: Vec = init .iter() .map(|fi| { @@ -3484,23 +3943,32 @@ impl<'a> Fmt<'a> { if let Some(ty) = &fi.ty { if let Some(t) = self.data_type(ty) { d.push(t); - d.push(text(" ")); + if fi.before_name.is_empty() { + d.push(text(" ")); + } else { + self.inline_comments_spaced(&fi.before_name, &mut d); + } } + } else { + self.slot_comments(&fi.before_name, &mut d); } - d.push(self.expr(&fi.assign.lhs)); - d.push(text(format!(" {} ", fi.assign.op))); - d.push(self.expr(&fi.assign.rhs)); + self.simple_assign(&fi.assign, &mut d); concat(d) }) .collect(); header.extend(join(init_parts, text(", "))); - header.push(text("; ")); + self.for_semi(&comments.before_first_semi, &comments.after_first_semi, &mut header); if let Some(c) = cond { header.push(self.expr(c)); } - header.push(text("; ")); + self.for_semi( + &comments.before_second_semi, + &comments.after_second_semi, + &mut header, + ); let step_parts: Vec = step.iter().map(|s| self.for_step(s)).collect(); header.extend(join(step_parts, text(", "))); + self.slot_comments(&comments.before_close, &mut header); header.push(text(")")); self.stmt_as_body(concat(header), body) } @@ -3508,22 +3976,38 @@ impl<'a> Fmt<'a> { let (parens, taken) = self.header_parens(cond, &body.meta); self.stmt_as_body_from(concat(vec![text("while "), parens]), body, taken) } - StmtKind::DoWhile { body, cond } => { + StmtKind::DoWhile { body, cond, comments } => { let mut docs = vec![text("do")]; match &body.kind { - StmtKind::Block { label, stmts, dangling, end_label, .. } => { + StmtKind::Block { + label_comments, + label, + stmts, + dangling, + end_label_comments, + end_label, + .. + } => { docs.push(text(" ")); - docs.push(self.block_doc(label, stmts, dangling, end_label)); - docs.push(text(" while ")); + docs.push(self.block_doc(BlockDoc { + label_comments, + label, + stmts, + dangling, + end_label_comments, + end_label, + })); + docs.push(text(" ")); + self.word_then("while", &comments.after_kw, &mut docs); } _ => { docs.push(group(vec![indent(vec![Doc::Line, self.stmt(body)])])); docs.push(Doc::HardLine); - docs.push(text("while ")); + self.word_then("while", &comments.after_kw, &mut docs); } } - docs.push(self.parens(cond)); - docs.push(text(";")); + docs.push(self.header_slots(cond, comments)); + docs.push(self.semi(before_semi)); concat(docs) } StmtKind::Repeat { count, body } => { @@ -3531,13 +4015,19 @@ impl<'a> Fmt<'a> { self.stmt_as_body_from(concat(vec![text("repeat "), parens]), body, taken) } StmtKind::Forever { body } => self.stmt_as_body(text("forever"), body), - StmtKind::Foreach { target, vars, body } => { - let head = concat(vec![ - text("foreach ("), - self.expr(target), - text(format!("[{}])", join_names(vars))), - ]); - self.stmt_as_body(head, body) + StmtKind::Foreach { target, vars, var_comments, comments, body } => { + let mut head = vec![text("foreach")]; + self.slot_comments(&comments.after_kw, &mut head); + if comments.after_kw.is_empty() { + head.push(text(" ")); + } + head.push(text("(")); + self.slot_comments(&comments.after_open, &mut head); + head.push(self.expr(target)); + head.push(self.foreach_vars(vars, var_comments)); + self.slot_comments(&comments.before_close, &mut head); + head.push(text(")")); + self.stmt_as_body(concat(head), body) } StmtKind::Assign { lhs, op, op_comments, rhs_comments, timing, rhs } => { let mut docs = vec![self.expr(lhs)]; @@ -3567,7 +4057,7 @@ impl<'a> Fmt<'a> { inner.push(concat(rhs_docs)); docs.push(indent(inner)); } - concat(vec![group(docs), text(";")]) + concat(vec![group(docs), self.semi(before_semi)]) } StmtKind::ForceRelease { kw, lhs, rhs } => { let mut docs = vec![text(format!("{kw} ")), self.expr(lhs)]; @@ -3575,14 +4065,14 @@ impl<'a> Fmt<'a> { docs.push(text(" = ")); docs.push(self.expr(r)); } - docs.push(text(";")); + docs.push(self.semi(before_semi)); concat(docs) } StmtKind::Timing { control, stmt } => { let control_doc = self.timing_control(control); match stmt { Some(s) => self.stmt_as_body(control_doc, s), - None => concat(vec![control_doc, text(";")]), + None => concat(vec![control_doc, self.semi(before_semi)]), } } StmtKind::Wait { cond, stmt } => match stmt { @@ -3590,23 +4080,35 @@ impl<'a> Fmt<'a> { let (parens, taken) = self.header_parens(cond, &s.meta); self.stmt_as_body_from(concat(vec![text("wait "), parens]), s, taken) } - None => concat(vec![text("wait "), self.parens(cond), text(";")]), + None => concat(vec![text("wait "), self.parens(cond), self.semi(before_semi)]), }, - StmtKind::ExprStmt(e) => concat(vec![self.expr(e), text(";")]), - StmtKind::EventTrigger(e) => concat(vec![text("-> "), self.expr(e), text(";")]), - StmtKind::VarDecl(d) => concat(vec![self.data_decl(d), text(";")]), + StmtKind::ExprStmt(e) => concat(vec![self.expr(e), self.semi(before_semi)]), + StmtKind::EventTrigger(e) => { + concat(vec![text("-> "), self.expr(e), self.semi(before_semi)]) + } + StmtKind::VarDecl(d) => concat(vec![self.data_decl(d), self.semi(before_semi)]), // The item form prints its own `;`. StmtKind::Typedef(t) => self.typedef(t), - StmtKind::ParamDecl(d) => concat(vec![self.param_decl(d, None), text(";")]), - StmtKind::PortDecl(d) => concat(vec![self.port_decl(d), text(";")]), - StmtKind::Return(e) => match e { - Some(e) => concat(vec![text("return "), self.expr(e), text(";")]), - None => text("return;"), + StmtKind::ParamDecl(d) => { + concat(vec![self.param_decl(d, None), self.semi(before_semi)]) + } + StmtKind::PortDecl(d) => concat(vec![self.port_decl(d), self.semi(before_semi)]), + StmtKind::Return { after_kw, expr } => match expr { + Some(e) => { + let mut docs = Vec::new(); + self.word_then("return", after_kw, &mut docs); + docs.push(self.expr(e)); + docs.push(self.semi(before_semi)); + concat(docs) + } + None => concat(vec![text("return"), self.semi(before_semi)]), }, - StmtKind::Break => text("break;"), - StmtKind::Continue => text("continue;"), - StmtKind::Disable(name) => text(format!("disable {};", named(name))), - StmtKind::WaitFork => text("wait fork;"), + StmtKind::Break => concat(vec![text("break"), self.semi(before_semi)]), + StmtKind::Continue => concat(vec![text("continue"), self.semi(before_semi)]), + StmtKind::Disable(name) => { + concat(vec![text(format!("disable {}", named(name))), self.semi(before_semi)]) + } + StmtKind::WaitFork => concat(vec![text("wait fork"), self.semi(before_semi)]), StmtKind::Import(paths) => text(format!("import {};", join_paths(paths))), // A statement label prints tight against its `:`, the way a case // label does: `check_decode: assert (...)`. @@ -3623,7 +4125,7 @@ impl<'a> Fmt<'a> { StmtKind::Assert { kw, cond, then, els } => { let mut docs = vec![text(format!("{kw} ")), self.parens(cond)]; match (then, els) { - (None, None) => docs.push(text(";")), + (None, None) => docs.push(self.semi(before_semi)), (Some(t), None) => { docs.push(group(vec![indent(vec![Doc::Line, self.stmt(t)])])); } @@ -3647,19 +4149,20 @@ impl<'a> Fmt<'a> { fn if_stmt( &self, qualifier: &Option, + after_kw: &[Comment], cond: &Expr, then: &Stmt, else_comments: &[Comment], els: &Option>, ) -> Doc { - let mut head = String::new(); + let mut head = Vec::new(); if let Some(q) = qualifier { - head.push_str(q); - head.push(' '); + head.push(text(format!("{q} "))); } - head.push_str("if "); + self.word_then("if", after_kw, &mut head); let (parens, taken) = self.header_parens(cond, &then.meta); - let prefix = concat(vec![text(head), parens]); + head.push(parens); + let prefix = concat(head); // A line comment trailing the then-branch runs to end of line, so a // cuddled `else` would be swallowed into its text. let then_is_block = @@ -3683,13 +4186,19 @@ impl<'a> Fmt<'a> { docs.push(text("else")); } // `else if` chains stay flat. - if let StmtKind::If { qualifier: eq, cond: ec, then: et, else_comments: ecm, els: ee } = - &els.kind + if let StmtKind::If { + qualifier: eq, + after_kw: ea, + cond: ec, + then: et, + else_comments: ecm, + els: ee, + } = &els.kind { docs.push(text(" ")); let mut meta_docs = self.leading(&els.meta); docs.append(&mut meta_docs); - docs.push(self.if_stmt(eq, ec, et, ecm, ee)); + docs.push(self.if_stmt(eq, ea, ec, et, ecm, ee)); docs.extend(self.trailing(&els.meta)); } else { docs.push(self.stmt_as_body(text(""), els)); @@ -3702,9 +4211,15 @@ impl<'a> Fmt<'a> { /// Labels normally share one line; as soon as any of them carries a /// comment they go one per line, so a comment written between two labels /// is printed between the same two labels instead of drifting past them. - fn case_labels(&self, labels: &[ExprItem], item: TextRange) -> Doc { + fn case_labels(&self, labels: &[ExprItem], before_colon: &[Comment], item: TextRange) -> Doc { if labels.is_empty() { - return text(if self.default_has_colon(item) { "default:" } else { "default" }); + if !self.default_has_colon(item) { + return text("default"); + } + let mut docs = vec![text("default")]; + self.slot_comments(before_colon, &mut docs); + docs.push(text(":")); + return concat(docs); } let plain = labels.iter().all(|l| { l.meta.leading.is_empty() && l.meta.before_sep.is_empty() && l.meta.trailing.is_none() @@ -3756,7 +4271,7 @@ impl<'a> Fmt<'a> { { return text("default;"); } - self.stmt_as_body(self.case_labels(&item.labels, item.span), &item.stmt) + self.stmt_as_body(self.case_labels(&item.labels, &item.before_colon, item.span), &item.stmt) } /// The items of a `case`/`randcase` body. `skip` is the number of leading @@ -3807,7 +4322,12 @@ impl<'a> Fmt<'a> { ExprKind::Str(s) => text(s.clone()), // Only reachable through `connection`, which handles the comments. ExprKind::Empty(_) => text(""), - ExprKind::Unary { op, expr } => concat(vec![text(op.clone()), self.expr(expr)]), + ExprKind::Unary { op, comments, expr } => { + let mut docs = vec![text(op.clone())]; + self.slot_comments(comments, &mut docs); + docs.push(self.expr(expr)); + concat(docs) + } ExprKind::Binary { .. } => self.binary_chain(e), ExprKind::Ternary { cond, then, els, comments } => { if comments.is_empty() { @@ -3845,22 +4365,27 @@ impl<'a> Fmt<'a> { // `new src` — one space, never a break: the source handle is a // postfix expression that breaks internally if it must. ExprKind::New(src) => concat(vec![text("new "), self.expr(src)]), - ExprKind::Index { base, index } => { - concat(vec![self.expr(base), text("["), self.expr_compact(index), text("]")]) + ExprKind::Index { base, index, comments } => { + let mut docs = vec![self.expr(base)]; + self.slot_comments(&comments.before_open, &mut docs); + docs.push(self.bracket_slots(comments, self.expr_compact(index), None)); + concat(docs) } - ExprKind::Range { base, op, msb, lsb } => concat(vec![ - self.expr(base), - text("["), - self.expr_compact(msb), - text(op.clone()), - self.expr_compact(lsb), - text("]"), - ]), - ExprKind::Member { base, name } => { - concat(vec![self.expr(base), text(format!(".{}", named(name)))]) + ExprKind::Range { base, op, msb, lsb, comments } => { + let mut docs = vec![self.expr(base)]; + self.slot_comments(&comments.before_open, &mut docs); + docs.push(self.bracket_slots( + comments, + self.expr_compact(msb), + Some((op, self.expr_compact(lsb))), + )); + concat(docs) } - ExprKind::Scope { base, name } => { - concat(vec![self.expr(base), text(format!("::{}", named(name)))]) + ExprKind::Member { base, name, comments } => { + self.chain_segment(base, ".", name, comments) + } + ExprKind::Scope { base, name, comments } => { + self.chain_segment(base, "::", name, comments) } // Written tight, like the `::` it almost always precedes. ExprKind::Parameterized { base, params } => { @@ -3893,11 +4418,27 @@ impl<'a> Fmt<'a> { } // `ty'{...}` prints no brackets of its own: the assignment // pattern already carries the `'{` and the `}`. - ExprKind::Cast { ty, expr, pattern: true } => { - concat(vec![self.expr(ty), self.expr(expr)]) + ExprKind::Cast { ty, comments, expr, pattern: true } => { + let mut docs = vec![self.expr(ty)]; + self.slot_comments(&comments.before_tick, &mut docs); + self.slot_comments(&comments.after_tick, &mut docs); + docs.push(self.expr(expr)); + concat(docs) } - ExprKind::Cast { ty, expr, .. } => { - concat(vec![self.expr(ty), text("'("), self.expr(expr), text(")")]) + ExprKind::Cast { ty, comments, expr, .. } => { + if comments.is_empty() { + return concat(vec![self.expr(ty), text("'("), self.expr(expr), text(")")]); + } + let mut docs = vec![self.expr(ty)]; + self.slot_comments(&comments.before_tick, &mut docs); + docs.push(text("'")); + self.slot_comments(&comments.after_tick, &mut docs); + docs.push(text("(")); + self.slot_comments(&comments.after_open, &mut docs); + docs.push(self.expr(expr)); + self.slot_comments(&comments.before_close, &mut docs); + docs.push(text(")")); + concat(docs) } ExprKind::AssignPattern(items) => { let items: Vec = items @@ -3921,7 +4462,12 @@ impl<'a> Fmt<'a> { self.expr_list("{", inner, "}"), text("}"), ]), - ExprKind::Postfix { expr, op } => concat(vec![self.expr(expr), text(op.clone())]), + ExprKind::Postfix { expr, op, comments } => { + let mut docs = vec![self.expr(expr)]; + self.slot_comments(comments, &mut docs); + docs.push(text(op.clone())); + concat(docs) + } ExprKind::With { base, arg, comments } => { concat(vec![self.with_head(base, comments), self.expr(arg)]) } @@ -3933,17 +4479,24 @@ impl<'a> Fmt<'a> { concat(vec![self.with_head(base, comments), body]) } ExprKind::Dist { expr, comments, weights } => self.dist(expr, comments, weights), - ExprKind::Inside { lhs, ranges } => { - concat(vec![self.expr(lhs), text(" inside "), self.expr_list("{", ranges, "}")]) + ExprKind::Inside { lhs, ranges, comments } => { + self.inside_head(lhs, comments, self.expr_list("{", ranges, "}")) } - ExprKind::InsideMacro { lhs, set } => { - concat(vec![self.expr(lhs), text(" inside "), text(set.clone())]) + ExprKind::InsideMacro { lhs, set, comments } => { + self.inside_head(lhs, comments, text(set.clone())) } // 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!(".{}(", named(name)))]; + ExprKind::NamedArg { name, value, comments, .. } => match &value.kind { + ExprKind::Empty(inner) => { + let comments_inner = inner; + let mut docs = vec![text(".")]; + self.slot_comments(&comments.after_dot, &mut docs); + docs.push(text(named(name))); + self.slot_comments(&comments.before_open, &mut docs); + docs.push(text("(")); + self.slot_comments(&comments.after_open, &mut docs); + let comments = comments_inner; let mut ends_line = false; for cm in comments { if ends_line { @@ -3960,17 +4513,21 @@ impl<'a> Fmt<'a> { } _ => { let mut inner = vec![Doc::SoftLine, self.expr(value)]; - let ends_line = self.inline_comments(close_comments, &mut inner); + let ends_line = self.inline_comments(&comments.close, &mut inner); let close = if ends_line { Doc::HardLine } else { Doc::SoftLine }; - concat(vec![ - text(format!(".{}(", named(name))), - group(vec![indent(inner), close]), - text(")"), - ]) + let mut docs = vec![text(".")]; + self.slot_comments(&comments.after_dot, &mut docs); + docs.push(text(named(name))); + self.slot_comments(&comments.before_open, &mut docs); + docs.push(text("(")); + self.slot_comments(&comments.after_open, &mut docs); + docs.push(group(vec![indent(inner), close])); + docs.push(text(")")); + concat(docs) } }, - ExprKind::ValueRange { lo, hi } => { - concat(vec![text("["), self.expr(lo), text(":"), self.expr(hi), text("]")]) + ExprKind::ValueRange { lo, hi, comments } => { + self.bracket_slots(comments, self.expr(lo), Some((":", self.expr(hi)))) } ExprKind::Type(ty) => self.data_type(ty).unwrap_or_else(|| text("")), ExprKind::MinTypMax { min, typ, max } => { @@ -3979,6 +4536,71 @@ impl<'a> Fmt<'a> { } } + /// The `[i, j]` of a `foreach` header — the one bracket group that + /// declares loop variables — with every comment written in it printed + /// back between the two tokens it was written between. + /// + /// Shared by the statement `foreach` and the constraint one, which write + /// the same grammar. + fn foreach_vars(&self, vars: &[ForeachVar], comments: &SegmentComments) -> Doc { + if comments.is_empty() && vars.iter().all(|v| v.before.is_empty() && v.after.is_empty()) { + let names: Vec = vars.iter().map(|v| v.name.clone()).collect(); + return text(format!("[{}]", join_names(&names))); + } + let mut docs = Vec::new(); + self.slot_comments(&comments.before_open, &mut docs); + docs.push(text("[")); + self.slot_comments(&comments.after_open, &mut docs); + for (i, v) in vars.iter().enumerate() { + if i > 0 { + docs.push(text(",")); + } + self.slot_comments(&v.before, &mut docs); + if i > 0 && v.before.is_empty() { + docs.push(text(" ")); + } + docs.push(text(named(&v.name.text))); + self.slot_comments(&v.after, &mut docs); + } + self.slot_comments(&comments.before_close, &mut docs); + docs.push(text("]")); + concat(docs) + } + + /// `base.name` / `base::name`, with the comments the source wrote on + /// either side of the joining token. + fn chain_segment( + &self, + base: &Expr, + joiner: &str, + name: &str, + comments: &SegmentComments, + ) -> Doc { + if comments.is_empty() { + return concat(vec![self.expr(base), text(format!("{joiner}{}", named(name)))]); + } + let mut docs = vec![self.expr(base)]; + self.slot_comments(&comments.before_open, &mut docs); + docs.push(text(joiner.to_string())); + self.slot_comments(&comments.after_open, &mut docs); + docs.push(text(named(name))); + concat(docs) + } + + /// `lhs inside set`, with the comments written on either side of the word + /// kept on their own side of it, as every binary operator's are. + fn inside_head(&self, lhs: &Expr, comments: &BinaryComments, set: Doc) -> Doc { + if comments.before.is_empty() && comments.after.is_empty() { + return concat(vec![self.expr(lhs), text(" inside "), set]); + } + let mut docs = vec![self.expr(lhs)]; + self.inline_comments_spaced(&comments.before, &mut docs); + docs.push(text("inside")); + self.inline_comments_spaced(&comments.after, &mut docs); + docs.push(set); + concat(docs) + } + /// A `? :` with comments written inside it. Each comment stays between the /// two tokens it was written between, and a line comment forces the break /// that follows it, so the layout can never fold a comment over the `?`, diff --git a/crates/vlog_formatter/tests/cases/comment_slots.cases b/crates/vlog_formatter/tests/cases/comment_slots.cases new file mode 100644 index 0000000..2cd1848 --- /dev/null +++ b/crates/vlog_formatter/tests/cases/comment_slots.cases @@ -0,0 +1,424 @@ +# Every comment slot `docs/features/comment-slots/README.md` added, one case +# per slot, with the comment written exactly where the slot owns it. The +# numbers in the comments are positions, not content: `/*1*/` is the first +# gap of the construct, `/*2*/` the second, and so on, so a comment that +# drifts across a token shows up as a renumbering rather than as a diff you +# have to squint at. +# +# A comment inside a bracket pair forces that pair open, which is why a few +# of these lay out across several lines. That is the same rule a comment +# inside a port list has always followed. + +# a postfix member and scope chain, both gaps of each joiner +module m; +assign y = a /*1*/ . /*2*/ b; +assign z = pkg /*3*/ :: /*4*/ item; +endmodule +---- +module m; + assign y = a /*1*/ . /*2*/ b; + assign z = pkg /*3*/ :: /*4*/ item; +endmodule +==== +# an index expression, all three of its slots +module m; +assign y = q /*1*/ [ /*2*/ i /*3*/ ]; +endmodule +---- +module m; + assign y = q /*1*/ [ /*2*/ i /*3*/ ]; +endmodule +==== +# a part-select range, all five of its slots +module m; +assign y = q /*1*/ [ /*2*/ hi /*3*/ : /*4*/ lo /*5*/ ]; +assign z = q[hi /*6*/ -: /*7*/ w]; +endmodule +---- +module m; + assign y = q /*1*/ [ /*2*/ hi /*3*/ : /*4*/ lo /*5*/ ]; + assign z = q[hi /*6*/ -: /*7*/ w]; +endmodule +==== +# a value range inside an `inside` set +module m; +assign y = a inside {[ /*1*/ 0 /*2*/ : /*3*/ 3 /*4*/ ], 7}; +endmodule +---- +module m; + assign y = a inside {[ /*1*/ 0 /*2*/ : /*3*/ 3 /*4*/ ], 7}; +endmodule +==== +# the `inside` operator keeps a comment on each of its sides +module m; +assign y = a /*1*/ inside /*2*/ {1, 2}; +endmodule +---- +module m; + assign y = a /*1*/ inside /*2*/ {1, 2}; +endmodule +==== +# a packed dimension's own five slots +module m; +logic /*1*/ [ /*2*/ 7 /*3*/ : /*4*/ 0 /*5*/ ] w; +endmodule +---- +module m; + logic /*1*/ [ /*2*/ 7 /*3*/ : /*4*/ 0 /*5*/ ] w; +endmodule +==== +# a dynamic and an associative dimension keep what stands between the brackets +module m; +int q[ /*1*/ ]; +int a[ /*2*/ * /*3*/ ]; +endmodule +---- +module m; + int q [ /*1*/ ]; + int a [ /*2*/ * /*3*/ ]; +endmodule +==== +# a statement's own `;` gap, every kind that owns one +module m; +initial begin +x = 1 /*1*/ ; +y <= 2 /*2*/ ; +f(x) /*3*/ ; +-> ev /*4*/ ; +#10 /*5*/ ; +end +endmodule +---- +module m; + initial begin + x = 1 /*1*/ ; + y <= 2 /*2*/ ; + f(x) /*3*/ ; + -> ev /*4*/ ; + #10 /*5*/ ; + end +endmodule +==== +# a `return`, a `break` and a `continue` keep the gap before their `;` +class c; +function int f(); +break /*1*/ ; +continue /*2*/ ; +return /*3*/ x /*4*/ ; +endfunction +endclass +---- +class c; + function int f(); + break /*1*/ ; + continue /*2*/ ; + return /*3*/ x /*4*/ ; + endfunction +endclass +==== +# a statement `if` header's keyword gap +module m; +initial if /*1*/ (a) x = 1; +endmodule +---- +module m; + initial if /*1*/ (a) x = 1; +endmodule +==== +# a statement `case` header's keyword gap and a `default` label's colon +module m; +always_comb begin +case /*1*/ (sel) +2'd0: y = a; +default /*2*/ : y = c; +endcase +end +endmodule +---- +module m; + always_comb begin + case /*1*/ (sel) + 2'd0: y = a; + default /*2*/ : y = c; + endcase + end +endmodule +==== +# a statement `foreach` header, all four of its slots +module m; +initial foreach /*1*/ ( /*2*/ q[i] /*3*/ ) q[i] = i; +endmodule +---- +module m; + initial foreach /*1*/ ( /*2*/ q[i] /*3*/ ) q[i] = i; +endmodule +==== +# a `foreach` loop-variable list keeps a comment between two slots +module m; +initial foreach (q[i /*1*/ , /*2*/ j]) q[i][j] = 0; +endmodule +---- +module m; + initial foreach (q[i /*1*/ , /*2*/ j]) q[i][j] = 0; +endmodule +==== +# a `for` header's seven slots +module m; +initial for /*1*/ ( /*2*/ int i = 0 /*3*/ ; /*4*/ i < N /*5*/ ; /*6*/ i++ /*7*/ ) x = i; +endmodule +---- +module m; + initial for /*1*/ ( /*2*/ int i = 0 /*3*/ ; /*4*/ i < N /*5*/ ; /*6*/ i++ /*7*/ ) x = i; +endmodule +==== +# a generate `for` header and its block label +module m; +for /*1*/ (genvar /*2*/ i = 0; i < N; i /*3*/ ++) /*4*/ begin /*5*/ : /*6*/ g +sub u (.a(a[i])); +end +endmodule +---- +module m; + for /*1*/ (genvar /*2*/ i = 0; i < N; i /*3*/ ++) /*4*/ begin /*5*/ : /*6*/ g + sub u (.a(a[i])); + end +endmodule +==== +# a `do ... while` header, which has no body to hand a comment back to +module m; +initial do x = 1; while /*1*/ ( /*2*/ c /*3*/ ); +endmodule +---- +module m; + initial + do x = 1; + while /*1*/ ( + /*2*/ + c /*3*/ + ); +endmodule +==== +# an event control's `@`, its edge keyword and its parenthesis +module m; +always @ /*1*/ (posedge /*2*/ clk) q <= d; +endmodule +---- +module m; + always @ /*1*/ (posedge /*2*/ clk) q <= d; +endmodule +==== +# a delay control's `#` +module m; +initial # /*1*/ 10 x = 1; +endmodule +---- +module m; + initial # /*1*/ 10 x = 1; +endmodule +==== +# a unary and a postfix operator keep the gap beside them +module m; +assign y = ~ /*1*/ a; +initial x = b /*2*/ ++; +endmodule +---- +module m; + assign y = ~ /*1*/ a; + initial x = b /*2*/ ++; +endmodule +==== +# a cast's four slots +module m; +assign y = state_t /*1*/ ' /*2*/ ( /*3*/ 0 /*4*/ ); +endmodule +---- +module m; + assign y = state_t /*1*/ ' /*2*/ ( /*3*/ 0 /*4*/ ); +endmodule +==== +# a module header: after the keyword, after the `#`, and before the `;` +module /*1*/ m # /*2*/ (parameter int W = 8) (input logic clk) /*3*/ ; +endmodule +---- +module /*1*/ m # /*2*/ (parameter int W = 8) (input logic clk) /*3*/ ; +endmodule +==== +# a package header and its `endpackage` label +package /*1*/ p /*2*/ ; +endpackage /*3*/ : /*4*/ p +---- +package /*1*/ p /*2*/ ; +endpackage /*3*/ : /*4*/ p +==== +# a class header, its qualifier run and its `endclass` label +class c; +local /*1*/ static /*2*/ int n; +endclass +---- +class c; + local /*1*/ static /*2*/ int n; +endclass +==== +# a parameter port's four slots +module m #(parameter /*1*/ int /*2*/ W /*3*/ = /*4*/ 8) (); +endmodule +---- +module m #(parameter /*1*/ int /*2*/ W /*3*/ = /*4*/ 8) (); +endmodule +==== +# an ANSI port's direction and name gaps +module m ( +input /*1*/ logic [3:0] /*2*/ a +); +endmodule +---- +module m (input /*1*/ logic [3:0] /*2*/ a); +endmodule +==== +# a `localparam` item's keyword and `=` gaps +module m; +localparam /*1*/ int N /*2*/ = /*3*/ 4; +endmodule +---- +module m; + localparam /*1*/ int N /*2*/ = /*3*/ 4; +endmodule +==== +# a continuous assignment's keyword and operator gaps +module m; +assign /*1*/ y /*2*/ = /*3*/ a; +endmodule +---- +module m; + assign /*1*/ y /*2*/ = /*3*/ a; +endmodule +==== +# a function header: keyword, return type, name, arguments and `;` +class c; +function /*1*/ void /*2*/ f /*3*/ ( /*4*/ ) /*5*/ ; +endfunction +endclass +---- +class c; + function /*1*/ void /*2*/ f /*3*/ ( + /*4*/ + ) /*5*/ ; + endfunction +endclass +==== +# a task/function argument's direction, name and default gaps +class c; +function void f(input /*1*/ int /*2*/ n /*3*/ = /*4*/ 0); +endfunction +endclass +---- +class c; + function void f(input /*1*/ int /*2*/ n /*3*/ = /*4*/ 0); + endfunction +endclass +==== +# an out-of-body definition's scope chain +class c; +extern function void f(); +endclass +function void c /*1*/ :: /*2*/ f(); +endfunction +---- +class c; + extern function void f(); +endclass +function void c /*1*/ :: /*2*/ f(); +endfunction +==== +# a typedef's keyword, name and `;` gaps, and a struct header's +package p; +typedef /*1*/ struct /*2*/ packed /*3*/ { +logic a; +} /*4*/ w_t /*5*/ ; +endpackage +---- +package p; + typedef /*1*/ struct /*2*/ packed /*3*/ { + logic a; + } /*4*/ w_t /*5*/ ; +endpackage +==== +# an enum's keyword, base and brace gaps, and a member's `=` +package p; +typedef enum /*1*/ logic [1:0] /*2*/ {A /*3*/ = /*4*/ 2'd0, B} e_t; +endpackage +---- +package p; + typedef enum /*1*/ logic [1:0] /*2*/ {A /*3*/ = /*4*/ 2'd0, B} e_t; +endpackage +==== +# an instantiation's `#`, its named connections and its `;` +module m; +sub # /*1*/ (.W(8)) u0 (. /*2*/ clk /*3*/ ( /*4*/ clk)) /*5*/ ; +endmodule +---- +module m; + sub # /*1*/ (.W(8)) u0 (. /*2*/ clk /*3*/ ( /*4*/ clk)) /*5*/ ; +endmodule +==== +# a `begin : label` and its `end : label` +module m; +initial begin /*1*/ : /*2*/ blk +x = 1; +end /*3*/ : /*4*/ blk +endmodule +---- +module m; + initial begin /*1*/ : /*2*/ blk + x = 1; + end /*3*/ : /*4*/ blk +endmodule +==== +# a `fork` label and a `join` label +module m; +initial fork /*1*/ : /*2*/ f +x = 1; +join /*3*/ : /*4*/ f +endmodule +---- +module m; + initial + fork /*1*/ : /*2*/ f + x = 1; + join /*3*/ : /*4*/ f +endmodule +==== +# a covergroup's qualifier run and its `endgroup` label +class c; +local /*1*/ covergroup cg; +cp: coverpoint a; +endgroup /*2*/ : /*3*/ cg +endclass +---- +class c; + local /*1*/ covergroup cg; + cp: coverpoint a; + endgroup /*2*/ : /*3*/ cg +endclass +==== +# a constraint's out-of-body scope and its qualifier run +class c; +static /*1*/ constraint c1 { +a < 5; +} +endclass +---- +class c; + static /*1*/ constraint c1 { + a < 5; + } +endclass +==== +# every escaped segment of a scoped type name keeps its terminator +module m; +\my-pkg ::\state-t \st ; +endmodule +---- +module m; + \my-pkg ::\state-t \st ; +endmodule diff --git a/crates/vlog_formatter/tests/cases/escaped_identifiers.cases b/crates/vlog_formatter/tests/cases/escaped_identifiers.cases index 06ad9e5..e2b7a88 100644 --- a/crates/vlog_formatter/tests/cases/escaped_identifiers.cases +++ b/crates/vlog_formatter/tests/cases/escaped_identifiers.cases @@ -280,17 +280,16 @@ endfunction function void \my-c ::\do-it (); endfunction ==== -# SKIP a `pkg::type` chain is joined into one string by the parser, so the -# SKIP boundary between the two escaped names is lost and the safety net -# SKIP rejects the file (no output, no corruption). Fixing it needs -# SKIP `parse_scoped_name` to keep its segments — see the Handshakes section -# SKIP of docs/features/escaped-identifiers/README.md. +# a `pkg::type` chain whose every segment is escaped: the join keeps the +# whitespace that terminates each one, so the three tokens stay three +# (docs/topo.md §2.9-21, closed by docs/features/comment-slots/README.md). +# The doubled space is what a bare escaped type name already prints. module m; \my-pkg ::\state-t \st ; endmodule ---- module m; - \my-pkg ::\state-t \st ; + \my-pkg ::\state-t \st ; endmodule ==== # an escaped type name widens the alignment column by its terminator diff --git a/crates/vlog_formatter/tests/verification.rs b/crates/vlog_formatter/tests/verification.rs index 3f3768f..6343092 100644 --- a/crates/vlog_formatter/tests/verification.rs +++ b/crates/vlog_formatter/tests/verification.rs @@ -1528,20 +1528,24 @@ fn expect_refusal(input: &str) { } } -/// The header shapes `header_parens` deliberately does *not* cover, pinned as -/// clean refusals so a future round sees them move rather than appear. +/// The header shapes `header_parens` did not cover, now covered by the +/// headers' own comment slots (`docs/features/comment-slots/README.md`). /// -/// `for` and `foreach` do not end their header in a single condition -/// expression, and a `do ... while (c);` has no body after its parentheses to -/// take the comment back from. All three still leave the file untouched. +/// The inverse of the pin this test used to be: `for`, `foreach` and +/// `do ... while` each own the gaps of their header outright, so a comment +/// written in one comes back where it was written instead of being refused. #[test] -fn a_comment_in_a_for_foreach_or_do_while_header_is_still_refused() { +fn a_comment_in_a_for_foreach_or_do_while_header_is_kept() { for input in [ "module m;\n initial begin\n for (int i = 0; i < 4; i++ // why\n ) begin\n y = 1;\n end\n end\nendmodule\n", "module m;\n initial begin\n foreach (arr[i] // why\n ) begin\n y = 1;\n end\n end\nendmodule\n", "module m;\n initial begin\n do begin\n y = 1;\n end while (c // why\n );\n end\nendmodule\n", ] { - expect_refusal(input); + let out = format_source(input, &Config::default()) + .unwrap_or_else(|e| panic!("{input:?} was refused: {e}")); + assert!(out.contains("// why"), "the comment survives: {out}"); + let twice = format_source(&out, &Config::default()).expect("and is a fixed point"); + assert_eq!(out, twice, "not idempotent: {out}"); } } @@ -1910,16 +1914,26 @@ fn a_space_dropped_before_a_scope_operator_is_rejected() { } #[test] -fn an_escaped_name_in_a_scoped_type_is_rejected_rather_than_corrupted() { - // `\my-pkg ::\state-t` is joined into one string by `parse_scoped_name`, - // so the formatter reprints it without the space it cannot know was - // there. The net catches it: an error, never a corrupted file. See the - // Handshakes section of docs/features/escaped-identifiers/README.md. +fn an_escaped_name_in_a_scoped_type_now_keeps_its_terminating_space() { + // The inverse of the pin this test used to be: `parse_scoped_name` and + // the two type-name joins now write the whitespace an escaped segment + // needs to terminate, so `\my-pkg ::\state-t` stays three tokens instead + // of being reprinted as the one token `\my-pkg::\state-t` and refused. + // `docs/topo.md` §2.9-21, closed by docs/features/comment-slots. let src = "module m;\n \\my-pkg ::\\state-t \\st ;\nendmodule\n"; - match format_source(src, &Config::default()) { - Err(FormatError::Verification(_)) => {} - other => panic!("expected the net to reject the scoped name, got {other:?}"), - } + let out = format_source(src, &Config::default()).expect("the scoped name survives"); + assert!(out.contains("\\my-pkg ::\\state-t"), "{out}"); + let twice = format_source(&out, &Config::default()).expect("and is a fixed point"); + assert_eq!(out, twice); +} + +/// Tightening that space back up is still a corruption, and still refused. +#[test] +fn a_space_dropped_inside_a_scoped_escaped_type_is_rejected() { + expect_divergence( + "module m;\n \\my-pkg ::\\state-t \\st ;\nendmodule\n", + "module m;\n \\my-pkg::\\state-t \\st ;\nendmodule\n", + ); } #[test] @@ -1988,11 +2002,14 @@ fn gaps(src: &str) -> Vec { out } -/// The fixtures with a `/*C*/` in one gap each, and whether that one formats -/// and round-trips. -fn failing_gaps() -> Vec { +/// One fixture set with a `/*C*/` in one gap each, and the ones that do not +/// format or do not round-trip. +/// +/// Shared by all four fixture sets: the question is the same everywhere, and +/// a per-set copy of it is how one of them quietly stops asking it. +fn failing_gaps(fixtures: &[&str]) -> Vec { let mut failed = Vec::new(); - for src in COVERGROUP_FIXTURES { + for src in fixtures { for at in gaps(src) { let mut probed = String::with_capacity(src.len() + 8); probed.push_str(&src[..at]); @@ -2010,199 +2027,31 @@ fn failing_gaps() -> Vec { failed } -#[test] -fn a_comment_in_every_covergroup_gap_still_formats() { - let total: usize = COVERGROUP_FIXTURES.iter().map(|s| gaps(s).len()).sum(); - let failed = failing_gaps(); - // The bar, stated out loud: of the fixtures' inter-token gaps, exactly - // these fail, every one of them in shared machinery that fails - // identically outside a covergroup (`docs/topo.md` §2.9-22) — the - // qualifier run, `[` index expressions, `class`/`package` headers, - // declarator dimensions and `parse_value_range`. A change that adds one - // fails here with the offending source printed. +/// The bar every fixture set is held to: **every** inter-token gap of every +/// fixture takes a `/*C*/`, and `format_source` must succeed and reach a fixed +/// point for each one. `total` is asserted too, so a fixture edited into +/// something smaller cannot quietly shrink the question. +fn assert_no_failing_gaps(name: &str, fixtures: &[&str], total: usize) { + let counted: usize = fixtures.iter().map(|s| gaps(s).len()).sum(); + let failed = failing_gaps(fixtures); assert_eq!( - (total, failed.len()), - (EXPECTED_GAPS, EXPECTED_FAILING_GAPS), - "the covergroup gap fuzzer moved:\n{}", + (counted, failed.len()), + (total, 0), + "the {name} gap fuzzer moved:\n{}", failed.join("\n") ); } -/// Inter-token gaps across [`COVERGROUP_FIXTURES`]. -const EXPECTED_GAPS: usize = 329; - -/// How many of them a `/*C*/` still breaks. Every one is classified by -/// [`shared_machinery_analogues`], whose sources are the same slots written -/// **outside** a covergroup — and which fail identically there: -/// -/// | shape | n | owner | -/// |---|---|---| -/// | `class /*C*/ c` / `class c /*C*/ ;` | 18 | the class header | -/// | `module /*C*/ m` / `module m /*C*/ ;` | 2 | the module header | -/// | a `tf_port_list` type, its dimensions and its name | 13 | `parse_tf_ports` | -/// | `endgroup /*C*/ : g` / `endgroup : /*C*/ g` | 4 | `parse_label` | -/// | `@ /*C*/ (` / `@(posedge /*C*/ clk)` | 2 | `parse_sens_list` | -/// | `[ /*C*/ 0 : 3 /*C*/ ]` | 8 | `parse_value_range` | -/// | `option /*C*/ . /*C*/ per_instance` | 4 | member expressions | -/// | `local /*C*/ covergroup` | 1 | `take_member_prefix` | -const EXPECTED_FAILING_GAPS: usize = 52; - -/// The same slots, written outside any covergroup. -/// -/// Every one of them is a *pre-existing* comment-drop in shared name, -/// declaration or expression machinery — `docs/topo.md` §2.9-22 — and none of -/// it is this round's to fix. This test is the classification, written down: -/// if one of these starts working, the fuzzer's count above moves in the same -/// commit, and both are updated together. -const SHARED_MACHINERY_ANALOGUES: &[(&str, &str)] = &[ - ( - "class /*C*/ c", - "class /*C*/ c; -endclass -", - ), - ( - "class c /*C*/ ;", - "class c /*C*/ ; -endclass -", - ), - ( - "module /*C*/ m", - "module /*C*/ m; -endmodule -", - ), - ( - "module m /*C*/ ;", - "module m /*C*/ ; -endmodule -", - ), - ( - "a tf port's type", - "class c; - function void f(bit /*C*/ [3:0] a); - endfunction -endclass -", - ), - ( - "a tf port's dimension", - "class c; - function void f(bit [ /*C*/ 3:0] a); - endfunction -endclass -", - ), - ( - "a tf port's name", - "class c; - function void f(bit [3:0] /*C*/ a); - endfunction -endclass -", - ), - ( - "an untyped tf port's name", - "class c; - function void f(int /*C*/ n); - endfunction -endclass -", - ), - ( - "endfunction /*C*/ : f", - "class c; - function void f(); - endfunction /*C*/ : f -endclass -", - ), - ( - "endfunction : /*C*/ f", - "class c; - function void f(); - endfunction : /*C*/ f -endclass -", - ), - ( - "always @ /*C*/ (", - "module m; - always @ /*C*/ (posedge clk) x <= 1; -endmodule -", - ), - ( - "always @(posedge /*C*/ clk)", - "module m; - always @(posedge /*C*/ clk) x <= 1; -endmodule -", - ), - ( - "a value range's open", - "module m; - assign y = a inside {[ /*C*/ 0:3]}; -endmodule -", - ), - ( - "a value range's colon", - "module m; - assign y = a inside {[0 /*C*/ :3]}; -endmodule -", - ), - ( - "a value range's close", - "module m; - assign y = a inside {[0:3 /*C*/ ]}; -endmodule -", - ), - ( - "a member access's dot", - "module m; - assign y = a /*C*/ .b; -endmodule -", - ), - ( - "a member access's name", - "module m; - assign y = a. /*C*/ b; -endmodule -", - ), - ( - "a member qualifier run", - "class c; - local /*C*/ function void f(); - endfunction -endclass -", - ), -]; - #[test] -fn the_gaps_the_fuzzer_still_fails_fail_outside_a_covergroup_too() { - let working: Vec<&str> = SHARED_MACHINERY_ANALOGUES - .iter() - .filter(|(_, src)| { - format_source(src, &Config::default()) - .is_ok_and(|out| format_source(&out, &Config::default()).is_ok_and(|t| t == out)) - }) - .map(|(name, _)| *name) - .collect(); - assert!( - working.is_empty(), - "these shared-machinery slots now keep their comment, so the covergroup \ - fuzzer's expected count above is stale: {working:?}" - ); +fn a_comment_in_every_covergroup_gap_still_formats() { + assert_no_failing_gaps("covergroup", COVERGROUP_FIXTURES, EXPECTED_GAPS); } +/// Inter-token gaps across [`COVERGROUP_FIXTURES`]. Every one of them keeps +/// its comment since `docs/features/comment-slots/README.md`; the count is +/// asserted so a shrunken fixture set cannot pass by asking less. +const EXPECTED_GAPS: usize = 329; + // ---------------------------------------------------------------------- // Fragment files — `docs/features/fragment-mode/README.md` // @@ -2295,94 +2144,222 @@ const FRAGMENT_FIXTURES: &[&str] = &[ "option.per_instance = 1;\ncoverpoint x;\n", ]; -/// The fragment fixtures with a `/*C*/` in one gap each, and whether that one -/// formats and round-trips. -fn failing_fragment_gaps() -> Vec { - let mut failed = Vec::new(); - for src in FRAGMENT_FIXTURES { - for at in gaps(src) { - let mut probed = String::with_capacity(src.len() + 8); - probed.push_str(&src[..at]); - probed.push_str(" /*C*/ "); - probed.push_str(&src[at..]); - let ok = match format_source(&probed, &Config::default()) { - Ok(out) => format_source(&out, &Config::default()).is_ok_and(|two| two == out), - Err(_) => false, - }; - if !ok { - failed.push(format!("{:?} … {:?}", &probed[..at + 7], &probed[at + 7..])); - } - } - } - failed -} - #[test] fn a_comment_in_every_fragment_gap_still_formats() { - let total: usize = FRAGMENT_FIXTURES.iter().map(|s| gaps(s).len()).sum(); - let failed = failing_fragment_gaps(); - assert_eq!( - (total, failed.len()), - (EXPECTED_FRAGMENT_GAPS, EXPECTED_FAILING_FRAGMENT_GAPS), - "the fragment gap fuzzer moved:\n{}", - failed.join("\n") - ); + assert_no_failing_gaps("fragment", FRAGMENT_FIXTURES, EXPECTED_FRAGMENT_GAPS); } /// Inter-token gaps across [`FRAGMENT_FIXTURES`]. const EXPECTED_FRAGMENT_GAPS: usize = 153; -/// How many of them a `/*C*/` still breaks. Every one is in shared name, -/// expression or statement machinery that fails identically *inside* a module -/// or a package — [`FRAGMENT_ANALOGUES`] is the same slot written there, and -/// [`the_gaps_the_fragment_fuzzer_fails_fail_outside_a_fragment_too`] proves -/// it rather than asserting it. Nothing here is fragment-specific; the whole -/// set is `docs/topo.md` §2.9-22, which `covergroup-bodies` opened. -const EXPECTED_FAILING_FRAGMENT_GAPS: usize = 41; +// ---------------------------------------------------------------------- +// Comment slots — `docs/features/comment-slots/README.md` +// +// `verify.rs` was not touched by this round and no normalization was +// widened; these are the attack pairs that say so out loud (CLAUDE.md +// invariant 4). Every one of them is a comment moved across exactly one of +// the tokens the new slots are defined *between* — the corruption a slot +// that claimed the wrong gap would produce, and which the net must refuse. +// ---------------------------------------------------------------------- -/// One entry per class of gap [`failing_fragment_gaps`] still reports, written -/// where the same construct stands inside an ordinary file. -const FRAGMENT_ANALOGUES: &[(&str, &str)] = &[ - ("an enum member's `=`", "package p;\n typedef enum {A, B /*C*/ = 2} e_t;\nendpackage\n"), - ("an enum member's value", "package p;\n typedef enum {A, B = /*C*/ 2} e_t;\nendpackage\n"), - ("an enum name range's `[`", "package p;\n typedef enum {A /*C*/ [0:1]} e_t;\nendpackage\n"), - ("inside an enum name range", "package p;\n typedef enum {A[ /*C*/ 0:1]} e_t;\nendpackage\n"), - ("a name range's `:`", "package p;\n typedef enum {A[0 /*C*/ :1]} e_t;\nendpackage\n"), - ("a name range's close", "package p;\n typedef enum {A[0:1 /*C*/ ]} e_t;\nendpackage\n"), - ("the gap before a statement's `;`", "module m;\n initial x = 1 /*C*/ ;\nendmodule\n"), - ("a statement keyword's `(`", "module m;\n initial if /*C*/ (a) x = 1;\nendmodule\n"), - ("a `foreach` header's `(`", "module m;\n initial foreach /*C*/ (q[i]) x = 1;\nendmodule\n"), - ("inside a `foreach` header", "module m;\n initial foreach ( /*C*/ q[i]) x = 1;\nendmodule\n"), - ("an index expression's `[`", "module m;\n initial q /*C*/ [i] = 1;\nendmodule\n"), - ("inside an index expression", "module m;\n initial q[ /*C*/ i] = 1;\nendmodule\n"), - ("an event control's `@`", "module m;\n always @ /*C*/ (posedge clk) x <= y;\nendmodule\n"), - ("an edge keyword", "module m;\n always @(posedge /*C*/ clk) x <= y;\nendmodule\n"), - ("a delay control's `#`", "module m;\n initial # /*C*/ 10 x = 1;\nendmodule\n"), - ("a member chain's `.`", "module m;\n initial a /*C*/ .b = 1;\nendmodule\n"), - ("after a member chain's `.`", "module m;\n initial a. /*C*/ b = 1;\nendmodule\n"), - ( - "a value range inside a bin", - "class c;\n covergroup cg;\n cp: coverpoint a {\n bins lo = {[ /*C*/ 0:9]};\n }\n endgroup\nendclass\n", - ), +#[test] +fn a_comment_moved_across_a_bracket_is_rejected() { + // `q [ ... ]`: across the `[`, and across the `]`. + expect_divergence( + "module m;\n assign y = q /*c*/ [i];\nendmodule\n", + "module m;\n assign y = q[ /*c*/ i];\nendmodule\n", + ); + expect_divergence( + "module m;\n assign y = q[i /*c*/ ];\nendmodule\n", + "module m;\n assign y = q[i] /*c*/ ;\nendmodule\n", + ); + // And across the `:` of a part-select, which is the same shape with one + // more token in it. + expect_divergence( + "module m;\n assign y = q[hi /*c*/ :lo];\nendmodule\n", + "module m;\n assign y = q[hi: /*c*/ lo];\nendmodule\n", + ); +} + +#[test] +fn a_comment_moved_across_a_scope_or_member_joiner_is_rejected() { + expect_divergence( + "module m;\n assign y = pkg /*c*/ ::item;\nendmodule\n", + "module m;\n assign y = pkg:: /*c*/ item;\nendmodule\n", + ); + expect_divergence( + "module m;\n assign y = a. /*c*/ b;\nendmodule\n", + "module m;\n assign y = a /*c*/ .b;\nendmodule\n", + ); +} + +#[test] +fn a_comment_moved_across_a_statements_semicolon_is_rejected() { + // `Stmt::before_semi` is the widest slot this round added: it is claimed + // by every statement kind that writes a `;`. Printed on the other side of + // that `;` it belongs to the *next* statement. + expect_divergence( + "module m;\n initial begin\n x = 1 /*c*/ ;\n y = 2;\n end\nendmodule\n", + "module m;\n initial begin\n x = 1;\n /*c*/ y = 2;\n end\nendmodule\n", + ); + expect_divergence( + "module m;\n initial begin\n return /*c*/ ;\n end\nendmodule\n", + "module m;\n initial begin\n return; /*c*/\n end\nendmodule\n", + ); +} + +#[test] +fn an_edge_keywords_comment_swapped_to_the_other_side_is_rejected() { + expect_divergence( + "module m;\n always @(posedge /*c*/ clk) q <= d;\nendmodule\n", + "module m;\n always @( /*c*/ posedge clk) q <= d;\nendmodule\n", + ); + // And the `@`'s own gap, which is one token further left again. + expect_divergence( + "module m;\n always @ /*c*/ (posedge clk) q <= d;\nendmodule\n", + "module m;\n always @(posedge clk /*c*/ ) q <= d;\nendmodule\n", + ); +} + +#[test] +fn a_qualifiers_comment_moved_to_the_next_gap_is_rejected() { + // Two keywords in a run, one comment: which gap it was written in is the + // whole content of `Qualifier::after`. + expect_divergence( + "class c;\n local /*c*/ static int n;\nendclass\n", + "class c;\n local static /*c*/ int n;\nendclass\n", + ); +} + +#[test] +fn a_label_comment_moved_across_the_colon_is_rejected() { + expect_divergence( + "module m;\n initial begin : b\n x = 1;\n end /*c*/ : b\nendmodule\n", + "module m;\n initial begin : b\n x = 1;\n end : /*c*/ b\nendmodule\n", + ); +} + +#[test] +fn a_header_keywords_comment_moved_inside_the_parens_is_rejected() { + expect_divergence( + "module m;\n initial if /*c*/ (a) x = 1;\nendmodule\n", + "module m;\n initial if ( /*c*/ a) x = 1;\nendmodule\n", + ); + expect_divergence( + "module m;\n initial for /*c*/ (int i = 0; i < 4; i++) x = i;\nendmodule\n", + "module m;\n initial for (int i = 0 /*c*/ ; i < 4; i++) x = i;\nendmodule\n", + ); +} + +#[test] +fn an_equals_signs_comment_swapped_across_it_is_rejected() { + // One `BinaryComments` per `=`, four constructs sharing the shape. + for (before, after) in [ + ( + "module m;\n localparam int N /*c*/ = 4;\nendmodule\n", + "module m;\n localparam int N = /*c*/ 4;\nendmodule\n", + ), + ( + "package p;\n typedef enum {A /*c*/ = 1} e_t;\nendpackage\n", + "package p;\n typedef enum {A = /*c*/ 1} e_t;\nendpackage\n", + ), + ( + "module m #(parameter int W /*c*/ = 8) ();\nendmodule\n", + "module m #(parameter int W = /*c*/ 8) ();\nendmodule\n", + ), + ( + "module m;\n assign y /*c*/ = a;\nendmodule\n", + "module m;\n assign y = /*c*/ a;\nendmodule\n", + ), + ] { + expect_divergence(before, after); + } +} + +#[test] +fn a_dropped_slot_comment_is_rejected() { + // The failure mode the whole round is about: a slot with no field does + // not delete the comment, it re-attaches it one node later — but a + // printer that dropped one outright would be caught here too. + expect_divergence( + "module m;\n assign y = a /*c*/ .b;\nendmodule\n", + "module m;\n assign y = a.b;\nendmodule\n", + ); + expect_divergence( + "class c;\n function void f( /*c*/ );\n endfunction\nendclass\n", + "class c;\n function void f();\n endfunction\nendclass\n", + ); +} + +// ---------------------------------------------------------------------- +// The constraint gap fuzzer +// +// `constraint-bodies` built this and reported its numbers in the work log, +// but never committed it. It is committed here, at zero: the round that +// invented the exhaustive question is the one whose sub-grammar has to keep +// answering it. +// ---------------------------------------------------------------------- + +/// The constraint sub-grammar, one shape per fixture, re-derived from the +/// table in `docs/features/constraint-bodies/README.md`. +const CONSTRAINT_FIXTURES: &[&str] = &[ + "class c;\n constraint valid_c {\n a < 5;\n b inside {[0:3], 7};\n }\nendclass\n", + "class c;\n constraint c1 {\n soft x == 1;\n soft y dist {0 := 5, [1:20] :/ 20};\n }\nendclass\n", + "class c;\n constraint c2 {\n unique {a, b};\n disable soft z;\n solve a, b before c, d;\n }\nendclass\n", + "class c;\n constraint c3 {\n a > 0 -> b == 1;\n c == 2 -> {\n d < 4;\n }\n }\nendclass\n", + "class c;\n constraint c4 {\n if (mode == 1) {\n len == 4;\n } else if (mode == 2) {\n len == 8;\n } else {\n len == 0;\n }\n }\nendclass\n", + "class c;\n constraint c5 {\n foreach (arr[i]) {\n arr[i] < 10;\n }\n }\nendclass\n", + "class c;\n constraint c6 {\n foreach (m[i, j]) m[i][j] == i * j;\n }\nendclass\n", + "class c;\n static constraint c7 {\n a == 1;\n }\n extern constraint c8;\nendclass\n", + "constraint c::c9 {\n a == 1;\n}\n", + "class c;\n constraint empty_c {}\n constraint semi_c { a == 1; };\nendclass\n", + "class c;\n function void f();\n obj.randomize() with {\n a < 5;\n b == 2;\n };\n endfunction\nendclass\n", + "class c;\n function void f();\n void'(std::randomize(x) with {x > 0;});\n endfunction\nendclass\n", + "class c;\n constraint c10 {\n `ifdef FOO\n a == 1;\n `endif\n b == 2;\n }\nendclass\n", + "class c;\n constraint c11 {\n x dist {[1:3] := 1, 5 := 2};\n ;\n }\nendclass\n", + "class c;\n constraint c12 {\n a inside {b, [c:d]};\n !(e inside {1, 2});\n }\nendclass\n", ]; #[test] -fn the_gaps_the_fragment_fuzzer_fails_fail_outside_a_fragment_too() { - let working: Vec<&str> = FRAGMENT_ANALOGUES - .iter() - .filter(|(_, src)| { - format_source(src, &Config::default()) - .is_ok_and(|out| format_source(&out, &Config::default()).is_ok_and(|t| t == out)) - }) - .map(|(name, _)| *name) - .collect(); - assert!( - working.is_empty(), - "these shared-machinery slots now keep their comment, so the fragment \ - fuzzer's expected count above is stale: {working:?}" - ); +fn a_comment_in_every_constraint_gap_still_formats() { + assert_no_failing_gaps("constraint", CONSTRAINT_FIXTURES, EXPECTED_CONSTRAINT_GAPS); } +/// Inter-token gaps across [`CONSTRAINT_FIXTURES`]. +const EXPECTED_CONSTRAINT_GAPS: usize = 395; + +// ---------------------------------------------------------------------- +// The RTL gap fuzzer +// +// The three fuzzers above each cover one sub-grammar. This one covers the +// language lucisv is actually pointed at all day: a module with parameters +// and ports, declarations, `always` blocks, a `case`, both `for` spellings, +// an instantiation, continuous assignments, a function and a package of +// typedefs. Every one of their inter-token gaps takes a `/*C*/` too. +// ---------------------------------------------------------------------- + +/// Ordinary RTL, one construct family per fixture. +const RTL_FIXTURES: &[&str] = &[ + "module m #(parameter int W = 8) (input logic clk, input logic rst_n, output logic [W-1:0] q);\nendmodule\n", + "module m;\n localparam int N = 4;\n logic [N-1:0] a, b;\n assign a = b & ~c;\nendmodule\n", + "module m;\n always_ff @(posedge clk or negedge rst_n) begin\n if (!rst_n) q <= '0;\n else q <= d;\n end\nendmodule\n", + "module m;\n always_comb begin\n case (sel)\n 2'd0: y = a;\n 2'd1, 2'd2: y = b;\n default: y = c;\n endcase\n end\nendmodule\n", + "module m;\n for (genvar i = 0; i < N; i++) begin : g\n sub u_sub (.a(a[i]), .b(b[i]));\n end\nendmodule\n", + "module m;\n initial begin\n for (int i = 0; i < N; i = i + 1) begin\n mem[i] = i;\n end\n end\nendmodule\n", + "module m;\n function automatic logic [7:0] f (input logic [7:0] x, int n);\n return x << n;\n endfunction\nendmodule\n", + "package p;\n typedef struct packed {\n logic [3:0] hi;\n logic [3:0] lo;\n } word_t;\n typedef enum logic [1:0] {A = 2'd0, B, C} st_e;\nendpackage\n", + "module m;\n sub #(.W(8)) u0 (.clk(clk), .d(d[3:0]), .q());\nendmodule\n", + "module m;\n assign y = cond ? a[3:0] : pkg::f(b).c;\nendmodule\n", +]; + +#[test] +fn a_comment_in_every_rtl_gap_still_formats() { + assert_no_failing_gaps("RTL", RTL_FIXTURES, EXPECTED_RTL_GAPS); +} + +/// Inter-token gaps across [`RTL_FIXTURES`]. +const EXPECTED_RTL_GAPS: usize = 352; + // ---------------------------------------------------------------------- // Vendor and formal collateral — `vendor-formal-grammar` // diff --git a/crates/vlog_linter/src/signals.rs b/crates/vlog_linter/src/signals.rs index d0acae1..a652c96 100644 --- a/crates/vlog_linter/src/signals.rs +++ b/crates/vlog_linter/src/signals.rs @@ -626,7 +626,12 @@ fn lvalue_targets(expr: &Expr, whole: bool, out: &mut Vec<(TextRange, bool)>) { /// expression. fn increment_target(expr: &Expr) -> Option<&Expr> { match &expr.kind { - ExprKind::Postfix { expr, op } | ExprKind::Unary { expr, op } + // `..` skips the `comments` slot the comment-slots round added to + // `ExprKind::Unary` and `ExprKind::Postfix` + // (docs/features/comment-slots/README.md) — a mechanical pattern + // update, flagged there as a handshake request against this file, + // which that round does not otherwise touch. + ExprKind::Postfix { expr, op, .. } | ExprKind::Unary { expr, op, .. } if op == "++" || op == "--" => { Some(expr) diff --git a/crates/vlog_parser/src/ast.rs b/crates/vlog_parser/src/ast.rs index a72d9a6..5466ee4 100644 --- a/crates/vlog_parser/src/ast.rs +++ b/crates/vlog_parser/src/ast.rs @@ -32,6 +32,95 @@ pub struct Name { pub span: TextRange, } +/// One `pkg::` / `cls::` segment written in front of an out-of-body +/// definition's name, with the comments written in its two gaps. +/// +/// The chain is kept as segments rather than joined into a `String` so that +/// (a) a comment written beside a `::` has a slot, and (b) an escaped +/// segment's terminating space survives — `\my-pkg ::\state-t` is three +/// tokens and `\my-pkg::\state-t` is one (`docs/topo.md` §2.9-21). +#[derive(Debug, Clone)] +pub struct ScopeSeg { + pub name: Name, + /// Comments written between this segment and the `::` after it. + pub before_sep: Vec, + /// Comments written between that `::` and whatever follows it. + pub after_sep: Vec, +} + +/// The `a::b::` prefix a [`ScopeSeg`] chain spells, joined for the consumers +/// that want one string (the binder's out-of-body home, hover text). +/// +/// An escaped segment keeps the whitespace that terminates it, for the reason +/// [`ScopeSeg`] gives; nothing else adds any. +pub fn scope_path(segs: &[ScopeSeg]) -> String { + let mut out = String::new(); + for seg in segs { + out.push_str(&seg.name.text); + if seg.name.text.rsplit(char::is_whitespace).next().is_some_and(|s| s.contains('\\')) { + out.push(' '); + } + out.push_str("::"); + } + out.pop(); + out.pop(); + out +} + +/// Comments written in the two gaps of a `keyword : name` label — the `end`, +/// `endfunction`, `endgroup`, `begin` … footers and headers that carry one. +#[derive(Debug, Clone, Default)] +pub struct LabelComments { + /// Between the keyword and the `:`. + pub before_colon: Vec, + /// Between the `:` and the name. + pub after_colon: Vec, +} + +impl LabelComments { + /// True when nothing was written in either gap — the common case. + pub fn is_empty(&self) -> bool { + self.before_colon.is_empty() && self.after_colon.is_empty() + } +} + +/// One keyword of a qualifier run, with the comments written between it and +/// whatever follows it (`local /*c*/ static /*c*/ function`). +/// +/// Kept per keyword rather than as one bucket for the run, because two +/// comments in different gaps of the same run are two different token +/// streams and the safety net compares them. +#[derive(Debug, Clone)] +pub struct Qualifier { + pub text: String, + /// Comments written after this keyword and before the next one — or + /// before whatever ends the run. + pub after: Vec, +} + +impl Qualifier { + /// A qualifier with nothing written after it, for the sites that build a + /// run rather than reading one from source. + pub fn plain(text: impl Into) -> Self { + Qualifier { text: text.into(), after: Vec::new() } + } +} + +/// One slot of a `foreach`'s loop-variable bracket, with the comments written +/// on either side of it so neither drifts across the `,` that separates two +/// slots. +#[derive(Debug, Clone)] +pub struct ForeachVar { + /// The loop variable. A **skipped** dimension (IEEE 1800 §12.7.3 — + /// `foreach (q[, j])` iterates only the second) is an empty name at the + /// point it was written: it declares nothing and prints as nothing. + pub name: Name, + /// Comments written between the `[` (or the previous `,`) and this slot. + pub before: Vec, + /// Comments written between this slot and the `,` or `]` after it. + pub after: Vec, +} + /// One `pkg::item` (or `pkg::*`) path of an `import`, each half with its own /// range — a language server resolves the package and the imported name /// separately. @@ -221,11 +310,17 @@ pub enum ItemKind { Module(Module), Package { kw: String, + /// Comments written between `package` and the name. + before_name: Vec, name: String, /// Byte range of `name`. name_span: TextRange, + /// Comments written between the name and the header's `;`. + before_semi: Vec, items: Vec, dangling: Vec, + /// Comments written in the two gaps of `endpackage : p`. + end_label_comments: Box, /// Label after `endpackage :`. end_label: Option, /// Byte range of `end_label`. @@ -266,7 +361,9 @@ pub enum ItemKind { dangling: Vec, }, GenIf(GenIf), - GenFor(GenFor), + /// Boxed: a `for` generate holds a whole `SimpleAssign`, a condition, a + /// step and a block, which together are twice the next-largest item. + GenFor(Box), GenCase(GenCase), Function(FunctionDecl), Task(TaskDecl), @@ -342,6 +439,9 @@ pub enum ItemKind { #[derive(Debug)] pub struct Module { pub kw: String, + /// Comments written between the keyword and the name + /// (`module /*c*/ m`). + pub before_name: Vec, pub name: String, /// Byte range of `name`. pub name_span: TextRange, @@ -352,6 +452,8 @@ pub struct Module { /// Comments written between the header's name (or its last `import`) and /// the `#` of the parameter port list. Empty when the header wrote none. pub param_comments: Vec, + /// Comments written between that `#` and its `(`. + pub param_after_hash: Vec, /// `None` when the header wrote no `#( ... )` at all; an empty `Some` is a /// written-but-empty `#()`, which must be printed back. pub param_ports: Option>, @@ -369,8 +471,12 @@ pub struct Module { pub port_directives: Vec, /// Comments written after the last port and before the `)`. pub port_dangling: Vec, + /// Comments written between the header's last token and its `;`. + pub before_semi: Vec, pub items: Vec, pub dangling: Vec, + /// Comments written in the two gaps of the footer's `: name` label. + pub end_label_comments: Box, pub end_label: Option, /// Byte range of `end_label`. pub end_label_span: Option, @@ -429,12 +535,19 @@ pub struct NonAnsiPort { pub struct AnsiPort { pub meta: Meta, pub dir: Option, + /// Comments written between the direction keyword and the type + /// (`input /*c*/ logic clk`). Empty when no direction was written. + pub after_dir: Vec, pub net: Option, pub ty: DataType, + /// Comments written between the type and the port's name. + pub before_name: Vec, pub name: String, /// Byte range of `name`. pub name_span: TextRange, pub unpacked: Vec, + /// Comments written on either side of the `=` of a default value. + pub eq_comments: Box, pub default: Option, /// True when a `,` followed this element in the source; see /// [`NonAnsiPort::comma`]. @@ -448,12 +561,19 @@ pub struct ParamPort { pub meta: Meta, /// `parameter` or `localparam`; empty if omitted (continuation params). pub kw: Option, + /// Comments written between that keyword and the type + /// (`parameter /*c*/ int W = 8`). + pub after_kw: Vec, pub ty: DataType, pub is_type: bool, + /// Comments written between the type and the parameter's name. + pub before_name: Vec, pub name: String, /// Byte range of `name`. pub name_span: TextRange, pub unpacked: Vec, + /// Comments written on either side of the `=` of a default value. + pub eq_comments: Box, pub default: Option, /// True when a `,` followed this element in the source; see /// [`NonAnsiPort::comma`]. @@ -560,6 +680,10 @@ impl VirtualKw { #[derive(Debug, Clone)] pub struct Dim { pub kind: DimKind, + /// Comments written in the dimension's own slots — before the `[`, just + /// inside it, around the `:` and before the `]`. Boxed for the reason + /// [`SegmentComments`] gives. + pub comments: Box, /// Code extent including the brackets. pub span: TextRange, } @@ -579,10 +703,18 @@ pub enum DimKind { #[derive(Debug)] pub struct Typedef { + /// Comments written between the `typedef` keyword and the base type + /// (`typedef /*c*/ struct packed { … } w_t;`). + pub after_kw: Vec, + /// Comments written between the base type and the new type's name + /// (`… } /*c*/ w_t;`). + pub before_name: Vec, pub name: String, /// Byte range of `name`. pub name_span: TextRange, pub unpacked: Vec, + /// Comments written between the name and the `;`. + pub before_semi: Vec, pub kind: TypedefKind, } @@ -597,7 +729,12 @@ pub enum TypedefKind { #[derive(Debug, Clone)] pub struct EnumType { + /// Comments written between the `enum` keyword and its base type + /// (`enum /*c*/ logic [1:0] { … }`). + pub after_kw: Vec, pub base: Option, + /// Comments written between the base type and the `{`. + pub before_open: Vec, pub members: Vec, /// Directives written between the members, in source order. pub directives: Vec, @@ -616,6 +753,9 @@ pub struct EnumMember { /// dimension parser and printer serve it, and it is printed back tight /// against the name because it is part of the name, not a layout choice. pub range: Vec, + /// Comments written on either side of the `=` of a member's value + /// (`B /*c*/ = /*c*/ 2`). + pub eq_comments: Box, pub value: Option, /// True when a `,` followed this element in the source; see /// [`NonAnsiPort::comma`]. @@ -628,6 +768,11 @@ pub struct EnumMember { pub struct StructType { /// "struct" or "union" pub kw: String, + /// Comments written between each word of the `struct packed signed` + /// header run and the next, and between the last of them and the `{`. + /// One entry per gap, in source order: after the keyword, after + /// `tagged`, after `packed`, after the signing word. + pub header_comments: Box, /// The `tagged` of `union tagged { ... }` (IEEE 1800 §7.3.2) — a /// discriminated union. Carried and printed; lucisv models no tag /// semantics, and the `tagged Valid 5` expression form that goes with it @@ -647,7 +792,7 @@ pub struct StructMember { /// accept them on a plain struct member and real code uses them /// (`spi_host/dv/env/spi_host_env_pkg.sv:64`); lucisv models no /// randomization semantics, so the words are simply carried and printed. - pub qualifiers: Vec, + pub qualifiers: Vec, pub ty: DataType, pub declarators: Vec, /// Code extent of the member, its `;` included. @@ -658,6 +803,9 @@ pub struct StructMember { pub struct ParamDecl { /// `parameter` or `localparam` pub kw: String, + /// Comments written between that keyword and the type + /// (`localparam /*c*/ int N = 4;`). + pub after_kw: Vec, /// A type parameter: `localparam type payload_t = logic [7:0];`. The /// declarator's `init` is then an [`ExprKind::Type`], not a value. pub is_type: bool, @@ -675,7 +823,7 @@ pub struct DataDecl { /// `automatic`, `static`, `const`, and — inside a class body — `rand`, /// `randc`, `local`, `protected`, and the `virtual [interface]` of a /// virtual-interface property. - pub qualifiers: Vec, + pub qualifiers: Vec, pub ty: DataType, pub declarators: Vec, } @@ -695,6 +843,8 @@ pub struct Declarator { /// Byte range of `name`. pub name_span: TextRange, pub unpacked: Vec, + /// Comments written on either side of the `=` of an initialiser. + pub eq_comments: Box, /// `=` for variables; net declarations also use this for the initial /// continuous assignment. pub init: Option, @@ -728,6 +878,9 @@ pub struct AssignPair { pub meta: Meta, pub lhs: Expr, pub rhs: Expr, + /// Comments written between the left-hand side and the `=` + /// (`assign y /*c*/ = x;`). + pub op_comments: Vec, /// Comments written between the `=` and the right-hand side. Kept here so /// they print on the `=`'s side of the value instead of drifting into it. pub rhs_comments: Vec, @@ -745,11 +898,19 @@ pub enum SensList { /// Comments between the `*` and the closing `)`. after: Vec, }, - List(Vec), + List { + items: Vec, + /// Comments written between the `@` and the `(` (`always @ /*c*/ (`). + after_at: 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), + Bare { + expr: Expr, + /// Comments written between the `@` and the name. + after_at: Vec, + }, } #[derive(Debug)] @@ -761,6 +922,9 @@ pub struct SensItem { /// The separator written before this item; `None` on the first item. pub sep: Option, pub edge: Option, + /// Comments written between the edge keyword and the expression + /// (`@(posedge /*c*/ clk)`). Empty when no edge keyword was written. + pub after_edge: Vec, pub expr: Expr, /// The gating condition of `@(posedge clk iff enable)` — IEEE 1800 /// §9.4.2's optional `iff expression` on one event expression term. @@ -788,6 +952,8 @@ pub struct Instantiation { /// Comments written between the module name and the `#` of the parameter /// override list. Empty when the source wrote no `#(...)`. pub param_comments: Vec, + /// Comments written between that `#` and its `(`. + pub after_hash: Vec, /// The parameter override list, `None` when the source wrote no `#(...)` /// at all. An empty `Some` is a written-but-empty `#()`, which must be /// printed back: dropping it would lose two tokens. @@ -797,6 +963,8 @@ pub struct Instantiation { /// whole body is one `` `include`` has no override to hang them on. pub param_directives: Vec, pub instances: Vec, + /// Comments written between the last instance and the `;`. + pub before_semi: Vec, } #[derive(Debug)] @@ -839,11 +1007,18 @@ pub struct OrderedConn { #[derive(Debug)] pub struct Connection { pub meta: Meta, + /// Comments written between the `.` and the port name (`. /*c*/ clk(x)`). + pub after_dot: Vec, /// Port/parameter name; `*` for the SystemVerilog `.*` wildcard. pub name: String, /// Byte range of `name`; empty for a positional connection, which has no /// name to point at. pub name_span: TextRange, + /// Comments written between the name and the `(` (`.clk /*c*/ (x)`). + pub before_open: Vec, + /// Comments written just inside the `(` (`.clk( /*c*/ x)`). An empty + /// connection keeps its own in [`ExprKind::Empty`], as it always has. + pub after_open: Vec, /// `None` for `.name` (implicit) and `.*`; `Some` for `.name(expr)`. /// An explicitly empty connection `.name()` is `Some(Expr::Empty)`. pub expr: Option, @@ -932,8 +1107,13 @@ pub enum GenElse { pub struct GenFor { pub init: SimpleAssign, pub init_genvar: bool, + /// Comments written between the `genvar` keyword and the loop variable. + /// Empty when no `genvar` was written. + pub after_genvar: Vec, pub cond: Expr, pub step: ForStep, + /// The same seven header slots a statement `for` owns. + pub comments: Box, pub body: GenBlock, } @@ -950,6 +1130,9 @@ pub struct GenCaseItem { /// Empty means `default`. Each label carries the comments written around /// it, so a comment between two labels stays between them. pub labels: Vec, + /// Comments written between the last label — or the `default` keyword — + /// and the `:` that ends the label list. + pub before_colon: Vec, pub body: GenBlock, /// Code extent of the case item, its body included. pub span: TextRange, @@ -959,12 +1142,22 @@ pub struct GenCaseItem { /// or a single item. #[derive(Debug)] pub struct GenBlock { + /// Comments written between whatever precedes the block and its `begin` + /// (`for (…) /*c*/ begin : g`). Empty for a block-less single item, which + /// keeps them in its own leading comments. + pub before_kw: Vec, + /// Comments written between `begin` and the `:` of its label. + pub before_colon: Vec, + /// Comments written between that `:` and the label name. + pub after_colon: Vec, pub label: Option, /// Byte range of `label`. pub label_span: Option, pub is_block: bool, pub items: Vec, pub dangling: Vec, + /// Comments written in the two gaps of `end : g`. + pub end_label_comments: Box, /// Label after `end :`. pub end_label: Option, /// Byte range of `end_label`. @@ -983,7 +1176,10 @@ pub struct ClassDecl { /// qualifiers, and the `interface` of an `interface class` (IEEE 1800 /// §8.26). Kept as a list so the source order is reproduced verbatim — /// see [`ClassDecl::is_interface_class`]. - pub prefix: Vec, + pub prefix: Vec, + /// Comments written between the qualifier run, the `class` keyword and + /// the name — the header's own `class /*c*/ c` slot. + pub before_name: Vec, /// `static`/`automatic` lifetime written after `class`, if any. pub lifetime: Option, pub name: String, @@ -992,6 +1188,8 @@ pub struct ClassDecl { /// Comments written between the class name and the `#` of its parameter /// port list. pub param_comments: Vec, + /// Comments written between that `#` and its `(`. + pub param_after_hash: Vec, /// `None` when the header wrote no `#( ... )`; an empty `Some` is a /// written-but-empty `#()`. pub param_ports: Option>, @@ -1003,8 +1201,12 @@ pub struct ClassDecl { pub extends: Option, /// Interface classes named by `implements A, B`. pub implements: Vec, + /// Comments written between the header's last token and its `;`. + pub before_semi: Vec, pub items: Vec, pub dangling: Vec, + /// Comments written in the two gaps of `endclass : c`. + pub end_label_comments: Box, /// Label after `endclass :`. pub end_label: Option, /// Byte range of `end_label`. @@ -1018,7 +1220,7 @@ impl ClassDecl { /// `extends`. It is an ordinary [`ClassDecl`] everywhere else: same /// header, same `endclass`, same symbol. pub fn is_interface_class(&self) -> bool { - self.prefix.iter().any(|word| word == "interface") + self.prefix.iter().any(|q| q.text == "interface") } } @@ -1028,6 +1230,8 @@ impl ClassDecl { /// way. #[derive(Debug)] pub struct ClassExtends { + /// Comments written between the `#` of an override list and its `(`. + pub after_hash: Vec, /// The base-class name as written, package scope included (`pkg::base`). pub name: String, /// Byte range covering `name`, its `::` chain included. @@ -1092,6 +1296,8 @@ pub struct ClockingDecl { pub dangling: Vec, /// True when the declaration wrote an `endclocking`. pub has_end: bool, + /// Comments written in the two gaps of `endclocking : cb`. + pub end_label_comments: Box, /// Label after `endclocking :`. pub end_label: Option, /// Byte range of `end_label`. @@ -1135,8 +1341,11 @@ pub struct FunctionDecl { /// Class-member qualifiers written *before* the `function` keyword, in /// source order: `virtual`, `local`, `protected`, `static`, `pure`, /// `extern`. Empty outside a class body. - pub prefix: Vec, - pub qualifiers: Vec, + pub prefix: Vec, + /// Comments written between the `function` keyword and whatever follows + /// it (`function /*c*/ void f()`). + pub after_kw: Vec, + pub qualifiers: Vec, /// True for a body-less prototype — `extern function ...;`, /// `pure virtual function ...;` or a DPI import — which has no /// `endfunction`. @@ -1144,16 +1353,28 @@ pub struct FunctionDecl { /// The `my_class::` written before the name when an `extern` method is /// *defined* outside its class body. Kept apart from `name` so /// `src[name_span] == name` still holds for the method's own name. - pub scope: Option, + pub scope: Vec, pub ret: Option, + /// Comments written between the return type (or the keyword run) and the + /// method's name (`function void /*c*/ f()`). + pub before_name: Vec, pub name: String, /// Byte range of `name`. pub name_span: TextRange, /// False for old-style `function f;` declarations without a port list. pub has_parens: bool, + /// Comments written between the name and the `(` of the port list. + pub before_args: Vec, pub args: Vec, + /// Comments written inside an argument list with no argument to carry + /// them (`function void f( /*c*/ );`). + pub args_dangling: Vec, + /// Comments written between the header's last token and its `;`. + pub before_semi: Vec, pub stmts: Vec, pub dangling: Vec, + /// Comments written in the two gaps of `endfunction : f`. + pub end_label_comments: Box, /// Label after `endfunction :`. pub end_label: Option, /// Byte range of `end_label`. @@ -1170,20 +1391,33 @@ pub struct TaskDecl { pub dpi: Option, /// Class-member qualifiers written *before* the `task` keyword; see /// [`FunctionDecl::prefix`]. - pub prefix: Vec, - pub qualifiers: Vec, + pub prefix: Vec, + /// Comments written between the `task` keyword and what follows it. + pub after_kw: Vec, + pub qualifiers: Vec, /// True for a body-less prototype; see [`FunctionDecl::is_prototype`]. pub is_prototype: bool, /// Out-of-body definition scope; see [`FunctionDecl::scope`]. - pub scope: Option, + pub scope: Vec, + /// Comments written between the keyword run and the task's name. + pub before_name: Vec, pub name: String, /// Byte range of `name`. pub name_span: TextRange, /// False for old-style `task t;` declarations without a port list. pub has_parens: bool, + /// Comments written between the name and the `(` of the port list. + pub before_args: Vec, pub args: Vec, + /// Comments written inside an empty argument list; see + /// [`FunctionDecl::args_dangling`]. + pub args_dangling: Vec, + /// Comments written between the header's last token and its `;`. + pub before_semi: Vec, pub stmts: Vec, pub dangling: Vec, + /// Comments written in the two gaps of `endtask : t`. + pub end_label_comments: Box, /// Label after `endtask :`. pub end_label: Option, /// Byte range of `end_label`. @@ -1214,20 +1448,45 @@ pub struct LetDecl { pub struct TfArg { pub meta: Meta, pub dir: Option, + /// Comments written between the direction keyword and the type + /// (`input /*c*/ logic`). Empty when no direction was written. + pub after_dir: Vec, pub ty: DataType, + /// Comments written between the type and the argument's name + /// (`bit [3:0] /*c*/ a`). + pub before_name: Vec, pub name: String, /// Byte range of `name`. pub name_span: TextRange, pub unpacked: Vec, + /// Comments written on either side of the `=` of a default value. + pub eq_comments: Box, pub default: Option, /// Code extent of the argument declaration. pub span: TextRange, } +/// A task/function port list: its arguments, plus the comments written inside +/// a pair of parentheses that hold no argument to carry them (`f( /*c*/ )`). +#[derive(Debug, Default)] +pub struct TfPorts { + pub args: Vec, + pub dangling: Vec, +} + #[derive(Debug)] pub struct Stmt { pub meta: Meta, pub kind: StmtKind, + /// Comments written in the gap between the statement's last token and the + /// `;` that ends it (`x = 1 /* inclusive */ ;`). + /// + /// The statement is the single owner of that gap — the same rule + /// [`ConstraintItem::before_semi`] states for a constraint item — because + /// the `;` is consumed in a dozen places and read in four of them to + /// decide the statement's shape. Always empty for a kind + /// [`StmtKind::takes_semi`] is false for. + pub before_semi: Vec, /// Code extent of the statement, its `(* ... *)` attributes included. pub span: TextRange, } @@ -1235,23 +1494,31 @@ pub struct Stmt { #[derive(Debug)] pub enum StmtKind { Block { + /// Comments written in the two gaps of the `begin : name` label. + label_comments: Box, label: Option, /// Byte range of `label`. label_span: Option, stmts: Vec, dangling: Vec, + /// Comments written in the two gaps of `end : name`. + end_label_comments: Box, /// Label after `end :`. end_label: Option, /// Byte range of `end_label`. end_label_span: Option, }, ForkJoin { + /// Comments written in the two gaps of the `fork : name` label. + label_comments: Box, label: Option, /// Byte range of `label`. label_span: Option, join_kw: String, stmts: Vec, dangling: Vec, + /// Comments written in the two gaps of `join : name`. + end_label_comments: Box, /// Label after `join :` (any join kind). end_label: Option, /// Byte range of `end_label`. @@ -1259,6 +1526,8 @@ pub enum StmtKind { }, If { qualifier: Option, + /// Comments written between the `if` keyword and its `(`. + after_kw: Vec, cond: Expr, then: Box, /// Comments written between the then-branch and the `else` keyword. @@ -1270,6 +1539,8 @@ pub enum StmtKind { Case { qualifier: Option, kw: String, + /// Comments written between the `case` keyword and its `(`. + after_kw: Vec, expr: Expr, /// True for `case (expr) inside`, whose labels may be `[lo:hi]` /// value ranges. @@ -1281,6 +1552,8 @@ pub enum StmtKind { init: Vec, cond: Option, step: Vec, + /// The seven fixed slots of a `for ( … ; … ; … )` header. + comments: Box, body: Box, }, While { @@ -1290,6 +1563,10 @@ pub enum StmtKind { DoWhile { body: Box, cond: Expr, + /// The `while /*a*/ ( /*b*/ cond /*c*/ )` slots. A `do ... while` is + /// the one loop with no body *after* its parentheses, so there is + /// nothing for `Fmt::header_parens` to take a comment back from. + comments: Box, }, Repeat { count: Expr, @@ -1307,7 +1584,13 @@ pub enum StmtKind { /// variables. Foreach { target: Expr, - vars: Vec, + vars: Vec, + /// Comments written around the loop-variable bracket + /// (`foreach (q /*a*/ [ … ] /*never*/)`) — `before_open`, + /// `after_open` and `before_close` only. + var_comments: Box, + /// The `foreach /*a*/ ( /*b*/ … /*c*/ ) /*d*/ body` slots. + comments: Box, body: Box, }, /// `randcase w1 : stmt; w2 : stmt; endcase` (IEEE 1800 §18.16) — a `case` @@ -1378,7 +1661,11 @@ pub enum StmtKind { ParamDecl(ParamDecl), /// Old-style task/function port declaration: `input [7:0] a;` PortDecl(PortDecl), - Return(Option), + Return { + /// Comments written between `return` and its value. + after_kw: Vec, + expr: Option, + }, Break, Continue, Disable(String), @@ -1405,10 +1692,54 @@ pub enum StmtKind { Error(RawText), } +impl StmtKind { + /// True for the kinds whose own last token is followed by a `;` this + /// statement wrote — the kinds [`Stmt::before_semi`] can be non-empty + /// for. + /// + /// A `begin`/`fork` block, an `if`, a `case`, a loop and a labelled + /// statement all end in a *body*, whose own last statement owns whatever + /// `;` stands there; [`StmtKind::Null`] **is** its `;`; a directive, a + /// macro call and a verbatim capture carry their own text. The three + /// shape-deciding kinds — a timing control, a `wait` and an immediate + /// assertion — take one only in the branch that wrote no body, which is + /// exactly the branch the parser read the `;` in. + /// + /// One answer, read by the parser (which consumes the `;`) and by the + /// formatter (which writes it back), so the two cannot disagree about who + /// owns the gap in front of it. + pub fn takes_semi(&self) -> bool { + match self { + StmtKind::Assign { .. } + | StmtKind::ExprStmt(_) + | StmtKind::EventTrigger(_) + | StmtKind::ForceRelease { .. } + | StmtKind::VarDecl(_) + | StmtKind::ParamDecl(_) + | StmtKind::PortDecl(_) + | StmtKind::Return { .. } + | StmtKind::Break + | StmtKind::Continue + | StmtKind::Disable(_) + | StmtKind::WaitFork + | StmtKind::DoWhile { .. } => true, + StmtKind::Timing { stmt, .. } => stmt.is_none(), + StmtKind::Wait { stmt, .. } => stmt.is_none(), + StmtKind::Assert { then, els, .. } => then.is_none() && els.is_none(), + _ => false, + } + } +} + #[derive(Debug)] pub enum TimingControl { /// `#expr` - Delay(Expr), + Delay { + /// Comments written between the `#` and the delay value + /// (`# /*c*/ 10`). + after_hash: Vec, + expr: Expr, + }, /// `@(...)`, `@*` Event(SensList), } @@ -1419,6 +1750,9 @@ pub struct CaseItem { /// Empty means `default`. Each label carries the comments written around /// it, so a comment between two labels stays between them. pub labels: Vec, + /// Comments written between the last label — or the `default` keyword — + /// and the `:` that ends the label list. + pub before_colon: Vec, pub stmt: Stmt, /// Code extent of the case item, its body included. pub span: TextRange, @@ -1428,6 +1762,8 @@ pub struct CaseItem { pub struct ForInit { /// Declared type for `for (int i = 0; ...)`. pub ty: Option, + /// Comments written between that type and the name (`for (int /*c*/ i`). + pub before_name: Vec, pub assign: SimpleAssign, } @@ -1435,9 +1771,32 @@ pub struct ForInit { pub struct SimpleAssign { pub lhs: Expr, pub op: String, + /// Comments written on either side of the operator. + pub op_comments: Box, pub rhs: Expr, } +/// Comments written in the fixed slots of a `for ( init ; cond ; step )` +/// header (IEEE 1800 §12.7.1). Seven punctuation positions, none of which has +/// anything beside it to carry a comment. +#[derive(Debug, Default)] +pub struct ForComments { + /// Between `for` and the `(`. + pub after_kw: Vec, + /// Just inside the `(`. + pub after_open: Vec, + /// Between the initialisers and the first `;`. + pub before_first_semi: Vec, + /// Between the first `;` and the condition. + pub after_first_semi: Vec, + /// Between the condition and the second `;`. + pub before_second_semi: Vec, + /// Between the second `;` and the step list. + pub after_second_semi: Vec, + /// Between the step list and the `)`. + pub before_close: Vec, +} + #[derive(Debug)] pub enum ForStep { Assign(SimpleAssign), @@ -1466,6 +1825,10 @@ pub enum ExprKind { Empty(Vec), Unary { op: String, + /// Comments written between the operator and its operand + /// (`~ /*c*/ a`), kept so neither drifts across the other. Boxed for + /// the reason [`ArgComments`] gives. + comments: Box>, expr: Box, }, Binary { @@ -1500,20 +1863,28 @@ pub enum ExprKind { Index { base: Box, index: Box, + /// `q /*a*/ [ /*b*/ i /*c*/ ]`. + comments: Box, }, Range { base: Box, op: String, msb: Box, lsb: Box, + /// Every slot of `q /*a*/ [ /*b*/ m /*c*/ : /*d*/ l /*e*/ ]`. + comments: Box, }, Member { base: Box, name: String, + /// `a /*a*/ . /*b*/ b`. + comments: Box, }, Scope { base: Box, name: String, + /// `pkg /*a*/ :: /*b*/ item`. + comments: Box, }, /// A parameterized class reference: the `uvm_config_db#(virtual bus_if)` /// of `uvm_config_db#(virtual bus_if)::get(...)`. The `#( ... )` is @@ -1555,6 +1926,8 @@ pub enum ExprKind { /// (`$bits(x)'(y)`) — IEEE 1800 §6.24.1. Cast { ty: Box, + /// Comments written in the cast's own four slots. + comments: Box, expr: Box, /// True for the `ty'{...}` spelling (IEEE 1800 §10.9.1), where the /// argument is an assignment pattern. The pattern brings its own @@ -1575,10 +1948,16 @@ pub enum ExprKind { Postfix { expr: Box, op: String, + /// Comments written between the operand and the operator + /// (`i /*c*/ ++`). Boxed for the reason [`ArgComments`] gives. + comments: Box>, }, Inside { lhs: Box, ranges: Vec, + /// Comments written on either side of the `inside` word, kept per + /// side the way every other binary operator's are. + comments: Box, }, /// `x inside `MACRO` — the set is a macro invocation that expands to a /// `{...}` set, so it is kept verbatim (corpus @@ -1587,6 +1966,9 @@ pub enum ExprKind { lhs: Box, /// The macro invocation token, exactly as written. set: String, + /// Comments written on either side of the `inside` word, as + /// [`ExprKind::Inside`] keeps them. + comments: Box, }, /// `expr with (expr)` — the iterator argument of an array method /// (IEEE 1800 §7.12): `fld.sum() with (item.bit_width)`. The argument is @@ -1629,15 +2011,18 @@ pub enum ExprKind { /// 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, + /// The four slots `.name( value )` owns. Boxed to keep `Expr` small: + /// every expression pays for the largest variant, and the tree is + /// walked recursively. + comments: Box, }, /// `[a:b]` inside an `inside` range list or value range. ValueRange { lo: Box, hi: Box, + /// `[ /*a*/ lo /*b*/ : /*c*/ hi /*d*/ ]` — the same four inner slots + /// an [`ExprKind::Range`] has, read by the same shared parse. + comments: Box, }, /// A type used in expression position (`parameter type T = logic [7:0]`). Type(DataType), @@ -1649,6 +2034,114 @@ pub enum ExprKind { }, } +/// Comments written in the fixed slots of a **postfix segment** or a +/// **bracketed range** — the one shape the grammar writes in five places: +/// +/// ```text +/// base /*before_open*/ [ /*after_open*/ msb /*before_op*/ : /*after_op*/ lsb /*before_close*/ ] +/// base /*before_open*/ . /*after_open*/ name +/// base /*before_open*/ :: /*after_open*/ name +/// ``` +/// +/// A member or scope segment uses the first two slots, an index the first +/// two and the last, a range all five. Kept per slot for the reason +/// [`TernaryComments`] gives: printed anywhere else, a comment crosses a +/// token and the safety net refuses the file. +/// +/// Boxed by every holder, as [`CallComments`] is: a segment with a comment in +/// it is rare and there is a `.`, a `::` or a `[` in every other line of real +/// code. +#[derive(Debug, Clone, Default)] +pub struct SegmentComments { + /// Between the base and the `.`, `::` or `[` that opens the segment. + pub before_open: Vec, + /// Just after that token. + pub after_open: Vec, + /// Between the first operand and the `:` / `+:` / `-:` of a range. + pub before_op: Vec, + /// Just after that operator. + pub after_op: Vec, + /// Just before the closing `]`. + pub before_close: Vec, +} + +impl SegmentComments { + /// True when nothing was written in any slot — the common case, laid out + /// without any comment handling at all. + pub fn is_empty(&self) -> bool { + self.before_open.is_empty() + && self.after_open.is_empty() + && self.before_op.is_empty() + && self.after_op.is_empty() + && self.before_close.is_empty() + } + + /// True when nothing was written before the opening token. The opener's + /// slot is the one a caller can print for itself, so a printer that has + /// already emitted the base asks this before spacing. + pub fn opens_clean(&self) -> bool { + self.before_open.is_empty() + } +} + +/// Comments written in the fixed slots of a `ty'(expr)` cast — the one +/// expression whose punctuation is three tokens with nothing between them to +/// carry a comment. +/// +/// The `ty'{...}` spelling writes no `(` `)` of its own, so only the first +/// two slots can be non-empty there. +#[derive(Debug, Clone, Default)] +pub struct CastComments { + /// Between the casting type and the `'`. + pub before_tick: Vec, + /// Between the `'` and the `(` (or the `{` of a pattern). + pub after_tick: Vec, + /// Just inside the `(`. + pub after_open: Vec, + /// Just before the `)`. + pub before_close: Vec, +} + +impl CastComments { + /// True when nothing was written in any slot — the common case. + pub fn is_empty(&self) -> bool { + self.before_tick.is_empty() + && self.after_tick.is_empty() + && self.after_open.is_empty() + && self.before_close.is_empty() + } +} + +/// Comments written in the gaps of a `struct|union [tagged] [packed] +/// [signing] {` header — four keyword positions with nothing between them to +/// carry a comment. +#[derive(Debug, Clone, Default)] +pub struct StructHeaderComments { + /// After `struct` / `union`. + pub after_kw: Vec, + /// After `tagged`, if written. + pub after_tagged: Vec, + /// After `packed`, if written. + pub after_packed: Vec, + /// After the signing word, if written. + pub after_signing: Vec, +} + +/// Comments written in the fixed slots of a `.name( value )` — a named call +/// argument or a port connection, which are the same four gaps. +#[derive(Debug, Clone, Default)] +pub struct ArgComments { + /// Between the `.` and the name. + pub after_dot: Vec, + /// Between the name and the `(`. + pub before_open: Vec, + /// Just inside the `(`. + pub after_open: Vec, + /// Between the value and the closing `)` (`.src(5'd0 /* x0 */)`), + /// printed back inside the parens. + pub close: Vec, +} + /// Comments written next to a binary operator. Kept per side so neither /// drifts across the operator: `a && // why` and `a // why` + `&& b` are /// different token streams. @@ -1750,10 +2243,10 @@ pub struct ExprItem { pub struct ConstraintDecl { /// The member qualifiers written before the keyword — `static`, /// `extern`, `pure`, `local`, `protected` — in source order. - pub qualifiers: Vec, + pub qualifiers: Vec, /// The `my_class::` of an out-of-block definition, as written and /// without the trailing `::`. `None` for the ordinary in-class form. - pub scope: Option, + pub scope: Vec, pub name: Name, /// Comments written between the `constraint` keyword and the name. pub before_name: Vec, @@ -1875,7 +2368,10 @@ pub enum ConstraintItemKind { /// [`StmtKind::Foreach`] spells one. Foreach { array: Expr, - vars: Vec, + vars: Vec, + /// Comments written around the loop-variable bracket, as + /// [`StmtKind::Foreach`] keeps them. + var_comments: Box, /// Comments written in the `foreach ( ... )` header's four slots. comments: Box, set: ConstraintSet, @@ -1957,7 +2453,7 @@ pub struct DistItem { pub struct CovergroupDecl { /// The member qualifiers written before the keyword (`local`, `static`, /// `protected`), in source order. - pub qualifiers: Vec, + pub qualifiers: Vec, /// Comments written between the `covergroup` keyword and the name. pub before_name: Vec, pub name: Name, @@ -1976,6 +2472,8 @@ pub struct CovergroupDecl { pub items: Vec, /// Comments written after the last item and before `endgroup`. pub dangling: Vec, + /// Comments written in the two gaps of `endgroup : g`. + pub end_label_comments: Box, /// The label of `endgroup : g`. pub end_label: Option, /// Comments written between `endgroup` (or its label) and a stray `;`. @@ -2351,3 +2849,21 @@ pub struct BinsofSel { pub after_intersect: Vec, pub intersect: Option>, } + +/// The sizes the comment-slots round pinned, so the next slot added inline +/// fails here rather than as a stack overflow in a debug-build test that +/// only runs with the corpus checked out (docs/features/comment-slots). +/// `Expr` is walked recursively; every expression-level comment struct is +/// boxed to keep it at its pre-round size. +#[cfg(all(test, target_pointer_width = "64"))] +mod size_pins { + use super::*; + use std::mem::size_of; + + #[test] + fn expr_stmt_and_stmt_kind_stay_within_their_pinned_sizes() { + assert!(size_of::() <= 96, "Expr is {} bytes: box the new field", size_of::()); + assert!(size_of::() <= 392, "StmtKind is {} bytes", size_of::()); + assert!(size_of::() <= 552, "Stmt is {} bytes", size_of::()); + } +} diff --git a/crates/vlog_parser/src/parser.rs b/crates/vlog_parser/src/parser.rs index 757ce70..ac896ee 100644 --- a/crates/vlog_parser/src/parser.rs +++ b/crates/vlog_parser/src/parser.rs @@ -243,6 +243,22 @@ struct ParamPortList { ports: Option>, directives: Vec, dangling: Vec, + /// Comments written between the `#` and the `(`. + after_hash: Vec, +} + +/// A task/function body: its statements, the comments left dangling before +/// the closing keyword, and that keyword's own `: name` label. +type TfBody = (Vec, Vec, Box, Option); + +/// The three pieces a `foreach` header's `array[i, j]` yields: what is +/// iterated, the loop variables, and the comments written around their +/// bracket. Both callers — the statement and the constraint item — store all +/// three. +struct ForeachTarget { + expr: Expr, + vars: Vec, + comments: Box, } /// What [`Parser::take_list_directives`] found between two list elements. @@ -297,6 +313,17 @@ pub struct Parser<'a> { /// front of it. Set and cleared around that one operand, and never left /// set on an error path. no_with: bool, + /// The comments written in the gap before the `;` that ends the statement + /// currently being parsed — `x = 1 /* inclusive */ ;`. + /// + /// The `;` is consumed in a dozen places (some of which read it to decide + /// the statement's *shape*), so the gap is handed up here instead of + /// through a dozen return types, and [`Parser::parse_stmt_inner`] moves it + /// onto [`Stmt::before_semi`] — the single owner of that gap, the way + /// `ConstraintItem::before_semi` is of a constraint item's. Cleared before + /// every statement kind is parsed, so nothing can leak from one statement + /// to the next. + semi_comments: Vec, } /// Everything a speculative parse may move, so that a failed one can be put @@ -650,6 +677,7 @@ impl<'a> Parser<'a> { covergroups: 0, covergroup_fallbacks: 0, no_with: false, + semi_comments: Vec::new(), } } @@ -880,7 +908,12 @@ impl<'a> Parser<'a> { Err(e) if self.tolerant => { let raw = self.recover(start_pos, start, e); let span = raw.span; - Ok(Stmt { meta: Meta::default(), kind: StmtKind::Error(raw), span }) + Ok(Stmt { + meta: Meta::default(), + kind: StmtKind::Error(raw), + before_semi: Vec::new(), + span, + }) } other => other, } @@ -1204,10 +1237,13 @@ impl<'a> Parser<'a> { fn parse_named_arg(&mut self) -> PResult { let start = self.here(); self.bump(); // . + let after_dot = self.take_gap(); let Name { text: name, span: name_span } = self.expect_name()?; + let before_open = self.take_before_open("("); let mark = self.pending_trailing.len(); let paren_start = self.here(); self.expect_sym("(")?; + let mut after_open = Vec::new(); 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 @@ -1216,6 +1252,7 @@ impl<'a> Parser<'a> { self.bump(); (self.expr_at(paren_start, ExprKind::Empty(comments)), Vec::new()) } else { + after_open = self.take_gap(); let value = self.parse_expr()?; // A comment before the closing `)` (`.src(5'd0 /* x0 */)`) // stays inside the parens, as a connection's does. @@ -1225,20 +1262,48 @@ impl<'a> Parser<'a> { }; Ok(self.expr_at( start, - ExprKind::NamedArg { name, name_span, value: Box::new(value), close_comments }, + ExprKind::NamedArg { + name, + name_span, + value: Box::new(value), + comments: Box::new(ArgComments { + after_dot, + before_open, + after_open, + close: close_comments, + }), + }, )) } /// `[lo:hi]` — a value range standing as a list element (a - /// `case ... inside` label). The cursor is on the `[`. + /// `case ... inside` label, an `inside` set member). The cursor is on + /// the `[`. + /// + /// The one place the `[a:b]` grammar is written, after this round: the + /// `inside` set used to inline a hand-copy of it and + /// [`Parser::parse_dims`] a second one, and each copy lost the comments + /// the others lost. See `docs/features/comment-slots/README.md`. fn parse_value_range(&mut self) -> PResult { let start = self.here(); + let mut comments = SegmentComments { before_open: self.take_gap(), ..Default::default() }; self.bump(); // [ + comments.after_open = self.take_gap(); let lo = self.parse_expr()?; + comments.before_op = self.gap_before(":"); self.expect_sym(":")?; + comments.after_op = self.take_gap(); let hi = self.parse_expr()?; + comments.before_close = self.gap_before("]"); self.expect_sym("]")?; - Ok(self.expr_at(start, ExprKind::ValueRange { lo: Box::new(lo), hi: Box::new(hi) })) + Ok(self.expr_at( + start, + ExprKind::ValueRange { + lo: Box::new(lo), + hi: Box::new(hi), + comments: Box::new(comments), + }, + )) } /// Continue a comma-separated expression list whose first element is @@ -1425,11 +1490,20 @@ impl<'a> Parser<'a> { /// keyword (`end`, `join`, `endfunction`, ...), if present. Kept on the /// node so the formatter can print it back. fn parse_label(&mut self) -> PResult> { - if self.eat_sym(":") { - Ok(Some(self.expect_name()?)) - } else { - Ok(None) + Ok(self.parse_label_with()?.1) + } + + /// The same, plus the comments written in the label's two gaps + /// (`endgroup /*a*/ : /*b*/ cg`). Every construct that keeps a label + /// keeps these beside it, so neither comment drifts across the `:`. + fn parse_label_with(&mut self) -> PResult<(Box, Option)> { + let before_colon = self.gap_before(":"); + if !self.eat_sym(":") { + return Ok((Box::default(), None)); } + let after_colon = self.take_gap(); + let name = self.expect_name()?; + Ok((Box::new(LabelComments { before_colon, after_colon }), Some(name))) } /// The first token past the run of [`MEMBER_QUALIFIERS`] at the cursor — @@ -1446,36 +1520,51 @@ impl<'a> Parser<'a> { } /// Consume the run of [`MEMBER_QUALIFIERS`] at the cursor, in source order. - fn take_member_prefix(&mut self) -> Vec { + fn take_member_prefix(&mut self) -> Vec { let mut out = Vec::new(); while self.cur().kind == TokenKind::Keyword && MEMBER_QUALIFIERS.contains(&self.cur().text.as_str()) { - out.push(self.bump().text); + let text = self.bump().text; + // `local /*c*/ static` — the gap after each keyword is that + // keyword's, so two comments in one run stay in their own gaps. + out.push(Qualifier { text, after: self.take_gap() }); } out } /// A method name, with the `my_class::` scope of an out-of-body /// definition split off so the returned [`Name`] is only the method's own. - fn parse_method_name(&mut self) -> PResult<(Option, Name)> { + fn parse_method_name(&mut self) -> PResult<(Vec, Name)> { let mut name = self.expect_name()?; - let mut scope: Option = None; + let mut scope: Vec = Vec::new(); while self.cur().is_sym("::") { + let before_sep = self.take_gap(); self.bump(); + let after_sep = self.take_gap(); let next = self.expect_name()?; - match &mut scope { - Some(s) => { - s.push_str("::"); - s.push_str(&name.text); - } - None => scope = Some(name.text), - } + scope.push(ScopeSeg { name, before_sep, after_sep }); name = next; } Ok((scope, name)) } + /// Append `::` plus the next segment to a joined scoped name, keeping the + /// whitespace an escaped segment needs to terminate. + /// + /// `\my-pkg ::\state-t` is three tokens; joined tightly it reprints as + /// `\my-pkg::\state-t`, which is one — the corruption the safety net had + /// to catch before this round (`docs/topo.md` §2.9-21). Whitespace is an + /// escaped identifier's only terminator, so it is part of the name as + /// written and belongs in the joined text. + fn push_scope_segment(joined: &mut String, segment: &str) { + if joined.rsplit(char::is_whitespace).next().is_some_and(|s| s.contains('\\')) { + joined.push(' '); + } + joined.push_str("::"); + joined.push_str(segment); + } + /// A `pkg::name` chain, returned as the joined text plus the /// range covering the whole chain. fn parse_scoped_name(&mut self) -> PResult<(String, TextRange)> { @@ -1483,8 +1572,8 @@ impl<'a> Parser<'a> { let mut name = self.expect_ident()?; while self.cur().is_sym("::") { self.bump(); - name.push_str("::"); - name.push_str(&self.expect_ident()?); + let segment = self.expect_ident()?; + Self::push_scope_segment(&mut name, &segment); } Ok((name, self.span_from(start))) } @@ -1811,7 +1900,7 @@ impl<'a> Parser<'a> { Ok(ItemKind::GenerateRegion { items, dangling }) } "if" => self.parse_gen_if().map(ItemKind::GenIf), - "for" => self.parse_gen_for().map(ItemKind::GenFor), + "for" => self.parse_gen_for().map(|g| ItemKind::GenFor(Box::new(g))), "case" => self.parse_gen_case().map(ItemKind::GenCase), "function" => self.parse_function().map(ItemKind::Function), "task" => self.parse_task().map(ItemKind::Task), @@ -1942,7 +2031,9 @@ impl<'a> Parser<'a> { fn parse_package(&mut self) -> PResult { let kw = self.bump().text; + let before_name = self.take_gap(); let Name { text: name, span: name_span } = self.expect_name()?; + let before_semi = self.gap_before(";"); self.expect_sym(";")?; let mut items = Vec::new(); while !self.at_body_end("endpackage") { @@ -1950,8 +2041,20 @@ impl<'a> Parser<'a> { } let dangling = self.take_dangling(); self.expect_closer("endpackage")?; - let (end_label, end_label_span) = split_label(self.parse_label()?); - Ok(ItemKind::Package { kw, name, name_span, items, dangling, end_label, end_label_span }) + let (end_label_comments, end_name) = self.parse_label_with()?; + let (end_label, end_label_span) = split_label(end_name); + Ok(ItemKind::Package { + kw, + before_name, + name, + name_span, + before_semi, + items, + dangling, + end_label_comments, + end_label, + end_label_span, + }) } fn parse_import_list(&mut self) -> PResult> { @@ -2080,11 +2183,15 @@ impl<'a> Parser<'a> { // prototypes, parameters and typedefs may stand in one — and legality // is a checker's business, not a formatter's. if self.cur().is_kw("interface") && self.nth(1).is_kw("class") { - prefix.push(self.bump().text); + let text = self.bump().text; + prefix.push(Qualifier { text, after: self.take_gap() }); } self.expect_kw("class")?; + let mut before_name = self.take_gap(); let lifetime = if self.cur().is_kw("static") || self.cur().is_kw("automatic") { - Some(self.bump().text) + let kw = self.bump().text; + before_name.append(&mut self.take_gap()); + Some(kw) } else { None }; @@ -2103,6 +2210,7 @@ impl<'a> Parser<'a> { } } } + let before_semi = self.gap_before(";"); self.expect_sym(";")?; let mut items = Vec::new(); while !self.at_body_end("endclass") { @@ -2110,20 +2218,25 @@ impl<'a> Parser<'a> { } let dangling = self.take_dangling(); self.expect_closer("endclass")?; - let (end_label, end_label_span) = split_label(self.parse_label()?); + let (end_label_comments, end_name) = self.parse_label_with()?; + let (end_label, end_label_span) = split_label(end_name); Ok(ClassDecl { prefix, + before_name, lifetime, name, name_span, param_comments, + param_after_hash: params.after_hash, param_ports: params.ports, param_directives: params.directives, param_dangling: params.dangling, extends, implements, + before_semi, items, dangling, + end_label_comments, end_label, end_label_span, }) @@ -2137,9 +2250,11 @@ impl<'a> Parser<'a> { let (name, name_span) = self.parse_scoped_name()?; let param_comments = self.take_before_open("#"); let mut params = None; + let mut after_hash = Vec::new(); let mut param_directives = Vec::new(); if self.cur().is_sym("#") { self.bump(); + after_hash = self.take_gap(); self.expect_sym("(")?; let mut list = Vec::new(); self.take_list_directives(&mut param_directives, 0); @@ -2172,6 +2287,7 @@ impl<'a> Parser<'a> { params = Some(list); } Ok(ClassExtends { + after_hash, name, name_span, param_comments, @@ -2253,6 +2369,28 @@ impl<'a> Parser<'a> { /// the gap belongs to this construct only if the token that closes it was /// written. [`Parser::take_before_open`] is the same idea; this is it /// spelled for a closer rather than an opener. + /// Consume the `;` that ends a statement, recording the comments written + /// in front of it on [`Parser::semi_comments`] for + /// [`Parser::parse_stmt_inner`] to move onto the statement. + fn expect_stmt_semi(&mut self) -> PResult<()> { + self.semi_comments = self.gap_before(";"); + self.expect_sym(";")?; + Ok(()) + } + + /// The same for the sites that *read* the `;` to decide the statement's + /// shape (`#10;` versus `#10 x = 1;`). Takes nothing when the cursor is + /// not on a `;`, because [`Parser::gap_before`] does not. + fn eat_stmt_semi(&mut self) -> bool { + let gap = self.gap_before(";"); + if self.eat_sym(";") { + self.semi_comments = gap; + true + } else { + false + } + } + fn gap_before(&mut self, sym: &str) -> Vec { if self.cur().is_sym(sym) { self.take_gap() @@ -2486,12 +2624,19 @@ impl<'a> Parser<'a> { let mut comments = HeaderComments { after_kw: self.take_gap(), ..Default::default() }; self.expect_sym("(")?; comments.after_open = self.take_gap(); - let (array, vars) = self.parse_foreach_target()?; + let ForeachTarget { expr: array, vars, comments: var_comments } = + self.parse_foreach_target()?; comments.before_close = self.gap_before(")"); self.expect_sym(")")?; comments.before_body = self.gap_before("{"); let set = self.parse_constraint_set()?; - Ok(ConstraintItemKind::Foreach { array, vars, comments: Box::new(comments), set }) + Ok(ConstraintItemKind::Foreach { + array, + vars, + var_comments, + comments: Box::new(comments), + set, + }) } /// True when the cursor opens `solve a, b before c, d;`. Both words are @@ -2759,7 +2904,7 @@ impl<'a> Parser<'a> { let before_name = self.take_gap(); let name = self.expect_name()?; let before_args = self.take_before_open("("); - let args = if self.cur().is_sym("(") { Some(self.parse_tf_ports()?) } else { None }; + let args = if self.cur().is_sym("(") { Some(self.parse_tf_ports()?.args) } else { None }; let event = self.parse_coverage_event()?; let before_semi = self.gap_before(";"); self.expect_sym(";")?; @@ -2770,7 +2915,7 @@ impl<'a> Parser<'a> { // records the tolerant diagnostic — one message, from one place, and // the same one v0.27.0 wrote. self.expect_kw("endgroup")?; - let end_label = self.parse_label()?; + let (end_label_comments, end_label) = self.parse_label_with()?; let before_end_semi = self.gap_before(";"); let end_semi = self.eat_sym(";"); Ok(CovergroupDecl { @@ -2783,6 +2928,7 @@ impl<'a> Parser<'a> { before_semi, items, dangling, + end_label_comments, end_label, before_end_semi, end_semi, @@ -2829,7 +2975,7 @@ impl<'a> Parser<'a> { self.bump(); let before_args = self.take_before_open("("); let has_parens = self.cur().is_sym("("); - let args = self.parse_tf_ports()?; + let args = self.parse_tf_ports()?.args; return Ok(Some(CoverageEvent::Sample(Box::new(SampleFn { before_with, after_with, @@ -3609,10 +3755,11 @@ impl<'a> Parser<'a> { fn parse_specparam_decl(&mut self) -> PResult { let kw = self.bump().text; + let after_kw = self.take_gap(); let ty = self.parse_opt_data_type()?; let declarators = self.parse_declarators()?; self.expect_sym(";")?; - Ok(ParamDecl { kw, is_type: false, ty, declarators }) + Ok(ParamDecl { kw, after_kw, is_type: false, ty, declarators }) } /// `alias a = b = c;` (IEEE 1800 §10.11) — one bidirectional connection @@ -4129,6 +4276,7 @@ impl<'a> Parser<'a> { /// only the closing keyword differs, so `end_kw` is the whole difference. fn parse_module(&mut self, end_kw: &str) -> PResult { let kw = self.bump().text; + let before_name = self.take_gap(); let Name { text: name, span: name_span } = self.expect_name()?; let mut imports = Vec::new(); while self.cur().is_kw("import") { @@ -4142,9 +4290,11 @@ impl<'a> Parser<'a> { ports: param_ports, directives: param_directives, dangling: param_dangling, + after_hash: param_after_hash, } = self.parse_param_port_list()?; let port_comments = self.take_before_open("("); let (ports, port_dangling, port_directives) = self.parse_port_list()?; + let before_semi = self.gap_before(";"); self.expect_sym(";")?; let mut items = Vec::new(); while !self.at_body_end(end_kw) { @@ -4152,10 +4302,13 @@ impl<'a> Parser<'a> { } let dangling = self.take_dangling(); self.expect_closer(end_kw)?; - let (end_label, end_label_span) = split_label(self.parse_label()?); + let (end_label_comments, end_name) = self.parse_label_with()?; + let (end_label, end_label_span) = split_label(end_name); Ok(Module { kw, + before_name, name, + param_after_hash, name_span, imports, param_comments, @@ -4166,8 +4319,10 @@ impl<'a> Parser<'a> { ports, port_directives, port_dangling, + before_semi, items, dangling, + end_label_comments, end_label, end_label_span, }) @@ -4261,6 +4416,7 @@ impl<'a> Parser<'a> { items: Vec::new(), dangling: Vec::new(), has_end: false, + end_label_comments: Box::default(), end_label: None, end_label_span: None, }); @@ -4271,13 +4427,15 @@ impl<'a> Parser<'a> { } let dangling = self.take_dangling(); self.expect_closer("endclocking")?; - let (end_label, end_label_span) = split_label(self.parse_label()?); + let (end_label_comments, end_name) = self.parse_label_with()?; + let (end_label, end_label_span) = split_label(end_name); Ok(ClockingDecl { is_default, name, event, items, dangling, + end_label_comments, has_end: true, end_label, end_label_span, @@ -4363,6 +4521,7 @@ impl<'a> Parser<'a> { return Ok(out); } self.bump(); + out.after_hash = self.take_gap(); self.expect_sym("(")?; let mut list = Vec::new(); self.take_list_directives(&mut out.directives, 0); @@ -4395,46 +4554,75 @@ impl<'a> Parser<'a> { Ok(out) } + /// An optional `= value`, with the comments written on either side of the + /// `=` (`W /*a*/ = /*b*/ 8`). The value is read by `parse`, since a + /// `type` parameter's default is a type and everything else's is an + /// expression. + fn parse_eq_default( + &mut self, + parse: fn(&mut Self) -> PResult, + ) -> PResult<(Box, Option)> { + if !self.cur().is_sym("=") { + return Ok((Box::default(), None)); + } + let before = self.take_gap(); + self.bump(); + let after = self.take_gap(); + let value = parse(self)?; + Ok((Box::new(BinaryComments { before, after }), Some(value))) + } + fn parse_param_port(&mut self) -> PResult { let start = self.here(); let mut meta = self.take_meta(); + let mut after_kw = Vec::new(); let kw = if self.cur().is_kw("parameter") || self.cur().is_kw("localparam") { - Some(self.bump().text) + let word = self.bump().text; + after_kw = self.take_gap(); + Some(word) } else { None }; if self.eat_kw("type") { + let before_name = self.take_gap(); let Name { text: name, span: name_span } = self.expect_name()?; - let default = if self.eat_sym("=") { Some(self.parse_type_expr()?) } else { None }; + let (eq_comments, default) = self.parse_eq_default(|p| p.parse_type_expr())?; let span = self.span_from(start); meta.trailing = self.take_trailing(); return Ok(ParamPort { meta, kw, + after_kw, ty: DataType::default(), is_type: true, + before_name, name, name_span, unpacked: Vec::new(), + eq_comments, default, comma: false, span, }); } let ty = self.parse_opt_data_type()?; + let before_name = self.take_gap(); let Name { text: name, span: name_span } = self.expect_name()?; let unpacked = self.parse_dims()?; - let default = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None }; + let (eq_comments, default) = self.parse_eq_default(|p| p.parse_expr())?; let span = self.span_from(start); meta.trailing = self.take_trailing(); Ok(ParamPort { meta, kw, + after_kw, ty, is_type: false, + before_name, name, name_span, unpacked, + eq_comments, default, comma: false, span, @@ -4500,10 +4688,16 @@ impl<'a> Parser<'a> { // Comments on their own lines before the `)` belong inside it. let dangling = self.take_dangling(); self.expect_sym(")")?; - // A trailing comment on the closing line belongs to the last port. - if let Some(last) = ports.last_mut() { - if last.meta.trailing.is_none() { - last.meta.trailing = self.take_trailing(); + // A trailing comment on the closing line belongs to the last + // port — but only when the header did not write a `;` right + // after the `)`. `module m (input a) /*c*/ ;` writes its comment + // in the *header's* gap, and printing it back inside the parens + // moves it across the `)`. + if !self.cur().is_sym(";") { + if let Some(last) = ports.last_mut() { + if last.meta.trailing.is_none() { + last.meta.trailing = self.take_trailing(); + } } } Ok((PortList::Ansi(ports), dangling, directives)) @@ -4540,6 +4734,7 @@ impl<'a> Parser<'a> { None } }; + let after_dir = if dir.is_some() { self.take_gap() } else { Vec::new() }; let net = { let t = self.cur(); let is_net = t.kind == TokenKind::Keyword && NET_KEYWORDS.contains(&t.text.as_str()); @@ -4554,12 +4749,27 @@ impl<'a> Parser<'a> { } else { self.parse_opt_data_type()? }; + let before_name = self.take_gap(); let Name { text: name, span: name_span } = self.expect_name()?; let unpacked = self.parse_dims()?; - let default = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None }; + let (eq_comments, default) = self.parse_eq_default(|p| p.parse_expr())?; let span = self.span_from(start); meta.trailing = self.take_trailing(); - Ok(AnsiPort { meta, dir, net, ty, name, name_span, unpacked, default, comma: false, span }) + Ok(AnsiPort { + meta, + dir, + after_dir, + net, + ty, + before_name, + name, + name_span, + unpacked, + eq_comments, + default, + comma: false, + span, + }) } /// Does the cursor sit on an interface port that names a modport, @@ -4627,8 +4837,8 @@ impl<'a> Parser<'a> { let mut name = self.expect_ident()?; while self.cur().is_sym("::") { self.bump(); - name.push_str("::"); - name.push_str(&self.expect_ident()?); + let segment = self.expect_ident()?; + Self::push_scope_segment(&mut name, &segment); } ty.name = name; if self.at_type_params() { @@ -4647,10 +4857,22 @@ impl<'a> Parser<'a> { let mut dims = Vec::new(); while self.cur().is_sym("[") { let start = self.here(); + // A dimension owns the same five slots a postfix `[ ]` segment + // does, and for the same reason: nothing else is written where a + // comment inside the brackets could attach. + let mut comments = + SegmentComments { before_open: self.take_gap(), ..Default::default() }; self.bump(); - let kind = if self.eat_sym("]") { + comments.after_open = self.take_gap(); + let kind = if self.cur().is_sym("]") { // `[]` — a dynamic array. - dims.push(Dim { kind: DimKind::Dynamic, span: self.span_from(start) }); + comments.before_close = std::mem::take(&mut comments.after_open); + self.bump(); + dims.push(Dim { + kind: DimKind::Dynamic, + comments: Box::new(comments), + span: self.span_from(start), + }); continue; } else if self.cur().is_sym("*") && self.nth(1).is_sym("]") { // `[*]` — a wildcard-keyed associative array. @@ -4658,11 +4880,18 @@ impl<'a> Parser<'a> { DimKind::Wildcard } else { let a = self.parse_expr()?; - let b = if self.eat_sym(":") { Some(self.parse_expr()?) } else { None }; + comments.before_op = self.gap_before(":"); + let b = if self.eat_sym(":") { + comments.after_op = self.take_gap(); + Some(self.parse_expr()?) + } else { + None + }; DimKind::Range { a, b } }; + comments.before_close = self.gap_before("]"); self.expect_sym("]")?; - dims.push(Dim { kind, span: self.span_from(start) }); + dims.push(Dim { kind, comments: Box::new(comments), span: self.span_from(start) }); } Ok(dims) } @@ -4687,13 +4916,14 @@ impl<'a> Parser<'a> { fn parse_param_decl(&mut self) -> PResult { let kw = self.bump().text; + let after_kw = self.take_gap(); // `localparam type payload_t = logic [$clog2(NumReq)-1:0];` — a type // parameter outside the `#( ... )` list // (lossy_valid_to_stream_tb.sv:26). Its default is a type, not a value. let is_type = self.eat_kw("type"); let ty = if is_type { DataType::default() } else { self.parse_opt_data_type()? }; let declarators = self.parse_declarator_list(is_type)?; - Ok(ParamDecl { kw, is_type, ty, declarators }) + Ok(ParamDecl { kw, after_kw, is_type, ty, declarators }) } /// Parse declarators up to (but not consuming) the terminating `;`. @@ -4710,10 +4940,10 @@ impl<'a> Parser<'a> { let mut meta = self.take_meta(); let Name { text: name, span: name_span } = self.expect_name()?; let unpacked = self.parse_dims()?; - let init = if self.eat_sym("=") { - Some(if type_init { self.parse_type_expr()? } else { self.parse_expr()? }) + let (eq_comments, init) = if type_init { + self.parse_eq_default(|p| p.parse_type_expr())? } else { - None + self.parse_eq_default(|p| p.parse_expr())? }; let span = self.span_from(start); self.take_before_sep(&mut meta, ","); @@ -4723,7 +4953,7 @@ impl<'a> Parser<'a> { // declaration, and the `;` has not been consumed yet, so nothing // written after it can be picked up here. meta.trailing = self.take_trailing(); - out.push(Declarator { meta, name, name_span, unpacked, init, span }); + out.push(Declarator { meta, name, name_span, unpacked, eq_comments, init, span }); if !more { break; } @@ -4740,12 +4970,14 @@ impl<'a> Parser<'a> { net = Some(self.bump().text); } else if t.kind == TokenKind::Keyword && MEMBER_QUALIFIERS.contains(&t.text.as_str()) { let was_virtual = t.is_kw("virtual"); - qualifiers.push(self.bump().text); + let text = self.bump().text; + qualifiers.push(Qualifier { text, after: self.take_gap() }); // `virtual interface my_if h;` — the `interface` keyword is // part of the qualifier, not a construct of its own, and is // only ever legal directly after `virtual`. if was_virtual && self.cur().is_kw("interface") { - qualifiers.push(self.bump().text); + let text = self.bump().text; + qualifiers.push(Qualifier { text, after: self.take_gap() }); } } else { break; @@ -4762,7 +4994,7 @@ impl<'a> Parser<'a> { // fire: `virtual spi_if.tb tb_sif = sif.tb;` // (`spi_device/pre_dv/tb/spid_jedec_tb.sv:32`) is recognized here // instead, the way `parse_ansi_port` recognizes an interface port's. - let ty = if qualifiers.iter().any(|q| q == "virtual") && self.at_modport_port() { + let ty = if qualifiers.iter().any(|q| q.text == "virtual") && self.at_modport_port() { self.parse_modport_port_type()? } else { self.parse_opt_data_type()? @@ -4791,37 +5023,25 @@ impl<'a> Parser<'a> { fn parse_typedef(&mut self) -> PResult { self.expect_kw("typedef")?; - if self.eat_kw("class") { + let after_kw = self.take_gap(); + let kind = if self.eat_kw("class") { // Forward declaration: `typedef class my_class;` — no type to // alias, just a name promised to exist later in the compilation. - let Name { text: name, span: name_span } = self.expect_name()?; - self.expect_sym(";")?; - return Ok(Typedef { - name, - name_span, - unpacked: Vec::new(), - kind: TypedefKind::ForwardClass, - }); - } - if self.cur().is_kw("enum") { - let e = self.parse_enum_type()?; - let Name { text: name, span: name_span } = self.expect_name()?; - let unpacked = self.parse_dims()?; - self.expect_sym(";")?; - return Ok(Typedef { name, name_span, unpacked, kind: TypedefKind::Enum(e) }); - } - if self.cur().is_kw("struct") || self.cur().is_kw("union") { - let s = self.parse_struct_type()?; - let Name { text: name, span: name_span } = self.expect_name()?; - let unpacked = self.parse_dims()?; - self.expect_sym(";")?; - return Ok(Typedef { name, name_span, unpacked, kind: TypedefKind::Struct(s) }); - } - let ty = self.parse_opt_data_type()?; + TypedefKind::ForwardClass + } else if self.cur().is_kw("enum") { + TypedefKind::Enum(self.parse_enum_type()?) + } else if self.cur().is_kw("struct") || self.cur().is_kw("union") { + TypedefKind::Struct(self.parse_struct_type()?) + } else { + TypedefKind::Alias(self.parse_opt_data_type()?) + }; + let before_name = self.take_gap(); let Name { text: name, span: name_span } = self.expect_name()?; - let unpacked = self.parse_dims()?; + let unpacked = + if matches!(kind, TypedefKind::ForwardClass) { Vec::new() } else { self.parse_dims()? }; + let before_semi = self.gap_before(";"); self.expect_sym(";")?; - Ok(Typedef { name, name_span, unpacked, kind: TypedefKind::Alias(ty) }) + Ok(Typedef { after_kw, before_name, name, name_span, unpacked, before_semi, kind }) } /// `enum [base] { A, B = 2 }` — the cursor is on `enum` and stops on the @@ -4829,14 +5049,16 @@ impl<'a> Parser<'a> { /// anonymous enum used as a type in place (IEEE 1800 §6.19). fn parse_enum_type(&mut self) -> PResult { self.expect_kw("enum")?; + let after_kw = self.take_gap(); // The base type may be a keyword (`logic [1:0]`) or a typedef'd name // (`typedef enum action_mask_t {...}`, prim_count_pkg.sv:10). let base = if self.cur().is_sym("{") { None } else { Some(self.parse_type_ref()?) }; + let before_open = self.take_before_open("{"); self.expect_sym("{")?; let (members, directives) = self.parse_enum_members(false)?; let dangling = self.take_dangling(); self.expect_sym("}")?; - Ok(EnumType { base, members, directives, dangling }) + Ok(EnumType { after_kw, base, before_open, members, directives, dangling }) } /// An `enum`'s member list, with the `` `ifdef``-style directives written @@ -4863,12 +5085,29 @@ impl<'a> Parser<'a> { // `ReqPeriResetIdx[0:1]`, `OtbnDmem[16]` — the enum name range of // IEEE 1800 §6.19 (`rstmgr_pkg.sv:72`, `chip_env_pkg.sv:88`). let range = self.parse_dims()?; - let value = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None }; + let mut eq_comments = BinaryComments::default(); + let value = if self.cur().is_sym("=") { + eq_comments.before = self.take_gap(); + self.bump(); + eq_comments.after = self.take_gap(); + Some(self.parse_expr()?) + } else { + None + }; let span = self.span_from(start); self.take_before_sep(&mut meta, ","); let comma = self.eat_sym(","); meta.trailing = self.take_trailing(); - members.push(EnumMember { meta, name, name_span, range, value, comma, span }); + members.push(EnumMember { + meta, + name, + name_span, + range, + eq_comments: Box::new(eq_comments), + value, + comma, + span, + }); let dirs = self.take_list_directives(&mut directives, members.len()); let at_close = if to_eof { self.at_eof() } else { self.cur().is_sym("}") }; if (!comma && !dirs.any) || (dirs.any && at_close) { @@ -4884,6 +5123,8 @@ impl<'a> Parser<'a> { /// a struct member whose own type is an inline struct (uart_reg_pkg.sv:30). fn parse_struct_type(&mut self) -> PResult { let kw = self.bump().text; + let mut header_comments = + StructHeaderComments { after_kw: self.take_gap(), ..Default::default() }; // `union tagged [packed] { ... }` (IEEE 1800 §7.3.2): the discriminated // union. `tagged` is matched by text rather than reserved, for the // reason [`word_at`] gives, and only the *flag* is modelled — the @@ -4892,10 +5133,16 @@ impl<'a> Parser<'a> { let tagged = word_at(self.cur(), "tagged"); if tagged { self.bump(); + header_comments.after_tagged = self.take_gap(); } let packed = self.eat_kw("packed"); + if packed { + header_comments.after_packed = self.take_gap(); + } let signing = if self.cur().is_kw("signed") || self.cur().is_kw("unsigned") { - Some(self.bump().text) + let word = self.bump().text; + header_comments.after_signing = self.take_gap(); + Some(word) } else { None }; @@ -4906,7 +5153,8 @@ impl<'a> Parser<'a> { let mut meta = self.take_meta(); let mut qualifiers = Vec::new(); while self.cur().is_kw("rand") || self.cur().is_kw("randc") { - qualifiers.push(self.bump().text); + let text = self.bump().text; + qualifiers.push(Qualifier { text, after: self.take_gap() }); } let ty = self.parse_opt_data_type()?; let declarators = self.parse_declarators()?; @@ -4917,7 +5165,15 @@ impl<'a> Parser<'a> { } let dangling = self.take_dangling(); self.expect_sym("}")?; - Ok(StructType { kw, tagged, packed, signing, members, dangling }) + Ok(StructType { + kw, + header_comments: Box::new(header_comments), + tagged, + packed, + signing, + members, + dangling, + }) } /// A data type in a position where one is *required* — an enum base type, @@ -4932,8 +5188,8 @@ impl<'a> Parser<'a> { let mut name = self.expect_ident()?; while self.cur().is_sym("::") { self.bump(); - name.push_str("::"); - name.push_str(&self.expect_ident()?); + let segment = self.expect_ident()?; + Self::push_scope_segment(&mut name, &segment); } let mut ty = DataType { name, ..DataType::default() }; if self.at_type_params() { @@ -4963,8 +5219,11 @@ impl<'a> Parser<'a> { loop { let start = self.here(); let mut meta = self.take_meta(); - let lhs = self.parse_unary()?; let mark = self.pending_trailing.len(); + let lhs = self.parse_unary()?; + // Whatever was written on either side of the `=` stays on its own + // side of it, as a procedural assignment's does. + let op_comments = self.take_around(mark); self.expect_sym("=")?; let rhs_comments = self.take_around(mark); let rhs = self.parse_expr()?; @@ -4978,7 +5237,7 @@ impl<'a> Parser<'a> { if more { meta.trailing = self.take_trailing(); } - assigns.push(AssignPair { meta, lhs, rhs, rhs_comments, span }); + assigns.push(AssignPair { meta, lhs, rhs, op_comments, rhs_comments, span }); if !more { break; } @@ -5153,15 +5412,17 @@ impl<'a> Parser<'a> { let mut module = self.expect_ident()?; while self.cur().is_sym("::") { self.bump(); - module.push_str("::"); - module.push_str(&self.expect_ident()?); + let segment = self.expect_ident()?; + Self::push_scope_segment(&mut module, &segment); } let module_span = self.span_from(module_start); let param_comments = self.take_before_open("#"); let mut params = None; + let mut after_hash = Vec::new(); let mut param_directives = Vec::new(); if self.cur().is_sym("#") { self.bump(); + after_hash = self.take_gap(); self.expect_sym("(")?; let mut list = Vec::new(); self.take_list_directives(&mut param_directives, 0); @@ -5230,14 +5491,17 @@ impl<'a> Parser<'a> { break; } } + let before_semi = self.gap_before(";"); self.expect_sym(";")?; Ok(Instantiation { module, module_span, param_comments, + after_hash, params, param_directives, instances, + before_semi, }) } @@ -5351,13 +5615,17 @@ impl<'a> Parser<'a> { meta.leading.append(&mut tok.leading); } if self.eat_sym(".") { + let after_dot = self.take_gap(); let star = self.cur().span; if self.eat_sym("*") { let span = self.span_from(start); return Ok(Connection { meta, + after_dot, name: "*".to_string(), name_span: star, + before_open: Vec::new(), + after_open: Vec::new(), expr: None, close_comments: Vec::new(), comma: false, @@ -5365,9 +5633,11 @@ impl<'a> Parser<'a> { }); } let Name { text: name, span: name_span } = self.expect_name()?; + let before_open = self.take_before_open("("); let mark = self.pending_trailing.len(); let paren_start = self.here(); let mut close_comments = Vec::new(); + let mut after_open = Vec::new(); let expr = if self.eat_sym("(") { if self.cur().is_sym(")") { // `.name(/* unused */)`: the comments were written inside @@ -5376,6 +5646,7 @@ impl<'a> Parser<'a> { self.bump(); Some(self.expr_at(paren_start, ExprKind::Empty(inside))) } else { + after_open = self.take_gap(); let value_mark = self.pending_trailing.len(); let e = self.parse_expr_or_type()?; // `.name(x /* c */)`: written inside the parens, so it is @@ -5389,15 +5660,29 @@ impl<'a> Parser<'a> { }; let span = self.span_from(start); meta.trailing = self.take_trailing(); - Ok(Connection { meta, name, name_span, expr, close_comments, comma: false, span }) + Ok(Connection { + meta, + after_dot, + name, + name_span, + before_open, + after_open, + expr, + close_comments, + comma: false, + span, + }) } else { let e = self.parse_expr_or_type()?; let span = self.span_from(start); meta.trailing = self.take_trailing(); Ok(Connection { meta, + after_dot: Vec::new(), name: String::new(), name_span: TextRange::empty(span.start), + before_open: Vec::new(), + after_open: Vec::new(), expr: Some(e), close_comments: Vec::new(), comma: false, @@ -5495,19 +5780,38 @@ impl<'a> Parser<'a> { fn parse_gen_for(&mut self) -> PResult { self.expect_kw("for")?; + let mut comments = ForComments { after_kw: self.take_gap(), ..Default::default() }; self.expect_sym("(")?; + comments.after_open = self.take_gap(); let init_genvar = self.eat_kw("genvar"); + let after_genvar = if init_genvar { self.take_gap() } else { Vec::new() }; let lhs = self.parse_unary()?; + let mut op_comments = BinaryComments { before: self.gap_before("="), after: Vec::new() }; self.expect_sym("=")?; + op_comments.after = self.take_gap(); let rhs = self.parse_expr()?; - let init = SimpleAssign { lhs, op: "=".to_string(), rhs }; + let init = + SimpleAssign { lhs, op: "=".to_string(), op_comments: Box::new(op_comments), rhs }; + comments.before_first_semi = self.gap_before(";"); self.expect_sym(";")?; + comments.after_first_semi = self.take_gap(); let cond = self.parse_expr()?; + comments.before_second_semi = self.gap_before(";"); self.expect_sym(";")?; + comments.after_second_semi = self.take_gap(); let step = self.parse_for_step()?; + comments.before_close = self.gap_before(")"); self.expect_sym(")")?; let body = self.parse_gen_block()?; - Ok(GenFor { init, init_genvar, cond, step, body }) + Ok(GenFor { + init, + init_genvar, + after_genvar, + cond, + step, + comments: Box::new(comments), + body, + }) } fn parse_gen_case(&mut self) -> PResult { @@ -5519,7 +5823,9 @@ impl<'a> Parser<'a> { while !self.at_body_end("endcase") { let start = self.here(); let mut meta = self.take_meta(); + let mut before_colon = Vec::new(); let labels = if self.eat_kw("default") { + before_colon = self.gap_before(":"); let _ = self.eat_sym(":"); Vec::new() } else { @@ -5531,7 +5837,7 @@ impl<'a> Parser<'a> { let body = self.parse_gen_block()?; let span = self.span_from(start); meta.trailing = self.take_trailing(); - items.push(GenCaseItem { meta, labels, body, span }); + items.push(GenCaseItem { meta, labels, before_colon, body, span }); } let dangling = self.take_dangling(); self.expect_closer("endcase")?; @@ -5541,21 +5847,37 @@ impl<'a> Parser<'a> { fn parse_gen_block(&mut self) -> PResult { let start = self.here(); if self.cur().is_kw("begin") { + // The gap between whatever came before and the `begin` belongs to + // the block — nothing else was written where it could attach. + let before_kw = self.take_gap(); self.bump(); - let (label, label_span) = split_label(self.parse_label()?); + let before_colon = self.gap_before(":"); + let mut after_colon = Vec::new(); + let label_name = if self.eat_sym(":") { + after_colon = self.take_gap(); + Some(self.expect_name()?) + } else { + None + }; + let (label, label_span) = split_label(label_name); let mut items = Vec::new(); while !self.at_body_end("end") { items.push(self.item_or_recover()?); } let dangling = self.take_dangling(); self.expect_closer("end")?; - let (end_label, end_label_span) = split_label(self.parse_label()?); + let (end_label_comments, end_name) = self.parse_label_with()?; + let (end_label, end_label_span) = split_label(end_name); Ok(GenBlock { + before_kw, + before_colon, + after_colon, label, label_span, is_block: true, items, dangling, + end_label_comments, end_label, end_label_span, span: self.span_from(start), @@ -5564,8 +5886,12 @@ impl<'a> Parser<'a> { let item = self.item_or_recover()?; let span = item.span; Ok(GenBlock { + before_kw: Vec::new(), + before_colon: Vec::new(), + after_colon: Vec::new(), label: None, label_span: None, + end_label_comments: Box::default(), is_block: false, items: vec![item], dangling: Vec::new(), @@ -5589,11 +5915,14 @@ impl<'a> Parser<'a> { // `extern`, `pure virtual` and a DPI import all introduce a prototype: // a header, a `;`, and no `endfunction`. The body is written elsewhere // (in C for a DPI import, nowhere at all for a pure virtual). - let is_prototype = dpi.is_some() || prefix.iter().any(|q| q == "extern" || q == "pure"); + let is_prototype = + dpi.is_some() || prefix.iter().any(|q| q.text == "extern" || q.text == "pure"); self.expect_kw("function")?; + let after_kw = self.take_gap(); let mut qualifiers = Vec::new(); while self.cur().is_kw("automatic") || self.cur().is_kw("static") { - qualifiers.push(self.bump().text); + let text = self.bump().text; + qualifiers.push(Qualifier { text, after: self.take_gap() }); } // Return type: everything up to the identifier followed by `(` or `;`. let ret = { @@ -5611,12 +5940,15 @@ impl<'a> Parser<'a> { }; // Out-of-body definitions of an `extern` method write the class name // in front: `function void my_class::configure(...)`. + let before_name = self.take_gap(); let (scope, Name { text: name, span: name_span }) = self.parse_method_name()?; let has_parens = self.cur().is_sym("("); - let args = self.parse_tf_ports()?; + let before_args = self.take_before_open("("); + let TfPorts { args, dangling: args_dangling } = self.parse_tf_ports()?; + let before_semi = self.gap_before(";"); self.expect_sym(";")?; - let (stmts, dangling, end) = if is_prototype { - (Vec::new(), Vec::new(), None) + let (stmts, dangling, end_label_comments, end) = if is_prototype { + (Vec::new(), Vec::new(), Box::default(), None) } else { self.parse_tf_body("endfunction")? }; @@ -5628,16 +5960,22 @@ impl<'a> Parser<'a> { Ok(FunctionDecl { dpi, prefix, + after_kw, qualifiers, is_prototype, scope, ret, + before_name, name, name_span, has_parens, + before_args, args, + args_dangling, + before_semi, stmts, dangling, + end_label_comments, end_label, end_label_span, end_semi, @@ -5650,18 +5988,24 @@ impl<'a> Parser<'a> { fn parse_task_decl(&mut self, dpi: Option) -> PResult { let prefix = self.take_member_prefix(); - let is_prototype = dpi.is_some() || prefix.iter().any(|q| q == "extern" || q == "pure"); + let is_prototype = + dpi.is_some() || prefix.iter().any(|q| q.text == "extern" || q.text == "pure"); self.expect_kw("task")?; + let after_kw = self.take_gap(); let mut qualifiers = Vec::new(); while self.cur().is_kw("automatic") || self.cur().is_kw("static") { - qualifiers.push(self.bump().text); + let text = self.bump().text; + qualifiers.push(Qualifier { text, after: self.take_gap() }); } + let before_name = self.take_gap(); let (scope, Name { text: name, span: name_span }) = self.parse_method_name()?; let has_parens = self.cur().is_sym("("); - let args = self.parse_tf_ports()?; + let before_args = self.take_before_open("("); + let TfPorts { args, dangling: args_dangling } = self.parse_tf_ports()?; + let before_semi = self.gap_before(";"); self.expect_sym(";")?; - let (stmts, dangling, end) = if is_prototype { - (Vec::new(), Vec::new(), None) + let (stmts, dangling, end_label_comments, end) = if is_prototype { + (Vec::new(), Vec::new(), Box::default(), None) } else { self.parse_tf_body("endtask")? }; @@ -5671,15 +6015,21 @@ impl<'a> Parser<'a> { Ok(TaskDecl { dpi, prefix, + after_kw, qualifiers, is_prototype, scope, + before_name, name, name_span, has_parens, + before_args, args, + args_dangling, + before_semi, stmts, dangling, + end_label_comments, end_label, end_label_span, end_semi, @@ -5697,21 +6047,25 @@ impl<'a> Parser<'a> { self.expect_kw("let")?; let Name { text: name, span: name_span } = self.expect_name()?; let has_parens = self.cur().is_sym("("); - let ports = self.parse_tf_ports()?; + let ports = self.parse_tf_ports()?.args; self.expect_sym("=")?; let value = self.parse_expr()?; self.expect_sym(";")?; Ok(LetDecl { name, name_span, has_parens, ports, value }) } - fn parse_tf_ports(&mut self) -> PResult> { + fn parse_tf_ports(&mut self) -> PResult { let mut args = Vec::new(); if !self.cur().is_sym("(") { - return Ok(args); + return Ok(TfPorts::default()); } self.bump(); - if self.eat_sym(")") { - return Ok(args); + if self.cur().is_sym(")") { + // Only what was written *inside* the empty `()`, as an empty + // argument list of a call keeps. + let dangling = self.take_gap(); + self.bump(); + return Ok(TfPorts { args, dangling }); } loop { let start = self.here(); @@ -5734,31 +6088,57 @@ impl<'a> Parser<'a> { None } }; + let after_dir = if dir.is_some() { self.take_gap() } else { Vec::new() }; let ty = self.parse_opt_data_type()?; + let before_name = self.take_gap(); let Name { text: name, span: name_span } = self.expect_name()?; let unpacked = self.parse_dims()?; - let default = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None }; + let mut eq_comments = BinaryComments::default(); + let default = if self.cur().is_sym("=") { + eq_comments.before = self.take_gap(); + self.bump(); + eq_comments.after = self.take_gap(); + Some(self.parse_expr()?) + } else { + None + }; let span = self.span_from(start); self.take_before_sep(&mut meta, ","); let more = self.eat_sym(","); meta.trailing = self.take_trailing(); - args.push(TfArg { meta, dir, ty, name, name_span, unpacked, default, span }); + args.push(TfArg { + meta, + dir, + after_dir, + ty, + before_name, + name, + name_span, + unpacked, + eq_comments: Box::new(eq_comments), + default, + span, + }); if !more { break; } } + if let Some(last) = args.last_mut() { + self.take_before_sep(&mut last.meta, ")"); + } self.expect_sym(")")?; - Ok(args) + Ok(TfPorts { args, dangling: Vec::new() }) } - fn parse_tf_body(&mut self, end_kw: &str) -> PResult<(Vec, Vec, Option)> { + fn parse_tf_body(&mut self, end_kw: &str) -> PResult { let mut stmts = Vec::new(); while !self.at_body_end(end_kw) { stmts.push(self.stmt_or_recover()?); } let dangling = self.take_dangling(); self.expect_closer(end_kw)?; - Ok((stmts, dangling, self.parse_label()?)) + let (comments, name) = self.parse_label_with()?; + Ok((stmts, dangling, comments, name)) } // ------------------------------------------------------------------ @@ -5783,15 +6163,23 @@ impl<'a> Parser<'a> { } let mark = ItemMark { pos: self.pos, conds: self.open_conds, diags: self.diagnostics.len() }; + // Nothing may leak from the statement before this one into this + // statement's own `;` slot. + self.semi_comments.clear(); let kind = match self.parse_stmt_kind() { Ok(kind) => kind, Err(e) => self.split_conditional_stmt(&mark, e)?, }; + let before_semi = std::mem::take(&mut self.semi_comments); + debug_assert!( + before_semi.is_empty() || kind.takes_semi(), + "only a kind that wrote a `;` may own the gap in front of it" + ); let span = self.span_from(start); if meta.trailing.is_none() { meta.trailing = self.take_trailing(); } - Ok(Stmt { meta, kind, span }) + Ok(Stmt { meta, kind, before_semi, span }) } /// The statement half of [`Parser::split_conditional_item`]: a statement a @@ -5868,20 +6256,24 @@ impl<'a> Parser<'a> { } if t.is_sym("#") { self.bump(); + let after_hash = self.take_gap(); let delay = self.parse_delay_value()?; - let stmt = if self.eat_sym(";") { None } else { Some(Box::new(self.parse_stmt()?)) }; - return Ok(StmtKind::Timing { control: TimingControl::Delay(delay), stmt }); + let stmt = if self.eat_stmt_semi() { None } else { Some(Box::new(self.parse_stmt()?)) }; + return Ok(StmtKind::Timing { + control: TimingControl::Delay { after_hash, expr: delay }, + stmt, + }); } if t.is_sym("@") { self.bump(); let sens = self.parse_sens_list()?; - let stmt = if self.eat_sym(";") { None } else { Some(Box::new(self.parse_stmt()?)) }; + let stmt = if self.eat_stmt_semi() { None } else { Some(Box::new(self.parse_stmt()?)) }; return Ok(StmtKind::Timing { control: TimingControl::Event(sens), stmt }); } if t.is_sym("->") { self.bump(); let e = self.parse_unary()?; - self.expect_sym(";")?; + self.expect_stmt_semi()?; return Ok(StmtKind::EventTrigger(e)); } if t.kind == TokenKind::Keyword { @@ -5896,26 +6288,31 @@ impl<'a> Parser<'a> { match kw.as_str() { "begin" => { self.bump(); - let (label, label_span) = split_label(self.parse_label()?); + let (label_comments, label_name) = self.parse_label_with()?; + let (label, label_span) = split_label(label_name); let mut stmts = Vec::new(); while !self.at_body_end("end") { stmts.push(self.stmt_or_recover()?); } let dangling = self.take_dangling(); self.expect_closer("end")?; - let (end_label, end_label_span) = split_label(self.parse_label()?); + let (end_label_comments, end_name) = self.parse_label_with()?; + let (end_label, end_label_span) = split_label(end_name); Ok(StmtKind::Block { + label_comments, label, label_span, stmts, dangling, + end_label_comments, end_label, end_label_span, }) } "fork" => { self.bump(); - let (label, label_span) = split_label(self.parse_label()?); + let (label_comments, label_name) = self.parse_label_with()?; + let (label, label_span) = split_label(label_name); let mut stmts = Vec::new(); while !self.at_eof() && !self.at_join_kw() @@ -5930,13 +6327,16 @@ impl<'a> Parser<'a> { } else { self.bump().text }; - let (end_label, end_label_span) = split_label(self.parse_label()?); + let (end_label_comments, end_name) = self.parse_label_with()?; + let (end_label, end_label_span) = split_label(end_name); Ok(StmtKind::ForkJoin { + label_comments, label, label_span, join_kw, stmts, dangling, + end_label_comments, end_label, end_label_span, }) @@ -5953,7 +6353,9 @@ impl<'a> Parser<'a> { "case" | "casex" | "casez" => self.parse_case_stmt(None), "for" => { self.bump(); + let mut comments = ForComments { after_kw: self.take_gap(), ..Default::default() }; self.expect_sym("(")?; + comments.after_open = self.take_gap(); let mut init = Vec::new(); if !self.cur().is_sym(";") { loop { @@ -5974,21 +6376,35 @@ impl<'a> Parser<'a> { None } }; + let before_name = self.take_gap(); let lhs = self.parse_unary()?; + let mut op_comments = + BinaryComments { before: self.gap_before("="), after: Vec::new() }; self.expect_sym("=")?; + op_comments.after = self.take_gap(); let rhs = self.parse_expr()?; init.push(ForInit { ty, - assign: SimpleAssign { lhs, op: "=".to_string(), rhs }, + before_name, + assign: SimpleAssign { + lhs, + op: "=".to_string(), + op_comments: Box::new(op_comments), + rhs, + }, }); if !self.eat_sym(",") { break; } } } + comments.before_first_semi = self.gap_before(";"); self.expect_sym(";")?; + comments.after_first_semi = self.take_gap(); let cond = if self.cur().is_sym(";") { None } else { Some(self.parse_expr()?) }; + comments.before_second_semi = self.gap_before(";"); self.expect_sym(";")?; + comments.after_second_semi = self.take_gap(); let mut step = Vec::new(); if !self.cur().is_sym(")") { step.push(self.parse_for_step()?); @@ -5996,9 +6412,10 @@ impl<'a> Parser<'a> { step.push(self.parse_for_step()?); } } + comments.before_close = self.gap_before(")"); self.expect_sym(")")?; let body = Box::new(self.parse_stmt()?); - Ok(StmtKind::For { init, cond, step, body }) + Ok(StmtKind::For { init, cond, step, comments: Box::new(comments), body }) } "while" => { self.bump(); @@ -6011,11 +6428,15 @@ impl<'a> Parser<'a> { self.bump(); let body = Box::new(self.parse_stmt()?); self.expect_kw("while")?; + let mut comments = + HeaderComments { after_kw: self.take_before_open("("), ..Default::default() }; self.expect_sym("(")?; + comments.after_open = self.take_gap(); let cond = self.parse_expr()?; + comments.before_close = self.gap_before(")"); self.expect_sym(")")?; - self.expect_sym(";")?; - Ok(StmtKind::DoWhile { body, cond }) + self.expect_stmt_semi()?; + Ok(StmtKind::DoWhile { body, cond, comments: Box::new(comments) }) } "repeat" => { self.bump(); @@ -6030,11 +6451,22 @@ impl<'a> Parser<'a> { } "foreach" => { self.bump(); + let mut comments = + HeaderComments { after_kw: self.take_gap(), ..Default::default() }; self.expect_sym("(")?; - let (target, vars) = self.parse_foreach_target()?; + comments.after_open = self.take_gap(); + let ForeachTarget { expr: target, vars, comments: var_comments } = + self.parse_foreach_target()?; + comments.before_close = self.gap_before(")"); self.expect_sym(")")?; let body = Box::new(self.parse_stmt()?); - Ok(StmtKind::Foreach { target, vars, body }) + Ok(StmtKind::Foreach { + target, + vars, + var_comments, + comments: Box::new(comments), + body, + }) } "randcase" => { self.bump(); @@ -6043,18 +6475,19 @@ impl<'a> Parser<'a> { } "return" => { self.bump(); - let e = if self.cur().is_sym(";") { None } else { Some(self.parse_expr()?) }; - self.expect_sym(";")?; - Ok(StmtKind::Return(e)) + let after_kw = self.take_gap(); + let expr = if self.cur().is_sym(";") { None } else { Some(self.parse_expr()?) }; + self.expect_stmt_semi()?; + Ok(StmtKind::Return { after_kw, expr }) } "break" => { self.bump(); - self.expect_sym(";")?; + self.expect_stmt_semi()?; Ok(StmtKind::Break) } "continue" => { self.bump(); - self.expect_sym(";")?; + self.expect_stmt_semi()?; Ok(StmtKind::Continue) } "disable" => { @@ -6063,7 +6496,7 @@ impl<'a> Parser<'a> { // started; `fork` is a keyword, not a block name. if self.cur().is_kw("fork") { self.bump(); - self.expect_sym(";")?; + self.expect_stmt_semi()?; return Ok(StmtKind::Disable("fork".to_string())); } let mut name = self.expect_ident()?; @@ -6072,7 +6505,7 @@ impl<'a> Parser<'a> { name.push('.'); name.push_str(&self.expect_ident()?); } - self.expect_sym(";")?; + self.expect_stmt_semi()?; Ok(StmtKind::Disable(name)) } "wait" => { @@ -6081,14 +6514,14 @@ impl<'a> Parser<'a> { // (IEEE 1800 §9.6.1); `fork` is a keyword, not a condition. if self.cur().is_kw("fork") { self.bump(); - self.expect_sym(";")?; + self.expect_stmt_semi()?; return Ok(StmtKind::WaitFork); } self.expect_sym("(")?; let cond = self.parse_expr()?; self.expect_sym(")")?; let stmt = - if self.eat_sym(";") { None } else { Some(Box::new(self.parse_stmt()?)) }; + if self.eat_stmt_semi() { None } else { Some(Box::new(self.parse_stmt()?)) }; Ok(StmtKind::Wait { cond, stmt }) } "assert" | "assume" | "cover" => { @@ -6096,7 +6529,7 @@ impl<'a> Parser<'a> { self.expect_sym("(")?; let cond = self.parse_expr()?; self.expect_sym(")")?; - let (then, els) = if self.eat_sym(";") { + let (then, els) = if self.eat_stmt_semi() { (None, None) } else if self.eat_kw("else") { (None, Some(Box::new(self.parse_stmt()?))) @@ -6113,18 +6546,18 @@ impl<'a> Parser<'a> { let lhs = self.parse_unary()?; self.expect_sym("=")?; let rhs = self.parse_expr()?; - self.expect_sym(";")?; + self.expect_stmt_semi()?; Ok(StmtKind::ForceRelease { kw: "force".into(), lhs, rhs: Some(rhs) }) } "release" | "deassign" => { let kw = self.bump().text; let lhs = self.parse_unary()?; - self.expect_sym(";")?; + self.expect_stmt_semi()?; Ok(StmtKind::ForceRelease { kw, lhs, rhs: None }) } "parameter" | "localparam" => { let d = self.parse_param_decl()?; - self.expect_sym(";")?; + self.expect_stmt_semi()?; Ok(StmtKind::ParamDecl(d)) } // A package import standing among a block's declarations @@ -6169,6 +6602,7 @@ impl<'a> Parser<'a> { fn parse_if_stmt(&mut self, qualifier: Option) -> PResult { self.expect_kw("if")?; + let after_kw = self.take_before_open("("); self.expect_sym("(")?; let cond = self.parse_expr()?; self.expect_sym(")")?; @@ -6184,11 +6618,12 @@ impl<'a> Parser<'a> { } else { None }; - Ok(StmtKind::If { qualifier, cond, then, else_comments, els }) + Ok(StmtKind::If { qualifier, after_kw, cond, then, else_comments, els }) } fn parse_case_stmt(&mut self, qualifier: Option) -> PResult { let kw = self.bump().text; + let after_kw = self.take_before_open("("); self.expect_sym("(")?; let expr = self.parse_expr()?; self.expect_sym(")")?; @@ -6196,7 +6631,7 @@ impl<'a> Parser<'a> { // labels may be `[lo:hi]` ranges (handled by `parse_expr_item`). let inside = self.eat_kw("inside"); let (items, dangling) = self.parse_case_body()?; - Ok(StmtKind::Case { qualifier, kw, expr, inside, items, dangling }) + Ok(StmtKind::Case { qualifier, kw, after_kw, expr, inside, items, dangling }) } /// The `label : statement` items of a `case`/`randcase` body, the @@ -6208,7 +6643,11 @@ impl<'a> Parser<'a> { while !self.at_body_end("endcase") { let start = self.here(); let mut meta = self.take_meta(); + let mut before_colon = Vec::new(); let labels = if self.eat_kw("default") { + // The `:` after `default` is optional (IEEE 1800 §12.5), so + // the gap only belongs to the item when one was written. + before_colon = self.gap_before(":"); let _ = self.eat_sym(":"); Vec::new() } else { @@ -6222,7 +6661,7 @@ impl<'a> Parser<'a> { if meta.trailing.is_none() { meta.trailing = self.take_trailing(); } - items.push(CaseItem { meta, labels, stmt, span }); + items.push(CaseItem { meta, labels, before_colon, stmt, span }); } let dangling = self.take_dangling(); self.expect_closer("endcase")?; @@ -6239,54 +6678,54 @@ impl<'a> Parser<'a> { /// (`csr_utils_pkg.sv:290`) — so it is parsed as a postfix chain. The /// bracket group the `)` follows is the one that declares the loop /// variables; every earlier one is an ordinary select. - fn parse_foreach_target(&mut self) -> PResult<(Expr, Vec)> { + fn parse_foreach_target(&mut self) -> PResult { let outer_links = self.links; let out = self.parse_foreach_target_inner(); self.links = outer_links; out } - fn parse_foreach_target_inner(&mut self) -> PResult<(Expr, Vec)> { + fn parse_foreach_target_inner(&mut self) -> PResult { let start = self.here(); let name = self.expect_ident()?; let mut expr = self.expr_at(start, ExprKind::Ident(name)); loop { self.link()?; let t = self.cur(); - if t.is_sym(".") { - self.bump(); - let name = self.expect_ident()?; - expr = self.expr_at(start, ExprKind::Member { base: Box::new(expr), name }); - } else if t.is_sym("::") { - self.bump(); - let name = self.expect_ident()?; - expr = self.expr_at(start, ExprKind::Scope { base: Box::new(expr), name }); - } else if t.is_sym("[") { + if t.is_sym("[") { + // The last bracket group is the loop-variable list, not a + // segment of the target: it is the one whose `]` is followed + // by the header's `)`. let after = self.scan_matching(self.pos, "[", "]"); if self.tokens.get(after).is_some_and(|t| t.is_sym(")")) { break; } - self.bump(); - let index = self.parse_expr()?; - self.expect_sym("]")?; - expr = self.expr_at( - start, - ExprKind::Index { base: Box::new(expr), index: Box::new(index) }, - ); - } else { + } else if !t.is_sym(".") && !t.is_sym("::") { break; } + expr = self.parse_postfix_segment(start, expr)?; } + let mut comments = SegmentComments { before_open: self.take_gap(), ..Default::default() }; self.expect_sym("[")?; + comments.after_open = self.take_gap(); let mut vars = Vec::new(); if !self.cur().is_sym("]") { vars.push(self.parse_foreach_var()?); - while self.eat_sym(",") { + while self.cur().is_sym(",") { + if let Some(last) = vars.last_mut() { + last.after = self.take_gap(); + } + self.bump(); vars.push(self.parse_foreach_var()?); } } + if let Some(last) = vars.last_mut() { + last.after = self.gap_before("]"); + } else { + comments.before_close = self.gap_before("]"); + } self.expect_sym("]")?; - Ok((expr, vars)) + Ok(ForeachTarget { expr, vars, comments: Box::new(comments) }) } /// One loop-variable slot of a `foreach`'s bracket list. A dimension may @@ -6295,22 +6734,33 @@ impl<'a> Parser<'a> { /// (`ip_templates/flash_ctrl/dv/env/flash_ctrl_env.sv:43`) iterates only /// the second dimension. A skipped slot is an empty name at the point it /// was written: it declares nothing, and it prints as nothing. - fn parse_foreach_var(&mut self) -> PResult { + fn parse_foreach_var(&mut self) -> PResult { + let before = self.take_gap(); if self.cur().is_sym(",") || self.cur().is_sym("]") { let here = self.here(); - return Ok(Name { text: String::new(), span: self.span_from(here) }); + let name = Name { text: String::new(), span: self.span_from(here) }; + return Ok(ForeachVar { name, before, after: Vec::new() }); } - self.expect_name() + let name = self.expect_name()?; + Ok(ForeachVar { name, before, after: Vec::new() }) } fn parse_for_step(&mut self) -> PResult { + let mark = self.pending_trailing.len(); let lhs = self.parse_unary()?; let op = self.cur().text.clone(); if self.cur().kind == TokenKind::Symbol && (ASSIGN_OPS.contains(&op.as_str()) || op == "<=") { + let before = self.take_around(mark); self.bump(); + let after = self.take_gap(); let rhs = self.parse_expr()?; - Ok(ForStep::Assign(SimpleAssign { lhs, op, rhs })) + Ok(ForStep::Assign(SimpleAssign { + lhs, + op, + op_comments: Box::new(BinaryComments { before, after }), + rhs, + })) } else { Ok(ForStep::Expr(lhs)) } @@ -6340,7 +6790,10 @@ impl<'a> Parser<'a> { let rhs_comments = self.take_around(mark); let timing = if self.cur().is_sym("#") { self.bump(); - Some(TimingControl::Delay(self.parse_delay_value()?)) + Some(TimingControl::Delay { + after_hash: self.take_gap(), + expr: self.parse_delay_value()?, + }) } else if self.cur().is_sym("@") { self.bump(); Some(TimingControl::Event(self.parse_sens_list()?)) @@ -6348,10 +6801,10 @@ impl<'a> Parser<'a> { None }; let rhs = self.parse_expr()?; - self.expect_sym(";")?; + self.expect_stmt_semi()?; Ok(StmtKind::Assign { lhs, op, op_comments, rhs_comments, timing, rhs }) } else { - self.expect_sym(";")?; + self.expect_stmt_semi()?; Ok(StmtKind::ExprStmt(lhs)) } } @@ -6370,32 +6823,24 @@ impl<'a> Parser<'a> { let name = self.expect_ident()?; let mut expr = self.expr_at(start, ExprKind::Ident(name)); loop { - if self.cur().is_sym(".") && self.nth(1).kind == TokenKind::Ident { - self.link()?; - self.bump(); - let member = self.expect_ident()?; - expr = self.expr_at(start, ExprKind::Member { base: Box::new(expr), name: member }); - } else if self.cur().is_sym("[") { - self.link()?; - self.bump(); - let index = self.parse_expr()?; - self.expect_sym("]")?; - expr = self.expr_at( - start, - ExprKind::Index { base: Box::new(expr), index: Box::new(index) }, - ); - } else { + let dotted = self.cur().is_sym(".") && self.nth(1).kind == TokenKind::Ident; + if !dotted && !self.cur().is_sym("[") { return Ok(expr); } + self.link()?; + expr = self.parse_postfix_segment(start, expr)?; } } fn parse_sens_list(&mut self) -> PResult { + // The `@` is consumed by the caller, so the gap that ends here is the + // one written after it. + let after_at = self.take_gap(); if self.cur().is_sym("*") { - // `@*` without parens. - let before = self.take_leading_here(); + // `@*` without parens — the gap after the `@` is the `*`'s own + // `before` slot, which the formatter prints in the same place. self.bump(); - return Ok(SensList::Star { before, after: Vec::new() }); + return Ok(SensList::Star { before: after_at, after: Vec::new() }); } if self.cur().kind == TokenKind::Ident { // `@ident` / `@a.b` without parens; recorded as `Bare` so the @@ -6406,12 +6851,13 @@ impl<'a> Parser<'a> { let outer_links = self.links; let out = self.parse_bare_event_name(); self.links = outer_links; - return out.map(SensList::Bare); + return out.map(|expr| SensList::Bare { expr, after_at }); } if self.cur().is_sym("(") && self.nth(1).is_sym("*") { // `@( /* c */ * /* d */ )`: the comments belong to the star, not // to whatever node comes next. - let mut before = self.take_trailing_here(); + let mut before = after_at; + before.append(&mut self.take_trailing_here()); self.bump(); // ( before.append(&mut self.take_leading_here()); let mut after = self.take_trailing_here(); @@ -6425,10 +6871,15 @@ impl<'a> Parser<'a> { let mut sep = None; loop { let mut meta = self.take_meta(); + let mut after_edge = Vec::new(); let edge = { let t = self.cur(); if t.is_kw("posedge") || t.is_kw("negedge") || t.is_kw("edge") { - Some(self.bump().text) + let kw = self.bump().text; + // `@(posedge /*c*/ clk)` — the gap after the keyword is + // the item's, not the next node's. + after_edge = self.take_gap(); + Some(kw) } else { None } @@ -6443,7 +6894,7 @@ impl<'a> Parser<'a> { if self.cur().is_sym(",") || self.cur().is_kw("or") || self.cur().is_sym(")") { self.take_before(&mut meta); } - items.push(SensItem { meta, sep, edge, expr, iff }); + items.push(SensItem { meta, sep, edge, after_edge, expr, iff }); // Both separators are legal in the same list; each is kept as // written so the formatter never rewrites one as the other. sep = if self.eat_sym(",") { @@ -6455,7 +6906,7 @@ impl<'a> Parser<'a> { }; } self.expect_sym(")")?; - Ok(SensList::List(items)) + Ok(SensList::List { items, after_at }) } // ------------------------------------------------------------------ @@ -6590,7 +7041,12 @@ impl<'a> Parser<'a> { break; } if self.cur().is_kw("inside") { + // The word is an operator like any other, and keeps the + // comments written on either side of it the same way. + let before = self.take_around(mark); self.bump(); + let after = self.take_around(mark); + let comments = Box::new(BinaryComments { before, after }); // `x inside `MACRO` — the macro expands to the `{...}` set, // so it stands in for one (corpus // `opentitan/hw/ip/uart/dv/env/uart_scoreboard.sv:155`). @@ -6598,7 +7054,10 @@ impl<'a> Parser<'a> { let set = self.bump().text; self.link()?; let start = lhs.span.start; - lhs = self.expr_at(start, ExprKind::InsideMacro { lhs: Box::new(lhs), set }); + lhs = self.expr_at( + start, + ExprKind::InsideMacro { lhs: Box::new(lhs), set, comments }, + ); continue; } self.expect_sym("{")?; @@ -6607,15 +7066,7 @@ impl<'a> Parser<'a> { let item_start = self.here(); let mut meta = self.take_meta(); let expr = if self.cur().is_sym("[") { - self.bump(); - let lo = self.parse_expr()?; - self.expect_sym(":")?; - let hi = self.parse_expr()?; - self.expect_sym("]")?; - self.expr_at( - item_start, - ExprKind::ValueRange { lo: Box::new(lo), hi: Box::new(hi) }, - ) + self.parse_value_range()? } else { self.parse_expr()? }; @@ -6636,7 +7087,8 @@ impl<'a> Parser<'a> { self.expect_sym("}")?; self.link()?; let start = lhs.span.start; - lhs = self.expr_at(start, ExprKind::Inside { lhs: Box::new(lhs), ranges }); + lhs = + self.expr_at(start, ExprKind::Inside { lhs: Box::new(lhs), ranges, comments }); continue; } // Comments between the operand and the operator belong to this @@ -6681,8 +7133,12 @@ impl<'a> Parser<'a> { { let start = self.here(); let op = self.bump().text; + let comments = self.take_gap(); let expr = self.parse_unary()?; - return Ok(self.expr_at(start, ExprKind::Unary { op, expr: Box::new(expr) })); + return Ok(self.expr_at( + start, + ExprKind::Unary { op, comments: Box::new(comments), expr: Box::new(expr) }, + )); } self.parse_postfix() } @@ -6747,6 +7203,62 @@ impl<'a> Parser<'a> { out } + /// One `.name`, `::name`, `[i]` or `[m:l]` segment wrapping `base`, with + /// the comments written in each of its fixed slots. + /// + /// The cursor is on the segment's opening token and `start` is where the + /// whole expression began — each segment wraps what came before it, so + /// every node in the chain starts at the same offset. This is the single + /// owner of the three-branch loop `parse_postfix_inner`, + /// [`Parser::parse_foreach_target_inner`] and + /// [`Parser::parse_bare_event_name`] each used to write out by hand, and + /// each used to lose the same comments in. + fn parse_postfix_segment(&mut self, start: u32, base: Expr) -> PResult { + let mut comments = SegmentComments { before_open: self.take_gap(), ..Default::default() }; + let base = Box::new(base); + if self.cur().is_sym(".") || self.cur().is_sym("::") { + let scoped = self.cur().is_sym("::"); + self.bump(); + comments.after_open = self.take_gap(); + let name = self.expect_ident()?; + let comments = Box::new(comments); + let kind = if scoped { + ExprKind::Scope { base, name, comments } + } else { + ExprKind::Member { base, name, comments } + }; + return Ok(self.expr_at(start, kind)); + } + self.expect_sym("[")?; + comments.after_open = self.take_gap(); + let a = self.parse_expr()?; + let t = self.cur(); + if t.is_sym(":") || t.is_sym("+:") || t.is_sym("-:") { + comments.before_op = self.take_gap(); + let op = self.bump().text; + comments.after_op = self.take_gap(); + let b = self.parse_expr()?; + comments.before_close = self.gap_before("]"); + self.expect_sym("]")?; + return Ok(self.expr_at( + start, + ExprKind::Range { + base, + op, + msb: Box::new(a), + lsb: Box::new(b), + comments: Box::new(comments), + }, + )); + } + comments.before_close = self.gap_before("]"); + self.expect_sym("]")?; + Ok(self.expr_at( + start, + ExprKind::Index { base, index: Box::new(a), comments: Box::new(comments) }, + )) + } + fn parse_postfix_inner(&mut self) -> PResult { let mut expr = self.parse_primary()?; while self.at_postfix_segment(&expr) { @@ -6759,38 +7271,8 @@ impl<'a> Parser<'a> { let params = self.parse_type_params()?; expr = self.expr_at(start, ExprKind::Parameterized { base: Box::new(expr), params }); - } else if t.is_sym(".") { - self.bump(); - let name = self.expect_ident()?; - expr = self.expr_at(start, ExprKind::Member { base: Box::new(expr), name }); - } else if t.is_sym("::") { - self.bump(); - let name = self.expect_ident()?; - expr = self.expr_at(start, ExprKind::Scope { base: Box::new(expr), name }); - } else if t.is_sym("[") { - self.bump(); - let a = self.parse_expr()?; - let t2 = self.cur(); - if t2.is_sym(":") || t2.is_sym("+:") || t2.is_sym("-:") { - let op = self.bump().text; - let b = self.parse_expr()?; - self.expect_sym("]")?; - expr = self.expr_at( - start, - ExprKind::Range { - base: Box::new(expr), - op, - msb: Box::new(a), - lsb: Box::new(b), - }, - ); - } else { - self.expect_sym("]")?; - expr = self.expr_at( - start, - ExprKind::Index { base: Box::new(expr), index: Box::new(a) }, - ); - } + } else if t.is_sym(".") || t.is_sym("::") || t.is_sym("[") { + expr = self.parse_postfix_segment(start, expr)?; } else if t.is_sym("(") { // Comments written around the brackets have no element to // attach to: before the `(`, and inside an empty `()`. @@ -6871,22 +7353,34 @@ impl<'a> Parser<'a> { if !self.is_cast_base(&expr) { return self.error("unsupported cast base expression"); } - if t.is_sym("'{") { + let is_pattern = t.is_sym("'{"); + let mut comments = + CastComments { before_tick: self.take_gap(), ..Default::default() }; + if is_pattern { let pattern_start = self.here(); let inner = self.parse_assign_pattern(pattern_start)?; expr = self.expr_at( start, - ExprKind::Cast { ty: Box::new(expr), expr: Box::new(inner), pattern: true }, + ExprKind::Cast { + ty: Box::new(expr), + comments: Box::new(comments), + expr: Box::new(inner), + pattern: true, + }, ); } else { self.bump(); // ' + comments.after_tick = self.take_gap(); self.bump(); // ( + comments.after_open = self.take_gap(); let inner = self.parse_expr()?; + comments.before_close = self.gap_before(")"); self.expect_sym(")")?; expr = self.expr_at( start, ExprKind::Cast { ty: Box::new(expr), + comments: Box::new(comments), expr: Box::new(inner), pattern: false, }, @@ -6894,8 +7388,12 @@ impl<'a> Parser<'a> { } } else { // `++` / `--`, the only remaining segment kind. + let comments = self.take_gap(); let op = self.bump().text; - expr = self.expr_at(start, ExprKind::Postfix { expr: Box::new(expr), op }); + expr = self.expr_at( + start, + ExprKind::Postfix { expr: Box::new(expr), op, comments: Box::new(comments) }, + ); } } Ok(expr) @@ -7105,13 +7603,23 @@ impl<'a> Parser<'a> { let ty_start = self.here(); let ty_text = self.bump().text; let ty = self.expr_at(ty_start, ExprKind::Ident(ty_text)); + let mut comments = + CastComments { before_tick: self.take_gap(), ..Default::default() }; self.bump(); // ' + comments.after_tick = self.take_gap(); self.bump(); // ( + comments.after_open = self.take_gap(); let inner = self.parse_expr()?; + comments.before_close = self.gap_before(")"); self.expect_sym(")")?; return Ok(self.expr_at( start, - ExprKind::Cast { ty: Box::new(ty), expr: Box::new(inner), pattern: false }, + ExprKind::Cast { + ty: Box::new(ty), + comments: Box::new(comments), + expr: Box::new(inner), + pattern: false, + }, )); } // Type keyword used as an argument (e.g. `$bits(int)`). @@ -7214,6 +7722,11 @@ mod tests { } } + /// The keywords of a qualifier run, without the comments each one carries. + fn words(run: &[Qualifier]) -> Vec<&str> { + run.iter().map(|q| q.text.as_str()).collect() + } + /// The texts of a comment slot, for the tests that pin where a comment /// with no node of its own was attached. fn texts(comments: &[Comment]) -> Vec<&str> { @@ -7893,8 +8406,9 @@ mod tests { parse_ok("module m;\nalways @(posedge clk, negedge rst_n or a, b) q <= d;\nendmodule"); let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; let ItemKind::Always { stmt, .. } = &m.items[0].kind else { panic!("expected an always") }; - let StmtKind::Timing { control: TimingControl::Event(SensList::List(items)), .. } = - &stmt.kind + let StmtKind::Timing { + control: TimingControl::Event(SensList::List { items, .. }), .. + } = &stmt.kind else { panic!("expected an event control") }; @@ -8526,7 +9040,7 @@ mod tests { implements i, j;\nendclass : c\n", ); let c = class_of(&f); - assert_eq!(c.prefix, ["virtual"]); + assert_eq!(words(&c.prefix), ["virtual"]); assert_eq!(c.name, "c"); assert_eq!(c.param_ports.as_ref().expect("a parameter port list").len(), 1); let ext = c.extends.as_ref().expect("an extends clause"); @@ -8573,16 +9087,16 @@ mod tests { ); let items = &class_of(&f).items; let ItemKind::DataDecl(d) = &items[0].kind else { panic!("expected a declaration") }; - assert_eq!(d.qualifiers, ["local", "rand"]); + assert_eq!(words(&d.qualifiers), ["local", "rand"]); let ItemKind::Function(g) = &items[1].kind else { panic!("expected a function") }; - assert_eq!(g.prefix, ["pure", "virtual"]); + assert_eq!(words(&g.prefix), ["pure", "virtual"]); assert!(g.is_prototype && g.stmts.is_empty()); let ItemKind::Task(t) = &items[2].kind else { panic!("expected a task") }; - assert_eq!(t.prefix, ["extern"]); + assert_eq!(words(&t.prefix), ["extern"]); assert!(t.is_prototype); let ItemKind::Task(u) = &items[3].kind else { panic!("expected a task") }; - assert_eq!(u.prefix, ["protected", "virtual"]); - assert_eq!(u.qualifiers, ["automatic"]); + assert_eq!(words(&u.prefix), ["protected", "virtual"]); + assert_eq!(words(&u.qualifiers), ["automatic"]); assert!(!u.is_prototype); } @@ -8690,7 +9204,7 @@ mod tests { fn an_out_of_body_method_keeps_its_class_scope_apart_from_its_name() { let f = parse_ok("function void my_class::configure(int x);\nendfunction\n"); let ItemKind::Function(g) = &f.items[0].kind else { panic!("expected a function") }; - assert_eq!(g.scope.as_deref(), Some("my_class")); + assert_eq!(scope_path(&g.scope), "my_class"); assert_eq!(g.name, "configure"); } @@ -8756,7 +9270,7 @@ mod tests { let c = constraint_of(&f); assert_eq!(c.name.text, "c_len"); assert_eq!(&src[c.name.span.as_range()], "c_len", "the name span slices the name"); - assert!(c.scope.is_none()); + assert!(c.scope.is_empty()); assert!(!c.semi); let items = &c.body.as_ref().expect("a body").items; assert_eq!(items.len(), 2); @@ -8767,7 +9281,7 @@ mod tests { fn a_constraint_prototype_has_no_body() { let f = parse_ok("class k;\n extern constraint c;\nendclass\n"); let c = constraint_of(&f); - assert_eq!(c.qualifiers, vec!["extern".to_string()]); + assert_eq!(words(&c.qualifiers), ["extern"]); assert_eq!(c.name.text, "c"); assert!(c.body.is_none()); } @@ -8775,7 +9289,7 @@ mod tests { #[test] fn a_pure_static_constraint_keeps_every_qualifier() { let f = parse_ok("class k;\n pure static constraint c;\nendclass\n"); - assert_eq!(constraint_of(&f).qualifiers, vec!["pure".to_string(), "static".to_string()]); + assert_eq!(words(&constraint_of(&f).qualifiers), ["pure", "static"]); } #[test] @@ -8893,8 +9407,8 @@ mod tests { panic!("expected a foreach") }; assert_eq!(vars.len(), 2); - assert!(vars[0].text.is_empty(), "a skipped dimension is an empty name"); - assert_eq!(vars[1].text, "j"); + assert!(vars[0].name.text.is_empty(), "a skipped dimension is an empty name"); + assert_eq!(vars[1].name.text, "j"); assert!(set.braced); } @@ -9157,7 +9671,7 @@ mod tests { let src = "constraint my_item::delay_c {\n soft delay dist {0 :/ 5};\n}\n"; let f = parse_ok(src); let c = file_constraint(&f); - assert_eq!(c.scope.as_deref(), Some("my_item")); + assert_eq!(scope_path(&c.scope), "my_item"); assert_eq!(c.name.text, "delay_c"); assert_eq!(&src[c.name.span.as_range()], "delay_c"); } @@ -9167,7 +9681,7 @@ mod tests { // `pkg::cls::name` — the same chain `parse_method_name` accepts for an // out-of-body method. let f = parse_ok("constraint pkg::cls::deep_c { x < 4; }\n"); - assert_eq!(file_constraint(&f).scope.as_deref(), Some("pkg::cls")); + assert_eq!(scope_path(&file_constraint(&f).scope), "pkg::cls"); } #[test] @@ -9386,7 +9900,7 @@ mod tests { }; // call( scope( parameterized( ident ) ) ) let ExprKind::Call { callee, .. } = &rhs.kind else { panic!("expected a call") }; - let ExprKind::Scope { base, name } = &callee.kind else { panic!("expected a scope") }; + let ExprKind::Scope { base, name, .. } = &callee.kind else { panic!("expected a scope") }; assert_eq!(name, "get"); let ExprKind::Parameterized { base, params } = &base.kind else { panic!("expected a parameterized reference") @@ -9498,7 +10012,7 @@ mod tests { 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") }; + let ExprKind::Member { base, name, .. } = &lhs.kind else { panic!("expected a member") }; assert_eq!(name, "label"); assert!(matches!(&base.kind, ExprKind::Index { .. })); } @@ -9556,14 +10070,16 @@ mod tests { 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 + let StmtKind::Timing { + control: TimingControl::Event(SensList::Bare { expr: 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 + let StmtKind::Timing { + control: TimingControl::Event(SensList::Bare { expr: e, .. }), .. + } = &task.stmts[1].kind else { panic!("expected a bare event control") }; @@ -9578,7 +10094,7 @@ mod tests { 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(_)), .. } + StmtKind::Timing { control: TimingControl::Event(SensList::List { .. }), .. } )); } @@ -9625,7 +10141,7 @@ mod tests { // as an `interface ... endinterface`. let f = parse_ok("interface class ic;\n pure virtual function void f();\nendclass\n"); let ItemKind::Class(c) = &f.items[0].kind else { panic!("expected a class") }; - assert_eq!(c.prefix, ["interface"]); + assert_eq!(words(&c.prefix), ["interface"]); assert!(c.is_interface_class()); assert_eq!(c.name, "ic"); assert_eq!(c.items.len(), 1, "the pure virtual prototype is an ordinary class item"); @@ -9999,8 +10515,9 @@ mod tests { let ItemKind::Always { stmt, .. } = &module_of(&f).items[0].kind else { panic!("expected an always block") }; - let StmtKind::Timing { control: TimingControl::Event(SensList::List(items)), .. } = - &stmt.kind + let StmtKind::Timing { + control: TimingControl::Event(SensList::List { items, .. }), .. + } = &stmt.kind else { panic!("expected an event control") }; @@ -10022,11 +10539,15 @@ mod tests { panic!("expected an initial block") }; let StmtKind::Forever { body } = &stmt.kind else { panic!("expected a forever loop") }; - let StmtKind::Timing { control: TimingControl::Event(SensList::Bare(e)), .. } = &body.kind + let StmtKind::Timing { + control: TimingControl::Event(SensList::Bare { expr: e, .. }), .. + } = &body.kind else { panic!("expected a bare event control") }; - let ExprKind::Member { base, name } = &e.kind else { panic!("expected a member access") }; + let ExprKind::Member { base, name, .. } = &e.kind else { + panic!("expected a member access") + }; assert_eq!(name, "sender_cb"); let ExprKind::Member { base, .. } = &base.kind else { panic!("expected a member access") }; assert!(matches!(base.kind, ExprKind::Index { .. }), "the bit-select is part of the path"); @@ -10593,7 +11114,7 @@ mod tests { // Everything before the last bracket group is the array. assert!(matches!(target.kind, ExprKind::Member { .. })); assert_eq!(vars.len(), 1); - assert_eq!(vars[0].text, "j"); + assert_eq!(vars[0].name.text, "j"); } #[test] @@ -10605,7 +11126,7 @@ mod tests { panic!("expected a foreach") }; assert!(matches!(target.kind, ExprKind::Index { .. })); - assert_eq!(vars[0].text, "j"); + assert_eq!(vars[0].name.text, "j"); } #[test] @@ -11422,7 +11943,7 @@ mod tests { let f = parse_ok("module m;\n assign y = expected_alert_t'{1, is_fatal};\nendmodule\n"); let m = module_of(&f); let ItemKind::ContAssign(a) = &m.items[0].kind else { panic!("expected an assign") }; - let ExprKind::Cast { ty, expr, pattern } = &a.assigns[0].rhs.kind else { + let ExprKind::Cast { ty, expr, pattern, .. } = &a.assigns[0].rhs.kind else { panic!("expected a cast") }; assert!(*pattern, "the `'{{...}}` spelling"); @@ -11489,7 +12010,7 @@ mod tests { let f = parse_ok("module m;\n virtual spi_if.tb tb_sif = sif.tb;\nendmodule\n"); let m = module_of(&f); let ItemKind::DataDecl(d) = &m.items[0].kind else { panic!("expected a declaration") }; - assert_eq!(d.qualifiers, ["virtual"]); + assert_eq!(words(&d.qualifiers), ["virtual"]); assert_eq!(d.ty.name, "spi_if.tb"); assert_eq!(d.declarators[0].name, "tb_sif"); @@ -11515,8 +12036,8 @@ mod tests { let f = parse_ok("typedef struct {\n rand bit cpol;\n randc int n;\n bit p;\n} c_t;\n"); let ItemKind::Typedef(t) = &f.items[0].kind else { panic!("expected a typedef") }; let TypedefKind::Struct(s) = &t.kind else { panic!("expected a struct") }; - assert_eq!(s.members[0].qualifiers, ["rand"]); - assert_eq!(s.members[1].qualifiers, ["randc"]); + assert_eq!(words(&s.members[0].qualifiers), ["rand"]); + assert_eq!(words(&s.members[1].qualifiers), ["randc"]); assert!(s.members[2].qualifiers.is_empty()); assert_eq!(s.members[0].declarators[0].name, "cpol"); } @@ -11531,10 +12052,10 @@ mod tests { ); let stmts = block_stmts(&f); let StmtKind::Foreach { vars, .. } = &stmts[0].kind else { panic!("expected a foreach") }; - assert_eq!(vars.iter().map(|v| v.text.as_str()).collect::>(), ["", "bank"]); - assert!(vars[0].span.is_empty(), "a skipped slot occupies no source"); + assert_eq!(vars.iter().map(|v| v.name.text.as_str()).collect::>(), ["", "bank"]); + assert!(vars[0].name.span.is_empty(), "a skipped slot occupies no source"); let StmtKind::Foreach { vars, .. } = &stmts[1].kind else { panic!("expected a foreach") }; - assert_eq!(vars.iter().map(|v| v.text.as_str()).collect::>(), ["i", "", "k"]); + assert_eq!(vars.iter().map(|v| v.name.text.as_str()).collect::>(), ["i", "", "k"]); } #[test] @@ -11651,7 +12172,7 @@ mod tests { let f = parse_ok( "class c;\n covergroup g @(posedge clk);\n coverpoint a;\n endgroup\nendclass\n", ); - let Some(CoverageEvent::Clocking { sens: SensList::List(items), .. }) = + let Some(CoverageEvent::Clocking { sens: SensList::List { items, .. }, .. }) = &covergroup_of(&f).event else { panic!("expected a clocking event") @@ -11661,7 +12182,7 @@ mod tests { // The bare `@ev` spelling keeps its lack of parentheses. let f = parse_ok("class c;\n covergroup g @ev;\n coverpoint a;\n endgroup\nendclass\n"); - let Some(CoverageEvent::Clocking { sens: SensList::Bare(_), .. }) = + let Some(CoverageEvent::Clocking { sens: SensList::Bare { .. }, .. }) = &covergroup_of(&f).event else { panic!("expected a bare event name") diff --git a/crates/vlog_parser/tests/error_recovery.rs b/crates/vlog_parser/tests/error_recovery.rs index 0a94e2a..0afed44 100644 --- a/crates/vlog_parser/tests/error_recovery.rs +++ b/crates/vlog_parser/tests/error_recovery.rs @@ -504,7 +504,7 @@ fn an_error_inside_a_function_or_task_body_keeps_the_rest() { let ItemKind::Function(f) = &m.items[0].kind else { panic!("{}", kind_name(&m.items[0])) }; assert_eq!(f.stmts.len(), 2, "the error statement and the `return` after it"); assert!(matches!(&f.stmts[0].kind, StmtKind::Error(_))); - assert!(matches!(&f.stmts[1].kind, StmtKind::Return(_))); + assert!(matches!(&f.stmts[1].kind, StmtKind::Return { .. })); } // ---------------------------------------------------------------------- diff --git a/crates/vlog_parser/tests/spans.rs b/crates/vlog_parser/tests/spans.rs index d01caf8..1c662ab 100644 --- a/crates/vlog_parser/tests/spans.rs +++ b/crates/vlog_parser/tests/spans.rs @@ -856,7 +856,7 @@ fn check_stmt(src: &str, stmt: &Stmt, parent: TextRange) { check_opt_expr(src, cond.as_ref(), here); check_stmt(src, body, here); } - StmtKind::While { cond, body } | StmtKind::DoWhile { body, cond } => { + StmtKind::While { cond, body } | StmtKind::DoWhile { body, cond, .. } => { check_expr(src, cond, here); check_stmt(src, body, here); } @@ -864,9 +864,11 @@ fn check_stmt(src: &str, stmt: &Stmt, parent: TextRange) { check_expr(src, e, here); check_stmt(src, body, here); } - StmtKind::Foreach { target, vars, body } => { + StmtKind::Foreach { target, vars, body, .. } => { check_expr(src, target, here); - check_names(src, "foreach variable", vars, here); + for v in vars { + check_name(src, "foreach variable", &v.name.text, v.name.span, here); + } check_stmt(src, body, here); } StmtKind::Forever { body } => check_stmt(src, body, here), @@ -894,7 +896,7 @@ fn check_stmt(src: &str, stmt: &Stmt, parent: TextRange) { StmtKind::Typedef(t) => check_typedef(src, t, here), StmtKind::ParamDecl(p) => check_declarators(src, &p.declarators, here), StmtKind::PortDecl(p) => check_declarators(src, &p.declarators, here), - StmtKind::Return(e) => check_opt_expr(src, e.as_ref(), here), + StmtKind::Return { expr, .. } => check_opt_expr(src, expr.as_ref(), here), StmtKind::Directive(raw) | StmtKind::Verbatim(raw) | StmtKind::MacroStmt(MacroCall { raw, .. }) => { @@ -989,7 +991,7 @@ fn check_expr(src: &str, e: &Expr, parent: TextRange) { } } ExprKind::New(source) => check_expr(src, source, here), - ExprKind::Index { base, index } => { + ExprKind::Index { base, index, .. } => { check_expr(src, base, here); check_expr(src, index, here); } @@ -1028,7 +1030,7 @@ fn check_expr(src: &str, e: &Expr, parent: TextRange) { check_expr(src, &i.value, here); } } - ExprKind::ValueRange { lo, hi } => { + ExprKind::ValueRange { lo, hi, .. } => { check_expr(src, lo, here); check_expr(src, hi, here); } @@ -1176,8 +1178,8 @@ fn every_name_span_slices_back_to_its_name() { assert_eq!(slice(src, label_span.expect("a block label")), "b_init"); assert_eq!(slice(src, end_label_span.expect("an end label")), "b_init"); let StmtKind::Foreach { vars, .. } = &stmts[0].kind else { panic!("expected a foreach") }; - assert_eq!(slice(src, vars[0].span), "fi"); - assert_eq!(slice(src, vars[1].span), "fj"); + assert_eq!(slice(src, vars[0].name.span), "fi"); + assert_eq!(slice(src, vars[1].name.span), "fj"); let StmtKind::ForkJoin { label_span, end_label_span, .. } = &stmts[1].kind else { panic!("expected a fork") }; @@ -1434,8 +1436,8 @@ fn check_constraint_set(src: &str, set: &ConstraintSet, parent: TextRange) { ConstraintItemKind::Foreach { array, vars, set, .. } => { check_expr(src, array, here); for v in vars { - if !v.text.is_empty() { - check_name(src, "foreach variable", &v.text, v.span, here); + if !v.name.text.is_empty() { + check_name(src, "foreach variable", &v.name.text, v.name.span, here); } } check_constraint_set(src, set, here); diff --git a/crates/vlog_refactor/src/rename.rs b/crates/vlog_refactor/src/rename.rs index efbc59f..cd6a97a 100644 --- a/crates/vlog_refactor/src/rename.rs +++ b/crates/vlog_refactor/src/rename.rs @@ -531,6 +531,12 @@ impl<'a> Scope<'a> { for i in 0..self.len() { warnings.extend(self.macro_use_warnings(i, &target.name)); } + // Same reason: a reference the workspace could not finish is spelled + // with the old name in a file the rename never edits, and silence + // there is the same kind of wrong as silence about a macro argument. + for i in 0..self.len() { + warnings.extend(self.unresolved_candidate_warnings(i, &target.name)); + } for (i, edits) in edits { warnings.extend(self.unaccounted_warnings(*i, &target.name, edits)); } @@ -684,12 +690,89 @@ impl<'a> Scope<'a> { .collect() } + /// Occurrences the workspace **could not finish**: the semantic layer did + /// record a reference, but neither this file nor the index could say what + /// it names, so the rename has no basis for editing it — and no basis for + /// claiming it is unrelated either. + /// + /// `u_x.sig` where `unknown_mod` is not in the indexed workspace is the + /// shape: the head resolves to the instance, the tail carries + /// `ExternalCandidate { paths: ["unknown_mod::sig"] }`, and the overlay + /// leaves it [`ExternalTarget::StillUnresolved`]. `stray_reason` used to + /// warn about the tail back when it carried no reference at all; the + /// reference it now carries is what silenced it (`docs/topo.md` §2.9-20). + /// + /// Grouped one line per (file, unit), because a name used against an + /// un-indexed module is used against it many times. + fn unresolved_candidate_warnings(&mut self, file: usize, name: &str) -> Vec { + let (Some(text), Some(path)) = (self.text(file), self.path(file)) else { + return Vec::new(); + }; + // The prefilter every whole-workspace scan uses: a file that does not + // spell the name cannot hold an occurrence of it. + if !text.contains(name) { + return Vec::new(); + } + let where_ = display(path).to_string(); + let lines = LineIndex::new(text); + let Some(analysis) = self.analysis(file) else { return Vec::new() }; + // Unit that could not be found → the lines it was named on. + let mut groups: Vec<(String, Vec)> = Vec::new(); + for (i, reference) in analysis.semantics.references().iter().enumerate() { + if reference.name != name { + continue; + } + // The resolution is asked first: an `InheritedCandidate` that + // missed stores nothing in the overlay, so `get` would answer + // `None` for it and for a plain local miss alike. + let Some(unit) = unresolved_unit(&reference.resolution) else { continue }; + if !matches!( + analysis.external.get(ReferenceId(i as u32)), + Some(ExternalTarget::StillUnresolved) + ) { + continue; + } + let line = lines.line_col(reference.name_span.start).0; + match groups.iter_mut().find(|(u, _)| *u == unit) { + Some((_, at)) => at.push(line), + None => groups.push((unit, vec![line])), + } + } + groups + .into_iter() + .map(|(unit, at)| { + let at = at.iter().map(u32::to_string).collect::>().join(", "); + format!( + "`{name}` at {where_} line(s) {at} could not be resolved — nothing in the indexed workspace answers `{unit}::{name}`, so lucisv records no reference there and it was left unchanged." + ) + }) + .collect() + } + /// The workspace index the edits were computed against. pub(crate) fn index(&self) -> &WorkspaceIndex { &self.index } } +/// The unit a still-unresolved reference was looking in, when there is one to +/// name: the head of `unknown_mod::sig`, or the base class of an inherited +/// candidate. +/// +/// `None` for a resolution that never had an external home to miss — the +/// warning is about a name the workspace *could* have answered and did not, +/// not about every unresolved identifier in the file. +fn unresolved_unit(resolution: &Resolution) -> Option { + match resolution { + Resolution::ExternalCandidate { paths } => { + let first = paths.first()?; + Some(first.rsplit_once("::")?.0.to_string()) + } + Resolution::InheritedCandidate { base, .. } => Some(base.clone()), + _ => None, + } +} + /// A `` `define``/`` `undef`` a name touches, found by [`Scope::define_sites`]. pub(crate) struct DefineSite { pub(crate) macro_name: String, diff --git a/crates/vlog_refactor/tests/rename.rs b/crates/vlog_refactor/tests/rename.rs index 11982eb..8a9d4df 100644 --- a/crates/vlog_refactor/tests/rename.rs +++ b/crates/vlog_refactor/tests/rename.rs @@ -856,8 +856,9 @@ fn a_hierarchical_tail_that_resolves_is_renamed_with_its_declaration() { #[test] fn a_hierarchical_tail_that_cannot_resolve_is_left_alone_and_named_as_such() { // The module behind the instance is nowhere in the workspace, so the tail - // records nothing and the rename can only say so: the old-spelled tail is - // left as written and the warning names it. + // records nothing the index can finish: the old-spelled tail is left as + // written and the warning names the unit that could not be found. + // `docs/topo.md` §2.9-20, closed by docs/features/comment-slots. let text = concat!( "module top;\n", " wire sig;\n", @@ -871,15 +872,60 @@ fn a_hierarchical_tail_that_cannot_resolve_is_left_alone_and_named_as_such() { let after = apply(text, &edit, &path("m.sv")); assert!(after.contains("wire signal;"), "{after}"); assert!(after.contains("u_x.sig;"), "an unresolved tail is not edited: {after}"); - // Known gap, filed as `docs/topo.md` §2.9-20 (lead, 2026-09-01): before - // class-member-access such a tail had no reference at all and the stray - // scan (`stray_reason`) warned about it; now it carries an - // `ExternalCandidate` the workspace cannot answer, which the engine - // neither edits nor warns about. The edit behavior is right; the missing - // heads-up is the same class as §2.9-18's lost macro-argument warnings. + let named: Vec<&String> = edit.warnings.iter().filter(|w| w.contains("unknown_mod")).collect(); + assert_eq!(named.len(), 1, "one warning, naming the un-indexed unit: {:?}", edit.warnings); + assert!(named[0].contains("line(s) 5"), "and the line it was written on: {}", named[0]); + assert!(named[0].contains("left unchanged"), "{}", named[0]); +} + +#[test] +fn a_tail_the_workspace_can_finish_earns_no_such_warning() { + // The control: with `sub` in the workspace the tail resolves, is edited, + // and nothing is warned about. + let text = concat!( + "module sub;\n wire sig;\nendmodule\n", + "module top;\n", + " sub u_x ();\n", + " wire w;\n", + " assign w = u_x.sig;\n", + "endmodule\n" + ); + let files = workspace(&[("m.sv", text)]); + let edit = rename(&files, &path("m.sv"), at(text, "wire", "sig"), "signal").expect("renames"); assert!( - !edit.warnings.iter().any(|w| w.contains("u_x")), - "premise of the filed gap — no warning names the tail today: {:?}", + apply(text, &edit, &path("m.sv")).contains("u_x.signal;"), + "premise: the tail really was edited" + ); + assert!( + !edit.warnings.iter().any(|w| w.contains("could not be resolved")), + "a finished tail is an edit, not a warning: {:?}", + edit.warnings + ); +} + +#[test] +fn an_unresolved_tail_in_a_file_the_rename_never_edits_is_still_named() { + // The warning runs over every file that spells the name, not only the + // edited ones — the rule `macro_use_warnings` already followed. + let decl = "module holder;\n wire sig;\nendmodule\n"; + let other = concat!( + "module other;\n", + " unknown_mod u_y ();\n", + " wire w;\n", + " assign w = u_y.sig;\n", + "endmodule\n" + ); + let files = workspace(&[("holder.sv", decl), ("other.sv", other)]); + let edit = + rename(&files, &path("holder.sv"), at(decl, "wire", "sig"), "signal").expect("renames"); + assert_eq!( + apply(other, &edit, &path("other.sv")), + other, + "the other file is not edited at all" + ); + assert!( + edit.warnings.iter().any(|w| w.contains("other.sv") && w.contains("unknown_mod")), + "but it is named: {:?}", edit.warnings ); } @@ -960,3 +1006,42 @@ fn prepare_declines_exactly_what_rename_would_decline() { } assert!(prepare_rename(&files, &path("m.sv"), at(text, "wire", "a")).is_ok()); } + +// ---------------------------------------------------------------------- +// casts — `docs/features/comment-slots/README.md` (M11) +// ---------------------------------------------------------------------- + +#[test] +fn a_typedef_used_in_a_cast_is_renamed_there_too() { + let text = concat!( + "module m;\n", + " typedef logic [1:0] state_t;\n", + " state_t s;\n", + " initial s = state_t'(0);\n", + "endmodule\n" + ); + assert_eq!( + rename_one(text, "typedef logic [1:0] ", "state_t", "phase_t").expect("renames"), + concat!( + "module m;\n", + " typedef logic [1:0] phase_t;\n", + " phase_t s;\n", + " initial s = phase_t'(0);\n", + "endmodule\n" + ), + "the declaration, the declaration's use, and the cast" + ); +} + +#[test] +fn renaming_from_inside_a_cast_is_the_same_rename() { + let text = concat!( + "module m;\n", + " typedef logic [1:0] state_t;\n", + " initial s = state_t'(0);\n", + "endmodule\n" + ); + let from_decl = rename_one(text, "typedef logic [1:0] ", "state_t", "phase_t"); + let from_cast = rename_one(text, "initial s = ", "state_t", "phase_t"); + assert_eq!(from_decl.expect("renames"), from_cast.expect("renames")); +} diff --git a/crates/vlog_semantic/src/bind.rs b/crates/vlog_semantic/src/bind.rs index d5f52c2..caa365a 100644 --- a/crates/vlog_semantic/src/bind.rs +++ b/crates/vlog_semantic/src/bind.rs @@ -895,7 +895,7 @@ impl<'a> Binder<'a> { } fn bind_function(&mut self, f: &'a FunctionDecl, span: TextRange, scope: ScopeId) { - if f.scope.is_some() { + if !f.scope.is_empty() { // An out-of-body definition binds into its class's scope, which // may not exist yet — deferred until the whole file is bound. self.deferred.push(Deferred::Function(f, span, scope)); @@ -918,7 +918,7 @@ impl<'a> Binder<'a> { } fn bind_task(&mut self, t: &'a TaskDecl, span: TextRange, scope: ScopeId) { - if t.scope.is_some() { + if !t.scope.is_empty() { self.deferred.push(Deferred::Task(t, span, scope)); return; } @@ -1090,7 +1090,7 @@ impl<'a> Binder<'a> { /// so `cls` can be looked up wherever it is written — or stood in for /// when it lives in another file. fn bind_constraint(&mut self, c: &'a ConstraintDecl, span: TextRange, scope: ScopeId) { - if c.scope.is_some() { + if !c.scope.is_empty() { self.deferred.push(Deferred::Constraint(c, span, scope)); return; } @@ -1159,7 +1159,8 @@ impl<'a> Binder<'a> { let inner = self.new_scope(ScopeKind::Block, scope, item.span); self.bind_expr(array, scope); for v in vars { - self.declare(inner, &v.text, SymbolKind::Var, v.span, v.span); + let span = v.name.span; + self.declare(inner, &v.name.text, SymbolKind::Var, span, span); } self.bind_constraint_set(set, inner); } @@ -1422,7 +1423,8 @@ impl<'a> Binder<'a> { for d in deferred { match d { Deferred::Function(f, span, scope) => { - let path = f.scope.as_deref().unwrap_or(""); + let path = scope_path(&f.scope); + let path = path.as_str(); self.bind_out_of_body( path, &f.name, @@ -1437,12 +1439,14 @@ impl<'a> Binder<'a> { ); } Deferred::Constraint(c, span, scope) => { - let path = c.scope.as_deref().unwrap_or(""); + let path = scope_path(&c.scope); + let path = path.as_str(); let home = self.out_of_body_home(path, c.name.span, span, scope); self.bind_constraint_in(c, span, home); } Deferred::Task(t, span, scope) => { - let path = t.scope.as_deref().unwrap_or(""); + let path = scope_path(&t.scope); + let path = path.as_str(); self.bind_out_of_body( path, &t.name, @@ -1635,7 +1639,7 @@ impl<'a> Binder<'a> { self.bind_import_path(path, scope); } } - StmtKind::For { init, cond, step, body } => { + StmtKind::For { init, cond, step, body, .. } => { let inner = self.new_scope(ScopeKind::Block, scope, stmt.span); for i in init { match &i.ty { @@ -1671,7 +1675,7 @@ impl<'a> Binder<'a> { } self.bind_stmt(body, inner); } - StmtKind::While { cond, body } | StmtKind::DoWhile { body, cond } => { + StmtKind::While { cond, body } | StmtKind::DoWhile { body, cond, .. } => { self.bind_expr(cond, scope); self.bind_stmt(body, scope); } @@ -1680,13 +1684,14 @@ impl<'a> Binder<'a> { self.bind_stmt(body, scope); } StmtKind::Forever { body } => self.bind_stmt(body, scope), - StmtKind::Foreach { target, vars, body } => { + StmtKind::Foreach { target, vars, body, .. } => { let inner = self.new_scope(ScopeKind::Block, scope, stmt.span); self.bind_expr(target, scope); // A skipped dimension (`arr[, j]`) arrives as an empty name; // `declare` already ignores those, so it declares nothing. for v in vars { - self.declare(inner, &v.text, SymbolKind::Var, v.span, v.span); + let span = v.name.span; + self.declare(inner, &v.name.text, SymbolKind::Var, span, span); } self.bind_stmt(body, inner); } @@ -1723,7 +1728,7 @@ impl<'a> Binder<'a> { self.bind_declarators(&p.declarators, param_kind(&p.kw), &p.ty, stmt.span, scope) } StmtKind::PortDecl(p) => self.bind_port_decl(p, stmt.span, scope), - StmtKind::Return(e) => self.bind_opt_expr(e.as_ref(), scope), + StmtKind::Return { expr: e, .. } => self.bind_opt_expr(e.as_ref(), scope), StmtKind::Disable(name) => { // A use, not a declaration, so name-spans deliberately gave it // no range — the one statement still located by scanning. @@ -1764,7 +1769,7 @@ impl<'a> Binder<'a> { fn bind_timing(&mut self, t: &'a TimingControl, scope: ScopeId) { match t { - TimingControl::Delay(e) => self.bind_expr(e, scope), + TimingControl::Delay { expr, .. } => self.bind_expr(expr, scope), TimingControl::Event(list) => self.bind_sens_list(list, scope), } } @@ -1773,7 +1778,7 @@ impl<'a> Binder<'a> { /// clocking block's event, which is the same grammar. fn bind_sens_list(&mut self, list: &SensList, scope: ScopeId) { match list { - SensList::List(items) => { + SensList::List { items, .. } => { for i in items { self.bind_expr(&i.expr, scope); // `@(posedge clk iff enable)` reads `enable` as ordinarily @@ -1785,7 +1790,7 @@ impl<'a> Binder<'a> { } SensList::Star { .. } => {} // `@name;` without parens — the expression is an ordinary use. - SensList::Bare(e) => self.bind_expr(e, scope), + SensList::Bare { expr, .. } => self.bind_expr(expr, scope), } } @@ -1836,7 +1841,7 @@ impl<'a> Binder<'a> { } // `new src` — the source handle is an ordinary reference. ExprKind::New(src) => self.bind_expr(src, scope), - ExprKind::Index { base, index } => { + ExprKind::Index { base, index, .. } => { self.bind_expr(base, scope); self.bind_expr(index, scope); } @@ -1856,7 +1861,7 @@ impl<'a> Binder<'a> { // (`a[i].b`, `f().b`) still resolves its own head and stops: // chasing those needs the element type of a container, which // this crate does not model (TODO.md §15). - ExprKind::Member { base, name } => match &base.kind { + ExprKind::Member { base, name, .. } => match &base.kind { ExprKind::Ident(head) if head == "this" => { self.use_member(scope, name, member_tail(e.span, name), Target::ThisMember) } @@ -1877,7 +1882,7 @@ impl<'a> Binder<'a> { } } }, - ExprKind::Scope { base, name } => self.bind_scoped(base, name, e.span, scope), + ExprKind::Scope { base, name, .. } => self.bind_scoped(base, name, e.span, scope), // The `#( ... )` is verbatim text this crate makes no claims // about; the name it parameterizes is still an ordinary use. ExprKind::Parameterized { base, .. } => self.bind_expr(base, scope), @@ -1886,7 +1891,7 @@ impl<'a> Binder<'a> { self.bind_expr(&i.expr, scope); } } - ExprKind::Inside { lhs, ranges } => { + ExprKind::Inside { lhs, ranges, .. } => { self.bind_expr(lhs, scope); for i in ranges { self.bind_expr(&i.expr, scope); @@ -1925,18 +1930,20 @@ impl<'a> Binder<'a> { } } ExprKind::Paren { inner, .. } => self.bind_expr(inner, scope), - // Only the cast's operand is bound. The casting type names a - // type — a keyword (`int'(x)`), a typedef or a parameter — and - // resolving those is the type-name work this crate does not do - // anywhere else either. - ExprKind::Cast { expr, .. } => self.bind_expr(expr, scope), + // Both halves of a cast are bound: the operand as an ordinary + // expression, the casting type as a *type* — which + // `bind_data_type` has resolved since `overlay-promotion`. + ExprKind::Cast { ty, expr, .. } => { + self.bind_type_expr(ty, scope); + self.bind_expr(expr, scope); + } ExprKind::AssignPattern(items) => { for i in items { self.bind_opt_expr(i.key.as_ref(), scope); self.bind_expr(&i.value, scope); } } - ExprKind::ValueRange { lo, hi } => { + ExprKind::ValueRange { lo, hi, .. } => { self.bind_expr(lo, scope); self.bind_expr(hi, scope); } @@ -1955,6 +1962,36 @@ impl<'a> Binder<'a> { /// `p::x`: the head names a unit (package or class), the tail is looked /// up inside it. + /// The **casting type** of a `ty'(expr)`, bound as a type reference. + /// + /// The parser keeps a `casting_type` (IEEE 1800 §6.24.1) as an + /// expression, because that is the only shape wide enough for everything + /// the grammar spells there. Three of those shapes name a type and bind + /// as one; the rest are values, and bind as values: + /// + /// - a bare name — `state_t'(0)` — is a [`Target::Type`], the same + /// binding `bind_data_type` gives a declaration's type name. A type + /// *keyword* (`int'(x)`) names nothing declared and binds to nothing, + /// which is what `bind_data_type` does with one too. + /// - `pkg::t'(x)` is a [`Target::Unit`] plus a [`Target::UnitMember`] — + /// again exactly what `bind_data_type` records for `pkg::t x;`. + /// - a size, a parenthesized constant expression (`(N)'(x)`) or a system + /// function call (`$bits(t)'(x)`) is an *expression* standing in for a + /// width. Its operands are ordinary uses and are bound as such. + fn bind_type_expr(&mut self, ty: &Expr, scope: ScopeId) { + match &ty.kind { + ExprKind::Ident(name) => { + if !is_keyword(name) { + self.use_name(scope, name, ty.span, Target::Type); + } + } + ExprKind::Scope { base, name, .. } => self.bind_scoped(base, name, ty.span, scope), + // A number is a size (`4'(x)`) and names nothing at all. + ExprKind::Number(_) => {} + _ => self.bind_expr(ty, scope), + } + } + fn bind_scoped(&mut self, base: &Expr, name: &str, span: TextRange, scope: ScopeId) { let tail = TextRange::new(span.end.saturating_sub(name.len() as u32), span.end); match &base.kind { @@ -2057,7 +2094,7 @@ fn spine(base: &Expr) -> Option<(String, Vec)> { mids.reverse(); return Some((name.clone(), mids)); } - ExprKind::Member { base, name } => { + ExprKind::Member { base, name, .. } => { mids.push(name.clone()); current = base; } @@ -2108,7 +2145,7 @@ fn last_segment(path: &str) -> &str { /// the middle links, which is exactly what [`Target::MemberOf`] carries. fn randomize_head(base: &Expr) -> Option<(String, Vec)> { let ExprKind::Call { callee, .. } = &base.kind else { return None }; - let ExprKind::Member { base, name } = &callee.kind else { return None }; + let ExprKind::Member { base, name, .. } = &callee.kind else { return None }; if name != "randomize" { return None; } @@ -2120,7 +2157,7 @@ fn randomize_head(base: &Expr) -> Option<(String, Vec)> { mids.reverse(); return Some((head.clone(), mids)); } - ExprKind::Member { base, name } => { + ExprKind::Member { base, name, .. } => { mids.push(name.clone()); cur = base; } diff --git a/crates/vlog_semantic/src/facts.rs b/crates/vlog_semantic/src/facts.rs index a47fef2..97e5e0e 100644 --- a/crates/vlog_semantic/src/facts.rs +++ b/crates/vlog_semantic/src/facts.rs @@ -78,7 +78,15 @@ use crate::workspace::{ /// because the file that reads it happened to be cached) rather than a missing /// one. See `docs/features/semantic-lints-on/README.md` for the store delta /// this costs. -pub const FACTS_FORMAT: u32 = 13; +/// +/// 13 → 14 (2026-09-02, comment-slots M11): a cast's **casting type** is now +/// bound as a type reference (`state_t'(0)`, `pkg::t'(x)`), so a file that +/// only ever names a typedef inside a cast now records a reference to it +/// where it recorded none. A store written by an older build would answer +/// find-all-references and the rename preflight with that file's cast sites +/// missing — a rename that reports "3 files" for a name used in 4. See +/// `docs/features/comment-slots/README.md`. +pub const FACTS_FORMAT: u32 = 14; impl FileFacts { /// These facts as one line's worth of fields, tab-separated. diff --git a/crates/vlog_semantic/tests/semantics.rs b/crates/vlog_semantic/tests/semantics.rs index f35968b..72b0b31 100644 --- a/crates/vlog_semantic/tests/semantics.rs +++ b/crates/vlog_semantic/tests/semantics.rs @@ -754,3 +754,90 @@ fn a_mismatched_end_label_records_nothing_rather_than_guessing() { let s = analyze(&file, src); assert!(s.references().iter().all(|r| r.name != "wrong")); } + +// ---------------------------------------------------------------------- +// Casts — `docs/features/comment-slots/README.md` (M11) +// +// A cast's *casting type* is a type reference like any other. Before this +// round `bind_expr` bound only the operand, so `state_t'(0)` named nothing at +// all and hover, go-to-definition and rename all stopped at the `'`. +// ---------------------------------------------------------------------- + +#[test] +fn a_casts_type_name_is_a_use_of_the_typedef() { + let src = "\ +module m; + typedef logic [1:0] state_t; + logic [1:0] s; + initial s = state_t'(0); +endmodule +"; + let s = sem(src); + let at = nth(src, "state_t'", 0); + let r = s.reference_at(at).expect("the casting type is a reference"); + assert_eq!(r.name, "state_t"); + assert_eq!( + r.resolved(), + Some(symbol_id(&s, "state_t")), + "and it resolves to the typedef this file declares" + ); +} + +#[test] +fn a_scoped_casts_type_binds_both_halves() { + let src = "\ +module m; + logic [1:0] s; + initial s = pkg::t'(x); +endmodule +"; + let s = sem(src); + let unit = s.reference_at(nth(src, "pkg::t'", 0)).expect("the package half"); + assert_eq!(unit.name, "pkg"); + let item = s.reference_at(nth(src, "t'", 0)).expect("the member half"); + assert_eq!(item.name, "t"); + assert_eq!( + item.resolution, + Resolution::ExternalCandidate { paths: vec!["pkg::t".into()] }, + "the same candidate `pkg::t x;` would record" + ); +} + +#[test] +fn a_keyword_cast_and_a_size_cast_name_nothing() { + let src = "\ +module m; + initial begin + a = int'(x); + b = 4'(y); + end +endmodule +"; + let s = sem(src); + assert!(s.reference_at(nth(src, "int'", 0)).is_none(), "`int` is a keyword, not a name"); + assert!(s.reference_at(nth(src, "4'", 0)).is_none(), "a size names nothing"); + // The operands are still ordinary uses. + assert_eq!(s.reference_at(nth(src, "x)", 0)).map(|r| r.name.as_str()), Some("x")); + assert_eq!(s.reference_at(nth(src, "y)", 0)).map(|r| r.name.as_str()), Some("y")); +} + +#[test] +fn a_call_or_parenthesized_cast_binds_its_own_operands() { + let src = "\ +module m; + typedef logic [3:0] nib_t; + localparam int N = 4; + initial begin + a = $bits(nib_t)'(x); + b = (N)'(y); + end +endmodule +"; + let s = sem(src); + let arg = s.reference_at(nth(src, "nib_t)", 0)).expect("the system call's argument"); + assert_eq!(arg.name, "nib_t"); + assert_eq!(arg.resolved(), Some(symbol_id(&s, "nib_t"))); + let n = s.reference_at(nth(src, "(N)", 0) + 1).expect("the parenthesized width"); + assert_eq!(n.name, "N"); + assert_eq!(n.resolved(), Some(symbol_id(&s, "N"))); +} diff --git a/docs/features/comment-slots/README.md b/docs/features/comment-slots/README.md new file mode 100644 index 0000000..6f249c4 --- /dev/null +++ b/docs/features/comment-slots/README.md @@ -0,0 +1,544 @@ +# comment slots + +## Goal + +Make hard invariant #3 — *comments are never dropped* — true at every +inter-token gap of the grammar, not just at the gaps a construct happened to +have a field for. A comment written where no AST node owns it is not deleted: +`Parser::bump` queues it and the next node's `take_meta` hands it to whatever +comes next, so the formatter prints it **one node later**, `verify.rs` +compares comments too, and the whole file is refused. Exit 2, no output — a +real file with a comment in an ordinary place becomes unformattable. Three +rounds had filed their leftovers here (`docs/topo.md` §2.9-22: 52 covergroup +gaps, 41 fragment gaps, 40 constraint gaps), and the count over ordinary RTL +had never been taken at all. This round adds the missing owner for every one +of them, commits the constraint fuzzer that measured the problem but was never +landed, adds a fourth fuzzer over plain RTL, and drives all four to **zero**. +It also carries three small correctness items that were waiting on the same +files: go-to-definition on a macro use (H5), the casting type of a cast +binding as a type (M11), and the rename warning for a reference the workspace +could not finish (§2.9-20) — plus §2.9-21, the escaped name inside a scoped +type, which falls out of the same segment work. + +## Assumptions + +- **A gap belongs to a construct only when the token that closes it was + written.** `Parser::gap_before(sym)` is `take_gap` behind that check, and + `take_before_open(sym)` is its opener-side twin. Both were already here; + every new slot uses one of them or `take_gap()` directly, which takes only + the comments written *since the last consumed token* — never a comment + queued from further back, which belongs to whoever owns the place it was + written. This is `constraint-bodies`' rule, applied about seventy more + times. +- **One owner per gap.** `StmtKind::takes_semi()` is the single answer to + "who writes a statement's `;`", the twin of + `ConstraintItemKind::takes_semi()`. A `debug_assert!` in + `parse_stmt_inner` refuses a `before_semi` on a kind that wrote no `;`. +- **The empty case must cost nothing.** Every new field is printed through + `Fmt::slot_comments`, which is a no-op on an empty slot, and every + construct with an `is_empty()` short-circuit keeps its old code path + verbatim. This is what the corpus byte-identity gate below actually + measures: 860 corpus files and 3 975 opentitan files format to the same + bytes as v0.30.0, because no comment-free construct takes a new branch. +- **`Expr` may not grow.** It is walked recursively in debug builds and the + server's whole-corpus completion test overflowed an 8 MiB stack the first + time it did (96 → 144 bytes). Every expression-level slot is therefore + boxed — `SegmentComments`, `CastComments`, `ArgComments`, and even the two + bare `Vec` on `Unary`/`Postfix` — and `Expr` is back at its + pre-round 96 bytes. `StmtKind` grew 368 → 392 and `Stmt` 504 → 552, which + the same test tolerates. +- **`verify.rs` is untouched and no normalization was widened.** Ten new + attack pairs ship anyway (CLAUDE.md invariant 4), each a comment moved + across exactly one of the tokens a new slot is defined *between*. +- **A comment inside a bracket pair forces that pair open.** That has always + been true of a port list; it is now true of a `for` header's parentheses, an + empty argument list and a `do ... while` condition too. Two + `comment_slots.cases` entries lay out across several lines for that reason + and are fixed points there. +- **The joined spelling of a scoped name keeps the whitespace an escaped + segment needs.** `\my-pkg ::\state-t` is three tokens; joined tightly it + reprints as the single token `\my-pkg::\state-t`. `Parser::push_scope_segment` + is the one place the join happens, and it writes the terminator. The + doubled space this produces before the declarator (`\state-t \st`) is what + a bare escaped type name already printed. + +## Handshakes + +**Consumed.** `Parser::{bump, take_meta, take_gap, gap_before, +take_before_open, take_around, take_dangling}` unchanged — every new slot is +built out of them. `Fmt::{inline_comments, inline_comments_spaced, +paren_comments, delimited_dangling}` likewise. `vlog_semantic::bind_data_type` +is the type resolver M11 mirrors. + +**Promised / changed, in AST order.** Everything here is additive except +where marked; no existing field changed meaning. + +| node | new | note | +|---|---|---| +| `ExprKind::{Member, Scope, Index, Range}` | `comments: Box` | one struct, five slots, one shared parse | +| `ExprKind::ValueRange` | `comments: Box` | the same `[a:b]` grammar | +| `ExprKind::{Inside, InsideMacro}` | `comments: Box` | `inside` is an operator like any other | +| `ExprKind::Cast` | `comments: Box` | `ty /*a*/ ' /*b*/ ( /*c*/ e /*d*/ )` | +| `ExprKind::Unary` / `Postfix` | `comments: Box>` | the gap beside the operator | +| `ExprKind::NamedArg` | `comments: Box` | replaces `close_comments` | +| `Dim` | `comments: Box` | packed, unpacked, `[]` and `[*]` | +| `Stmt` | `before_semi` + `StmtKind::takes_semi()` | widest slot of the round | +| `StmtKind::{If, Case}` | `after_kw` | in-paren comments still via `header_parens` | +| `StmtKind::{For, DoWhile}` | `comments: Box` / `Box` | `do ... while` has no body to recover from | +| `StmtKind::Foreach` | `comments`, `var_comments`, `vars: Vec` | `Name` → `ForeachVar` | +| `StmtKind::{Block, ForkJoin}` | `label_comments`, `end_label_comments` | | +| `StmtKind::Return` | tuple → `{ after_kw, expr }` | | +| `CaseItem` / `GenCaseItem` | `before_colon` | the optional `:` of `default` | +| `TimingControl::Delay` | tuple → `{ after_hash, expr }` | | +| `SensList::{List, Bare}` | `after_at`; tuple → struct for `Bare` | `Star` already had its two | +| `SensItem` | `after_edge` | `@(posedge /*c*/ clk)` | +| `Module`, `ItemKind::Package`, `ClassDecl` | `before_name`, `before_semi`, `end_label_comments`, `param_after_hash` | | +| `FunctionDecl`, `TaskDecl` | `after_kw`, `before_name`, `before_args`, `args_dangling`, `before_semi`, `end_label_comments`; `prefix`/`qualifiers`: `Vec` → `Vec`; `scope`: `Option` → `Vec` | | +| `ConstraintDecl`, `CovergroupDecl` | `qualifiers: Vec`, `end_label_comments`; `ConstraintDecl::scope: Vec` | | +| `DataDecl`, `StructMember` | `qualifiers: Vec` | | +| `ParamDecl` | `after_kw` | | +| `Declarator`, `TfArg`, `AnsiPort`, `ParamPort`, `EnumMember` | `eq_comments`, plus `after_dir`/`after_kw`/`before_name` where the shape has one | | +| `Connection` | `after_dot`, `before_open`, `after_open` | | +| `Instantiation` | `after_hash`, `before_semi` | | +| `Typedef` | `after_kw`, `before_name`, `before_semi` | | +| `StructType` | `header_comments: Box` | four keyword gaps | +| `EnumType` | `after_kw`, `before_open` | | +| `GenBlock` | `before_kw`, `before_colon`, `after_colon`, `end_label_comments` | | +| `GenFor` | `after_genvar`, `comments`; `ItemKind::GenFor(Box)` | boxed on clippy's advice | +| `ClockingDecl` | `end_label_comments` | | +| `vlog_semantic::FACTS_FORMAT` | 13 → 14 | M11 records references a cached store would not have | + +**Requests filed.** + +1. **`crates/vlog_linter/src/signals.rs:629` was edited** — one `..` added to + `ExprKind::Postfix { expr, op }` and `ExprKind::Unary { expr, op }` in + `increment_target`, forced by the two new `comments` fields. That file + belonged to the §24 lane when this round started (it has since merged), so + the change is flagged rather than made silently. It is a mechanical pattern + update with a comment saying so, and nothing else in `vlog_linter` was + touched. +2. **A cross-file instance-member tail does not resolve for rename.** The new + §2.9-20 warning surfaced it: with `module sub` in `sub.sv` and + `assign w = u_x.sig;` in `top.sv`, renaming `sub`'s `wire sig` edits + `sub.sv` only and now *says* so. In one file the same shape resolves and is + edited (`a_hierarchical_tail_that_resolves_is_renamed_with_its_declaration` + is the pin). Not this round's to fix — the warning is exactly the heads-up + §2.9-20 asked for — but it is a real gap worth a row of its own. +3. **`docs/topo.md` rows 20, 21 and 22 are closed** and want striking by the + lead (this round does not edit `topo.md`). + +## Status / TODO + +- [x] **G1** shared postfix segments — one `parse_postfix_segment` replaces + the three-branch loop in `parse_postfix_inner`, + `parse_foreach_target_inner` and `parse_bare_event_name` +- [x] **G2** one `[a:b]` grammar — `parse_value_range` is now the only copy; + the `inside` set calls it and `parse_dims` shares `SegmentComments` +- [x] **G3** header keyword gaps — statement `if`/`case`/`for`/`foreach`/ + `do ... while`, `@` event control, `#` delay +- [x] **G4** `Stmt::before_semi` + `StmtKind::takes_semi()` +- [x] **G5** segment-preserving scoped names — `ScopeSeg`, and + `push_scope_segment` for the joined spellings (closes §2.9-21) +- [x] **G6** per-construct slots: qualifier runs, `parse_tf_ports`, labels, + module/package/class/function/task/typedef/enum/struct headers, + declarators, ports, connections, instantiations, casts, unary/postfix +- [x] Four gap fuzzers at zero: covergroup 329, fragment 153, constraint 395, + RTL 352 — `EXPECTED_FAILING_*` and both analogue tests deleted, the + constraint fuzzer committed, an RTL fuzzer added +- [x] `cases/comment_slots.cases` — 37 cases, one per slot family +- [x] 10 attack pairs; `verify.rs` untouched +- [x] Premise pins inverted: + `a_comment_in_a_for_foreach_or_do_while_header_is_kept`, + `an_escaped_name_in_a_scoped_type_now_keeps_its_terminating_space`, + `a_hierarchical_tail_that_cannot_resolve_is_left_alone_and_named_as_such` +- [x] **H5** `nav::definition` gains the macro branch, sharing hover's + `macro_name` and `narrowed_to_the_include_graph` +- [x] **M11** `bind_type_expr` — a cast's casting type binds as a type; + `FACTS_FORMAT` 13 → 14 +- [x] **§2.9-20** `Scope::unresolved_candidate_warnings`, run over every file + that spells the name +- [x] Gates: fmt / clippy / `cargo test --workspace` / corpus gate + byte + identity / opentitan sweep / vsix smoke + +## Work log + +**2026-09-02 — dev.** + +*The mechanism, restated, because it is what the whole round turns on.* A +comment is never dropped by a missing slot. `bump` moves a consumed token's +leading comments into `pending_leading` and its trailing into +`pending_trailing`; `take_meta` — the only universal harvest, and it runs at a +node's **start** — drains both into the *next* node's `Meta::leading`. So a +gap with no owner prints its comment one node later, and `verify.rs` refuses +the file for a reordered comment. The fix is never "stop losing it"; it is +always "give this gap a field, and print the field between the same two +tokens". + +*Order of work.* The fuzzers drove everything. A scratch harness ran all four +fixture sets after each change and printed the failing sources, so no slot was +guessed at: covergroup 52 → 30 → 8 → 4 → 0, fragment 41 → 14 → 3 → 1 → 0, +constraint 92 → 49 → 19 → 7 → 2 → 0, RTL 178 → 120 → 91 → 62 → 39 → 24 → 11 → +7 → 0. (The constraint set is re-derived from the README's table rather than +the original fifteen fixtures byte for byte, which is why it is 395 gaps and +not 358.) + +*Three duplicates became one.* `parse_postfix_inner`, +`parse_foreach_target_inner` and `parse_bare_event_name` each wrote the +`.`/`::`/`[` loop out by hand, and each lost the same comments in it. +`parse_postfix_segment` is now the only copy; the two callers keep only their +own break conditions (a `foreach` target stops at the bracket group the `)` +follows; a bare event name needs an identifier after its `.`). The `[a:b]` +grammar was written three times the same way — `parse_value_range`, an inlined +copy in the `inside` set, and `parse_dims` — and `parse_value_range` is now +the only one, with `parse_dims` sharing its `SegmentComments` shape. + +*Two decisions worth arguing with.* + +1. **`header_parens` was left standing for `if` and `case`.** It is a + *print-side* recovery: it reads the body statement's leading comments, + partitions them by span around the condition, and prints them back inside + the parentheses. Giving `if` real `after_open`/`before_close` slots would + have taken those comments away from the body's meta, made `header_parens` + a no-op, and changed the layout of every corpus file that has a comment + there. So `if` and `case` got only `after_kw` — the one gap + `header_parens` structurally cannot reach, because it sits *outside* the + parentheses. `for`, `foreach` and `do ... while` have no body-after-parens + to recover from and got the full slot set. This is why the corpus is + byte-identical. +2. **The `;` is still printed per statement kind.** `takes_semi()` is the + single owner of the *gap*, as the brief asked, but the `;` itself is + emitted by each `stmt_kind` arm through `Fmt::semi(before_semi)` rather + than centrally by `stmt`. Moving it out would have moved it outside the + `group(...)` that several arms wrap, changing what fits on a line. The + ownership question — who may hold `before_semi` — is answered once, by + `takes_semi()` and a `debug_assert!`; the emission is threaded. + +*Labels.* `parse_label` gained `parse_label_with`, which returns +`Box` alongside the name, and ten nodes gained an +`end_label_comments` (plus `label_comments` on `Block`/`ForkJoin`, and three +fields on `GenBlock` for `for (…) /*c*/ begin /*c*/ : /*c*/ g`). `Fmt::closing` +is untouched for the empty case; `closing_labeled` delegates to it when the +slots are empty, which is every existing corpus file. + +*Qualifier runs.* `take_member_prefix` returned `Vec`, which cannot +say *which* gap of `pure /*c*/ static` a comment was written in — and the two +spellings are different token streams. It returns `Vec` now, one +`after` per keyword; `Fmt::qualifier_run` prints the run and the separator +after each word. The same change covers `DataDecl::qualifiers` and +`StructMember::qualifiers` (`rand /*c*/ bit x;`, a QA finding filed by +`constraint-bodies` round 2). + +*The size regression, and the fix.* Adding the slots inline took `Expr` from +96 to 144 bytes and `Stmt` from 504 to 696, and +`completion::tests::a_member_request_over_the_whole_corpus_stays_in_budget` +overflowed its stack in a debug build. Boxing the four expression comment +structs (`NamedArg` alone carried 72 bytes of `Vec`) put `Expr` back to +exactly 96. `ItemKind::GenFor` was boxed on clippy's advice for the same +reason. Worth writing down: an AST field is not free just because it is +usually empty. + +*§2.9-21 without restructuring `DataType`.* The escaped-name gap needed the +scoped-name *join* to keep whitespace, not `DataType::name` to become +segments. `Parser::push_scope_segment` is that join — used by +`parse_scoped_name`, both type-name loops and `parse_instantiation` — and +`parse_method_name` keeps real segments (`ScopeSeg`) because it also needed a +comment slot per `::`. The `escaped_identifiers.cases` `#SKIP` is now a live +case and the verification pin is inverted, with a new pair asserting that +tightening the space back up is still refused. + +*H5.* `nav::definition` had no macro branch at all: a macro use is one token +with no `Reference`, so both layers below answered `None`. It now runs the +same two-step lookup hover does — `doc.defines.latest(name)` first, then +`narrowed_to_the_include_graph(ws, doc, ws.index().find_define(name))` — and +returns every surviving candidate. `macro_name` and the narrowing became +`pub(crate)` rather than being copied. Five unit tests and one e2e session +(in-file, cross-file, include-narrowed, a define inside a fragment file, and +`` `uvm_info`` with no UVM in the index → nothing). + +*M11.* `bind_expr`'s `Cast` arm dropped `ty` behind a stale comment claiming +type names are not resolved; `bind_data_type` has resolved them since +`overlay-promotion`. `bind_type_expr` mirrors its three shapes: a bare name is +a `Target::Type` (a type *keyword* names nothing, exactly as +`bind_data_type` treats one), `pkg::t` is `Target::Unit` + +`Target::UnitMember`, and a size, a parenthesized width or a `$bits(...)` call +is an expression whose operands bind as ordinary uses. `type_def.rs`'s doc +comment has claimed since it was written that case 2 "is what reaches a cast +(`state_t'(0)`)"; it is true now, and pinned. `FACTS_FORMAT` is bumped because +a store written by 0.30.0 records no reference for a typedef named only inside +a cast, and find-all-references would answer from it. + +*§2.9-20.* `unaccounted_warnings` builds `covered` from every reference's +`name_span` regardless of resolution, so a candidate that stayed +`ExternalTarget::StillUnresolved` through the overlay was silently skipped — +the tail's *own* reference is what silenced the stray scan that used to warn +about it. `unresolved_candidate_warnings` asks the `Resolution` first (an +`InheritedCandidate` that missed stores nothing in the overlay, so `get` +answers `None` for it and for a plain local miss alike), then checks for +`StillUnresolved`, and groups one line per (file, unit). It runs over every +file that spells the name, with the `text.contains` prefilter +`macro_use_warnings` uses — and because `collect_occurrences` has already +analysed every such file, it costs nothing extra. Writing the control test is +what turned up request 2 above. + +*Gate numbers.* `cargo test --workspace`: 46 binaries, **3 159 passed, 0 +failed**. `cargo test -p vlog_formatter`: 910 cases (37 new), 194 verification +tests, all green. Corpus gate 814/820, unchanged, and the formatted output of +all **860** corpus files is **byte-identical** to a v0.30.0 build — zero files +moved, because no comment-free construct takes a new branch. Opentitan +read-only sweep over **3 975** files: zero output differences, zero new +failures, the same 10 pre-existing ones, and zero files that newly format +(nothing in opentitan had a comment in a re-attaching slot). `cargo fmt` clean +per crate, `cargo clippy --all-targets --workspace` clean, vsix smoke OK. + +## QA log + +**2026-09-02 — QA.** + +Scope confirmed: `git status --porcelain` at the start of this pass showed the +25 modified files + `crates/vlog_formatter/tests/cases/comment_slots.cases` + +`docs/features/comment-slots/` the brief named. Partway through the pass +`docs/topo.md` also appeared modified — rows 20/21/22 struck and a new row 23 +filed for the cross-instance-member-tail gap the dev's Handshakes section +flagged. That is the lead's stated follow-up (CLAUDE.md: "this round does not +edit `topo.md`"), not the dev's, and its content matches everything verified +below, so it is noted here rather than treated as scope creep. + +*1. Gates, run directly.* +`git diff --stat -- crates/vlog_formatter/src/verify.rs` is empty — invariant +4 holds, the safety net is untouched. `cargo fmt --check` clean on all six +touched crates. `cargo clippy --all-targets --workspace`: 0 warnings; grepped +the full diff for `allow(` on every added line — none. `cargo test +--workspace --no-fail-fast`: 46 binaries, **3159 passed, 0 failed** (34 + 2 + +1 + 1 ignored, all pre-existing, not this round's), reproduced twice +identically. `cargo test -p vlog_formatter`: **194 verification tests + 910 +cases (37 new to `comment_slots.cases`)**, 0 failed. `tools/corpus_check.sh`: +814/820 (11 ok-unchanged + 803 would-reformat + 6 parse-error), 0 +verification-error, 0 crash — matches the dev's number exactly, and confirms +it is a live, reproducible gate rather than a one-time measurement. + +*2. Output neutrality, independently.* Built v0.30.0 in +`.claude/worktrees/qa-base` and the working tree's release binary, then +compared `--stdout` output byte-for-byte over every corpus file and a large +opentitan sample: +- **Corpus (860 files):** 854 identical, **0 differing**, 6 both-fail (the + known parse-error set both builds share). Matches "byte-identical … zero + files moved." +- **Opentitan (3947 files found under the current checkout, vs the dev's + 3975 — the checkout has drifted slightly since the round's own sweep; not + a regression, see below):** 3936 identical, **0 differing**, 11 both-fail + (dev reported 10; the +1 is consistent with the same checkout drift, not a + new failure — no file differs in *output*, which is the invariant that + matters). `git -C /Users/guoliangchen/repo/opentitan status --porcelain` + after the sweep showed only the owner's three pre-existing files + (`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/ast.sv`, + `hw/top_earlgrey/ip/ast/rtl/ast.sv`) — untouched, nothing else. Worktree + removed after (`git worktree remove --force .claude/worktrees/qa-base`). + +*3. Comment slots — tried to break them.* Read every `Fmt::slot_comments` +call site and the `SegmentComments`/`BinaryComments`/`LabelComments`/ +`ScopeSeg`/`before_semi` fields in `ast.rs`, then wrote 35 targeted `.sv` +probes (not the dev's own fixtures) covering essentially every row of the +Handshakes table: module/class/package headers and end-labels, typedef + +struct/enum headers, `Dim` arithmetic, instantiation + named connection, +clocking end-label, `genvar` `for`, `foreach` with a bracketed var, +`inside`, casts, unary/postfix, named args, qualifier runs, `case` +`default:`, `#`/`@` delay and edge-keyword gaps, block/fork-join labels, +`return`, `do…while`, generate blocks (labelled and not), constraint/ +covergroup qualifiers+scope+end-label, `rand`/qualifier runs on +`DataDecl`/`StructMember`, ANSI ports, param ports, enum-member `=`, +declarator `=`, `TfArg` default `=`. For each: formatted once, re-formatted +the output, and diffed comment counts. **35/35 format successfully, are +idempotent, and keep every comment exactly where it was written** — no drift +to the next node. Cross-checked all 35 against the v0.30.0 baseline: **33 of +35 were refused by 0.30.0** (the round's whole point) and now format; the +other 2 (a plain module end-label, a bare clocking end-label) happened to +already pass on 0.30.0 too. One out-of-scope gap found and confirmed +**pre-existing, not a regression**: a comment inside a *plain* (non-escaped) +scoped type name used as an ordinary declaration type (`pkg /*c*/ ::item +x;`) is still rejected identically on both v0.30.0 and the working build — +`ScopeSeg`/comment slots were only ever promised for `FunctionDecl`/ +`TaskDecl`/`ConstraintDecl::scope` and `parse_method_name` chains, never for +`DataType::name`'s plain-string join, so this is correctly out of the +round's stated scope. Filed here for visibility, not as a blocking finding. + +*4. The four fuzzers.* Found in `crates/vlog_formatter/tests/verification.rs` +(`gaps`/`failing_gaps`/`assert_no_failing_gaps`, lines ~1988–2043, shared by +all four). Each fixture set's total gap count is asserted alongside the +zero-failures count (`assert_eq!((counted, failed.len()), (total, 0), …)`), +so a shrunken fixture can't pass by asking less — confirmed the constants +(329/153/395/352) match the dev's numbers exactly. No allowlist, `#SKIP`, or +filter anywhere in the fuzzer machinery (`grep -rn "#SKIP" +crates/vlog_formatter/tests/cases/*.cases` returns nothing at all — the +escaped-identifiers `#SKIP` this round closed was the last one in the repo). +Confirmed the two old "expected failing" analogue tests +(`EXPECTED_FAILING_GAPS`/`EXPECTED_FAILING_FRAGMENT_GAPS`, 52/41) are gone +from the diff as pure deletions, not renames. Ran all four fuzzer tests +individually: green. + +*5. G4 single-ownership `debug_assert!`.* Found at +`crates/vlog_parser/src/parser.rs:6174`, inside `parse_stmt_inner`, gated by +the ordinary `self.enter()?`/depth machinery that already runs under debug +assertions in every `cargo test` (release-mode debug_assert stripping is not +in play here — this is the default `dev`/`test` profile). Traced the +single-writer property by hand: `self.semi_comments` is cleared at the top of +every `parse_stmt_inner` call and taken (`mem::take`, which resets it) right +before that same call returns; the only writers, +`expect_stmt_semi`/`eat_stmt_semi`, are called exclusively from the branches +of `parse_stmt_kind` that correspond 1:1 to `takes_semi()`'s `true` arms +(verified `Assign`/`ExprStmt` at parser.rs:6790–6807 and the `Timing`/`Wait`/ +`Assert`/`DoWhile` branch-selecting `eat_stmt_semi` call sites at +6261/6270/6524/6532). A statement kind that recurses into a nested +`parse_stmt()` (an `if`, a block, `do…while`'s body) always does so *before* +its own optional `expect_stmt_semi` call, and the nested call's own +clear/take pair fully resets `self.semi_comments` on the way back out, so +there is no path by which a child's semicolon comments could leak into a +parent's `before_semi` or vice versa. Exercised by all 3159 workspace tests +and the 910-case suite with zero assertion failures. Reachable and correct; +no double-ownership path found. + +*6. H5 (macro go-to-definition).* Ran the dev's e2e test +(`go_to_definition_on_a_macro_use_lands_on_its_define`) and all 5 named unit +tests in `crates/lucisv_server/src/nav.rs` individually: all green, +in-file/cross-file/include-narrowed/fragment-file/unknown-macro as +described. Confirmed `hover::macro_name` and +`hover::narrowed_to_the_include_graph` were widened from private to +`pub(crate)` rather than duplicated (the diff shows only the visibility +change). Did not additionally run the real server against an opentitan DV +file — the e2e session already covers in-file, cross-file and +include-narrowing against real workspace machinery, and opentitan's own +`` `uvm_* `` macros are exactly the "not in the index" case the +`a_macro_nothing_defines_has_no_definition` unit test already pins. + +*7. M11 (casts).* Ran the dev's 3 `type_def.rs` unit tests and 4 +`vlog_semantic` tests: green. Read `bind_type_expr` (bind.rs:1981) and +confirmed it mirrors `bind_data_type`'s three shapes exactly as claimed. +Added temporary throwaway tests (removed after, see incident note below) for +`pkg::t'(x)` cross-package, `signed'(x)` and `logic'(y)`: all three answer +**silently** (empty location list) rather than a wrong target, which is +within the task's own bar ("go to the right declaration or be silent, never +a wrong target"). This is a real, but pre-existing and never-promised, +limitation of `type_def.rs::type_use_at` — it only ever consulted an +**in-file** resolved `Reference` (`reference.resolved()`), never the +workspace overlay, for the "cursor on a *use*" case (case 2); the plain +*declaration* case (case 1, `pkg::t s;`) has always worked cross-file because +it hands off to `nav::definition` instead. M11's own promise — and its only +tested claim — is that the casting type's reference is now *recorded at all* +(confirmed at the semantic layer by +`a_scoped_casts_type_binds_both_halves`, which pins the `ExternalCandidate` +resolution `pkg::t` feeds to rename/find-references), not that +`textDocument/typeDefinition` gained cross-file reach for a cast +specifically. The `type-definition/README.md` amendment is scoped the same +way (case 2, in-file), so there is no doc/reality mismatch — noting this as +context, not a finding that forces rework. + +**Incident, disclosed in full.** While building the cross-package-cast probe +above I first added a throwaway e2e test to `crates/lucisv_server/tests/e2e.rs` +and, to remove it again, ran a Python script keyed on a start/end text +marker; the end marker's `str.rindex` matched much further down the file than +intended and the removal deleted roughly 3100 lines of pre-existing, +unrelated test code (everything after the `typedef` cross-file test to +EOF) — none of it the dev's own work, but real code all the same. Caught +immediately via `git diff --stat` (expected `68 insertions(+), 0 deletions`, +saw `3122 deletions`). Recovered fully and losslessly: confirmed the deleted +range was byte-identical between HEAD and the dev's working copy (the dev's +diff for this file is a single contiguous 68-line insertion earlier in the +file, confirmed by line-number offset arithmetic and a direct byte +comparison of the boundary lines), then reconstructed the missing tail from +`git show HEAD:crates/lucisv_server/tests/e2e.rs` and appended it back. +Re-diffed against the dev's original hunk: identical, `68 insertions(+), 0 +deletions(-)`. Full `cargo test -p lucisv_server` re-run clean afterward +(1429 + 83 + 3 = 1515 passed, 0 failed). The `type_def.rs` scratch tests were +removed with the `Edit` tool (exact string match) rather than the same +script, and its diff was independently confirmed to match the dev's original +43-line insertion exactly. Final `git status --porcelain` matches the +session's opening snapshot file-for-file (plus the lead's `docs/topo.md` +update noted above). No dev work was lost; flagging this so the lead knows a +large bulk-text-removal script touched the tree mid-session and was +verified, not merely trusted. + +*8. §2.9-20 (rename warnings).* Ran +`a_hierarchical_tail_that_cannot_resolve_is_left_alone_and_named_as_such`, +`a_tail_the_workspace_can_finish_earns_no_such_warning`, and +`an_unresolved_tail_in_a_file_the_rename_never_edits_is_still_named` +individually: all green. Confirmed the two-file case (resolvable in one file, +unresolvable in another) edits the resolvable file, leaves the other +untouched, and warns naming both the file and the unit +(`other.sv`/`unknown_mod`), and that the warning text includes the line +number and "left unchanged." Confirmed the premise pin really did invert +(old name `..._is_left_alone_and_named_as_such` now documents the *warned* +behavior, per the diff and the topo.md row-20 strike-through). + +*9. §2.9-21 (escaped scoped segments).* Ran +`an_escaped_name_in_a_scoped_type_now_keeps_its_terminating_space` and +`a_space_dropped_inside_a_scoped_escaped_type_is_rejected`: green. +`grep -rn "#SKIP" crates/vlog_formatter/tests/cases/*.cases` is empty — the +former `#SKIP` case is confirmed live. Manually probed three shapes the +dev's own tests don't cover: `\pkg ::\x \v ;` (fully escaped, single +segment), `pkg::\weird.name \v ;` (mixed plain+escaped), and a three-level +chain `\my-pkg ::\a-b ::\c-d \v ;` — all three format, keep the double-space +terminator before the declarator, and are idempotent on a second pass. + +*10. Size pins.* **No `size_of::()`/`size_of::()`/ +`size_of::()` assertion exists anywhere in the tree** (`grep -rln +size_of crates/` returns nothing) — not even a printed-but-unasserted one. +The only regression signal for the round's central size invariant ("`Expr` +may not grow") is the *indirect* symptom the dev's own work log describes: a +debug-build stack overflow in +`lucisv_server::completion::tests::a_member_request_over_the_whole_corpus_stays_in_budget`, +which additionally **no-ops silently when `corpus/` is not checked out** +(`if !corpus.is_dir() { …; return; }`). That means a future change that grew +`Expr` back past 96 bytes would have no fast, direct, always-on test failure +— only a slow, corpus-dependent, debug-only crash in an unrelated server +test, or none at all in an environment without the corpus checked out. +**MEDIUM finding**, not blocking (nothing is wrong today; the pin the round's +own Assumptions section relies on doesn't exist as code) — recommend a +`const _: () = assert!(std::mem::size_of::() <= 96);`-style static +assertion in `vlog_parser::ast` for `Expr`, `Stmt` and `StmtKind`, filed here +rather than fixed directly since it's outside this pass's small-fix +allowance and belongs in the feature's own file scope. + +*11. Docs.* `docs/features/comment-slots/README.md` has all seven required +sections. Status/TODO checklist matches what's actually landed (verified +G1–G6, the fuzzers, H5, M11, §2.9-20 items above; the one unchecked line — +"QA: fuzz 5 fresh fixtures…" — is this pass's own item, now done). `TODO.md` +§25 checkboxes match: G1–G6, fuzzers, H5, M11, §2.9-20 ticked; only the QA +line remains open pending this log. Spot-checked three of the other seven +edited feature READMEs against the actual diffs: `escaped-identifiers`, +`refactor-rename` and `overlay-promotion`/`type-definition` (four, since two +were quick) — all accurately describe the mechanism, cite the right +function/test names, and match the code read in items 6, 7, 8 and 9 above. + +**Verdict: PASS.** No wrong answer found anywhere the brief asked to check. +One MEDIUM finding (item 10, missing size pins — recommend, don't block) and +one informational out-of-scope note (item 3's plain-scoped-name gap, item +7's cross-file cast-typeDefinition limit) that are both pre-existing, +correctly out of this round's stated scope, and consistent with the docs. +The mid-pass file-recovery incident (see item 7) is disclosed in full above +and was fully and verifiably resolved before this verdict was written. + +## Review + +**2026-09-02 — lead.** Accepted. The dev's own framing is the right one: +a missing slot never *deleted* a comment, it re-attached it one node later +and the safety net refused the file — so the fix is an owner per gap, and +the proof is four exhaustive fuzzers at zero plus byte-identity of every +comment-free file against v0.30.0 (860 corpus, 3 975 opentitan; QA +reproduced both from an independent baseline build: 0 differing). The two +deviations are correct calls: a real in-paren slot for `if`/`case` would +have moved comments out of `header_parens`' reach and changed shipped +layout for no gain, and the `;` staying inside each arm's `group(...)` is +what keeps line fitting unchanged. `bind_type_expr`'s keyword check is +redundant with `use_name`'s, which is fine. The rename warning asks the +`Resolution` before the overlay for exactly the reason it states. + +Acted on at review: QA's one MEDIUM — no static size pin existed, only an +indirect debug-only stack overflow that needs the corpus on disk — is +closed by `ast::size_pins` (`Expr` ≤ 96, `StmtKind` ≤ 392, `Stmt` ≤ 552 on +64-bit). QA's e2e.rs accident was verified recovered: the working diff +against HEAD is 68 added lines and zero removed, the one new H5 test, and +the `lucisv_server` suite is green. Handshake 1 (`signals.rs` pattern +`..`) accepted as flagged; handshake 2 filed as `docs/topo.md` §2.9-23; +rows 20/21/22 struck. QA's pre-existing gap — a comment inside a plain +`pkg::item` type name — is the `push_scope_segment` join and belongs to +the next comment round; noted here, not filed separately. Ships in +0.31.0. diff --git a/docs/features/constraint-bodies/README.md b/docs/features/constraint-bodies/README.md index d161327..98a9f7f 100644 --- a/docs/features/constraint-bodies/README.md +++ b/docs/features/constraint-bodies/README.md @@ -622,7 +622,14 @@ That is the honest bar and I have not quietly widened it: an `ItemKind::Verbatim` body made *all* of these work before this round, so a file with a comment in one of them is a real regression for constraint bodies — it is just not a regression I can fix without editing machinery -this lane does not own. Filed as request 3 below. QA's separately-filed +this lane does not own. Filed as request 3 below. + +> **Amended 2026-09-02 (`comment-slots`).** Request 3 is closed: all forty are +> fixed, and the fuzzer this section describes — which measured the problem +> but was never committed — is now **in the tree** as +> `a_comment_in_every_constraint_gap_still_formats`, at **zero failing**. Its +> fifteen fixtures are re-derived from the table above rather than restored +> byte for byte, which is why it counts 395 inter-token gaps and not 358. QA's separately-filed `foreach (arr[/*c*/ i])` is the third row of that table. **What the fix looks like.** Fourteen named comment fields (the table in diff --git a/docs/features/covergroup-bodies/README.md b/docs/features/covergroup-bodies/README.md index 2daadfb..c2b280e 100644 --- a/docs/features/covergroup-bodies/README.md +++ b/docs/features/covergroup-bodies/README.md @@ -139,16 +139,18 @@ exhaustive gap fuzzer — this time from day one rather than after a rework. **Requests filed, not acted on:** -1. **The 52 gaps the fuzzer still fails are `docs/topo.md` §2.9-22's**, the - parser-wide comment-slot round round 1 filed. Every one of them is in - shared name, declaration or expression machinery — the `class`/`module` - header, `parse_tf_ports`, `parse_label`, `parse_sens_list`, - `parse_value_range`, member expressions, `take_member_prefix` — and every - one fails identically **outside** a covergroup. That classification is not - a claim in prose: `the_gaps_the_fuzzer_still_fails_fail_outside_a_covergroup_too` - in `tests/verification.rs` runs the equivalent non-covergroup source for - each shape and asserts it fails too, so if §2.9-22 is ever done, both tests - move in the same commit. +1. ~~**The 52 gaps the fuzzer still fails are `docs/topo.md` §2.9-22's**~~ — + **closed 2026-09-02 by `docs/features/comment-slots/README.md`.** Every one + of them was in shared name, declaration or expression machinery (the + `class`/`module` header, `parse_tf_ports`, `parse_label`, + `parse_sens_list`, `parse_value_range`, member expressions, + `take_member_prefix`) and every one failed identically outside a + covergroup, which + `the_gaps_the_fuzzer_still_fails_fail_outside_a_covergroup_too` asserted + rather than claimed. All eighteen shapes now keep their comment, so that + test is **deleted** and `a_comment_in_every_covergroup_gap_still_formats` + asserts **329 gaps, 0 failing** — both in the same commit, as this entry + promised. 2. **Files edited outside the stated ownership list**: none, except one new `#[ignore]`d probe, `crates/vlog_parser/tests/census.rs`, which is what produces the sweep numbers in the work log (`CENSUS= cargo test -p @@ -482,6 +484,12 @@ machinery, and the classification is asserted rather than asserted-in-prose: equivalent non-covergroup source for each of the eighteen shapes and requires it to fail too. All 18 do. +> **Amended 2026-09-02 (`comment-slots`).** All 52 are fixed and the +> classification test is deleted; the count below is history. The fuzzer now +> reads `assert_no_failing_gaps("covergroup", COVERGROUP_FIXTURES, 329)` — the +> same 329 gaps, none of them failing — and shares that helper with three +> sibling fuzzers (fragment, constraint, RTL), all at zero. + | shape | n | owner | |---|---|---| | `class /*c*/ c` / `class c /*c*/ ;` | 18 | the class header | diff --git a/docs/features/escaped-identifiers/README.md b/docs/features/escaped-identifiers/README.md index 9b9f539..eced5b5 100644 --- a/docs/features/escaped-identifiers/README.md +++ b/docs/features/escaped-identifiers/README.md @@ -58,9 +58,10 @@ the same rule (`terminate`/`ends_escaped`, the precedent this followed); the duplication is deliberate — a shared helper would be a cross-crate public API with two callers and no third in sight. -**Requested from `vlog_parser` (open, not done here — parser.rs is not this -lane's file).** `Parser::parse_scoped_name` joins a `pkg::name` chain into one -`String`, which erases the boundary between the segments. When a segment is +**Requested from `vlog_parser` — DELIVERED 2026-09-02 by +`docs/features/comment-slots/README.md` (`docs/topo.md` §2.9-21).** The +request as written: `Parser::parse_scoped_name` joins a `pkg::name` chain into +one `String`, which erases the boundary between the segments. When a segment is escaped (`\my-pkg ::\state-t`) the formatter cannot know a space belonged between them, reprints `\my-pkg::\state-t`, and the safety net rejects the file — an error, never a corruption. The fix is for the AST to keep the @@ -73,6 +74,21 @@ mechanism: it must keep failing until the parser fix lands, at which point the marker has to go) and as `verification::an_escaped_name_in_a_scoped_type_is_rejected_rather_than_corrupted`. +**How it was answered.** Not by making `DataType::name` a `Vec` — that +would ripple through type resolution, the server and the refactorings for a +whitespace question. The join itself keeps the terminator: +`Parser::push_scope_segment` is now the one place a `::` chain is joined +(`parse_scoped_name`, both type-name loops, `parse_instantiation`) and it +writes the space an escaped segment needs, so `\my-pkg ::\state-t` stays three +tokens. `parse_method_name` went further and keeps real segments (`ScopeSeg`), +because it also needed a comment slot on either side of each `::`. The `#SKIP` +marker is **gone** — that case is live, expecting +`\my-pkg ::\state-t \st ;` (the doubled space is what a bare escaped type +name already printed) — and the verification pin is inverted to +`an_escaped_name_in_a_scoped_type_now_keeps_its_terminating_space`, with a new +attack pair `a_space_dropped_inside_a_scoped_escaped_type_is_rejected` +holding the corruption side. + **`verify.rs` untouched** (invariant 4). Nothing about the safety net was widened, softened or normalized; the new tests only add attack pairs it already rejects. @@ -100,8 +116,10 @@ already rejects. - [x] Attack pairs in `tests/verification.rs` (7 tests). - [x] Lexer pin in `lexer.rs` tests. - [x] Corpus proven neutral: no corpus file contains an escaped identifier. -- [ ] (parser lane, not this one) keep `parse_scoped_name`'s segments — see - Handshakes. +- [x] (parser lane, not this one) keep `parse_scoped_name`'s segments — see + Handshakes. **Done 2026-09-02 by `comment-slots`**: the join keeps the + escaped segment's terminating space, the `#SKIP` is a live case and the + verification pin is inverted. ## Work log @@ -321,10 +339,9 @@ ran in parallel per CLAUDE.md — disjoint files, no topo edge). every backslash in the 860 files is inside a string or comment. QA's opentitan set comparison (trunk vs worktree binaries, `--no-cache` after spotting the shared-cache confound) is identical file-for-file. -- Open handshake carried forward, honestly stated: `parse_scoped_name` joins - `\my-pkg ::\state-t` into one string, so such a file is *refused* (exit 2), - never corrupted — pinned by the cases file's `#SKIP` and a verification - test that must keep failing-to-format until the parser keeps the - segments. Filed as `docs/topo.md` §2.9-21. +- ~~Open handshake carried forward~~ — **closed 2026-09-02 by + `comment-slots`.** `parse_scoped_name` joined `\my-pkg ::\state-t` into one + string, so such a file was *refused* (exit 2), never corrupted; the join now + keeps the terminator and the file formats. `docs/topo.md` §2.9-21. - Gates in the worktree: fmt clean, clippy zero warnings, 2 819 passed / 0 failed, corpus 813/820. diff --git a/docs/features/fragment-mode/README.md b/docs/features/fragment-mode/README.md index 4299b1b..e6b7e8d 100644 --- a/docs/features/fragment-mode/README.md +++ b/docs/features/fragment-mode/README.md @@ -189,10 +189,13 @@ Known limits, each pinned by a test so a change to them is deliberate: which is false: a declaration is exactly what a class-body or module-item fragment is made of. - `--lines` over a fragment formats the whole file (see Handshakes). -- The 41 comment slots the fragment gap fuzzer still fails are all in shared - name / expression / statement machinery — `docs/topo.md` §2.9-22 — and - `the_gaps_the_fragment_fuzzer_fails_fail_outside_a_fragment_too` proves each - one fails identically inside an ordinary module or package. +- ~~The 41 comment slots the fragment gap fuzzer still fails~~ — **closed + 2026-09-02 by `docs/features/comment-slots/README.md`.** All 41 were in + shared name / expression / statement machinery (`docs/topo.md` §2.9-22) and + `the_gaps_the_fragment_fuzzer_fails_fail_outside_a_fragment_too` proved it + rather than claiming it. Every one now keeps its comment, so that test is + **deleted** and `a_comment_in_every_fragment_gap_still_formats` asserts + **153 gaps, 0 failing**. ## Work log @@ -339,6 +342,11 @@ control's `#`, a member chain's `.`, and a value range inside a bin. Every one is `docs/topo.md` §2.9-22, which `covergroup-bodies` opened; this round adds no new comment-loss slot of its own. +> **Amended 2026-09-02 (`comment-slots`).** All 41 are fixed and the +> 18-analogue test is deleted; the classification above is history. The fuzzer +> now reads `assert_no_failing_gaps("fragment", FRAGMENT_FIXTURES, 153)` — the +> same 153 gaps, none failing. + **Measurements.** | gate | result | diff --git a/docs/features/overlay-promotion/README.md b/docs/features/overlay-promotion/README.md index 647ae4e..b9ccd49 100644 --- a/docs/features/overlay-promotion/README.md +++ b/docs/features/overlay-promotion/README.md @@ -398,11 +398,16 @@ the interface in the body and says why. window was already bound separately by the time `declare` is called), and the name is by construction one this file *does* bind, so it resolves and never reaches `miss` anyway. Left. - - **Not a call site, worth recording:** a cast's type. `ExprKind::Cast` - binds only its operand (`bind.rs:1169`, `{ expr, .. }`) — the casting type - is dropped and produces no reference at all, before this round and after. - So `state_t'(0)` needs no promotion; it needs a reference first. Out of - scope here, noted for whoever picks it up. + - ~~**Not a call site, worth recording:** a cast's type.~~ **Picked up + 2026-09-02 by `docs/features/comment-slots/README.md` (M11).** The note as + written: `ExprKind::Cast` binds only its operand, so the casting type is + dropped and produces no reference at all — `state_t'(0)` needs no + promotion, it needs a reference first. It has one now. + `Binder::bind_type_expr` mirrors `bind_data_type`'s three shapes: a bare + name is a `Target::Type` (so the promotion this round installed applies to + it), `pkg::t` is `Target::Unit` + `Target::UnitMember`, and a size, a + parenthesized width or a `$bits(...)` call binds its own operands as + ordinary uses. `FACTS_FORMAT` went 13 → 14 with it. - **Consumer audit, the additions.** `bind::Target` is `pub(crate)` and `grep -rn 'Target' crates --include='*.rs'` finds exactly one match site for it, `resolve.rs::resolve` — every other hit is `ExternalTarget` (the overlay diff --git a/docs/features/refactor-rename/README.md b/docs/features/refactor-rename/README.md index b577eb9..9828a55 100644 --- a/docs/features/refactor-rename/README.md +++ b/docs/features/refactor-rename/README.md @@ -506,6 +506,25 @@ implemented: warns per occurrence: "`a` appears in the arguments of the macro invocation `` `BUMP `` at m.sv:4 …". This scan covers files the rename never edits, since a macro call in an untouched file still expands to the old name. +- **A reference the *workspace* could not finish is left alone and warned + about too.** Added 2026-09-02 (`docs/features/comment-slots/README.md`, + `docs/topo.md` §2.9-20). The stray-token scan below cannot see these: it + skips any span the semantic layer recorded a reference for, and a + hierarchical tail like `u_x.sig` *does* carry one — an + `ExternalCandidate { paths: ["unknown_mod::sig"] }` the overlay leaves + `ExternalTarget::StillUnresolved` because nothing in the indexed workspace + answers it. Before this the tail had no reference at all and the stray scan + warned about it; gaining a reference is what silenced it. + `Scope::unresolved_candidate_warnings` asks the `Resolution` first (an + `InheritedCandidate` that missed stores nothing in the overlay, so + `ExternalResolutions::get` answers `None` for it and for a plain local miss + alike), then checks for `StillUnresolved`, and emits one line per + (file, unit): "`sig` at top.sv line(s) 4 could not be resolved — nothing in + the indexed workspace answers `unknown_mod::sig`, so lucisv records no + reference there and it was left unchanged." Like the macro-invocation scan + it runs over **every** file that spells the name, not only the edited ones, + and it costs nothing extra because `collect_occurrences` has already + analysed each of them. - **`` `ifdef`` arms are ordinary tokens to lucisv**, so a resolved reference inside one **is** renamed — in every arm. That is the honest behavior: the tokens are there, they bound to the declaration, and editing only one arm diff --git a/docs/features/type-definition/README.md b/docs/features/type-definition/README.md index 6ba6443..68ba4dd 100644 --- a/docs/features/type-definition/README.md +++ b/docs/features/type-definition/README.md @@ -23,6 +23,19 @@ feature adds is *which offset to ask about*. window from the parse tree and picks the reference the binder left in it. A keyword type (`logic`, `wire`, `int`) is never a reference, which is what makes "a built-in has no type definition" fall out with no special case. +- **The cursor on a *use* the file binds as a type answers for it too**, which + is what `type_name`'s case 2 is and what `type_use_at` implements. Its doc + comment has always named a cast (`state_t'(0)`) as the shape that reaches + it. **Amended 2026-09-02** (`docs/features/comment-slots/README.md`, M11): + that was aspirational until the binder started binding a cast's casting type + — `bind_expr`'s `Cast` arm dropped `ty` outright, so the cursor on + `state_t'` found no reference and case 2 never fired there. `bind_type_expr` + gives the casting type a reference and three tests pin the claim: + `a_cast_reaches_the_typedef_it_names`, + `a_keyword_cast_asks_nothing_of_the_index` (`int'(x)` names nothing, exactly + as a keyword type in a declaration does) and + `a_sized_or_computed_cast_answers_for_its_own_operand` + (`$bits(nib_t)'(x)` — a width, whose operand is an ordinary use). - **One hop, never a chain.** With `typedef state_t alias_t; alias_t x;` the cursor on `x` lands on `alias_t`'s typedef, not on `state_t`'s. That is what every editor's go-to-type-definition does; the user presses the key again for diff --git a/docs/topo.md b/docs/topo.md index 03359c2..a44f66f 100644 --- a/docs/topo.md +++ b/docs/topo.md @@ -360,6 +360,7 @@ recursion-limit, whose edges sit in §2.1). Code edges: | `directive-in-statements ◀──▶ formatter-bug-fixes` | handshake | formatter-bug-fixes round 2 filed the `take_before_open` pending-comment drain; directive-in-statements delivered it as `Parser::take_gap` (comments kept only when `span.start >= last_end()`, `CallComments::dangling` included — the specified fix alone was insufficient). The refusal pin flipped to a formats case on the merged tree, closing the last bucket-2 file (`keymgr_scoreboard.sv`). | | `null-items ──▶ corpus-check / safety-net` | depends | `ItemKind::Empty` (2026-09-01): a lone `;` where an item belongs — IEEE 1800-2017 A.1.4's null item — accepted in every item scope by one branch at the top of `parse_item_kind`. The variant's exhaustive-arm cost was paid in exactly the three places §3.3 predicts (`format.rs`, `bind.rs`, `tests/spans.rs`); every other walker is catch-all and a leaf needs nothing. Formatter layout is decided from `src` spans in `item_seq` (glued to the previous sibling's line when no newline separates them and the `;` carries no docs of its own; else its own line), so the AST carries no layout flag. `verify.rs` untouched, seven attack pairs added; corpus byte-identical at 813/820, measured against the pre-change binary. Ships with the `empty-item` lint (slang's `-Wempty-member`) and its safe fix — see §2.4. | | `escaped-identifiers ──▶ safety-net / spans` | depends | (2026-09-02) An escaped identifier is terminated by whitespace (IEEE 1800 §5.6.1) and the lexer ends the token *before* it, so the formatter — which emitted every name bare or through a `format!` splice — produced `\my-signal;`, one token on re-lex, and the safety net refused the whole file. Fix: one choke point (`format::named`/`name_doc`, predicate `ends_escaped` because parser-joined composites end inside an escaped name) that fifty emission sites go through; the space is unconditional and the printer's trailing trim removes it before a break. `verify.rs` untouched, eight attack pairs; corpus neutral by construction. Ran in a worktree in parallel with member-completion (disjoint files). Open: §2.9-21. | +| `comment-slots ──▶ parser / formatter / safety-net` | depends | (2026-09-02) Hard invariant #3 made true at every inter-token gap: `Parser::bump` queues a comment and `take_meta` hands it to the *next* node, so a gap with no field printed it one node later and `verify.rs` refused the file. ~70 named slots, each printed through `Fmt::slot_comments` (a no-op when empty, which is why 860 corpus + 3 975 opentitan files are byte-identical to v0.30.0), one owner per `;` (`StmtKind::takes_semi()` + a `debug_assert!`), boxed expression slots so `Expr` stays 96 bytes. Four gap fuzzers at zero are the regression gate. `verify.rs` untouched; ten attack pairs. Also carried H5 (`nav::definition` macro branch sharing hover's `macro_name`/`narrowed_to_the_include_graph`), M11 (`bind_type_expr`: a cast's type binds as a type, `FACTS_FORMAT` 13 → 14) and §2.9-20/21. One flagged edit outside scope: `vlog_linter/src/signals.rs` pattern `..`. Closed §2.9-20/21/22; opened §2.9-23. | | `constraint-bodies ──▶ classes / out-of-class-constraints / dv-statements / safety-net` | depends | (2026-09-02, round 1 of coverage_gaps C1) `ItemKind::Constraint(ConstraintDecl)` with a structured `ConstraintSet` (`Expr{soft}`, `Implication`, `If`, `Foreach`, `SolveBefore`, `Unique`, `DisableSoft`, `Directive`, `Empty`), `ExprKind::Dist`, and `WithConstraint.block` as `ConstraintBody::{Items, Verbatim}`. The parser takes a `Rewind` snapshot (cursor, **both pending-comment buckets**, depth, links, `open_conds`, diagnostics length), attempts the structured body, and on any error restores it and re-runs v0.26.0's verbatim capture character for character — so an unknown shape *is* the old behavior, not an approximation (pinned on text, slice and `col`). **No keywords reserved**: `soft`/`dist`/`solve`/`before` are matched by text like `restrict`, so `token.rs`, `pairs.rs`, the editor grammar and `tests/grammar.rs` are untouched and `logic before;` keeps working; `:=`/`:/` stay two tokens with a span-adjacency check (a `:/` token would swallow `:/* c */`). Canonical layout: one item per line, `}` at the header column, dist weights as a braced list; a `with` block keeps the source's one-line-or-not shape. `verify.rs` untouched; the constraint attack pairs re-derived plus new ones. Exhaustive arms paid in `format.rs`, `bind.rs`, `tests/spans.rs`; `visit.rs` gets an explicit no-op arm (no items/statements inside). **QA rework**: comments after the round's own text-matched words were dropped; the dev answered with an exhaustive gap fuzzer (a `/*C*/` in every inter-token gap of 15 fixtures, 358 gaps, format + idempotency demanded) and 14 named comment fields plus `ConstraintItemKind::takes_semi()` (one owner of the `;`) and `Parser::gap_before` (the closer-side twin of `take_before_open`); 96 regressions vs v0.26.0 became 40, all in shared machinery outside this lane — §2.9-22. Opentitan: 1 993 of 2 009 bodies structured (fallbacks: 10 macro-item bodies, 6 non-LRM shapes), failure set unchanged, per-file tolerant diagnostics identical, 48 DV files idempotent with comment streams byte-identical. | | `covergroup-bodies ──▶ constraint-bodies / classes / safety-net` | depends | (2026-09-02, round 2 of coverage_gaps C1) `ItemKind::Covergroup(Box)` with `CoverItemKind::{Coverpoint, Cross, Option, Directive, Empty}`, `BinDecl { wildcard, kind, name, array, spec: BinSpec::{Values, Transitions, Default, DefaultSequence, Select}, with_expr, iff }`, `SelectExpr` for `binsof … intersect … && !binsof`, one `CoverageEvent` enum. Same `Rewind` fallback as constraints — v0.27.0's flat scan re-run character for character on any failure — and no keywords reserved (`coverpoint`, `bins`, `cross`, `binsof`, `intersect`, `wildcard`, `ignore_bins`, `illegal_bins`, `option`, `type_option` by text). **Two guards in shared expression machinery, the round's one risk**: `at_postfix_segment` refuses `[` followed by `*`/`->`/`=` (no index can start with those — it is what lets `1'b1[*5]` be a transition repeat), and a `no_with` flag while a bin spec operand is read (so the bin's own `with (…)` filter is not eaten as an array-method iterator argument); `(`-disambiguation is by position, the LRM's own rule. `plain_expr_list` → `plain_list` and `constraint_parens` → `guard_parens`, shared with `iff`/`with`. `verify.rs` untouched, twelve attack pairs. The gap fuzzer was built in from day one (329 gaps, 52 fail, all §2.9-22 shared machinery — *asserted* by running each shape outside a covergroup). Opentitan: 544 of 544 covergroups structured, 87/87 DV covergroup files idempotent, failure set and per-file diagnostics identical. `on_type.rs` keeps `covergroup` OPAQUE by argument. | | `fragment-mode ──▶ error-recovery / define-table / lexer-cleanup / covergroup-bodies` | depends | (2026-09-02, coverage_gaps H4 corrected) Class-body and module-item `.svh` fragments already parsed — the file-scope item loop *is* the class-item loop; the three shapes that did not (statement lists, enum-member lists, cover-item lists) become `SourceFile::fragment: Option` (`items` empty iff `fragment` is `Some`). Detection is a whole-file rule, not an error-message match: the FIRST STRUCTURAL item failed (directives, macro items and null items are legal in every body and do not count; a tolerant `Ok` that recorded a diagnostic counts as failed — the `if … else` generate-vs-statement parity bug), the file does not open with a design-unit keyword, and a shape consumes the file to EOF, tried narrowest-first (cover items → enum members → statements: the wider grammars mis-read the narrower). Each shape re-lexes a fresh token stream — `Rewind` deliberately does not restore the tokens' comment buckets, right for verbatim captures and fatal here. Shared loops lifted (`parse_enum_members`, `parse_cover_items`); formatter prints a fragment at indent 0 through existing printers; binder gives statements a file `Block` scope and enum variants file scope; **no census change** (a fragment's variants are not exported — `pkg::CUSTOM_1` must not resolve to a name that does not exist), FACTS stays 12. Separately, the lexer continues a `` `define `` whose formal-argument `(` touches the name and is still open at end of line, no backslash needed until the list closes — `cip_base_vseq__tl_errors.svh`'s real blocker. Corpus 813 → 814/820; opentitan 12 → 10, exactly the two predicted files. | @@ -551,9 +552,10 @@ update the filing README(s) and this file. | 17 | Inline aggregate as a parameter-override *argument* (`m #(.T(struct packed { logic a; })) u ();`) is rejected in expression position; M4's `instantiation_plan` drops such a `parameter type` default rather than emit unparseable text | refactor-instantiate (gap 1; its gap 2 was delivered by ansi-first-port) | vlog_parser | | 18 | *(substrate delivered 2026-09-02: `FileFacts::words` includes the identifier-shaped words inside macro invocations and directives — rename's lost warnings can now be answered from it; the wiring into `macro_use_warnings` is what remains)* A macro-invocation census in `FileFacts`: per-file macro names plus identifier-shaped words in their arguments. Rename's index-bounded fan-out currently preserves every edit/refusal but can lose informational macro-argument warnings in files that have no other relationship to the renamed name; the same table would serve the port refactorings' identical scan. This changes the record shape and therefore requires a `FACTS_FORMAT` bump. | refactor-rename (performance-wave residue, accepted and filed) | vlog_semantic | | 19 | An execute-command spelling of the instantiation skeleton (plain-text `render` through the same `plan_for`), for clients without `textDocument/inlineCompletion` — since the 2026-08-30 names-only popup, such a client (Neovim's built-in LSP, today) has no path to the full skeleton at all. Filed at lead review after correcting the dev's assumption that a `lucisv/instantiate` command already existed (it never did). | inline-instantiation (lead) | lucisv_server | -| 20 | Rename loses its heads-up for an **unresolvable member/hierarchical tail** spelling the renamed name (`unknown_mod u_x (); … u_x.sig` when `unknown_mod` is indexed nowhere): before class-member-access the tail had no reference and `rename.rs::stray_reason` warned "a hierarchical or member tail, which lucisv does not resolve"; since round 2 it carries an `ExternalCandidate` the workspace cannot answer, which the engine neither edits (correct) nor mentions. Wanted: a warning for candidate references that spell the old name and stayed unresolved through the overlay — one message per file. Pinned as a premise by `a_hierarchical_tail_that_cannot_resolve_is_left_alone_and_named_as_such`. Same class as item 18. | class-member-access round 2 (lead) | vlog_refactor (`rename.rs`) | -| 21 | `Parser::parse_scoped_name` joins a `pkg::name` chain into one `String`, erasing the segment boundary, so an escaped segment (`\my-pkg ::\state-t` as a type, an instantiated module or a `bind` target) is reprinted without its terminating space and **refused by the safety net** — an error, never a corruption. Wanted: the AST keeps the segments (as `parse_method_name` already does for `FunctionDecl::scope`). Pinned by `escaped_identifiers.cases`'s one `#SKIP` and `verification::an_escaped_name_in_a_scoped_type_is_rejected_rather_than_corrupted`, both of which must keep failing-to-format until delivered | escaped-identifiers | vlog_parser | -| 22 | **Comment slots in shared expression/name machinery** drop the comment and the safety net refuses the file: `q[/*c*/ i]` (index expressions), `x inside {[/*c*/ 0:3]}` and `n /*c*/ inside {` (`inside` / `parse_value_range`), `pkg/*c*/ ::cls::name` (`parse_method_name` chains), `foreach (q[/*c*/ i])` (`parse_foreach_target`), `static /*c*/ constraint` / `pure /*c*/ static function` (`take_member_prefix`). Found by constraint-bodies' exhaustive gap fuzzer (358 gaps; these 40 fail identically on v0.26.0 in the same constructs outside a constraint). Inside a constraint they are regressions relative to the verbatim era — but no opentitan file hits one (sweep unchanged). Wanted: a parser-wide round giving each slot a `Meta`/comments field, then re-running the fuzzer to zero. | constraint-bodies (dev + QA) | vlog_parser | +| ~~20~~ | ~~Rename loses its heads-up for an **unresolvable member/hierarchical tail** spelling the renamed name (`unknown_mod u_x (); … u_x.sig` when `unknown_mod` is indexed nowhere): before class-member-access the tail had no reference and `rename.rs::stray_reason` warned "a hierarchical or member tail, which lucisv does not resolve"; since round 2 it carries an `ExternalCandidate` the workspace cannot answer, which the engine neither edits (correct) nor mentions. Wanted: a warning for candidate references that spell the old name and stayed unresolved through the overlay — one message per file. Pinned as a premise by `a_hierarchical_tail_that_cannot_resolve_is_left_alone_and_named_as_such`. Same class as item 18.~~ — **delivered 2026-09-02 by comment-slots**: `Scope::unresolved_candidate_warnings` — a reference that stayed `ExternalTarget::StillUnresolved` through the overlay (or an `InheritedCandidate` that missed) is reported one line per (file, unit), run over every file that spells the name. The premise pin is inverted. Surfaced item 23 in the process | class-member-access round 2 (lead) | ~~vlog_refactor (`rename.rs`)~~ done | +| ~~21~~ | ~~`Parser::parse_scoped_name` joins a `pkg::name` chain into one `String`, erasing the segment boundary, so an escaped segment (`\my-pkg ::\state-t` as a type, an instantiated module or a `bind` target) is reprinted without its terminating space and **refused by the safety net** — an error, never a corruption. Wanted: the AST keeps the segments (as `parse_method_name` already does for `FunctionDecl::scope`). Pinned by `escaped_identifiers.cases`'s one `#SKIP` and `verification::an_escaped_name_in_a_scoped_type_is_rejected_rather_than_corrupted`, both of which must keep failing-to-format until delivered~~ — **delivered 2026-09-02 by comment-slots**: `Parser::push_scope_segment` is the one join for every `::` chain and writes the escaped segment's terminator; `parse_method_name` keeps real segments (`ScopeSeg`, one comment slot per `::`). The `#SKIP` is a live case and the verification pin is inverted, with a new pair asserting the tightened spelling is still refused | escaped-identifiers | ~~vlog_parser~~ done | +| ~~22~~ | ~~**Comment slots in shared expression/name machinery** drop the comment and the safety net refuses the file: `q[/*c*/ i]` (index expressions), `x inside {[/*c*/ 0:3]}` and `n /*c*/ inside {` (`inside` / `parse_value_range`), `pkg/*c*/ ::cls::name` (`parse_method_name` chains), `foreach (q[/*c*/ i])` (`parse_foreach_target`), `static /*c*/ constraint` / `pure /*c*/ static function` (`take_member_prefix`). Found by constraint-bodies' exhaustive gap fuzzer (358 gaps; these 40 fail identically on v0.26.0 in the same constructs outside a constraint). Inside a constraint they are regressions relative to the verbatim era — but no opentitan file hits one (sweep unchanged). Wanted: a parser-wide round giving each slot a `Meta`/comments field, then re-running the fuzzer to zero.~~ — **delivered 2026-09-02 by comment-slots**: ~70 named comment fields across `ExprKind`/`Stmt`/declarations/headers/labels (`SegmentComments`, `BinaryComments`, `CastComments`, `LabelComments`, `Stmt::before_semi` + `StmtKind::takes_semi()`), three duplicated grammars folded into `parse_postfix_segment` / `parse_value_range`, and four gap fuzzers at zero — covergroup 329, fragment 153, constraint 395 (committed at last), RTL 352 (new). Corpus (860 files) and opentitan (3 975 files) byte-identical to v0.30.0. Deliberately left: `if`/`case` in-paren comments still recovered print-side by `header_parens` (only `after_kw` got a slot) — a real slot there would change existing layout | constraint-bodies (dev + QA) | ~~vlog_parser~~ done | +| 23 | A **cross-file instance-member tail does not resolve for rename**: with `module sub` in `sub.sv` and `assign w = u_x.sig;` in `top.sv`, renaming `sub`'s `wire sig` edits `sub.sv` only — the same shape in one file resolves and is edited (`a_hierarchical_tail_that_resolves_is_renamed_with_its_declaration`). Since comment-slots the rename *says so* (item 20's warning); the edit itself is the gap. Modules export ports and parameters only (the class-member-access round 2 ruling), so an internal net is exactly what the cross-file hop refuses — the fix is either an export rule for nets named through an instance or a rename-time in-file fallback resolution of the tail. | comment-slots (dev, surfaced by the §2.9-20 control test) | vlog_semantic / vlog_refactor | --- diff --git a/editors/vscode/CHANGELOG.md b/editors/vscode/CHANGELOG.md index 5b09eed..ee23684 100644 --- a/editors/vscode/CHANGELOG.md +++ b/editors/vscode/CHANGELOG.md @@ -5,6 +5,24 @@ for you. The extension and its bundled language server share one version number; the full engineering notes live in the [project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md). +## 0.31.0 — 2026-09-02 + +- **Comments survive everywhere.** A comment written between two tokens + the formatter had no place for — inside `q[/*c*/ i]`, after `if`, before + a `;`, in a function header, a port list, a label, a qualifier run like + `pure /*c*/ static`, and about seventy more spots — used to make the + whole file unformattable (exit 2, nothing written). Every such gap now + keeps its comment in place. Files without comments in those spots + format byte-for-byte as before. +- Escaped names inside scoped names (`\my-pkg ::\state-t`) format. +- **Go to definition on a macro use** jumps to its `` `define``, in this + file or across the workspace (narrowed by the include graph). +- A cast's type (`state_t'(0)`, `pkg::t'(x)`) counts as a reference: + find-all-references, go-to-type-definition and rename see it. +- Rename names the `u_x.sig` uses it could not resolve instead of + skipping them silently. +- The index store format changed; it rebuilds once after updating. + ## 0.30.0 — 2026-09-02 - **The semantic lints are on**: `unused-signal`, `undriven-net` and diff --git a/editors/vscode/README.md b/editors/vscode/README.md index b10c729..95154e9 100644 --- a/editors/vscode/README.md +++ b/editors/vscode/README.md @@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view, then open a Verilog or SystemVerilog file. There is no separate server or CLI setup. -The current release is **0.30.0**. Its platform packages include both +The current release is **0.31.0**. Its platform packages include both `lucisv-server` and the `lucisv` command-line tool: | Package target | Machines | @@ -326,6 +326,14 @@ Every nesting color is a proper VS Code theme color: } ``` +## Release 0.31.0 highlights + +Version 0.31.0 makes "comments are never dropped" true at every gap of +the grammar — about seventy places where a comment used to leave a file +unformattable now keep it exactly where it was written, with no change +to any file that had none — and adds go-to-definition on macro uses, +casts as references, and rename warnings for the uses it cannot resolve. + ## Release 0.30.0 highlights Version 0.30.0 turns the semantic lints on by default — `unused-signal`, diff --git a/editors/vscode/package.json b/editors/vscode/package.json index d881e26..3e1aa47 100644 --- a/editors/vscode/package.json +++ b/editors/vscode/package.json @@ -2,7 +2,7 @@ "name": "lucisv", "displayName": "lucisv — Verilog/SystemVerilog", "description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.", - "version": "0.30.0", + "version": "0.31.0", "publisher": "guoliangchen", "author": "Guoliang Chen", "license": "MIT",