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
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.