diff --git a/TODO.md b/TODO.md index 1ab38ac..421fa4c 100644 --- a/TODO.md +++ b/TODO.md @@ -710,8 +710,8 @@ section only tracks the milestones. - [x] **M14 `macro-expansion`** — single-step macro expansion on hover (the define-table README's promised follow-up); version 0.5.0 with a CHANGELOG entry covering M7–M14. -- [ ] Backlog (extract module, inline, ~~`.*` expansion~~, ANSI conversion, - organize imports, …) — triaged in the umbrella README after M5. +- [ ] Backlog (extract module, inline, ~~`.*` expansion~~, ~~ANSI + conversion~~, organize imports, …) — triaged in the umbrella README after M5. **`.*` expansion shipped 2026-09-05 (§50, `docs/features/expand-wildcard/README.md`)**: the wildcard written out as the named connections it stands for, per IEEE 1800 §23.3.2.4, with a code @@ -719,6 +719,17 @@ section only tracks the milestones. this backlog: **a `.*` written in a `bind` directive**, which binds in the target's scope rather than the one it is written in — elaboration, not lexical lookup, and 57 of OpenTitan's 66 wildcard sites. + **Non-ANSI → ANSI conversion shipped 2026-09-05 (§51, + `docs/features/ansi-conversion/README.md`)**: a Verilog-2001 header rewritten + the modern way, each port declaration merged with the net or variable + declaration that completes it per IEEE 1800 §23.2.2.2, with a code action and + `lucisv.convertToAnsi`. It leaves two things behind, added to this backlog: + **an `interface`'s non-ANSI header**, which needs the `modport`s that name + the same ports read first; and **an attribute instance on an absorbed + declaration** (`(* keep *) input a;`), which the conversion refuses rather + than moves — where a `(* ... *)` belongs in an ANSI port list, and whether + the same one may be split across the ports a multi-name declaration + declares, is a design question the merge rule does not answer. ## 9. LSP 3.18 protocol audit (2026-08-26) @@ -5051,10 +5062,92 @@ parses" verifier is the safety net; this is the whole-header version. non-ANSI modules under `hw/vendor` and ten conversions into scratch copies. -- [ ] 51.1 `convert_to_ansi` engine + refusals -- [ ] 51.2 code action (lazy) + command -- [ ] docs: feature README; README/site rows (lead applies); §8 line +- [x] 51.1 `convert_to_ansi` engine + refusals — `ports/ansi.rs` (the planner) + plus `ports/merge.rs` (IEEE 1800 §23.2.2.2), 23 refusals, each a sentence +- [x] 51.2 code action (lazy) + command — the fourth `port_actions` offer, so + both offer paths get it; `lucisv.convertToAnsi` is the fifth command +- [x] docs: feature README; README/site rows (lead applies); §8 line annotated -- [ ] Gates (guarded); byte-identity vs 0.45.0; the corpus conversion census -- [ ] QA: every §23.2.2.2 merge rule attacked; comments; refusals; the - corpus census re-derived; opentitan scratch conversions +- [x] Gates (guarded); byte-identity vs 0.45.0; the corpus conversion census + — **zero non-ANSI headers in corpus/ and in all of OpenTitan**, so the + acceptance material is real ANSI headers made non-ANSI and converted + back: 5 in the shipped suite, 290 verified under `hw/ip` +- [x] QA: every §23.2.2.2 merge rule attacked; comments; refusals; the + corpus census re-derived; opentitan scratch conversions — verdict + REWORK, two findings in `docs/features/ansi-conversion/README.md`'s + QA log (V-1: `comments_kept` forgives a duplicated *untouched* + comment, no attack test; V-2: an attribute on an absorbed + declaration is silently dropped) + +## 52. Organize imports (planned 2026-09-05) — the third §8 refactoring + +One lane after 0.46.0, §36's protocol. Feature README: +`docs/features/organize-imports/README.md`. Ships in 0.47.0 with §53. + +`import pkg::*;` / `import pkg::item;` items accumulate at the top of a +module, package, class or compilation unit. "Organize" does what Pylance's +does: remove the imports nothing uses, merge exact duplicates, and sort the +contiguous run at the scope's top — package name, then item, `*` first +within one package — keeping every comment. The same computation is a +lint rule, `unused-import` (Style, default off; safe fix = the removal), +so the editor squiggles what the action would delete. + +- **What "used" means (the whole risk).** An import `p::*` in scope S is + used when some reference in S or a scope nested in S resolves to a + member of `p` *through that import* — i.e. the name is not declared + locally between the reference and S, and `p` exports it (same-file + package: the binder's own tables; cross-file: the index's member table + for `p`, including §48's re-exports). `p::x` is used when `x` is + referenced that way. A qualified use `p::y` does NOT use the import. + **Refuse to judge — never remove — when `p` is unknown to the index + (not indexed, or in an unindexed scope), when `p` is declared twice, + when S or any nested scope contains a macro call or a conditional + directive (a name may live in text lucisv did not read), when S is a + class with a base class outside the file (an inherited member could be + the use), or when the file has a parse diagnostic.** The verifier's + resolution check is the second net: after the edit every reference in + the file must resolve to what it resolved to before (that is what the + ports engine's `verify_splice` already asserts — reuse it). +- **Engine** (`vlog_refactor`, new `imports.rs` + `imports/` if it grows): + `organize_imports(files, file, offset) -> Result` + for the scope at the cursor (the innermost module/package/class/unit), + and `unused_imports(files, file) -> Vec<(TextRange, reason)>` for the + rule. Edits: deletions of whole `import` items (with their line) and + one replacement for the sorted run; an import that carries a comment + is never deleted (refuse with a sentence: "delete the comment first") + and is sorted with its comment attached (the `pieces` rule of §51's + verifier). Exact duplicates keep the first. +- **Rule** `unused-import` in `vlog_linter` (Style, default off; option + none), reading the same engine function through the project-facts + oracle the semantic rules use (`ctx.mentioned_elsewhere`-style — + whatever gives the index's member table; if the linter cannot reach it + in single-file mode, the rule is silent there, as `unused-signal` is). + Safe fix: delete the item. Docs row + toggle regenerated. +- **Server:** code action `lucisv: organize imports (removes N, sorts M)` + on a cursor in an import run or the scope header (lazy per §37.1), + `source.organizeImports` kind so editors' organize-on-save wires it; + command `lucisv.organizeImports [uri, position]`. +- Tests: engine — used/unused for `*` and item forms, same-file and + cross-file packages, a re-export chain (§48), a name shadowed locally + (import unused), a nested class using the outer scope's import (used), + duplicates, sort order with mixed `*`/items, comments on imports (kept, + moved with their line, deletion refused), every refusal; the verifier's + resolution check catches a wrong removal (an attack pair: remove an + import a reference needs → must be refused); idempotency; corpus census + over every scope with ≥ 2 imports: organize in a scratch copy, result + parses/formats/converges, resolution counts unchanged, counts of + removed/sorted/refused reported. Rule — true positives, near-misses, + the census over the corpus with counts. Server — offer/resolve, the + `source.organizeImports` kind honoured on `codeAction` with `only`, + the command; opentitan read-only: UVM env packages (`hw/ip/*/dv/env/*_pkg.sv`) + organized into scratch copies, counts, and every "unused" claim + checked by grep for the package's members in the file. + +- [ ] 52.1 engine: used/unused, sort, dedup, refusals +- [ ] 52.2 `unused-import` rule + safe fix + toggle +- [ ] 52.3 code action (`source.organizeImports`, lazy) + command +- [ ] docs; §8 line annotated; README/site rows (lead) +- [ ] Gates (guarded); byte-identity vs 0.46.0; corpus census +- [ ] QA: every "unused" claim attacked (shadowing, nested scopes, + re-exports, macros, directives, unknown packages); the verifier + attack pair; opentitan UVM packages diff --git a/crates/lucisv_server/src/ports.rs b/crates/lucisv_server/src/ports.rs index 109c64a..4ef4c08 100644 --- a/crates/lucisv_server/src/ports.rs +++ b/crates/lucisv_server/src/ports.rs @@ -1,5 +1,5 @@ -//! The port refactorings on the wire: `textDocument/codeAction` for the three -//! that need no typing, and `workspace/executeCommand` for all four. +//! The port refactorings on the wire: `textDocument/codeAction` for the four +//! that need no typing, and `workspace/executeCommand` for all five. //! //! Protocol only. Every edit is computed by `vlog_refactor` over the same file //! set the workspace index was built from; this module turns the result into a @@ -9,9 +9,9 @@ //! **Why commands as well as code actions.** Adding a port needs a //! declaration typed by the user, and a code action carries no input — so //! `lucisv.addPort` is the API a UI calls once it has asked. `lucisv.removePort`, -//! `lucisv.propagatePorts` and `lucisv.expandWildcard` take a position and -//! exist for the same reason a Vim user has no lightbulb: a command works -//! everywhere a keybinding does. +//! `lucisv.propagatePorts`, `lucisv.expandWildcard` and `lucisv.convertToAnsi` +//! take a position and exist for the same reason a Vim user has no lightbulb: +//! a command works everywhere a keybinding does. //! See `docs/features/refactor-ports/README.md`. //! //! **Two shapes of code action.** A client that can resolve is *offered* @@ -51,6 +51,8 @@ pub const REMOVE_PORT: &str = "lucisv.removePort"; pub const PROPAGATE_PORTS: &str = "lucisv.propagatePorts"; /// Write out the `.*` at a position: `[uri, position]`. pub const EXPAND_WILDCARD: &str = "lucisv.expandWildcard"; +/// Rewrite the non-ANSI header at a position ANSI-style: `[uri, position]`. +pub const CONVERT_TO_ANSI: &str = "lucisv.convertToAnsi"; /// Every command this server executes. pub fn commands() -> Vec { @@ -59,6 +61,7 @@ pub fn commands() -> Vec { REMOVE_PORT.to_string(), PROPAGATE_PORTS.to_string(), EXPAND_WILDCARD.to_string(), + CONVERT_TO_ANSI.to_string(), ] } @@ -284,7 +287,7 @@ fn declared_twice(ws: &Workspace, name: &str) -> bool { ws.index().units(name).iter().filter(|def| def.kind.is_instantiable()).count() > 1 } -/// Run one of the four commands, or say why it cannot run. +/// Run one of the five commands, or say why it cannot run. /// /// The answer is the `WorkspaceEdit` to apply plus the engine's warnings. How /// it reaches the editor is `server.rs`'s business: it is pushed as a @@ -336,6 +339,12 @@ pub fn execute( let sources = sources_at(ws, &path, offset); vlog_refactor::expand_wildcard(&sources, &path, offset)? } + CONVERT_TO_ANSI => { + let (_, path) = target(ws, arguments.first())?; + let offset = position_argument(ws, arguments, CONVERT_TO_ANSI)?; + let sources = sources_at(ws, &path, offset); + vlog_refactor::convert_to_ansi(&sources, &path, offset)? + } // The instantiation skeleton is not a port refactoring and computes // its own `WorkspaceEdit`, but `server.rs` routes every non-lens // `workspace/executeCommand` through here — this is the one place an @@ -1426,8 +1435,77 @@ mod tests { assert_eq!(edits_for(resolved.edit.as_ref().expect("edit"), &uri)[0].new_text, ".rst(rst)"); } + // ------------------------------------------------------------------ + // the non-ANSI → ANSI conversion (TODO §51) + // ------------------------------------------------------------------ + + /// A workspace whose `legacy.sv` writes a Verilog-2001 header. + const LEGACY: &str = + "module legacy (\n a,\n b\n);\n input a;\n output [7:0] b;\n reg [7:0] b;\nendmodule\n"; + + fn legacy(tree: &Tree) -> (Workspace, Uri) { + let path = tree.write("legacy.sv", LEGACY); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&path).expect("uri"); + ws.set_document(uri.clone(), LEGACY.to_string()); + (ws, uri) + } + + #[test] + fn convert_to_ansi_takes_a_position() { + let tree = Tree::new("ansi"); + let (ws, uri) = legacy(&tree); + let arguments = vec![ + serde_json::to_value(&uri).expect("uri"), + // The module's own name — inside the header, and nowhere near a + // port declaration. + serde_json::to_value(Position { line: 0, character: 8 }).expect("position"), + ]; + // Two insertions — the ANSI prefixes — and three deletions: `input a;`, + // `output [7:0] b;` and the `reg [7:0] b;` that completed it. + let (edit, warnings) = execute(&ws, CONVERT_TO_ANSI, &arguments).expect("converts"); + assert!(warnings.is_empty(), "{warnings:?}"); + let edits = edits_for(&edit, &uri); + let written: Vec<&str> = edits.iter().map(|e| e.new_text.as_str()).collect(); + assert_eq!(written, vec!["input ", "output reg [7:0] ", "", "", ""], "{edits:#?}"); + } + + #[test] + fn convert_to_ansi_refuses_an_ansi_header() { + let tree = Tree::new("ansi_none"); + let (ws, top_uri, _) = opened(&tree); + let arguments = vec![ + serde_json::to_value(&top_uri).expect("uri"), + serde_json::to_value(Position { line: 0, character: 8 }).expect("position"), + ]; + let message = execute(&ws, CONVERT_TO_ANSI, &arguments).expect_err("nothing to convert"); + assert!(message.contains("declares no ports"), "{message}"); + } + + #[test] + fn the_ansi_action_is_offered_lazily_and_resolves_to_the_eager_edit() { + let tree = Tree::new("ansi_action"); + let (ws, uri) = legacy(&tree); + // The cursor on the module's name: in the header, on no port. + let offset = LEGACY.find("legacy (").expect("the name") as u32; + + let lazy = offered(&ws, &uri, offset); + assert_eq!(menu(&lazy), menu(&code_actions(&ws, &uri, offset))); + assert_eq!(menu(&lazy)[0].0, "lucisv: convert ports to ANSI (2 ports)"); + assert!(only(&lazy).edit.is_none(), "an offer carries no edit"); + + let resolved = resolve(&ws, only(&lazy).clone()).expect("edit"); + assert_eq!(resolved.title, "lucisv: convert ports to ANSI (2 ports)"); + assert_eq!(resolved.edit, only(&code_actions(&ws, &uri, offset)).edit); + assert_eq!(edits_for(resolved.edit.as_ref().expect("edit"), &uri)[0].new_text, "input "); + } + #[test] fn the_command_list_is_what_the_server_advertises() { - assert_eq!(commands(), vec![ADD_PORT, REMOVE_PORT, PROPAGATE_PORTS, EXPAND_WILDCARD]); + assert_eq!( + commands(), + vec![ADD_PORT, REMOVE_PORT, PROPAGATE_PORTS, EXPAND_WILDCARD, CONVERT_TO_ANSI] + ); } } diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index ceb1047..898f9e9 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -1592,6 +1592,112 @@ fn a_client_that_resolves_is_offered_the_port_action_without_its_edit() { const WILDCARD_TOP: &str = "module top;\n logic clk, rst;\n sub u_sub (.clk(clk), .*);\nendmodule\n"; +const LEGACY_TOP: &str = + "module legacy (\n a,\n b\n);\n input a;\n output [7:0] b;\n reg [7:0] b;\nendmodule\n"; + +#[test] +fn the_ansi_conversion_is_offered_resolved_and_commanded_over_the_wire() { + // TODO §51 on the wire: the action is offered with the cursor on the + // module's own name — anywhere in a non-ANSI header — with the port count + // in its title, the resolve hands back the insertions and deletions, and + // the command answers with the same edit for a client with no lightbulb. + let dir = temp_dir("ansi"); + let legacy = dir.join("legacy.sv"); + std::fs::write(&legacy, LEGACY_TOP).expect("write"); + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", legacy.display()); + + let boot = |id: u32| { + [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":{id},"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"codeAction":{{"resolveSupport":{{"properties":["edit"]}}}}}}}}}}}}"# + )), + 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(LEGACY_TOP).expect("json") + )), + ] + .concat() + }; + + let session = [ + boot(1), + // The cursor on the module's name, which is in the header and on no port. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":0,"character":9}},"end":{{"line":0,"character":9}}}},"context":{{"diagnostics":[]}}}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":3,"method":"workspace/executeCommand","params":{{"command":"lucisv.convertToAnsi","arguments":["{uri}",{{"line":0,"character":9}}]}}}}"# + )), + // ...and a position inside the body is refused with the engine's sentence. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":4,"method":"workspace/executeCommand","params":{{"command":"lucisv.convertToAnsi","arguments":["{uri}",{{"line":7,"character":9}}]}}}}"# + )), + 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); + + // 1. The command is advertised beside the other four. + let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response"); + let commands = initialize["result"]["capabilities"]["executeCommandProvider"]["commands"] + .as_array() + .expect("the commands are listed"); + assert!(commands.iter().any(|c| c == "lucisv.convertToAnsi"), "{commands:#?}"); + + // 2. The offer names the conversion and its port count, with no edit. + let actions = messages.iter().find(|m| m["id"] == 2).expect("codeAction response"); + let offered = actions["result"].as_array().expect("an array of actions"); + let action = offered + .iter() + .find(|a| a["kind"] == "refactor.rewrite.lucisv.ports") + .unwrap_or_else(|| panic!("no port action in {offered:#?}")); + assert_eq!(action["title"], "lucisv: convert ports to ANSI (2 ports)"); + assert!(action["edit"].is_null(), "an offer carries no edit: {action:#?}"); + + // 3. The command answers with the two insertions and the three deletions: + // `b`'s port declaration and the `reg` that completed it both go. + let converted = messages.iter().find(|m| m["id"] == 3).expect("executeCommand response"); + let edits = converted["result"]["changes"][&uri].as_array().expect("edits"); + let written: Vec<&str> = edits.iter().map(|e| e["newText"].as_str().unwrap_or("?")).collect(); + assert_eq!(written, vec!["input ", "output reg [7:0] ", "", "", ""], "{edits:#?}"); + assert_eq!(edits[0]["range"]["start"]["line"], 1, "the first port's own line"); + assert_eq!(edits[0]["range"]["start"], edits[0]["range"]["end"], "an insertion, not a rewrite"); + + // 4. ...and a refusal is `RequestFailed` with the engine's own sentence. + let refused = messages.iter().find(|m| m["id"] == 4).expect("refusal response"); + assert_eq!(refused["error"]["code"], -32803, "LSP's RequestFailed"); + assert!( + refused["error"]["message"] + .as_str() + .is_some_and(|m| m.contains("no module declaration at this position")), + "{refused:#?}" + ); + + // 5. Handing the offered action back resolves it to that same edit. + let resolve = [ + boot(1), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":3,"method":"codeAction/resolve","params":{}}}"#, + serde_json::to_string(action).expect("json") + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + let messages = talk(&resolve); + let resolved = messages.iter().find(|m| m["id"] == 3).expect("resolve response"); + let edits = resolved["result"]["edit"]["changes"][&uri] + .as_array() + .unwrap_or_else(|| panic!("no edit in {resolved:#?}")); + assert_eq!(edits[0]["newText"], "input "); + assert_eq!(resolved["result"]["title"], "lucisv: convert ports to ANSI (2 ports)"); + + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn the_wildcard_expansion_is_offered_resolved_and_commanded_over_the_wire() { // TODO §50 on the wire: the action is offered lazily at the `.*` with the diff --git a/crates/vlog_refactor/src/check.rs b/crates/vlog_refactor/src/check.rs index 9babfe3..d5ed3a1 100644 --- a/crates/vlog_refactor/src/check.rs +++ b/crates/vlog_refactor/src/check.rs @@ -10,9 +10,9 @@ //! [`verify`] is the *rename* contract: the token stream may not change shape //! at all. [`verify_splice`] is the same contract for a refactoring that //! deliberately writes or deletes text (the port ones): the token stream may -//! change only by exactly the pieces the edits spell, no comment may be -//! deleted, no file may gain a parse error, and every name *outside* the -//! edited ranges must still resolve to exactly what it did. +//! change only by exactly the pieces the edits spell, no comment and no +//! attribute may be deleted, no file may gain a parse error, and every name +//! *outside* the edited ranges must still resolve to exactly what it did. //! //! Nothing here touches `vlog_formatter` or its `verify.rs`: this is the same //! contract, kept separately, so the formatter's safety net does not widen. @@ -120,9 +120,11 @@ pub(crate) fn verify( /// in at the edits' positions and nothing else moved. An edit that landed /// in a string, split a token or wrote a `,` into a line comment cannot /// survive it. -/// 2. **Comments are never dropped** (CLAUDE.md invariant 3): no deletion may -/// cover a comment. A port or connection with a comment on it is refused, -/// not silently un-commented. +/// 2. **Comments and attributes are never dropped** (CLAUDE.md invariant 3): +/// every comment and every `(* ... *)` the file had it still has, and no +/// more. A deletion may cover one only when the edits write it back — which +/// is how the ANSI conversion moves a body declaration's comment onto the +/// port it becomes; see [`never_dropped`]. /// 3. **The file still parses**: a touched file may not gain a parse /// diagnostic it did not have. /// 4. **Resolution identity outside the edits.** Every declaration and every @@ -400,22 +402,6 @@ fn pieces_match( display(path) )); }; - // Invariant 3, checked here rather than trusted to the planner: a deletion - // that covers a comment would delete it from both sides of this comparison - // and pass, so it is refused outright. - for (span, piece) in &old { - let deleted = edits.iter().any(|e| !e.range.is_empty() && overlaps(e.range, *span)); - if deleted && matches!(piece, Piece::Comment(_)) { - return Err(format!( - "{what} would delete {} in {}; comments are never dropped, so nothing was edited.", - piece.describe(), - display(path) - )); - } - } - - let mut expected: Vec = Vec::new(); - let mut next = 0usize; let mut written: Vec> = Vec::new(); for edit in edits { let Some(pieces) = pieces(&edit.new_text) else { @@ -423,6 +409,10 @@ fn pieces_match( }; written.push(pieces); } + never_dropped(&old, &new, edits, &written, path, what)?; + + let mut expected: Vec = Vec::new(); + let mut next = 0usize; for (span, piece) in old { while let (Some(edit), Some(pieces)) = (edits.get(next), written.get(next)) { if edit.range.start > span.start { @@ -478,6 +468,145 @@ fn pieces_match( Ok(()) } +/// The pieces an edit may never lose, gain or duplicate: a **comment** +/// (CLAUDE.md invariant 3) and an **attribute instance** `(* ... *)`. +/// +/// The piece comparison above cannot see either on its own. A piece inside a +/// deleted range disappears from *both* sides of it — from `expected`, because +/// pieces inside an edit are skipped, and from `actual`, because it is really +/// gone — so a dropped comment, or a dropped `(* keep *)`, would pass +/// unnoticed. An attribute is a code token rather than trivia, but a deletion +/// hides it exactly the way it hides a comment, and losing one changes what a +/// synthesizer does; so both are counted here, by exact text. +/// +/// Three equations, over every text that appears on any side. `had` and `has` +/// are the file's counts before and after, `gone` counts the old pieces a +/// non-empty edit range covers, and `wrote` counts the pieces lexed out of the +/// edits' own inserted text. +/// +/// 1. **`has >= had`** — nothing is ever lost. This is the whole of invariant +/// 3 and the only half the rule this replaced had. +/// 2. **`wrote <= gone`**, unless the text is one a refactoring +/// [`generated`] itself — a piece is written back *where it was deleted*, +/// and nowhere else. This refuses a planner that takes the comment on +/// `input a, b;` and writes it onto *both* ports (one really did, on the +/// way — see the work log), and equally one that duplicates the text of a +/// comment it never touched. +/// 3. **`has == had - gone + wrote`** — the applied text says exactly what the +/// edits say. An application that grew a second copy of a comment the edits +/// write once is masked corruption the first two equations would forgive. +/// +/// Where each piece now *sits* is the piece comparison's business, not this +/// one's; between them a moved comment is verified as exactly as a stationary +/// one. +fn never_dropped( + old: &[(TextRange, Piece)], + new: &[(TextRange, Piece)], + edits: &[TextEdit], + written: &[Vec<(TextRange, Piece)>], + path: &Path, + what: &str, +) -> Result<(), String> { + let covered = |span: TextRange| { + edits.iter().any(|edit| !edit.range.is_empty() && overlaps(edit.range, span)) + }; + let before = tally(old.iter().map(|(_, piece)| piece)); + let after = tally(new.iter().map(|(_, piece)| piece)); + let deleted = tally(old.iter().filter(|(span, _)| covered(*span)).map(|(_, piece)| piece)); + let writes = tally(written.iter().flatten().map(|(_, piece)| piece)); + + let mut texts: Vec<&Kept> = before.keys().chain(after.keys()).chain(writes.keys()).collect(); + texts.sort_unstable(); + texts.dedup(); + let count = |tally: &Tally, key: &Kept| tally.get(key).copied().unwrap_or(0); + + // Three passes rather than three tests in one pass, so that the sentence + // the user reads is the worst thing wrong with the edit rather than + // whichever text sorted first. + if let Some(Kept(noun, text)) = + texts.iter().find(|key| count(&after, key) < count(&before, key)) + { + return Err(format!( + "{what} would delete the {noun} `{text}` in {}; {noun}s are never dropped, so nothing was edited.", + display(path) + )); + } + if let Some(key) = + texts.iter().find(|key| count(&writes, key) > count(&deleted, key) && !generated(&key.1)) + { + let Kept(noun, text) = key; + let (gone, wrote) = (count(&deleted, key), count(&writes, key)); + let deletes = match gone { + 0 => "without deleting it".to_string(), + gone => format!("where it deletes it {}", times(gone)), + }; + return Err(format!( + "{what} would write the {noun} `{text}` {} in {} {deletes}; {noun}s are never duplicated, so nothing was edited.", + times(wrote), + display(path) + )); + } + // `deleted` is a subset of `before`, so the subtraction cannot go under — + // saturating rather than plain because an arithmetic panic is not a + // refusal, and this is a safety net. + let accounted = + |key: &Kept| count(&before, key).saturating_sub(count(&deleted, key)) + count(&writes, key); + if let Some(key) = texts.iter().find(|key| count(&after, key) != accounted(key)) { + let Kept(noun, text) = key; + return Err(format!( + "{what} would leave the {noun} `{text}` in {} {}, where its edits account for it {}; nothing was edited.", + display(path), + times(count(&after, key)), + times(accounted(key)) + )); + } + Ok(()) +} + +/// One never-dropped piece, keyed for counting: the noun a refusal calls it by +/// (`comment` or `attribute`) and its exact text. +#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)] +struct Kept(&'static str, String); + +type Tally = HashMap; + +/// How many of each never-dropped piece a stream of pieces holds. Every other +/// piece is a code token the comparison above already pins position by +/// position, so it is not counted here. +fn tally<'p>(pieces: impl Iterator) -> Tally { + let mut out = Tally::new(); + for piece in pieces { + let key = match piece { + Piece::Comment(text) => Kept("comment", text.clone()), + Piece::Code(TokenKind::Attribute, text) => Kept("attribute", text.clone()), + Piece::Code(..) => continue, + }; + *out.entry(key).or_insert(0) += 1; + } + out +} + +/// The comments a refactoring writes itself rather than moves, which it may +/// therefore write however many times it needs and even where the file already +/// has one. `add_port` and `propagate_ports` both leave +/// `/* TODO: connect */` at a connection they cannot name a signal for, and a +/// module gains its ports one at a time — so the second addition to a file +/// finds the first one's placeholder already sitting there. Everything else a +/// refactoring writes has to be a piece it is deleting somewhere else. +fn generated(text: &str) -> bool { + text == "/* TODO: connect */" +} + +/// A count, in prose, so a refusal reads like a sentence. +fn times(n: usize) -> String { + match n { + 0 => "never".to_string(), + 1 => "once".to_string(), + 2 => "twice".to_string(), + n => format!("{n} times"), + } +} + /// Whether two byte ranges share a byte. Empty ranges — the insertions — /// overlap nothing: they replace no text, so they delete nothing. fn overlaps(a: TextRange, b: TextRange) -> bool { @@ -777,7 +906,8 @@ mod tests { #[test] fn a_splice_that_also_dropped_a_comment_is_rejected() { let corrupted = apply(PORTS, &add_edits()).replace(" // a", ""); - assert!(splice_attack(&corrupted).is_err(), "comments are never dropped"); + let message = splice_attack(&corrupted).expect_err("a dropped comment is a refusal"); + assert!(message.contains("comments are never dropped"), "{message}"); } #[test] @@ -822,6 +952,267 @@ mod tests { assert!(splice_attack(&corrupted).is_err(), "an unlexable result is a failure, not output"); } + // ------------------------------------------------------------------ + // the moved-comment rule, and the attacks on it (CLAUDE.md invariant 4) + // ------------------------------------------------------------------ + // + // 2026-09-05: `comments_kept` replaced "no deletion may cover a comment", + // so that `ports::ansi` can move a body declaration's comment onto the + // ANSI port that declaration becomes. Every attack below is a crafted + // (input, corrupted output) pair the relaxation could plausibly forgive. + + /// A Verilog-2001 header whose two declarations each carry a comment — + /// the shape the ANSI conversion has to move a comment out of. + const MOVED: &str = + "module m (\n a,\n b\n);\n input a; // the note\n output b; // the note\nendmodule\n"; + + /// The edits `convert_to_ansi` really produces for `MOVED`. + fn move_edits() -> Vec { + let files = vec![(PathBuf::from("/rtl/m.sv"), MOVED.to_string())]; + let at = MOVED.find("module m").expect("header") as u32; + let edit = crate::convert_to_ansi(&files, Path::new("/rtl/m.sv"), at) + .expect("the conversion the attacks corrupt"); + edit.edits.into_iter().next().expect("one file").1 + } + + fn move_attack(corrupted: &str) -> Result<(), String> { + pieces_match( + MOVED, + corrupted, + &move_edits(), + Path::new("/rtl/m.sv"), + "converting `m`'s ports to ANSI", + ) + } + + #[test] + fn the_moved_comments_the_engine_actually_writes_verify() { + let honest = apply(MOVED, &move_edits()); + assert_eq!(move_attack(&honest), Ok(()), "the real output must pass"); + assert_eq!(honest.matches("// the note").count(), 2, "both comments survive: {honest}"); + assert!(honest.contains("input a, // the note"), "{honest}"); + } + + #[test] + fn a_move_that_kept_only_one_of_two_identical_comments_is_rejected() { + // The exact hole the character budget exists for: one of the two + // `// the note`s is dropped, and a search for its text still finds + // the other one. + let corrupted = apply(MOVED, &move_edits()).replacen(" // the note", "", 1); + let message = move_attack(&corrupted).expect_err("one comment short is a refusal"); + assert!(message.contains("comments are never dropped"), "{message}"); + } + + #[test] + fn a_move_that_dropped_a_comment_and_invented_another_is_rejected() { + // Same character count, different text: the budget alone would + // forgive this one, and the per-comment search does not. + let corrupted = apply(MOVED, &move_edits()).replacen("// the note", "// the NOTE", 1); + let message = move_attack(&corrupted).expect_err("a rewritten comment is a refusal"); + assert!(message.contains("comments are never dropped"), "{message}"); + } + + #[test] + fn a_move_that_shortened_a_comment_is_rejected() { + let corrupted = apply(MOVED, &move_edits()).replacen("// the note", "// the", 1); + let message = move_attack(&corrupted).expect_err("a truncated comment is a refusal"); + assert!(message.contains("comments are never dropped"), "{message}"); + } + + #[test] + fn a_move_that_left_the_comment_where_it_was_is_rejected() { + // The deletion really deleted, but the comment was written back into + // the *body* rather than into the header: every comment is still + // there, and the piece order is not what the edits promised. + let honest = apply(MOVED, &move_edits()); + let corrupted = honest + .replace("input a, // the note", "input a,") + .replace("endmodule", "// the note\nendmodule"); + // `never_dropped` passes this one: every count is equal on both sides + // (the comment really was deleted and really was written back once). + // The *piece comparison* is the guard, because where a comment lands + // is bound to where the edits put it — which is also the answer to + // "a comment deleted here and written back somewhere unrelated". + let message = move_attack(&corrupted).expect_err("a misplaced comment is a refusal"); + assert!(message.contains("where the comment `// the note` belongs"), "{message}"); + } + + #[test] + fn a_move_that_wrote_the_comment_onto_two_ports_is_rejected() { + // The bug this half of the rule was added for, reproduced as the edits + // that caused it: one declaration declares two ports, and its comment + // is written onto *both*. Nothing is dropped, and the piece comparison + // cannot object — it checks the edits against themselves, and the + // duplicate is in the edits. Only counting the file's comments sees it. + const SHARED: &str = "module m (\n a,\n b\n);\n input a, b; // both\nendmodule\n"; + let at = |needle: &str| SHARED.find(needle).expect(needle) as u32; + let (a, b) = (at("\n a,") + 3, at("\n b\n") + 3); + let edits = vec![ + TextEdit { range: TextRange::empty(a), new_text: "input ".into() }, + TextEdit { range: TextRange::empty(a + 2), new_text: " // both".into() }, + TextEdit { range: TextRange::empty(b), new_text: "input ".into() }, + TextEdit { range: TextRange::empty(b + 1), new_text: " // both".into() }, + TextEdit { + range: TextRange::new(at(" input a,"), at("endmodule")), + new_text: String::new(), + }, + ]; + let corrupted = apply(SHARED, &edits); + assert_eq!(corrupted.matches("// both").count(), 2, "the attack really doubles it"); + let message = pieces_match(SHARED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit") + .expect_err("a doubled comment is a refusal"); + assert!(message.contains("would write the comment"), "{message}"); + } + + #[test] + fn a_deletion_that_swallows_a_comment_nothing_writes_back_is_still_refused() { + // The old rule's own case, restated: no edit writes the comment, so + // the relaxation must not reach it. + let start = MOVED.find("input a;").expect("a") as u32; + let end = MOVED.find("\n output").expect("output") as u32; + let edits = vec![TextEdit { range: TextRange::new(start, end), new_text: String::new() }]; + let corrupted = apply(MOVED, &edits); + let message = pieces_match(MOVED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit") + .expect_err("a deleted comment nothing writes back is a refusal"); + assert!(message.contains("comments are never dropped"), "{message}"); + } + + // ------------------------------------------------------------------ + // 2026-09-05 rework: the duplication half, the equation, and attributes + // ------------------------------------------------------------------ + + #[test] + fn an_insertion_that_duplicates_an_untouched_comment_is_rejected() { + // QA's V-1 pair. Nothing deletes — or even overlaps — the body's own + // `// shared`, and two pure insertions each write it again. Every + // count only grows, so "before is a subset of after" forgives it, and + // the piece comparison cannot object because the duplicates are in the + // edits. Only `wrote <= gone` sees it. + const SHARED: &str = + "module m (\n a,\n b\n);\n input a; // shared\n output b;\nendmodule\n"; + let at = |needle: &str| SHARED.find(needle).expect(needle) as u32; + let (a, b) = (at("\n a,") + 4, at("\n b\n") + 4); + let edits = vec![ + TextEdit { range: TextRange::empty(a), new_text: " // shared".into() }, + TextEdit { range: TextRange::empty(b), new_text: " // shared".into() }, + ]; + let corrupted = apply(SHARED, &edits); + assert_eq!(corrupted.matches("// shared").count(), 3, "the attack really triples it"); + let message = pieces_match(SHARED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit") + .expect_err("a duplicated comment is a refusal"); + assert!(message.contains("comments are never duplicated"), "{message}"); + } + + #[test] + fn a_generated_placeholder_may_be_written_where_the_file_already_has_one() { + // The whitelist, and the whole of it. `add_port` and + // `propagate_ports` write `/* TODO: connect */` themselves, and a + // module gains its ports one at a time — so the second addition to a + // file finds the first one's placeholder already sitting there and + // writes another. `wrote > gone` with nothing deleted, and legitimate. + let source = "module top;\n sub u1 (.a(/* TODO: connect */));\nendmodule\n"; + let at = source.find("))").expect("list") as u32 + 1; + let edits = vec![TextEdit { + range: TextRange::empty(at), + new_text: ", .b(/* TODO: connect */)".into(), + }]; + let spliced = apply(source, &edits); + assert_eq!(spliced.matches("TODO").count(), 2, "{spliced}"); + let outcome = + pieces_match(source, &spliced, &edits, Path::new("/rtl/top.sv"), "adding port `b`"); + assert_eq!(outcome, Ok(()), "a generated placeholder is the engine's own text"); + } + + #[test] + fn an_application_that_grew_a_copy_the_edits_do_not_write_is_rejected() { + // Masked corruption of the third kind: the edits are honest — they + // delete both `// the note`s and write both back — and the *applied* + // text carries a third. Neither "nothing is lost" nor "written back + // where it was deleted" can see that; only the equation can. + let corrupted = apply(MOVED, &move_edits()).replace("endmodule", "// the note\nendmodule"); + let message = move_attack(&corrupted).expect_err("an invented copy is a refusal"); + assert!(message.contains("where its edits account for it"), "{message}"); + } + + #[test] + fn a_comment_written_back_inside_a_string_or_another_comment_is_rejected() { + // A `//` is only a comment where the lexer says it is. Written back + // inside a string literal, or swallowed into the comment next to it, + // the text is present in the file and absent from its pieces — which + // is exactly the substring search this rule refuses to be. + let honest = apply(MOVED, &move_edits()); + let in_string = honest + .replacen(" // the note", "", 1) + .replace("endmodule", " initial $display(\"// the note\");\nendmodule"); + let message = move_attack(&in_string).expect_err("a string is not a comment"); + assert!(message.contains("comments are never dropped"), "{message}"); + + let nested = honest + .replacen(" // the note", "", 1) + .replace("// the note", "// the note // the note"); + let message = move_attack(&nested).expect_err("one comment is not two"); + assert!(message.contains("comments are never dropped"), "{message}"); + } + + /// A body declaration carrying an attribute instance. `Item.span` covers + /// the `(* keep *)`, so a deletion hides it from *both* sides of the piece + /// comparison exactly the way it hides a comment — QA's finding V-2. + const ATTRIBUTED: &str = "module m (\n a\n);\n (* keep *) input a;\nendmodule\n"; + + /// The edits an absorbing conversion of `ATTRIBUTED` makes: `input ` (plus + /// whatever `written` says) before the header name, and the whole body + /// declaration gone. + fn attribute_edits(written: &str) -> Vec { + let at = |needle: &str| ATTRIBUTED.find(needle).expect(needle) as u32; + vec![ + TextEdit { range: TextRange::empty(at("\n a\n") + 3), new_text: written.into() }, + TextEdit { + range: TextRange::new(at(" (* keep *)"), at("endmodule")), + new_text: String::new(), + }, + ] + } + + fn attribute_attack(edits: &[TextEdit]) -> Result<(), String> { + let corrupted = apply(ATTRIBUTED, edits); + pieces_match( + ATTRIBUTED, + &corrupted, + edits, + Path::new("/rtl/m.sv"), + "converting `m`'s ports to ANSI", + ) + } + + #[test] + fn a_deletion_that_swallows_an_attribute_is_rejected() { + // The planner refuses this one first (`ports::ansi::attributes_clear`, + // pinned in `tests/ansi.rs`); this is the verifier saying so a second + // time, from the edits alone, for whatever writes them next. + let message = attribute_attack(&attribute_edits("input ")) + .expect_err("a dropped attribute is a refusal"); + assert!(message.contains("attributes are never dropped"), "{message}"); + assert!(message.contains("`(* keep *)`"), "{message}"); + } + + #[test] + fn an_edit_that_moves_an_attribute_verifies() { + // What the refusal above is protecting: an edit that really does carry + // the attribute over is not what this rule is for. + let edits = attribute_edits("(* keep *) input "); + assert_eq!(attribute_attack(&edits), Ok(()), "a moved attribute is a kept attribute"); + assert!(apply(ATTRIBUTED, &edits).contains("(* keep *) input a")); + } + + #[test] + fn an_edit_that_rewrote_an_attribute_is_rejected() { + // `(* keep *)` and `(* keep=1 *)` are not the same instruction to a + // synthesizer, and an attribute is matched by exact text. + let message = attribute_attack(&attribute_edits("(* keep=1 *) input ")) + .expect_err("a rewritten attribute is a refusal"); + assert!(message.contains("attributes are never dropped"), "{message}"); + } + #[test] fn a_splice_that_captures_a_name_outside_the_edit_is_rejected() { // The resolution half: the module already has a net called `cfg`, and diff --git a/crates/vlog_refactor/src/lib.rs b/crates/vlog_refactor/src/lib.rs index 710fec5..6cfb2b5 100644 --- a/crates/vlog_refactor/src/lib.rs +++ b/crates/vlog_refactor/src/lib.rs @@ -41,9 +41,9 @@ pub use instantiate::{ PlanPort, Site, }; pub use ports::{ - add_port, enclosing_module, expand_wildcard, is_sites_phrase, may_have_port_action, - port_action_modules, port_actions, propagate_ports, remove_port, sites_phrase, ModuleRef, - PortAction, + add_port, convert_to_ansi, enclosing_module, expand_wildcard, is_sites_phrase, + may_have_port_action, port_action_modules, port_actions, propagate_ports, remove_port, + sites_phrase, ModuleRef, PortAction, }; pub use rename::{ contains_word, prepare_rename, prepare_rename_here, rename, rename_name_at, RenameTarget, diff --git a/crates/vlog_refactor/src/ports/add.rs b/crates/vlog_refactor/src/ports/add.rs index 93ae95a..4cc0ce9 100644 --- a/crates/vlog_refactor/src/ports/add.rs +++ b/crates/vlog_refactor/src/ports/add.rs @@ -229,19 +229,19 @@ pub(super) fn element_spans(ports: &[DeclaredPort]) -> Vec { /// One compiler directive written inside a port list or a module body, and /// where it is written. -struct Directive { - text: String, - span: TextRange, +pub(super) struct Directive { + pub(super) text: String, + pub(super) span: TextRange, } /// What a directive does to the conditional nesting depth. -enum Nesting { +pub(super) enum Nesting { Open, Close, Neither, } -fn nesting_of(directive: &str) -> Nesting { +pub(super) fn nesting_of(directive: &str) -> Nesting { let word = directive.split_whitespace().next().unwrap_or_default(); match word { "`ifdef" | "`ifndef" => Nesting::Open, @@ -264,7 +264,7 @@ fn list_directives(module: &Module) -> Vec { /// The directives written among a module's items — where a non-ANSI port /// declaration goes. A macro *item* (`` `ASSERT_INIT(...) ``) is not collected: /// it is a call, not a directive, and cannot open a conditional region. -fn body_directives(module: &Module) -> Vec { +pub(super) fn body_directives(module: &Module) -> Vec { module .items .iter() diff --git a/crates/vlog_refactor/src/ports/ansi.rs b/crates/vlog_refactor/src/ports/ansi.rs new file mode 100644 index 0000000..225a40b --- /dev/null +++ b/crates/vlog_refactor/src/ports/ansi.rs @@ -0,0 +1,488 @@ +//! Converting a Verilog-2001 header to an ANSI one: `module m (a, b);` with +//! `input a; output [7:0] b; reg [7:0] b;` in the body becomes +//! `module m (input a, output reg [7:0] b);` with the body declarations gone. +//! +//! **The edit is insertions, never a rewrite of the list.** Each header name +//! keeps the bytes it already occupies; what an ANSI port adds is written +//! *around* it — the direction, type and packed dimensions just before the +//! name, an unpacked dimension just after it. Two things follow from that, and +//! both are the reason it is done this way: +//! +//! * The header's own layout, commas and comments are not touched at all, so a +//! one-per-line list stays one per line and a comment written beside a port +//! name stays beside it. +//! * `Shift::map` maps the port's name span onto exactly the bytes the name +//! occupies afterwards, so `check::verify_splice`'s resolution check — which +//! requires every reference outside the edits to resolve to the *same* +//! declaration, at the same place — passes. A conversion that replaced the +//! element wholesale would move the declaration the body's references point +//! at, and the verifier would rightly refuse the whole refactoring. +//! +//! The merge itself is `merge.rs` (IEEE 1800 §23.2.2.2). This file locates the +//! module, refuses everything lucisv will not convert, decides where each +//! absorbed declaration's comments go, and writes the edits. + +use std::path::Path; + +use vlog_parser::ast::{ + GenBlock, GenElse, Item, ItemKind, ListElem, Module, NonAnsiPort, PortList, +}; +use vlog_parser::span::TextRange; +use vlog_parser::token::Comment; +use vlog_parser::{parse_source_tolerant, tokenize, LineIndex, ParseDiagnostic}; + +use crate::rename::{display, Scope}; +use crate::TextEdit; + +use super::add::{body_directives, nesting_of, Directive, Nesting}; +use super::find::{find_module, locate_module, module_at, not_in_scope, ModuleSite}; +use super::list::{after_same_line_comments, comma_after, insert, line_indent, whole_line}; +use super::merge::{absorb, Absorbed}; +use super::{shape, ModuleRef, Plan}; + +/// One planned conversion: what to edit, and what the title will promise. +pub(super) struct Conversion { + pub(super) site: ModuleSite, + pub(super) plan: Plan, + /// How many ports the header declares — what the code action counts. + pub(super) count: usize, +} + +pub(super) fn plan_convert( + scope: &mut Scope, + file: &Path, + offset: u32, +) -> Result { + let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) }; + let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) }; + let (tree, diagnostics) = parse_source_tolerant(text); + let mut found = None; + module_at(&tree.items, offset, &mut found); + let Some(name) = found else { + return Err("there is no module declaration at this position.".to_string()); + }; + let Some((module, _)) = find_module(&tree, &name) else { + return Err(format!("lucisv can no longer find the declaration of `{name}`.")); + }; + let ports = header(module)?; + unparsed(file, &diagnostics)?; + let names = header_names(module, &ports)?; + if !module.port_directives.is_empty() { + return Err(format!( + "`{name}`'s port list carries compiler directives, so which ports it declares depends on the configuration; lucisv does not preprocess, so it made no edits." + )); + } + if let Some(hidden) = in_generate(&module.items, &names) { + return Err(format!( + "`{name}` declares `{hidden}` inside a generate region, where lucisv will not read a port's declaration; it made no edits." + )); + } + let site = locate_module(scope, ModuleRef::Name(&name))?; + if site.file != i { + return Err(format!( + "`{name}`'s indexed declaration is in another file than the one under the cursor; lucisv made no edits." + )); + } + + let absorbed = absorb(text, &name, &module.items, &names)?; + attributes_clear(&name, &absorbed)?; + directives_clear(text, file, module, &absorbed)?; + let comments = comments_of(text, file)?; + let mut plan = Plan::default(); + // One declaration may declare several ports (`input a, b;`), and its + // comments belong to the first of them: written onto both they would be + // duplicated, which is as much a corruption as dropping them. + let mut claimed: Vec = Vec::new(); + for (port, absorbed) in ports.iter().zip(&absorbed) { + plan.add(i, port_edits(text, &name, port, absorbed, &comments, &mut claimed)?); + } + plan.add(i, deletions(text, &name, &absorbed, &comments)?); + plan.expected.push((i, shape(text, &name))); + Ok(Conversion { site, plan, count: ports.len() }) +} + +/// The non-ANSI port list this conversion needs, or the sentence saying why +/// there is not one. +fn header(module: &Module) -> Result, String> { + let name = &module.name; + if module.kw == "interface" || module.kw == "program" { + return Err(format!( + "`{name}` is an `{}`, not a module, and lucisv does not convert an {}'s non-ANSI header in this round; it made no edits.", + module.kw, module.kw + )); + } + let ports = match &module.ports { + PortList::NonAnsi(ports) => ports, + PortList::Ansi(_) => { + return Err(format!( + "`{name}`'s header already declares its ports ANSI-style, so there is nothing to convert." + )) + } + PortList::Empty | PortList::None => { + return Err(format!("`{name}` declares no ports, so there is nothing to convert.")) + } + }; + if ports.iter().any(ListElem::is_error) { + return Err(format!( + "`{name}`'s header writes a port expression (IEEE 1800 §23.2.2.1's `.a({{x,y}})` or `{{x,y}}`), which has no ANSI spelling; lucisv made no edits." + )); + } + Ok(ports.iter().filter_map(ListElem::ok).collect()) +} + +/// The header's names in header order, with a repeated one refused: a list +/// that names a port twice is not one lucisv will guess at. +fn header_names(module: &Module, ports: &[&NonAnsiPort]) -> Result, String> { + let mut names: Vec = Vec::new(); + for port in ports { + if names.contains(&port.name) { + return Err(format!( + "`{}`'s header names `{}` twice; lucisv will not guess which port that is.", + module.name, port.name + )); + } + names.push(port.name.clone()); + } + Ok(names) +} + +/// The refusal a file that does not parse earns. Stricter than the verifier's +/// "no *new* diagnostic" rule, and for the same reason the `.*` expansion is: +/// a header lucisv misread is a header whose ports it would declare twice. +fn unparsed(file: &Path, diagnostics: &[ParseDiagnostic]) -> Result<(), String> { + match diagnostics.first() { + None => Ok(()), + Some(problem) => Err(format!( + "{} does not parse ({} at line {}), so lucisv will not convert its ports to ANSI.", + display(file), + problem.message, + problem.line + )), + } +} + +/// A header port declared inside a generate construct is a declaration in +/// another scope, which lucisv will not absorb into the header. +fn in_generate(items: &[Item], names: &[String]) -> Option { + fn walk(items: &[Item], names: &[String], inside: bool, found: &mut Option) { + for item in items { + match &item.kind { + ItemKind::PortDecl(decl) if inside => { + named(decl.declarators.iter().map(|d| &d.name), names, found); + } + ItemKind::DataDecl(decl) if inside => { + named(decl.declarators.iter().map(|d| &d.name), names, found); + } + ItemKind::GenerateRegion { items, .. } => walk(items, names, true, found), + ItemKind::GenBlock(block) => walk(&block.items, names, true, found), + ItemKind::GenFor(gen) => block(&gen.body, names, found), + ItemKind::GenCase(gen) => { + for arm in &gen.items { + block(&arm.body, names, found); + } + } + ItemKind::GenIf(gen) => { + block(&gen.then, names, found); + let mut els = gen.els.as_deref(); + while let Some(next) = els { + match next { + GenElse::If(_, gen) => { + block(&gen.then, names, found); + els = gen.els.as_deref(); + } + GenElse::Block(b) => { + block(b, names, found); + els = None; + } + } + } + } + _ => {} + } + } + } + fn block(b: &GenBlock, names: &[String], found: &mut Option) { + walk(&b.items, names, true, found); + } + fn named<'a>( + declared: impl Iterator, + names: &[String], + found: &mut Option, + ) { + for name in declared { + if found.is_none() && names.contains(name) { + *found = Some(name.clone()); + } + } + } + let mut found = None; + walk(items, names, false, &mut found); + found +} + +/// Refuse a declaration that carries an attribute instance. +/// +/// `Item.span` covers the `(* ... *)` written before it, so the deletion takes +/// the attribute with the declaration and only the *comments* are carried onto +/// the port — a silent loss of something that changes what a synthesizer does. +/// Where an attribute belongs in an ANSI port list is a design question rather +/// than a merge rule, so the conversion refuses instead of guessing, the same +/// way it refuses an initialiser or a qualifier. `check::never_dropped` counts +/// attributes too, so a planner that ever misses one is refused a second time. +fn attributes_clear(module: &str, absorbed: &[Absorbed<'_>]) -> Result<(), String> { + for port in absorbed { + for item in &port.items { + let Some(attr) = item.meta.attrs.first() else { continue }; + return Err(format!( + "`{}` on `{module}`'s declaration of `{}` would be dropped, and lucisv does not decide where an attribute belongs in an ANSI port list; move the attribute onto the port by hand, and it made no edits.", + attr.text.trim(), + port.name + )); + } + } + Ok(()) +} + +/// lucisv does not preprocess, so a declaration it deletes must not be one an +/// `` `ifdef`` arm holds, and no directive may stand between the declarations +/// it deletes: either way the body it leaves behind is one no configuration +/// ever had. +fn directives_clear( + text: &str, + file: &Path, + module: &Module, + absorbed: &[Absorbed<'_>], +) -> Result<(), String> { + let directives = body_directives(module); + if directives.is_empty() { + return Ok(()); + } + let spans: Vec = + absorbed.iter().flat_map(|a| a.items.iter().map(|i| i.span)).collect(); + let (Some(first), Some(last)) = + (spans.iter().map(|span| span.start).min(), spans.iter().map(|span| span.end).max()) + else { + return Ok(()); + }; + let region = format!("`{}`'s body", module.name); + for span in &spans { + depth_zero(&directives, span.start, ®ion)?; + } + match directives.iter().find(|d| d.span.start >= first && d.span.start < last) { + None => Ok(()), + Some(directive) => Err(format!( + "a compiler directive (`{}` at {}:{}) is written among the declarations converting `{}` would delete, so lucisv does not know what the body it leaves behind would say; it made no edits.", + directive.text.trim().lines().next().unwrap_or_default().trim_end(), + display(file), + LineIndex::new(text).line_col(directive.span.start).0, + module.name + )), + } +} + +/// Refuse a declaration that stands inside a conditional arm. +fn depth_zero(directives: &[Directive], at: u32, region: &str) -> Result<(), String> { + let mut depth = 0i32; + for directive in directives.iter().filter(|d| d.span.start < at) { + match nesting_of(&directive.text) { + Nesting::Open => depth += 1, + Nesting::Close => depth -= 1, + Nesting::Neither => {} + } + } + match depth { + 0 => Ok(()), + _ => Err(format!( + "{region} is conditionally compiled, and one of the declarations the conversion would delete stands inside an `ifdef arm; a port declared in one arm does not exist in the other, so lucisv made no edits." + )), + } +} + +/// Every comment in the file, with the bytes it occupies — the same pieces +/// `check::pieces` reads, so a comment this file moves is a comment the +/// verifier can account for. +fn comments_of(text: &str, file: &Path) -> Result, String> { + let Ok(tokens) = tokenize(text) else { + return Err(format!("{} does not lex, so lucisv will not edit it.", display(file))); + }; + let mut out: Vec<(TextRange, String)> = Vec::new(); + let mut push = |comment: &Comment| out.push((comment.span, comment.text.clone())); + for token in &tokens { + token.leading.iter().for_each(&mut push); + if let Some(trailing) = &token.trailing { + push(trailing); + } + } + out.sort_by_key(|(span, _)| (span.start, span.end)); + out.dedup_by_key(|(span, _)| *span); + Ok(out) +} + +/// The comments one absorbed declaration carries, and the bytes a deletion +/// must therefore cover. +#[derive(Default)] +struct Carried { + before: Vec, + after: Vec, +} + +/// What one body item takes with it: its own bytes plus the comments written +/// before and after it, which move onto the ANSI port. +fn carried( + text: &str, + module: &str, + item: &Item, + comments: &[(TextRange, String)], +) -> Result<(TextRange, Carried), String> { + let start = item.meta.leading.first().map_or(item.span.start, |c| c.span.start); + let end = item.meta.trailing.as_ref().map_or(item.span.end, |c| c.span.end); + let mut carried = Carried::default(); + for (span, comment) in + comments.iter().filter(|(span, _)| span.start >= start && span.end <= end) + { + if span.start >= item.span.start && span.end <= item.span.end { + return Err(format!( + "`{module}` writes the comment `{comment}` inside a declaration the conversion would delete, and lucisv will not decide where a comment written inside a declaration goes in an ANSI port; it made no edits." + )); + } + match span.end <= item.span.start { + true => carried.before.push(comment.clone()), + false => carried.after.push(comment.clone()), + } + } + Ok((whole_line(text, TextRange::new(start, end)), carried)) +} + +/// The insertions that turn one header name into an ANSI port declaration. +/// +/// The comments the absorbed declarations carried go in one of two places. +/// The first choice, for a comment written *after* a declaration, is the end +/// of the port's own line — where the source had it, relative to what it +/// describes. That is only free when nothing else is written there and the +/// header wrote no comment of its own beside the port, and there is exactly +/// one of them. Everything else goes on its own line above the port, which +/// always works for a list written one port per line; a list written on one +/// line takes a block comment inline and refuses a `//`. +fn port_edits( + text: &str, + module: &str, + port: &NonAnsiPort, + absorbed: &Absorbed<'_>, + comments: &[(TextRange, String)], + claimed: &mut Vec, +) -> Result, String> { + let mut moved = Carried::default(); + for item in &absorbed.items { + let (_, carried) = carried(text, module, item, comments)?; + // A declaration this port shares with an earlier one has already + // handed its comments over; taking them again would write them twice. + if claimed.contains(&item.span) { + continue; + } + claimed.push(item.span); + moved.before.extend(carried.before); + moved.after.extend(carried.after); + } + let at = tail(text, port); + // Exactly one comment may go beside the port, because two comments landing + // on one line become *one* comment — a `//` runs to the end of the line and + // the lexer merges what follows it into the same trailing comment — and a + // refactoring that joins two comments the source kept apart is one the + // verifier rightly refuses. The rest go above. + let beside = moved.after.len() == 1 + && after_same_line_comments(text, at).at == at + && line_free(text, at); + let mut above = moved.before; + if !beside { + above.extend(moved.after.iter().cloned()); + } + + let mut edits = vec![insert(port.span.start, prefix(text, module, port, absorbed, &above)?)]; + if !absorbed.unpacked.is_empty() { + edits.push(insert(port.span.end, absorbed.unpacked.clone())); + } + if beside { + edits.push(insert(at, format!(" {}", moved.after.join(" ")))); + } + Ok(edits) +} + +/// What is written just before the port's name: the comments its declarations +/// carried, then the declaration itself. +fn prefix( + text: &str, + module: &str, + port: &NonAnsiPort, + absorbed: &Absorbed<'_>, + above: &[String], +) -> Result { + let mut out = String::new(); + match own_line(text, port.span.start) { + Some(indent) => { + for comment in above { + out.push_str(comment); + out.push('\n'); + out.push_str(&indent); + } + } + None => { + for comment in above { + if !inline_safe(comment) { + return Err(format!( + "the comment `{comment}` on `{module}`'s declaration of `{}` would have to move into a port list written on one line, where it would swallow the rest of it; break `{module}`'s port list across lines first, and lucisv made no edits.", + absorbed.name + )); + } + out.push_str(comment); + out.push(' '); + } + } + } + out.push_str(&absorbed.prefix); + Ok(out) +} + +/// Where a port's trailing comment goes: past the `,` that follows the name, +/// or — for the last port — straight after it. +fn tail(text: &str, port: &NonAnsiPort) -> u32 { + comma_after(text, port.span.end).map_or(port.span.end, |comma| comma + 1) +} + +/// The deletions that take the absorbed body declarations away, comments +/// included: each one moved onto its port above. +fn deletions( + text: &str, + module: &str, + absorbed: &[Absorbed<'_>], + comments: &[(TextRange, String)], +) -> Result, String> { + let mut ranges: Vec = Vec::new(); + for item in absorbed.iter().flat_map(|a| a.items.iter()) { + let (range, _) = carried(text, module, item, comments)?; + if !ranges.contains(&range) { + ranges.push(range); + } + } + Ok(ranges.into_iter().map(|range| TextEdit { range, new_text: String::new() }).collect()) +} + +/// The indentation of the line `at` starts, or `None` when something else is +/// written on that line before it. +fn own_line(text: &str, at: u32) -> Option { + let indent = line_indent(text, at); + let start = (at as usize).checked_sub(indent.len())?; + (start == 0 || text.as_bytes().get(start - 1) == Some(&b'\n')).then_some(indent) +} + +/// Whether the rest of the line from `at` is blank — which is what makes room +/// for a `//` comment. +fn line_free(text: &str, at: u32) -> bool { + text.get(at as usize..) + .is_none_or(|rest| rest.split('\n').next().is_none_or(|line| line.trim().is_empty())) +} + +/// Whether a comment can be written in the middle of a line: a block comment +/// that stays on it. +fn inline_safe(comment: &str) -> bool { + comment.starts_with("/*") && !comment.contains('\n') +} diff --git a/crates/vlog_refactor/src/ports/list.rs b/crates/vlog_refactor/src/ports/list.rs index 5f0cd71..3bf2faf 100644 --- a/crates/vlog_refactor/src/ports/list.rs +++ b/crates/vlog_refactor/src/ports/list.rs @@ -174,7 +174,7 @@ pub(super) fn line_indent(text: &str, offset: u32) -> String { } /// The `,` written after `end`, skipping whitespace and comments. -fn comma_after(text: &str, end: u32) -> Option { +pub(super) fn comma_after(text: &str, end: u32) -> Option { let mut at = end as usize; loop { let rest = text.get(at..)?; diff --git a/crates/vlog_refactor/src/ports/merge.rs b/crates/vlog_refactor/src/ports/merge.rs new file mode 100644 index 0000000..d59e892 --- /dev/null +++ b/crates/vlog_refactor/src/ports/merge.rs @@ -0,0 +1,325 @@ +//! IEEE 1800 §23.2.2.2: pairing each name of a non-ANSI header with the body +//! declarations that describe it, and merging the two into the one ANSI port +//! declaration that says the same thing. +//! +//! The LRM's rule in one paragraph. A non-ANSI header names its ports and the +//! body declares them. The *port declaration* (`output [7:0] b;`) always +//! carries the direction; when it also carries a net or a variable type +//! (`output reg [7:0] b;`, `input wire a;`) the port is **completely +//! declared** and declaring it again is an error. When it does not, a separate +//! net or variable declaration of the same name (`reg [7:0] b;`) finishes it, +//! and the two must agree: identical packed ranges, identical unpacked +//! dimensions, one signing. The merge is the union — `output [7:0] b;` plus +//! `reg [7:0] b;` is `output reg [7:0] b`. +//! +//! Everything this module produces is *text*, written in the order the +//! formatter's own ANSI port printer writes it (`vlog_formatter`'s +//! `ansi_port_cells`: direction, net, type, signing, packed dimensions, name, +//! unpacked dimensions), so a converted header formats to itself. + +use vlog_parser::ast::{DataDecl, DataType, Declarator, Dim, Item, ItemKind, PortDecl}; + +/// One header port, once its body declarations have been read and merged. +pub(super) struct Absorbed<'t> { + pub(super) name: String, + /// The body items this port takes with it: its port declaration, and the + /// net or variable declaration that completed it, if there was one. + pub(super) items: Vec<&'t Item>, + /// Everything an ANSI port writes before its name: `output reg [7:0] `. + pub(super) prefix: String, + /// Everything it writes after it: ` [0:3]` for an unpacked dimension. + pub(super) unpacked: String, +} + +/// Where one declarator of one body declaration is written. +struct Site<'t> { + item: &'t Item, + declarator: &'t Declarator, +} + +/// Read a module's body declarations and merge each header name with its own. +/// +/// `names` is the header's port list in header order; the answer is in the +/// same order, which is what makes the converted list the list the source +/// wrote. +pub(super) fn absorb<'t>( + text: &str, + module: &str, + items: &'t [Item], + names: &[String], +) -> Result>, String> { + let Body { ports, vars } = collect(module, items, names)?; + let mut out = Vec::new(); + for name in names { + let port = one( + &ports, + name, + || { + format!( + "`{module}`'s header names `{name}`, but its body declares no direction for it; a port with no declaration is illegal, so lucisv made no edits." + ) + }, + || { + format!( + "`{module}` declares a direction for `{name}` twice; lucisv will not guess which one is the port." + ) + }, + )?; + let var = match vars.iter().filter(|site| site.declarator.name == *name).count() { + 0 => None, + 1 => vars.iter().find(|site| site.declarator.name == *name), + _ => { + return Err(format!( + "`{module}` declares `{name}` twice outside its port declaration; lucisv will not guess which one completes the port." + )) + } + }; + out.push(merged(text, module, name, port, var)?); + } + Ok(out) +} + +/// A module body as the merge reads it: the port declarations that give the +/// directions, and the net/variable declarations that complete them. +struct Body<'t> { + ports: Vec>, + vars: Vec>, +} + +/// Read the body, with the declarations lucisv will not absorb refused. +fn collect<'t>(module: &str, items: &'t [Item], names: &[String]) -> Result, String> { + let mut ports = Vec::new(); + let mut vars = Vec::new(); + for item in items { + match &item.kind { + ItemKind::PortDecl(decl) => { + for declarator in &decl.declarators { + if !names.contains(&declarator.name) { + return Err(format!( + "`{module}` declares a direction for `{}`, which its header does not name; lucisv made no edits.", + declarator.name + )); + } + no_initialiser(module, declarator)?; + ports.push(Site { item, declarator }); + } + } + ItemKind::DataDecl(decl) => { + let mine = decl.declarators.iter().filter(|d| names.contains(&d.name)).count(); + if mine == 0 { + continue; + } + shared(module, decl, mine)?; + for declarator in &decl.declarators { + no_initialiser(module, declarator)?; + vars.push(Site { item, declarator }); + } + } + _ => {} + } + } + Ok(Body { ports, vars }) +} + +/// A declaration that names a header port *and* something else cannot be +/// deleted: the local it also declares would go with it. +fn shared(module: &str, decl: &DataDecl, mine: usize) -> Result<(), String> { + if mine == decl.declarators.len() { + return no_qualifier(module, decl); + } + Err(format!( + "`{module}` declares {} in one declaration, of which only {mine} {} a port; lucisv cannot absorb one without the other, so split the declaration first.", + decl.declarators.iter().map(|d| format!("`{}`", d.name)).collect::>().join(", "), + if mine == 1 { "is" } else { "are" } + )) +} + +/// What lucisv refuses to carry from a variable declaration into a port list: +/// a `var`/`const`/`automatic` qualifier, and a net delay. +fn no_qualifier(module: &str, decl: &DataDecl) -> Result<(), String> { + if let Some(qualifier) = decl.qualifiers.first() { + return Err(format!( + "`{module}` writes `{}` where it completes a port's declaration, and lucisv does not move a qualifier into a port list; it made no edits.", + qualifier.text + )); + } + if decl.delay.is_some() { + return Err(format!( + "`{module}` writes a net delay where it completes a port's declaration, and lucisv does not move a delay into a port list; it made no edits." + )); + } + Ok(()) +} + +fn no_initialiser(module: &str, declarator: &Declarator) -> Result<(), String> { + match declarator.init { + None => Ok(()), + Some(_) => Err(format!( + "`{module}` initialises `{}` where it declares it, and lucisv does not move an initialiser into a port list; it made no edits.", + declarator.name + )), + } +} + +/// The one site declaring `name`, or the sentence for none and for several. +fn one<'a, 't>( + sites: &'a [Site<'t>], + name: &str, + none: impl Fn() -> String, + several: impl Fn() -> String, +) -> Result<&'a Site<'t>, String> { + let mut found = sites.iter().filter(|site| site.declarator.name == name); + let first = found.next().ok_or_else(none)?; + match found.next() { + None => Ok(first), + Some(_) => Err(several()), + } +} + +/// One header name plus its declarations, written out as an ANSI port. +fn merged<'t>( + text: &str, + module: &str, + name: &str, + port: &Site<'t>, + var: Option<&Site<'t>>, +) -> Result, String> { + let ItemKind::PortDecl(decl) = &port.item.kind else { + return Err(format!("lucisv lost track of `{module}`'s declaration of `{name}`.")); + }; + let variable = match var.map(|site| &site.item.kind) { + Some(ItemKind::DataDecl(decl)) => Some(decl), + _ => None, + }; + if variable.is_some() && complete(decl) { + return Err(format!( + "`{module}` gives `{name}` a type in its port declaration and declares it again; IEEE 1800 §23.2.2.2 makes that an error, so lucisv made no edits." + )); + } + plain(module, name, &decl.ty)?; + if let Some(variable) = variable { + plain(module, name, &variable.ty)?; + } + + let net = decl.net.clone().or_else(|| variable.and_then(|v| v.net.clone())); + let ty = pick_name(&decl.ty, variable.map(|v| &v.ty)); + let signing = signing( + module, + name, + decl.ty.signing.clone(), + variable.and_then(|v| v.ty.signing.clone()), + )?; + let var_packed = variable.map_or(&[][..], |v| v.ty.packed.as_slice()); + let packed = dims(text, module, name, "packed range", &decl.ty.packed, var_packed)?; + let unpacked = dims( + text, + module, + name, + "unpacked dimension", + &port.declarator.unpacked, + var.map_or(&[][..], |site| site.declarator.unpacked.as_slice()), + )?; + + let mut prefix = String::new(); + let mut word = |part: &str| { + prefix.push_str(part); + prefix.push(' '); + }; + word(&decl.dir); + for part in [net.as_deref(), ty.as_deref(), signing.as_deref()].into_iter().flatten() { + word(part); + } + if !packed.is_empty() { + word(&packed); + } + + let mut items = vec![port.item]; + if let Some(site) = var { + items.push(site.item); + } + let unpacked = match unpacked.is_empty() { + true => String::new(), + false => format!(" {unpacked}"), + }; + Ok(Absorbed { name: name.to_string(), items, prefix, unpacked }) +} + +/// Whether a port declaration already says what the port *is* — a net type or +/// a data type — which is what makes it complete under §23.2.2.2. +fn complete(decl: &PortDecl) -> bool { + decl.net.is_some() || !decl.ty.name.is_empty() +} + +/// A type lucisv writes into a port list is a name, a signing and packed +/// dimensions and nothing else: an anonymous `enum`/`struct` body, a +/// parameterized `#( ... )` reference or a `virtual` interface type is text +/// lucisv will not move for the user. +fn plain(module: &str, name: &str, ty: &DataType) -> Result<(), String> { + match ty.virt.is_none() && ty.extra.is_none() { + true => Ok(()), + false => Err(format!( + "`{module}` declares `{name}` with a type lucisv does not move into a port list (an anonymous aggregate, a parameterized reference or a virtual interface); it made no edits." + )), + } +} + +/// The type name the merge writes: the port declaration's own, or — when it +/// declared none — the one the variable declaration finished it with. +fn pick_name(port: &DataType, var: Option<&DataType>) -> Option { + let from_var = var.map(|ty| ty.name.clone()).filter(|name| !name.is_empty()); + match port.name.is_empty() { + true => from_var, + false => Some(port.name.clone()), + } +} + +/// The signing the merge writes. Two halves of one declaration must not +/// disagree; `None` on either side is silence, not disagreement. +fn signing( + module: &str, + name: &str, + port: Option, + var: Option, +) -> Result, String> { + match (port, var) { + (Some(a), Some(b)) if a == b => Ok(Some(a)), + (Some(a), Some(b)) => Err(format!( + "`{module}` declares `{name}` `{a}` in its port declaration and `{b}` where it completes it; IEEE 1800 §23.2.2.2 asks the two to agree, so lucisv made no edits." + )), + (Some(a), None) | (None, Some(a)) => Ok(Some(a)), + (None, None) => Ok(None), + } +} + +/// The dimensions the merge writes, as the source spells them. Two lists that +/// are both written must be the same list — that is the LRM's "identical +/// range" — compared with the whitespace taken out, so `[7 : 0]` and `[7:0]` +/// agree. +fn dims( + text: &str, + module: &str, + name: &str, + what: &str, + port: &[Dim], + var: &[Dim], +) -> Result { + let written = |list: &[Dim]| -> String { + list.iter() + .map(|dim| text.get(dim.span.start as usize..dim.span.end as usize).unwrap_or_default()) + .collect() + }; + let (a, b) = (written(port), written(var)); + if a.is_empty() || b.is_empty() { + return Ok(match a.is_empty() { + true => b, + false => a, + }); + } + let tight = |s: &str| s.chars().filter(|c| !c.is_whitespace()).collect::(); + match tight(&a) == tight(&b) { + true => Ok(a), + false => Err(format!( + "`{module}` declares `{name}` with the {what} `{a}` in its port declaration and `{b}` where it completes it; IEEE 1800 §23.2.2.2 asks for identical ones, so lucisv made no edits." + )), + } +} diff --git a/crates/vlog_refactor/src/ports/mod.rs b/crates/vlog_refactor/src/ports/mod.rs index 8cc9db9..614bc78 100644 --- a/crates/vlog_refactor/src/ports/mod.rs +++ b/crates/vlog_refactor/src/ports/mod.rs @@ -22,9 +22,11 @@ //! parenthesis finding they share. mod add; +mod ansi; mod expand; mod find; mod list; +mod merge; mod propagate; mod remove; @@ -32,13 +34,14 @@ pub(crate) use find::{find_module, visible_in}; use std::path::{Path, PathBuf}; -use vlog_parser::ast::{Connections, ItemKind}; +use vlog_parser::ast::{Connections, ItemKind, Module, PortList}; use vlog_parser::parse_source_tolerant; use crate::rename::{display, Scope}; use crate::{check, RefactorEdit, TextEdit}; use add::{parse_port_decl, plan_add}; +use ansi::plan_convert; use expand::plan_expand; use find::{collect_instantiations, declared_ports, locate_module, module_at}; use propagate::plan_propagate; @@ -156,6 +159,36 @@ fn expansion( Ok((edit, expansion.count)) } +/// Rewrite a Verilog-2001 header as an ANSI one: every port the header names +/// gains the direction, type, signing and dimensions its body declarations +/// gave it (IEEE 1800 §23.2.2.2), and those declarations go. +/// +/// The header's own layout, commas and comments are untouched — what an ANSI +/// port adds is inserted around each name — and a comment on an absorbed +/// declaration moves onto the port it described. Nothing outside the module's +/// own file is edited. +pub fn convert_to_ansi( + files: &[(PathBuf, String)], + file: &Path, + offset: u32, +) -> Result { + Ok(conversion(files, file, offset)?.0) +} + +/// The conversion and how many ports it declares — what a code action's title +/// promises. +fn conversion( + files: &[(PathBuf, String)], + file: &Path, + offset: u32, +) -> Result<(RefactorEdit, usize), String> { + let mut scope = Scope::build(files); + let conversion = plan_convert(&mut scope, file, offset)?; + let what = format!("converting `{}`'s ports to ANSI", conversion.site.name); + let edit = finish(&mut scope, conversion.plan, &conversion.site.name, &what)?.0; + Ok((edit, conversion.count)) +} + /// Every port refactoring available at a position, each with its edit already /// computed and verified — which is what lets a code action carry its own /// `WorkspaceEdit` instead of a command the editor has to resolve. @@ -193,6 +226,15 @@ pub fn port_actions(files: &[(PathBuf, String)], file: &Path, offset: u32) -> Ve edit, }); } + if let Ok((edit, count)) = conversion(files, file, offset) { + out.push(PortAction { + title: format!( + "lucisv: convert ports to ANSI ({count} port{})", + if count == 1 { "" } else { "s" } + ), + edit, + }); + } out } @@ -253,10 +295,29 @@ pub fn port_action_modules(text: &str, offset: u32) -> Vec { ItemKind::PortDecl(decl) => decl.declarators.iter().any(|d| d.span.contains(offset)), _ => false, }); - match on_body_declaration { - true => vec![name], - false => Vec::new(), + if on_body_declaration || in_non_ansi_header(module, offset) { + return vec![name]; } + Vec::new() +} + +/// Whether the cursor is anywhere in the header of a module written the +/// Verilog-2001 way — the one position the ANSI conversion is offered at that +/// no other port refactoring cares about. +/// +/// The header is everything from the module's keyword to the first item it +/// declares (that item's own leading comments included, since a cursor there +/// is still above the body). An ANSI module answers `false`: nothing would be +/// offered, and the gate exists to keep a cursor that carries no action from +/// materializing a workspace. +fn in_non_ansi_header(module: &Module, offset: u32) -> bool { + if !matches!(module.ports, PortList::NonAnsi(_)) { + return false; + } + let body = module.items.first().map(|item| { + item.meta.leading.first().map_or(item.span.start, |comment| comment.span.start) + }); + offset < body.unwrap_or(u32::MAX) } /// The module whose declaration covers this offset — what diff --git a/crates/vlog_refactor/tests/ansi.rs b/crates/vlog_refactor/tests/ansi.rs new file mode 100644 index 0000000..1775d0c --- /dev/null +++ b/crates/vlog_refactor/tests/ansi.rs @@ -0,0 +1,551 @@ +//! `convert_to_ansi`: a Verilog-2001 header rewritten ANSI-style. +//! +//! Behaviour tests, written against the public API the way an editor calls it. +//! The merge rules are IEEE 1800 §23.2.2.2's, one test each; the refusals are +//! the list in `docs/features/ansi-conversion/README.md`, one test each. + +use std::path::{Path, PathBuf}; + +use vlog_refactor::{convert_to_ansi, port_actions, RefactorEdit, TextEdit}; + +const TOP: &str = "/rtl/m.sv"; + +fn files(source: &str) -> Vec<(PathBuf, String)> { + vec![(PathBuf::from(TOP), source.to_string())] +} + +/// Apply an edit to the one file it touches. +fn applied(source: &str, edit: &RefactorEdit) -> String { + let (_, edits) = edit.edits.first().expect("one file edited"); + let mut out = String::new(); + let mut cursor = 0usize; + for TextEdit { range, new_text } in edits { + out.push_str(&source[cursor..range.start as usize]); + out.push_str(new_text); + cursor = range.end as usize; + } + out.push_str(&source[cursor..]); + out +} + +/// Convert at the module's name, which is inside every non-ANSI header. +fn convert(source: &str) -> Result { + let at = source.find("module ").map_or(0, |i| i + 7) as u32; + let edit = convert_to_ansi(&files(source), Path::new(TOP), at)?; + assert!(edit.edits.len() == 1, "only the module's own file is edited"); + Ok(applied(source, &edit)) +} + +/// The sentence a refusal is. +fn refused(source: &str) -> String { + convert(source).expect_err("this one is refused") +} + +fn count_comments(text: &str) -> usize { + text.match_indices("//").count() + text.match_indices("/*").count() +} + +// ---------------------------------------------------------------------- +// IEEE 1800 §23.2.2.2, one merge rule at a time +// ---------------------------------------------------------------------- + +#[test] +fn a_bare_port_declaration_becomes_a_bare_ansi_port() { + let source = "module m (a, b);\n input a;\n inout b;\nendmodule\n"; + assert_eq!(convert(source).expect("converted"), "module m (input a, inout b);\nendmodule\n"); +} + +#[test] +fn a_vector_port_keeps_its_packed_range() { + let source = "module m (b);\n output [7:0] b;\nendmodule\n"; + assert_eq!(convert(source).expect("converted"), "module m (output [7:0] b);\nendmodule\n"); +} + +#[test] +fn a_port_completed_by_a_variable_declaration_merges_the_two() { + // The LRM's own example: `output [7:0] b; reg [7:0] b;` is `output reg + // [7:0] b`. + let source = "module m (b);\n output [7:0] b;\n reg [7:0] b;\nendmodule\n"; + assert_eq!(convert(source).expect("converted"), "module m (output reg [7:0] b);\nendmodule\n"); +} + +#[test] +fn a_scalar_port_completed_by_a_scalar_variable_merges_too() { + let source = "module m (b);\n output b;\n reg b;\nendmodule\n"; + assert_eq!(convert(source).expect("converted"), "module m (output reg b);\nendmodule\n"); +} + +#[test] +fn a_port_completed_by_a_logic_declaration_merges() { + let source = "module m (b);\n output b;\n logic [3:0] b;\nendmodule\n"; + assert_eq!( + convert(source).expect("converted"), + "module m (output logic [3:0] b);\nendmodule\n" + ); +} + +#[test] +fn a_port_completed_by_a_net_declaration_merges() { + let source = "module m (a);\n input a;\n wire [1:0] a;\nendmodule\n"; + assert_eq!(convert(source).expect("converted"), "module m (input wire [1:0] a);\nendmodule\n"); +} + +#[test] +fn a_port_declaration_that_is_already_complete_needs_no_second_one() { + let source = "module m (a);\n input wire signed [7:0] a;\nendmodule\n"; + assert_eq!( + convert(source).expect("converted"), + "module m (input wire signed [7:0] a);\nendmodule\n" + ); +} + +#[test] +fn signing_written_on_either_half_reaches_the_ansi_port() { + let port = "module m (b);\n output signed [7:0] b;\n reg [7:0] b;\nendmodule\n"; + assert_eq!( + convert(port).expect("converted"), + "module m (output reg signed [7:0] b);\nendmodule\n" + ); + let var = "module m (b);\n output [7:0] b;\n reg signed [7:0] b;\nendmodule\n"; + assert_eq!( + convert(var).expect("converted"), + "module m (output reg signed [7:0] b);\nendmodule\n" + ); +} + +#[test] +fn a_packed_range_written_on_only_one_half_is_the_merged_one() { + let source = "module m (b);\n output b;\n reg [7:0] b;\nendmodule\n"; + assert_eq!(convert(source).expect("converted"), "module m (output reg [7:0] b);\nendmodule\n"); +} + +#[test] +fn identical_unpacked_dimensions_survive_the_merge() { + let source = "module m (mem);\n output [7:0] mem [0:3];\n reg [7:0] mem [0:3];\nendmodule\n"; + assert_eq!( + convert(source).expect("converted"), + "module m (output reg [7:0] mem [0:3]);\nendmodule\n" + ); +} + +#[test] +fn one_declaration_may_declare_several_ports() { + let source = "module m (a, b, c);\n input a, b;\n output c;\nendmodule\n"; + assert_eq!( + convert(source).expect("converted"), + "module m (input a, input b, output c);\nendmodule\n" + ); +} + +#[test] +fn a_user_defined_type_is_written_as_the_source_spells_it() { + let source = "module m (a);\n input a;\n pkg::word_t a;\nendmodule\n"; + assert_eq!(convert(source).expect("converted"), "module m (input pkg::word_t a);\nendmodule\n"); +} + +// ---------------------------------------------------------------------- +// layout, comments and the body +// ---------------------------------------------------------------------- + +#[test] +fn a_one_per_line_header_stays_one_per_line() { + let source = "module m (\n a,\n b\n);\n input a;\n output [7:0] b;\nendmodule\n"; + assert_eq!( + convert(source).expect("converted"), + "module m (\n input a,\n output [7:0] b\n);\nendmodule\n" + ); +} + +#[test] +fn the_headers_own_comments_are_not_touched() { + let source = "module m (\n a, // the clock\n b\n);\n input a;\n output b;\nendmodule\n"; + let out = convert(source).expect("converted"); + assert!(out.contains("input a, // the clock"), "{out}"); + assert_eq!(count_comments(&out), count_comments(source)); +} + +#[test] +fn a_trailing_comment_moves_onto_the_port_it_described() { + let source = + "module m (\n a,\n b\n);\n input a; // the clock\n output b; // the data\nendmodule\n"; + assert_eq!( + convert(source).expect("converted"), + "module m (\n input a, // the clock\n output b // the data\n);\nendmodule\n" + ); +} + +#[test] +fn a_leading_comment_moves_onto_its_own_line_above_the_port() { + let source = + "module m (\n a,\n b\n);\n // the clock\n input a;\n output b;\nendmodule\n"; + assert_eq!( + convert(source).expect("converted"), + "module m (\n // the clock\n input a,\n output b\n);\nendmodule\n" + ); +} + +#[test] +fn both_halves_of_a_merged_port_keep_their_comments() { + // Two comments never become one: a `//` swallows the line, so only one + // may sit beside the port and the rest go above it. + let source = "module m (\n b\n);\n output [7:0] b; // the port\n reg [7:0] b; // the storage\nendmodule\n"; + assert_eq!( + convert(source).expect("converted"), + "module m (\n // the port\n // the storage\n output reg [7:0] b\n);\nendmodule\n" + ); +} + +#[test] +fn a_block_comment_moves_into_an_inline_header() { + let source = "module m (a, b);\n /* first */ input a;\n output b;\nendmodule\n"; + let out = convert(source).expect("converted"); + assert!(out.contains("/* first */ input a"), "{out}"); + assert_eq!(count_comments(&out), count_comments(source)); +} + +#[test] +fn every_comment_in_the_module_survives_the_conversion() { + let source = concat!( + "// about the file\n", + "module m (\n", + " a, // in the header\n", + " b\n", + ");\n", + " // above the input\n", + " input a; // beside the input\n", + " /* above the output */\n", + " output [7:0] b; /* beside the output */\n", + " // an ordinary body comment\n", + " wire c;\n", + "endmodule\n" + ); + let out = convert(source).expect("converted"); + assert_eq!(count_comments(&out), count_comments(source), "{out}"); + for comment in [ + "// about the file", + "// in the header", + "// above the input", + "// beside the input", + "/* above the output */", + "/* beside the output */", + "// an ordinary body comment", + ] { + assert!(out.contains(comment), "{comment} is gone from {out}"); + } +} + +#[test] +fn a_parameter_written_between_the_declarations_is_left_alone() { + let source = + "module m (a, b);\n input a;\n parameter W = 8;\n output [W-1:0] b;\nendmodule\n"; + assert_eq!( + convert(source).expect("converted"), + "module m (input a, output [W-1:0] b);\n parameter W = 8;\nendmodule\n" + ); +} + +#[test] +fn body_declarations_that_are_not_ports_stay_where_they_are() { + let source = "module m (a);\n input a;\n wire b;\n reg [3:0] c;\nendmodule\n"; + assert_eq!( + convert(source).expect("converted"), + "module m (input a);\n wire b;\n reg [3:0] c;\nendmodule\n" + ); +} + +#[test] +fn a_twenty_port_header_of_mixed_declarations_converts_whole() { + let mut header = String::from("module wide (\n"); + let mut body = String::new(); + for n in 0..20 { + let comma = if n == 19 { "" } else { "," }; + header.push_str(&format!(" p{n}{comma}\n")); + match n % 5 { + 0 => body.push_str(&format!(" input p{n};\n")), + 1 => body.push_str(&format!(" input [7:0] p{n};\n")), + 2 => body.push_str(&format!(" output p{n};\n reg p{n};\n")), + 3 => { + body.push_str(&format!(" output signed [3:0] p{n};\n wire signed [3:0] p{n};\n")) + } + _ => body.push_str(&format!(" inout wire p{n};\n")), + } + } + let source = format!("{header});\n{body}endmodule\n"); + let out = convert(&source).expect("converted"); + assert!(out.contains(" input p0,"), "{out}"); + assert!(out.contains(" input [7:0] p1,"), "{out}"); + assert!(out.contains(" output reg p2,"), "{out}"); + assert!(out.contains(" output wire signed [3:0] p3,"), "{out}"); + assert!(out.contains(" inout wire p4,"), "{out}"); + assert!(out.contains(" inout wire p19\n);"), "{out}"); + assert!(!out.contains(" input p0;"), "the body declarations are gone: {out}"); + assert_eq!(out.matches("p19").count(), 1, "{out}"); +} + +// ---------------------------------------------------------------------- +// idempotency +// ---------------------------------------------------------------------- + +#[test] +fn converting_a_converted_header_refuses_because_it_is_already_ansi() { + let source = "module m (a, b);\n input a;\n output [7:0] b;\nendmodule\n"; + let once = convert(source).expect("converted"); + let again = convert(&once).expect_err("nothing left to convert"); + assert!(again.contains("already declares its ports ANSI-style"), "{again}"); +} + +// ---------------------------------------------------------------------- +// the refusals +// ---------------------------------------------------------------------- + +#[test] +fn a_position_in_no_module_is_refused() { + let source = "// nothing here\nmodule m (a);\n input a;\nendmodule\n"; + let said = convert_to_ansi(&files(source), Path::new(TOP), 2).expect_err("no module"); + assert_eq!(said, "there is no module declaration at this position."); +} + +#[test] +fn a_file_outside_the_scope_is_refused() { + let source = "module m (a);\n input a;\nendmodule\n"; + let said = convert_to_ansi(&files(source), Path::new("/elsewhere.sv"), 8) + .expect_err("outside the scope"); + assert!(said.contains("is not one of the files lucisv indexes"), "{said}"); +} + +#[test] +fn an_ansi_header_is_refused() { + let said = refused("module m (input a);\nendmodule\n"); + assert!(said.contains("already declares its ports ANSI-style"), "{said}"); +} + +#[test] +fn a_module_with_no_ports_is_refused() { + assert!(refused("module m ();\nendmodule\n").contains("declares no ports")); + assert!(refused("module m;\nendmodule\n").contains("declares no ports")); +} + +#[test] +fn an_interface_is_out_of_scope_this_round() { + let source = "interface it (a);\n input a;\nendinterface\n"; + let at = source.find("it (").expect("name") as u32; + let said = convert_to_ansi(&files(source), Path::new(TOP), at).expect_err("an interface"); + assert!(said.contains("is an `interface`, not a module"), "{said}"); +} + +#[test] +fn a_port_expression_is_refused() { + let concat = "module m ({x, y}, b);\n input x, y;\n input b;\nendmodule\n"; + assert!(refused(concat).contains("writes a port expression"), "{}", refused(concat)); + let named = "module m (.a({x, y}), b);\n input x, y;\n input b;\nendmodule\n"; + assert!(refused(named).contains("writes a port expression"), "{}", refused(named)); +} + +#[test] +fn a_file_that_does_not_parse_is_refused() { + let source = "module m (a);\n input a;\n always @(posedge do begin end\nendmodule\n"; + assert!(refused(source).contains("does not parse"), "{}", refused(source)); +} + +#[test] +fn a_header_name_with_no_declaration_is_refused() { + let source = "module m (a, c);\n input a;\nendmodule\n"; + let said = refused(source); + assert!(said.contains("names `c`, but its body declares no direction for it"), "{said}"); +} + +#[test] +fn a_declaration_for_a_name_the_header_does_not_carry_is_refused() { + let source = "module m (a);\n input a;\n output z;\nendmodule\n"; + let said = refused(source); + assert!( + said.contains("declares a direction for `z`, which its header does not name"), + "{said}" + ); +} + +#[test] +fn a_port_declared_twice_is_refused() { + let source = "module m (a);\n input a;\n input a;\nendmodule\n"; + assert!(refused(source).contains("declares a direction for `a` twice"), "{}", refused(source)); +} + +#[test] +fn a_variable_declared_twice_is_refused() { + let source = "module m (b);\n output b;\n reg b;\n reg b;\nendmodule\n"; + let said = refused(source); + assert!(said.contains("declares `b` twice outside its port declaration"), "{said}"); +} + +#[test] +fn a_complete_port_declared_again_is_refused() { + let source = "module m (b);\n output reg b;\n reg b;\nendmodule\n"; + let said = refused(source); + assert!(said.contains("IEEE 1800 §23.2.2.2 makes that an error"), "{said}"); +} + +#[test] +fn packed_ranges_that_disagree_are_refused() { + let source = "module m (b);\n output [7:0] b;\n reg [3:0] b;\nendmodule\n"; + let said = refused(source); + assert!(said.contains("packed range"), "{said}"); + assert!(said.contains("asks for identical ones"), "{said}"); +} + +#[test] +fn unpacked_dimensions_that_disagree_are_refused() { + let source = "module m (mem);\n output [7:0] mem [0:3];\n reg [7:0] mem [0:7];\nendmodule\n"; + let said = refused(source); + assert!(said.contains("unpacked dimension"), "{said}"); +} + +#[test] +fn signing_that_disagrees_is_refused() { + let source = "module m (b);\n output signed [7:0] b;\n reg unsigned [7:0] b;\nendmodule\n"; + let said = refused(source); + assert!(said.contains("`signed`") && said.contains("`unsigned`"), "{said}"); +} + +#[test] +fn a_declaration_shared_with_a_local_is_refused() { + let source = "module m (b);\n output [7:0] b;\n reg [7:0] b, scratch;\nendmodule\n"; + let said = refused(source); + assert!(said.contains("split the declaration first"), "{said}"); +} + +#[test] +fn an_initialiser_is_refused() { + let source = "module m (b);\n output b;\n reg b = 1'b0;\nendmodule\n"; + assert!(refused(source).contains("does not move an initialiser"), "{}", refused(source)); +} + +#[test] +fn an_attribute_on_an_absorbed_declaration_is_refused() { + // `Item.span` covers the `(* ... *)`, so the deletion would take it with + // the declaration and only the comments are carried; `(* keep *)` changes + // what a synthesizer does, and where an attribute belongs in an ANSI port + // list is a design question rather than a merge rule. + let source = "module m (a);\n (* keep *) input a;\nendmodule\n"; + let said = refused(source); + assert!(said.contains("`(* keep *)` on `m`'s declaration of `a` would be dropped"), "{said}"); + assert!(said.contains("move the attribute onto the port by hand"), "{said}"); +} + +#[test] +fn an_attribute_on_the_completing_declaration_is_refused_too() { + // The other half of the merge is absorbed by the same deletion. + let source = "module m (b);\n output b;\n (* mark_debug = \"true\" *) reg b;\nendmodule\n"; + let said = refused(source); + assert!(said.contains("would be dropped"), "{said}"); + assert!(said.contains("mark_debug"), "{said}"); +} + +#[test] +fn a_declaration_inside_a_generate_region_is_refused() { + let source = "module m (b);\n output b;\n generate\n reg b;\n endgenerate\nendmodule\n"; + let said = refused(source); + assert!(said.contains("inside a generate region"), "{said}"); +} + +#[test] +fn compiler_directives_in_the_port_list_are_refused() { + let source = "module m (\n a,\n`ifdef WIDE\n b,\n`endif\n c\n);\n input a;\n input b;\n input c;\nendmodule\n"; + let said = refused(source); + assert!(said.contains("port list carries compiler directives"), "{said}"); +} + +#[test] +fn a_declaration_inside_a_conditional_arm_is_refused() { + let source = "module m (a, b);\n input a;\n`ifdef WIDE\n input b;\n`endif\nendmodule\n"; + let said = refused(source); + assert!(said.contains("conditionally compiled"), "{said}"); +} + +#[test] +fn a_directive_between_the_declarations_is_refused() { + let source = "module m (a, b);\n input a;\n`include \"more.svh\"\n input b;\nendmodule\n"; + let said = refused(source); + assert!(said.contains("is written among the declarations"), "{said}"); +} + +#[test] +fn a_comment_written_inside_a_declaration_is_refused() { + let source = "module m (a);\n input /* which */ a;\nendmodule\n"; + let said = refused(source); + assert!(said.contains("inside a declaration the conversion would delete"), "{said}"); +} + +#[test] +fn a_line_comment_that_has_nowhere_to_go_is_refused() { + let source = "module m (a, b);\n input a; // the clock\n output b;\nendmodule\n"; + let said = refused(source); + assert!(said.contains("break `m`'s port list across lines first"), "{said}"); +} + +#[test] +fn a_module_declared_twice_in_the_workspace_is_refused() { + let source = "module m (a);\n input a;\nendmodule\n"; + let files = vec![ + (PathBuf::from(TOP), source.to_string()), + (PathBuf::from("/rtl/other.sv"), source.to_string()), + ]; + let said = convert_to_ansi(&files, Path::new(TOP), 8).expect_err("declared twice"); + assert!(said.contains("is declared in more than one indexed file"), "{said}"); +} + +#[test] +fn a_header_that_names_a_port_twice_is_refused() { + let source = "module m (a, a);\n input a;\nendmodule\n"; + assert!(refused(source).contains("names `a` twice"), "{}", refused(source)); +} + +// ---------------------------------------------------------------------- +// the code action +// ---------------------------------------------------------------------- + +#[test] +fn the_action_is_offered_anywhere_in_a_non_ansi_header() { + let source = "module m (\n a,\n b\n);\n input a;\n output [7:0] b;\nendmodule\n"; + let files = files(source); + for needle in ["module m", "m (", "a,", "b\n)"] { + let at = source.find(needle).expect(needle) as u32; + let titles: Vec = + port_actions(&files, Path::new(TOP), at).into_iter().map(|a| a.title).collect(); + assert!( + titles.iter().any(|t| t == "lucisv: convert ports to ANSI (2 ports)"), + "at {needle:?}: {titles:?}" + ); + } +} + +#[test] +fn the_action_is_not_offered_in_the_body_or_in_an_ansi_module() { + let source = "module m (\n a\n);\n input a;\n wire w;\n assign w = a;\nendmodule\n"; + let at = source.find("assign").expect("body") as u32; + assert!(port_actions(&files(source), Path::new(TOP), at).is_empty()); + + let ansi = "module m (input a);\n wire w;\n assign w = a;\nendmodule\n"; + let at = ansi.find("module m").expect("header") as u32; + let titles: Vec = + port_actions(&files(ansi), Path::new(TOP), at).into_iter().map(|a| a.title).collect(); + assert!(!titles.iter().any(|t| t.contains("convert ports to ANSI")), "{titles:?}"); +} + +#[test] +fn the_action_says_one_port_in_the_singular() { + let source = "module m (a);\n input a;\nendmodule\n"; + let at = source.find("module m").expect("header") as u32; + let titles: Vec = + port_actions(&files(source), Path::new(TOP), at).into_iter().map(|a| a.title).collect(); + assert!(titles.contains(&"lucisv: convert ports to ANSI (1 port)".to_string()), "{titles:?}"); +} + +#[test] +fn a_comment_on_a_declaration_of_two_ports_is_written_once() { + // The declaration is absorbed by both ports; its comment belongs to the + // first of them and must not be copied onto the second. + let source = "module m (\n a,\n b\n);\n input a, b; // both of them\nendmodule\n"; + let out = convert(source).expect("converted"); + assert_eq!(out.matches("// both of them").count(), 1, "{out}"); + assert_eq!(out, "module m (\n input a, // both of them\n input b\n);\nendmodule\n"); +} diff --git a/crates/vlog_refactor/tests/corpus.rs b/crates/vlog_refactor/tests/corpus.rs index 24b3fa9..c337b60 100644 --- a/crates/vlog_refactor/tests/corpus.rs +++ b/crates/vlog_refactor/tests/corpus.rs @@ -10,9 +10,10 @@ use std::fs; use std::path::{Path, PathBuf}; use std::time::Instant; +use vlog_parser::ast::{Item, ItemKind, ListElem, PortList}; use vlog_refactor::{ - add_port, expand_wildcard, instantiation_plan, module_definition, port_actions, prepare_rename, - rename, Layout, ModuleRef, + add_port, convert_to_ansi, expand_wildcard, instantiation_plan, module_definition, + port_actions, prepare_rename, rename, Layout, ModuleRef, }; use vlog_semantic::WorkspaceIndex; @@ -331,3 +332,324 @@ fn wildcard_offset(text: &str) -> Option { } None } + +// ---------------------------------------------------------------------- +// TODO §51 — the non-ANSI → ANSI conversion +// ---------------------------------------------------------------------- + +/// The census the plan asks for: how many modules in the corpus write a +/// Verilog-2001 header, and does every one of them convert? +/// +/// **The count is zero, and that is the finding.** common_cells, ibex, +/// opentitan and picorv32 are all written ANSI-style — even picorv32, the +/// oldest of them — so there is no non-ANSI header in 860 files to convert. +/// The assertion is therefore written as a census rather than as a number: it +/// converts *every* one it finds, and stays honest the day the corpus gains +/// one. The real-RTL exercise the conversion does get is +/// `an_ansi_header_written_the_2001_way_converts_back_to_itself` below, which +/// makes its material out of the corpus's own ANSI modules. +#[test] +fn every_non_ansi_module_in_the_corpus_converts() { + let Some(files) = corpus() else { return }; + let sources = read(&files); + assert!(!sources.is_empty(), "corpus/ exists but holds no Verilog"); + let config = vlog_formatter::Config::default(); + + let sites: Vec<(PathBuf, String, u32)> = sources + .iter() + .flat_map(|(path, text)| { + non_ansi_modules(text).into_iter().map(move |(name, at)| (path.clone(), name, at)) + }) + .collect(); + println!("corpus non-ANSI module headers: {}", sites.len()); + + let mut refused: Vec = Vec::new(); + for (path, name, at) in &sites { + let Some((_, text)) = sources.iter().find(|(held, _)| held == path) else { continue }; + match convert_to_ansi(&sources, path, *at) { + Err(said) => refused.push(format!("{} :: {name}: {said}", path.display())), + Ok(edit) => { + let copy = edited(text, edit.edits_for(path)); + let once = vlog_formatter::format_source(©, &config).unwrap_or_else(|e| { + panic!("the formatter refuses {} :: {name}: {e}\n{copy}", path.display()) + }); + let twice = + vlog_formatter::format_source(&once, &config).expect("formats a second time"); + assert_eq!(once, twice, "{} :: {name} does not converge", path.display()); + assert_eq!( + port_names(©, name), + port_names(text, name), + "{} :: {name} changed its port list", + path.display() + ); + } + } + } + println!("refused: {}\n {}", refused.len(), refused.join("\n ")); +} + +/// Real RTL, made non-ANSI and converted back. +/// +/// The corpus writes no Verilog-2001 header, so this test manufactures them out +/// of real ones: a corpus module's ANSI port list is rewritten the 2001 way — +/// bare names in the header, each declaration moved into the body verbatim — +/// and `convert_to_ansi` is asked to undo it. Three properties, on real port +/// lists of up to a few dozen ports: +/// +/// * the converted file **parses with no diagnostic** and formats, and +/// formatting it twice does not move it; +/// * its module declares the **same ports, in the same order, with the same +/// direction, net, type, signing and dimensions** as the module the corpus +/// ships — [`signature`], which is the whole of what the conversion promises; +/// * and the file's comment count is unchanged. +/// +/// Not byte-identity after formatting: the formatter keeps the *author's* +/// column alignment in an ANSI port list, and a refactoring writes edited +/// source rather than formatted source, so the alignment the corpus wrote by +/// hand is not something the conversion undertakes to reproduce. +/// +/// Nothing is written back to `corpus/`; every edit is applied to a copy. +#[test] +fn an_ansi_header_written_the_2001_way_converts_back_to_itself() { + let Some(files) = corpus() else { return }; + let sources = read(&files); + let config = vlog_formatter::Config::default(); + + let mut done: Vec = Vec::new(); + for (path, text) in &sources { + if done.len() >= 5 { + break; + } + let Some((name, legacy)) = as_non_ansi(text) else { continue }; + let mut scratch = sources.clone(); + let Some(slot) = scratch.iter_mut().find(|(held, _)| held == path) else { continue }; + slot.1 = legacy.clone(); + let at = legacy.find(&format!("module {name}")).expect("the header") as u32; + + let started = Instant::now(); + let edit = match convert_to_ansi(&scratch, path, at) { + Ok(edit) => edit, + Err(said) => { + println!("skipped {} :: {name}: {said}", path.display()); + continue; + } + }; + let back = edited(&legacy, edit.edits_for(path)); + assert!( + vlog_parser::parse_source_tolerant(&back).1.is_empty(), + "{} :: {name} does not parse after the conversion\n{back}", + path.display() + ); + assert_eq!( + signature(&back, &name), + signature(text, &name), + "{} :: {name} did not come back to what the corpus ships", + path.display() + ); + assert_eq!( + back.matches("//").count() + back.matches("/*").count(), + text.matches("//").count() + text.matches("/*").count(), + "{} :: {name} lost or gained a comment", + path.display() + ); + let once = vlog_formatter::format_source(&back, &config).expect("the conversion formats"); + let twice = vlog_formatter::format_source(&once, &config).expect("formats a second time"); + assert_eq!(once, twice, "{} :: {name} does not converge", path.display()); + done.push(format!( + "{} :: {name} in {:.2}s", + path.display(), + started.elapsed().as_secs_f64() + )); + } + println!("round-tripped:\n {}", done.join("\n ")); + assert!(done.len() >= 5, "five real round trips, got {done:?}"); +} + +/// Every module in a file whose header is a `PortList::NonAnsi`, with the +/// offset of its name. +fn non_ansi_modules(text: &str) -> Vec<(String, u32)> { + fn walk(items: &[Item], out: &mut Vec<(String, u32)>) { + for item in items { + match &item.kind { + ItemKind::Module(module) => { + if matches!(module.ports, PortList::NonAnsi(_)) { + out.push((module.name.clone(), module.name_span.start)); + } + walk(&module.items, out); + } + ItemKind::Package { items, .. } => walk(items, out), + _ => {} + } + } + } + let mut out = Vec::new(); + walk(&vlog_parser::parse_source_tolerant(text).0.items, &mut out); + out +} + +/// What a module's ANSI port list says, port by port: direction, net type, +/// data type, signing, packed and unpacked dimensions, and the name. +/// +/// The whole of what the conversion promises, and the one thing a +/// non-ANSI header and the ANSI header it becomes must agree about. +/// Whitespace is taken out, since a `[7 : 0]` and a `[7:0]` are one range. +fn signature(text: &str, module: &str) -> Vec { + let (tree, _) = vlog_parser::parse_source_tolerant(text); + fn walk<'t>(items: &'t [Item], module: &str) -> Option<&'t vlog_parser::ast::Module> { + for item in items { + match &item.kind { + ItemKind::Module(found) if found.name == module => return Some(found), + ItemKind::Module(found) => { + if let Some(found) = walk(&found.items, module) { + return Some(found); + } + } + ItemKind::Package { items, .. } => { + if let Some(found) = walk(items, module) { + return Some(found); + } + } + _ => {} + } + } + None + } + let tight = |s: &str| s.chars().filter(|c| !c.is_whitespace()).collect::(); + let dims = |list: &[vlog_parser::ast::Dim]| -> String { + list.iter() + .map(|d| tight(text.get(d.span.start as usize..d.span.end as usize).unwrap_or(""))) + .collect() + }; + let Some(module) = walk(&tree.items, module) else { return Vec::new() }; + let PortList::Ansi(ports) = &module.ports else { return Vec::new() }; + ports + .iter() + .filter_map(ListElem::ok) + .map(|p| { + format!( + "{}|{}|{}|{}|{}|{}|{}", + p.dir.clone().unwrap_or_default(), + p.net.clone().unwrap_or_default(), + p.ty.name, + p.ty.signing.clone().unwrap_or_default(), + dims(&p.ty.packed), + dims(&p.unpacked), + p.name + ) + }) + .collect() +} + +/// The port names a module declares, in order. +fn port_names(text: &str, module: &str) -> Vec { + let (tree, _) = vlog_parser::parse_source_tolerant(text); + fn walk(items: &[Item], module: &str) -> Option> { + for item in items { + match &item.kind { + ItemKind::Module(found) if found.name == module => { + return Some(match &found.ports { + PortList::Ansi(ports) => { + ports.iter().filter_map(ListElem::ok).map(|p| p.name.clone()).collect() + } + PortList::NonAnsi(ports) => { + ports.iter().filter_map(ListElem::ok).map(|p| p.name.clone()).collect() + } + PortList::Empty | PortList::None => Vec::new(), + }) + } + ItemKind::Module(found) => { + if let Some(names) = walk(&found.items, module) { + return Some(names); + } + } + ItemKind::Package { items, .. } => { + if let Some(names) = walk(items, module) { + return Some(names); + } + } + _ => {} + } + } + None + } + walk(&tree.items, module).unwrap_or_default() +} + +/// One file's first ANSI module rewritten the Verilog-2001 way: the header +/// keeps the names, each declaration moves into the body verbatim. +/// +/// `None` for a file with no module the rewrite is faithful for — a port with +/// a default value, a comment inside the list, an interface port or a +/// direction-less continuation port all make the two spellings say different +/// things, and this is a test fixture rather than a second refactoring. +fn as_non_ansi(text: &str) -> Option<(String, String)> { + let (tree, diagnostics) = vlog_parser::parse_source_tolerant(text); + if !diagnostics.is_empty() { + return None; + } + let ItemKind::Module(module) = &tree + .items + .iter() + .find(|item| { + matches!(&item.kind, ItemKind::Module(m) + if m.kw == "module" && m.port_directives.is_empty()) + })? + .kind + else { + return None; + }; + let PortList::Ansi(ports) = &module.ports else { return None }; + let ports: Vec<&vlog_parser::ast::AnsiPort> = + ports.iter().map(ListElem::ok).collect::>>()?; + let (first, last) = (ports.first()?, ports.last()?); + let list = text.get(first.span.start as usize..last.span.end as usize)?; + if list.contains("//") || list.contains("/*") { + return None; + } + for port in &ports { + let plain = port.dir.is_some() + && port.default.is_none() + && port.meta.leading.is_empty() + && port.meta.trailing.is_none() + && port.meta.before_sep.is_empty() + && port.after_dir.is_empty() + && port.before_name.is_empty() + && port.ty.extra.is_none() + && port.ty.virt.is_none(); + if !plain { + return None; + } + } + // The header's `;`, which is where the body declarations go. + let semi = last.span.end as usize + text.get(last.span.end as usize..)?.find(';')? + 1; + // Each element is replaced by its own name, so the list keeps the layout + // the file wrote — the conversion is asked to put the declarations back, + // not to reflow anything. + let mut out = String::new(); + let mut cursor = 0usize; + for port in &ports { + out.push_str(text.get(cursor..port.span.start as usize)?); + out.push_str(&port.name); + cursor = port.span.end as usize; + } + out.push_str(text.get(cursor..semi)?); + for port in &ports { + out.push_str("\n "); + out.push_str(text.get(port.span.start as usize..port.span.end as usize)?); + out.push(';'); + } + out.push_str(text.get(semi..)?); + Some((module.name.clone(), out)) +} + +/// A copy of `text` with one file's edits applied. +fn edited(text: &str, edits: &[vlog_refactor::TextEdit]) -> String { + let mut copy = text.to_string(); + for change in edits.iter().rev() { + copy.replace_range( + change.range.start as usize..change.range.end as usize, + &change.new_text, + ); + } + copy +} diff --git a/crates/vlog_refactor/tests/ports.rs b/crates/vlog_refactor/tests/ports.rs index 2a91c24..12e2a7b 100644 --- a/crates/vlog_refactor/tests/ports.rs +++ b/crates/vlog_refactor/tests/ports.rs @@ -88,6 +88,28 @@ fn a_connection_with_no_signal_of_that_name_is_left_as_a_todo() { assert!(warnings(&edit).contains("`u1` (top.sv:2)"), "{:?}", edit.warnings); } +#[test] +fn a_second_port_may_leave_a_second_todo_where_the_first_one_already_is() { + // A module gains its ports one at a time, so the second addition finds the + // first one's `/* TODO: connect */` already sitting in the file and writes + // another. `check::never_dropped` refuses an edit that writes a comment it + // is not deleting — this is the one flow that legitimately does, and the + // reason the rule keeps a whitelist of the text the engine writes itself. + let first = files(&[ + ("/rtl/sub.sv", SUB), + ("/rtl/top.sv", "module top;\n sub u1 (.clk(c), .rst(r));\nendmodule\n"), + ]); + let edit = add_port(&first, ModuleRef::Name("sub"), "input logic cfg").expect("adds `cfg`"); + let second = files(&[ + ("/rtl/sub.sv", &applied(&first, &edit, "/rtl/sub.sv")), + ("/rtl/top.sv", &applied(&first, &edit, "/rtl/top.sv")), + ]); + let edit = add_port(&second, ModuleRef::Name("sub"), "input logic mode").expect("adds `mode`"); + let top = applied(&second, &edit, "/rtl/top.sv"); + assert_eq!(top.matches("/* TODO: connect */").count(), 2, "{top}"); + assert!(top.contains(".cfg(/* TODO: connect */), .mode(/* TODO: connect */)"), "{top}"); +} + #[test] fn a_one_per_line_connection_list_stays_one_per_line() { let workspace = files(&[ diff --git a/docs/features/ansi-conversion/README.md b/docs/features/ansi-conversion/README.md new file mode 100644 index 0000000..d36857a --- /dev/null +++ b/docs/features/ansi-conversion/README.md @@ -0,0 +1,1044 @@ +# ansi-conversion + +TODO §51 — the second of the §8 refactoring backlog to ship. One engine +function, one code action, one command. + +## Goal + +A Verilog-2001 header names its ports and the body declares them: + +```verilog +module m (a, b); + input a; + output [7:0] b; + reg [7:0] b; + ... +endmodule +``` + +**Converting it to ANSI** writes those declarations where a modern reader +looks for them, and deletes them from the body: + +```verilog +module m (input a, output reg [7:0] b); + ... +endmodule +``` + +That is the first thing an engineer does to a file inherited from 2001, and it +is the one edit every other lucisv port refactoring is easier after: `add_port` +writes one element into an ANSI list instead of an element *and* a body +declaration, `remove_port` has one place to delete rather than two, and hover +no longer has to point at a `detail_span` on another line to say what a port +is. IEEE 1800 §23.2.2.2 says exactly how the two declarations merge, and this +round implements that paragraph and nothing more. + +The engine is `vlog_refactor::convert_to_ansi`, so Vim, VS Code and any future +CLI get identical behaviour; `lucisv_server` maps the protocol and decides +nothing. Whole-edit-or-nothing, through the ports engine's lexical splice and +its "the file still parses" verifier: an `Ok` is safe to apply, an `Err` is a +sentence for the user and no edits at all. + +## API as built + +```rust +// crates/vlog_refactor/src/lib.rs +pub fn convert_to_ansi(files: &[(PathBuf, String)], file: &Path, offset: u32) + -> Result; +``` + +`files`, `RefactorEdit`, `TextEdit` and the `Err(String)`-is-a-sentence +convention are M2's, unchanged. `port_actions` gained a fourth offer, so the +code-action path needed no new entry point; `port_action_modules` gained one +position (anywhere in a non-ANSI header) so that the offer reaches the cursor +the plan asks for. + +## The edit's shape — insertions, never a rewrite of the list + +Each header name **keeps the bytes it already occupies**. What an ANSI port +adds is inserted *around* it: the direction, net, type, signing and packed +dimensions just before the name, an unpacked dimension just after it, a moved +comment past the comma. Two things follow, and both are why it is done this +way rather than by replacing the list: + +* **The header's own layout, commas and comments are untouched.** A list + written one port per line stays one port per line, at its own indentation; a + comment the source wrote beside a port name stays beside it; the source's + `(`/`)` placement is not lucisv's business. Refactored output is *edited + source*, not reformatted source (umbrella Handshakes). +* **`check::verify_splice`'s resolution check passes.** That check requires + every reference outside the edits to resolve to the same declaration *at the + same place*, mapped through `Shift::map`. A non-ANSI port's `Symbol` is the + **header** name (`vlog_semantic` models the body `input a;` as its + `detail_span`, not as a second symbol — verified), so every body use of `a` + anchors at the header. Replacing the header element would move that anchor + and the verifier would refuse the whole refactoring, correctly. Inserting + around the name leaves the anchor exactly where `Shift::map` predicts, and + the identity holds. + +The `Plan`'s expected shape is therefore `shape(text, module)` **unchanged**: +the module must declare the same ports, in the same order, after the edit as +before. A conversion that reordered or lost a port cannot survive `confirm`. + +## The merge rule, exactly as implemented (IEEE 1800 §23.2.2.2) + +`merge.rs`. For each header name, in header order: + +| what the body writes | the ANSI port | +|---|---| +| `input a;` | `input a` | +| `input [7:0] a;` | `input [7:0] a` | +| `input wire signed [7:0] a;` | `input wire signed [7:0] a` (already complete) | +| `output b;` + `reg b;` | `output reg b` | +| `output [7:0] b;` + `reg [7:0] b;` | `output reg [7:0] b` | +| `output b;` + `reg [7:0] b;` | `output reg [7:0] b` (the one range written wins) | +| `input a;` + `wire [1:0] a;` | `input wire [1:0] a` | +| `output signed [7:0] b;` + `reg [7:0] b;` | `output reg signed [7:0] b` | +| `output [7:0] mem [0:3];` + `reg [7:0] mem [0:3];` | `output reg [7:0] mem [0:3]` | +| `input a, b;` (one declaration, two ports) | `input a`, `input b` | + +Read as rules: + +1. The **port declaration** (`input`/`output`/`inout`) always gives the + direction, and there must be exactly one for each header name. +2. If it also gives a **net or data type** (`input wire a;`, `output reg b;`) + the port is *completely declared*; a second declaration of that name is an + error under the LRM and lucisv refuses rather than merging it. +3. Otherwise a **net or variable declaration** of the same name completes it. + The merged port is the union: the net keyword from whichever half wrote one, + the type name from whichever half wrote one, `signed`/`unsigned` from + whichever wrote one, the packed range from whichever wrote one, the unpacked + dimensions from whichever wrote one. +4. Where **both** halves write the same thing, the two must agree — identical + packed ranges, identical unpacked dimensions, one signing. Ranges are + compared with the whitespace taken out, so `[7 : 0]` and `[7:0]` agree. +5. The text is written in the order **`vlog_formatter`'s own ANSI port printer + writes it** (`ansi_port_cells`: direction, net, type, signing, packed, name, + unpacked), so a converted header is what the formatter would have printed + and formatting it moves nothing but whitespace. + +## Comments + +Invariant 3 is the hardest part of this refactoring, because unlike every port +refactoring before it this one **deletes a construct a comment is attached +to**. Nothing is dropped and nothing is guessed at: + +* A comment written **before** an absorbed declaration goes on its own line + above the ANSI port, at the port's indentation. +* A comment written **after** one, on its line, goes at the end of the port's + own line — where the source had it, relative to what it describes. +* **At most one comment may go beside a port**, and only when nothing else is + written there and the header wrote no comment of its own beside that port. + Two comments landing on one line become **one** comment (a `//` runs to the + end of the line and the lexer merges what follows into the same trailing + comment), and a refactoring that joins two comments the source kept apart is + not one lucisv will do. Everything that cannot sit beside the port goes above + it instead. +* A port list written **on one line** has no line above a port either. There a + single-line block comment is written inline (`/* first */ input a`) and a + `//` comment is a refusal with a sentence, because it would swallow the rest + of the header. +* A comment written **inside** a declaration (`input /* which */ a;`) is a + refusal: lucisv will not decide where that one goes in an ANSI port. This is + §50's precedent, applied to a declaration instead of a connection. +* A declaration that declares **several ports** (`input a, b; // both`) hands + its comments to the **first** of them and to no other: written onto both they + would be duplicated, which is as much a corruption as dropping them. The + verifier enforces this independently of the planner. + +An **attribute instance** is not a comment and is not carried: `(* keep *)` on +an absorbed declaration is a **refusal** (refusal 23), because where a +`(* ... *)` belongs in an ANSI port list is a design question rather than a +merge rule, and losing one changes what a synthesizer does. + +**`check.rs` changed for this**, and the change is a *tightening* rather than a +widening — see Handshakes and the work log. + +## The refusal list — exact + +`convert_to_ansi` refuses when: + +1. **The position is in no module** — *"there is no module declaration at this + position."* +2. **The file is outside the in-scope set** — `not_in_scope`'s existing + sentence. +3. **The header is already ANSI** — *"`m`'s header already declares its ports + ANSI-style, so there is nothing to convert."* This is also what makes the + refactoring idempotent, and it is asserted as such. +4. **The module declares no ports** (`module m;`, `module m ();`) — *"`m` + declares no ports, so there is nothing to convert."* +5. **It is an `interface` or a `program`** — *"`bus_if` is an `interface`, not + a module, and lucisv does not convert an `interface`'s non-ANSI header in + this round; it made no edits."* Out of scope this round, said out loud. +6. **The header writes a port expression** — *"`m`'s header writes a port + expression (IEEE 1800 §23.2.2.1's `.a({x,y})` or `{x,y}`), which has no ANSI + spelling; lucisv made no edits."* Recognised from the `ListElem::Error` a + tolerant parse leaves in the list, and checked **before** the + does-not-parse refusal so the user gets the specific sentence. +7. **The file carries a parse diagnostic** — *"m.sv does not parse (… at line + N), so lucisv will not convert its ports to ANSI."* Stricter than the + verifier's "no *new* diagnostic" rule, for §50's reason: a header lucisv + misread is a header whose ports it would declare twice. +8. **The header names a port twice** — *"`m`'s header names `a` twice; lucisv + will not guess which port that is."* +9. **A header name has no body declaration** — *"`m`'s header names `c`, but + its body declares no direction for it; a port with no declaration is + illegal, so lucisv made no edits."* +10. **A body declaration names something the header does not** — *"`m` declares + a direction for `z`, which its header does not name; lucisv made no + edits."* +11. **A port is declared twice** — *"`m` declares a direction for `b` twice; + lucisv will not guess which one is the port."* And the variable half: + *"`m` declares `b` twice outside its port declaration; …"* +12. **A complete port declaration is declared again** — *"`m` gives `b` a type + in its port declaration and declares it again; IEEE 1800 §23.2.2.2 makes + that an error, so lucisv made no edits."* +13. **The two halves disagree** — packed ranges (*"…with the packed range + `[7:0]` … and `[3:0]` …; IEEE 1800 §23.2.2.2 asks for identical ones…"*), + unpacked dimensions (the same sentence), or signing (*"…declares `b` + `signed` … and `unsigned` …"*). +14. **A declaration is shared with a local** — *"`m` declares `b`, `scratch` in + one declaration, of which only 1 is a port; lucisv cannot absorb one + without the other, so split the declaration first."* Deleting it would take + the local with it. +15. **A declaration carries an initialiser** (*"…does not move an initialiser + into a port list…"*), a **qualifier** (`var`, `const`, `automatic` — *"…does + not move a qualifier into a port list…"*), a **net delay**, or a type + lucisv will not move (an anonymous `enum`/`struct` body, a parameterized + `#( ... )` reference, a `virtual` interface type). +16. **A header port is declared inside a generate region** — *"`m` declares `b` + inside a generate region, where lucisv will not read a port's declaration; + it made no edits."* +17. **The port list carries compiler directives** — §50's sentence, adapted: + *"`m`'s port list carries compiler directives, so which ports it declares + depends on the configuration; lucisv does not preprocess, so it made no + edits."* +18. **A declaration stands inside a conditional arm**, or **a directive is + written among the declarations the conversion would delete** — two + sentences, both saying lucisv does not know what body it would leave + behind. +19. **A comment is written inside an absorbed declaration** — see Comments. +20. **A `//` comment would have to move into a one-line port list** — *"the + comment `// the clock` on `m`'s declaration of `a` would have to move into + a port list written on one line, where it would swallow the rest of it; + break `m`'s port list across lines first, and lucisv made no edits."* +21. **The header already writes a comment beside the port** and one would have + to join it — this one never surfaces as a sentence, because the planner + puts the comment on its own line above the port instead. +22. **The module is declared twice in the workspace**, or its indexed + declaration is in another file — `locate_module`'s existing sentences. +23. **An absorbed declaration carries an attribute instance** — *"`(* keep *)` + on `m`'s declaration of `a` would be dropped, and lucisv does not decide + where an attribute belongs in an ANSI port list; move the attribute onto + the port by hand, and it made no edits."* `Item.span` covers the + `(* ... *)`, so the deletion would take it and only the *comments* are + carried onto the port — and unlike a comment, a lost `(* keep *)` changes + what a synthesizer does. Added by the rework; see the work log. +24. **Verification fails** — the five checks in + `docs/features/refactor-ports/README.md`, unchanged. + +Every one of 1–20, 22 and 23 is pinned by a behaviour test in +`crates/vlog_refactor/tests/ansi.rs`. Nothing is offered as a code action where +the refactoring would be refused, so the lightbulb never appears to explain +itself. + +## Assumptions + +- **The module's own file is the only file edited.** A non-ANSI header's ports + keep their names and their order, so no instantiation anywhere changes — this + refactoring has no fan-out at all, which is what makes the lazy code action + exact rather than optimistic. +- **`vlog_semantic` models a non-ANSI port as one symbol, in the header.** The + body `input a;` is that symbol's `detail_span`, and a separate `reg a;` + produces no second symbol. Verified against the analyzer before the edit + shape was chosen, and it is the assumption the insertion-based edit rests on; + if it ever changed, the resolution check would refuse every conversion rather + than let a wrong one through. +- **lucisv does not preprocess**, so a port list or a body split across + `` `ifdef`` arms is refused rather than read straight through — §50's + assumption, and stricter here for the same reason: this refactoring + enumerates and deletes a whole set of declarations rather than appending one + element. +- **lucisv is not a legality checker.** `inout` merged with `reg` is illegal + Verilog; lucisv writes what the two declarations said and lets the compiler + say so. What it refuses is what it cannot *express*, not what a tool would + reject. +- **A module name is unique in scope**, and the index is the server's authority + on where it is declared — the ports engine's assumptions, unchanged. + +## Handshakes + +**Consumed from `vlog_parser`** (no change required): `parse_source_tolerant` +and its `ParseDiagnostic`, `tokenize` and `token::Comment` (the comment scan), +`TextRange`, and `ast::{Module, PortList, NonAnsiPort, Item, ItemKind, +PortDecl, DataDecl, Declarator, Dim, DataType, ListElem, GenBlock, GenElse}`. +`PortList::NonAnsi` holding a `ListElem::Error` for a port expression is what +makes refusal 6 possible. + +**Consumed from `vlog_semantic`**: nothing new. The conversion asks no +semantic question of its own; the verifier asks all of them. + +**Changed inside `vlog_refactor`** — two new files and four small edits to +existing ones: + +- `ports/ansi.rs` (new, 464 lines, 362 of them code): the planner — locate, + refuse, place the comments, write the insertions and the deletions. +- `ports/merge.rs` (new, 325 lines, 254 of them code): IEEE 1800 §23.2.2.2, and + nothing else. +- `ports/mod.rs`: `convert_to_ansi`, `conversion` (the edit plus its port + count), the fourth `port_actions` offer, and `in_non_ansi_header` — the one + new position `port_action_modules` answers for. +- `ports/add.rs`: `Directive`, `Nesting`, `nesting_of` and `body_directives` + are `pub(super)` instead of private. Four visibility words; no call site + changed, no behaviour changed. +- `ports/list.rs`: `comma_after` is `pub(super)`. One word. +- **`check.rs`: `never_dropped` replaces the "no deletion may cover a comment" + rule.** The one substantive change outside the new files; see the work log + for why it is a tightening and for the attack tests that ship with it + (CLAUDE.md invariant 4). It counts **attribute instances** alongside + comments, so *every* refactoring — not only this one — is now refused if an + edit of its deletes a `(* ... *)` without writing it back. + +**Promised to `lucisv_server`**: everything the other port refactorings +promise. `convert_to_ansi` does not panic, returns no partial edit, sorts and +de-overlaps its edits, edits exactly one file, and produces no warnings at all. +`PortAction.title` is user-facing text the server does not rewrite — and +`(N ports)` is *not* a `sites_phrase`, so `ports::counted` leaves it alone +(`vlog_refactor::is_sites_phrase`, §50's own guard, already answers `false` for +it; no change was needed there). + +**Changed in `lucisv_server`** (protocol layer only): `CONVERT_TO_ANSI` +(`lucisv.convertToAnsi`) added to `ports::commands()` and to `ports::execute`. +The dispatch arm, the capability advertisement and both code-action paths +needed no change — commands are advertised from `commands()`, every +`workspace/executeCommand` already routes through `ports::execute`, and +`code_actions`/`offers` already fan out from `port_actions`. **The VS Code +extension needed nothing**: server commands are discovered over LSP. + +**Requested of nobody.** No change was needed in `vlog_parser`, +`vlog_semantic`, `vlog_formatter` or `lucisv_core`. + +## The LSP surface + +| Surface | What it says | +|---|---| +| Code action, kind `refactor.rewrite.lucisv.ports` | *"lucisv: convert ports to ANSI (2 ports)"* — offered with the cursor anywhere in a non-ANSI module's header, lazily (`offers` → `resolve`, §37.1) or eagerly (`code_actions`), whichever the client supports. | +| `lucisv.convertToAnsi [uri, Position]` | The same edit for a client with no lightbulb — a Vim user's keybinding. | + +The count is the ports the header declares, and it is exact in the offer +already: the conversion reads and edits one file. It is written `1 port` for +one, which is why the plan's *"(N ports)"* is a shape rather than a literal. + +## Status / TODO + +- [x] 51.1 `convert_to_ansi` engine (`ports/ansi.rs` + `ports/merge.rs`) and + every refusal above +- [x] 51.1 the §23.2.2.2 merge table, one behaviour test per row +- [x] 51.1 comments moved, never dropped, never joined; `check.rs`'s comment + rule restated with its attack tests +- [x] 51.2 code action through both offer paths, with `port_action_modules` + answering for a cursor anywhere in a non-ANSI header +- [x] 51.2 `lucisv.convertToAnsi` in `commands()` / `execute` +- [x] Tests: 54 behaviour tests in `vlog_refactor/tests/ansi.rs`, 14 attack + tests in `check.rs`, 2 corpus tests, 3 in `lucisv_server`'s `ports.rs`, + 1 e2e session over the wire — the rework added 2 behaviour tests (the + attribute refusal, both halves of the merge), 7 attack tests and one + `tests/ports.rs` test for the placeholder whitelist's realistic flow +- [x] Rework (QA 2026-09-05): V-1 `never_dropped` is an exact equation with + `wrote <= gone`; V-2 attributes refused by the conversion and counted by + the verifier +- [x] Gates: `cargo fmt` per crate, clippy `--all-targets` clean, the workspace + suite, the corpus gate, byte-identity vs 0.45.0, the VS Code smoke test +- [x] Corpus and OpenTitan census (see Acceptance — the count is **zero**, and + that is the finding) +- [ ] Deferred, deliberately: an `interface`'s non-ANSI header (refusal 5). An + interface body also holds `modport`s that name the same ports, and moving + a declaration into the header without reading them is not something to do + unverified. Worth a backlog line of its own. +- [ ] Deferred: the inverse refactoring (ANSI → non-ANSI), which nobody asked + for and which the test fixture in `tests/corpus.rs` shows is three lines + of text editing when it is ever wanted. +- [ ] Deferred: absorbing a declaration that also declares a local + (refusal 14) by *splitting* it first. A second refactoring, not this one. + +## Docs to apply at merge (lead) + +`README.md`, `docs/topo.md`, `docs/repository-analysis.md` and `docs/site/` are +the lead's; the text for them is here rather than edited in place. + +**`README.md` — the refactoring list** gains a row beside "expand `.*`": + +> | **convert ports to ANSI** | Rewrites a Verilog-2001 header +> (`module m (a, b);` plus `input a; output [7:0] b;`) as an ANSI one, merging +> each port declaration with the net or variable declaration that completes it +> (IEEE 1800 §23.2.2.2) and deleting both from the body. Code action anywhere +> in the header, or `lucisv.convertToAnsi`. | + +**`docs/site/` (editors / language-tools page)** — the same sentence in the +code-action list: *"convert ports to ANSI — a Verilog-2001 header rewritten the +modern way, with each body declaration merged into the port it described and +its comments carried along."* + +**TODO.md §8** (the refactoring backlog): the non-ANSI→ANSI line is annotated +*"— shipped in 0.46.0, `docs/features/ansi-conversion/README.md`"* (done in +this branch), and the list gains a backlog entry: *"convert an `interface`'s +non-ANSI header (needs the `modport`s that name the same ports read first)."* + +**`docs/topo.md`**: no new edge. `vlog_refactor ──▶ vlog_formatter` +(dev-dependency, tests only) already exists from §50 and is what the two new +corpus tests use. + +## Work log + +**2026-09-05 — dev agent.** Built `ports/ansi.rs` + `ports/merge.rs`, the +fourth `port_actions` offer, the fifth command, and one change to `check.rs`. +The decisions worth recording: + +- **Insertions, not a replacement — and the verifier is why.** The obvious + edit is "replace the port list with the ANSI one". It cannot work, and the + reason is worth writing down: a non-ANSI port's symbol lives in the *header* + (the body declaration is only its `detail_span`), so every body reference to + the port anchors at the header name. Replacing the element moves that anchor, + `Shift::map` maps the old span onto the whole replacement, and + `verify_splice`'s resolution check refuses — correctly, since from its point + of view a declaration moved. Inserting around the untouched name leaves every + anchor where the map predicts. The happy consequence is that the header's + layout and its own comments are never touched, and `Plan::expected` is the + *unchanged* shape, which is the strongest thing the shape check could say. +- **`check.rs`'s comment rule had to be restated, and it came out stricter.** + The old rule was "no deletion may cover a comment", which exists because a + comment deleted from both sides of the piece comparison passes unnoticed. + This refactoring must delete a declaration a comment is attached to and write + that comment somewhere else, so the rule is now stated over the text: + **every comment the file had, it still has**, matched by exact text and + counted, so two identical comments must still be two. That is stronger than + the rule it replaces — it catches a comment *rewritten* or *duplicated* by an + edit, which the old rule never looked for — and it is one-directional, since + a refactoring may legitimately write a comment (`add_port`'s + `/* TODO: connect */`, which the first draft of this rule wrongly refused and + the existing suite caught within a minute). Seven masked-corruption attack + tests ship with it (CLAUDE.md invariant 4): the honest conversion verifies; + one of two identical comments dropped, a comment rewritten to the same + length, a comment truncated, a comment written back in the wrong place, a + comment written *twice*, and a deletion nothing writes back are all refused. + The pair the budget-only and the search-only formulations each forgive is in + there by name. +- **The duplication half of that rule caught a real bug in this very + refactoring.** A declaration that declares two ports (`input a, b; // both`) + is absorbed by both of them, and the first draft carried its comment onto + each — one comment in, two out. Nothing was dropped, so invariant 3 was + intact; the piece comparison could not object because it checks the edits + against themselves and the duplicate was *in* the edits. The planner now + hands each declaration's comments to the first port that claims it, and + `comments_kept` refuses a comment a deletion covers being written back a + different number of times — so the same class of bug is a refusal rather + than output, whoever writes it next. Found by review, pinned by a behaviour + test and by the seventh attack test. +- **Two comments never become one.** The lexer merges every comment following a + token on one line into a single trailing comment, so writing `// a` beside a + port that already carries `// b` produces one comment where the verifier + expects two — a refusal, not corruption, but a pointless one. The planner + therefore places at most one comment beside a port and puts the rest on their + own lines above it. Everything about comment placement is a *fallback chain* + ending in a refusal sentence, never a guess. +- **The merge is a table, and it is small.** §23.2.2.2 fits in one function + once "the port declaration is complete" is named. The only judgement call is + what to refuse rather than express: an initialiser, a qualifier, a net delay, + an anonymous aggregate or a parameterized type reference are all things + lucisv could textually move into a port list and none of them is something it + should decide to move for the user. Each is a sentence. +- **`(N ports)` is not a sites phrase, and §50 already made that safe.** The + server's `counted` rewrites an offered title's parenthesised tail from its + index; `is_sites_phrase` — added in §50 after exactly this bug — answers + `false` for `"2 ports"`, so nothing had to change. The server test asserts + the offered title character-for-character anyway. +- **The corpus and OpenTitan hold no non-ANSI headers at all.** See Acceptance. + This is the round's one real deviation from the plan, and it is a fact about + the world rather than a gap in the work: the acceptance material had to be + manufactured out of real ANSI headers instead, which turned out to be a + better test than the plan's. + +No `unwrap`/`expect`/`panic!` and no `unsafe` in any library path (test modules +only). `ansi.rs` is 464 lines (362 of them code) with no function over 50; +`merge.rs` 325 (254 code) with none over 65; every file touched stayed inside +the size rule — `ports/mod.rs` 494, `check.rs` 1 068 of which 363 are its +`#[cfg(test)]` module, `lucisv_server/src/ports.rs` 1 511 of which 1 053 are +tests. + +**2026-09-05 — rework (dev agent), after QA's REWORK verdict.** Two findings, +both in the safety net rather than in the shipped output; neither reached a +user, and both are closed by making the verifier stricter. + +- **V-1 — the rule is now an equation, not an inequality.** `comments_kept` + bounded an untouched comment only from below ("before ⊆ after"), so two + insertions could each write a third copy of a comment nothing deleted and + the verifier said `Ok`. The rule is renamed `never_dropped` and restated as + three equations over every piece text, with `had`/`has` the file's counts + before and after, `gone` the old pieces a non-empty edit range covers and + `wrote` the pieces lexed out of the edits' own inserted text: + **(1) `has >= had`** — nothing is ever lost, which is invariant 3 and all + the old rule had; **(2) `wrote <= gone`** unless the text is one the engine + generates — a piece is written back *where it was deleted* and nowhere else; + **(3) `has == had − gone + wrote`** — the applied text says exactly what the + edits say. +- **Why (2) is `wrote <= gone` and not "may not write a text the file already + has outside the edits".** The latter was the shape the plan proposed, and it + is both too weak and too strong. Too weak: it forgives the + `input a, b; // both` bug, where the comment *is* deleted and *is* written + twice — the attack test that already existed would have regressed. Too + strong: it refuses an honest conversion of a file that writes `// unused` + on an absorbed declaration *and* somewhere untouched, where `wrote = gone = + 1` and nothing is duplicated at all. `wrote <= gone` refuses QA's V-1 pair + and the doubled comment, and refuses no honest edit in the suite. +- **The whitelist, choice (a), and the evidence for it.** With (2) stated that + way, *any* comment a planner invents needs an exemption, so `generated()` + names the one text lucisv writes itself — `/* TODO: connect */`, from + `ports/add.rs` and `ports/propagate.rs`. It is not a judgement call: stubbing + `generated()` to `false` fails six tests, four of them pre-existing + (`a_connection_with_no_signal_of_that_name_is_left_as_a_todo`, + `propagating_adds_only_the_connections_that_are_missing`, + `propagating_needs_to_know_which_instance_when_a_statement_declares_several`, + `a_port_refactoring_finds_an_interface_the_way_it_finds_a_module`). The + realistic flow the plan asked about is pinned by a new behaviour test, + `a_second_port_may_leave_a_second_todo_where_the_first_one_already_is`: a + module gains its ports one at a time, so the second `add_port` finds the + first one's placeholder already in the file and writes another. +- **V-2 — attributes, in both halves.** The *conversion* now refuses a + declaration that carries an attribute instance + (`ports/ansi.rs::attributes_clear`, refusal 23) rather than deleting it with + the declaration; refuse rather than move, because where a `(* ... *)` belongs + in an ANSI port list — and whether one may be split across the ports a + multi-name declaration declares — is a design question, now a TODO §8 backlog + line. The *verifier* treats an attribute as a never-dropped piece exactly as + it treats a comment. `pieces` was never the hole: `TokenKind::Attribute` is a + real token and `Piece::Code` has always carried it, so an attribute outside + an edit was already pinned. The hole was the same one comments had — a piece + inside a deleted range vanishes from *both* sides of the comparison — and it + is closed by counting attributes in `never_dropped` beside comments, keyed by + the noun the refusal uses (`attributes are never dropped`). That covers every + refactoring, not only this one: any edit that deletes a `(* ... *)` without + writing it back is now refused. +- **The attack tests (CLAUDE.md invariant 4).** Seven new, on top of the seven + §51 shipped. In `check.rs`: + `an_insertion_that_duplicates_an_untouched_comment_is_rejected` (QA's V-1 + pair, three copies out of one), `a_generated_placeholder_may_be_written_where + _the_file_already_has_one` (the whitelist, accepted), + `an_application_that_grew_a_copy_the_edits_do_not_write_is_rejected` + (equation 3 — honest edits, corrupted application), + `a_comment_written_back_inside_a_string_or_another_comment_is_rejected` (the + lexer must see a comment, not a substring — both halves), + `a_deletion_that_swallows_an_attribute_is_rejected`, + `an_edit_that_moves_an_attribute_verifies` and + `an_edit_that_rewrote_an_attribute_is_rejected`. In `tests/ansi.rs`, two + behaviour tests pin refusal 23 on both halves of the merge. +- **No test without a guard it proves.** QA's note that four of the seven + existing attack tests were really caught by the piece-order comparison is + answered one by one. Three of them — + `a_move_that_kept_only_one_of_two_identical_comments_is_rejected`, + `a_move_that_dropped_a_comment_and_invented_another_is_rejected` and + `a_move_that_shortened_a_comment_is_rejected`, the last of which gained the + assertion — now assert `comments are never dropped`, which only + `never_dropped` says and which it says first, so neutering it breaks them. + The fourth, `a_move_that_left_the_comment_where_it_was_is_rejected`, is + honestly the piece comparison's: every count is equal on both sides, and its + doc comment now says so and asserts that guard's own sentence. It is also + the plan's "a comment deleted here and written back somewhere unrelated" — + placement is bound to the edits, not to the totals. + `a_splice_that_also_dropped_a_comment_is_rejected` gained the same treatment. +- **Nothing legitimate was refused.** The stricter rule refuses no edit any of + the five port refactorings produces: `cargo test -p vlog_refactor` is green + with no change to any existing expectation, and the §51 corpus round trips + and census are unchanged. `check.rs` measures 566 production lines (566 < 600), + so the comment/attribute rule stays where it is; `never_dropped` is 63 lines + (three passes and their three sentences) and nothing else grew. + +## Gates + +All guarded (`tools/guard.sh`, 8 GB / 30 min defaults); no guard kill. + +- **fmt**: `cargo fmt -p vlog_refactor`, `cargo fmt -p lucisv_server`; + `cargo fmt --all -- --check` clean. +- **clippy**: `cargo clippy --all-targets`, **0 warnings**, and no new + `#[allow]` anywhere in the diff — the one this round nearly needed + (`clippy::type_complexity` on a returned pair) was removed by naming the + pair `merge::Body` instead. +- **suite**: `cargo test --workspace` — **3 941 passed, 0 failed, 44 ignored** + across 51 test binaries (baseline 3 876, **+65**: 52 behaviour, 7 attack, 2 + corpus, 3 server unit, 1 e2e). +- **corpus gate**: `tools/corpus_check.sh` — **814/820** (804 would-reformat + + 10 ok-unchanged), the same six known parse errors, **0 verification errors, + 0 crashes**. +- **formatter byte-identity**: `lucisv format --stdout` over all corpus files, + this build vs `~/.cache/lucisv-baselines/lucisv-0.45.0` — **860 total, 854 + checked identical, 0 differing**, 6 refused by both. `git diff` over + `vlog_formatter`, `vlog_parser` and `verify.rs` is empty; this round touched + neither. +- **vsix smoke**: `node editors/vscode/smoke.js target/release/lucisv-server` + — OK, 20 messages. +- **opentitan after the round**: `git -C ~/repo/opentitan status --porcelain` + shows only the three pre-existing modifications. Every run over it was + read-only, and every edited copy went to the session scratchpad. + +**Re-run after the 2026-09-05 rework**, same guard, no guard kill: + +- **fmt**: `cargo fmt -p vlog_refactor`; `cargo fmt --all -- --check` clean. +- **clippy**: `cargo clippy --all-targets`, **0 warnings**, no new `#[allow]`. +- **suite**: `cargo test --workspace` — **3 951 passed, 0 failed, 44 ignored** + across 51 test binaries (**+10** on the round's own 3 941: 7 attack tests in + `check.rs`, 2 behaviour tests in `tests/ansi.rs`, 1 in `tests/ports.rs`). + Not one existing expectation changed to make the stricter rule pass — the + five port refactorings' suites are green as written, so nothing legitimate is + refused. +- **corpus gate**: `tools/corpus_check.sh` — **814/820 (99.3 %)**, 10 + ok-unchanged, the same six known parse errors, **0 verification errors, 0 + crashes**; the §51 corpus round trips and the non-ANSI census are unchanged. +- **file size**: `check.rs` 566 production lines, under the 600 threshold, so + the comment/attribute rule stayed in place rather than moving to + `check/comments.rs`. + +## Acceptance + +### The corpus, and OpenTitan: zero non-ANSI headers + +**Deviation from the plan, stated plainly: there is nothing to convert in +either tree.** The plan asks for a census of `PortList::NonAnsi` modules across +`corpus/` and ten conversions under OpenTitan's `hw/`. Both counts are **zero**: + +| Tree | Files | `PortList::NonAnsi` modules | +|---|---|---| +| `corpus/` (common_cells, ibex, opentitan, picorv32) | 860 | **0** | +| `~/repo/opentitan` (all of it) | 3 979 | **0** | + +Cross-checked against the AST census with a text grep for a body port +declaration (`^\s*(input|output|inout)[^;()]*;`): 18 files in the corpus and 47 +under OpenTitan match, and **every one of them** is an `interface` body, a +`function`/`task` argument list, or an ANSI header whose `output ...;` line is +inside a function — not a single non-ANSI module header. Even picorv32, the +oldest code in the corpus, writes `module picorv32 #(...) (input clk, ...)`. + +The census is nevertheless shipped as a test +(`every_non_ansi_module_in_the_corpus_converts`) rather than as a number: it +converts *every* non-ANSI module it finds and asserts the properties on each, +so it stays honest the day the corpus gains one. + +### Real RTL, made non-ANSI and converted back + +Since the world's non-ANSI headers are not in these two trees, the acceptance +material is manufactured out of real ANSI ones. A corpus module's ANSI port +list is rewritten the Verilog-2001 way — each element replaced by its own name, +each declaration moved into the body verbatim, layout otherwise untouched — and +`convert_to_ansi` is asked to undo it. Three properties per module: + +* the result **parses with no diagnostic**, formats, and formatting it twice + does not move it; +* its module declares the **same ports, in the same order, with the same + direction, net type, data type, signing, packed range and unpacked + dimensions** as the module the tree actually ships; +* and the file's comment count is unchanged. + +Not byte-identity after formatting: the formatter preserves the *author's* +column alignment in an ANSI port list, and a refactoring writes edited source +rather than formatted source, so the hand-alignment the corpus wrote is not +something the conversion undertakes to reproduce. (The first draft asserted +byte-identity and this is what it found — recorded because it is the honest +limit of the property.) + +`an_ansi_header_written_the_2001_way_converts_back_to_itself` in +`crates/vlog_refactor/tests/corpus.rs` does five of these in the shipped suite +(~2.4 s each in debug, the index build over 860 files): `binary_to_gray`, +`boxcar`, `cc_onehot`, `cdc_2phase` and `cdc_2phase_clearable`. + +### OpenTitan (read-only) + +The same round trip over `hw/ip`, run from a throwaway probe +(`tests/zz_census.rs`, never committed) with every edited copy written into the +session scratchpad: + +| | | +|---|---| +| files under `hw/ip` | 1 807 | +| `PortList::NonAnsi` module headers | **0** | +| files holding a module the fixture can rewrite | 291 | +| round trips **fully verified** | **290** | +| refused by the conversion | 0 | +| failed | 1 — `kmac/pre_dv/kmac_reduced_tb/rtl/kmac_reduced_tb.sv` | + +The one failure is not the conversion's: its parse, its port signature and its +comment count are all correct, and only the *formatter* half of the check +fails — because `lucisv format` already refuses that file as it ships +(`parse error: 53:3: expected expression (found ")")` — a trailing comma in a +`#( ... )` parameter override list, `kmac_reduced #( .EntropyWidth(...), )`). +Pre-existing, unrelated to this round, and worth a line of its own to the lead. + +A single-file scope is used per conversion rather than the whole 1 807-file +index, since this refactoring reads and edits exactly one file; the shipped +corpus test uses the full 860-file scope and agrees. + +`git -C ~/repo/opentitan status --porcelain` shows only the three pre-existing +modifications (`hw/ip/aes/dv/tb/tb.sv`, +`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`) +before and after. Nothing was written into the repository. + +## QA log + +**2026-09-05 — QA agent.** Verified against the plan (TODO §51) and this +README, with `git diff` reads of every file the Handshakes section names, +targeted attack tests against `check.rs`'s new `comments_kept` (added as +extra `#[test]` functions, run, then removed — the tree is unchanged apart +from this log and the TODO checkbox), engine probes through +`convert_to_ansi`/`vlog_formatter::format_source` (same in/out discipline), +an independent re-derivation of the OpenTitan census on scratch copies, and +the full gate battery, all through `tools/guard.sh`. No guard kill. + +### Priority 1 — the verifier (`comments_kept`, CLAUDE.md invariant 4) + +Read `comments_kept` line by line (`crates/vlog_refactor/src/check.rs:499-544`). +Its two halves: (a) every comment text in `old` must have a match in `new` +(a plain multiset "before ⊆ after" by exact text, no position check), and +(b) for a comment whose **span was itself covered by a non-empty-range +edit** (`moved`), the count of its text in `new` must equal the count in +`old`. Attack table (pair → verdict): + +| # | Attack | Verdict | +|---|---|---| +| 1 | Honest ANSI conversion output | **verifies** (dev's own test, reconfirmed) | +| 2 | One of two identical comments dropped after a real conversion | **REJECTED** — but via the *piece-order* comparison (`would lose the comment`), not via `comments_kept`'s count check. Confirmed by neutering `comments_kept` (env-gated stub, scratch-only, reverted): the test's `is_err()` still held, only its specific `message.contains("comments are never dropped")` assertion broke, because the rejection now came from a different message. **Not a gap** — the outcome is still correctly refused — but it means this attack test does not actually exercise `comments_kept` in isolation the way its comment claims. | +| 3 | A dropped comment "replaced" by an invented one of different text, same position | **REJECTED**, same caveat as #2 — piece-order comparison catches it (`would write the comment ... where ... belongs`), `comments_kept` is not the operative guard here either. | +| 4 | Comment shortened after a real conversion | **REJECTED** — piece-order comparison again, not `comments_kept`. | +| 5 | Comment left in the body instead of moving to the header (position swapped, count intact) | **REJECTED** — piece-order comparison (position is part of what the edits promise). | +| 6 | One declaration's comment written onto **two** ports, via edits that are internally self-consistent (the dev's own found bug, reproduced) | **REJECTED**, and **only** by `comments_kept` — neutering it turns this into `Ok(())`. This is a true, load-bearing dependency. | +| 7 | A deletion that covers a comment; nothing writes it back | **REJECTED**, and **only** by `comments_kept` (its first half). Neutering it turns this into `Ok(())` — the exact case the old rule existed for. | +| 8 (new, QA) | **A comment duplicated where the original is left completely untouched** — no edit's range overlaps the original comment's span; a second, independent insertion elsewhere writes the identical text | **FORGIVEN — Ok(())`.** See finding V-1 below. | +| 9 (new, QA) | Comment rewritten with different whitespace only (`// the note` → `// the note`) | **REJECTED** (exact-text compare, no normalization). | +| 10 (new, QA) | Moved comment's text written nested inside a *surviving* block comment (`/* keep */` → `/* keep // moved */`) rather than as its own piece | **REJECTED** — the lexer sees one comment with new text, not two, so the original text reads as dropped. | +| 11 (new, QA) | Comment text that is a substring of another comment in the same file (`// a` vs. `// a and more`) | **Not confused** — exact string equality, verified against an unedited file (`comments_kept` on identity input returns `Ok`). | +| 12 (new, QA) | A `//` written back mid-line with no following newline, swallowing the rest of the file into the comment | **REJECTED**, and rejected by the **token/piece comparison before the parse-diagnostic check is ever reached** (`pieces_match` alone returns `Err`; `verify_splice`'s "no new diagnostic" gate is redundant here, not the first line of defense). | + +**Finding V-1 (HIGH).** `comments_kept`'s "written back exactly once" half +(`crates/vlog_refactor/src/check.rs:531-541`) only runs `if moved` — i.e. +only for a comment whose **own span** was overlapped by a non-empty-range +edit. A comment whose span nothing deletes is checked *only* by the +first half's "before ⊆ after" pass, which requires the text to still be +present at least once but places **no upper bound** on how many times it +may now appear. Reproduction (as a temporary test against `pieces_match`, +removed after confirming): + +``` +before: "module m (\n a,\n b\n);\n input a; // shared\n output b;\nendmodule\n" +edits: two pure insertions (empty ranges), each writing " // shared" + after the header names `a` and `b`; nothing deletes or even + overlaps the body's own "// shared". +after: the same text 3 times (1 original + 2 inserted copies) +result: pieces_match(...) == Ok(()) +``` + +This is not exploitable through today's `ports/ansi.rs` (its `claimed` +vector already prevents attaching one declaration's comment to more than +one port, and every comment it moves comes from a declaration it also +deletes — see the work log's account of the bug it *did* catch), so it is +not corrupting anything the shipping planner produces. But it is a real, +untested hole in the invariant-4 safety net itself: a future planner bug +that duplicates an *untouched* comment's exact text elsewhere in the file +— rather than one it is actively deleting — passes verification silently. +The rule's own doc comment says "a comment nothing deleted" may be freely +*written* (true, and needed for `add_port`'s `/* TODO: connect */`), but +the implementation doesn't distinguish "genuinely new text" from "a second +copy of an existing comment's exact text," which is the case that matters. +Recommend: extend the equality check to every text present in `before` +with count > 0, not only the ones whose span is `moved` — or, if that's +judged too strict for legitimate cases, at minimum ship a masked-corruption +attack test for this pair so the gap is a documented, accepted risk rather +than an untested one. + +**Everything else Priority 1 asked for held.** No finding for the +"different owner, same text" case (e.g. two ports' comments swapped): that +is a placement-correctness question the piece-order comparison settles +only when it is fed a *corrupted-after-the-fact* text that disagrees with +the literal edits; it is not a new gap introduced by `comments_kept`, and +placement correctness is what `tests/ansi.rs`'s behaviour tests (leading +above, trailing beside, at-most-one-beside) already pin. + +### Priority 2 — the conversion + +Read `merge.rs` and `ansi.rs` in full; every §23.2.2.2 table row and every +one of the 20 pinned refusals has its own test in `tests/ansi.rs` (52 +tests, confirmed present by name). The multi-name-declaration bug pin +(`a_comment_on_a_declaration_of_two_ports_is_written_once`, `input a, b; // +both of them` → one comment, on the first port only) is present and +correct. + +QA's own probes (temporary `#[test]`s in `tests/ansi.rs`, removed after +running) against scenarios not named in the 52: attribute on the absorbed +declaration, `inout`+`tri`, `input signed`/`wire signed` combination, +escaped port name, a port named `inputs` (keyword-prefix collision), the +three-declaration case (`output b; reg b; wire b;`), idempotency plus a +formatter-fixpoint check on the converted output, and a body declaration +also referenced inside an `always` block. Results: + +| Probe | Result | +|---|---| +| `inout b; tri [3:0] b;` | `inout tri [3:0] b` — correct | +| `input signed a; wire signed a;` | `input wire signed a` — correct, signing not duplicated | +| Escaped port name `\my$sig ` | `input \my$sig ;` — correct | +| Port named `inputs` | `input inputs` — correct, no substring false-positive | +| `output b; reg b; wire b;` | refused ("declares `b` twice outside its port declaration") — correct | +| Re-running the converted output | refused ("already declares its ports ANSI-style") — correct, idempotent | +| Formatting the converted output twice | fixpoint — correct | +| `reg b;` also driven in an `always` block, header port `b` | converts; the always block's reference to `b` still resolves to the ANSI port — correct | +| `(* keep *) input a;` | **the attribute is silently deleted** — see finding V-2 | + +**Finding V-2 (HIGH).** An attribute instance on an absorbed body +declaration is silently dropped. `Item.span` is documented as including its +`(* ... *)` attributes (`crates/vlog_parser/src/ast/mod.rs:157,330`), and +`ansi.rs`'s `carried()`/`deletions()` delete the item's whole span; only +`Meta::leading`/`Meta::trailing` **comments** are read out and carried +anywhere (`ports::ansi::Carried`) — attributes are never inspected. Nothing +in `merge.rs`'s refusal list (initialiser, qualifier, net delay, fancy +type) mentions attributes either. Reproduction: + +``` +input: "module m (a);\n (* keep *) input a;\nendmodule\n" +output: Ok("module m (input a);\nendmodule\n") +``` + +`(* keep *)` (or `dont_touch`, `mark_debug`, any synthesis attribute) is +gone, with no refusal and no warning. This is not covered by invariant 3 +(comments only) and not visible to `check.rs`'s resolution check (attributes +aren't symbols or references), so nothing in the safety net catches it — +this is planner-level silent data loss, not a verifier gap. Unlike a +dropped comment this can change **synthesis behaviour**, which makes it +arguably more serious than the comment-loss class invariant 3 was written +for. Recommend either refusing a declaration that carries an attribute +(same shape as the qualifier/initialiser refusals) or moving it into the +ANSI port list, with a masked-corruption test either way. Not fixed by QA +— this is a planner design decision, not a small unambiguous fix. + +### Priority 3 — round-trip acceptance + +Ran the dev's own five corpus round trips and the census test under guard +(`cargo test -p vlog_refactor --test corpus -- --nocapture`): both green, +identical output to the dev's account — `corpus non-ANSI module headers: +0`, five round trips (`binary_to_gray`, `boxcar`, `cc_onehot`, `cdc_2phase`, +`cdc_2phase_clearable`), 0 refused. + +**Independent OpenTitan re-derivation** (own script, read-only, `~/repo/ +opentitan/hw/ip`, scratch-only edited copies, removed after running): +1780 files scanned (dev: 1807 — the gap is `.sv`/`.v` extension filtering, +not a discrepancy in the conversion), **0** `PortList::NonAnsi` headers +(matches), **291** files holding a module the round-trip fixture can +rewrite (**exact match** with the dev's 291). Sampled 30 (every 9th of +291): 24 fully verified (parses, same port signature, same comment count, +formats and converges), 0 failed, 6 refused — but the 6 refusals are an +artifact of QA's own script using the **whole 1780-file workspace** as +scope rather than the dev's single-file-per-conversion scope, which +surfaces `prim_*` module-name collisions across `prim_xilinx`/ +`prim_generic`/`prim_asap7` variants that a single-file scope never sees. +Not a defect in the conversion. Directly re-confirmed the dev's one +opentitan failure: `lucisv --check .../kmac_reduced_tb.sv` reproduces +`parse error: 53:3: expected expression (found ")")` byte-for-byte as +claimed, pre-existing and unrelated to this round. + +**Five QA-constructed round trips, deliberately different from the dev's +five and deliberately comment-bearing** — worth calling out because the +dev's own fixture (`tests/corpus.rs::as_non_ansi`) explicitly bails out of +any ANSI port list containing a comment (`if list.contains("//") || +list.contains("/*") { return None; }`), so neither the shipped 5-module +round trip nor the OpenTitan census ever exercises a *real* comment-bearing +RTL header — only the synthetic ones in `tests/ansi.rs`. QA wrote an +independent generator that keeps a port's own leading/trailing comment and +moves it into the fabricated body declaration, run against `common_cells`: +`sync.sv`, `max_counter.sv` (10 ports, each with a trailing comment), +`fall_through_register.sv`, `lfsr.sv`, `lzc.sv` (leading `///` doc comments +on every port). All 5/5 round-tripped: parse clean, same port signature, +same comment count, format and converge, and each comment landed on its +own line above the port it described exactly as the Comments section says. +This is a genuine coverage gap closed by QA rather than a defect — noting +it so the dev/lead can decide whether to fold a comment-bearing corpus +fixture into the shipped suite. + +### Priority 4 — server wire + +Read `crates/lucisv_server/src/ports.rs` and `tests/e2e.rs` diffs in full +against the LSP surface table. `CONVERT_TO_ANSI`/`lucisv.convertToAnsi` is +listed in `commands()`, dispatched in `execute`, and the e2e test +(`the_ansi_conversion_is_offered_resolved_and_commanded_over_the_wire`) +exercises all five wire behaviours the plan named: advertised command, +offer with port count and no edit, command answer with the insertions/ +deletions, a body-position refusal as `RequestFailed` with the engine's +sentence, and `codeAction/resolve` returning the same edit. Read +`in_non_ansi_header` (`ports/mod.rs`): returns `false` immediately for an +`PortList::Ansi` module (confirmed: the offer cannot appear in an ANSI +header), and treats any offset from the module keyword up to the first +body item (leading comments included) as "header" for a non-ANSI module — +correct given `module_at` already guarantees the offset is inside the +module's own span before this function is reached. Confirmed +`is_sites_phrase("2 ports")` is `false` by inspection (`phrase != +"no instantiation in scope"` and does not start with `"updates "`), so +`ports::counted` leaves the ANSI title untouched — matches the claim, no +test needed beyond reading the two functions side by side. + +### Gates + +All guarded, no guard kill: + +- `cargo fmt --all -- --check`: clean. +- `cargo clippy --all-targets`: **0 warnings** (re-ran on the tree with + every QA probe removed). +- `cargo test --workspace`: **3941 passed, 0 failed, 44 ignored** — exact + match to the dev's reported baseline. +- `tools/corpus_check.sh`: **814/820 parsed & formattable (99.3%)**, 10 + ok-unchanged, 6 parse-error (the same six known ones), **0 + verification-error, 0 crash**. +- Byte-identity: `lucisv format --stdout` over all 820 corpus files vs + `~/.cache/lucisv-baselines/lucisv-0.45.0` — 814 checked, **0 differing**, + 6 refused by both. +- `node editors/vscode/smoke.js target/release/lucisv-server`: **OK, 20 + messages**. +- OpenTitan: `git -C ~/repo/opentitan status --porcelain` showed only the + three pre-existing modifications before and after every QA read. + +Noted but out of scope for this log: `CHANGELOG.md`, `editors/vscode/ +CHANGELOG.md` and `editors/vscode/README.md` acquired uncommitted 0.46.0 +entries during this QA session that QA did not make — flagged to the lead +as a fact, not investigated further (outside the file set this QA pass +owns). + +**Verdict: REWORK** — not because anything shipped is broken (nothing QA +found reaches the shipping planner: V-1 is unreachable through today's +`ports/ansi.rs`, and no corpus/OpenTitan file exercises V-2), but because +CLAUDE.md invariant 4 requires masked-corruption attack tests for every +widening of the verifier's forgiveness, and V-1 is a widening with none. +Two items before this closes clean: + +1. **V-1**: either tighten `comments_kept` so an untouched comment's text + cannot be silently duplicated, or add a masked-corruption attack test + documenting the accepted gap (dev + lead's call which). +2. **V-2**: a decision on attributes — refuse (safe, matches the existing + qualifier/initialiser refusals) or carry them into the ANSI port list — + with a test either way. Silent attribute loss should not ship + unaddressed given it can change synthesis results, not just comments. + +Everything else — the merge table, the 20 refusals, the wire surface, the +corpus and OpenTitan acceptance, and all five gates — verified clean and +is ready to merge as soon as V-1 and V-2 are resolved. + +### 2026-09-05 — Re-attack of the rework + +Re-attacked `check::never_dropped` (replacing `comments_kept`) and +`ports::ansi::attributes_clear` against V-1 and V-2, per CLAUDE.md invariant +4: every widening of the verifier's forgiveness is guilty until proven +innocent. All probes were temporary `#[test]` functions in `check.rs`'s own +test module and `tests/ansi.rs` (plus one neutering pass that stubbed +`never_dropped` to `Ok(())`), run under `tools/guard.sh`, removed afterward. +`git diff`/`git status` confirm `check.rs` and `tests/ansi.rs` carry only the +dev's rework — no residue. + +**Attack table** (pair → verdict; "gone"/"wrote"/"had"/"has" as the dev's +equations name them): + +| # | Attack (task's numbering) | Verdict | +|---|---|---| +| 1.1 | Untouched comment `// x`, one insertion writes `// x` again (`gone=0, wrote=1`) | **REJECTED** — "comments are never duplicated" (equation 2) | +| 1.2 | Whitelist text (`/* TODO: connect */`) written where the file had zero | **ACCEPTED** | +| 1.2b | Whitelist text written **twice** by two insertions where the file had zero | **ACCEPTED** — unbounded, by design (see finding QA-1 below) | +| 1.3 | Whitelist text deleted once (`gone=1`), written back **twice**, with **no separator** between the two copies | **REJECTED**, but for a reason unrelated to the intended attack: the lexer merges the two adjacent, unseparated `/* TODO: connect */` block comments into *one* trailing comment whose text is `/* TODO: connect */ /* TODO: connect */` (a space inserted), which no longer equals the whitelisted key, so equation 1 (`has >= had`) fires as "would delete the comment". Confirmed by dumping `tokenize()`'s `trailing` field directly. | +| 1.3b | Same, but comma-separated the way `add_port`/`propagate_ports` actually write two placeholders (`.a(/* TODO: connect */), .b(/* TODO: connect */)`, one deleted, both rewritten) | **ACCEPTED** — this is the realistic shape, and it verifies. See finding QA-1. | +| 2.1 | Two `// a` comments, one deleted+rewritten in place (no-op), one untouched | **ACCEPTED** | +| 2.2 | Applied text drops the untouched `// a` instead of the deleted one (`has=1`) | **REJECTED** by `never_dropped`'s equation 1 directly (`"would delete the comment"`), not by piece order — confirmed by calling `never_dropped` in isolation, which alone returns the same `Err`. | +| 2.3 | Applied text relocates the *untouched* `// a` to a distant, non-merging line while the edit's own `// a` stays exactly where the edit wrote it (counts stay balanced, `has == had == 2`) | `never_dropped` alone: **`Ok(())`** (it is text-only, no position). `pieces_match` as a whole: **REJECTED** — `"would write the token `output` where the comment `// a` belongs"`. The piece-order comparison is the guard for this one, confirmed by calling both separately. (First draft of this attack accidentally placed both copies on the same source line, which the lexer's comment-merging folded into one piece and made `never_dropped` itself reject — corrected to isolate the intended guard.) | +| 3.1 | Insertion text `// x` lands, in the full file, *inside a string literal's content* (`$display("a// xb")`) — never a real comment in `after` | **REJECTED** — `"comments are never duplicated ... without deleting it"`. This is `wrote` overcounting: it is computed by lexing `edit.new_text` alone (`pieces(&edit.new_text)`, `check.rs:407`), context-free, so `// x` counts as a comment piece even though in context it is swallowed into a string token. The direction is safe (a false rejection, not a forgiven corruption) but it is a real context-free-lexing gap in `wrote`, worth a comment in the code — see finding QA-2. | +| 3.2 | Insertion of `*/` that closes an already-complete block comment early (`/* note */` → insert `*/` before the real closer, giving `/* note*/ */`) | **REJECTED** — by `never_dropped` equation 1 (the comment's text changed from `/* note */` to `/* note*/`, a straight count/text mismatch), not by the "still parses" gate. | +| 3.3 | Insertion of a bare `/*` that opens an unterminated block comment swallowing the rest of the file | **REJECTED** at the very first step of `pieces_match` — `pieces(after)` returns `None` because the corrupted file no longer lexes at all (`"would no longer lex after an edit"`). This fires before `never_dropped` and before `verify_splice`'s "no new parse diagnostic" check ever runs — confirmed via both `pieces_match` alone and the full `verify_splice` path. | +| 3.4 | A brand-new (non-whitelisted, non-moved) comment inserted at EOF with no trailing newline | **REJECTED** — `"comments are never duplicated ... without deleting it"`. Not a bug: rule 2 refuses *any* comment insertion that is neither the exact generated whitelist text nor a piece moved out of a deletion, EOF or not. First draft of this test wrongly asserted the opposite; corrected. | +| 3.5 | `//` inserted immediately before an existing `// existing` on the same line | **REJECTED** — the two merge into one trailing comment (`// new // existing`), which fails equation 1 against the original `// existing` text. | +| 4.1 | `(* a *) (* b *) input a;` — two attributes on one absorbed declaration | **REJECTED** by `attributes_clear` (reports the first: `` `(* a *)` ``) | +| 4.2 | `(* keep *)` inside a `//` comment (`// (* keep *)` above a port) | **Not treated as an attribute** — converts cleanly, the comment (not an attribute) moves onto the port intact. Confirmed the lexer's comment scan consumes the whole line before the attribute-detection branch is ever reached (`lexer.rs`'s `//`/`/*` dispatch precedes the `(* ... *)` dispatch). | +| 4.3 | `"(* keep *)"` as a string literal's content | **Not treated as an attribute** — converts cleanly, string untouched. | +| 4.4 | `(* keep *)` on an **`always` block**, not on any absorbed port declaration, in the same module being converted | **Not refused** — `attributes_clear` only inspects `absorbed[].items`, so a non-absorbed item's attribute is invisible to it and survives verbatim in the output, confirmed byte-for-byte. | +| 4.5 | An absorbed declaration and an unrelated attributed declaration crammed onto the **same source line** (`input a; (* keep *) wire w;`) — attacking `list::whole_line`'s deletion-range widening | **Not swept** — `whole_line` only widens a deletion to the full line when everything *outside* the item's own span on that line is whitespace; a real neighboring token blocks the widening, so the sibling's attribute survives untouched. Confirmed by direct conversion. | +| 4.6 | Verifier-level attribute checks (deleted-not-rewritten, moved, rewritten) | Already exercised by the dev's own `an_edit_that_moves_an_attribute_verifies` / `a_deletion_that_swallows_an_attribute_is_rejected` / `an_edit_that_rewrote_an_attribute_is_rejected`; re-run and re-read, no changes needed. | +| 5 | Whitelist completeness: `grep -rn '"[^"]*//[^"]*"\|"[^"]*/\*[^"]*"' crates/vlog_refactor/src/ports/*.rs crates/vlog_refactor/src/rename/*.rs` | Exactly two call sites produce a comment-shaped string literal that is ever written into an edit (`ports/add.rs:469`, `ports/propagate.rs:112`), both `/* TODO: connect */` verbatim — matching `generated()`'s only whitelisted text exactly. No second generated text found; `rename/*.rs`'s only hits are test fixtures. | +| 6 | Neutering: stub `never_dropped` to `Ok(())`, run `check.rs`'s full test module | **14 tests fail**, exactly the ones that claim `never_dropped` (or one of its three equations) as their guard: both attribute tests that assert dropping/rewriting, the "written onto two ports" bug pin, the "deletion nothing writes back" pins (old and new), the three "moved comment" attacks the work log says *now* assert `never_dropped`'s sentence, the V-1 pair (dev's and this QA's own copy), the equation-3 pin, and this QA's own EOF/duplicate-comment probes. `a_move_that_left_the_comment_where_it_was_is_rejected` — the one test the work log says is honestly the piece-order comparison's — **still passes** stubbed, confirming the dev's own attribution. No test that should be piece-order-only broke, and no test that should be `never_dropped`-only survived. | + +**Finding QA-1 (LOW, confirmed-by-design, not a defect).** Equation 2 +(`wrote <= gone`) is fully bypassed for `generated()` text, with **no upper +bound at all** — `has == had - gone + wrote` is the only remaining check, and +it balances for any `wrote` the *edits themselves* honestly claim. So a +refactoring may legitimately write the whitelisted placeholder as many times +as it wants, including duplicating one that was only deleted once (1.3b: +`gone=1`, `wrote=2`, comma-separated, **accepted**). This matches the work +log's own description ("may write however many times it needs") and is not +exploitable for anything beyond a cosmetic extra `/* TODO: connect */` — it +never applies to a comment carrying user-authored information, only to the +one generated string every call site writes identically. No test guards this +specific "duplicate a deleted generated placeholder" shape today (the dev's +own whitelist test only covers "written a second time where one already +existed untouched", not "one deleted and two written back"); recommend one +line added to `check.rs`'s attack suite (`qa_scratch_1c2` above is a ready +template) so this accepted-and-intentional case has a permanent regression +pin, but it is not a blocker — nothing about it is masked corruption. + +**Finding QA-2 (LOW, direction-safe).** `wrote` is computed by lexing each +edit's `new_text` **in isolation** (`pieces(&edit.new_text)`, `check.rs:407`), +not in the context of where it lands in the file. Text that is a comment (or +attribute) when lexed alone but is actually absorbed into a string literal or +another token in context is still counted as a "written comment/attribute", +which can cause a spurious refusal of a hypothetical edit that legitimately +writes `//`- or `(* *)`-shaped text inside a string. No shipped refactoring +does this, so nothing is corrupted or forgiven — the effect is fail-closed, +consistent with CLAUDE.md's "guilty until proven innocent" stance — but it is +worth a one-line doc comment on `written`'s computation noting the +context-free lexing, so a future dev is not surprised by a refusal for an +edit that never actually writes a comment. Not a blocker. + +**Everything else held.** All 12 of the predecessor's Priority-1 attacks +(re-run conceptually via the dev's own `MOVED`/`SHARED`/`ATTRIBUTED` fixtures) +still verify or refuse exactly as before; V-1's exact reproduction pair now +refuses (`an_insertion_that_duplicates_an_untouched_comment_is_rejected`, +confirmed depends on `never_dropped` by the neutering pass); V-2's exact +reproduction (`(* keep *) input a;`) now refuses via +`attributes_clear`/refusal 23, confirmed on both halves of the merge and +confirmed to *not* fire for a non-absorbed sibling. No new HIGH or MEDIUM +finding. + +**Gates**, all guarded, no guard kill: + +- `cargo clippy --all-targets`: **0 warnings**. +- `tools/guard.sh -- cargo test -p vlog_refactor -p lucisv_server`: all + binaries green — 1499 (vlog_refactor lib) + 97 + 3 + 101 + 54 + 8 + 32 + 53 + + 70 (vlog_refactor integration suites) + 97 + 2 + 32 (lucisv_server) + doc + tests, **0 failed** across the board. +- `tools/guard.sh -- cargo test --workspace`: **3951 passed, 0 failed, 44 + ignored** — exact match to the dev's reported baseline for this rework + (the predecessor's pre-rework count plus the seven new `check.rs` attack + tests and two new `tests/ansi.rs` behaviour tests this rework added). + +**Verdict: PASS.** Both of the predecessor's blocking findings are closed +with attack-tested fixes: V-1 by `never_dropped`'s equation 2 (confirmed +load-bearing by neutering), V-2 by `attributes_clear` plus `never_dropped`'s +attribute counting (confirmed load-bearing by neutering, confirmed scoped +correctly — fires only on absorbed items, never on a sibling). Two LOW, +non-blocking notes (QA-1, QA-2) are recorded above for the lead's awareness; +neither is masked corruption and neither requires rework before merge. + +## Review + +**2026-09-05 — lead.** Accepted after one rework; ships in 0.46.0 with §50. +The engine is the right shape — insertions around each header name, so +no reference anchor moves and the verifier's resolution check holds — +and the §23.2.2.2 merge table is implemented row by row with a refusal +for every disagreement. That no non-ANSI module exists in the corpus or +in opentitan is a finding about the trees, not the feature; the +round-trip acceptance (an ANSI header rewritten the 2001 way and +converted back, same ports in the same order with the same types) is the +honest substitute and the census test keeps it live. QA's two HIGHs were +exactly the invariant-4 case: a widened verifier without the attack +tests to prove it. The rework's rule — `has ≥ had`, `wrote ≤ gone` unless +generated, `has == had − gone + wrote`, over comments and attribute +instances alike — is stricter than the wording I gave (which would have +forgiven the doubled-comment pin) and refuses nothing honest; the +whitelist is the one placeholder two engines write, with a test for the +two-ports-in-sequence flow; an attributed declaration is refused rather +than moved, and the verifier now refuses any refactoring that drops an +attribute. QA's re-attack (30-plus pairs, a neutering pass) found only +two fail-closed LOWs. This is what invariant 4 is for. diff --git a/docs/site/dist/pagefind/fragment/en_a668f18.pf_fragment b/docs/site/dist/pagefind/fragment/en_a668f18.pf_fragment new file mode 100644 index 0000000..89dbce6 Binary files /dev/null and b/docs/site/dist/pagefind/fragment/en_a668f18.pf_fragment differ diff --git a/docs/site/dist/pagefind/fragment/en_bcf82a6.pf_fragment b/docs/site/dist/pagefind/fragment/en_bcf82a6.pf_fragment deleted file mode 100644 index 796e382..0000000 Binary files a/docs/site/dist/pagefind/fragment/en_bcf82a6.pf_fragment and /dev/null differ diff --git a/docs/site/dist/pagefind/index/en_2af3cff.pf_index b/docs/site/dist/pagefind/index/en_2af3cff.pf_index deleted file mode 100644 index 74c2f61..0000000 Binary files a/docs/site/dist/pagefind/index/en_2af3cff.pf_index and /dev/null differ diff --git a/docs/site/dist/pagefind/index/en_3f6ad46.pf_index b/docs/site/dist/pagefind/index/en_3f6ad46.pf_index new file mode 100644 index 0000000..b55be1d Binary files /dev/null and b/docs/site/dist/pagefind/index/en_3f6ad46.pf_index differ diff --git a/docs/site/dist/pagefind/index/en_6d60f47.pf_index b/docs/site/dist/pagefind/index/en_6d60f47.pf_index deleted file mode 100644 index 8d7805b..0000000 Binary files a/docs/site/dist/pagefind/index/en_6d60f47.pf_index and /dev/null differ diff --git a/docs/site/dist/pagefind/index/en_9adb19f.pf_index b/docs/site/dist/pagefind/index/en_9adb19f.pf_index new file mode 100644 index 0000000..a1c02bb Binary files /dev/null and b/docs/site/dist/pagefind/index/en_9adb19f.pf_index differ diff --git a/docs/site/dist/pagefind/pagefind-entry.json b/docs/site/dist/pagefind/pagefind-entry.json index 798dcc0..d832603 100644 --- a/docs/site/dist/pagefind/pagefind-entry.json +++ b/docs/site/dist/pagefind/pagefind-entry.json @@ -1 +1 @@ -{"version":"1.5.2","languages":{"en":{"hash":"en_f74701efcf","wasm":"en","page_count":12}},"include_characters":["_","‿","⁀","⁔","︳","︴","﹍","﹎","﹏","_"]} \ No newline at end of file +{"version":"1.5.2","languages":{"en":{"hash":"en_bd6347a7d0","wasm":"en","page_count":12}},"include_characters":["_","‿","⁀","⁔","︳","︴","﹍","﹎","﹏","_"]} \ No newline at end of file diff --git a/docs/site/dist/pagefind/pagefind.en_bd6347a7d0.pf_meta b/docs/site/dist/pagefind/pagefind.en_bd6347a7d0.pf_meta new file mode 100644 index 0000000..0ff21c4 Binary files /dev/null and b/docs/site/dist/pagefind/pagefind.en_bd6347a7d0.pf_meta differ diff --git a/docs/site/dist/pagefind/pagefind.en_f74701efcf.pf_meta b/docs/site/dist/pagefind/pagefind.en_f74701efcf.pf_meta deleted file mode 100644 index 056d892..0000000 Binary files a/docs/site/dist/pagefind/pagefind.en_f74701efcf.pf_meta and /dev/null differ diff --git a/docs/site/dist/reference/language-tools/index.html b/docs/site/dist/reference/language-tools/index.html index c1b446d..3e0e270 100644 --- a/docs/site/dist/reference/language-tools/index.html +++ b/docs/site/dist/reference/language-tools/index.html @@ -289,7 +289,7 @@ index scope when the defining module lives outside the default folder scope.

Port actions code actions / commands -Adds, removes, and propagates module ports; expands a .* wildcard into the named connections it stands for (a port with no same-named signal in scope becomes .p() and is named in a warning) — lucisv.expandWildcard +Adds, removes, and propagates module ports; expands a .* wildcard into the named connections it stands for (a port with no same-named signal in scope becomes .p() and is named in a warning) — lucisv.expandWildcard; converts a Verilog-2001 header to ANSI, each body declaration merged into the port it described (IEEE 1800 §23.2.2.2) with its comments carried along — lucisv.convertToAnsi Instantiate module @@ -342,4 +342,4 @@ index scope when the defining module lives outside the default folder scope.

The server handles didOpen, incremental didChange, didSave, didClose, watched-file changes, configuration changes, cancellation, shutdown, and exit. It dynamically registers file watchers, emits work-done progress while building large indexes, coalesces code-lens refreshes, and promotes open-buffer overlays into the workspace without waiting for disk writes.

- \ No newline at end of file + \ No newline at end of file diff --git a/docs/site/src/content/docs/reference/language-tools.md b/docs/site/src/content/docs/reference/language-tools.md index c11ee03..bdaa0f2 100644 --- a/docs/site/src/content/docs/reference/language-tools.md +++ b/docs/site/src/content/docs/reference/language-tools.md @@ -68,7 +68,7 @@ index scope when the defining module lives outside the default folder scope. |---|---|---| | Prepare rename | `textDocument/prepareRename` | Verifies the target and returns its editable range | | Rename | `textDocument/rename` | Renames local or workspace-resolved symbols | -| Port actions | code actions / commands | Adds, removes, and propagates module ports; expands a `.*` wildcard into the named connections it stands for (a port with no same-named signal in scope becomes `.p()` and is named in a warning) — `lucisv.expandWildcard` | +| Port actions | code actions / commands | Adds, removes, and propagates module ports; expands a `.*` wildcard into the named connections it stands for (a port with no same-named signal in scope becomes `.p()` and is named in a warning) — `lucisv.expandWildcard`; converts a Verilog-2001 header to ANSI, each body declaration merged into the port it described (IEEE 1800 §23.2.2.2) with its comments carried along — `lucisv.convertToAnsi` | | Instantiate module | inline completion / `lucisv.instantiate` | Builds an instance from an indexed module interface, including in clients without ghost text | | Apply workspace edit | `workspace/applyEdit` | Delivers multi-file refactor changes to the client | | Show definition | `window/showDocument` | Opens a generated or resolved target after an action |