Convert ports to ANSI: a Verilog-2001 header merged with its body declarations, and a verifier that never drops a comment or an attribute
TODO §51 (docs/features/ansi-conversion), the second §8 refactoring. `vlog_refactor::convert_to_ansi` (ports/ansi.rs, ports/merge.rs): for a `PortList::NonAnsi` module, each header name gains its direction, net or variable type, signing and packed dims from the body declarations that describe it, merged per IEEE 1800 §23.2.2.2 (`output b; reg [7:0] b;` → `output reg [7:0] b`), as insertions around the untouched name so no reference anchor moves; the absorbed declarations are deleted with their comments carried onto the ports. Twenty-three refusals, each a sentence (port expressions, disagreeing ranges, initialisers, directives, a comment that would have to move into a one-line list, an attributed declaration). Code action `lucisv: convert ports to ANSI (N ports)` and command `lucisv.convertToAnsi`. Review rework (QA's two HIGHs, invariant 4): the verifier's comment rule is now `never_dropped` over comments and attribute instances alike — `has ≥ had`, `wrote ≤ gone` unless the text is the one generated placeholder, `has == had − gone + wrote` — with masked-corruption attack tests, re-attacked by QA (30-plus pairs, a neutering pass). Neither the corpus nor opentitan holds a non-ANSI module; acceptance is by round trip (ANSI → 2001 → ANSI, same ports/types in order) over five corpus modules and 290 of 291 opentitan candidates (the one failure is kmac_reduced_tb.sv's pre-existing trailing-comma parse error). 0 of 854 corpus files differ from 0.45.0. Co-Authored-By: Claude Fable 5.1 <[email protected]>
This commit is contained in:
1 parent
d9ed2c447a
commit
aa479cf701
25 files changed
+3539
-58
No files matched your search
@@ -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<RefactorEdit, String>`
|
||||
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
|
||||
@@ -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<String> {
|
||||
@@ -59,6 +61,7 @@ pub fn commands() -> Vec<String> {
|
||||
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]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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<Piece> = Vec::new();
|
||||
let mut next = 0usize;
|
||||
let mut written: Vec<Vec<(TextRange, Piece)>> = 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<Piece> = 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<Kept, usize>;
|
||||
|
||||
/// 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<Item = &'p Piece>) -> 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<TextEdit> {
|
||||
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<TextEdit> {
|
||||
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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -229,19 +229,19 @@ pub(super) fn element_spans(ports: &[DeclaredPort]) -> Vec<TextRange> {
|
||||
|
||||
/// 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<Directive> {
|
||||
/// 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<Directive> {
|
||||
pub(super) fn body_directives(module: &Module) -> Vec<Directive> {
|
||||
module
|
||||
.items
|
||||
.iter()
|
||||
|
||||
@@ -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<Conversion, String> {
|
||||
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<TextRange> = 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<Vec<&NonAnsiPort>, 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<Vec<String>, String> {
|
||||
let mut names: Vec<String> = 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<String> {
|
||||
fn walk(items: &[Item], names: &[String], inside: bool, found: &mut Option<String>) {
|
||||
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<String>) {
|
||||
walk(&b.items, names, true, found);
|
||||
}
|
||||
fn named<'a>(
|
||||
declared: impl Iterator<Item = &'a String>,
|
||||
names: &[String],
|
||||
found: &mut Option<String>,
|
||||
) {
|
||||
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<TextRange> =
|
||||
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<Vec<(TextRange, String)>, 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<String>,
|
||||
after: Vec<String>,
|
||||
}
|
||||
|
||||
/// 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<TextRange>,
|
||||
) -> Result<Vec<TextEdit>, 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<String, String> {
|
||||
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<Vec<TextEdit>, String> {
|
||||
let mut ranges: Vec<TextRange> = 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<String> {
|
||||
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')
|
||||
}
|
||||
@@ -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<u32> {
|
||||
pub(super) fn comma_after(text: &str, end: u32) -> Option<u32> {
|
||||
let mut at = end as usize;
|
||||
loop {
|
||||
let rest = text.get(at..)?;
|
||||
|
||||
@@ -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<Vec<Absorbed<'t>>, 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<Site<'t>>,
|
||||
vars: Vec<Site<'t>>,
|
||||
}
|
||||
|
||||
/// Read the body, with the declarations lucisv will not absorb refused.
|
||||
fn collect<'t>(module: &str, items: &'t [Item], names: &[String]) -> Result<Body<'t>, 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::<Vec<_>>().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<Absorbed<'t>, 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<String> {
|
||||
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<String>,
|
||||
var: Option<String>,
|
||||
) -> Result<Option<String>, 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<String, String> {
|
||||
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::<String>();
|
||||
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."
|
||||
)),
|
||||
}
|
||||
}
|
||||
@@ -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<RefactorEdit, String> {
|
||||
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<String> {
|
||||
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
|
||||
|
||||
@@ -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<String, String> {
|
||||
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<String> =
|
||||
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<String> =
|
||||
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<String> =
|
||||
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");
|
||||
}
|
||||
@@ -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<u32> {
|
||||
}
|
||||
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<String> = 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<String> = 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<String> {
|
||||
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::<String>();
|
||||
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<String> {
|
||||
let (tree, _) = vlog_parser::parse_source_tolerant(text);
|
||||
fn walk(items: &[Item], module: &str) -> Option<Vec<String>> {
|
||||
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::<Option<Vec<_>>>()?;
|
||||
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
|
||||
}
|
||||
@@ -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(&[
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1
-1
@@ -1 +1 @@
|
||||
{"version":"1.5.2","languages":{"en":{"hash":"en_f74701efcf","wasm":"en","page_count":12}},"include_characters":["_","‿","⁀","⁔","︳","︴","﹍","﹎","﹏","_"]}
|
||||
{"version":"1.5.2","languages":{"en":{"hash":"en_bd6347a7d0","wasm":"en","page_count":12}},"include_characters":["_","‿","⁀","⁔","︳","︴","﹍","﹎","﹏","_"]}
|
||||
Binary file not shown.
Binary file not shown.
+2
-2
@@ -289,7 +289,7 @@ index scope when the defining module lives outside the default folder scope.</p>
|
||||
<tr>
|
||||
<td>Port actions</td>
|
||||
<td>code actions / commands</td>
|
||||
<td>Adds, removes, and propagates module ports; expands a <code dir="auto">.*</code> wildcard into the named connections it stands for (a port with no same-named signal in scope becomes <code dir="auto">.p()</code> and is named in a warning) — <code dir="auto">lucisv.expandWildcard</code></td>
|
||||
<td>Adds, removes, and propagates module ports; expands a <code dir="auto">.*</code> wildcard into the named connections it stands for (a port with no same-named signal in scope becomes <code dir="auto">.p()</code> and is named in a warning) — <code dir="auto">lucisv.expandWildcard</code>; 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 — <code dir="auto">lucisv.convertToAnsi</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Instantiate module</td>
|
||||
@@ -342,4 +342,4 @@ index scope when the defining module lives outside the default folder scope.</p>
|
||||
</table>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="workspace-lifecycle">Workspace lifecycle</h2><a class="sl-anchor-link" href="#workspace-lifecycle"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Workspace lifecycle”</span></a></div>
|
||||
<p>The server handles <code dir="auto">didOpen</code>, incremental <code dir="auto">didChange</code>, <code dir="auto">didSave</code>, <code dir="auto">didClose</code>, 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.</p>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/language-tools.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T04:37:55.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/rules/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Lint rules</span></span></a><a href="/reference/rust-api/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Rust API index</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/language-tools.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T20:03:11.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/rules/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Lint rules</span></span></a><a href="/reference/rust-api/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Rust API index</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
@@ -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 |
|
||||
|
||||
Reference in new issue
Block a user