From acf20f7e62a1aaffabf1613e6f739cc043756f31 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Sat, 5 Sep 2026 23:04:14 -0500 Subject: [PATCH] Extract module: dataflow-inferred ports, a new file where the client can create one, and a verifier ledger that follows the move MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TODO §53.1 (docs/features/extract-inline-module), the fourth §8 refactoring; §53.2 inline module is unstarted and runs as its own lane. `vlog_refactor::extract` (region, flow, boundary, render): a selection of whole module items becomes a new module — a name declared outside and read inside is an `input`, written inside an `output` (assign and procedural LHS, for init/step, ++/--, force/release/deassign, `-> ev`, an initialiser, an output/inout connection through the index), written on both sides refused; parameters passed through `#(.P(P))`, used imports copied, the port's type taken from the declaration's own text; the selection replaced by an instantiation rendered from the new module's text. Forty-three refusal sentences. `RefactorEdit::created`; the server emits `CreateFile` document changes when the client reads both halves of the capability, else writes the module below its source; `refactor.extract` action carrying `lucisv.extractModule [uri, range, name]`, and a name prompt in the VS Code extension through the language client's middleware. The verifier's never-dropped ledger follows the move (review rework of QA's two HIGHs): `verify_move(moving: &[(file, region)])` — a piece deleted inside the moved region must land exactly once in the file the move names, a deletion outside the region stays an ordinary deletion, four equations, twelve attack pairs through the production entry; `check.rs` split (pure move) into `check/{mod,ledger}.rs`. `interface` and `program` bodies are refused (one AST node, gated on `kw`). QA's re-attack: PASS; its MEDIUM (a same-file relocation as two edits) is filed as topo §2.9-32. Trials: corpus 5 extracted / 6 refused, opentitan `hw/ip/{aes,uart, spi_host,hmac}` 5 / 5, the unresolved-name census held for every accepted extraction. 0 of 820 corpus files differ from 0.46.0. Co-Authored-By: Claude Fable 5.1 --- TODO.md | 188 ++- crates/lucisv_server/src/extract.rs | 371 ++++++ crates/lucisv_server/src/main.rs | 86 +- crates/lucisv_server/src/server/dispatch.rs | 30 +- crates/lucisv_server/src/server/mod.rs | 7 + crates/vlog_refactor/src/check/ledger.rs | 888 +++++++++++++ .../src/{check.rs => check/mod.rs} | 964 +++++--------- crates/vlog_refactor/src/extract/boundary.rs | 469 +++++++ crates/vlog_refactor/src/extract/flow.rs | 664 ++++++++++ crates/vlog_refactor/src/extract/mod.rs | 511 ++++++++ crates/vlog_refactor/src/extract/region.rs | 209 ++++ crates/vlog_refactor/src/extract/render.rs | 384 ++++++ crates/vlog_refactor/src/imports.rs | 3 +- crates/vlog_refactor/src/lib.rs | 9 + crates/vlog_refactor/src/ports/mod.rs | 2 +- crates/vlog_refactor/src/rename/mod.rs | 2 +- crates/vlog_refactor/tests/corpus.rs | 156 ++- crates/vlog_refactor/tests/extract.rs | 736 +++++++++++ docs/coverage_gaps.md | 2 +- docs/features/extract-inline-module/README.md | 1109 +++++++++++++++++ .../pagefind/fragment/en_1a2f59a.pf_fragment | Bin 2714 -> 0 bytes .../pagefind/fragment/en_a48254a.pf_fragment | Bin 0 -> 2904 bytes .../dist/pagefind/index/en_1d5c371.pf_index | Bin 8343 -> 0 bytes .../dist/pagefind/index/en_30d4d48.pf_index | Bin 36994 -> 0 bytes .../dist/pagefind/index/en_72ebf93.pf_index | Bin 0 -> 37021 bytes .../dist/pagefind/index/en_eb39104.pf_index | Bin 0 -> 8527 bytes docs/site/dist/pagefind/pagefind-entry.json | 2 +- .../pagefind/pagefind.en_63f86fa784.pf_meta | Bin 0 -> 223 bytes .../pagefind/pagefind.en_fc49ef3316.pf_meta | Bin 225 -> 0 bytes .../dist/reference/language-tools/index.html | 7 +- docs/site/dist/reference/rules/index.html | 2 +- .../content/docs/reference/language-tools.md | 1 + docs/topo.md | 2 + editors/vscode/extension.js | 19 + editors/vscode/extract.js | 74 ++ editors/vscode/extract_test.js | 137 ++ 36 files changed, 6365 insertions(+), 669 deletions(-) create mode 100644 crates/lucisv_server/src/extract.rs create mode 100644 crates/vlog_refactor/src/check/ledger.rs rename crates/vlog_refactor/src/{check.rs => check/mod.rs} (50%) create mode 100644 crates/vlog_refactor/src/extract/boundary.rs create mode 100644 crates/vlog_refactor/src/extract/flow.rs create mode 100644 crates/vlog_refactor/src/extract/mod.rs create mode 100644 crates/vlog_refactor/src/extract/region.rs create mode 100644 crates/vlog_refactor/src/extract/render.rs create mode 100644 crates/vlog_refactor/tests/extract.rs create mode 100644 docs/features/extract-inline-module/README.md delete mode 100644 docs/site/dist/pagefind/fragment/en_1a2f59a.pf_fragment create mode 100644 docs/site/dist/pagefind/fragment/en_a48254a.pf_fragment delete mode 100644 docs/site/dist/pagefind/index/en_1d5c371.pf_index delete mode 100644 docs/site/dist/pagefind/index/en_30d4d48.pf_index create mode 100644 docs/site/dist/pagefind/index/en_72ebf93.pf_index create mode 100644 docs/site/dist/pagefind/index/en_eb39104.pf_index create mode 100644 docs/site/dist/pagefind/pagefind.en_63f86fa784.pf_meta delete mode 100644 docs/site/dist/pagefind/pagefind.en_fc49ef3316.pf_meta create mode 100644 editors/vscode/extract.js create mode 100644 editors/vscode/extract_test.js diff --git a/TODO.md b/TODO.md index 656423b..d1b14f4 100644 --- a/TODO.md +++ b/TODO.md @@ -710,7 +710,7 @@ 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 +- [ ] 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 @@ -743,6 +743,21 @@ section only tracks the milestones. holding a macro call or a `` `include ``**, which lucisv refuses to judge at all: 32 of the corpus's 40 multi-import scopes and 33 of 33 OpenTitan UVM env packages. + **Extract module shipped 2026-09-05 (§53.1, + `docs/features/extract-inline-module/README.md`)**: a selection of whole + module items becomes a module of its own, with ports and parameters inferred + from the dataflow across the boundary, the `import`s it needs carried across, + and the instantiation that replaces it rendered from the new module's own + text — into a file beside its own where the editor can create one, below the + module it came from where it cannot. `refactor.extract` plus + `lucisv.extractModule`, whose name comes from an input box the VS Code + extension puts in front of it. **Inline module (§53.2) is not started**, so + the backlog line above keeps it. Extract leaves four things behind, added to + this backlog: **a task or function used on both sides** of the selection, + which would have to move or be duplicated; **a hierarchical reference** + crossing the boundary, which no port can carry; **an `initial`/`final` + block**, whose meaning is when it runs; and **an unpacked-array or + interface-typed name** crossing, which the port renderer will not write. ## 9. LSP 3.18 protocol audit (2026-08-26) @@ -4625,8 +4640,10 @@ lead, a release every two or three sections: 0.44.0 → §47 `DataType` spans, retire `scan.rs` (topo 2) → §48 package re-exports (topo 16) → §49 cross-file instance-member tail in rename (topo 23) → 0.45.0 → §50 `.*` expansion → §51 non-ANSI → ANSI ports → -0.46.0 → §52 organize imports → §53 extract / inline module → 0.47.0 → -§54 coverage gaps L3/L6/L10 → 0.48.0. Sections after §46 are planned when +0.46.0 → §52 organize imports → §53.1 extract module → 0.47.0 → +**§56 DUT-centred hierarchy view (owner request 2026-09-06) → 0.48.0** → +§53.2 inline module (its own lane; 53.1 consumed the round, as planned) +→ §54 coverage gaps L3/L6/L10 → 0.49.0. Sections after §46 are planned when reached. ## 45. Small items, round 4 (planned 2026-09-05) — topo §2.9-29, 30, 17, 22 @@ -5263,12 +5280,167 @@ imports copied into `M` if `M` lacks them. a `lucisv check --select unused-signal,undriven-net` census over the result is unchanged in count from the original two files. -- [ ] 53.1 extract: dataflow ports, parameters, imports, the new file, +- [x] 53.1 extract: dataflow ports, parameters, imports, the new file, refusals, action + command + extension input box - [ ] 53.2 inline: substitution, prefixing, refusals, action + command -- [ ] the extract → inline round trip pinned -- [ ] docs; §8 lines annotated; site rows (lead) -- [ ] Gates (guarded); byte-identity vs 0.46.0; corpus scratch checks -- [ ] QA: dataflow direction attacked (every statement kind that writes + — **unstarted**; §53.1 alone took the round +- [ ] the extract → inline round trip pinned — blocked on 53.2 +- [x] docs; §8 line annotated (extract only); site rows (lead — see the + feature README's "Docs to apply at merge") +- [x] Gates (guarded); byte-identity vs 0.46.0; corpus scratch checks +- [x] QA: dataflow direction attacked (every statement kind that writes a name), boundary-crossing shapes, collisions, the round trip, the client-capability fallback, opentitan scratch trials + +## 54. Coverage gaps L3, L6, L10 (planned 2026-09-06) — the owner's "do all three" + +One lane after 0.47.0, §36's protocol. Feature README: +`docs/features/coverage-gaps-l/README.md`. Ships in 0.48.0. Every item is +a grammar arm with its formatter twin, the snapshot + idempotency suite, +strict/tolerant parity, and the byte-identity gates; none of these shapes +occur in the corpus or opentitan (say so per item with the grep), so the +acceptance is hand-written cases plus the fuzzers. + +### 54.1 L6 — the language shapes + +- `->>` non-blocking event trigger (`->> e;`, `->> #5 e;`, `->> @(posedge clk) e;`). +- Stream operator `with [range]` (`{<< {a with [0:3]}}`, `[i+:4]`, `[i-:4]`). +- Cast bases other than a name or system call: a parenthesised width + `(W+1)'(x)`, a sized literal `4'(x)`, a type with dims `logic [3:0]'(x)` + — the LRM's `casting_type` (§6.24.1). +- Drive strength on a net declaration: `wire (strong0, weak1) w = a;`, + `wire (supply0, supply1) [7:0] v;` — `DataDecl` gains the strength the way + `ContAssign` already carries one (`parse_opt_drive_strength` exists). +- `let` at statement position (a `let` declared inside a sequential block + / procedural scope, IEEE 1800 §11.13). +- `#(min:typ:max)` clocking skew: `default input #(1:2:3) output #(2:3:4);` + and per-signal skews. +Each: parser arm, AST field with comment slots where a gap opens (the +comment-slots gap fuzzer's zero-failure bar), formatter arm, cases file, +strict/tolerant parity, `size_pins` unmoved. + +### 54.2 L3 — `randsequence` bodies + +`randsequence (main) main : first second; first : { $display("a"); }; +second : third | fourth := 2; …; endsequence` — a production grammar (IEEE +1800 §18.17): productions with optional return types and arguments, +weighted alternatives `:=`, `rand join`, `repeat`, `if`/`case`, code +blocks, `break`/`return`. Today an opaque `Verbatim` leaf? Check +(`grep -rn randsequence crates/vlog_parser/src`). Ruling: model the +production list and alternatives as real nodes (a `RandSequence` statement +with `Production { name, ret_type, args, alternatives: Vec }`, items being production references or a code block +parsed as a statement block); the formatter prints one production per +line, alternatives aligned after `:` / `|`; comment slots per production. +Zero corpus occurrences — a pure-LRM feature; the LRM's own examples are +the cases. + +### 54.3 L10 — cosmetics + +- An enum body one-lined when short: `typedef enum {A, B, C} e_t;` stays on + one line when it fits the width and has no comments — today it always + breaks? Confirm with a case; make the group breakable the way a port list + is (`Doc::Group`), so long bodies still break one per line. **Byte + identity WILL change** for corpus files with short enums: measure the + count, list them, and the lead rules at review whether the change is + wanted (the corpus has ibex/opentitan enums — likely dozens of files). +- `` `uvm_field_* `` lines dedented to the `` `uvm_object_utils_begin `` + column: macro statements between `_begin`/`_end` are plain macro items + with no block for the formatter to see; a targeted rule — a macro + statement whose name matches `uvm_object_utils_begin`/`uvm_component_utils_begin` + opens an indent level closed by `uvm_object_utils_end`/`uvm_component_utils_end` + — in the item/statement sequence printer, gated on exactly those names. + Byte identity changes for UVM files that already indent them — measure + and list. +Both cosmetics are **off by default behind a config key** if the corpus +count is large: `[format] enum-one-line = true|false`, `[format] +uvm-utils-indent = true|false`, default false, so 0.48.0 changes no +byte for anyone who does not opt in; the lead decides the defaults at +review from the counts. + +- [ ] 54.1 the six L6 shapes, each with cases + parity + fuzzers +- [ ] 54.2 `randsequence` as real nodes +- [ ] 54.3 the two cosmetics behind config keys, corpus impact measured +- [ ] docs; coverage_gaps L3/L6/L10 struck; README/site config keys (lead) +- [ ] Gates (guarded); byte-identity vs 0.47.0 (0 differing with the keys + off); opentitan sweep unchanged +- [ ] QA: every shape with comments in every gap; the fuzzers; the keys on + over the corpus in a scratch copy (idempotent, comments kept) + +## 56. DUT-centred hierarchy view (owner request 2026-09-06) + +The next lane after 0.47.0 ships — ahead of §53.2 and §54, at the owner's +request. One lane, §36's protocol; dev Opus 5, QA Sonnet 5. Feature README: +`docs/features/dut-hierarchy/README.md`. Ships in 0.48.0. + +**What the owner asked for, verbatim in substance.** A design holds many +modules and one (or a few) is the DUT — the module that matters most. It +usually has DV above it (a testbench that instantiates it). The hierarchy +pane should let the user right-click any module and **star it as DUT**. +With one DUT starred the pane shows three sections: **the DUT with its +children** (its instance subtree, the DUT at the very top), **the DUT's +parents** (every module that instantiates it, transitively — typically the +DV — as a tree explored upward from the DUT), and **all other modules** +(everything that is neither below nor above any DUT), each section +collapsible. Two DUTs starred → five sections: DUT1 + children, DUT1 +parents, DUT2 + children, DUT2 parents, all other modules. Unstar from the +same menu. + +**Where it lives.** Entirely in the extension over the existing flat +snapshot (`lucisv/moduleHierarchy`: `files`, `modules`, `instances`; +`hierarchyModel.js::buildHierarchy` already builds the forward tree and +chooses roots) — the server changes nothing. The reverse map (module → +instantiating modules, via each instance's owning module) is one pass over +the same snapshot in the model. DUT choices persist per workspace in +`workspaceState` (a list of module names, in the order starred), the way +the existing bookmark does (`hierarchyView.js` `BOOKMARK_KEY`). + +- **Model** (`hierarchyModel.js`): `sections(model, duts)` returning, in + order, for each starred DUT `{ kind: 'dut', name, root }` (the DUT's + forward subtree, exactly the node the plain view would show for it) and + `{ kind: 'parents', name, root }` (an upward tree: the DUT as the root, + each child a module that instantiates the parent node — with the + instance name that does it — recursing up until a module nothing + instantiates; cycles cut with a visited set), then + `{ kind: 'others', roots }` = today's roots minus every module that is in + any DUT's subtree or ancestor chain (a module both below DUT1 and above + DUT2 appears in both DUT sections and not in others). A starred name the + snapshot no longer holds (renamed/deleted) keeps its section with an + empty "not in the index" row rather than vanishing silently. +- **View** (`hierarchyView.js`): section nodes as collapsible tree items + with icons (`debug-start`-style for a DUT, an upward arrow for parents, + a folder for others), the DUT section expanded by default, others + collapsed; DUT rows carry a `contextValue` so the menu shows + "Unstar DUT" on a starred module and "Star as DUT" on any other; the + existing search, reveal-on-open and bookmark behaviour work inside every + section; when no DUT is starred the pane looks exactly as today (pin it + — the snapshot-to-tree output byte-identical to the current tests). +- **Commands + menus** (`package.json`): `lucisv.hierarchy.starDut`, + `lucisv.hierarchy.unstarDut`, `lucisv.hierarchy.clearDuts`; `view/item/context` + entries gated on `viewItem`; a `view/title` "Clear DUTs". Also a setting + `lucisv.hierarchy.duts` (string array) as the second way to set them + (a checked-in `.vscode/settings.json` for a team) — the union with the + starred list, the setting's entries shown with a lock icon and not + unstar-able from the menu (say so in a tooltip). +- **Tests** (`node --test editors/vscode/*_test.js`, the existing model + tests' harness): sections for zero, one and two DUTs on a fixture with a + DV bench above a DUT above three leaves plus two unrelated modules; a + module both below one DUT and above another; a cycle (`a` instantiates + `b` instantiates `a`) in the parents walk; a starred name absent from the + snapshot; the others section excludes exactly the right set; the plain + view unchanged with no DUT; persistence round trip through a fake + `workspaceState`; the setting union and lock; the menu `when` clauses. + Manual: a checklist entry in `docs/manual-acceptance.md` (star aes in + opentitan → three sections; star aes and hmac → five; unstar). +- Docs: the extension README's hierarchy section, the site's editors page + (lead applies), the feature README. + +- [ ] 56.1 model: reverse map, `sections()`, others-exclusion, cycle cut +- [ ] 56.2 view: section nodes, icons, context values, persistence, + setting union +- [ ] 56.3 commands, menus, package.json, tests, acceptance checklist row +- [ ] docs (lead applies README/site) +- [ ] Gates: `node --test editors/vscode/*_test.js`; vsix smoke; the plain + view pinned unchanged +- [ ] QA: every section shape attacked on the fixture and on opentitan + (real snapshot, read-only); persistence; the setting; menus diff --git a/crates/lucisv_server/src/extract.rs b/crates/lucisv_server/src/extract.rs new file mode 100644 index 0000000..119cdcd --- /dev/null +++ b/crates/lucisv_server/src/extract.rs @@ -0,0 +1,371 @@ +//! Extract a selection into a module of its own, on the wire: +//! `textDocument/codeAction` under LSP's own `refactor.extract`, and +//! `workspace/executeCommand` for the editors that have no lightbulb. +//! +//! Protocol only. The edit is `vlog_refactor::extract_module`; this module +//! decides which files that engine is handed, turns its answer into a +//! `WorkspaceEdit`, and turns its refusal into a request error. +//! +//! **The action carries a command, not an edit** — which is what makes it the +//! laziest of the lot rather than merely a lazy one. Extracting needs a *name* +//! for the new module, and LSP has no prompt: a code action can carry an +//! `edit`, a `command`, or both, and only a command can be intercepted by a +//! client that wants to ask the user something first. So the offer is one +//! parse of one buffer (`vlog_refactor::extract_site`) plus a `Command` naming +//! [`EXTRACT_MODULE`] and the default name `M_extracted`; the VS Code +//! extension registers a client-side command of the same name that shows an +//! input box and calls the server's with what the user typed, and every other +//! client runs the command as sent and gets the default. See +//! `docs/features/extract-inline-module/README.md`. +//! +//! **The new file.** A module extracted into a file of its own is a +//! `CreateFile` resource operation, which only a client that advertises +//! `workspace.workspaceEdit.documentChanges` *and* `resourceOperations` +//! containing `create` can apply. That capability is read at `initialize` +//! ([`crate::server::ClientAbilities::create_files`]) and is the whole of the +//! choice between the two homes: a client that can create files gets `N.sv` +//! beside `M`'s file, and every other client gets `N` written below `M` in the +//! file it came from. The engine says which happened in its warnings. + +// See `rename.rs` for why this is a `WorkspaceEdit`'s problem and not ours. +#![allow(clippy::mutable_key_type)] + +use lsp_types::{ + CodeAction, CodeActionKind, CodeActionOrCommand, Command, CreateFile, DocumentChangeOperation, + DocumentChanges, OneOf, OptionalVersionedTextDocumentIdentifier, Range, ResourceOp, + TextDocumentEdit, TextEdit, Uri, WorkspaceEdit, +}; +use serde_json::Value; +use vlog_parser::LineIndex; +use vlog_refactor::{Home, RefactorEdit}; + +use crate::convert::Positions; +use crate::state::Workspace; +use crate::uri::path_to_uri; + +/// Extract a selection into a module: `[uri, range, name]`. +pub const EXTRACT_MODULE: &str = "lucisv.extractModule"; + +/// Every command this module executes. +pub fn commands() -> Vec { + vec![EXTRACT_MODULE.to_string()] +} + +/// The kind LSP reserves for an extraction, which is what an editor's +/// "Refactor…" menu asks for by name. +pub fn kind() -> CodeActionKind { + CodeActionKind::REFACTOR_EXTRACT +} + +/// The action for a selection, carrying the command that will ask for a name. +/// +/// One parse of the buffer and nothing else: the engine's cheap gate answers +/// "there is nothing here" for almost every selection, and where it does find +/// something the offer is a `Command`, so no workspace is read until the user +/// has picked the action *and* named the module. +pub fn code_actions(ws: &Workspace, uri: &Uri, range: Range) -> Vec { + let Some(doc) = ws.document(uri) else { return Vec::new() }; + if doc.path.is_none() { + // An `untitled:` buffer has no directory to put `N.sv` beside and no + // path for the engine's file set; nothing is offered rather than + // offered and refused. + return Vec::new(); + } + let positions = doc.positions(); + let (start, end) = (positions.offset(range.start), positions.offset(range.end)); + let Some(site) = vlog_refactor::extract_site(&doc.text, start, end) else { return Vec::new() }; + let arguments = vec![ + serde_json::to_value(uri).unwrap_or(Value::Null), + serde_json::to_value(range).unwrap_or(Value::Null), + Value::String(site.default_name.clone()), + ]; + let title = vlog_refactor::extract_title(); + vec![CodeActionOrCommand::CodeAction(CodeAction { + title: title.clone(), + kind: Some(kind()), + command: Some(Command { + title, + command: EXTRACT_MODULE.to_string(), + arguments: Some(arguments), + }), + ..Default::default() + })] +} + +/// Run `lucisv.extractModule`, or say why it cannot run. +pub fn execute( + ws: &Workspace, + arguments: &[Value], + create_files: bool, +) -> Result<(WorkspaceEdit, Vec), String> { + let uri: Uri = argument(arguments, 0, "a document URI")?; + let range: Range = argument(arguments, 1, "a range")?; + let name: String = argument(arguments, 2, "a name for the new module")?; + let doc = ws + .document(&uri) + .ok_or_else(|| "lucisv can only extract from an open file.".to_string())?; + let path = doc + .path + .clone() + .ok_or_else(|| "lucisv can only extract from a file that has been saved.".to_string())?; + let positions = doc.positions(); + let (start, end) = (positions.offset(range.start), positions.offset(range.end)); + let Some(site) = vlog_refactor::extract_site(&doc.text, start, end) else { + return Err(NOTHING.to_string()); + }; + // The engine looks up every module the selection instantiates and every + // package it imports, so the file set is those units' own fan-out — plus + // the new name's, so a workspace that already declares it is a workspace + // the engine can refuse over. + let mut units = site.units; + units.push(name.clone()); + let files = ws.module_sources(&path, &units); + let home = match create_files { + true => Home::NewFile, + false => Home::SameFile, + }; + let refactoring = vlog_refactor::extract_module(&files, &path, start, end, &name, home)?; + Ok((workspace_edit(ws, &refactoring)?, refactoring.warnings)) +} + +/// A whole extraction as a `WorkspaceEdit`. +/// +/// `documentChanges` rather than `changes` whenever a file is created: a +/// creation is a resource operation, and the two shapes cannot be mixed in one +/// edit. An extraction that creates nothing goes through the ordinary +/// `changes` map, which every client understands. +pub fn workspace_edit(ws: &Workspace, refactoring: &RefactorEdit) -> Result { + if refactoring.created.is_empty() { + return crate::ports::workspace_edit(ws, refactoring); + } + let mut operations: Vec = Vec::new(); + for path in &refactoring.created { + let uri = path_to_uri(path).ok_or_else(|| unaddressable(path))?; + operations.push(DocumentChangeOperation::Op(ResourceOp::Create(CreateFile { + uri, + options: None, + annotation_id: None, + }))); + } + for (path, edits) in &refactoring.edits { + let uri = path_to_uri(path).ok_or_else(|| unaddressable(path))?; + // A file the edit creates has no text yet, and the one insertion into + // it is at 0:0 — which is what `Positions` over an empty text says. + let created = refactoring.created.iter().any(|created| created == path); + let text = match created { + true => String::new(), + false => ws.text_of(path).ok_or_else(|| unaddressable(path))?, + }; + let index = LineIndex::new(&text); + let positions = Positions::new(&text, &index); + operations.push(DocumentChangeOperation::Edit(TextDocumentEdit { + text_document: OptionalVersionedTextDocumentIdentifier { uri, version: None }, + edits: edits + .iter() + .map(|edit| { + OneOf::Left(TextEdit { + range: positions.range(edit.range), + new_text: edit.new_text.clone(), + }) + }) + .collect(), + })); + } + Ok(WorkspaceEdit { + document_changes: Some(DocumentChanges::Operations(operations)), + ..Default::default() + }) +} + +fn argument( + arguments: &[Value], + n: usize, + what: &str, +) -> Result { + arguments + .get(n) + .and_then(|value| serde_json::from_value(value.clone()).ok()) + .ok_or_else(|| format!("{EXTRACT_MODULE} wants {what} as argument {}.", n + 1)) +} + +fn unaddressable(path: &std::path::Path) -> String { + format!("lucisv could not address {} as a document; no edits were made.", path.display()) +} + +const NOTHING: &str = "there is nothing to extract at this selection."; + +#[cfg(test)] +mod tests { + use super::*; + use crate::uri::path_to_uri; + use lsp_types::Position; + use std::fs; + use std::path::PathBuf; + + /// A scratch workspace root. Removed on drop. + struct Tree { + path: PathBuf, + } + + impl Tree { + fn new(name: &str) -> Tree { + let path = std::env::temp_dir() + .join(format!("lucisv_server_extract_{}_{name}", std::process::id())); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("temp dir"); + Tree { path } + } + + fn write(&self, rel: &str, text: &str) -> PathBuf { + let path = self.path.join(rel); + fs::write(&path, text).expect("write"); + path + } + } + + impl Drop for Tree { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } + } + + const TOP: &str = "\ +module top ( + input logic [7:0] a, + input logic [7:0] b, + output logic [7:0] q +); + logic [7:0] s; + assign s = a + b; + assign q = s; +endmodule +"; + + fn opened(tree: &Tree) -> (Workspace, Uri) { + let top = tree.write("top.sv", TOP); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&top).expect("uri"); + ws.set_document(uri.clone(), TOP.to_string()); + (ws, uri) + } + + /// The range of `assign s = a + b;`, as the client speaks it. + fn selection() -> Range { + Range { + start: Position { line: 6, character: 2 }, + end: Position { line: 6, character: 19 }, + } + } + + fn only(actions: Vec) -> Vec { + actions + .into_iter() + .filter_map(|a| match a { + CodeActionOrCommand::CodeAction(action) => Some(action), + CodeActionOrCommand::Command(_) => None, + }) + .collect() + } + + #[test] + fn a_selection_of_whole_items_is_offered_the_action_with_a_command_and_a_default_name() { + let tree = Tree::new("offer"); + let (ws, uri) = opened(&tree); + let actions = only(code_actions(&ws, &uri, selection())); + let [action] = actions.as_slice() else { panic!("one action, got {actions:?}") }; + assert_eq!(action.title, "lucisv: extract selection into module…"); + assert_eq!(action.kind, Some(CodeActionKind::REFACTOR_EXTRACT)); + assert!(action.edit.is_none(), "the offer reads no workspace"); + let command = action.command.as_ref().expect("a command"); + assert_eq!(command.command, EXTRACT_MODULE); + let arguments = command.arguments.as_ref().expect("arguments"); + assert_eq!(arguments.len(), 3); + assert_eq!(arguments[2], Value::String("top_extracted".to_string())); + } + + #[test] + fn a_selection_that_covers_no_whole_item_is_offered_nothing() { + let tree = Tree::new("nothing"); + let (ws, uri) = opened(&tree); + let half = Range { + start: Position { line: 6, character: 2 }, + end: Position { line: 6, character: 8 }, + }; + assert!(code_actions(&ws, &uri, half).is_empty()); + } + + #[test] + fn the_command_creates_the_new_file_for_a_client_that_can() { + let tree = Tree::new("create"); + let (ws, uri) = opened(&tree); + let arguments = vec![ + serde_json::to_value(&uri).expect("uri"), + serde_json::to_value(selection()).expect("range"), + Value::String("sum".to_string()), + ]; + let (edit, warnings) = execute(&ws, &arguments, true).expect("extracts"); + assert!(warnings.iter().any(|w| w.contains("sum.sv")), "{warnings:?}"); + let Some(DocumentChanges::Operations(ops)) = edit.document_changes else { + panic!("a creating edit speaks documentChanges: {edit:?}") + }; + let creates = ops + .iter() + .filter(|op| matches!(op, DocumentChangeOperation::Op(ResourceOp::Create(_)))) + .count(); + assert_eq!(creates, 1, "one file is created: {ops:?}"); + assert_eq!(ops.len(), 3, "the creation plus one edit per file: {ops:?}"); + } + + #[test] + fn the_command_writes_the_module_into_the_same_file_for_a_client_that_cannot() { + let tree = Tree::new("same"); + let (ws, uri) = opened(&tree); + let arguments = vec![ + serde_json::to_value(&uri).expect("uri"), + serde_json::to_value(selection()).expect("range"), + Value::String("sum".to_string()), + ]; + let (edit, warnings) = execute(&ws, &arguments, false).expect("extracts"); + assert!( + warnings.iter().any(|w| w.contains("did not say it can create files")), + "{warnings:?}" + ); + assert!(edit.document_changes.is_none(), "no resource operation is needed"); + let changes = edit.changes.as_ref().expect("changes"); + assert_eq!(changes.len(), 1, "one file is touched"); + assert_eq!(changes.get(&uri).expect("this file").len(), 2); + } + + #[test] + fn the_command_says_why_when_there_is_nothing_to_extract() { + let tree = Tree::new("refuse"); + let (ws, uri) = opened(&tree); + let arguments = vec![ + serde_json::to_value(&uri).expect("uri"), + serde_json::to_value(Range { + start: Position { line: 0, character: 0 }, + end: Position { line: 0, character: 3 }, + }) + .expect("range"), + Value::String("sum".to_string()), + ]; + assert_eq!(execute(&ws, &arguments, true), Err(NOTHING.to_string())); + } + + #[test] + fn the_command_wants_all_three_of_its_arguments() { + let tree = Tree::new("arguments"); + let (ws, uri) = opened(&tree); + let short = vec![serde_json::to_value(&uri).expect("uri")]; + let message = execute(&ws, &short, true).expect_err("a refusal"); + assert!(message.contains("argument 2"), "{message}"); + } + + #[test] + fn a_client_asking_only_for_refactor_extract_is_answered() { + let filter = [CodeActionKind::REFACTOR_EXTRACT]; + assert!(crate::code_action::wanted(Some(&filter), &kind())); + assert!(!crate::code_action::wanted(Some(&filter), &CodeActionKind::QUICKFIX)); + } +} diff --git a/crates/lucisv_server/src/main.rs b/crates/lucisv_server/src/main.rs index 268957c..4f10709 100644 --- a/crates/lucisv_server/src/main.rs +++ b/crates/lucisv_server/src/main.rs @@ -13,6 +13,7 @@ mod convert; mod design_hierarchy; mod diagnostics; mod expand; +mod extract; mod file_ops; mod folding; mod format; @@ -60,11 +61,12 @@ use lsp_types::{ DocumentLinkOptions, DocumentOnTypeFormattingOptions, ExecuteCommandOptions, FoldingRangeProviderCapability, InitializeParams, InlayHintOptions, InlayHintServerCapabilities, LinkedEditingRangeServerCapabilities, OneOf, PositionEncodingKind, - RenameOptions, SaveOptions, SelectionRangeProviderCapability, SemanticTokensFullOptions, - SemanticTokensLegend, SemanticTokensOptions, SemanticTokensServerCapabilities, - ServerCapabilities, SignatureHelpOptions, TextDocumentSyncCapability, TextDocumentSyncKind, - TextDocumentSyncOptions, TextDocumentSyncSaveOptions, TypeDefinitionProviderCapability, - WorkDoneProgressOptions, WorkspaceFoldersServerCapabilities, WorkspaceServerCapabilities, + RenameOptions, ResourceOperationKind, SaveOptions, SelectionRangeProviderCapability, + SemanticTokensFullOptions, SemanticTokensLegend, SemanticTokensOptions, + SemanticTokensServerCapabilities, ServerCapabilities, SignatureHelpOptions, + TextDocumentSyncCapability, TextDocumentSyncKind, TextDocumentSyncOptions, + TextDocumentSyncSaveOptions, TypeDefinitionProviderCapability, WorkDoneProgressOptions, + WorkspaceFoldersServerCapabilities, WorkspaceServerCapabilities, }; use vlog_parser::PARSE_STACK_SIZE; @@ -128,6 +130,7 @@ fn main() -> Result<(), Box> { token_server_cancel: token_server_cancel_support(¶ms), hierarchy_view, code_action_resolve: code_action_resolve_support(¶ms), + create_files: create_files_support(¶ms), }; connection.initialize_finish(id, initialize_value(ranges_formatting)?)?; @@ -262,6 +265,7 @@ fn capabilities() -> ServerCapabilities { CodeActionKind::new(code_action::FIX_ALL), CodeActionKind::new(ports::REFACTOR_PORTS), imports::kind(), + extract::kind(), ]), work_done_progress_options: WorkDoneProgressOptions::default(), // The quick fixes are complete when they are offered; the port @@ -404,6 +408,7 @@ fn capabilities() -> ServerCapabilities { fn commands() -> Vec { let mut commands = ports::commands(); commands.extend(imports::commands()); + commands.extend(extract::commands()); commands.extend(instantiate::commands()); commands.extend(lens::commands()); commands @@ -526,6 +531,32 @@ fn code_action_resolve_support(params: &InitializeParams) -> bool { .is_some_and(|resolve| resolve.properties.iter().any(|property| property == "edit")) } +/// Whether the client can apply a `WorkspaceEdit` that **creates a file** — +/// `workspace.workspaceEdit.documentChanges` *and* a `resourceOperations` +/// list containing `create`. +/// +/// Both halves, because a creation is a resource operation and a resource +/// operation can only be sent inside `documentChanges`: a client with one and +/// not the other cannot apply the edit at all. A client that says nothing gets +/// the extracted module written below the one it came from, in the file it +/// came from, which needs no capability of any kind +/// (`docs/features/extract-inline-module/README.md`). +fn create_files_support(params: &InitializeParams) -> bool { + let Some(edits) = params + .capabilities + .workspace + .as_ref() + .and_then(|workspace| workspace.workspace_edit.as_ref()) + else { + return false; + }; + let creates = edits + .resource_operations + .as_ref() + .is_some_and(|kinds| kinds.contains(&ResourceOperationKind::Create)); + edits.document_changes.unwrap_or(false) && creates +} + /// Whether the client applies a `workspace/applyEdit` request. /// /// A client that did not say so gets a command's edit back as the request @@ -1182,6 +1213,51 @@ mod tests { ); } + #[test] + fn create_files_support_needs_both_halves_of_the_capability() { + use lsp_types::{ + ClientCapabilities, ResourceOperationKind, WorkspaceClientCapabilities, + WorkspaceEditClientCapabilities, + }; + assert!( + !create_files_support(&InitializeParams::default()), + "silence means the module goes below the one it came from" + ); + + let saying = |document_changes: Option, ops: Option<&[ResourceOperationKind]>| { + InitializeParams { + capabilities: ClientCapabilities { + workspace: Some(WorkspaceClientCapabilities { + workspace_edit: Some(WorkspaceEditClientCapabilities { + document_changes, + resource_operations: ops.map(<[_]>::to_vec), + ..Default::default() + }), + ..Default::default() + }), + ..Default::default() + }, + ..Default::default() + } + }; + let create = [ResourceOperationKind::Create]; + let rename = [ResourceOperationKind::Rename]; + assert!(create_files_support(&saying(Some(true), Some(&create))), "what VS Code sends"); + assert!( + !create_files_support(&saying(Some(true), Some(&rename))), + "a client that can rename but not create cannot apply the creation" + ); + assert!( + !create_files_support(&saying(Some(true), None)), + "no resource operations at all is no creation" + ); + assert!( + !create_files_support(&saying(None, Some(&create))), + "a resource operation can only be sent inside `documentChanges`" + ); + assert!(!create_files_support(&saying(Some(false), Some(&create)))); + } + #[test] fn code_action_resolve_support_is_read_from_the_clients_own_capabilities() { use lsp_types::{ diff --git a/crates/lucisv_server/src/server/dispatch.rs b/crates/lucisv_server/src/server/dispatch.rs index acd3b3c..4338233 100644 --- a/crates/lucisv_server/src/server/dispatch.rs +++ b/crates/lucisv_server/src/server/dispatch.rs @@ -44,9 +44,9 @@ use serde_json::Value; use super::client::ms; use super::Server; use crate::{ - code_action, completion, design_hierarchy, file_ops, folding, format, hierarchy, hover, - imports, includes, inlay, inline, lens, linked, lint, nav, pairs, ports, rename, selection, - signature, symbols, tokens, type_def, type_hierarchy, + code_action, completion, design_hierarchy, extract, file_ops, folding, format, hierarchy, + hover, imports, includes, inlay, inline, lens, linked, lint, nav, pairs, ports, rename, + selection, signature, symbols, tokens, type_def, type_hierarchy, }; impl Server { @@ -278,6 +278,14 @@ impl Server { false => imports::code_actions(&self.workspace, &uri, offset), }); } + // Extracting a selection into a module of its own. This one + // answers for the *range*, not the cursor, and carries a + // command rather than an edit — it needs a name for the new + // module, and only a command can be intercepted by a client + // that wants to ask the user for one. + if code_action::wanted(only.as_deref(), &extract::kind()) { + actions.extend(extract::code_actions(&self.workspace, &uri, p.range)); + } to_value(actions) }), // The edit for an action offered without one. An action that @@ -360,6 +368,22 @@ impl Server { Err(message) => Err(Failure::Request(message)), }; } + // Extracting takes the client's own capability with it: only + // a client that can apply a `CreateFile` gets the new module + // in a file of its own. + if p.command == extract::EXTRACT_MODULE { + return match extract::execute( + &self.workspace, + &p.arguments, + self.abilities.create_files, + ) { + Ok((edit, warnings)) => { + self.report_scope(warnings); + self.deliver(&p.command, edit) + } + Err(message) => Err(Failure::Request(message)), + }; + } match ports::execute(&self.workspace, &p.command, &p.arguments) { Ok((edit, warnings)) => { self.report_scope(warnings); diff --git a/crates/lucisv_server/src/server/mod.rs b/crates/lucisv_server/src/server/mod.rs index f4572cc..9f358d5 100644 --- a/crates/lucisv_server/src/server/mod.rs +++ b/crates/lucisv_server/src/server/mod.rs @@ -111,6 +111,13 @@ pub struct ClientAbilities { /// which is what every client got before this was read /// (`docs/features/lazy-code-action/README.md`). pub code_action_resolve: bool, + /// Whether the client can apply a `WorkspaceEdit` that creates a file — + /// `workspace.workspaceEdit.documentChanges` plus a `resourceOperations` + /// list containing `create`. Only then does an extracted module get a + /// file of its own; a client that said nothing gets it written below the + /// module it came from + /// (`docs/features/extract-inline-module/README.md`). + pub create_files: bool, } /// Everything the server owns. diff --git a/crates/vlog_refactor/src/check/ledger.rs b/crates/vlog_refactor/src/check/ledger.rs new file mode 100644 index 0000000..a7926a9 --- /dev/null +++ b/crates/vlog_refactor/src/check/ledger.rs @@ -0,0 +1,888 @@ +//! The lexical half of the splice contract: the pieces a file is made of, the +//! comparison that says an edit wrote exactly what it promised, and the ledger +//! of the pieces that are never dropped. +//! +//! [`super::verify_splice`] and [`super::verify_move`] are the callers, and the +//! difference between them lives here: a splice balances every never-dropped +//! piece inside one file, while a move is allowed to carry the pieces of one +//! region into the file that receives them — [`Transit`] is that allowance and +//! the whole of it. + +use std::collections::HashMap; +use std::path::Path; + +use vlog_parser::span::TextRange; +use vlog_parser::token::TokenKind; +use vlog_parser::tokenize; + +use crate::rename::display; +use crate::TextEdit; + +// ---------------------------------------------------------------------- +// lexical splice +// ---------------------------------------------------------------------- + +/// One lexical piece of a file, in source order: a code token, or a comment. +/// Comments are pieces of their own rather than trivia hanging off a token, +/// because an insertion can legitimately move which token a comment attaches +/// to without moving the comment itself. +#[derive(Debug, Clone, PartialEq, Eq)] +enum Piece { + Code(TokenKind, String), + Comment(String), +} + +impl Piece { + /// How the piece is named in a refusal. + fn describe(&self) -> String { + match self { + Piece::Code(_, text) => format!("the token `{text}`"), + Piece::Comment(text) => format!("the comment `{text}`"), + } + } +} + +/// Every piece of a file with the bytes it occupies, in source order. +fn pieces(text: &str) -> Option> { + let tokens = tokenize(text).ok()?; + let mut out: Vec<(TextRange, Piece)> = Vec::new(); + for token in &tokens { + for comment in &token.leading { + out.push((comment.span, Piece::Comment(comment.text.clone()))); + } + if token.kind != TokenKind::Eof { + out.push((token.span, Piece::Code(token.kind, token.text.clone()))); + } + if let Some(comment) = &token.trailing { + out.push((comment.span, Piece::Comment(comment.text.clone()))); + } + } + out.sort_by_key(|(span, _)| (span.start, span.end)); + Some(out) +} + +/// One file's three streams of pieces: what it had, what it has, and what the +/// edits themselves spell. +pub(super) struct Split { + old: Vec<(TextRange, Piece)>, + new: Vec<(TextRange, Piece)>, + written: Vec>, +} + +impl Split { + /// Lex all three, or say which one lucisv could not read. + pub(super) fn read( + before: &str, + after: &str, + edits: &[TextEdit], + path: &Path, + what: &str, + ) -> Result { + let (Some(old), Some(new)) = (pieces(before), pieces(after)) else { + return Err(format!( + "{} would no longer lex after {what}; no edits were made.", + display(path) + )); + }; + let mut written: Vec> = Vec::new(); + for edit in edits { + let Some(pieces) = pieces(&edit.new_text) else { + return Err(format!( + "{what} would write text that does not lex; no edits were made." + )); + }; + written.push(pieces); + } + Ok(Split { old, new, written }) + } + + /// The edited file must lex to the original's pieces with the edits' own + /// pieces written in where the edits are — and to nothing else. + pub(super) fn positions_match( + &self, + edits: &[TextEdit], + path: &Path, + what: &str, + ) -> Result<(), String> { + let clone = |pieces: &[(TextRange, Piece)]| -> Vec { + pieces + .iter() + .map(|(_, piece)| match piece { + Piece::Code(kind, text) => Piece::Code(*kind, text.clone()), + Piece::Comment(text) => Piece::Comment(text.clone()), + }) + .collect() + }; + let mut expected: Vec = Vec::new(); + let mut next = 0usize; + for (span, piece) in &self.old { + while let (Some(edit), Some(pieces)) = (edits.get(next), self.written.get(next)) { + if edit.range.start > span.start { + break; + } + expected.extend(clone(pieces)); + next += 1; + } + if edits.iter().any(|e| !e.range.is_empty() && overlaps(e.range, *span)) { + continue; + } + expected.push(piece.clone()); + } + while let Some(pieces) = self.written.get(next) { + expected.extend(clone(pieces)); + next += 1; + } + + let actual = clone(&self.new); + for (n, expected) in expected.iter().enumerate() { + match actual.get(n) { + Some(actual) if actual == expected => {} + Some(actual) => { + return Err(format!( + "{what} would write {} where {} belongs in {}; no edits were made.", + actual.describe(), + expected.describe(), + display(path) + )) + } + None => { + return Err(format!( + "{what} would lose {} in {}; no edits were made.", + expected.describe(), + display(path) + )) + } + } + } + if actual.len() > expected.len() { + let extra = actual.get(expected.len()).map_or_else(String::new, Piece::describe); + return Err(format!( + "{what} would add {extra} to {}, which is not part of the edit; no edits were made.", + display(path) + )); + } + Ok(()) + } +} + +/// The per-file contract: the never-dropped ledger, checked on the spot, and +/// then the positional comparison. The order is the one that gives the most +/// useful sentence — a dropped comment is said as a dropped comment rather +/// than as a piece that went missing from position 47. +pub(super) fn pieces_match( + split: &Split, + edits: &[TextEdit], + path: &Path, + what: &str, +) -> Result<(), String> { + let ledger = Ledger::of(split, edits, TextRange::empty(0)); + ledger.check(&display(path), what, &Tally::new())?; + split.positions_match(edits, path, what) +} + +/// The range the move takes text out of file `i`, if it names that file at all: +/// a source's own region, or the empty range that says "this one only +/// receives". A file the move does not name has none, and keeps the per-file +/// contract. +pub(super) fn region_of(moving: &[(usize, TextRange)], i: usize) -> Option { + moving.iter().find(|(file, _)| *file == i).map(|(_, region)| *region) +} + +/// Whether a piece sits inside the bytes a move takes out of its file. An +/// empty region holds nothing: a destination has no region, and a piece that +/// only *overlaps* a region is one the move did not wholly carry, so it is an +/// ordinary deletion and has to be written back where it was. +fn within(region: TextRange, span: TextRange) -> bool { + !region.is_empty() && region.start <= span.start && span.end <= region.end +} + +/// 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, `wrote` counts the pieces lexed out of the +/// edits' own inserted text, and `out` counts the pieces of `gone` that a move +/// carried out of this file — zero for every file that is not the source of +/// one, which is every file but an extraction's. +/// +/// 1. **`has + out >= had`** — nothing is ever lost. This is the whole of +/// invariant 3 and the only half the rule this replaced had; a file may end +/// up short only by exactly what left through its own moved region. +/// 2. **`wrote <= gone - out + in`**, 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. `in` is the transit a **destination** of a +/// move may receive and is zero everywhere else, so a deletion outside the +/// moved region has to be written back in its own file as it always did. +/// 3. **`has == had - gone + wrote`** — the applied text says exactly what the +/// edits say, transit out counted as gone and transit in as wrote. 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. +/// +/// **A ledger is one file's**, always. [`pieces_match`] checks it with no +/// transit at all, which is the contract every refactoring that stays inside +/// one file has always had. [`super::verify_move`] gives the source of a move its +/// region — so the comment carried out of `M.sv` is `out` rather than lost — +/// and the destination the allowance to receive it, and then [`Transit`] holds +/// the two halves to each other. See +/// `docs/features/extract-inline-module/README.md` for the attack pairs. +#[derive(Default)] +struct Ledger { + /// The pieces the file had before the edits. + before: Tally, + /// The pieces it has after them. + after: Tally, + /// The old pieces a non-empty edit range covers. + deleted: Tally, + /// Of those, the ones inside the region a move takes out of this file. + out: Tally, + /// The pieces the edits' own inserted text spells. + writes: Tally, +} + +impl Ledger { + /// Count one file's streams. `region` is the bytes a move carries out of + /// it — empty for every file that keeps the per-file contract, and for a + /// file that only receives. + fn of(split: &Split, edits: &[TextEdit], region: TextRange) -> Ledger { + let covered = |span: TextRange| { + edits.iter().any(|edit| !edit.range.is_empty() && overlaps(edit.range, span)) + }; + let mut out = Ledger::default(); + tally_into(&mut out.before, split.old.iter().map(|(_, piece)| piece)); + tally_into(&mut out.after, split.new.iter().map(|(_, piece)| piece)); + tally_into( + &mut out.deleted, + split.old.iter().filter(|(span, _)| covered(*span)).map(|(_, piece)| piece), + ); + tally_into( + &mut out.out, + split + .old + .iter() + .filter(|(span, _)| covered(*span) && within(region, *span)) + .map(|(_, piece)| piece), + ); + tally_into(&mut out.writes, split.written.iter().flatten().map(|(_, piece)| piece)); + out + } + + /// The three equations, for this one file. `where_` names it, already + /// quoted for a sentence; `receives` is the transit it may be handed by + /// the rest of the move, and is empty for every file that is not a + /// destination of one. + fn check(&self, where_: &str, what: &str, receives: &Tally) -> Result<(), String> { + let mut texts: Vec<&Kept> = + self.before.keys().chain(self.after.keys()).chain(self.writes.keys()).collect(); + texts.sort_unstable(); + texts.dedup(); + let count = |tally: &Tally, key: &Kept| tally.get(key).copied().unwrap_or(0); + // `out` is a subset of `deleted`, 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 ordinary = |key: &Kept| count(&self.deleted, key).saturating_sub(count(&self.out, key)); + + // 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(&self.after, key) + count(&self.out, key) < count(&self.before, key)) + { + return Err(format!( + "{what} would delete the {noun} `{text}` in {where_}; {noun}s are never dropped, so nothing was edited." + )); + } + if let Some(key) = texts.iter().find(|key| { + count(&self.writes, key) > ordinary(key) + count(receives, key) && !generated(&key.1) + }) { + let Kept(noun, text) = key; + let (gone, wrote) = (ordinary(key), count(&self.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 {where_} {deletes}; {noun}s are never duplicated, so nothing was edited.", + times(wrote) + )); + } + // `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(&self.before, key).saturating_sub(count(&self.deleted, key)) + + count(&self.writes, key) + }; + if let Some(key) = texts.iter().find(|key| count(&self.after, key) != accounted(key)) { + let Kept(noun, text) = key; + return Err(format!( + "{what} would leave the {noun} `{text}` in {where_} {}, where its edits account for it {}; nothing was edited.", + times(count(&self.after, key)), + times(accounted(key)) + )); + } + Ok(()) + } + + /// How many more of a piece this file's edits write than they delete — + /// what a destination of a move has to have received. + fn gained(&self, key: &Kept) -> i64 { + let count = |tally: &Tally| tally.get(key).copied().unwrap_or(0) as i64; + count(&self.writes) - count(&self.deleted) + } +} + +/// The files a move names, and the never-dropped pieces travelling between +/// them: a **source** loses the pieces inside its own region, and a +/// **destination** — a file the move names with an empty range — is the only +/// place they may land. +/// +/// This is the whole of the widening [`super::verify_move`] exists for, and +/// the whole of what it is allowed to forgive: the allowance is bound to the +/// bytes that move, so a piece deleted anywhere else in one of these files is +/// an ordinary deletion its own ledger holds it to. +#[derive(Default)] +pub(super) struct Transit { + files: Vec, +} + +/// One file of a move: what a refusal calls it, whether it receives rather +/// than sends, and its own ledger. +struct Moved { + where_: String, + receives: bool, + ledger: Ledger, +} + +impl Transit { + /// Take one file's counts, with the region the move carries text out of. + pub(super) fn add( + &mut self, + where_: &str, + region: TextRange, + split: &Split, + edits: &[TextEdit], + ) { + self.files.push(Moved { + where_: where_.to_string(), + receives: region.is_empty(), + ledger: Ledger::of(split, edits, region), + }); + } + + /// The three equations per file — the destinations, and only they, holding + /// the transit as their allowance — and then rule 4 over the move whole. + pub(super) fn check(&self, what: &str) -> Result<(), String> { + let mut sent = Tally::new(); + for file in &self.files { + for (key, n) in &file.ledger.out { + *sent.entry(key.clone()).or_insert(0) += n; + } + } + let nothing = Tally::new(); + for file in &self.files { + let receives = match file.receives { + true => &sent, + false => ¬hing, + }; + file.ledger.check(&file.where_, what, receives)?; + } + self.lands(&sent, what) + } + + /// Rule 4: what left a region has to land, exactly once in total, in the + /// files the move named as destinations. Rule 2 lets each destination + /// receive the transit; this is what says the move as a whole received it + /// once — two destinations that each write the comment are two comments. + fn lands(&self, sent: &Tally, what: &str) -> Result<(), String> { + let names = |receives: bool| -> Vec { + self.files.iter().filter(|f| f.receives == receives).map(|f| f.where_.clone()).collect() + }; + let mut texts: Vec<&Kept> = sent.keys().collect(); + texts.sort_unstable(); + for key in texts { + let out = sent.get(key).copied().unwrap_or(0); + let landed: i64 = + self.files.iter().filter(|f| f.receives).map(|f| f.ledger.gained(key)).sum(); + if landed == out as i64 { + continue; + } + let Kept(noun, text) = key; + let rule = match landed < out as i64 { + true => format!("{noun}s are never dropped"), + false => format!("{noun}s are never duplicated"), + }; + let (sources, destinations) = (names(false), names(true)); + let landing = match landed > 0 { + true => format!("{} into {}", times(landed as usize), and_list(&destinations)), + false => "nowhere".to_string(), + }; + return Err(format!( + "{what} would move the {noun} `{text}` out of {} {} and write it back {landing}; {rule}, so nothing was edited.", + and_list(&sources), + times(out) + )); + } + Ok(()) + } +} + +/// One never-dropped piece, keyed for counting: the noun a refusal calls it by +/// (`comment` or `attribute`) and its exact text. +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +struct Kept(&'static str, String); + +type Tally = HashMap; + +/// How many of each never-dropped piece a stream of pieces holds. Every other +/// piece is a code token the comparison above already pins position by +/// position, so it is not counted here. +fn tally_into<'p>(out: &mut Tally, pieces: impl Iterator) { + 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; + } +} + +/// 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. +pub(super) fn overlaps(a: TextRange, b: TextRange) -> bool { + a.start < b.end && b.start < a.end +} + +/// A list of file names as a sentence reads them: `a.sv`, `a.sv` and `b.sv`, +/// `a.sv`, `b.sv` and `c.sv`. +fn and_list(names: &[String]) -> String { + let quoted: Vec = names.iter().map(|name| format!("`{name}`")).collect(); + match quoted.split_last() { + None => "no files".to_string(), + Some((last, [])) => last.clone(), + Some((last, head)) => format!("{} and {last}", head.join(", ")), + } +} + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + + use super::*; + use crate::apply; + + /// The per-file splice contract, over texts — one lex plus the production + /// [`super::pieces_match`], so every attack below asks the real question. + fn pieces_match( + before: &str, + after: &str, + edits: &[TextEdit], + path: &Path, + what: &str, + ) -> Result<(), String> { + let split = Split::read(before, after, edits, path, what)?; + super::pieces_match(&split, edits, path, what) + } + + // ------------------------------------------------------------------ + // the splice verifier, and the attacks on it + // ------------------------------------------------------------------ + + /// A module whose port list is one per line, with a comment on each port — + /// the shape every one of the attacks below tries to damage. + const PORTS: &str = + "module m (\n input clk, // the clock\n input rst /* sync */\n);\n wire a; // a\nendmodule\n"; + + /// The edit `add_port` produces for `PORTS`: a `,` before the last port's + /// comment and the new port after it. + fn add_edits() -> Vec { + let end = PORTS.find("input rst").expect("rst") as u32 + "input rst".len() as u32; + let after_comment = PORTS.find("*/").expect("comment") as u32 + 2; + vec![ + TextEdit { range: TextRange::empty(end), new_text: ",".into() }, + TextEdit { + range: TextRange::empty(after_comment), + new_text: "\n input logic [7:0] cfg".into(), + }, + ] + } + + fn splice_attack(corrupted: &str) -> Result<(), String> { + pieces_match(PORTS, corrupted, &add_edits(), Path::new("/rtl/m.sv"), "adding port `cfg`") + } + + #[test] + fn the_splice_the_engine_actually_produces_verifies() { + let honest = apply(PORTS, &add_edits()); + assert_eq!(splice_attack(&honest), Ok(()), "the real output must pass"); + assert!(honest.contains("input rst, /* sync */\n input logic [7:0] cfg"), "{honest}"); + } + + #[test] + fn a_splice_that_wrote_the_comma_into_a_line_comment_is_rejected() { + // The hazard the two-edit shape exists to avoid: a `,` after `//` is a + // `,` nobody will ever see. + let corrupted = PORTS + .replace("// the clock", "// the clock,") + .replace("input rst /* sync */", "input rst /* sync */\n input logic [7:0] cfg"); + assert!(splice_attack(&corrupted).is_err(), "a comma inside a comment is not an edit"); + } + + #[test] + fn a_splice_that_landed_at_the_wrong_place_is_rejected() { + // The same tokens, spliced one port earlier: every piece is accounted + // for, but not in the order the edits promised. + let corrupted = apply(PORTS, &add_edits()) + .replace("input clk,", "input clk, input logic [7:0] cfg,") + .replace(",\n input logic [7:0] cfg\n)", "\n)"); + assert!(splice_attack(&corrupted).is_err(), "position is part of the promise"); + } + + #[test] + fn a_splice_that_also_dropped_a_comment_is_rejected() { + let corrupted = apply(PORTS, &add_edits()).replace(" // a", ""); + let message = splice_attack(&corrupted).expect_err("a dropped comment is a refusal"); + assert!(message.contains("comments are never dropped"), "{message}"); + } + + #[test] + fn a_splice_that_also_rewrote_an_untouched_token_is_rejected() { + let corrupted = apply(PORTS, &add_edits()).replace("wire a;", "wire b;"); + assert!(splice_attack(&corrupted).is_err(), "nothing outside the edit may move"); + } + + #[test] + fn a_splice_that_wrote_more_than_it_promised_is_rejected() { + let corrupted = apply(PORTS, &add_edits()).replace("wire a;", "wire a; wire extra;"); + assert!(splice_attack(&corrupted).is_err(), "an invented declaration"); + } + + #[test] + fn a_splice_that_landed_inside_a_string_is_rejected() { + let text = "module m;\n initial $display(\"hello\");\nendmodule\n"; + let at = text.find("hello").expect("string") as u32; + let edits = vec![TextEdit { range: TextRange::empty(at), new_text: "x".into() }]; + let corrupted = apply(text, &edits); + let outcome = pieces_match(text, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit"); + assert!(outcome.is_err(), "the string's own text is not a token lucisv may write"); + } + + #[test] + fn a_deletion_that_would_swallow_a_comment_is_refused() { + // The one rule the piece comparison cannot see on its own: a comment + // inside a deleted range disappears from *both* sides. + let start = PORTS.find("input rst").expect("rst") as u32; + let end = PORTS.find("*/").expect("comment") as u32 + 2; + let edits = vec![TextEdit { range: TextRange::new(start, end), new_text: String::new() }]; + let corrupted = apply(PORTS, &edits); + let outcome = + pieces_match(PORTS, &corrupted, &edits, Path::new("/rtl/m.sv"), "removing port `rst`"); + let message = outcome.expect_err("a deleted comment is a refusal"); + assert!(message.contains("comments are never dropped"), "{message}"); + } + + #[test] + fn a_splice_whose_result_does_not_lex_is_rejected() { + let corrupted = apply(PORTS, &add_edits()).replace("endmodule", "/* oops"); + assert!(splice_attack(&corrupted).is_err(), "an unlexable result is a failure, not output"); + } + + // ------------------------------------------------------------------ + // the moved-comment rule, and the attacks on it (CLAUDE.md invariant 4) + // ------------------------------------------------------------------ + // + // 2026-09-05: `comments_kept` replaced "no deletion may cover a comment", + // so that `ports::ansi` can move a body declaration's comment onto the + // ANSI port that declaration becomes. Every attack below is a crafted + // (input, corrupted output) pair the relaxation could plausibly forgive. + + /// A Verilog-2001 header whose two declarations each carry a comment — + /// the shape the ANSI conversion has to move a comment out of. + const MOVED: &str = + "module m (\n a,\n b\n);\n input a; // the note\n output b; // the note\nendmodule\n"; + + /// The edits `convert_to_ansi` really produces for `MOVED`. + fn move_edits() -> Vec { + let files = vec![(PathBuf::from("/rtl/m.sv"), MOVED.to_string())]; + let at = MOVED.find("module m").expect("header") as u32; + let edit = crate::convert_to_ansi(&files, Path::new("/rtl/m.sv"), at) + .expect("the conversion the attacks corrupt"); + edit.edits.into_iter().next().expect("one file").1 + } + + fn move_attack(corrupted: &str) -> Result<(), String> { + pieces_match( + MOVED, + corrupted, + &move_edits(), + Path::new("/rtl/m.sv"), + "converting `m`'s ports to ANSI", + ) + } + + #[test] + fn the_moved_comments_the_engine_actually_writes_verify() { + let honest = apply(MOVED, &move_edits()); + assert_eq!(move_attack(&honest), Ok(()), "the real output must pass"); + assert_eq!(honest.matches("// the note").count(), 2, "both comments survive: {honest}"); + assert!(honest.contains("input a, // the note"), "{honest}"); + } + + #[test] + fn a_move_that_kept_only_one_of_two_identical_comments_is_rejected() { + // The exact hole the character budget exists for: one of the two + // `// the note`s is dropped, and a search for its text still finds + // the other one. + let corrupted = apply(MOVED, &move_edits()).replacen(" // the note", "", 1); + let message = move_attack(&corrupted).expect_err("one comment short is a refusal"); + assert!(message.contains("comments are never dropped"), "{message}"); + } + + #[test] + fn a_move_that_dropped_a_comment_and_invented_another_is_rejected() { + // Same character count, different text: the budget alone would + // forgive this one, and the per-comment search does not. + let corrupted = apply(MOVED, &move_edits()).replacen("// the note", "// the NOTE", 1); + let message = move_attack(&corrupted).expect_err("a rewritten comment is a refusal"); + assert!(message.contains("comments are never dropped"), "{message}"); + } + + #[test] + fn a_move_that_shortened_a_comment_is_rejected() { + let corrupted = apply(MOVED, &move_edits()).replacen("// the note", "// the", 1); + let message = move_attack(&corrupted).expect_err("a truncated comment is a refusal"); + assert!(message.contains("comments are never dropped"), "{message}"); + } + + #[test] + fn a_move_that_left_the_comment_where_it_was_is_rejected() { + // The deletion really deleted, but the comment was written back into + // the *body* rather than into the header: every comment is still + // there, and the piece order is not what the edits promised. + let honest = apply(MOVED, &move_edits()); + let corrupted = honest + .replace("input a, // the note", "input a,") + .replace("endmodule", "// the note\nendmodule"); + // `never_dropped` passes this one: every count is equal on both sides + // (the comment really was deleted and really was written back once). + // The *piece comparison* is the guard, because where a comment lands + // is bound to where the edits put it — which is also the answer to + // "a comment deleted here and written back somewhere unrelated". + let message = move_attack(&corrupted).expect_err("a misplaced comment is a refusal"); + assert!(message.contains("where the comment `// the note` belongs"), "{message}"); + } + + #[test] + fn a_move_that_wrote_the_comment_onto_two_ports_is_rejected() { + // The bug this half of the rule was added for, reproduced as the edits + // that caused it: one declaration declares two ports, and its comment + // is written onto *both*. Nothing is dropped, and the piece comparison + // cannot object — it checks the edits against themselves, and the + // duplicate is in the edits. Only counting the file's comments sees it. + const SHARED: &str = "module m (\n a,\n b\n);\n input a, b; // both\nendmodule\n"; + let at = |needle: &str| SHARED.find(needle).expect(needle) as u32; + let (a, b) = (at("\n a,") + 3, at("\n b\n") + 3); + let edits = vec![ + TextEdit { range: TextRange::empty(a), new_text: "input ".into() }, + TextEdit { range: TextRange::empty(a + 2), new_text: " // both".into() }, + TextEdit { range: TextRange::empty(b), new_text: "input ".into() }, + TextEdit { range: TextRange::empty(b + 1), new_text: " // both".into() }, + TextEdit { + range: TextRange::new(at(" input a,"), at("endmodule")), + new_text: String::new(), + }, + ]; + let corrupted = apply(SHARED, &edits); + assert_eq!(corrupted.matches("// both").count(), 2, "the attack really doubles it"); + let message = pieces_match(SHARED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit") + .expect_err("a doubled comment is a refusal"); + assert!(message.contains("would write the comment"), "{message}"); + } + + #[test] + fn a_deletion_that_swallows_a_comment_nothing_writes_back_is_still_refused() { + // The old rule's own case, restated: no edit writes the comment, so + // the relaxation must not reach it. + let start = MOVED.find("input a;").expect("a") as u32; + let end = MOVED.find("\n output").expect("output") as u32; + let edits = vec![TextEdit { range: TextRange::new(start, end), new_text: String::new() }]; + let corrupted = apply(MOVED, &edits); + let message = pieces_match(MOVED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit") + .expect_err("a deleted comment nothing writes back is a refusal"); + assert!(message.contains("comments are never dropped"), "{message}"); + } + + // ------------------------------------------------------------------ + // 2026-09-05 rework: the duplication half, the equation, and attributes + // ------------------------------------------------------------------ + + #[test] + fn an_insertion_that_duplicates_an_untouched_comment_is_rejected() { + // QA's V-1 pair. Nothing deletes — or even overlaps — the body's own + // `// shared`, and two pure insertions each write it again. Every + // count only grows, so "before is a subset of after" forgives it, and + // the piece comparison cannot object because the duplicates are in the + // edits. Only `wrote <= gone` sees it. + const SHARED: &str = + "module m (\n a,\n b\n);\n input a; // shared\n output b;\nendmodule\n"; + let at = |needle: &str| SHARED.find(needle).expect(needle) as u32; + let (a, b) = (at("\n a,") + 4, at("\n b\n") + 4); + let edits = vec![ + TextEdit { range: TextRange::empty(a), new_text: " // shared".into() }, + TextEdit { range: TextRange::empty(b), new_text: " // shared".into() }, + ]; + let corrupted = apply(SHARED, &edits); + assert_eq!(corrupted.matches("// shared").count(), 3, "the attack really triples it"); + let message = pieces_match(SHARED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit") + .expect_err("a duplicated comment is a refusal"); + assert!(message.contains("comments are never duplicated"), "{message}"); + } + + #[test] + fn a_generated_placeholder_may_be_written_where_the_file_already_has_one() { + // The whitelist, and the whole of it. `add_port` and + // `propagate_ports` write `/* TODO: connect */` themselves, and a + // module gains its ports one at a time — so the second addition to a + // file finds the first one's placeholder already sitting there and + // writes another. `wrote > gone` with nothing deleted, and legitimate. + let source = "module top;\n sub u1 (.a(/* TODO: connect */));\nendmodule\n"; + let at = source.find("))").expect("list") as u32 + 1; + let edits = vec![TextEdit { + range: TextRange::empty(at), + new_text: ", .b(/* TODO: connect */)".into(), + }]; + let spliced = apply(source, &edits); + assert_eq!(spliced.matches("TODO").count(), 2, "{spliced}"); + let outcome = + pieces_match(source, &spliced, &edits, Path::new("/rtl/top.sv"), "adding port `b`"); + assert_eq!(outcome, Ok(()), "a generated placeholder is the engine's own text"); + } + + #[test] + fn an_application_that_grew_a_copy_the_edits_do_not_write_is_rejected() { + // Masked corruption of the third kind: the edits are honest — they + // delete both `// the note`s and write both back — and the *applied* + // text carries a third. Neither "nothing is lost" nor "written back + // where it was deleted" can see that; only the equation can. + let corrupted = apply(MOVED, &move_edits()).replace("endmodule", "// the note\nendmodule"); + let message = move_attack(&corrupted).expect_err("an invented copy is a refusal"); + assert!(message.contains("where its edits account for it"), "{message}"); + } + + #[test] + fn a_comment_written_back_inside_a_string_or_another_comment_is_rejected() { + // A `//` is only a comment where the lexer says it is. Written back + // inside a string literal, or swallowed into the comment next to it, + // the text is present in the file and absent from its pieces — which + // is exactly the substring search this rule refuses to be. + let honest = apply(MOVED, &move_edits()); + let in_string = honest + .replacen(" // the note", "", 1) + .replace("endmodule", " initial $display(\"// the note\");\nendmodule"); + let message = move_attack(&in_string).expect_err("a string is not a comment"); + assert!(message.contains("comments are never dropped"), "{message}"); + + let nested = honest + .replacen(" // the note", "", 1) + .replace("// the note", "// the note // the note"); + let message = move_attack(&nested).expect_err("one comment is not two"); + assert!(message.contains("comments are never dropped"), "{message}"); + } + + /// A body declaration carrying an attribute instance. `Item.span` covers + /// the `(* keep *)`, so a deletion hides it from *both* sides of the piece + /// comparison exactly the way it hides a comment — QA's finding V-2. + const ATTRIBUTED: &str = "module m (\n a\n);\n (* keep *) input a;\nendmodule\n"; + + /// The edits an absorbing conversion of `ATTRIBUTED` makes: `input ` (plus + /// whatever `written` says) before the header name, and the whole body + /// declaration gone. + fn attribute_edits(written: &str) -> Vec { + let at = |needle: &str| ATTRIBUTED.find(needle).expect(needle) as u32; + vec![ + TextEdit { range: TextRange::empty(at("\n a\n") + 3), new_text: written.into() }, + TextEdit { + range: TextRange::new(at(" (* keep *)"), at("endmodule")), + new_text: String::new(), + }, + ] + } + + fn attribute_attack(edits: &[TextEdit]) -> Result<(), String> { + let corrupted = apply(ATTRIBUTED, edits); + pieces_match( + ATTRIBUTED, + &corrupted, + edits, + Path::new("/rtl/m.sv"), + "converting `m`'s ports to ANSI", + ) + } + + #[test] + fn a_deletion_that_swallows_an_attribute_is_rejected() { + // The planner refuses this one first (`ports::ansi::attributes_clear`, + // pinned in `tests/ansi.rs`); this is the verifier saying so a second + // time, from the edits alone, for whatever writes them next. + let message = attribute_attack(&attribute_edits("input ")) + .expect_err("a dropped attribute is a refusal"); + assert!(message.contains("attributes are never dropped"), "{message}"); + assert!(message.contains("`(* keep *)`"), "{message}"); + } + + #[test] + fn an_edit_that_moves_an_attribute_verifies() { + // What the refusal above is protecting: an edit that really does carry + // the attribute over is not what this rule is for. + let edits = attribute_edits("(* keep *) input "); + assert_eq!(attribute_attack(&edits), Ok(()), "a moved attribute is a kept attribute"); + assert!(apply(ATTRIBUTED, &edits).contains("(* keep *) input a")); + } + + #[test] + fn an_edit_that_rewrote_an_attribute_is_rejected() { + // `(* keep *)` and `(* keep=1 *)` are not the same instruction to a + // synthesizer, and an attribute is matched by exact text. + let message = attribute_attack(&attribute_edits("(* keep=1 *) input ")) + .expect_err("a rewritten attribute is a refusal"); + assert!(message.contains("attributes are never dropped"), "{message}"); + } +} diff --git a/crates/vlog_refactor/src/check.rs b/crates/vlog_refactor/src/check/mod.rs similarity index 50% rename from crates/vlog_refactor/src/check.rs rename to crates/vlog_refactor/src/check/mod.rs index 45495ba..2dafaf2 100644 --- a/crates/vlog_refactor/src/check.rs +++ b/crates/vlog_refactor/src/check/mod.rs @@ -17,6 +17,8 @@ //! 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. +mod ledger; + use std::collections::HashMap; use std::path::{Path, PathBuf}; @@ -31,6 +33,8 @@ use vlog_semantic::{ use crate::rename::{contains_word, display, Scope}; use crate::{apply, Shift, TextEdit}; +use ledger::{overlaps, pieces_match, region_of, Split, Transit}; + /// Check the whole edit, or refuse it whole. pub(crate) fn verify( scope: &mut Scope, @@ -63,7 +67,7 @@ pub(crate) fn verify( // cannot see them. A file that spells *either* is watched, which is what // catches a third file whose existing `new_name` reference the rename // would make ambiguous without touching a byte of it. - let watched = watched_files(scope, edits, old_name, new_name); + let watched = watched_files(scope, edits, &[old_name, new_name]); for &i in &watched { if scope.analysis(i).is_none() { return Err(ABANDONED.to_string()); @@ -124,7 +128,7 @@ pub(crate) fn verify( /// 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`]. +/// port it becomes; see [`ledger::Ledger`]. /// 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 @@ -137,6 +141,54 @@ pub(crate) fn verify_splice( edits: &[(usize, Vec)], watch_name: &str, what: &str, +) -> Result<(), String> { + verify_move(scope, edits, &[watch_name], what, &[]) +} + +/// [`verify_splice`], for a refactoring that **moves text from one file into +/// another** — which is what extracting a module into its own file is. +/// +/// Everything is the same except the accounting of the pieces that are never +/// dropped. Per file, "a comment this edit deletes must be one this edit +/// writes back" is exactly right for every refactoring that stays inside one +/// file, and exactly wrong for a move: the comment is deleted in `M.sv` and +/// written in `N.sv`, so neither file balances on its own. +/// +/// **The widening is bound to the bytes that move, not to the files.** +/// `moving` names every file the move touches: a **source**, with the byte +/// range the move takes its text out of (the selection), and a +/// **destination** — a file that only receives — with an empty range. Per file +/// `f` and per never-dropped text `t`, where `before`/`after` are the file's +/// own counts, `gone` the old pieces a non-empty edit range covers, `wrote` the +/// pieces the edits' own text spells, and `out` the pieces of `gone` that sit +/// **inside** `f`'s region — the ones in transit: +/// +/// 1. `after_f + out_f >= before_f` — nothing is lost. A file may end up short +/// only by exactly what left through its own region. +/// 2. `wrote_f <= (gone_f - out_f) + in_f`, unless the text is one a +/// refactoring generated itself (`ledger::generated`) — nothing is duplicated. `in_f` is the whole +/// transit (`Σ out`) for a destination and zero for everyone else, so a +/// deletion *outside* the region is an ordinary deletion that has to be +/// written back in its own file exactly as before. +/// 3. `after_f == before_f - gone_f + wrote_f` — the applied text says exactly +/// what the edits say, transit out counted as gone and transit in as wrote. +/// 4. `Σ over destinations of (wrote - gone) == Σ over sources of out` — the +/// transit lands, exactly once, in the files the move named. +/// +/// A file `moving` does not name keeps the per-file contract untouched, so a +/// piece in transit to a file the move never named is refused twice over: by +/// that file's own rule 2, and by rule 4. See +/// `docs/features/extract-inline-module/README.md` for the attack pairs. +/// +/// `watched` are the names whose meaning the refactoring changes (the module +/// whose ports moved; both module names, for an extraction), which is what +/// widens the resolution check beyond the edited files. +pub(crate) fn verify_move( + scope: &mut Scope, + edits: &[(usize, Vec)], + watched_names: &[&str], + what: &str, + moving: &[(usize, TextRange)], ) -> Result<(), String> { let abandoned = format!("lucisv could not verify {what}, so it made no edits."); let edited: Vec<(PathBuf, String)> = edits @@ -150,9 +202,19 @@ pub(crate) fn verify_splice( return Err(abandoned); } + let mut transit = Transit::default(); for ((i, edits), (path, text)) in edits.iter().zip(&edited) { let Some(before) = scope.text(*i) else { return Err(abandoned) }; - pieces_match(before, text, edits, path, what)?; + let split = Split::read(before, text, edits, path, what)?; + match region_of(moving, *i) { + // A file the move names balances against the pieces in transit + // rather than on its own; its positional comparison is unchanged. + Some(region) => { + transit.add(&display(path), region, &split, edits); + split.positions_match(edits, path, what)?; + } + None => pieces_match(&split, edits, path, what)?, + } // A tolerant parse of a file that was already broken still reports its // old diagnostics, so the bar is "no *new* one", not "none". let (before_count, after_count) = @@ -164,10 +226,11 @@ pub(crate) fn verify_splice( )); } } + transit.check(what)?; let shifts = Shifts::new(scope, edits, ""); let excluded = Excluded::new(scope, edits); - let watched = watched_files(scope, edits, watch_name, watch_name); + let watched = watched_files(scope, edits, watched_names); for &i in &watched { if scope.analysis(i).is_none() { return Err(abandoned); @@ -261,19 +324,14 @@ impl Excluded { /// is a sound *superset* of "has a token spelling the name" — a token spells /// its name literally, so it is always found — and it errs by watching a few /// files whose only mention is in a comment. -fn watched_files( - scope: &Scope, - edits: &[(usize, Vec)], - old_name: &str, - new_name: &str, -) -> Vec { +fn watched_files(scope: &Scope, edits: &[(usize, Vec)], names: &[&str]) -> Vec { let mut watched: Vec = edits.iter().map(|(i, _)| *i).collect(); for i in 0..scope.len() { let Some(text) = scope.text(i) else { continue }; if watched.contains(&i) { continue; } - if contains_word(text, old_name) || contains_word(text, new_name) { + if names.iter().any(|name| contains_word(text, name)) { watched.push(i); } } @@ -344,275 +402,6 @@ fn tokens_match( Ok(()) } -// ---------------------------------------------------------------------- -// lexical splice -// ---------------------------------------------------------------------- - -/// One lexical piece of a file, in source order: a code token, or a comment. -/// Comments are pieces of their own rather than trivia hanging off a token, -/// because an insertion can legitimately move which token a comment attaches -/// to without moving the comment itself. -#[derive(Debug, PartialEq, Eq)] -enum Piece { - Code(TokenKind, String), - Comment(String), -} - -impl Piece { - /// How the piece is named in a refusal. - fn describe(&self) -> String { - match self { - Piece::Code(_, text) => format!("the token `{text}`"), - Piece::Comment(text) => format!("the comment `{text}`"), - } - } -} - -/// Every piece of a file with the bytes it occupies, in source order. -fn pieces(text: &str) -> Option> { - let tokens = tokenize(text).ok()?; - let mut out: Vec<(TextRange, Piece)> = Vec::new(); - for token in &tokens { - for comment in &token.leading { - out.push((comment.span, Piece::Comment(comment.text.clone()))); - } - if token.kind != TokenKind::Eof { - out.push((token.span, Piece::Code(token.kind, token.text.clone()))); - } - if let Some(comment) = &token.trailing { - out.push((comment.span, Piece::Comment(comment.text.clone()))); - } - } - out.sort_by_key(|(span, _)| (span.start, span.end)); - Some(out) -} - -/// The edited file must lex to the original's pieces with the edits' own -/// pieces written in where the edits are — and to nothing else. -fn pieces_match( - before: &str, - after: &str, - edits: &[TextEdit], - path: &Path, - what: &str, -) -> Result<(), String> { - let (Some(old), Some(new)) = (pieces(before), pieces(after)) else { - return Err(format!( - "{} would no longer lex after {what}; no edits were made.", - display(path) - )); - }; - let mut written: Vec> = Vec::new(); - for edit in edits { - let Some(pieces) = pieces(&edit.new_text) else { - return Err(format!("{what} would write text that does not lex; no edits were made.")); - }; - written.push(pieces); - } - never_dropped(&old, &new, edits, &written, path, what)?; - - let mut expected: Vec = Vec::new(); - let mut next = 0usize; - for (span, piece) in old { - while let (Some(edit), Some(pieces)) = (edits.get(next), written.get(next)) { - if edit.range.start > span.start { - break; - } - expected.extend(pieces.iter().map(|(_, piece)| match piece { - Piece::Code(kind, text) => Piece::Code(*kind, text.clone()), - Piece::Comment(text) => Piece::Comment(text.clone()), - })); - next += 1; - } - if edits.iter().any(|e| !e.range.is_empty() && overlaps(e.range, span)) { - continue; - } - expected.push(piece); - } - while let Some(pieces) = written.get(next) { - expected.extend(pieces.iter().map(|(_, piece)| match piece { - Piece::Code(kind, text) => Piece::Code(*kind, text.clone()), - Piece::Comment(text) => Piece::Comment(text.clone()), - })); - next += 1; - } - - let actual: Vec = new.into_iter().map(|(_, piece)| piece).collect(); - for (n, expected) in expected.iter().enumerate() { - match actual.get(n) { - Some(actual) if actual == expected => {} - Some(actual) => { - return Err(format!( - "{what} would write {} where {} belongs in {}; no edits were made.", - actual.describe(), - expected.describe(), - display(path) - )) - } - None => { - return Err(format!( - "{what} would lose {} in {}; no edits were made.", - expected.describe(), - display(path) - )) - } - } - } - if actual.len() > expected.len() { - let extra = actual.get(expected.len()).map_or_else(String::new, Piece::describe); - return Err(format!( - "{what} would add {extra} to {}, which is not part of the edit; no edits were made.", - display(path) - )); - } - Ok(()) -} - -/// The pieces an edit may never lose, gain or duplicate: a **comment** -/// (CLAUDE.md invariant 3) and an **attribute instance** `(* ... *)`. -/// -/// The piece comparison above cannot see either on its own. A piece inside a -/// deleted range disappears from *both* sides of it — from `expected`, because -/// pieces inside an edit are skipped, and from `actual`, because it is really -/// gone — so a dropped comment, or a dropped `(* keep *)`, would pass -/// unnoticed. An attribute is a code token rather than trivia, but a deletion -/// hides it exactly the way it hides a comment, and losing one changes what a -/// synthesizer does; so both are counted here, by exact text. -/// -/// Three equations, over every text that appears on any side. `had` and `has` -/// are the file's counts before and after, `gone` counts the old pieces a -/// non-empty edit range covers, and `wrote` counts the pieces lexed out of the -/// edits' own inserted text. -/// -/// 1. **`has >= had`** — nothing is ever lost. This is the whole of invariant -/// 3 and the only half the rule this replaced had. -/// 2. **`wrote <= gone`**, unless the text is one a refactoring -/// [`generated`] itself — a piece is written back *where it was deleted*, -/// and nowhere else. This refuses a planner that takes the comment on -/// `input a, b;` and writes it onto *both* ports (one really did, on the -/// way — see the work log), and equally one that duplicates the text of a -/// comment it never touched. -/// 3. **`has == had - gone + wrote`** — the applied text says exactly what the -/// edits say. An application that grew a second copy of a comment the edits -/// write once is masked corruption the first two equations would forgive. -/// -/// Where each piece now *sits* is the piece comparison's business, not this -/// one's; between them a moved comment is verified as exactly as a stationary -/// one. -fn never_dropped( - old: &[(TextRange, Piece)], - new: &[(TextRange, Piece)], - edits: &[TextEdit], - written: &[Vec<(TextRange, Piece)>], - path: &Path, - what: &str, -) -> Result<(), String> { - let covered = |span: TextRange| { - edits.iter().any(|edit| !edit.range.is_empty() && overlaps(edit.range, span)) - }; - let before = tally(old.iter().map(|(_, piece)| piece)); - let after = tally(new.iter().map(|(_, piece)| piece)); - let deleted = tally(old.iter().filter(|(span, _)| covered(*span)).map(|(_, piece)| piece)); - let writes = tally(written.iter().flatten().map(|(_, piece)| piece)); - - let mut texts: Vec<&Kept> = before.keys().chain(after.keys()).chain(writes.keys()).collect(); - texts.sort_unstable(); - texts.dedup(); - let count = |tally: &Tally, key: &Kept| tally.get(key).copied().unwrap_or(0); - - // Three passes rather than three tests in one pass, so that the sentence - // the user reads is the worst thing wrong with the edit rather than - // whichever text sorted first. - if let Some(Kept(noun, text)) = - texts.iter().find(|key| count(&after, key) < count(&before, key)) - { - return Err(format!( - "{what} would delete the {noun} `{text}` in {}; {noun}s are never dropped, so nothing was edited.", - display(path) - )); - } - if let Some(key) = - texts.iter().find(|key| count(&writes, key) > count(&deleted, key) && !generated(&key.1)) - { - let Kept(noun, text) = key; - let (gone, wrote) = (count(&deleted, key), count(&writes, key)); - let deletes = match gone { - 0 => "without deleting it".to_string(), - gone => format!("where it deletes it {}", times(gone)), - }; - return Err(format!( - "{what} would write the {noun} `{text}` {} in {} {deletes}; {noun}s are never duplicated, so nothing was edited.", - times(wrote), - display(path) - )); - } - // `deleted` is a subset of `before`, so the subtraction cannot go under — - // saturating rather than plain because an arithmetic panic is not a - // refusal, and this is a safety net. - let accounted = - |key: &Kept| count(&before, key).saturating_sub(count(&deleted, key)) + count(&writes, key); - if let Some(key) = texts.iter().find(|key| count(&after, key) != accounted(key)) { - let Kept(noun, text) = key; - return Err(format!( - "{what} would leave the {noun} `{text}` in {} {}, where its edits account for it {}; nothing was edited.", - display(path), - times(count(&after, key)), - times(accounted(key)) - )); - } - Ok(()) -} - -/// One never-dropped piece, keyed for counting: the noun a refusal calls it by -/// (`comment` or `attribute`) and its exact text. -#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)] -struct Kept(&'static str, String); - -type Tally = HashMap; - -/// How many of each never-dropped piece a stream of pieces holds. Every other -/// piece is a code token the comparison above already pins position by -/// position, so it is not counted here. -fn tally<'p>(pieces: impl Iterator) -> Tally { - let mut out = Tally::new(); - for piece in pieces { - let key = match piece { - Piece::Comment(text) => Kept("comment", text.clone()), - Piece::Code(TokenKind::Attribute, text) => Kept("attribute", text.clone()), - Piece::Code(..) => continue, - }; - *out.entry(key).or_insert(0) += 1; - } - out -} - -/// The comments a refactoring writes itself rather than moves, which it may -/// therefore write however many times it needs and even where the file already -/// has one. `add_port` and `propagate_ports` both leave -/// `/* TODO: connect */` at a connection they cannot name a signal for, and a -/// module gains its ports one at a time — so the second addition to a file -/// finds the first one's placeholder already sitting there. Everything else a -/// refactoring writes has to be a piece it is deleting somewhere else. -fn generated(text: &str) -> bool { - text == "/* TODO: connect */" -} - -/// A count, in prose, so a refusal reads like a sentence. -fn times(n: usize) -> String { - match n { - 0 => "never".to_string(), - 1 => "once".to_string(), - 2 => "twice".to_string(), - n => format!("{n} times"), - } -} - -/// Whether two byte ranges share a byte. Empty ranges — the insertions — -/// overlap nothing: they replace no text, so they delete nothing. -fn overlaps(a: TextRange, b: TextRange) -> bool { - a.start < b.end && b.start < a.end -} - // ---------------------------------------------------------------------- // resolution identity // ---------------------------------------------------------------------- @@ -849,370 +638,6 @@ mod tests { assert!(attack(&corrupted).is_err(), "an unlexable result is a failure, not output"); } - // ------------------------------------------------------------------ - // the splice verifier, and the attacks on it - // ------------------------------------------------------------------ - - /// A module whose port list is one per line, with a comment on each port — - /// the shape every one of the attacks below tries to damage. - const PORTS: &str = - "module m (\n input clk, // the clock\n input rst /* sync */\n);\n wire a; // a\nendmodule\n"; - - /// The edit `add_port` produces for `PORTS`: a `,` before the last port's - /// comment and the new port after it. - fn add_edits() -> Vec { - let end = PORTS.find("input rst").expect("rst") as u32 + "input rst".len() as u32; - let after_comment = PORTS.find("*/").expect("comment") as u32 + 2; - vec![ - TextEdit { range: TextRange::empty(end), new_text: ",".into() }, - TextEdit { - range: TextRange::empty(after_comment), - new_text: "\n input logic [7:0] cfg".into(), - }, - ] - } - - fn splice_attack(corrupted: &str) -> Result<(), String> { - pieces_match(PORTS, corrupted, &add_edits(), Path::new("/rtl/m.sv"), "adding port `cfg`") - } - - #[test] - fn the_splice_the_engine_actually_produces_verifies() { - let honest = apply(PORTS, &add_edits()); - assert_eq!(splice_attack(&honest), Ok(()), "the real output must pass"); - assert!(honest.contains("input rst, /* sync */\n input logic [7:0] cfg"), "{honest}"); - } - - #[test] - fn a_splice_that_wrote_the_comma_into_a_line_comment_is_rejected() { - // The hazard the two-edit shape exists to avoid: a `,` after `//` is a - // `,` nobody will ever see. - let corrupted = PORTS - .replace("// the clock", "// the clock,") - .replace("input rst /* sync */", "input rst /* sync */\n input logic [7:0] cfg"); - assert!(splice_attack(&corrupted).is_err(), "a comma inside a comment is not an edit"); - } - - #[test] - fn a_splice_that_landed_at_the_wrong_place_is_rejected() { - // The same tokens, spliced one port earlier: every piece is accounted - // for, but not in the order the edits promised. - let corrupted = apply(PORTS, &add_edits()) - .replace("input clk,", "input clk, input logic [7:0] cfg,") - .replace(",\n input logic [7:0] cfg\n)", "\n)"); - assert!(splice_attack(&corrupted).is_err(), "position is part of the promise"); - } - - #[test] - fn a_splice_that_also_dropped_a_comment_is_rejected() { - let corrupted = apply(PORTS, &add_edits()).replace(" // a", ""); - let message = splice_attack(&corrupted).expect_err("a dropped comment is a refusal"); - assert!(message.contains("comments are never dropped"), "{message}"); - } - - #[test] - fn a_splice_that_also_rewrote_an_untouched_token_is_rejected() { - let corrupted = apply(PORTS, &add_edits()).replace("wire a;", "wire b;"); - assert!(splice_attack(&corrupted).is_err(), "nothing outside the edit may move"); - } - - #[test] - fn a_splice_that_wrote_more_than_it_promised_is_rejected() { - let corrupted = apply(PORTS, &add_edits()).replace("wire a;", "wire a; wire extra;"); - assert!(splice_attack(&corrupted).is_err(), "an invented declaration"); - } - - #[test] - fn a_splice_that_landed_inside_a_string_is_rejected() { - let text = "module m;\n initial $display(\"hello\");\nendmodule\n"; - let at = text.find("hello").expect("string") as u32; - let edits = vec![TextEdit { range: TextRange::empty(at), new_text: "x".into() }]; - let corrupted = apply(text, &edits); - let outcome = pieces_match(text, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit"); - assert!(outcome.is_err(), "the string's own text is not a token lucisv may write"); - } - - #[test] - fn a_deletion_that_would_swallow_a_comment_is_refused() { - // The one rule the piece comparison cannot see on its own: a comment - // inside a deleted range disappears from *both* sides. - let start = PORTS.find("input rst").expect("rst") as u32; - let end = PORTS.find("*/").expect("comment") as u32 + 2; - let edits = vec![TextEdit { range: TextRange::new(start, end), new_text: String::new() }]; - let corrupted = apply(PORTS, &edits); - let outcome = - pieces_match(PORTS, &corrupted, &edits, Path::new("/rtl/m.sv"), "removing port `rst`"); - let message = outcome.expect_err("a deleted comment is a refusal"); - assert!(message.contains("comments are never dropped"), "{message}"); - } - - #[test] - fn a_splice_whose_result_does_not_lex_is_rejected() { - let corrupted = apply(PORTS, &add_edits()).replace("endmodule", "/* oops"); - assert!(splice_attack(&corrupted).is_err(), "an unlexable result is a failure, not output"); - } - - // ------------------------------------------------------------------ - // the moved-comment rule, and the attacks on it (CLAUDE.md invariant 4) - // ------------------------------------------------------------------ - // - // 2026-09-05: `comments_kept` replaced "no deletion may cover a comment", - // so that `ports::ansi` can move a body declaration's comment onto the - // ANSI port that declaration becomes. Every attack below is a crafted - // (input, corrupted output) pair the relaxation could plausibly forgive. - - /// A Verilog-2001 header whose two declarations each carry a comment — - /// the shape the ANSI conversion has to move a comment out of. - const MOVED: &str = - "module m (\n a,\n b\n);\n input a; // the note\n output b; // the note\nendmodule\n"; - - /// The edits `convert_to_ansi` really produces for `MOVED`. - fn move_edits() -> Vec { - let files = vec![(PathBuf::from("/rtl/m.sv"), MOVED.to_string())]; - let at = MOVED.find("module m").expect("header") as u32; - let edit = crate::convert_to_ansi(&files, Path::new("/rtl/m.sv"), at) - .expect("the conversion the attacks corrupt"); - edit.edits.into_iter().next().expect("one file").1 - } - - fn move_attack(corrupted: &str) -> Result<(), String> { - pieces_match( - MOVED, - corrupted, - &move_edits(), - Path::new("/rtl/m.sv"), - "converting `m`'s ports to ANSI", - ) - } - - #[test] - fn the_moved_comments_the_engine_actually_writes_verify() { - let honest = apply(MOVED, &move_edits()); - assert_eq!(move_attack(&honest), Ok(()), "the real output must pass"); - assert_eq!(honest.matches("// the note").count(), 2, "both comments survive: {honest}"); - assert!(honest.contains("input a, // the note"), "{honest}"); - } - - #[test] - fn a_move_that_kept_only_one_of_two_identical_comments_is_rejected() { - // The exact hole the character budget exists for: one of the two - // `// the note`s is dropped, and a search for its text still finds - // the other one. - let corrupted = apply(MOVED, &move_edits()).replacen(" // the note", "", 1); - let message = move_attack(&corrupted).expect_err("one comment short is a refusal"); - assert!(message.contains("comments are never dropped"), "{message}"); - } - - #[test] - fn a_move_that_dropped_a_comment_and_invented_another_is_rejected() { - // Same character count, different text: the budget alone would - // forgive this one, and the per-comment search does not. - let corrupted = apply(MOVED, &move_edits()).replacen("// the note", "// the NOTE", 1); - let message = move_attack(&corrupted).expect_err("a rewritten comment is a refusal"); - assert!(message.contains("comments are never dropped"), "{message}"); - } - - #[test] - fn a_move_that_shortened_a_comment_is_rejected() { - let corrupted = apply(MOVED, &move_edits()).replacen("// the note", "// the", 1); - let message = move_attack(&corrupted).expect_err("a truncated comment is a refusal"); - assert!(message.contains("comments are never dropped"), "{message}"); - } - - #[test] - fn a_move_that_left_the_comment_where_it_was_is_rejected() { - // The deletion really deleted, but the comment was written back into - // the *body* rather than into the header: every comment is still - // there, and the piece order is not what the edits promised. - let honest = apply(MOVED, &move_edits()); - let corrupted = honest - .replace("input a, // the note", "input a,") - .replace("endmodule", "// the note\nendmodule"); - // `never_dropped` passes this one: every count is equal on both sides - // (the comment really was deleted and really was written back once). - // The *piece comparison* is the guard, because where a comment lands - // is bound to where the edits put it — which is also the answer to - // "a comment deleted here and written back somewhere unrelated". - let message = move_attack(&corrupted).expect_err("a misplaced comment is a refusal"); - assert!(message.contains("where the comment `// the note` belongs"), "{message}"); - } - - #[test] - fn a_move_that_wrote_the_comment_onto_two_ports_is_rejected() { - // The bug this half of the rule was added for, reproduced as the edits - // that caused it: one declaration declares two ports, and its comment - // is written onto *both*. Nothing is dropped, and the piece comparison - // cannot object — it checks the edits against themselves, and the - // duplicate is in the edits. Only counting the file's comments sees it. - const SHARED: &str = "module m (\n a,\n b\n);\n input a, b; // both\nendmodule\n"; - let at = |needle: &str| SHARED.find(needle).expect(needle) as u32; - let (a, b) = (at("\n a,") + 3, at("\n b\n") + 3); - let edits = vec![ - TextEdit { range: TextRange::empty(a), new_text: "input ".into() }, - TextEdit { range: TextRange::empty(a + 2), new_text: " // both".into() }, - TextEdit { range: TextRange::empty(b), new_text: "input ".into() }, - TextEdit { range: TextRange::empty(b + 1), new_text: " // both".into() }, - TextEdit { - range: TextRange::new(at(" input a,"), at("endmodule")), - new_text: String::new(), - }, - ]; - let corrupted = apply(SHARED, &edits); - assert_eq!(corrupted.matches("// both").count(), 2, "the attack really doubles it"); - let message = pieces_match(SHARED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit") - .expect_err("a doubled comment is a refusal"); - assert!(message.contains("would write the comment"), "{message}"); - } - - #[test] - fn a_deletion_that_swallows_a_comment_nothing_writes_back_is_still_refused() { - // The old rule's own case, restated: no edit writes the comment, so - // the relaxation must not reach it. - let start = MOVED.find("input a;").expect("a") as u32; - let end = MOVED.find("\n output").expect("output") as u32; - let edits = vec![TextEdit { range: TextRange::new(start, end), new_text: String::new() }]; - let corrupted = apply(MOVED, &edits); - let message = pieces_match(MOVED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit") - .expect_err("a deleted comment nothing writes back is a refusal"); - assert!(message.contains("comments are never dropped"), "{message}"); - } - - // ------------------------------------------------------------------ - // 2026-09-05 rework: the duplication half, the equation, and attributes - // ------------------------------------------------------------------ - - #[test] - fn an_insertion_that_duplicates_an_untouched_comment_is_rejected() { - // QA's V-1 pair. Nothing deletes — or even overlaps — the body's own - // `// shared`, and two pure insertions each write it again. Every - // count only grows, so "before is a subset of after" forgives it, and - // the piece comparison cannot object because the duplicates are in the - // edits. Only `wrote <= gone` sees it. - const SHARED: &str = - "module m (\n a,\n b\n);\n input a; // shared\n output b;\nendmodule\n"; - let at = |needle: &str| SHARED.find(needle).expect(needle) as u32; - let (a, b) = (at("\n a,") + 4, at("\n b\n") + 4); - let edits = vec![ - TextEdit { range: TextRange::empty(a), new_text: " // shared".into() }, - TextEdit { range: TextRange::empty(b), new_text: " // shared".into() }, - ]; - let corrupted = apply(SHARED, &edits); - assert_eq!(corrupted.matches("// shared").count(), 3, "the attack really triples it"); - let message = pieces_match(SHARED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit") - .expect_err("a duplicated comment is a refusal"); - assert!(message.contains("comments are never duplicated"), "{message}"); - } - - #[test] - fn a_generated_placeholder_may_be_written_where_the_file_already_has_one() { - // The whitelist, and the whole of it. `add_port` and - // `propagate_ports` write `/* TODO: connect */` themselves, and a - // module gains its ports one at a time — so the second addition to a - // file finds the first one's placeholder already sitting there and - // writes another. `wrote > gone` with nothing deleted, and legitimate. - let source = "module top;\n sub u1 (.a(/* TODO: connect */));\nendmodule\n"; - let at = source.find("))").expect("list") as u32 + 1; - let edits = vec![TextEdit { - range: TextRange::empty(at), - new_text: ", .b(/* TODO: connect */)".into(), - }]; - let spliced = apply(source, &edits); - assert_eq!(spliced.matches("TODO").count(), 2, "{spliced}"); - let outcome = - pieces_match(source, &spliced, &edits, Path::new("/rtl/top.sv"), "adding port `b`"); - assert_eq!(outcome, Ok(()), "a generated placeholder is the engine's own text"); - } - - #[test] - fn an_application_that_grew_a_copy_the_edits_do_not_write_is_rejected() { - // Masked corruption of the third kind: the edits are honest — they - // delete both `// the note`s and write both back — and the *applied* - // text carries a third. Neither "nothing is lost" nor "written back - // where it was deleted" can see that; only the equation can. - let corrupted = apply(MOVED, &move_edits()).replace("endmodule", "// the note\nendmodule"); - let message = move_attack(&corrupted).expect_err("an invented copy is a refusal"); - assert!(message.contains("where its edits account for it"), "{message}"); - } - - #[test] - fn a_comment_written_back_inside_a_string_or_another_comment_is_rejected() { - // A `//` is only a comment where the lexer says it is. Written back - // inside a string literal, or swallowed into the comment next to it, - // the text is present in the file and absent from its pieces — which - // is exactly the substring search this rule refuses to be. - let honest = apply(MOVED, &move_edits()); - let in_string = honest - .replacen(" // the note", "", 1) - .replace("endmodule", " initial $display(\"// the note\");\nendmodule"); - let message = move_attack(&in_string).expect_err("a string is not a comment"); - assert!(message.contains("comments are never dropped"), "{message}"); - - let nested = honest - .replacen(" // the note", "", 1) - .replace("// the note", "// the note // the note"); - let message = move_attack(&nested).expect_err("one comment is not two"); - assert!(message.contains("comments are never dropped"), "{message}"); - } - - /// A body declaration carrying an attribute instance. `Item.span` covers - /// the `(* keep *)`, so a deletion hides it from *both* sides of the piece - /// comparison exactly the way it hides a comment — QA's finding V-2. - const ATTRIBUTED: &str = "module m (\n a\n);\n (* keep *) input a;\nendmodule\n"; - - /// The edits an absorbing conversion of `ATTRIBUTED` makes: `input ` (plus - /// whatever `written` says) before the header name, and the whole body - /// declaration gone. - fn attribute_edits(written: &str) -> Vec { - let at = |needle: &str| ATTRIBUTED.find(needle).expect(needle) as u32; - vec![ - TextEdit { range: TextRange::empty(at("\n a\n") + 3), new_text: written.into() }, - TextEdit { - range: TextRange::new(at(" (* keep *)"), at("endmodule")), - new_text: String::new(), - }, - ] - } - - fn attribute_attack(edits: &[TextEdit]) -> Result<(), String> { - let corrupted = apply(ATTRIBUTED, edits); - pieces_match( - ATTRIBUTED, - &corrupted, - edits, - Path::new("/rtl/m.sv"), - "converting `m`'s ports to ANSI", - ) - } - - #[test] - fn a_deletion_that_swallows_an_attribute_is_rejected() { - // The planner refuses this one first (`ports::ansi::attributes_clear`, - // pinned in `tests/ansi.rs`); this is the verifier saying so a second - // time, from the edits alone, for whatever writes them next. - let message = attribute_attack(&attribute_edits("input ")) - .expect_err("a dropped attribute is a refusal"); - assert!(message.contains("attributes are never dropped"), "{message}"); - assert!(message.contains("`(* keep *)`"), "{message}"); - } - - #[test] - fn an_edit_that_moves_an_attribute_verifies() { - // What the refusal above is protecting: an edit that really does carry - // the attribute over is not what this rule is for. - let edits = attribute_edits("(* keep *) input "); - assert_eq!(attribute_attack(&edits), Ok(()), "a moved attribute is a kept attribute"); - assert!(apply(ATTRIBUTED, &edits).contains("(* keep *) input a")); - } - - #[test] - fn an_edit_that_rewrote_an_attribute_is_rejected() { - // `(* keep *)` and `(* keep=1 *)` are not the same instruction to a - // synthesizer, and an attribute is matched by exact text. - let message = attribute_attack(&attribute_edits("(* keep=1 *) input ")) - .expect_err("a rewritten attribute is a refusal"); - assert!(message.contains("attributes are never dropped"), "{message}"); - } - #[test] fn a_splice_that_captures_a_name_outside_the_edit_is_rejected() { // The resolution half: the module already has a net called `cfg`, and @@ -1329,6 +754,257 @@ mod tests { (PathBuf::from(path), text.to_string()) } + // ------------------------------------------------------------------ + // the moved-piece rule, and the attacks on it (CLAUDE.md invariant 4) + // ------------------------------------------------------------------ + // + // 2026-09-05: `verify_move` lets a piece that is never dropped travel out + // of the region an extraction moves and into the file that receives it — a + // comment deleted in `m.sv` and written in `sum.sv` balances across the + // move and in neither file alone. + // + // 2026-09-06 rework (QA's finding V1): the allowance is bound to the + // **region**, not to the files, and every attack below goes through the + // production entry point — a real `Scope`, the raw `TextEdit`s and + // `verify_move` itself, positional comparison and all. The pair in + // `a_copy_deleted_outside_the_region_is_not_one_the_move_may_balance` is + // the one the file-scoped pool forgave, and no ledger-only helper could + // have seen it. + + /// A module with a comment and an attribute inside the region an + /// extraction moves — the two pieces the ledger is the only guard for. + const EXTRACT: &str = "module m (\n input logic a,\n input logic b,\n output logic q\n);\n logic s;\n (* keep *) assign s = a & b; // the and\n assign q = s | 1'b0;\nendmodule\n"; + + const MOVED_WHAT: &str = "extracting `sum` out of `m`"; + + /// One extraction, as the verifier is told about it: the edits per file, + /// and the bytes the move carries out of `m.sv`. + struct Plan { + m: Vec, + n: Vec, + region: TextRange, + } + + /// The edits the extraction really makes for `source`: one replacement in + /// `m.sv`, one insertion into an empty `sum.sv`. + fn extraction(source: &str) -> Plan { + let files = vec![(PathBuf::from("/rtl/m.sv"), source.to_string())]; + let start = source.find("(* keep *)").expect("attribute") as u32; + let end = source.find("// the and").expect("comment") as u32 + 10; + let edit = crate::extract_module( + &files, + Path::new("/rtl/m.sv"), + start, + end, + "sum", + crate::Home::NewFile, + ) + .expect("the extraction the attacks corrupt"); + let m = edit.edits_for(&PathBuf::from("/rtl/m.sv")).to_vec(); + let n = edit.edits_for(&PathBuf::from("/rtl/sum.sv")).to_vec(); + let region = m.first().expect("the replacement").range; + Plan { m, n, region } + } + + /// Verify a plan the way the engine does: a real `Scope` over the two + /// files, the raw edits, and the production `verify_move`. `moves` is what + /// the engine passes — `m.sv` as the source of the region and `sum.sv` as + /// the file that receives — or nothing at all, for the opt-in test. + fn verified(source: &str, plan: &Plan, moves: bool) -> Result<(), String> { + let files = vec![ + (PathBuf::from("/rtl/m.sv"), source.to_string()), + (PathBuf::from("/rtl/sum.sv"), String::new()), + ]; + let mut scope = Scope::build(&files); + let at = |name: &str| scope.index_of(Path::new(name)).expect(name); + let (m, n) = (at("/rtl/m.sv"), at("/rtl/sum.sv")); + let edits = vec![(m, plan.m.clone()), (n, plan.n.clone())]; + let moving = match moves { + true => vec![(m, plan.region), (n, TextRange::empty(0))], + false => Vec::new(), + }; + verify_move(&mut scope, &edits, &["m", "sum"], MOVED_WHAT, &moving) + } + + #[test] + fn the_move_the_engine_actually_produces_verifies() { + let plan = extraction(EXTRACT); + assert_eq!(verified(EXTRACT, &plan, true), Ok(()), "the real output must pass"); + let (m, n) = (apply(EXTRACT, &plan.m), apply("", &plan.n)); + // The comment *and* the attribute travel, which is the whole of what + // the allowance is for. + assert!(n.contains("// the and") && n.contains("(* keep *)"), "{n}"); + assert!(!m.contains("// the and") && !m.contains("(* keep *)"), "{m}"); + } + + #[test] + fn a_copy_deleted_outside_the_region_is_not_one_the_move_may_balance() { + // QA's V1 pair, and the reason the allowance is bound to the region + // rather than to the files. `m.sv` holds the same comment twice: one + // inside the region, one on a line the extraction never touches. The + // corrupted plan deletes *both* and writes the comment into `sum.sv` + // twice — so a pool kept over the two files balanced two in against + // two out and forgave it, while `m.sv` alone lost a comment nothing + // ever moved. + let source = EXTRACT.replace("assign q = s | 1'b0;", "assign q = s | 1'b0; // the and"); + let mut plan = extraction(&source); + let stray = source.rfind("// the and").expect("the untouched copy") as u32; + plan.m.push(TextEdit { + range: TextRange::new(stray - 1, stray + 10), + new_text: String::new(), + }); + for edit in &mut plan.n { + edit.new_text = edit.new_text.replace("// the and", "// the and\n // the and"); + } + // Each file is honest about its own edits — this is not a positional + // failure — and the counts over the pair really do balance: two copies + // before, two after. Only the region says which of them moved. + let (m, n) = (apply(&source, &plan.m), apply("", &plan.n)); + assert_eq!(source.matches("// the and").count(), 2, "two copies to begin with"); + assert_eq!( + m.matches("// the and").count() + n.matches("// the and").count(), + 2, + "and two after, which is what a pool kept over the files forgave" + ); + let message = verified(&source, &plan, true).expect_err("a lost copy is a refusal"); + assert!(message.contains("comments are never dropped"), "{message}"); + assert!(message.contains("m.sv"), "{message}"); + } + + #[test] + fn a_comment_that_lands_twice_in_the_new_file_is_rejected() { + // The corruption in the *edits* rather than in the application: the + // new file's text carries the comment twice where the region held it + // once. The transit is an allowance for one. + let mut plan = extraction(EXTRACT); + for edit in &mut plan.n { + edit.new_text = edit.new_text.replace("// the and", "// the and\n // the and"); + } + let message = verified(EXTRACT, &plan, true).expect_err("a duplicate is a refusal"); + assert!(message.contains("never duplicated"), "{message}"); + } + + #[test] + fn a_comment_left_behind_as_well_as_moved_is_rejected() { + // Deleted once, written twice — once where it belongs and once back + // into the file it came from, above the instantiation. + let mut plan = extraction(EXTRACT); + for edit in &mut plan.m { + edit.new_text = format!("// the and\n {}", edit.new_text); + } + let message = verified(EXTRACT, &plan, true).expect_err("a duplicate is a refusal"); + assert!(message.contains("never duplicated"), "{message}"); + } + + #[test] + fn a_comment_the_move_carries_that_lands_nowhere_is_rejected() { + // The whole hazard of the allowance: the comment leaves `m.sv` + // legitimately, and the corrupted `sum.sv` simply never writes it. + // Per file, both halves look innocent. + let mut plan = extraction(EXTRACT); + for edit in &mut plan.n { + edit.new_text = edit.new_text.replace(" // the and", ""); + } + let message = verified(EXTRACT, &plan, true).expect_err("a lost comment is a refusal"); + assert!(message.contains("comments are never dropped"), "{message}"); + assert!(message.contains("write it back nowhere"), "{message}"); + } + + #[test] + fn an_attribute_the_move_carries_that_lands_nowhere_is_rejected() { + let mut plan = extraction(EXTRACT); + for edit in &mut plan.n { + edit.new_text = edit.new_text.replace("(* keep *) ", ""); + } + let message = verified(EXTRACT, &plan, true).expect_err("a lost attribute is a refusal"); + assert!(message.contains("attributes are never dropped"), "{message}"); + } + + #[test] + fn a_comment_the_new_file_invents_with_nothing_in_transit_is_rejected() { + // Nothing deleted it anywhere, and the transit is the only allowance a + // destination has. + let mut plan = extraction(EXTRACT); + for edit in &mut plan.n { + edit.new_text = edit.new_text.replace("endmodule", " // invented\nendmodule"); + } + let message = verified(EXTRACT, &plan, true).expect_err("an invented comment is a refusal"); + assert!(message.contains("never duplicated"), "{message}"); + assert!(message.contains("// invented"), "{message}"); + } + + #[test] + fn a_generated_placeholder_the_new_file_writes_is_not_a_duplicate() { + // The whitelist is untouched by the rework: `/* TODO: connect */` is + // text a refactoring writes itself, not a piece it moves. + let mut plan = extraction(EXTRACT); + for edit in &mut plan.n { + edit.new_text = edit.new_text.replace("endmodule", " /* TODO: connect */\nendmodule"); + } + assert_eq!(verified(EXTRACT, &plan, true), Ok(()), "the whitelist still whitelists"); + } + + #[test] + fn a_piece_in_transit_to_a_file_the_move_did_not_name_is_rejected() { + // The move names `m.sv` and `sum.sv`; the plan writes the new module + // into a third file instead. That file never asked for an allowance, + // so it keeps the per-file contract and the comment it writes is one + // it never deleted. + let plan = extraction(EXTRACT); + let files = vec![ + (PathBuf::from("/rtl/m.sv"), EXTRACT.to_string()), + (PathBuf::from("/rtl/other.sv"), String::new()), + (PathBuf::from("/rtl/sum.sv"), String::new()), + ]; + let mut scope = Scope::build(&files); + let at = |name: &str| scope.index_of(Path::new(name)).expect(name); + let (m, other, sum) = (at("/rtl/m.sv"), at("/rtl/other.sv"), at("/rtl/sum.sv")); + let edits = vec![(m, plan.m.clone()), (other, plan.n.clone())]; + let moving = vec![(m, plan.region), (sum, TextRange::empty(0))]; + let message = verify_move(&mut scope, &edits, &["m", "sum"], MOVED_WHAT, &moving) + .expect_err("a file the move did not name is not a destination"); + assert!(message.contains("never duplicated"), "{message}"); + } + + #[test] + fn a_deletion_wider_than_the_region_is_an_ordinary_deletion() { + // The old fifth attack, through the production entry: a deletion + // widened past the selection swallows `// the rest`, which was never + // the extraction's to move and which nothing writes back. Only the + // pieces *inside* the region are in transit. + let source = EXTRACT.replace("assign q = s | 1'b0;", "assign q = s | 1'b0; // the rest"); + let mut plan = extraction(&source); + let end = source.find("// the rest").expect("comment") as u32 + 11; + plan.m[0].range = TextRange::new(plan.m[0].range.start, end); + let message = verified(&source, &plan, true).expect_err("a swallowed comment is a refusal"); + assert!(message.contains("comments are never dropped"), "{message}"); + assert!(message.contains("// the rest"), "{message}"); + } + + #[test] + fn a_region_that_does_not_cover_what_the_edits_delete_is_rejected() { + // The planner lying about its own region is the same corruption seen + // from the other side: it says the move takes only the `assign`, and + // its edit deletes the trailing comment too. + let mut plan = extraction(EXTRACT); + let comment = EXTRACT.find("// the and").expect("comment") as u32; + plan.region = TextRange::new(plan.region.start, comment); + let message = verified(EXTRACT, &plan, true).expect_err("a lied-about region is a refusal"); + assert!(message.contains("comments are never dropped"), "{message}"); + } + + #[test] + fn the_widening_is_opt_in_and_a_refactoring_that_asked_for_none_still_gets_none() { + // The same honest extraction, verified with an *empty* `moving` list: + // the per-file contract refuses it, which is what says nothing else in + // this crate lost a guard when `verify_move` gained one. + let plan = extraction(EXTRACT); + let message = verified(EXTRACT, &plan, false) + .expect_err("without `moving`, a cross-file move is a dropped piece"); + assert!(message.contains("are never dropped"), "{message}"); + assert_eq!(verified(EXTRACT, &plan, true), Ok(()), "and with it, the same plan verifies"); + } + #[test] fn a_rename_that_edited_the_declaration_but_not_its_uses_is_rejected() { // The whole point of the resolution check: the tokens are perfect, the diff --git a/crates/vlog_refactor/src/extract/boundary.rs b/crates/vlog_refactor/src/extract/boundary.rs new file mode 100644 index 0000000..8981477 --- /dev/null +++ b/crates/vlog_refactor/src/extract/boundary.rs @@ -0,0 +1,469 @@ +//! Which names cross the selection's boundary, and what the new module's +//! header is therefore made of. +//! +//! `flow` says what is *done* to each name on each side; this says what each +//! crossing name **becomes** — a port, a parameter, a copied `import`, or a +//! refusal. Three closures run here, and they are one closure really: the +//! signals the selection reads and drives, the parameters they and their own +//! types depend on, and the imports the whole of that needs to resolve. +//! +//! The last of the three is the subtle one. What the new module has to be able +//! to resolve is not "the names the selection writes down" but that *plus the +//! type names of its own header* — a port declared `input logic [N-1:0] a` +//! names `N` even though no statement in the selection does, and a port typed +//! `word_t` needs whatever import supplied it. Both were found by the corpus +//! and opentitan trials rather than by reasoning; see the feature README's +//! work log. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use vlog_parser::ast::{ItemKind, SourceFile}; +use vlog_parser::span::TextRange; +use vlog_semantic::{Resolution, Semantics, SymbolId, SymbolKind}; + +use crate::rename::display; + +use super::flow; +use super::region::Region; +use super::render::{self, Param, Port}; +use super::{count, escaped, header_names, inside, inside_module, lost_name}; +use super::{outside_module, outside_module_member}; +use super::{slice, unmovable}; + +// ---------------------------------------------------------------------- +// the boundary +// ---------------------------------------------------------------------- + +/// Everything that crosses the selection's boundary, classified. +pub(super) struct Crossing { + pub(super) ports: Vec, + pub(super) params: Vec, + pub(super) imports: Vec, +} + +impl Crossing { + pub(super) fn read( + text: &str, + semantics: &Semantics, + region: &Region<'_>, + flow: &flow::Flow, + packages: &[(String, TextRange)], + new_file: bool, + ) -> Result { + let mut ports: Vec<(TextRange, Port)> = Vec::new(); + let mut params: Vec<(TextRange, Param)> = Vec::new(); + let module = region.module_name().to_string(); + let mut wanted: Vec = Vec::new(); + // Names a `package` of this file declares. `N` reaches one the way + // `M` does — through a qualified spelling, or through an import of + // that package which the new module is given a copy of. + let mut from_package: Vec<(String, String)> = Vec::new(); + + for (n, symbol) in semantics.symbols().iter().enumerate() { + let sides = flow.sides(SymbolId(n as u32)); + let declared_inside = inside(region, symbol.name_span); + if declared_inside { + if sides.used_outside() { + return Err(escaped(&symbol.name)); + } + continue; + } + if !sides.used_inside() { + continue; + } + // A module, an interface and a package are visible from every + // file of the design, so one declared beside `M` is one `N` can + // reach too — they never become ports and never refuse. + if matches!( + symbol.kind, + SymbolKind::Module | SymbolKind::Interface | SymbolKind::Package + ) { + continue; + } + if !inside_module(region, symbol.name_span) { + // Not a port: a name the module itself does not declare is + // one the new module reaches the way `M` did, or one `visible` + // below refuses because a file of its own would not see it. + if let Some(package) = package_of(packages, symbol.name_span) { + from_package.push((package.to_string(), symbol.name.clone())); + } + continue; + } + match symbol.kind { + SymbolKind::Port | SymbolKind::Net | SymbolKind::Var => { + let dir = direction(&symbol.name, sides)?; + let Some(site) = render::site_of(region.module, &symbol.name) else { + return Err(lost_name(&symbol.name)); + }; + let port = render::port(text, &module, &symbol.name, &site, dir)?; + ports.push((symbol.name_span, port)); + } + SymbolKind::Param | SymbolKind::LocalParam => wanted.push(symbol.name.clone()), + kind => return Err(unmovable(&symbol.name, &module, kind)), + } + } + + // A **port's own type** may name a parameter — `input logic [N-1:0] a` + // — and that parameter crosses the boundary as squarely as one the + // selection reads, or the new module's header names nothing. So does + // a parameter's type, and a parameter's default; the three are one + // closure, run below until nothing new is wanted. + let declared = declarations(semantics, region); + for (_, port) in &ports { + for word in &port.names { + depends(&declared, &module, &port.name, word, &mut wanted)?; + } + } + let mut seen: Vec = Vec::new(); + while let Some(name) = wanted.pop() { + if seen.contains(&name) { + continue; + } + let Some(site) = render::site_of(region.module, &name) else { + return Err(lost_name(&name)); + }; + let param = render::param(text, &module, &name, &site)?; + for word in ¶m.names { + depends(&declared, &module, &name, word, &mut wanted)?; + } + let span = span_of(semantics, region, &name); + params.push((span, param)); + seen.push(name); + } + + ports.sort_by_key(|(span, _)| (span.start, span.end)); + params.sort_by_key(|(span, _)| (span.start, span.end)); + let needed = needed(text, semantics, flow, &ports, ¶ms); + visible(text, semantics, region, packages, &needed, &module, new_file)?; + let imports = imports(semantics, region, packages, &needed); + reachable(text, &needed, &from_package, &imports)?; + Ok(Crossing { + ports: ports.into_iter().map(|(_, port)| port).collect(), + params: params.into_iter().map(|(_, param)| param).collect(), + imports, + }) + } + + pub(super) fn warnings( + &self, + new_name: &str, + created: &Option, + file: &Path, + ) -> Vec { + let mut out = Vec::new(); + out.push(match created { + Some(path) => format!( + "`{new_name}` was written to a new file, `{}`.", + display(path) + ), + None => format!( + "`{new_name}` was written below its neighbour in `{}`: this editor did not say it can create files, so lucisv did not make one.", + display(file) + ), + }); + out.push(format!( + "lucisv gave `{new_name}` {} and {} from the names the selection reads and drives; check the directions before you rely on them.", + count(self.ports.len(), "port"), + count(self.params.len(), "parameter"), + )); + if !self.imports.is_empty() { + out.push(format!( + "`{new_name}` imports {}, which the selection needed.", + self.imports.iter().map(|path| format!("`{path}`")).collect::>().join(", ") + )); + } + out + } +} + +/// The direction one crossing signal's port gets, or the sentence saying why +/// lucisv will not decide. +fn direction(name: &str, sides: flow::Sides) -> Result<&'static str, String> { + if sides.inside_unknown { + return Err(format!( + "the selection passes `{name}` to a task or function, and only that routine's declaration says whether it is an argument in or out; lucisv will not guess a port direction from it." + )); + } + if !sides.inside_write { + return Ok("input"); + } + if sides.outside_write { + return Err(format!("`{name}` is driven on both sides of the selection.")); + } + if sides.outside_unknown { + return Err(format!( + "the selection drives `{name}`, and something outside it passes the same name to a task or function, which may drive it too; lucisv will not make it an output over that." + )); + } + Ok("output") +} + +/// One identifier written in a header lucisv is about to move: a parameter it +/// has to carry across too, a keyword or a package name it can ignore, or a +/// declaration of `M`'s that a header in another module could not name. +fn depends( + declared: &HashMap<&str, SymbolKind>, + module: &str, + owner: &str, + word: &str, + wanted: &mut Vec, +) -> Result<(), String> { + match declared.get(word) { + // A keyword (`logic`, `int`), a system function, or a name that comes + // from somewhere `visible` and `reachable` judge on their own terms. + None => Ok(()), + Some(SymbolKind::Param | SymbolKind::LocalParam) => { + wanted.push(word.to_string()); + Ok(()) + } + Some(_) => Err(header_names(module, owner, word)), + } +} + +/// Every name the module's own scope declares, with its kind — what a +/// parameter default is checked against. +fn declarations<'s>(semantics: &'s Semantics, region: &Region<'_>) -> HashMap<&'s str, SymbolKind> { + semantics + .symbols() + .iter() + .filter(|symbol| inside_module(region, symbol.name_span)) + .map(|symbol| (symbol.name.as_str(), symbol.kind)) + .collect() +} + +/// Where the module declares `name`, for ordering a header the way the source +/// orders its declarations. +fn span_of(semantics: &Semantics, region: &Region<'_>, name: &str) -> TextRange { + semantics + .symbols() + .iter() + .find(|symbol| symbol.name == name && inside_module(region, symbol.name_span)) + .map_or(TextRange::empty(0), |symbol| symbol.name_span) +} + +/// Every name the new module has to be able to resolve for itself: the names +/// the selection writes down, plus the type names its own header will carry. +/// +/// A header type is matched by the *text* the declaration wrote — the port's +/// prefix is that text — so a `word_t` in a port list is the same reference the +/// import judgement asks about, and not a second reading of it. +fn needed<'s>( + text: &str, + semantics: &'s Semantics, + flow: &flow::Flow, + ports: &[(TextRange, Port)], + params: &[(TextRange, Param)], +) -> Vec<&'s vlog_semantic::Reference> { + let mut out: Vec<&vlog_semantic::Reference> = + flow.inside.iter().filter_map(|n| semantics.references().get(*n)).collect(); + let header: Vec<&str> = ports + .iter() + .map(|(_, port)| port.prefix.as_str()) + .chain(params.iter().map(|(_, param)| param.prefix.as_str())) + .collect(); + for reference in semantics.references() { + let written = slice(text, reference.name_span); + if written.is_empty() { + continue; + } + if header.iter().any(|prefix| prefix.split_whitespace().any(|word| word == written)) { + out.push(reference); + } + } + out +} + +/// The `import` paths the new module gets: the ones written in `M` that one of +/// the names it needs could have come through. +fn imports( + semantics: &Semantics, + region: &Region<'_>, + packages: &[(String, TextRange)], + needed: &[&vlog_semantic::Reference], +) -> Vec { + let Some(scope) = semantics + .symbol_at(region.module.name_span.start) + .and_then(|id| semantics.symbol(id)) + .and_then(|symbol| symbol.child_scope) + .and_then(|id| semantics.scope(id)) + else { + return Vec::new(); + }; + let mut out = Vec::new(); + for import in &scope.imports { + let path = import.path(); + if out.contains(&path) { + continue; + } + if needed.iter().any(|r| supplied_by(semantics, packages, import, r)) { + out.push(path); + } + } + out +} + +/// Whether a use of a name could have come through an import of `package`. +/// +/// Two shapes, because the binder answers them differently. A package +/// **another file** declares leaves an [`Resolution::ExternalCandidate`] whose +/// `paths` name it; a package **this file** declares is resolved on the spot, +/// and what says so is that the declaration sits inside that package's own +/// item span. +fn supplied_by( + semantics: &Semantics, + packages: &[(String, TextRange)], + import: &vlog_semantic::Import, + reference: &vlog_semantic::Reference, +) -> bool { + if !import.supplies(&reference.name) { + return false; + } + let package = import.package.as_str(); + match &reference.resolution { + // The binder writes the import paths it walked into `paths`, in the + // spelling the source wrote them (`p::*`, `p::w_t`) — so the question + // is whether this very import is one of them, not whether some path + // happens to end in the name. + Resolution::ExternalCandidate { paths, .. } + | Resolution::InheritedCandidate { paths, .. } => { + paths.iter().any(|path| *path == import.path()) + } + Resolution::Resolved(symbol) => semantics + .symbol(*symbol) + .and_then(|symbol| package_of(packages, symbol.name_span)) + .is_some_and(|declared_in| declared_in == package), + Resolution::NotFound => false, + } +} + +/// Every name the new module needs has to be one a file of its own can see: a +/// declaration of `M`'s own (which becomes a port or a parameter), a unit of +/// the design (a module, an interface, a package), or a member of a package. +/// +/// What this refuses is the rest — a `typedef`, a `localparam` or a class +/// written at the **file scope** of `M`'s file, which is a compilation-unit +/// declaration and reaches exactly the files that were compiled with it. It +/// runs over the names the new module writes down *and* the type names of its +/// own header, so a port typed with a file-scope `typedef` is refused as +/// squarely as a body reference to one. +fn visible( + text: &str, + semantics: &Semantics, + region: &Region<'_>, + packages: &[(String, TextRange)], + needed: &[&vlog_semantic::Reference], + module: &str, + new_file: bool, +) -> Result<(), String> { + if !new_file { + return Ok(()); + } + for reference in needed { + let Resolution::Resolved(id) = reference.resolution else { continue }; + let Some(symbol) = semantics.symbol(id) else { continue }; + if inside_module(region, symbol.name_span) { + continue; + } + if package_of(packages, symbol.name_span).is_some() { + continue; + } + if matches!(symbol.kind, SymbolKind::Module | SymbolKind::Interface | SymbolKind::Package) { + continue; + } + // A field of a struct and a signal of an interface each have a + // declaration of their own, and naming it is not what the user needs + // to read: what crosses the boundary is `s` or `bus`, and `f` is a + // name of *its* type. So the head goes first when there is one. + return Err(match access_head(text, reference.name_span) { + Some(head) => outside_module_member(head, &symbol.name, module), + None => outside_module(&symbol.name, module), + }); + } + Ok(()) +} + +/// The head of a member access, if the reference is one: `s` in `s.f`, `bus` +/// in `bus.data`, and `u` in `u.v.w`. +/// +/// Read from the text rather than from the tree because that is where the +/// question is cheap and exact: a reference's own span is the field, and what +/// precedes it — a `.` and an identifier — is the thing the field belongs to. +fn access_head(text: &str, span: TextRange) -> Option<&str> { + let (mut at, mut head) = dotted_word_before(text, span.start as usize)?; + while let Some((start, word)) = dotted_word_before(text, at) { + at = start; + head = word; + } + Some(head) +} + +/// The identifier written immediately before `at` and a `.`, with where it +/// starts: `("s", …)` for `s.` and nothing at all for anything else. +fn dotted_word_before(text: &str, at: usize) -> Option<(usize, &str)> { + let rest = text.get(..at)?.trim_end().strip_suffix('.')?.trim_end(); + let start = rest + .char_indices() + .rev() + .take_while(|(_, c)| c.is_alphanumeric() || *c == '_' || *c == '$') + .last() + .map(|(i, _)| i)?; + let word = rest.get(start..)?; + match word.starts_with(|c: char| c.is_ascii_digit()) { + true => None, + false => Some((start, word)), + } +} + +/// A name a `package` of this file declares reaches the new module only if the +/// new module can spell it: either every use writes the package out +/// (`w_pkg::word_t`), or `M` imports it and lucisv copied that import across. +fn reachable( + text: &str, + needed: &[&vlog_semantic::Reference], + from_package: &[(String, String)], + imports: &[String], +) -> Result<(), String> { + for (package, name) in from_package { + let unqualified = needed + .iter() + .filter(|reference| reference.name == *name) + .any(|reference| !qualified(text, reference.name_span)); + if !unqualified { + continue; + } + let imported = imports + .iter() + .any(|path| path == &format!("{package}::*") || path == &format!("{package}::{name}")); + if !imported { + return Err(format!( + "the selection uses `{name}`, which `{package}` declares, without writing `{package}::` in front of it and without an `import` lucisv could carry across; write the package out, or import it where the new module can see it." + )); + } + } + Ok(()) +} + +/// Whether a name is written with its package in front of it: `w_pkg::word_t`. +fn qualified(text: &str, span: TextRange) -> bool { + text.get(..span.start as usize).is_some_and(|head| head.trim_end().ends_with("::")) +} + +/// The `package` of this file whose body holds `span`, if any. +fn package_of(packages: &[(String, TextRange)], span: TextRange) -> Option<&str> { + packages + .iter() + .find(|(_, at)| at.start <= span.start && span.end <= at.end) + .map(|(name, _)| name.as_str()) +} + +/// Every `package` this file declares, with the bytes it occupies. +pub(super) fn packages(tree: &SourceFile) -> Vec<(String, TextRange)> { + tree.items + .iter() + .filter_map(|item| match &item.kind { + ItemKind::Package { name, .. } => Some((name.clone(), item.span)), + _ => None, + }) + .collect() +} diff --git a/crates/vlog_refactor/src/extract/flow.rs b/crates/vlog_refactor/src/extract/flow.rs new file mode 100644 index 0000000..ef1e0ed --- /dev/null +++ b/crates/vlog_refactor/src/extract/flow.rs @@ -0,0 +1,664 @@ +//! Which names cross the selection's boundary, and in which direction. +//! +//! The whole of "what ports does the new module need" is here, and it is one +//! question asked of two tables: `vlog_semantic`'s references say *which +//! declaration* each name in the module means, and the tree says whether each +//! use of it is a **write** or a **read**. A name declared outside the +//! selection and used inside it becomes a port — `input` when the selection +//! only reads it, `output` when the selection writes it. +//! +//! **A name is written by the selection when, and only when, it is:** the +//! left-hand side of a continuous assignment; the left-hand side of a +//! blocking or non-blocking assignment (or of a `for` initialiser or step, or +//! the target of a `++`/`--`) anywhere inside an `always` block; the target of +//! a `force`, a `release` or a `deassign`; the target of a `-> ev`; the +//! declarator's own initialiser; or connected to an `output` or `inout` port +//! of an instantiated module — which is a fact only that module's own +//! declaration holds, so it is looked up through the workspace index and the +//! extraction is **refused** when the index cannot answer. Everything else is +//! a read. Two positions are neither, and both refuse rather than guess: an +//! argument of a task or function call, whose direction only the routine's +//! prototype knows, and a positional or `.*` connection, which names no port +//! at all. +//! +//! Nothing here edits. It answers, or it refuses with a sentence. + +use std::collections::HashMap; + +use vlog_parser::ast::{ + Connections, Expr, ExprKind, ForStep, Instantiation, Item, ItemKind, ListElem, Stmt, StmtKind, +}; +use vlog_parser::span::TextRange; +use vlog_semantic::{Reference, Resolution, Semantics, Surface, SymbolId, SymbolKind}; + +use crate::instantiate::{instantiation_plan, module_definition}; +use crate::rename::Scope; + +use super::region::Region; + +/// What one use of a name is. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Use { + Read, + Write, + /// A position whose direction lucisv cannot know: a call argument, a + /// connection to a port it could not read. + Unknown, +} + +/// Everything done to one declaration, on each side of the boundary. +#[derive(Debug, Default, Clone, Copy)] +pub(super) struct Sides { + pub(super) inside_read: bool, + pub(super) inside_write: bool, + pub(super) inside_unknown: bool, + pub(super) outside_read: bool, + pub(super) outside_write: bool, + pub(super) outside_unknown: bool, +} + +impl Sides { + pub(super) fn used_inside(&self) -> bool { + self.inside_read || self.inside_write || self.inside_unknown + } + + pub(super) fn used_outside(&self) -> bool { + self.outside_read || self.outside_write || self.outside_unknown + } +} + +/// The boundary table: what each declaration the module holds has done to it +/// on each side of the selection, and which of the module's own references sit +/// inside it. +pub(super) struct Flow { + sides: HashMap, + /// The references written inside the region, in source order. + pub(super) inside: Vec, +} + +impl Flow { + pub(super) fn sides(&self, symbol: SymbolId) -> Sides { + self.sides.get(&symbol).copied().unwrap_or_default() + } +} + +/// Classify every use of every name in the module, on both sides of the +/// selection. +pub(super) fn read( + scope: &Scope<'_>, + text: &str, + semantics: &Semantics, + region: &Region<'_>, +) -> Result { + let mut marks = Marks::default(); + marks.items(scope, region, ®ion.module.items)?; + + // Every reference in the file, placed on its side of the boundary and + // given the direction the tree marked its span with. + let mut sides: HashMap = HashMap::new(); + let mut inside = Vec::new(); + for (n, reference) in semantics.references().iter().enumerate() { + let span = reference.name_span; + let within = region.span.start <= span.start && span.end <= region.span.end; + if within { + inside.push(n); + } + let Resolution::Resolved(symbol) = reference.resolution else { continue }; + let use_ = marks.use_of(span); + let entry = sides.entry(symbol).or_default(); + match (within, use_) { + (true, Use::Read) => entry.inside_read = true, + (true, Use::Write) => entry.inside_write = true, + (true, Use::Unknown) => entry.inside_unknown = true, + (false, Use::Read) => entry.outside_read = true, + (false, Use::Write) => entry.outside_write = true, + (false, Use::Unknown) => entry.outside_unknown = true, + } + } + // A declarator's own initialiser writes the declaration rather than + // referring to it, so it is not in the reference table at all. + for (span, within) in marks.initialised.drain(..) { + let Some(symbol) = semantics.symbol_at(span.start) else { continue }; + let entry = sides.entry(symbol).or_default(); + match within { + true => entry.inside_write = true, + false => entry.outside_write = true, + } + } + let _ = text; + Ok(Flow { sides, inside }) +} + +/// Whether any reference inside the region is a **hierarchical** one whose +/// head instance the region does not itself declare — `u_x.sig` reaching out +/// of the selection, which lucisv will not move across a module boundary. +/// +/// The §49 surface is what says a tail is hierarchical at all +/// ([`Surface::Hierarchical`] is recorded exactly when the head resolved to an +/// instance); the head is then the nearest reference before it that resolved +/// to an [`SymbolKind::Instance`] with nothing but the dots of the path +/// between them. +pub(super) fn hierarchical_escape( + text: &str, + semantics: &Semantics, + region: &Region<'_>, +) -> Option { + let refs = semantics.references(); + for reference in refs { + let span = reference.name_span; + if span.start < region.span.start || region.span.end < span.end { + continue; + } + let Resolution::ExternalCandidate { surface: Surface::Hierarchical, .. } = + &reference.resolution + else { + continue; + }; + match head_of(text, semantics, refs, reference) { + // The instance the path starts at moves with the selection, so + // the path is not crossing anything. It is the *declaration* that + // has to move, not the mention of it. + Some(head) if declared_inside(semantics, region, head) => continue, + Some(head) => return Some(format!("{}.{}", head.name, reference.name)), + None => return Some(format!("\u{2026}.{}", reference.name)), + } + } + None +} + +/// The instance a hierarchical tail hangs off: the nearest earlier reference +/// that resolved to an instance, with only a dotted path between the two. +fn head_of<'r>( + text: &str, + semantics: &Semantics, + refs: &'r [Reference], + tail: &Reference, +) -> Option<&'r Reference> { + let mut best: Option<&Reference> = None; + for candidate in refs { + if candidate.name_span.end > tail.name_span.start { + continue; + } + let is_instance = candidate + .resolved() + .and_then(|id| semantics.symbol(id)) + .is_some_and(|symbol| symbol.kind == SymbolKind::Instance); + if !is_instance { + continue; + } + if best.is_none_or(|found| candidate.name_span.end > found.name_span.end) { + best = Some(candidate); + } + } + let head = best?; + let between = text.get(head.name_span.end as usize..tail.name_span.start as usize)?; + // A dotted path, index selects included: `u_a.u_b`, `u_q[0].sig`. + let dotted = between + .chars() + .all(|c| c == '.' || c == '[' || c == ']' || c == ':' || c.is_alphanumeric() || c == '_'); + dotted.then_some(head) +} + +fn inside(region: &Region<'_>, span: TextRange) -> bool { + region.span.start <= span.start && span.end <= region.span.end +} + +/// Whether the declaration a reference names is written inside the region. +fn declared_inside(semantics: &Semantics, region: &Region<'_>, reference: &Reference) -> bool { + reference + .resolved() + .and_then(|id| semantics.symbol(id)) + .is_some_and(|symbol| inside(region, symbol.name_span)) +} + +// ---------------------------------------------------------------------- +// marking the tree +// ---------------------------------------------------------------------- + +/// Where the tree says a name is written, and where it says lucisv cannot +/// know. Both are sets of *name spans*, which is what lets the reference table +/// be read straight off them. +#[derive(Default)] +struct Marks { + writes: Vec, + unknown: Vec, + /// `(declared name's span, inside the region)` for every declarator whose + /// own initialiser drives it. + initialised: Vec<(TextRange, bool)>, +} + +impl Marks { + fn use_of(&self, span: TextRange) -> Use { + if self.unknown.iter().any(|marked| covers(*marked, span)) { + return Use::Unknown; + } + match self.writes.contains(&span) { + true => Use::Write, + false => Use::Read, + } + } + + fn items( + &mut self, + scope: &Scope<'_>, + region: &Region<'_>, + items: &[Item], + ) -> Result<(), String> { + for item in items { + self.item(scope, region, item)?; + } + Ok(()) + } + + fn item(&mut self, scope: &Scope<'_>, region: &Region<'_>, item: &Item) -> Result<(), String> { + match &item.kind { + ItemKind::DataDecl(decl) => { + for declarator in &decl.declarators { + if declarator.init.is_some() { + self.initialised + .push((declarator.name_span, inside(region, declarator.name_span))); + } + } + } + ItemKind::ContAssign(assign) => { + for pair in &assign.assigns { + self.write(&pair.lhs); + } + } + ItemKind::Always { stmt, .. } => self.body(stmt), + ItemKind::Initial(stmt) | ItemKind::Final(stmt) => self.body(stmt), + ItemKind::Function(decl) => { + for stmt in &decl.stmts { + self.body(stmt); + } + } + ItemKind::Task(decl) => { + for stmt in &decl.stmts { + self.body(stmt); + } + } + ItemKind::Instantiation(inst) => self.instantiation(scope, region, inst)?, + ItemKind::GateInstantiation(gates) => { + for instance in &gates.instances { + for arg in &instance.args { + self.unknown.push(arg.span); + } + } + } + ItemKind::GenerateRegion { items, .. } => self.items(scope, region, items)?, + ItemKind::GenBlock(block) => self.items(scope, region, &block.items)?, + ItemKind::GenIf(gen_if) => { + self.items(scope, region, &gen_if.then.items)?; + let mut els = gen_if.els.as_deref(); + while let Some(branch) = els { + match branch { + vlog_parser::ast::GenElse::If(_, nested) => { + self.items(scope, region, &nested.then.items)?; + els = nested.els.as_deref(); + } + vlog_parser::ast::GenElse::Block(block) => { + self.items(scope, region, &block.items)?; + els = None; + } + } + } + } + ItemKind::GenFor(gen_for) => self.items(scope, region, &gen_for.body.items)?, + ItemKind::GenCase(gen_case) => { + for case_item in &gen_case.items { + self.items(scope, region, &case_item.body.items)?; + } + } + _ => {} + } + Ok(()) + } + + /// Every write inside one procedural block, at any statement depth. + fn body(&mut self, stmt: &Stmt) { + walk(stmt, &mut |stmt| match &stmt.kind { + StmtKind::Assign { lhs, .. } | StmtKind::ForceRelease { lhs, .. } => self.write(lhs), + StmtKind::EventTrigger(expr) => self.write(expr), + StmtKind::For { init, step, .. } => { + for entry in init { + self.write(&entry.assign.lhs); + } + for entry in step { + match entry { + ForStep::Assign(assign) => self.write(&assign.lhs), + ForStep::Expr(expr) => match increment_target(expr) { + Some(target) => self.write(target), + None => self.unknown.push(expr.span), + }, + } + } + } + // `x++;` is a write; every other expression statement is a call, + // whose arguments may be `output` arguments. + StmtKind::ExprStmt(expr) => match increment_target(expr) { + Some(target) => self.write(target), + None => self.unknown.push(expr.span), + }, + _ => {} + }); + // A call written anywhere in the block — in a condition, on the + // right-hand side of an assignment — passes arguments whose direction + // only the routine's own prototype knows. + walk(stmt, &mut |stmt| stmt_exprs(stmt, &mut |expr| self.calls(expr))); + } + + /// An instantiation's connections, whose direction the instantiated + /// module's declaration holds. + fn instantiation( + &mut self, + scope: &Scope<'_>, + region: &Region<'_>, + inst: &Instantiation, + ) -> Result<(), String> { + let touches = inst.instances.iter().any(|instance| inside(region, instance.name_span)); + for instance in &inst.instances { + match &instance.conns { + Connections::Ordered(conns) => { + if touches { + return Err(positional(&inst.module, &instance.name)); + } + for conn in conns { + self.unknown.push(match conn { + ListElem::Ok(conn) => conn.span, + ListElem::Error(raw) => raw.span, + }); + } + } + Connections::Named(conns) => { + let ports = match touches { + true => Some(ports_of(scope, &inst.module)?), + false => None, + }; + for conn in conns { + let conn = match conn { + ListElem::Ok(conn) => conn, + ListElem::Error(raw) => { + if touches { + return Err(unreadable(&inst.module, &instance.name)); + } + self.unknown.push(raw.span); + continue; + } + }; + let Some(ports) = ports.as_deref() else { + self.unknown.push(conn.span); + continue; + }; + if conn.name == "*" { + return Err(wildcard(&inst.module, &instance.name)); + } + // `.p` with no expression connects the same-named + // signal, whose own name is not written down here; + // the connection's port name is the signal's name. + let Some(port) = ports.iter().find(|(name, _)| *name == conn.name) else { + return Err(no_such_port(&inst.module, &conn.name)); + }; + let Some(expr) = &conn.expr else { + return Err(implicit(&inst.module, &instance.name, &conn.name)); + }; + match port.1.as_str() { + "output" | "inout" => self.write(expr), + "input" => {} + _ => return Err(no_direction(&inst.module, &conn.name)), + } + } + } + } + } + Ok(()) + } + + /// Every argument of every call in an expression, marked unknown. + fn calls(&mut self, expr: &Expr) { + walk_expr(expr, &mut |expr| { + if let ExprKind::Call { args, .. } = &expr.kind { + for arg in args { + self.unknown.push(arg.span); + } + } + }); + } + + /// Records every name an assignment's left-hand side writes. + fn write(&mut self, lhs: &Expr) { + lvalue_targets(lhs, &mut self.writes); + } +} + +/// Whether `outer` covers `inner` entirely. +fn covers(outer: TextRange, inner: TextRange) -> bool { + outer.start <= inner.start && inner.end <= outer.end +} + +/// The names one left-hand side writes. `a.b[3] = x` writes `a`, which is +/// what resolves. +fn lvalue_targets(expr: &Expr, out: &mut Vec) { + match &expr.kind { + ExprKind::Ident(_) => out.push(expr.span), + ExprKind::Paren { inner, .. } => lvalue_targets(inner, out), + ExprKind::Cast { expr, .. } => lvalue_targets(expr, out), + ExprKind::Index { base, .. } | ExprKind::Range { base, .. } => lvalue_targets(base, out), + ExprKind::Member { base, .. } => lvalue_targets(base, out), + ExprKind::Concat(items) | ExprKind::Stream { inner: items, .. } => { + for item in items { + lvalue_targets(&item.expr, out); + } + } + _ => {} + } +} + +/// The target of `x++` / `x--` / `++x`, which is a write dressed as an +/// expression. +fn increment_target(expr: &Expr) -> Option<&Expr> { + match &expr.kind { + ExprKind::Postfix { expr, op, .. } | ExprKind::Unary { expr, op, .. } + if op == "++" || op == "--" => + { + Some(expr) + } + _ => None, + } +} + +/// The ports of an instantiated module: name and direction, read from the +/// file the workspace index says declares it. +fn ports_of(scope: &Scope<'_>, module: &str) -> Result, String> { + let path = + module_definition(scope.index(), module).map_err(|_| unknown_module(module))?.to_path_buf(); + let Some(text) = scope.index_of(&path).and_then(|i| scope.text(i)) else { + return Err(unknown_module(module)); + }; + let plan = instantiation_plan(module, text, None).map_err(|_| unknown_module(module))?; + Ok(plan.ports.into_iter().map(|port| (port.name, port.dir)).collect()) +} + +// ---------------------------------------------------------------------- +// walks +// ---------------------------------------------------------------------- + +fn walk(stmt: &Stmt, f: &mut dyn FnMut(&Stmt)) { + f(stmt); + match &stmt.kind { + StmtKind::Block { stmts, .. } | StmtKind::ForkJoin { stmts, .. } => { + for stmt in stmts { + walk(stmt, f); + } + } + StmtKind::If { then, els, .. } => { + walk(then, f); + if let Some(els) = els { + walk(els, f); + } + } + StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => { + for item in items { + walk(&item.stmt, f); + } + } + StmtKind::Labeled { stmt, .. } => walk(stmt, f), + StmtKind::For { body, .. } + | StmtKind::While { body, .. } + | StmtKind::DoWhile { body, .. } + | StmtKind::Repeat { body, .. } + | StmtKind::Forever { body } + | StmtKind::Foreach { body, .. } => walk(body, f), + StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => { + walk(inner, f) + } + StmtKind::Assert { then, els, .. } => { + if let Some(then) = then { + walk(then, f); + } + if let Some(els) = els { + walk(els, f); + } + } + _ => {} + } +} + +/// The expressions one statement writes directly — not its children's. +fn stmt_exprs(stmt: &Stmt, f: &mut dyn FnMut(&Expr)) { + match &stmt.kind { + StmtKind::Assign { lhs, rhs, .. } => { + f(lhs); + f(rhs); + } + StmtKind::If { cond, .. } | StmtKind::While { cond, .. } | StmtKind::Wait { cond, .. } => { + f(cond) + } + StmtKind::DoWhile { cond, .. } => f(cond), + StmtKind::Case { expr, items, .. } => { + f(expr); + for item in items { + for label in &item.labels { + f(&label.expr); + } + } + } + StmtKind::Repeat { count, .. } => f(count), + StmtKind::ExprStmt(expr) | StmtKind::EventTrigger(expr) => f(expr), + StmtKind::ForceRelease { lhs, rhs, .. } => { + f(lhs); + if let Some(rhs) = rhs { + f(rhs); + } + } + StmtKind::For { init, cond, step, .. } => { + for entry in init { + f(&entry.assign.rhs); + } + if let Some(cond) = cond { + f(cond); + } + for entry in step { + match entry { + ForStep::Assign(assign) => f(&assign.rhs), + ForStep::Expr(expr) => f(expr), + } + } + } + StmtKind::Return { expr: Some(expr), .. } => f(expr), + StmtKind::Assert { cond, .. } => f(cond), + _ => {} + } +} + +fn walk_expr(expr: &Expr, f: &mut dyn FnMut(&Expr)) { + f(expr); + match &expr.kind { + ExprKind::Unary { expr, .. } | ExprKind::Postfix { expr, .. } => walk_expr(expr, f), + ExprKind::Binary { lhs, rhs, .. } => { + walk_expr(lhs, f); + walk_expr(rhs, f); + } + ExprKind::Ternary { cond, then, els, .. } => { + walk_expr(cond, f); + walk_expr(then, f); + walk_expr(els, f); + } + ExprKind::Call { callee, args, .. } => { + walk_expr(callee, f); + for arg in args { + walk_expr(&arg.expr, f); + } + } + ExprKind::Index { base, index, .. } => { + walk_expr(base, f); + walk_expr(index, f); + } + ExprKind::Range { base, msb, lsb, .. } => { + walk_expr(base, f); + walk_expr(msb, f); + walk_expr(lsb, f); + } + ExprKind::Member { base, .. } | ExprKind::Scope { base, .. } => walk_expr(base, f), + ExprKind::Concat(items) | ExprKind::Stream { inner: items, .. } => { + for item in items { + walk_expr(&item.expr, f); + } + } + ExprKind::Repl { count, inner, .. } => { + walk_expr(count, f); + for item in inner { + walk_expr(&item.expr, f); + } + } + ExprKind::Paren { inner, .. } => walk_expr(inner, f), + ExprKind::Cast { expr, .. } => walk_expr(expr, f), + ExprKind::New(inner) => walk_expr(inner, f), + _ => {} + } +} + +// ---------------------------------------------------------------------- +// sentences +// ---------------------------------------------------------------------- + +fn positional(module: &str, instance: &str) -> String { + format!( + "`{instance}` connects `{module}` by position, so lucisv cannot tell which of its connections are outputs; convert it to named connections first." + ) +} + +fn wildcard(module: &str, instance: &str) -> String { + format!( + "`{instance}` connects `{module}` with `.*`, which names no signals; expand the `.*` first (lucisv offers that as its own refactoring)." + ) +} + +fn implicit(module: &str, instance: &str, port: &str) -> String { + format!( + "`{instance}` connects `{module}`'s `{port}` implicitly (`.{port}`), which names no expression for lucisv to move; write the signal out first." + ) +} + +fn unreadable(module: &str, instance: &str) -> String { + format!( + "lucisv could not read one of `{instance}`'s connections to `{module}`, so it cannot tell what the selection drives." + ) +} + +fn unknown_module(module: &str) -> String { + format!( + "the selection instantiates `{module}`, and lucisv has no single indexed declaration of it, so it cannot tell which of its connections are outputs." + ) +} + +fn no_such_port(module: &str, port: &str) -> String { + format!( + "the selection connects `.{port}`, which `{module}`'s declaration does not name, so lucisv cannot tell whether it is driven." + ) +} + +fn no_direction(module: &str, port: &str) -> String { + format!( + "`{module}` declares `{port}` without a direction, so lucisv cannot tell whether the selection drives it." + ) +} diff --git a/crates/vlog_refactor/src/extract/mod.rs b/crates/vlog_refactor/src/extract/mod.rs new file mode 100644 index 0000000..cd85c74 --- /dev/null +++ b/crates/vlog_refactor/src/extract/mod.rs @@ -0,0 +1,511 @@ +//! Extract a selection of whole module items into a module of its own. +//! +//! The user selects one or more contiguous items of a module `M` — an +//! `always` block, an `assign`, an instantiation, a declaration, a generate +//! construct — and names the module `N` they want them in. lucisv works out +//! `N`'s ports from the dataflow across the selection's boundary, writes `N` +//! into a file of its own beside `M`'s (or below `M`, for a client that cannot +//! create files), and replaces the selection with an instantiation of `N` +//! **rendered from `N`'s own text**, so the skeleton and the module can never +//! disagree about what `N`'s ports are. +//! +//! Three files, one question each: +//! +//! * `region` — *what does the selection cover?* The module, the run of whole +//! items, and the item kinds lucisv will not carry into another module. +//! * `flow` — *which names cross the boundary, and in which direction?* The +//! dataflow rule, and the two positions it refuses to guess at. +//! * `render` — *what does lucisv write?* A port's type as its declaration +//! spells it, the new module, and the instantiation. +//! +//! This file is the plan: the entry points, the classification of each +//! crossing name into a port, a parameter or a refusal, the edits, and the +//! verification. Everything is one [`check::verify_move`] over the whole edit, +//! which for a new file is the ordinary splice contract plus one deliberate +//! widening: the comments the selection carries are deleted in `M`'s file and +//! written in `N`'s, so the never-dropped ledger is kept over the pair rather +//! than over each file alone. See +//! `docs/features/extract-inline-module/README.md`. + +mod boundary; +mod flow; +mod region; +mod render; + +use std::path::{Path, PathBuf}; + +use vlog_parser::ast::{Item, ItemKind, SourceFile}; +use vlog_parser::parse_source_tolerant; +use vlog_parser::span::TextRange; +use vlog_semantic::{analyze, SymbolKind}; + +use crate::rename::{display, Scope}; +use crate::{check, RefactorEdit, TextEdit}; + +use boundary::Crossing; +use region::Region; + +/// Where the extracted module is written. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Home { + /// A file `N.sv` beside `M`'s own — what a client that advertises + /// `workspace.workspaceEdit.documentChanges` with `CreateFile` support + /// gets, because only such a client can apply the creation. + NewFile, + /// Below `M`, in `M`'s own file — the fallback for every other client, + /// and for a caller that asked for it. + SameFile, +} + +/// What the cheap gate found: the selection is in a module, and these are the +/// units whose files the engine needs read. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ExtractSite { + /// The module the selection is written in. + pub module: String, + /// The name the action proposes when the caller has none: `M_extracted`. + pub default_name: String, + /// Every unit whose declaration the engine will look up: the module + /// itself, the modules the selection instantiates, and the packages the + /// module imports. + pub units: Vec, +} + +/// Whether a selection is one lucisv could extract, and what it would need to +/// read to try. +/// +/// **The cheap gate**: one parse of one buffer, no workspace and no I/O — the +/// bargain `port_action_modules` and `imported_packages` strike, and for the +/// same reason (a `textDocument/codeAction` arrives on every cursor move). +/// Empty exactly where [`extract_module`] would refuse for want of a module or +/// a whole item to move. +pub fn extract_site(text: &str, start: u32, end: u32) -> Option { + let (tree, diagnostics) = parse_source_tolerant(text); + if !diagnostics.is_empty() { + return None; + } + let region = Region::read(&tree, text, TextRange::new(start, end)).ok()?; + let module = region.module_name().to_string(); + let mut units = vec![module.clone()]; + for item in ®ion.items { + collect_instantiated(item, &mut units); + } + for import in ®ion.module.imports { + for path in &import.paths { + push(&mut units, path.pkg.text.clone()); + } + } + for item in ®ion.module.items { + if let ItemKind::Import(paths) = &item.kind { + for path in paths { + push(&mut units, path.pkg.text.clone()); + } + } + } + Some(ExtractSite { default_name: format!("{module}_extracted"), module, units }) +} + +/// The lightbulb's text, written here so every front end says the same thing. +pub fn extract_title() -> String { + "lucisv: extract selection into module…".to_string() +} + +/// Extract the items `[start, end)` covers out of the module that holds them, +/// into a module called `new_name`. +pub fn extract_module( + files: &[(PathBuf, String)], + file: &Path, + start: u32, + end: u32, + new_name: &str, + home: Home, +) -> Result { + plain_identifier(new_name)?; + // The new file joins the in-scope set as an *empty* file, so that every + // question below — the index, the analysis, the verification — is asked + // about it exactly the way it is asked about a file that was always there. + let mut sources: Vec<(PathBuf, String)> = files.to_vec(); + let created = match home { + Home::SameFile => None, + Home::NewFile => { + let path = beside(file, new_name); + match sources.iter().find(|(held, _)| *held == path) { + Some((_, text)) if !text.trim().is_empty() => return Err(occupied(&path)), + Some(_) => {} + None => sources.push((path.clone(), String::new())), + } + Some(path) + } + }; + let plan = Extraction::plan(&sources, file, start, end, new_name, created.clone())?; + Ok(RefactorEdit { + edits: plan.edits, + warnings: plan.warnings, + created: created.into_iter().collect(), + }) +} + +/// What the extraction produced, before it is dressed as a [`RefactorEdit`]. +struct Extraction { + edits: Vec<(PathBuf, Vec)>, + warnings: Vec, +} + +impl Extraction { + fn plan( + sources: &[(PathBuf, String)], + file: &Path, + start: u32, + end: u32, + new_name: &str, + created: Option, + ) -> Result { + let mut scope = Scope::build(sources); + let Some(here) = scope.index_of(file) else { return Err(not_in_scope(file)) }; + let Some(text) = scope.text(here) else { return Err(not_in_scope(file)) }; + let (tree, diagnostics) = parse_source_tolerant(text); + if let Some(problem) = diagnostics.first() { + return Err(format!( + "{} does not parse ({} at line {}), so lucisv will not extract from it.", + display(file), + problem.message, + problem.line + )); + } + let region = Region::read(&tree, text, TextRange::new(start, end))?; + let module = region.module_name().to_string(); + declared_once(&scope, &module)?; + undeclared(&scope, new_name)?; + if new_name == module { + return Err(format!("`{module}` is already the name of the module you are in.")); + } + if created.is_some() { + no_directive(&tree, text, ®ion)?; + } + let semantics = analyze(&tree, text); + if let Some(path) = flow::hierarchical_escape(text, &semantics, ®ion) { + return Err(hierarchical(&path)); + } + let flow = flow::read(&scope, text, &semantics, ®ion)?; + let packages = boundary::packages(&tree); + let crossing = + Crossing::read(text, &semantics, ®ion, &flow, &packages, created.is_some())?; + + // The new module, then the instantiation read back out of it. + let body = format!("{}{}", region.indent, slice(text, region.span)); + let module_text = render::new_module( + new_name, + &crossing.imports, + &crossing.params, + &crossing.ports, + &ensure_newline(&body), + ); + let instance = render::instantiation(new_name, &module_text, ®ion.indent)?; + + let mut edits: Vec<(usize, Vec)> = Vec::new(); + // What the verifier is allowed to let travel, and between which bytes: + // `M`'s file loses exactly the pieces inside the region, and the new + // file — named with an empty range, because it has no region of its + // own — is the only place they may land. + let mut moving: Vec<(usize, TextRange)> = Vec::new(); + let replace = TextEdit { range: region.span, new_text: instance }; + match &created { + Some(path) => { + let Some(there) = scope.index_of(path) else { return Err(not_in_scope(path)) }; + edits.push((here, vec![replace])); + edits.push(( + there, + vec![TextEdit { range: TextRange::empty(0), new_text: module_text.clone() }], + )); + moving = vec![(here, region.span), (there, TextRange::empty(0))]; + } + None => { + let append = TextEdit { + range: TextRange::empty(region.module_span.end), + new_text: format!("\n\n{module_text}"), + }; + edits.push((here, vec![replace, append])); + } + } + edits.sort_by_key(|(i, _)| *i); + moving.sort_by_key(|(i, _)| *i); + + let what = format!("extracting `{new_name}` out of `{module}`"); + check::verify_move(&mut scope, &edits, &[&module, new_name], &what, &moving)?; + confirm(&scope, &edits, new_name, &crossing, &what)?; + + let mut out: Vec<(PathBuf, Vec)> = Vec::new(); + for (i, file_edits) in edits { + let Some(path) = scope.path(i) else { return Err(lost(&what)) }; + out.push((path.to_path_buf(), file_edits)); + } + out.sort_by(|a, b| a.0.cmp(&b.0)); + Ok(Extraction { edits: out, warnings: crossing.warnings(new_name, &created, file) }) + } +} + +/// Read the edited text back and require the new module to declare exactly the +/// ports and parameters the plan promised. +/// +/// `verify_move` proves the edit is lexically and semantically honest; nothing +/// in it proves the header lucisv wrote is the header it meant to write. +fn confirm( + scope: &Scope<'_>, + edits: &[(usize, Vec)], + new_name: &str, + crossing: &Crossing, + what: &str, +) -> Result<(), String> { + for (i, file_edits) in edits { + let (Some(text), Some(path)) = (scope.text(*i), scope.path(*i)) else { + return Err(lost(what)); + }; + let edited = crate::apply(text, file_edits); + let Ok(plan) = crate::instantiate::instantiation_plan(new_name, &edited, None) else { + continue; + }; + let ports: Vec<&str> = plan.ports.iter().map(|port| port.name.as_str()).collect(); + let params: Vec<&str> = plan.params.iter().map(|param| param.name.as_str()).collect(); + let wanted_ports: Vec<&str> = crossing.ports.iter().map(|p| p.name.as_str()).collect(); + let wanted_params: Vec<&str> = crossing.params.iter().map(|p| p.name.as_str()).collect(); + if ports != wanted_ports || params != wanted_params { + return Err(format!( + "{what} would not leave `{new_name}` with the header lucisv intended in {}; no edits were made.", + display(path) + )); + } + return Ok(()); + } + Err(lost(what)) +} + +// ---------------------------------------------------------------------- +// odds and ends +// ---------------------------------------------------------------------- + +fn inside(region: &Region<'_>, span: TextRange) -> bool { + region.span.start <= span.start && span.end <= region.span.end +} + +fn inside_module(region: &Region<'_>, span: TextRange) -> bool { + region.module_span.start <= span.start && span.end <= region.module_span.end +} + +fn slice(text: &str, span: TextRange) -> &str { + text.get(span.start as usize..span.end as usize).unwrap_or("") +} + +fn ensure_newline(text: &str) -> String { + match text.ends_with('\n') { + true => text.to_string(), + false => format!("{text}\n"), + } +} + +fn push(out: &mut Vec, name: String) { + if !out.contains(&name) { + out.push(name); + } +} + +/// Every module an item instantiates, nested generate constructs included. +fn collect_instantiated(item: &Item, out: &mut Vec) { + match &item.kind { + ItemKind::Instantiation(inst) => push(out, inst.module.clone()), + ItemKind::GenerateRegion { items, .. } => { + for item in items { + collect_instantiated(item, out); + } + } + ItemKind::GenBlock(block) => { + for item in &block.items { + collect_instantiated(item, out); + } + } + ItemKind::GenIf(gen_if) => { + for item in &gen_if.then.items { + collect_instantiated(item, out); + } + let mut els = gen_if.els.as_deref(); + while let Some(branch) = els { + match branch { + vlog_parser::ast::GenElse::If(_, nested) => { + for item in &nested.then.items { + collect_instantiated(item, out); + } + els = nested.els.as_deref(); + } + vlog_parser::ast::GenElse::Block(block) => { + for item in &block.items { + collect_instantiated(item, out); + } + els = None; + } + } + } + } + ItemKind::GenFor(gen_for) => { + for item in &gen_for.body.items { + collect_instantiated(item, out); + } + } + ItemKind::GenCase(gen_case) => { + for case_item in &gen_case.items { + for item in &case_item.body.items { + collect_instantiated(item, out); + } + } + } + _ => {} + } +} + +/// The file the new module goes in: `N.sv`, beside the file it came out of. +fn beside(file: &Path, new_name: &str) -> PathBuf { + let parent = file.parent().map_or_else(PathBuf::new, Path::to_path_buf); + parent.join(format!("{new_name}.sv")) +} + +/// A module name lucisv will write into a file name and a header: a plain +/// identifier, never an escaped one. +fn plain_identifier(name: &str) -> Result<(), String> { + let mut chars = name.chars(); + let head = chars.next().filter(|c| c.is_ascii_alphabetic() || *c == '_'); + let tail = chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$'); + match head.is_some() && tail { + true => Ok(()), + false => Err(format!( + "`{name}` is not a plain SystemVerilog identifier, and lucisv will not name a module — or a file — with anything else." + )), + } +} + +/// The module the selection is in must be declared exactly once in the +/// workspace: an extraction rewrites *this* `M`, and two of them means lucisv +/// does not know whose ports the selection reads. +fn declared_once(scope: &Scope<'_>, module: &str) -> Result<(), String> { + let defs = scope.index().units(module).iter().filter(|def| def.kind.is_instantiable()).count(); + match defs { + 1 => Ok(()), + 0 => Err(format!("lucisv indexes no module named `{module}`.")), + _ => Err(format!( + "`{module}` is declared in more than one indexed file, so lucisv cannot tell which one the selection belongs to." + )), + } +} + +fn undeclared(scope: &Scope<'_>, name: &str) -> Result<(), String> { + match scope.index().units(name).is_empty() { + true => Ok(()), + false => { + Err(format!("the workspace already declares `{name}`; pick a name nothing else uses.")) + } + } +} + +/// A `timescale` or a `default_nettype` in force where `M` is written does not +/// follow the items into a file of their own, and silently changing either one +/// changes what the design does. +fn no_directive(tree: &SourceFile, text: &str, region: &Region<'_>) -> Result<(), String> { + for item in &tree.items { + let ItemKind::Directive(raw) = &item.kind else { continue }; + if item.span.start > region.module_span.end { + continue; + } + let word = raw.text.split_whitespace().next().unwrap_or(""); + if word == "`timescale" || word == "`default_nettype" || word == "`resetall" { + return Err(format!( + "`{}` writes `{word}` before the module the selection is in, and a new file would not inherit it; extract into the same file, or move the directive into an include both files use.", + first_line(text, item.span.start) + )); + } + } + Ok(()) +} + +/// The file's own name is not to hand here, so a directive refusal names the +/// line the directive is on instead. +fn first_line(text: &str, at: u32) -> String { + let line = text.get(..at as usize).map_or(0, |head| head.matches('\n').count()) + 1; + format!("line {line}") +} + +fn count(n: usize, noun: &str) -> String { + match n { + 1 => format!("1 {noun}"), + n => format!("{n} {noun}s"), + } +} + +// ---------------------------------------------------------------------- +// sentences +// ---------------------------------------------------------------------- + +fn not_in_scope(file: &Path) -> String { + format!("{} is not one of the files lucisv was given.", display(file)) +} + +fn occupied(path: &Path) -> String { + format!("there is already a `{}` beside this file; pick another name.", display(path)) +} + +fn escaped(name: &str) -> String { + format!( + "`{name}` is declared inside the selection and used outside it; move the declaration of `{name}` out of the selection first." + ) +} + +fn outside_module(name: &str, module: &str) -> String { + format!( + "the selection uses `{name}`, which is declared outside `{module}` in the same file; a module in a file of its own would not see it, so lucisv made no edits." + ) +} + +/// The same refusal for a **member access**, which names the head first. +/// `s.f` and `bus.data` cross the boundary as `s` and `bus` — the port or the +/// variable — and `f` and `data` are names of *their* types; a sentence that +/// leads with the field reads as if the field were a signal of `M`'s own. +fn outside_module_member(head: &str, name: &str, module: &str) -> String { + format!( + "the selection uses `{head}.{name}`, and `{head}` is declared with a type written outside `{module}` in the same file; a module in a file of its own would not see it, so lucisv made no edits." + ) +} + +fn unmovable(name: &str, module: &str, kind: SymbolKind) -> String { + let what = match kind { + SymbolKind::Genvar => "a `genvar`", + SymbolKind::Function => "a function", + SymbolKind::Task => "a task", + SymbolKind::Typedef => "a type", + SymbolKind::EnumVariant => "an enumeration member", + SymbolKind::Instance => "an instance", + SymbolKind::Modport => "a modport", + SymbolKind::Clocking => "a clocking block", + SymbolKind::Class => "a class", + SymbolKind::Block => "a named block", + _ => "a declaration", + }; + format!( + "the selection uses `{name}`, {what} `{module}` declares outside it; lucisv makes ports out of signals and parameters and nothing else, so it made no edits." + ) +} + +fn header_names(module: &str, owner: &str, word: &str) -> String { + format!( + "`{module}` declares `{owner}` with something that names `{word}`, which is neither a parameter nor a name a module in another file could reach; lucisv made no edits." + ) +} + +fn hierarchical(path: &str) -> String { + format!( + "the selection reads `{path}` through the design hierarchy, and a hierarchical path does not survive being moved into another module; lucisv made no edits." + ) +} + +fn lost_name(name: &str) -> String { + format!("lucisv lost track of the declaration of `{name}`, so it made no edits.") +} + +fn lost(what: &str) -> String { + format!("lucisv could not name one of the files it edited for {what}.") +} diff --git a/crates/vlog_refactor/src/extract/region.rs b/crates/vlog_refactor/src/extract/region.rs new file mode 100644 index 0000000..1cbff27 --- /dev/null +++ b/crates/vlog_refactor/src/extract/region.rs @@ -0,0 +1,209 @@ +//! What the selection covers: the module it is written in, the run of whole +//! module items it spans, and the bytes the extraction will delete. +//! +//! Nothing here reads the symbol table — this is the *shape* half of the +//! refusal list, answered from the tree and the text alone: the selection has +//! to cover whole items, and the items it covers have to be ones lucisv can +//! move without changing what they mean where they land. + +use vlog_parser::ast::{Item, ItemKind, Module, SourceFile}; +use vlog_parser::span::TextRange; + +/// The selection, resolved. +pub(super) struct Region<'t> { + /// The module the selection is written in. + pub(super) module: &'t Module, + /// Where that module is written, `module` keyword to `endmodule`. + pub(super) module_span: TextRange, + /// The items the selection covers, in source order. + pub(super) items: Vec<&'t Item>, + /// The bytes the extraction deletes from the module's file: the covered + /// items and whatever of their own comments the selection covers too. + pub(super) span: TextRange, + /// The whitespace the region's first line begins with — what the + /// instantiation written in its place is laid out against. + pub(super) indent: String, +} + +impl<'t> Region<'t> { + /// Read the selection, or say why lucisv will not extract it. + pub(super) fn read( + tree: &'t SourceFile, + text: &str, + selection: TextRange, + ) -> Result, String> { + let (module, module_span) = + module_at(&tree.items, selection).ok_or_else(|| NO_MODULE.to_string())?; + extractable(module)?; + // A cursor is a selection of one item: an editor sends the caret's + // own empty range when nothing is selected, and "extract the thing I + // am standing on" is what the user means by it. + let selection = match selection.is_empty() { + false => selection, + true => module + .items + .iter() + .map(|item| item.span) + .find(|span| span.contains(selection.start) || span.end == selection.start) + .ok_or_else(|| EMPTY.to_string())?, + }; + let mut items: Vec<&Item> = Vec::new(); + let mut span: Option = None; + for item in &module.items { + let extent = extent(item, selection); + if !overlaps(extent, selection) { + continue; + } + if extent.start < selection.start || selection.end < extent.end { + return Err(PARTIAL.to_string()); + } + span = Some(match span { + None => extent, + Some(so_far) => TextRange::new(so_far.start, extent.end), + }); + items.push(item); + } + let Some(span) = span else { return Err(EMPTY.to_string()) }; + for item in &items { + movable(item)?; + } + Ok(Region { module, module_span, items, span, indent: indent_at(text, span.start) }) + } + + /// The module's name. + pub(super) fn module_name(&self) -> &str { + &self.module.name + } +} + +/// The `module`, `interface` or `program` whose body covers the whole +/// selection — the parser writes all three as one node, and [`extractable`] is +/// what says only the first is one lucisv extracts out of. +fn module_at(items: &[Item], selection: TextRange) -> Option<(&Module, TextRange)> { + for item in items { + let ItemKind::Module(module) = &item.kind else { continue }; + if !item.span.contains(selection.start) { + continue; + } + if selection.end > item.span.end { + return None; + } + return Some((module, item.span)); + } + None +} + +/// Only a `module` is a thing lucisv extracts out of. +/// +/// The parser gives a `module`, an `interface` and a `program` one node — +/// their headers and bodies are the same grammar (IEEE 1800 §25.3) — and +/// [`Module::kw`] is the only thing that says which was written. Extracting is +/// a dataflow question about a boundary, and neither of the other two has the +/// boundary this rule assumes: an `interface`'s signals *are* its surface, +/// named by whoever instantiates it and driven from anywhere, so "what does +/// this region drive" does not answer what a port should be; a `program`'s +/// items are testbench code whose meaning depends on when they run. +fn extractable(module: &Module) -> Result<(), String> { + match module.kw.as_str() { + "module" | "macromodule" => Ok(()), + "interface" => Err(INTERFACE.to_string()), + "program" => Err(PROGRAM.to_string()), + kw => Err(format!( + "the selection is inside a `{kw}`, and lucisv extracts module items out of a `module`, so it made no edits." + )), + } +} + +/// The bytes one item owns for the purpose of the selection: the item itself, +/// plus every comment and attribute of its own that the selection also covers. +/// +/// A comment the user left *outside* the selection stays where it is, which is +/// what makes a selection that starts on the item's own line do the obvious +/// thing and one that starts a line earlier take the note with it. +fn extent(item: &Item, selection: TextRange) -> TextRange { + let mut spans = vec![item.span]; + spans.extend(item.meta.leading.iter().map(|c| c.span)); + spans.extend(item.meta.before_sep.iter().map(|c| c.span)); + spans.extend(item.meta.trailing.iter().map(|c| c.span)); + spans.extend(item.meta.attrs.iter().map(|a| a.span)); + let mut out = item.span; + for span in spans { + if span.start < selection.start || selection.end < span.end { + continue; + } + out = TextRange::new(out.start.min(span.start), out.end.max(span.end)); + } + out +} + +fn overlaps(a: TextRange, b: TextRange) -> bool { + a.start < b.end && b.start < a.end +} + +/// The item kinds lucisv will not carry into another module, each with the +/// sentence saying why. +fn movable(item: &Item) -> Result<(), String> { + match &item.kind { + ItemKind::PortDecl(_) => Err(kind_refusal("a port declaration")), + ItemKind::ParamDecl(decl) => Err(kind_refusal(match decl.kw.as_str() { + "localparam" => "a `localparam` declaration", + _ => "a `parameter` declaration", + })), + ItemKind::Genvar(_) => Err(kind_refusal("a `genvar` declaration")), + ItemKind::Bind(_) => Err(kind_refusal("a `bind` directive")), + ItemKind::Initial(_) => Err( + "the selection holds an `initial` block; that is testbench code whose meaning depends on when it runs, and lucisv does not move one into another module this round." + .to_string(), + ), + ItemKind::Final(_) => Err( + "the selection holds a `final` block; that is testbench code whose meaning depends on when it runs, and lucisv does not move one into another module this round." + .to_string(), + ), + ItemKind::MacroItem(_) => Err( + "the selection holds a macro invocation, and lucisv does not expand macros, so it cannot tell what would move with it." + .to_string(), + ), + ItemKind::Directive(_) => Err( + "the selection holds a compiler directive, and lucisv does not evaluate one, so it cannot tell what the selection means in another module." + .to_string(), + ), + ItemKind::Verbatim(_) => Err( + "the selection holds a block lucisv keeps verbatim (an assertion, a `property`, a `sequence`, a `constraint` or a `covergroup` body it could not read), so it cannot tell which names cross the boundary." + .to_string(), + ), + ItemKind::Error(_) => Err( + "part of the selection did not parse, so lucisv cannot tell what it would be moving." + .to_string(), + ), + ItemKind::Module(_) | ItemKind::Package { .. } | ItemKind::Class(_) => { + Err(kind_refusal("a declaration of its own")) + } + _ => Ok(()), + } +} + +fn kind_refusal(what: &str) -> String { + format!( + "the selection holds {what}, which belongs to the module that wrote it; lucisv does not move one into a new module." + ) +} + +/// The whitespace the line holding `at` begins with. +fn indent_at(text: &str, at: u32) -> String { + let start = text.get(..at as usize).and_then(|head| head.rfind('\n')).map_or(0, |n| n + 1); + text.get(start..at as usize) + .unwrap_or("") + .chars() + .take_while(|c| *c == ' ' || *c == '\t') + .collect() +} + +const NO_MODULE: &str = + "the selection is not inside one module's body, so there is nothing for lucisv to extract from."; +const PARTIAL: &str = + "the selection cuts an item in half; lucisv extracts whole module items, so select from the start of the first one to the end of the last."; +const EMPTY: &str = "the selection covers no module item, so there is nothing to extract."; +const INTERFACE: &str = + "the selection is inside an `interface`, whose signals are its surface — every one of them is driven and read by whatever instantiates it — so there is no boundary for lucisv to infer ports across; lucisv extracts out of a `module`."; +const PROGRAM: &str = + "the selection is inside a `program`, whose items are testbench code whose meaning depends on when it runs; lucisv extracts out of a `module`."; diff --git a/crates/vlog_refactor/src/extract/render.rs b/crates/vlog_refactor/src/extract/render.rs new file mode 100644 index 0000000..265440d --- /dev/null +++ b/crates/vlog_refactor/src/extract/render.rs @@ -0,0 +1,384 @@ +//! Writing the new module, and the instantiation that stands where its items +//! used to be. +//! +//! Two rules govern everything here. A **port's type is the declaration's own +//! text**, reassembled from the tree in the order `vlog_formatter`'s ANSI port +//! printer writes it (direction, net, type, signing, packed dimensions, name), +//! so what lucisv writes is what the formatter would; anything the tree says is +//! not a plain name-signing-dimensions type — an anonymous aggregate, a +//! parameterized reference, a virtual interface, an unpacked dimension — is +//! refused rather than approximated. And the **instantiation is rendered from +//! the new module's own text**, through +//! [`instantiation_plan`](crate::instantiate::instantiation_plan), so the two +//! halves of the edit cannot disagree about what `N`'s ports are. + +use vlog_parser::ast::{ + AnsiPort, DataDecl, DataType, Declarator, Dim, ItemKind, ListElem, Module, ParamDecl, + ParamPort, PortDecl, PortList, +}; +use vlog_parser::span::TextRange; + +use crate::instantiate::{instantiation_plan, Layout}; + +/// Where a name that crosses the boundary is declared in the module. +pub(super) enum Site<'t> { + /// An ANSI port of the header. + Ansi(&'t AnsiPort), + /// A name-only header port, with the body declarations that describe it. + NonAnsi(&'t PortDecl, &'t Declarator, Option<(&'t DataDecl, &'t Declarator)>), + /// A net or variable declared in the body. + Data(&'t DataDecl, &'t Declarator), + /// A parameter or localparam declared in the body. + Param(&'t ParamDecl, &'t Declarator), + /// A parameter declared in the header's `#( ... )`. + ParamPort(&'t ParamPort), +} + +/// Every declaration of the module that a crossing name could name. +pub(super) fn site_of<'t>(module: &'t Module, name: &str) -> Option> { + if let PortList::Ansi(ports) = &module.ports { + if let Some(port) = ports.iter().filter_map(ListElem::ok).find(|p| p.name == name) { + return Some(Site::Ansi(port)); + } + } + if let Some(params) = &module.param_ports { + if let Some(param) = params.iter().filter_map(ListElem::ok).find(|p| p.name == name) { + return Some(Site::ParamPort(param)); + } + } + let mut port: Option<(&PortDecl, &Declarator)> = None; + let mut data: Option<(&DataDecl, &Declarator)> = None; + for item in &module.items { + match &item.kind { + ItemKind::PortDecl(decl) => { + if let Some(d) = decl.declarators.iter().find(|d| d.name == name) { + port = Some((decl, d)); + } + } + ItemKind::DataDecl(decl) => { + if let Some(d) = decl.declarators.iter().find(|d| d.name == name) { + data = Some((decl, d)); + } + } + ItemKind::ParamDecl(decl) => { + if let Some(d) = decl.declarators.iter().find(|d| d.name == name) { + return Some(Site::Param(decl, d)); + } + } + _ => {} + } + } + match (port, data) { + (Some((decl, declarator)), other) => Some(Site::NonAnsi(decl, declarator, other)), + (None, Some((decl, declarator))) => Some(Site::Data(decl, declarator)), + (None, None) => None, + } +} + +/// One port of the new module, ready to be written. +pub(super) struct Port { + pub(super) name: String, + /// `input logic [7:0] `, the name's own text excluded. + pub(super) prefix: String, + /// Every identifier that prefix spells — the direction and the type + /// keywords among them. A port whose width is `[N-1:0]` names `N`, and + /// `N` has to cross the boundary with it or the new module names nothing. + pub(super) names: Vec, +} + +/// One parameter of the new module. +pub(super) struct Param { + pub(super) name: String, + /// `parameter int `, the name's own text excluded. + pub(super) prefix: String, + /// The default as `M` writes it, or an empty string when it writes none. + pub(super) default: String, + /// Every identifier its type and its default name, for the closure that + /// carries the parameters one parameter depends on across with it. + pub(super) names: Vec, +} + +/// The declaration of a crossing signal, written as an ANSI port of the new +/// module. +pub(super) fn port( + text: &str, + module: &str, + name: &str, + site: &Site<'_>, + dir: &str, +) -> Result { + let (net, ty, unpacked) = match site { + Site::Ansi(port) => (port.net.as_deref(), &port.ty, port.unpacked.as_slice()), + Site::NonAnsi(decl, declarator, var) => { + let (net, ty) = match var { + Some((data, _)) if decl.net.is_none() && decl.ty.name.is_empty() => { + (data.net.as_deref().or(decl.net.as_deref()), &data.ty) + } + _ => (decl.net.as_deref(), &decl.ty), + }; + if let Some((data, other)) = var { + if !data.qualifiers.is_empty() { + return Err(qualified(module, name)); + } + if !other.unpacked.is_empty() { + return Err(unpacked_refusal(module, name)); + } + } + (net, ty, declarator.unpacked.as_slice()) + } + Site::Data(decl, declarator) => { + if !decl.qualifiers.is_empty() { + return Err(qualified(module, name)); + } + if decl.delay.is_some() { + return Err(delayed(module, name)); + } + (decl.net.as_deref(), &decl.ty, declarator.unpacked.as_slice()) + } + Site::Param(..) | Site::ParamPort(_) => return Err(lost(name)), + }; + if !unpacked.is_empty() { + return Err(unpacked_refusal(module, name)); + } + let ty = type_text(text, module, name, ty)?; + let mut prefix = String::new(); + let mut word = |part: &str| { + prefix.push_str(part); + prefix.push(' '); + }; + word(dir); + if let Some(net) = net { + word(net); + } + if !ty.is_empty() { + word(&ty); + } + let names = words(&prefix); + Ok(Port { name: name.to_string(), prefix, names }) +} + +/// The declaration of a crossing parameter, written as a parameter of the new +/// module. +pub(super) fn param( + text: &str, + module: &str, + name: &str, + site: &Site<'_>, +) -> Result { + let (is_type, ty, default) = match site { + Site::Param(decl, declarator) => { + (decl.is_type, &decl.ty, declarator.init.as_ref().map(|e| e.span)) + } + Site::ParamPort(param) => { + (param.is_type, ¶m.ty, param.default.as_ref().map(|e| e.span)) + } + _ => return Err(lost(name)), + }; + if is_type { + return Err(format!( + "`{module}`'s `{name}` is a type parameter, and lucisv does not carry one into a new module this round." + )); + } + let ty = type_text(text, module, name, ty)?; + let mut prefix = String::from("parameter "); + if !ty.is_empty() { + prefix.push_str(&ty); + prefix.push(' '); + } + let default = default.map(|span| slice(text, span).trim().to_string()).unwrap_or_default(); + if default.contains('\n') { + return Err(format!( + "`{module}` writes `{name}`'s default across several lines, and lucisv does not re-flow one into a new module's header." + )); + } + let mut names = words(&prefix); + names.extend(words(&default)); + Ok(Param { name: name.to_string(), prefix, default, names }) +} + +/// Everything a declaration writes between the direction and the name, as the +/// source spells it: `logic [7:0]`, `my_pkg::word_t`, `signed [31:0]`. +fn type_text(text: &str, module: &str, name: &str, ty: &DataType) -> Result { + if ty.virt.is_some() || ty.extra.is_some() { + return 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)." + )); + } + let mut out = String::new(); + for part in [ty.name.as_str(), ty.signing.as_deref().unwrap_or("")] { + if part.is_empty() { + continue; + } + if !out.is_empty() { + out.push(' '); + } + out.push_str(part); + } + let packed = dims(text, &ty.packed); + if !packed.is_empty() { + if !out.is_empty() { + out.push(' '); + } + out.push_str(&packed); + } + Ok(out) +} + +fn dims(text: &str, list: &[Dim]) -> String { + list.iter().map(|dim| slice(text, dim.span)).collect() +} + +fn slice(text: &str, span: TextRange) -> &str { + text.get(span.start as usize..span.end as usize).unwrap_or("") +} + +/// Every whole word of an expression's text — what a parameter default may +/// depend on. +fn words(text: &str) -> Vec { + let mut out: Vec = Vec::new(); + let bytes = text.as_bytes(); + let mut i = 0usize; + while i < bytes.len() { + if !is_word_byte(bytes[i]) { + i += 1; + continue; + } + let start = i; + while i < bytes.len() && is_word_byte(bytes[i]) { + i += 1; + } + let leading_digit = bytes[start].is_ascii_digit(); + let after_tick = start > 0 && bytes[start - 1] == b'\''; + if !leading_digit && !after_tick { + if let Some(word) = text.get(start..i) { + out.push(word.to_string()); + } + } + } + out +} + +fn is_word_byte(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$' +} + +// ---------------------------------------------------------------------- +// the two texts +// ---------------------------------------------------------------------- + +/// The whole new module: header, the imports it needs, and the selection's own +/// bytes, verbatim. +/// +/// Verbatim is the point. The items are module items in `M` and module items +/// in `N`, at the same nesting depth, so the source's own indentation is +/// already right — and every comment, every attribute and every string travels +/// byte for byte, which is what lets the splice verifier count them. +pub(super) fn new_module( + name: &str, + imports: &[String], + params: &[Param], + ports: &[Port], + body: &str, +) -> String { + let mut out = format!("module {name}"); + for path in imports { + out.push_str("\n import "); + out.push_str(path); + out.push(';'); + } + // A header import is written on its own line, which is where the formatter + // puts one; the list after it then starts a line of its own rather than + // continuing with a space. + let sep = match imports.is_empty() { + true => " ", + false => "\n", + }; + if !params.is_empty() { + out.push_str(sep); + out.push_str("#(\n"); + for (i, param) in params.iter().enumerate() { + out.push_str(" "); + out.push_str(¶m.prefix); + out.push_str(¶m.name); + if !param.default.is_empty() { + out.push_str(" = "); + out.push_str(¶m.default); + } + out.push_str(if i + 1 < params.len() { ",\n" } else { "\n" }); + } + out.push(')'); + } + let sep = match params.is_empty() { + true => sep, + false => " ", + }; + match ports.is_empty() { + true => { + out.push_str(sep); + out.push_str("();\n"); + } + false => { + out.push_str(sep); + out.push_str("(\n"); + for (i, port) in ports.iter().enumerate() { + out.push_str(" "); + out.push_str(&port.prefix); + out.push_str(&port.name); + out.push_str(if i + 1 < ports.len() { ",\n" } else { "\n" }); + } + out.push_str(");\n"); + } + } + out.push_str(body); + if !body.ends_with('\n') { + out.push('\n'); + } + out.push_str("endmodule\n"); + out +} + +/// The instantiation that replaces the selection, read back out of the new +/// module's own text. +/// +/// Every port connects to the signal of the same name — which is what the +/// extraction just made true — and every parameter to the parameter of the +/// same name. +pub(super) fn instantiation(name: &str, module_text: &str, indent: &str) -> Result { + let mut plan = instantiation_plan(name, module_text, None)?; + for port in &mut plan.ports { + port.auto_connect = true; + } + let params = plan.params.len(); + let names: Vec = plan.params.iter().map(|param| param.name.clone()).collect(); + let layout = Layout { base: indent.to_string(), step: " ".to_string() }; + Ok(plan.render_with(&layout, &mut |n, default| match n <= params { + true => names.get(n - 1).cloned().unwrap_or_default(), + false => default.to_string(), + })) +} + +// ---------------------------------------------------------------------- +// sentences +// ---------------------------------------------------------------------- + +fn unpacked_refusal(module: &str, name: &str) -> String { + format!( + "`{name}` crosses the selection's boundary and `{module}` declares it with an unpacked dimension; lucisv does not turn one into a port this round." + ) +} + +fn qualified(module: &str, name: &str) -> String { + format!( + "`{module}` declares `{name}` with a qualifier (`var`, `const`, `automatic`), and lucisv does not move a qualifier into a port list." + ) +} + +fn delayed(module: &str, name: &str) -> String { + format!( + "`{module}` declares `{name}` with a net delay, and lucisv does not move a delay into a port list." + ) +} + +fn lost(name: &str) -> String { + format!("lucisv lost track of the declaration of `{name}`, so it made no edits.") +} diff --git a/crates/vlog_refactor/src/imports.rs b/crates/vlog_refactor/src/imports.rs index 9101edd..5f92bb6 100644 --- a/crates/vlog_refactor/src/imports.rs +++ b/crates/vlog_refactor/src/imports.rs @@ -161,7 +161,8 @@ fn organize( let plan = vec![(i, edits)]; check::verify_splice(&mut scope, &plan, "", what)?; let Some((_, edits)) = plan.into_iter().next() else { return Err(not_in_scope(file)) }; - let edit = RefactorEdit { edits: vec![(file.to_path_buf(), edits)], warnings }; + let edit = + RefactorEdit { edits: vec![(file.to_path_buf(), edits)], warnings, created: Vec::new() }; Ok((edit, removed, sorted)) } diff --git a/crates/vlog_refactor/src/lib.rs b/crates/vlog_refactor/src/lib.rs index 01c91f4..3a53540 100644 --- a/crates/vlog_refactor/src/lib.rs +++ b/crates/vlog_refactor/src/lib.rs @@ -28,6 +28,7 @@ //! spans instead of edits — see `docs/features/references-nav/README.md`. mod check; +mod extract; mod imports; mod instantiate; mod ports; @@ -35,6 +36,7 @@ mod references; mod rename; mod scope; +pub use extract::{extract_module, extract_site, extract_title, ExtractSite, Home}; pub use imports::{ imported_packages, organize_counts, organize_imports, organize_title, unused_imports, }; @@ -80,6 +82,13 @@ pub struct RefactorEdit { /// for (macro bodies, `endmodule :` labels). Informational only — a /// result with warnings is still safe to apply. pub warnings: Vec, + /// Files the refactoring **creates**. Each one also appears in `edits`, + /// with exactly one insertion at offset 0 writing the whole file, so a + /// caller that cannot create files can ignore this and get nothing; a + /// caller that can (LSP's `CreateFile`) creates each of these first and + /// then applies the edits as it applies every other one. Empty for every + /// refactoring but [`extract_module`]. + pub created: Vec, } impl RefactorEdit { diff --git a/crates/vlog_refactor/src/ports/mod.rs b/crates/vlog_refactor/src/ports/mod.rs index 614bc78..c985509 100644 --- a/crates/vlog_refactor/src/ports/mod.rs +++ b/crates/vlog_refactor/src/ports/mod.rs @@ -428,7 +428,7 @@ fn finish( edits.push((path.to_path_buf(), file_edits)); } edits.sort_by(|a, b| a.0.cmp(&b.0)); - Ok((RefactorEdit { edits, warnings: plan.warnings }, plan.sites)) + Ok((RefactorEdit { edits, warnings: plan.warnings, created: Vec::new() }, plan.sites)) } /// What one file says about a module's signature: the module's own declared diff --git a/crates/vlog_refactor/src/rename/mod.rs b/crates/vlog_refactor/src/rename/mod.rs index b25621a..ee97769 100644 --- a/crates/vlog_refactor/src/rename/mod.rs +++ b/crates/vlog_refactor/src/rename/mod.rs @@ -171,7 +171,7 @@ pub fn rename( .filter_map(|(i, edits)| Some((scope.path(i)?.to_path_buf(), edits))) .collect(); out.sort_by(|a, b| a.0.cmp(&b.0)); - Ok(RefactorEdit { edits: out, warnings }) + Ok(RefactorEdit { edits: out, warnings, created: Vec::new() }) } /// A new name must lex as exactly one identifier and must not be a keyword. diff --git a/crates/vlog_refactor/tests/corpus.rs b/crates/vlog_refactor/tests/corpus.rs index 7f1450a..43e0a1e 100644 --- a/crates/vlog_refactor/tests/corpus.rs +++ b/crates/vlog_refactor/tests/corpus.rs @@ -12,8 +12,8 @@ use std::time::Instant; use vlog_parser::ast::{Item, ItemKind, ListElem, PortList}; use vlog_refactor::{ - add_port, convert_to_ansi, expand_wildcard, instantiation_plan, module_definition, - port_actions, prepare_rename, rename, Layout, ModuleRef, + add_port, convert_to_ansi, expand_wildcard, extract_module, instantiation_plan, + module_definition, port_actions, prepare_rename, rename, Home, Layout, ModuleRef, }; use vlog_semantic::WorkspaceIndex; @@ -796,3 +796,155 @@ fn refusal_kind(said: &str) -> &'static str { ]; KINDS.iter().find(|(needle, _)| said.contains(needle)).map_or("other", |(_, kind)| *kind) } + +// ---------------------------------------------------------------------- +// extracting a module out of real RTL (TODO §53.1) +// ---------------------------------------------------------------------- + +/// Where the extraction trial reads its design from. `corpus/` by default; +/// `LUCISV_EXTRACT_ROOT` points it at a **copy** of another tree — which is how +/// the opentitan trial is run without touching that checkout. +fn extract_root() -> Option> { + let root = match std::env::var("LUCISV_EXTRACT_ROOT") { + Ok(path) => PathBuf::from(path), + Err(_) => Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus"), + }; + if !root.is_dir() { + eprintln!("{} not checked out — skipping", root.display()); + return None; + } + let mut files = Vec::new(); + collect(&root, &mut files); + files.sort(); + Some(files) +} + +/// The first `always` block or continuous assignment of each module, as a +/// selection an extraction could be asked about. +fn regions(text: &str) -> Vec<(String, u32, u32)> { + let (tree, diagnostics) = vlog_parser::parse_source_tolerant(text); + if !diagnostics.is_empty() { + return Vec::new(); + } + let mut out = Vec::new(); + for item in &tree.items { + let ItemKind::Module(module) = &item.kind else { continue }; + let found = module.items.iter().find(|item| { + matches!(item.kind, ItemKind::Always { .. } | ItemKind::ContAssign(_)) + && item.meta.leading.is_empty() + }); + if let Some(region) = found { + out.push((module.name.clone(), region.span.start, region.span.end)); + } + } + out +} + +/// How many of a design's names fail to resolve. The census the trial holds +/// fixed: an extraction moves items and writes a header, so the number of +/// names nothing binds may not grow. +fn unresolved_over(sources: &[(PathBuf, String)]) -> usize { + let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str()))); + let mut out = 0usize; + for (_, text) in sources { + let (tree, _) = vlog_parser::parse_source_tolerant(text); + let semantics = vlog_semantic::analyze(&tree, text); + let external = vlog_semantic::resolve_external(&semantics, &index); + for (n, reference) in semantics.references().iter().enumerate() { + if reference.resolved().is_some() { + continue; + } + let id = vlog_semantic::ReferenceId(n as u32); + if !matches!(external.get(id), Some(vlog_semantic::ExternalTarget::Resolved(_))) { + out += 1; + } + } + } + out +} + +#[test] +fn five_regions_of_real_rtl_extract_into_modules_that_parse_format_and_converge() { + let Some(files) = extract_root() else { return }; + let sources = read(&files); + assert!(!sources.is_empty(), "the tree exists but holds no Verilog"); + let config = vlog_formatter::Config::default(); + let before = unresolved_over(&sources); + + let started = Instant::now(); + let mut done: Vec = Vec::new(); + let mut refusals = 0usize; + 'files: for (path, text) in &sources { + for (module, start, end) in regions(text) { + if done.len() == 5 { + break 'files; + } + let name = format!("{module}_lucisv_extracted"); + let edit = match extract_module(&sources, path, start, end, &name, Home::NewFile) { + Ok(edit) => edit, + // Printed, not only counted: which regions the trial refuses + // and why is the other half of a reproducible run (2026-09-06 + // rework — the opentitan numbers in the feature README are + // this list). + Err(said) => { + refusals += 1; + println!(" refused {} `{module}`: {said}", path.display()); + continue; + } + }; + + // The two halves, as the editor would write them. + let mut after: Vec<(PathBuf, String)> = sources.clone(); + for created in &edit.created { + after.push((created.clone(), String::new())); + } + for (file, edits) in &edit.edits { + let Some(slot) = after.iter_mut().find(|(held, _)| held == file) else { + panic!("{} edits {} which is not in scope", name, file.display()) + }; + let mut out = slot.1.clone(); + for one in edits.iter().rev() { + out.replace_range( + one.range.start as usize..one.range.end as usize, + &one.new_text, + ); + } + slot.1 = out; + } + + // Both files parse, format, and formatting them again is a no-op. + for (file, edits) in &edit.edits { + let text = &after.iter().find(|(held, _)| held == file).expect("edited").1; + let (_, diagnostics) = vlog_parser::parse_source_tolerant(text); + assert!( + diagnostics.is_empty(), + "{name}: {} no longer parses: {diagnostics:?}\n{text}", + file.display() + ); + let once = vlog_formatter::format_source(text, &config).unwrap_or_else(|e| { + panic!("{name}: the formatter refuses {}: {e}", file.display()) + }); + let twice = vlog_formatter::format_source(&once, &config).expect("formats again"); + assert_eq!(once, twice, "{name}: {} does not converge", file.display()); + let _ = edits; + } + + // The census over the whole design, the two files together. + let now = unresolved_over(&after); + assert!(now <= before, "{name}: {} names went unresolved, up from {before}", now); + // Printed, not only asserted: the trial's numbers are what the + // feature README records, and a census that merely *held* is the + // evidence the extraction was honest (2026-09-06 rework). + println!(" {name} in {}: census {before} -> {now}", path.display()); + done.push(name); + } + } + println!( + "extract over {} files: {} regions extracted, {} refused, in {:.2}s", + sources.len(), + done.len(), + refusals, + started.elapsed().as_secs_f64() + ); + assert_eq!(done.len(), 5, "five real regions must extract: {done:?}"); +} diff --git a/crates/vlog_refactor/tests/extract.rs b/crates/vlog_refactor/tests/extract.rs new file mode 100644 index 0000000..3978d4f --- /dev/null +++ b/crates/vlog_refactor/tests/extract.rs @@ -0,0 +1,736 @@ +//! Extracting a selection of whole module items into a module of its own — +//! TODO §53.1. +//! +//! Three groups. What the extraction *writes* (a combinational region, a +//! sequential one, one carrying a parameter and an import, the two homes the +//! new module can have); every **refusal**, one test per sentence; and the +//! acceptance checks that say the result is real Verilog — it parses, the +//! formatter accepts it, formatting it twice changes nothing, and the two +//! files together name every signal the one file named. + +use std::path::{Path, PathBuf}; + +use vlog_refactor::{extract_module, extract_site, Home, RefactorEdit}; + +const M: &str = "/rtl/m.sv"; + +fn files(text: &str) -> Vec<(PathBuf, String)> { + vec![(PathBuf::from(M), text.to_string())] +} + +fn workspace(entries: &[(&str, &str)]) -> Vec<(PathBuf, String)> { + entries.iter().map(|(p, t)| (PathBuf::from(*p), t.to_string())).collect() +} + +/// The byte range of `needle` in `text`. +fn at(text: &str, needle: &str) -> (u32, u32) { + let start = text.find(needle).expect("needle") as u32; + (start, start + needle.len() as u32) +} + +/// One file's text after the edit. A file the extraction creates starts empty. +fn applied(text: &str, edit: &RefactorEdit, path: &str) -> String { + let created = edit.created.iter().any(|created| created == Path::new(path)); + let mut out = match created { + true => String::new(), + false => text.to_string(), + }; + for one in edit.edits_for(Path::new(path)).iter().rev() { + out.replace_range(one.range.start as usize..one.range.end as usize, &one.new_text); + } + out +} + +/// Extract `needle` out of `text` into `name`, into a file of its own. +fn extract(text: &str, needle: &str, name: &str) -> Result { + let (start, end) = at(text, needle); + extract_module(&files(text), Path::new(M), start, end, name, Home::NewFile) +} + +/// The two halves of an extraction, as the editor would have them. +fn halves(text: &str, needle: &str, name: &str) -> (String, String) { + let edit = extract(text, needle, name).expect("extracts"); + let new = format!("/rtl/{name}.sv"); + (applied(text, &edit, M), applied(text, &edit, &new)) +} + +/// Every result has to be Verilog the formatter accepts and leaves alone the +/// second time — the acceptance bar every refactoring in this crate meets. +fn accepted(label: &str, text: &str) { + let config = vlog_formatter::Config::default(); + let once = vlog_formatter::format_source(text, &config) + .unwrap_or_else(|e| panic!("the formatter refuses {label}: {e}\n{text}")); + let twice = vlog_formatter::format_source(&once, &config).expect("formats again"); + assert_eq!(once, twice, "formatting {label} does not converge"); +} + +// ---------------------------------------------------------------------- +// what it writes +// ---------------------------------------------------------------------- + +const COMB: &str = "\ +module m ( + input logic [7:0] a, + input logic [7:0] b, + output logic [7:0] q +); + logic [7:0] s; + assign s = a + b; // the sum + assign q = s ^ 8'hFF; +endmodule +"; + +#[test] +fn a_combinational_region_reads_two_names_and_drives_one() { + let (old, new) = halves(COMB, "assign s = a + b; // the sum", "sum"); + assert_eq!( + new, + "\ +module sum ( + input logic [7:0] a, + input logic [7:0] b, + output logic [7:0] s +); + assign s = a + b; // the sum +endmodule +" + ); + assert!(old.contains("sum u_sum (\n .a(a),\n .b(b),\n .s(s)\n );"), "{old}"); + // The comment travelled: it is in the new file and gone from the old one. + assert!(!old.contains("// the sum"), "{old}"); + accepted("the new module", &new); + accepted("what is left", &old); +} + +const SEQ: &str = "\ +module m ( + input logic clk, + input logic rst_n, + input logic [7:0] d, + output logic [7:0] q +); + logic [7:0] r; + always_ff @(posedge clk or negedge rst_n) begin + if (!rst_n) r <= '0; + else r <= d; + end + assign q = r; +endmodule +"; + +#[test] +fn a_sequential_region_makes_the_clock_an_input_and_the_register_an_output() { + let start = SEQ.find("always_ff").expect("always") as u32; + let end = SEQ.find(" end\n").expect("end") as u32 + 5; + let edit = extract_module(&files(SEQ), Path::new(M), start, end, "reg_stage", Home::NewFile) + .expect("extracts"); + let new = applied(SEQ, &edit, "/rtl/reg_stage.sv"); + assert!(new.contains("input logic clk,"), "{new}"); + assert!(new.contains("input logic rst_n,"), "{new}"); + assert!(new.contains("input logic [7:0] d,"), "{new}"); + assert!(new.contains("output logic [7:0] r"), "{new}"); + accepted("the sequential module", &new); + accepted("what is left", &applied(SEQ, &edit, M)); +} + +const PARAM: &str = "\ +package w_pkg; + typedef logic [7:0] word_t; +endpackage + +module m #( + parameter int W = 8 +) ( + input word_t a, + output word_t q +); + import w_pkg::*; + localparam int MASK = W - 1; + word_t t; + assign t = a & word_t'(MASK); + assign q = t; +endmodule +"; + +#[test] +fn a_region_using_a_parameter_and_an_import_carries_both() { + let (old, new) = halves(PARAM, "assign t = a & word_t'(MASK);", "masker"); + // The `localparam` the selection reads becomes a parameter of the new + // module, and so does the parameter *its own default* names. + assert!(new.contains("parameter int W = 8,"), "{new}"); + assert!(new.contains("parameter int MASK = W - 1"), "{new}"); + assert!(new.contains("import w_pkg::*;"), "{new}"); + assert!(new.contains("input word_t a,"), "{new}"); + assert!(new.contains("output word_t t"), "{new}"); + assert!(old.contains(".W(W),"), "{old}"); + assert!(old.contains(".MASK(MASK)"), "{old}"); + accepted("the parameterized module", &new); + accepted("what is left", &old); +} + +#[test] +fn a_parameter_a_ports_own_width_names_crosses_with_it() { + // The corpus found this one: `binary_to_gray`'s `N` is read by no + // statement the selection carries — only by the *type* of the port the + // extraction is about to write — so a closure over the region's + // references alone left the new module naming nothing. + let text = "\ +module m #( + parameter int N = -1 +) ( + input logic [N-1:0] a, + output logic [N-1:0] q +); + assign q = a ^ (a >> 1); +endmodule +"; + let (old, new) = halves(text, "assign q = a ^ (a >> 1);", "gray"); + assert!(new.contains("parameter int N = -1"), "{new}"); + assert!(new.contains("input logic [N-1:0] a,"), "{new}"); + assert!(new.contains("output logic [N-1:0] q"), "{new}"); + assert!(old.contains(".N(N)"), "{old}"); + accepted("the new module", &new); + accepted("what is left", &old); +} + +#[test] +fn a_wildcard_import_in_the_header_is_carried_across() { + // The opentitan trial found this one: the binder records a wildcard + // import in a reference's `paths` as `p::*` — the spelling the source + // wrote — not as `p::`, so a judgement matching on the latter + // copied no import at all and the new file named a package's types with + // nothing importing them. + let pkg = "package p;\n typedef logic [1:0] w_t;\n parameter int W = 2;\nendpackage\n"; + let top = "\ +module m import p::*; +( + input logic [W-1:0] a, + output w_t q +); + assign q = w_t'(a); +endmodule +"; + let sources = workspace(&[("/rtl/p.sv", pkg), (M, top)]); + let (start, end) = at(top, "assign q = w_t'(a);"); + let edit = extract_module(&sources, Path::new(M), start, end, "caster", Home::NewFile) + .expect("extracts"); + let new = applied(top, &edit, "/rtl/caster.sv"); + assert!(new.contains("import p::*;"), "{new}"); + assert!(new.contains("input logic [W-1:0] a,"), "{new}"); + assert!(new.contains("output w_t q"), "{new}"); + assert!(edit.warnings.iter().any(|w| w.contains("`p::*`")), "{:?}", edit.warnings); + accepted("the new module", &new); +} + +#[test] +fn a_named_import_is_carried_across_only_when_the_name_it_supplies_is_needed() { + let a = "package a_pkg;\n typedef logic [1:0] a_t;\nendpackage\n"; + let b = "package b_pkg;\n typedef logic [3:0] b_t;\nendpackage\n"; + let top = "\ +module m ( + input logic [1:0] i, + output logic [1:0] o +); + import a_pkg::a_t; + import b_pkg::b_t; + assign o = a_t'(i); +endmodule +"; + let sources = workspace(&[("/rtl/a.sv", a), ("/rtl/b.sv", b), (M, top)]); + let (start, end) = at(top, "assign o = a_t'(i);"); + let edit = extract_module(&sources, Path::new(M), start, end, "caster", Home::NewFile) + .expect("extracts"); + let new = applied(top, &edit, "/rtl/caster.sv"); + assert!(new.contains("import a_pkg::a_t;"), "{new}"); + assert!(!new.contains("b_pkg"), "an import nothing moved needs is not copied: {new}"); + accepted("the new module", &new); +} + +#[test] +fn a_type_declared_in_the_module_that_a_crossing_ports_type_names_is_refused() { + let text = "\ +module m ( + input logic [7:0] i, + output logic [7:0] o +); + typedef logic [7:0] local_t; + local_t mid; + assign mid = i; + assign o = mid; +endmodule +"; + let message = refusal(text, "assign mid = i;"); + assert!(message.contains("`local_t`"), "{message}"); +} + +#[test] +fn a_client_that_cannot_create_files_gets_the_module_below_the_one_it_came_from() { + let (start, end) = at(COMB, "assign s = a + b; // the sum"); + let edit = extract_module(&files(COMB), Path::new(M), start, end, "sum", Home::SameFile) + .expect("extracts"); + assert!(edit.created.is_empty(), "nothing is created"); + assert_eq!(edit.file_count(), 1, "one file is touched"); + let text = applied(COMB, &edit, M); + assert!(text.contains("endmodule\n\nmodule sum ("), "{text}"); + assert!(edit.warnings.iter().any(|w| w.contains("did not say it can create files"))); + accepted("the one-file result", &text); +} + +#[test] +fn the_new_module_is_named_in_the_warnings_with_the_file_it_went_to() { + let edit = extract(COMB, "assign s = a + b; // the sum", "sum").expect("extracts"); + assert_eq!(edit.created, vec![PathBuf::from("/rtl/sum.sv")]); + assert!(edit.warnings.iter().any(|w| w.contains("`sum.sv`")), "{:?}", edit.warnings); + assert!(edit.warnings.iter().any(|w| w.contains("3 ports")), "{:?}", edit.warnings); +} + +#[test] +fn an_instantiation_whose_module_the_index_knows_gives_its_outputs_the_right_direction() { + let sub = "module sub (\n input logic i,\n output logic o\n);\nendmodule\n"; + let top = "\ +module m ( + input logic i, + output logic o +); + logic mid; + sub u_sub (.i(i), .o(mid)); + assign o = mid; +endmodule +"; + let sources = workspace(&[("/rtl/sub.sv", sub), (M, top)]); + let (start, end) = at(top, "sub u_sub (.i(i), .o(mid));"); + let edit = extract_module(&sources, Path::new(M), start, end, "wrap", Home::NewFile) + .expect("extracts"); + let new = applied(top, &edit, "/rtl/wrap.sv"); + assert!(new.contains("input logic i,"), "{new}"); + assert!(new.contains("output logic mid"), "{new}"); + accepted("the wrapper", &new); +} + +// ---------------------------------------------------------------------- +// the refusals +// ---------------------------------------------------------------------- + +/// The sentence an extraction of `needle` refuses with. +fn refusal(text: &str, needle: &str) -> String { + extract(text, needle, "n").expect_err("a refusal") +} + +#[test] +fn half_an_item_is_refused() { + let (start, _) = at(COMB, "assign s = a + b;"); + let edit = extract_module(&files(COMB), Path::new(M), start, start + 8, "n", Home::NewFile); + assert!(edit.expect_err("a refusal").contains("cuts an item in half")); +} + +#[test] +fn a_selection_outside_every_module_is_refused() { + let text = "package p;\n typedef int t;\nendpackage\n"; + let (start, end) = at(text, "typedef int t;"); + let edit = extract_module(&files(text), Path::new(M), start, end, "n", Home::NewFile); + assert!(edit.expect_err("a refusal").contains("not inside one module's body")); +} + +/// The same three items, written as each of the three declarations the parser +/// gives one node to. +const INTERFACE: &str = + "interface bus_if;\n logic [7:0] a;\n logic [7:0] q;\n assign q = a;\nendinterface\n"; +const PROGRAM: &str = "program p;\n logic a;\n logic q;\n assign q = a;\nendprogram\n"; +const MODULE: &str = "module m;\n logic [7:0] a;\n logic [7:0] q;\n assign q = a;\nendmodule\n"; + +#[test] +fn a_selection_inside_an_interface_or_a_program_is_refused() { + // `vlog_parser` writes a `module`, an `interface` and a `program` as one + // `ItemKind::Module`, and only `Module::kw` says which — so the gate has + // to ask. QA's finding V2: without it an `interface` body extracted into a + // module instantiated inside what remained an `interface`, and four names + // in opentitan's `aes_masking_reseed_if.sv` stopped resolving. + let said = refusal(INTERFACE, "assign q = a;"); + assert!(said.contains("inside an `interface`"), "{said}"); + assert!(said.contains("signals are its surface"), "{said}"); + + let said = refusal(PROGRAM, "assign q = a;"); + assert!(said.contains("inside a `program`"), "{said}"); + assert!(said.contains("testbench code"), "{said}"); + + // The same three items written as a module still extract. + assert!(extract(MODULE, "assign q = a;", "n").is_ok(), "a `module` is still extractable"); +} + +#[test] +fn the_action_is_not_offered_inside_an_interface_or_a_program() { + // The cheap gate reads the same `Region`, so the lightbulb never appears + // where the engine would refuse. + for text in [INTERFACE, PROGRAM] { + let (start, end) = at(text, "assign q = a;"); + assert!(extract_site(text, start, end).is_none(), "not offered in: {text}"); + } + let (start, end) = at(MODULE, "assign q = a;"); + assert!(extract_site(MODULE, start, end).is_some(), "and still offered in a module"); +} + +#[test] +fn a_port_a_parameter_a_genvar_and_a_bind_are_each_refused_by_name() { + let non_ansi = "module m (a);\n input a;\n wire b;\n assign b = a;\nendmodule\n"; + assert!(refusal(non_ansi, "input a;").contains("a port declaration")); + + let param = "module m;\n localparam int W = 8;\n wire [W-1:0] x;\nendmodule\n"; + assert!(refusal(param, "localparam int W = 8;").contains("a `localparam` declaration")); + + let genvar = "module m;\n genvar g;\nendmodule\n"; + assert!(refusal(genvar, "genvar g;").contains("a `genvar` declaration")); + + let bind = "module m;\n bind m sub u_s ();\nendmodule\n"; + assert!(refusal(bind, "bind m sub u_s ();").contains("a `bind` directive")); +} + +#[test] +fn a_macro_call_and_a_compiler_directive_are_refused() { + let macro_item = "module m;\n `ASSERT(a, b)\n wire w;\nendmodule\n"; + assert!(refusal(macro_item, "`ASSERT(a, b)").contains("macro invocation")); + + let directive = "module m;\n`ifdef FOO\n`endif\n wire w;\nendmodule\n"; + assert!(refusal(directive, "`ifdef FOO").contains("compiler directive")); +} + +#[test] +fn an_initial_and_a_final_block_are_refused_as_testbench_code() { + let initial = "module m;\n logic x;\n initial x = 1'b0;\nendmodule\n"; + assert!(refusal(initial, "initial x = 1'b0;").contains("`initial` block")); + + let last = "module m;\n logic x;\n final $display(\"%d\", x);\nendmodule\n"; + assert!(refusal(last, "final $display(\"%d\", x);").contains("`final` block")); +} + +#[test] +fn a_name_declared_inside_the_selection_and_used_outside_it_is_refused() { + let text = "\ +module m ( + input logic a, + output logic q +); + wire t; + assign t = a; + assign q = t; +endmodule +"; + // `t`'s declaration is in the selection; `assign q = t;` is not. + let (start, _) = at(text, "wire t;"); + let (_, end) = at(text, "assign t = a;"); + let edit = extract_module(&files(text), Path::new(M), start, end, "n", Home::NewFile); + let message = edit.expect_err("a refusal"); + assert!( + message.contains("move the declaration of `t` out of the selection first"), + "{message}" + ); +} + +#[test] +fn a_name_driven_on_both_sides_of_the_selection_is_refused() { + let text = "\ +module m ( + input logic a, + input logic b, + output logic q +); + always_comb q = a; + always_comb q = b; +endmodule +"; + let message = refusal(text, "always_comb q = a;"); + assert!(message.contains("`q` is driven on both sides of the selection."), "{message}"); +} + +#[test] +fn a_task_or_function_the_selection_calls_from_outside_it_is_refused() { + let text = "\ +module m ( + input logic [7:0] a, + output logic [7:0] q +); + function automatic logic [7:0] twice(input logic [7:0] x); + return x + x; + endfunction + assign q = twice(a); +endmodule +"; + let message = refusal(text, "assign q = twice(a);"); + assert!(message.contains("`twice`"), "{message}"); + assert!(message.contains("a function"), "{message}"); +} + +#[test] +fn a_signal_passed_to_a_routine_inside_the_selection_refuses_rather_than_guesses() { + let text = "\ +module m ( + input logic clk, + output logic [7:0] q +); + always_ff @(posedge clk) begin + $cast(q, 8'h01); + end +endmodule +"; + let message = refusal(text, "always_ff @(posedge clk) begin\n $cast(q, 8'h01);\n end"); + assert!(message.contains("passes `q` to a task or function"), "{message}"); +} + +#[test] +fn a_hierarchical_reference_out_of_the_selection_is_refused() { + let sub = "module sub (\n input logic i\n);\n logic probe;\nendmodule\n"; + let top = "\ +module m ( + input logic i, + output logic o +); + sub u_sub (.i(i)); + assign o = u_sub.probe; +endmodule +"; + let sources = workspace(&[("/rtl/sub.sv", sub), (M, top)]); + let (start, end) = at(top, "assign o = u_sub.probe;"); + let edit = extract_module(&sources, Path::new(M), start, end, "n", Home::NewFile); + let message = edit.expect_err("a refusal"); + assert!(message.contains("through the design hierarchy"), "{message}"); +} + +#[test] +fn a_crossing_name_with_an_unpacked_dimension_is_refused() { + let text = "\ +module m ( + input logic [7:0] a, + output logic [7:0] q +); + logic [7:0] mem [0:3]; + assign q = mem[0] ^ a; +endmodule +"; + let message = refusal(text, "assign q = mem[0] ^ a;"); + assert!(message.contains("unpacked dimension"), "{message}"); +} + +#[test] +fn a_name_the_workspace_already_declares_is_refused() { + let sub = "module taken;\nendmodule\n"; + let sources = workspace(&[("/rtl/lib/taken.sv", sub), (M, COMB)]); + let (start, end) = at(COMB, "assign s = a + b; // the sum"); + let edit = extract_module(&sources, Path::new(M), start, end, "taken", Home::NewFile); + assert!(edit.expect_err("a refusal").contains("already declares `taken`")); +} + +#[test] +fn a_module_declared_twice_is_refused() { + let twin = "module m;\nendmodule\n"; + let sources = workspace(&[("/rtl/twin.sv", twin), (M, COMB)]); + let (start, end) = at(COMB, "assign s = a + b; // the sum"); + let edit = extract_module(&sources, Path::new(M), start, end, "sum", Home::NewFile); + assert!(edit.expect_err("a refusal").contains("declared in more than one indexed file")); +} + +#[test] +fn a_timescale_a_new_file_would_not_inherit_is_refused_and_the_same_file_is_not() { + let text = format!("`timescale 1ns/1ps\n{COMB}"); + let (start, end) = at(&text, "assign s = a + b; // the sum"); + let sources = vec![(PathBuf::from(M), text.clone())]; + let refused = extract_module(&sources, Path::new(M), start, end, "sum", Home::NewFile); + let message = refused.expect_err("a refusal"); + assert!(message.contains("`timescale"), "{message}"); + // The same directive is no obstacle when the module stays in the file. + extract_module(&sources, Path::new(M), start, end, "sum", Home::SameFile) + .expect("the same file inherits it"); +} + +#[test] +fn a_default_nettype_is_refused_the_same_way() { + let text = format!("`default_nettype none\n{COMB}"); + let (start, end) = at(&text, "assign s = a + b; // the sum"); + let sources = vec![(PathBuf::from(M), text.clone())]; + let refused = extract_module(&sources, Path::new(M), start, end, "sum", Home::NewFile); + assert!(refused.expect_err("a refusal").contains("`default_nettype")); +} + +#[test] +fn a_name_that_is_not_an_identifier_is_refused_before_anything_else() { + let (start, end) = at(COMB, "assign s = a + b; // the sum"); + for name in ["", "2fast", "\\odd-name", "with space"] { + let edit = extract_module(&files(COMB), Path::new(M), start, end, name, Home::NewFile); + assert!( + edit.expect_err("a refusal").contains("not a plain SystemVerilog identifier"), + "{name}" + ); + } +} + +#[test] +fn a_positional_instantiation_inside_the_selection_is_refused() { + let sub = "module sub (\n input logic i,\n output logic o\n);\nendmodule\n"; + let top = + "module m (\n input logic i,\n output logic o\n);\n sub u_sub (i, o);\nendmodule\n"; + let sources = workspace(&[("/rtl/sub.sv", sub), (M, top)]); + let (start, end) = at(top, "sub u_sub (i, o);"); + let edit = extract_module(&sources, Path::new(M), start, end, "n", Home::NewFile); + assert!(edit.expect_err("a refusal").contains("by position")); +} + +#[test] +fn a_wildcard_instantiation_inside_the_selection_is_refused() { + let sub = "module sub (\n input logic i,\n output logic o\n);\nendmodule\n"; + let top = "module m (\n input logic i,\n output logic o\n);\n sub u_sub (.*);\nendmodule\n"; + let sources = workspace(&[("/rtl/sub.sv", sub), (M, top)]); + let (start, end) = at(top, "sub u_sub (.*);"); + let edit = extract_module(&sources, Path::new(M), start, end, "n", Home::NewFile); + assert!(edit.expect_err("a refusal").contains("`.*`")); +} + +#[test] +fn an_instantiation_of_a_module_the_index_does_not_know_is_refused() { + let top = "\ +module m ( + input logic i, + output logic o +); + stranger u_s (.i(i), .o(o)); +endmodule +"; + let message = refusal(top, "stranger u_s (.i(i), .o(o));"); + assert!(message.contains("no single indexed declaration"), "{message}"); +} + +#[test] +fn a_name_declared_outside_the_module_in_the_same_file_is_refused_for_a_new_file() { + let text = "\ +typedef logic [7:0] byte_t; + +module m ( + input byte_t a, + output byte_t q +); + byte_t t; + assign t = a; + assign q = t; +endmodule +"; + let message = refusal(text, "assign t = a;"); + assert!(message.contains("declared outside `m` in the same file"), "{message}"); + // The same selection is fine when the module stays in that file. + let (start, end) = at(text, "assign t = a;"); + extract_module(&files(text), Path::new(M), start, end, "n", Home::SameFile) + .expect("the same file sees it"); +} + +#[test] +fn a_selection_that_covers_nothing_is_refused() { + let (start, _) = at(COMB, "module m"); + let edit = extract_module(&files(COMB), Path::new(M), start, start, "n", Home::NewFile); + assert!(edit.expect_err("a refusal").contains("no module item")); +} + +#[test] +fn a_file_that_does_not_parse_is_refused() { + let text = "module m;\n assign = ;\nendmodule\n"; + let edit = extract_module(&files(text), Path::new(M), 0, text.len() as u32, "n", Home::NewFile); + assert!(edit.expect_err("a refusal").contains("does not parse")); +} + +#[test] +fn an_occupied_file_name_is_refused() { + let sources = workspace(&[("/rtl/sum.sv", "// notes\n"), (M, COMB)]); + let (start, end) = at(COMB, "assign s = a + b; // the sum"); + let edit = extract_module(&sources, Path::new(M), start, end, "sum", Home::NewFile); + assert!(edit.expect_err("a refusal").contains("already a `sum.sv`")); +} + +// ---------------------------------------------------------------------- +// the cheap gate +// ---------------------------------------------------------------------- + +#[test] +fn the_gate_names_the_module_and_everything_the_engine_will_read() { + let text = "\ +module m ( + input logic i, + output logic o +); + import p::*; + sub u_sub (.i(i), .o(o)); +endmodule +"; + let (start, end) = at(text, "sub u_sub (.i(i), .o(o));"); + let site = extract_site(text, start, end).expect("a site"); + assert_eq!(site.module, "m"); + assert_eq!(site.default_name, "m_extracted"); + assert_eq!(site.units, vec!["m".to_string(), "sub".to_string(), "p".to_string()]); +} + +#[test] +fn the_gate_is_empty_where_the_engine_would_refuse_for_want_of_an_item() { + assert!(extract_site(COMB, 0, 3).is_none(), "outside every module"); + assert!(extract_site("not verilog at all", 0, 4).is_none(), "an unparsed buffer"); +} + +#[test] +fn a_cursor_with_no_selection_extracts_the_item_it_is_on() { + let at_assign = COMB.find("assign s").expect("assign") as u32 + 3; + let edit = + extract_module(&files(COMB), Path::new(M), at_assign, at_assign, "sum", Home::NewFile) + .expect("extracts"); + let new = applied(COMB, &edit, "/rtl/sum.sv"); + assert!(new.contains("assign s = a + b;"), "{new}"); +} + +// ---------------------------------------------------------------------- +// the census: the design still names what it named +// ---------------------------------------------------------------------- + +#[test] +fn the_two_files_together_name_every_signal_the_one_file_named() { + // The reference census the corpus trials run, in miniature: the names the + // design writes down are the same before and after, because an extraction + // moves items and adds a header, and adds no name that was not there. + let start = SEQ.find("always_ff").expect("always") as u32; + let end = SEQ.find(" end\n").expect("end") as u32 + 5; + let edit = extract_module(&files(SEQ), Path::new(M), start, end, "reg_stage", Home::NewFile) + .expect("extracts"); + let old = applied(SEQ, &edit, M); + let new = applied(SEQ, &edit, "/rtl/reg_stage.sv"); + let before = words(SEQ); + let after: Vec = words(&old).into_iter().chain(words(&new)).collect(); + for name in ["clk", "rst_n", "d", "q", "r"] { + let was = before.iter().filter(|w| *w == name).count(); + let now = after.iter().filter(|w| *w == name).count(); + assert!(now >= was, "`{name}` was named {was} times and is now named {now}"); + } +} + +/// Every identifier-shaped word of a text. +fn words(text: &str) -> Vec { + let mut out = Vec::new(); + let mut word = String::new(); + for c in text.chars() { + if c.is_alphanumeric() || c == '_' { + word.push(c); + } else if !word.is_empty() { + out.push(std::mem::take(&mut word)); + } + } + if !word.is_empty() { + out.push(word); + } + out +} + +#[test] +fn a_crossing_member_access_names_the_head_and_the_field_second() { + // QA's LOW: `b.data` and `s.f` cross the boundary as `b` and `s` — the + // port and the variable — and a sentence leading with the field reads as + // if the field were a signal of `m`'s own. + let iface = "interface bus_if;\n logic data;\n modport mp (output data);\nendinterface\nmodule m (bus_if.mp b, input logic a);\n logic q;\n assign b.data = a;\n assign q = a;\nendmodule\n"; + let said = refusal(iface, "assign b.data = a;"); + assert!(said.contains("uses `b.data`"), "{said}"); + assert!(said.contains("`b` is declared with a type written outside `m`"), "{said}"); + + let packed = "typedef struct packed {\n logic f;\n logic g;\n} s_t;\nmodule m (input logic a, output s_t s);\n logic q;\n assign s.f = a;\n assign q = a;\nendmodule\n"; + let said = refusal(packed, "assign s.f = a;"); + assert!(said.contains("uses `s.f`"), "{said}"); + assert!(said.contains("`s` is declared with a type written outside `m`"), "{said}"); +} diff --git a/docs/coverage_gaps.md b/docs/coverage_gaps.md index 19ae9d2..f7e43dd 100644 --- a/docs/coverage_gaps.md +++ b/docs/coverage_gaps.md @@ -97,7 +97,7 @@ request. | L6 | `->>` non-blocking event trigger; stream `with [range]`; cast bases other than a name/system call; drive strength on a net declaration; net delay written after the type; `let` at statement position; `#(min:typ:max)` clocking skew. | expressions-2 / interfaces / dv-statements READMEs, TODO §11 skips. | | L7 | `` `ifdef `` conditions never evaluated (both arms listed); no macro expansion; stringification passes through. | TODO §7 non-goal — by design, like Verible. | | ~~L8~~ | ~~Execute-command spelling of the instantiation skeleton for clients without `inlineCompletion` (topo §2.9-19).~~ — **delivered 2026-09-02 by TODO §26**: `lucisv.instantiate [uri, position, module]`, planned through the ghost's own `nearest_definition`/`plan_for`, rendered plainly and pushed as a `workspace/applyEdit`. Documented with a keymap in `editors/nvim/README.md`. | inline-instantiation README. | -| L9 | `codeAction/resolve` laziness; `inlayHint` zero at default scope; index widen not interleaved. | TODO §10 deferred. | +| ~~L9~~ | ~~`codeAction/resolve` laziness; `inlayHint` zero at default scope; index widen not interleaved.~~ — **delivered 2026-09-04/05 by TODO §37** (lazy resolve, 11.8× on the cursor path; the inlay zero ruled correct — `pins_if` is outside the default scope) and **ruled** (a widen stays one bar per session). | TODO §10 closed. | | L10 | Cosmetic: an enum body one-lined when short; `` `uvm_field_* `` lines dedented to the `` `uvm_object_utils_begin `` column (they are plain macro statements — no block for the formatter to see). | Probe observations. | --- diff --git a/docs/features/extract-inline-module/README.md b/docs/features/extract-inline-module/README.md new file mode 100644 index 0000000..f9c02a4 --- /dev/null +++ b/docs/features/extract-inline-module/README.md @@ -0,0 +1,1109 @@ +# extract-inline-module + +TODO §53 — the dearest of the §8 refactoring backlog, in two halves. +**§53.1 extract module ships. §53.2 inline module is unstarted** and is +described here only where §53.1 had to leave room for it. + +## Goal + +A module grows until one of its `always` blocks is a module of its own. The +refactoring every RTL engineer does by hand is: select the items, invent a +name, work out which signals cross the boundary and in which direction, write +the new module's header, paste the items into it, and write an instantiation +where they were. Every step of that is mechanical and every step of it is easy +to get wrong — a signal made an `input` that the block actually drives is a +silent, synthesizable bug. + +**Extract module** does it. Given a selection covering one or more contiguous +whole module items of a module `M`, and a name `N`, lucisv writes a module `N` +whose ports and parameters are inferred from the dataflow across the +selection's boundary, into a file `N.sv` beside `M`'s own, and replaces the +selection with `N u_N (...)` — **rendered from `N`'s own text** through +`instantiation_plan`, so the skeleton and the module cannot disagree about what +`N`'s ports are. + +Whole-edit-or-nothing, through the crate's own splice verifier +(`vlog_refactor::check`): an `Ok` is safe to apply, an `Err` is a sentence for +the user and no edits at all. Where lucisv cannot *know* — the direction of a +routine's argument, the direction of a connection to a module the index has no +single declaration of — it refuses rather than guesses. + +## API as built + +```rust +// crates/vlog_refactor/src/lib.rs +pub enum Home { NewFile, SameFile } + +pub struct ExtractSite { // the cheap gate's answer + pub module: String, // the module the selection is in + pub default_name: String, // `M_extracted` + pub units: Vec, // what the engine will need read +} + +pub fn extract_site(text: &str, start: u32, end: u32) -> Option; +pub fn extract_title() -> String; +pub fn extract_module(files: &[(PathBuf, String)], file: &Path, + start: u32, end: u32, new_name: &str, home: Home) + -> Result; + +// widened, additively +pub struct RefactorEdit { pub edits: …, pub warnings: …, pub created: Vec } + +// crates/lucisv_server/src/extract.rs +pub const EXTRACT_MODULE: &str = "lucisv.extractModule"; // [uri, range, name] +pub fn kind() -> CodeActionKind; // refactor.extract +pub fn code_actions(ws, uri, range) -> Vec; +pub fn execute(ws, arguments, create_files) -> Result<(WorkspaceEdit, Vec), String>; +pub fn workspace_edit(ws, refactoring) -> Result; + +// editors/vscode/extract.js +executeCommand(deps, command, args, next) // the language client's middleware +validateModuleName(value) +``` + +`crates/vlog_refactor/src/extract/` is five files, one question each (and +`region.rs` answers a sixth: an `interface` and a `program` are the same AST +node as a `module`, and only the first is one lucisv extracts out of): + +| file | one sentence | +| --- | --- | +| `mod.rs` | the entry points, the plan, the edits, the verification | +| `region.rs` | what the selection covers, and the item kinds that refuse | +| `flow.rs` | which names cross, and in which direction | +| `boundary.rs` | what each crossing name becomes: port, parameter, import | +| `render.rs` | the new module's text, and the instantiation | + +## The dataflow rule, exactly as implemented + +A name is **written by** a region when, and only when, it is: + +* the left-hand side of a **continuous assignment** (`assign x = …`); +* the left-hand side of a **blocking or non-blocking assignment**, a `for` + initialiser or step, or the target of a `++`/`--`, anywhere inside an + `always` / `initial` / `final` block or a routine body; +* the target of a **`force`**, a **`release`** or a **`deassign`**; +* the target of a **`-> ev`**; +* the **declarator's own initialiser** (`wire w = a & b;`); +* connected to an **`output` or `inout` port of an instantiation** — a fact + only the instantiated module's declaration holds, so it is looked up through + the workspace index (`module_definition` + `instantiation_plan`). + +Everything else is a **read**. Two positions are neither, and both refuse +rather than guess: + +* an **argument of a task or function call** — only the routine's prototype + says whether it is in or out; +* a **positional** or **`.*`** connection, and a `.p` with no expression, which + name no port and no signal respectively. + +The left-hand side of an assignment writes the *base* of whatever it selects: +`a.b[3] = x` writes `a`, which is what resolves. A concatenation or stream on +the left writes each element. + +The boundary table is then, per declaration of `M`, four bits per side +(`read`, `write`, `unknown`, and the same outside). From it: + +| the selection… | outside… | the port | +| --- | --- | --- | +| reads only | anything | `input` | +| writes | does not write it | `output` | +| writes | **also writes it** | refused | +| writes | passes it to a routine | refused | +| passes it to a routine | anything | refused | + +A **parameter** or **localparam** of `M` the selection reads becomes a +`parameter` of `N` with `M`'s own default, overridden `.P(P)` at the +instantiation — and so does every parameter that parameter's *type* or +*default* names, transitively, and every parameter a **crossing port's own +type** names (`input logic [N-1:0] a` carries `N` across). A name in one of +those positions that is declared in `M` and is *not* a parameter is a refusal. + +`import` items of `M` — body imports and header imports alike — are copied into +`N`'s header when one of the names `N` has to resolve could have come through +them. "Could have come through" is the binder's own answer: a use of a name a +package supplies carries the import paths it walked in +`Resolution::ExternalCandidate::paths`, in the spelling the source wrote +(`p::*`, `p::w_t`), and an import is copied exactly when one of the needed +names names *that* import. For a package declared in the same file the binder +resolves the name on the spot, so the same question is asked of the +declaration's position instead: a symbol inside a `package` item's span is one +that package supplies. + +## Refusals — the whole list, each with its sentence + +**Shape of the selection** (`region.rs`): + +| when | the sentence says | +| --- | --- | +| the selection is not inside one module's body | "not inside one module's body" | +| it is inside an **`interface`** | "whose signals are its surface … so there is no boundary for lucisv to infer ports across; lucisv extracts out of a `module`" | +| it is inside a **`program`** | "whose items are testbench code whose meaning depends on when it runs" | +| it cuts an item in half | "cuts an item in half; lucisv extracts whole module items" | +| it covers no item at all | "covers no module item" | +| it holds a **port declaration** | "…a port declaration, which belongs to the module that wrote it" | +| a **`parameter`/`localparam`** declaration | "…a `parameter` declaration" / "…a `localparam` declaration" | +| a **`genvar`** | "…a `genvar` declaration" | +| a **`bind`** | "…a `bind` directive" | +| an **`initial`** block | "testbench code whose meaning depends on when it runs" | +| a **`final`** block | the same | +| a **macro invocation** | "lucisv does not expand macros, so it cannot tell what would move with it" | +| a **compiler directive** | "lucisv does not evaluate one" | +| a **verbatim block** (an assertion, a `property`/`sequence`/`constraint`/`covergroup` body it could not read) | "it cannot tell which names cross the boundary" | +| an **unparsed** leaf | "part of the selection did not parse" | +| a **module/package/class** declaration | "…a declaration of its own" | + +**Dataflow and names** (`flow.rs`, `boundary.rs`): + +| when | the sentence says | +| --- | --- | +| a name is declared **inside** and used **outside** | "move the declaration of `x` out of the selection first" | +| a name is **driven on both sides** | "`x` is driven on both sides of the selection." | +| the selection **passes a crossing signal to a routine** | "only that routine's declaration says whether it is an argument in or out" | +| the selection drives it and something **outside passes it to a routine** | "lucisv will not make it an output over that" | +| a crossing name is a **genvar / function / task / type / enum member / instance / modport / clocking block / class / named block** | "lucisv makes ports out of signals and parameters and nothing else" | +| a crossing name has an **unpacked dimension** | "lucisv does not turn one into a port this round" | +| a crossing declaration has a **qualifier** (`var`, `const`, `automatic`) | "lucisv does not move a qualifier into a port list" | +| a crossing declaration has a **net delay** | "…does not move a delay into a port list" | +| a crossing type is an **anonymous aggregate, a parameterized reference or a virtual interface** (an interface-typed name among them) | "a type lucisv does not move into a port list" | +| a **type parameter** crosses | "lucisv does not carry one into a new module this round" | +| a parameter's default is written **across several lines** | "lucisv does not re-flow one into a new module's header" | +| a header (a port's or a parameter's type, a default) **names something that is not a parameter** | "which is neither a parameter nor a name a module in another file could reach" | +| a **hierarchical reference** crosses (`u_x.sig`, either direction) | "a hierarchical path does not survive being moved into another module" | +| a name is declared **outside `M` at file scope** (a compilation-unit `typedef`, `localparam`, class) — new file only | "a module in a file of its own would not see it" | +| a package name is used **unqualified with no import to carry** | "write the package out, or import it where the new module can see it" | + +**Instantiations inside the selection** (`flow.rs`): + +| when | the sentence says | +| --- | --- | +| **positional** connections | "convert it to named connections first" | +| **`.*`** | "expand the `.*` first (lucisv offers that as its own refactoring)" | +| **`.p`** with no expression | "which names no expression for lucisv to move" | +| a connection lucisv could not read | "cannot tell what the selection drives" | +| the module has **no single indexed declaration** | "no single indexed declaration of it" | +| a `.port` the module does not declare | "cannot tell whether it is driven" | +| a port with **no direction** | "cannot tell whether the selection drives it" | + +**The workspace and the new file** (`mod.rs`): + +| when | the sentence says | +| --- | --- | +| the new name is **not a plain identifier** (empty, leading digit, a space, an escaped `\name`) | "not a plain SystemVerilog identifier, and lucisv will not name a module — or a file — with anything else" | +| the workspace **already declares** the new name | "pick a name nothing else uses" | +| the new name **is `M`'s** | "already the name of the module you are in" | +| `M` is **declared twice** in the workspace | "declared in more than one indexed file" | +| lucisv **indexes no `M`** | "indexes no module named `M`" | +| the file **does not parse** | "does not parse (… at line N)" | +| there is already a file at `N.sv` | "there is already a `N.sv` beside this file" | +| a **`` `timescale ``, `` `default_nettype `` or `` `resetall ``** is in force before `M` — new file only | "a new file would not inherit it; extract into the same file, or move the directive into an include both files use" | + +## Where the new module goes, and the client capability behind it + +A file `N.sv` beside `M`'s is a **`CreateFile` resource operation**, and LSP +only lets one be sent inside `documentChanges`. So the server reads, at +`initialize`, both halves of the capability — +`workspace.workspaceEdit.documentChanges == true` **and** +`workspace.workspaceEdit.resourceOperations` containing `create` — the way §37 +reads `codeAction.resolveSupport` (`main.rs::create_files_support`, +`ClientAbilities::create_files`). Then: + +* **can create files** (VS Code does): `Home::NewFile`. The edit is + `documentChanges: [CreateFile(N.sv), TextDocumentEdit(M.sv), TextDocumentEdit(N.sv)]`. +* **cannot** (or a caller that asked for it): `Home::SameFile`. `N` is written + below `M` in `M`'s own file, as one ordinary `changes` map — no capability of + any kind. The `` `timescale `` refusal does not apply, because the same file + inherits it. + +Either way the engine says which happened, in the first of its warnings, so the +user is never left guessing where their module went. + +## The name, and how the user is asked for it + +LSP has no prompt. A code action may carry an `edit`, a `command`, or both, and +only a `command` can be intercepted by a client that wants to ask the user +something first — so the action carries **`lucisv.extractModule [uri, range, +"M_extracted"]` and no edit**. That is also what makes it the laziest action in +the server: the offer is one parse of one buffer (`extract_site`), and no +workspace is read until the user has both picked the action *and* named the +module. + +The VS Code extension steps in through the language client's +**`middleware.executeCommand`** (`editors/vscode/extract.js`), not through a +command of its own: `vscode-languageclient` registers every command the server +advertises in `executeCommandProvider` with `vscode.commands.registerCommand`, +so a second registration of the same id would collide at activation. The +middleware shows an input box prefilled with the default, validates against the +same identifier rule the engine enforces, and hands the typed name to `next`. A +cancelled box sends nothing at all. Every other client runs the command as sent +and gets the default name — or passes its own, which is the documented API. + +## The verifier, and the one widening (CLAUDE.md invariant 4) + +Everything is one `check::verify_move` over the whole edit — the splice +contract unchanged: the pieces comparison, the parse check, and resolution +identity outside the edited ranges, in every watched file. + +**The widening.** `never_dropped`'s three equations used to be kept per file, +which is exactly right for every refactoring that stays inside one file and +exactly wrong for a move: a comment the selection carries is *deleted* in +`M.sv` and *written* in `N.sv`, so neither file balances on its own. So the +counting was factored into a `Ledger`, and `verify_move` takes a +`moving: &[(usize, TextRange)]` list. + +**The widening is bound to the bytes that move, not to the files** (the +2026-09-06 rework; QA's finding V1). `moving` names every file the move +touches: a **source**, with the byte range the move takes its text out of — the +selection — and a **destination**, a file that only receives, with an empty +range. A ledger is one file's, always. Per file `f` and per never-dropped text +`t`, with `before`/`after` the file's own counts, `gone` the old pieces a +non-empty edit range covers, `wrote` the pieces the edits' own text spells, and +`out` the pieces of `gone` inside `f`'s region: + +1. `after_f + out_f >= before_f` — nothing is lost; a file may end short only + by exactly what left through its own region. +2. `wrote_f <= (gone_f - out_f) + in_f`, unless the text is one a refactoring + `generated` — nothing is duplicated. `in_f` is the whole transit (`Σ out`) + for a destination and zero everywhere else, so **a deletion outside the + region is an ordinary deletion that has to be written back in its own file**. +3. `after_f == before_f - gone_f + wrote_f` — the applied text says exactly + what the edits say, transit out counted as gone and transit in as wrote. +4. `Σ over destinations of (wrote - gone) == Σ over sources of out` — the + transit lands, exactly once, in the files the move named. + +A file `moving` does not name keeps the per-file contract untouched, so a piece +in transit to a file the move never named is refused twice over (by that file's +rule 2 and by rule 4). `verify_splice` is `verify_move(…, &[])` and is +byte-for-byte the old behaviour. The positional piece comparison is untouched +and still runs per file. + +**The masked-corruption attacks** — crafted (plan, corrupted plan) pairs the +widening could plausibly forgive. All of them go through the **production** +entry point: a real `Scope` over the two files, the raw `TextEdit`s, and +`check::verify_move` itself, `positions_match` and all (QA's V1: the six they +replace went through a ledger-only test helper, which is why the first row +below was invisible). In `check/ledger.rs`'s and `check/mod.rs`'s test modules: + +| # | the pair | verdict | +| --- | --- | --- | +| 1 | the honest extraction the engine produces — comment *and* `(* keep *)` in transit | **accepted** | +| 2 | `M` holds the same comment twice; the plan deletes the copy **outside** the region as well and writes the moved one into `N` twice, so the pair balances 2-in/2-out | **rejected** — "comments are never dropped", naming `m.sv` | +| 3 | the comment in transit written **twice** into `N` | rejected — "never duplicated" | +| 4 | deleted in the region and **also** written back into `M` above the instantiation | rejected — "never duplicated" | +| 5 | deleted in the region and written **nowhere** | rejected — "would move … and write it back nowhere; comments are never dropped" | +| 6 | the same for an **attribute** `(* keep *)` | rejected — "attributes are never dropped" | +| 7 | `N` writes a comment **nothing** put in transit | rejected — "never duplicated" | +| 8 | `N` writes `/* TODO: connect */`, the `generated` whitelist | **accepted** — the whitelist is unchanged | +| 9 | the module text written into a **third file the move did not name** | rejected — that file keeps the per-file contract | +| 10 | the deletion **widened past the region** swallows `// the rest` | rejected — naming that comment | +| 11 | the `moving` range does **not cover** what the edits delete (the planner lied about its region) | rejected — "comments are never dropped" | +| 12 | the honest extraction with an **empty** `moving` | rejected — the widening is opt-in | + +`confirm` is the second net, as in `ports`: the edited text is read back and +the new module's header must declare exactly the ports and parameters the plan +promised — `verify_move` proves the edit is honest, nothing in it proves the +header lucisv wrote is the header it meant to write. + +## Assumptions + +* **The selection covers whole module items.** An item's own comments and + attributes travel with it exactly when the selection covers them too, so a + selection starting on the item's line leaves the note above it behind and one + starting a line earlier takes it along. An empty selection — a bare cursor — + is read as the item it is on, because that is what an editor sends when + nothing is selected. +* **The region's text moves verbatim.** Items are module items in `M` and + module items in `N`, at the same nesting depth, so the source's own + indentation is already right and every comment, attribute and string travels + byte for byte — which is what lets the splice verifier count them. The + header lucisv writes around them is two-space-indented; the formatter + reconciles the two on the next save, and the tests pin that the result + formats and converges. +* **A hierarchical reference inside the selection is judged by §49's surface.** + `Resolution::ExternalCandidate { surface: Hierarchical }` is recorded exactly + when the head resolved to an instance; the head is found as the nearest + earlier reference resolving to an `Instance` with only a dotted path between + the two. A hierarchical path whose head instance the selection *also* moves + is allowed; every other one refuses. +* **A module, an interface and a package are visible from every file**, so one + declared beside `M` never becomes a port and never refuses. A `typedef`, a + `localparam` or a class at **file scope** is a compilation-unit declaration + and does refuse — for a new file. +* **`M` is declared exactly once in the workspace lucisv was handed.** The + server hands the engine the fan-out of the units the selection names, so a + second `M` the index knows about is one the engine sees. +* The extraction does not rename anything and does not reorder anything. If the + user wants the new module's ports in a different order, that is + `remove_port`/`add_port`'s job. + +## Handshakes + +* **`vlog_refactor::RefactorEdit`** (widened, additive). New field + `created: Vec` — the files the refactoring creates, each of which + also appears in `edits` with one insertion at offset 0. Every existing + producer sets it to `Vec::new()`; every existing consumer that ignores it + gets exactly what it got before. +* **`vlog_refactor::check`** (internal). `verify_splice` now delegates to + `verify_move(scope, edits, watched_names, what, moving)`, where `moving` is + `&[(usize, TextRange)]` — a file with its moved region, or with an empty + range for one that only receives; `never_dropped` is now `Ledger::of` + + `Ledger::check` with `Transit` holding the two halves of a move to each + other, and `pieces_match` takes a pre-lexed `Split`. `watched_files` takes a + `&[&str]` of names rather than two. `check.rs` is now `check/mod.rs` plus + `check/ledger.rs` (a pure move; the paths are unchanged). All + crate-internal; no call site outside `vlog_refactor` sees any of it. +* **`lucisv_server::server::ClientAbilities`** (new field). + `create_files: bool`, read at `initialize` by `create_files_support`. +* **`lucisv_server`** — one new module (`extract.rs`), one new code-action kind + (`refactor.extract`) in `capabilities`, one new command in `commands()`, and + two new branches in `server/dispatch.rs` (the `codeAction` fan-out, and the + `executeCommand` split — the extract command is routed before + `ports::execute` because it needs the client's own capability). + `ports::workspace_edit` is reused unchanged for the same-file case. +* **`editors/vscode`** — one new module (`extract.js`) and its test + (`extract_test.js`), plus `clientOptions.middleware.executeCommand` in + `extension.js`. No `package.json` change: the command is registered by the + language client from the server's own `executeCommandProvider`, and + contributing it again would put it in the command palette without its + arguments. +* **Request to `vlog_semantic`: none.** Everything the engine needed was + already public (`Semantics`, `Resolution`, `Surface`, `WorkspaceIndex`). + +## Status / TODO + +- [x] 53.1 extract: dataflow ports, parameters, imports, the new file, + refusals, action + command + extension input box +- [ ] 53.2 inline: substitution, prefixing, refusals, action + command — + **unstarted**, see "What §53.2 still needs" below +- [ ] the extract → inline round trip pinned — **blocked on 53.2** +- [x] docs; §8 lines annotated; site rows (lead — see below) +- [x] Gates (guarded); byte-identity vs 0.46.0; corpus scratch checks +- [ ] QA + +## What §53.2 still needs (unstarted) + +Nothing in §53.1 was shaped to make §53.2 harder, and two things were shaped to +make it easier: + +* `RefactorEdit::created` and `check::verify_move`'s `moving` list are general. + An inline moves text the other way — out of `S.sv` into `M.sv` — and, if it + ever deletes `S.sv`, will want a `deleted` field beside `created`. +* `flow.rs`'s write/read classification is the same question an inline asks of + `S`'s body when it decides which of `M`'s names a substituted port may be + bound to. It is `pub(super)` today and would move up a level. + +The refusal list in TODO §53.2 stands as written; none of it has been +implemented, and no `refactor.inline` action is offered. + +## Gate numbers after the rework (2026-09-06, all guarded) + +| Gate | Result | +| --- | --- | +| `cargo fmt -p vlog_refactor` | clean | +| `cargo clippy --all-targets` | clean, no new `#[allow]` | +| `cargo test --workspace` | **4 081 passed, 0 failed, 44 ignored** (4 073 + 5 verifier attacks + 3 extract tests) | +| `tools/corpus_check.sh` | **814/820 (99.3%)**, the same six parse errors, 0 verification errors | +| corpus extraction trial (860 files) | **5 extracted, 6 refused**, unchanged; the census holds at 10 268 for every one | +| opentitan extraction trial (237 files, scratch copies of `hw/ip/{aes,uart,spi_host,hmac}`) | **5 extracted, 5 refused**; census 10 614 → 10 614 for every extraction | + +The opentitan trial is now reproducible as run: copy +`hw/ip/{aes,uart,spi_host,hmac}` (237 `.sv`/`.svh`/`.v` files, opentitan at +`0098135264`) to a scratch tree and point `LUCISV_EXTRACT_ROOT` at the copy. +The trial prints each accepted extraction with its census and each refusal with +its sentence, so the list below is what it says. + +| file | module | outcome | +| --- | --- | --- | +| `aes/dv/sva/aes_idle_check.sv` | `aes_idle_check` | extracted, census 10 614 → 10 614 | +| `aes/dv/sva/aes_masking_reseed_if.sv` | `aes_masking_reseed_if` | **refused** — inside an `interface` (QA's V2; this one used to extract and cost four names) | +| `aes/dv/sva/aes_reseed_if.sv` | `aes_reseed_if` | **refused** — inside an `interface` | +| `aes/dv/tb/tb.sv` | `tb` | refused — `tb` declared in more than one indexed file | +| `aes/pre_dv/aes_cipher_core_tb/rtl/aes_cipher_core_tb.sv` | `aes_cipher_core_tb` | extracted, census unchanged | +| `aes/pre_dv/aes_sbox_lec/aes_sbox_masked_wrapper.sv` | `aes_sbox_masked_wrapper` | refused — `prd_masking` passed to a routine outside | +| `aes/pre_dv/aes_sbox_tb/rtl/aes_sbox_tb.sv` | `aes_sbox_tb` | extracted, census unchanged | +| `aes/pre_dv/aes_tb/rtl/aes_tb.sv` | `aes_tb` | refused — `entropy_q` passed to a routine outside | +| `aes/pre_dv/aes_tb/rtl/aes_tb_c_dpi.sv` | `aes_tb_c_dpi` | extracted, census unchanged | +| `aes/pre_dv/aes_tb/rtl/aes_tb_reqs.sv` | `aes_tb_reqs` | extracted, census unchanged | + +(The trial stops at five extractions, which is why the scan ends inside `aes/`.) +`git -C …/opentitan status --porcelain` shows the same three pre-existing files +before and after; nothing but scratch copies was read. + +## Gate numbers (2026-09-05, all guarded) + +| Gate | Result | +| --- | --- | +| `cargo fmt -p vlog_refactor -p lucisv_server` | clean | +| `cargo clippy --all-targets` | clean, no new `#[allow]` | +| `cargo test --workspace` | **4 073 passed, 0 failed, 44 ignored** (baseline 4 020) | +| `tools/corpus_check.sh` | **814/820 (99.3%)**, the same six | +| `format --stdout` vs `~/.cache/lucisv-baselines/lucisv-0.46.0` over 860 corpus files | **854 identical, 0 differing**, 6 refused by both | +| `cargo build --release -p lucisv -p lucisv_server` | ok | +| `node editors/vscode/smoke.js target/release/lucisv-server` | OK | +| `node editors/vscode/extract_test.js` | OK, 31 checks | +| corpus extraction trial (860 files) | **5 extracted, 6 refused**, every result parses, formats, converges; the design's unresolved-name census unchanged | +| opentitan extraction trial (244 files, scratch copies) | **5 extracted, 11 refused**, same checks | + +**Not this lane's:** `docs/coverage_gaps.md` is modified in the working tree +(the L9 row, about §37's lazy resolve). It was already modified when this lane +started and nothing here touched it — flagged rather than reverted, per the +file-ownership rule. + +## Measurements + +Production lines (non-blank, non-comment), all under the 600 target: + +| file | lines | +| --- | --- | +| `vlog_refactor/src/extract/mod.rs` | 381 | +| `vlog_refactor/src/extract/flow.rs` | 534 | +| `vlog_refactor/src/extract/boundary.rs` | 352 | +| `vlog_refactor/src/extract/render.rs` | 303 | +| `vlog_refactor/src/extract/region.rs` | 155 | +| `lucisv_server/src/extract.rs` | 286 (incl. tests) | + +`check.rs` reached **702 production lines** with the rework's equations on +board, over the 600 target, so it was split (2026-09-06, a pure move — public +paths, behaviour and output all unchanged): + +| file | production lines | one sentence | +| --- | --- | --- | +| `vlog_refactor/src/check/mod.rs` | 392 | verify the whole edit — token identity, the parse check, resolution identity — or refuse it whole | +| `vlog_refactor/src/check/ledger.rs` | 334 | the pieces a file is made of, the comparison that says an edit wrote what it promised, and the ledger of the ones that are never dropped | + +## Work log + +**2026-09-05 — dev (§53.1).** Read §52's engine and README, `ports/`'s +splice/`confirm` spine, `instantiate.rs`, `check.rs`, `vlog_semantic`'s model +and §49's surface, and the server's lazy-action and command plumbing. Then, in +order: + +1. **`check.rs`: the widening first**, so the rest could be built on a verifier + that admits a cross-file move. `never_dropped` became `Ledger::{add,check}`, + `pieces_match` became `Split::read` + `Split::positions_match` + a per-file + `pieces_match` over the pair, and `verify_splice` became a `verify_move` + with an empty `moving` list. Six masked-corruption attacks written at the + same time (invariant 4), including one that pins the widening as opt-in. +2. **`extract/region.rs`** — the selection, the whole-item rule and the + item-kind refusals. Decision: an item's extent includes its own comments + *only when the selection covers them*, which is what makes a selection do + what the user's mouse said. Second decision: an empty selection is the item + under the cursor, so the action is available without dragging. +3. **`extract/flow.rs`** — the dataflow. The classification is a second + implementation of a question `vlog_linter::signals` also answers, and that + was deliberate: `vlog_refactor` may not depend on `vlog_linter` (it would + pull in `lucisv_core`), the linter's table is `pub(crate)`, and the two + questions differ where it matters — the linter's rule is *say nothing when + unsure*, this one's is *refuse when unsure*. Recorded here rather than + hidden: if a third caller ever wants it, the shared home is `vlog_semantic`. +4. **`extract/render.rs`, `extract/mod.rs`** — the header, the new module, the + instantiation through `instantiation_plan`. The new file joins the in-scope + set as an **empty file** before anything else happens, so the index, the + analysis and the verification all ask about it exactly the way they ask + about a file that was always there. +5. **`lucisv_server/src/extract.rs`**, the capability, the dispatch, and + `editors/vscode/extract.js`. + +**Two defects the trials found, both fixed and both pinned by a test.** + +* *The corpus.* `common_cells/src/binary_to_gray.sv` extracted into a module + whose ports read `input logic [N-1:0] a` with no `N` anywhere: the parameter + is named by the **port's own type**, and no statement in the selection names + it, so a closure over the region's references alone never wanted it. Fixed by + seeding the parameter closure with the words of every port's rendered prefix + (and of every parameter's, transitively) — `boundary::depends`. Pinned by + `a_parameter_a_ports_own_width_names_crosses_with_it`. +* *opentitan.* `hw/ip/aes/rtl/aes_ctr.sv` writes `module aes_ctr import + aes_pkg::*;` and the extraction copied **no import at all**, leaving + `sp2v_e` and `Sp2VWidth` naming nothing. The binder records a wildcard import + in a reference's `paths` as `p::*` — the spelling the source wrote — and the + judgement was matching `p::`. Fixed by comparing against + `Import::path()`, which is that same spelling, with `Import::supplies` as the + gate. Pinned by `a_wildcard_import_in_the_header_is_carried_across` and + `a_named_import_is_carried_across_only_when_the_name_it_supplies_is_needed`. + +Both were caught by the **census** — the number of names the design cannot +resolve, before and after — which is why the trial asserts on it rather than on +"it parsed". Neither would have failed a parse check. + +**One split, mid-round.** `extract/mod.rs` reached 685 production lines, over +the 600 target, so the boundary classification moved to `extract/boundary.rs` +(pure move; the test count did not change). mod.rs is 376. + +**Deviations from the plan, all deliberate and all named:** + +* **`53.2` is unstarted.** §53.1 alone consumed the round, as the brief + anticipated; a finished half beats two unfinished ones. The round-trip pin is + blocked on it. +* **The refusal for a routine's argument is broader than the plan's letter.** + The plan says "a task/function call's output argument"; lucisv cannot tell an + output argument from an input one without the prototype, so it refuses on + *any* argument position that names a crossing **signal**. A crossing + *parameter* in an argument (`$clog2(WIDTH)`) is untouched — a parameter has + no direction. In practice the common case is already refused a step earlier, + because a routine declared in `M` outside the selection and called inside it + refuses on its own. +* **The hierarchical refusal is conservative in one shape.** A hierarchical + path whose head instance the selection also moves is allowed, and that is + decided by a nearest-earlier-instance-reference-with-a-dotted-path + heuristic. Where the heuristic cannot find a head at all, the extraction + refuses (naming `….sig`), which is the safe direction. +* **A file-scope `typedef` in `M`'s own file refuses for a new file and is + allowed for the same file.** The plan does not name this refusal; it is + forced by the language (a compilation-unit declaration does not reach a file + that was not compiled with it), and the same-file fallback is exactly the + escape hatch. +* **The action carries a command rather than a resolvable edit.** The plan + says "lazy"; a command with no edit is lazier, and it is the only shape a + client can put an input box in front of. + +**2026-09-06 — dev, rework (QA's V1, V2 and the LOW).** + +**V1 — the pool was bound to the wrong thing.** `verify_move` pooled one +never-dropped ledger over whole *files*, so a pair of individually-honest edits +could balance in aggregate while one file lost content nothing ever moved: QA's +`m.sv` deletes an untouched second copy of a comment, `n.sv` writes a duplicate +of the moved one, 2 in and 2 out, accepted. Fixed by binding the allowance to +the **bytes that move**. `moving` is now `&[(usize, TextRange)]` — a source +with its region, a destination with an empty range — a `Ledger` is one file's +again, and `Transit` holds the halves of a move to each other. The four +equations are written out above and in `verify_move`'s doc comment; the one +that does the work is rule 2's `wrote_f <= (gone_f − out_f) + in_f`, which says +that **a deletion outside the region is an ordinary deletion, to be written +back in its own file**, exactly as it always was. QA's pair now refuses with +"comments are never dropped", naming `m.sv`. + +The twelve attack pairs in the table above all go through the production +`verify_move` with a real `Scope` and raw `TextEdit`s — the `pooled()` helper +QA objected to is gone, and with it the last place a corruption could be judged +without `positions_match` also having its say. Corruption is expressed as a +corrupted *plan* rather than a corrupted applied text, which is one notch more +real: the verifier applies the edits itself. + +`check.rs` was 618 production lines before this and 702 after, so it was split +into `check/mod.rs` (392) and `check/ledger.rs` (334) — a pure move: the same +items, the same `crate::check::…` paths, the same tests, `cargo test +-p vlog_refactor` unchanged but for the rework's own additions. + +**V2 — the `kw` gate.** `vlog_parser` writes `module`, `interface` and +`program` as one `ItemKind::Module` distinguished only by `Module::kw`, and +`region.rs::module_at` never asked. `Region::read` now calls `extractable`, +which accepts `module`/`macromodule` and refuses the other two with the +sentences the refusal table promises. `extract_site` reads the same `Region`, +so the code action is no longer offered inside an interface either. Pinned by +`a_selection_inside_an_interface_or_a_program_is_refused` and +`the_action_is_not_offered_inside_an_interface_or_a_program`, and by the +opentitan trial above: `aes_masking_reseed_if.sv` and `aes_reseed_if.sv` are +now refusals, and every accepted extraction leaves the census at 10 614. + +**The LOW — a member access names its head.** `boundary::visible` refused with +the field (`data`, `f`), which reads as if the field were a signal of `M`'s +own; what crosses the boundary is the port or the variable. A text-side +`access_head` reads `s` out of `s.f` and `b` out of `b.data`, and the refusal +is now "the selection uses `b.data`, and `b` is declared with a type written +outside `m` in the same file…". Pinned by +`a_crossing_member_access_names_the_head_and_the_field_second`. + +**No existing expectation was altered.** The three tests whose text changed are +the ones the rework replaces (the six `pooled()` attacks became the twelve +`verify_move` ones); everything else — 40 in `tests/extract.rs`, the corpus +trial's 5/6, the workspace's other 4 000 — is as it was. `tests/corpus.rs` +gained two `println!`s (the census per extraction and each refusal's sentence), +so a trial run is reproducible without patching it first. + +## Docs to apply at merge (lead) + +**`docs/site/` — language-tools row.** Add beside organize-imports: + +> **Extract module** — select the `always` blocks, assignments or +> instantiations that have grown into a module of their own, name it, and +> lucisv writes it: ports and parameters inferred from what the selection reads +> and drives, `import`s carried across, the items moved byte for byte, and the +> instantiation that replaces them rendered from the new module's own text. A +> file of its own where the editor can create one, below the module it came +> from where it cannot. Refuses — with a sentence — wherever a direction +> cannot be known: a routine's argument, a `.*`, a positional connection, a +> module the index cannot pin down, a name both sides drive. + +**`README.md`** — the refactorings list gains one entry beside the port ones: + +> * **extract module** (`refactor.extract`, `lucisv.extractModule`) — a +> selection of whole module items becomes a module of its own, with ports +> inferred from the dataflow across the boundary. + +**`docs/topo.md`** — two edges to record: + +* `vlog_refactor::RefactorEdit::created` — a new public field, read by + `lucisv_server::extract` only. `lucisv_server ◀── vlog_refactor`, widened. +* `lucisv_server::server::ClientAbilities::create_files` — a new capability + read at `initialize`, consumed by `server/dispatch.rs` only. + +**`TODO.md` §8** — the extract-module line is annotated in place (done by this +lane); the inline-module line is **not**, because §53.2 is unstarted. §53's own +checkboxes are ticked except 53.2, the round trip, and the QA line. + +## QA log + +**2026-09-06 — QA (§53.1 only).** Read this README, the diffs (`check.rs`, +`vlog_refactor/src/extract/{mod,region,flow,boundary,render}.rs`, +`tests/{extract,corpus}.rs`, `lucisv_server/src/extract.rs`, +`server/{dispatch,mod}.rs`, `main.rs`, `editors/vscode/{extract,extension}.js`), +then attacked the verifier, attacked the dataflow rule with hand-picked shapes, +read the server/extension wiring, and re-ran the trials and every gate. Two +confirmed defects, both HIGH, below; verdict is **REWORK**. + +### Priority 1 — the verifier widening (`check.rs`) + +All six of the dev's own attack tests were re-read and re-run +(`cargo test -p vlog_refactor --lib check::`, 44/44 pass, including all six +under `the pooled ledger, and the attacks on it`). They are sound, but they +all go through the dev's own `pooled()` test helper, which calls +`Ledger::add`/`Ledger::check` **directly** and never calls +`Split::positions_match` — so they exercise the aggregate-count equations in +isolation, not the full `verify_move` path a real refactoring goes through. +I re-attacked through the *production* entry point instead: a `Scope` built +from real files, raw `TextEdit`s, and `check::verify_move` itself (temporary +tests, removed after; reproductions below use the same shape so the dev can +paste them back in). + +| # | attack | via | result | +| --- | --- | --- | --- | +| 1 | comment deleted in M, written in N once | `verify_move` | **ACCEPTED** (correct) | +| 2 | comment deleted in M, written in N twice | dev's `pooled()` | REJECTED — "never duplicated" | +| 3 | deleted in M, written in N *and* left in M | dev's `pooled()` | REJECTED — "nothing was edited" | +| 4 | deleted in M, written nowhere | dev's `pooled()` | REJECTED — "never dropped" | +| 5 | written in N, never deleted in M (invented) | flow.rs makes this unreachable via the real edits, but the equation (`writes > deleted`) rejects it directly in `Ledger::check` | REJECTED | +| 6 | deleted in M, written into a **third file not in `moving`** | `verify_move`, 3 files, `moving=[m,n]` | REJECTED — the third file's own per-file `pieces_match` sees an invented write ("never duplicated"); confirmed by re-attack | +| 7 | same honest move, `moving` **empty** | dev's test 6 | REJECTED — "never dropped" (opt-in confirmed) | +| 8 | attribute `(* keep *)` in transit, balanced / lost | dev's tests 1–2 | ACCEPTED / REJECTED correctly | +| 9 | **two identical comments, one moved and one left untouched**, corrupted so the pool balances (2 in, 2 out) but `m.sv` alone loses the *untouched* copy while `n.sv` gains a *duplicate* of the moved one | `verify_move`, real `Scope` + hand-edits | **ACCEPTED — FORGIVEN. HIGH.** | +| 10 | `moving` naming a file the edits never touch | `verify_move` | inert — honest move still verifies, no false accept | +| 11 | `moving` naming the same file index twice | `verify_move` | same as naming it once | +| 12 | edit outside `moving` (file left out) deletes a comment | `verify_move` | REJECTED — old per-file contract, unwidened | + +**Finding V1 (HIGH) — the pooled ledger can forgive a per-file loss when a second, textually-identical never-dropped piece is in play.** +`Ledger::check` (`crates/vlog_refactor/src/check.rs:617`) only ever compares +*counts* of a `(noun, text)` key summed over every file named in `moving` +(`Ledger::add`, `check.rs:602`). `Split::positions_match` +(`check.rs` — the per-file token-position comparison) still runs for every +pooled file, but it only checks that applying that file's *own* edits +produces that file's *own* claimed text — it says nothing about whether a +piece that disappeared from position N in file A was legitimately moved to +file B or simply invented/lost independently. Two edits that are each +"positionally honest" for their own file can therefore corrupt correctness as +a *pair*: `m.sv`'s edit deletes an extra copy of a comment nobody meant to +move, `n.sv`'s edit writes an extra copy of the one that did, and the pool's +aggregate math (`before=2, deleted=2, writes=2, after=2`) is satisfied by +construction, even though `m.sv` alone lost content it never gave up. +Reproduction (paste into `check.rs`'s test module, real `verify_move`, no +`pooled()` helper): +```rust +const TWO_NOTES: &str = "module m (\n input logic a,\n input logic b,\n output logic p,\n output logic q\n);\n assign p = a; // note\n assign q = b; // note\nendmodule\n"; +// m_edits: delete the untouched first "// note" (own TextEdit, empty +// new_text) AND replace "assign q = b; // note" with an instantiation. +// n_edits: one insertion of a whole `module second` whose body writes +// "// note" twice. +// files sorted by Scope::build: m.sv, second.sv. +verify_move(&mut scope, &plan, &["m", "second"], MOVED_WHAT, &[0, 1]) == Ok(()) +// ^ should be Err; it is Ok. +``` +This is not a shape the current `extract` engine is known to *produce* today +(no corpus or opentitan trial hit it) — it is the shape CLAUDE.md invariant 4 +asks every widening to be attacked with regardless, because a future bug in +`render.rs`'s comment-carrying code (or a second consumer of `verify_move`, +which `RefactorEdit::created`'s Handshakes note §53.2 will be) could produce +exactly this pair and the safety net would wave it through. Needs: either a +per-piece *identity* (not just count) carried through the pool — e.g. an +edit-relative source position tag on each `Piece::Comment`/`Piece::Attr` so a +piece can only balance against its own counterpart — or an explicit bound +that a file's own per-file delta (`after - (before - deleted)`) can only be +negative (a piece leaving) when `moving` is non-empty *and* the piece +actually appears in another pooled file's `writes` at least once **per +occurrence**, not just in aggregate. Left to the dev; QA does not redesign. + +### Priority 2 — the dataflow rule and the extraction + +Read `region.rs`, `flow.rs`, `boundary.rs`, `render.rs`, `mod.rs` in full. +Cross-referenced every row of the brief's dataflow matrix against +`tests/extract.rs`'s existing 33 tests (thorough — combinational, sequential, +parameter+import, parameter-in-port-type, wildcard/named import, +file-scope-typedef refusal, both-sides-write, routine-argument refusal, +hierarchical refusal, unpacked-dimension refusal, positional/`.*`/no-such-port +instantiation refusals, timescale/default_nettype, name-collision refusals, +cursor-as-selection, the reference census). Then ran additional scratch +extractions (temporary `tests/qa_scratch_53_1.rs`, removed after) for rows +the existing suite does not cover: + +| row | result | +| --- | --- | +| struct member write `s.f = a` (S declared as a port) | ACCEPTED, `s` becomes `output` — correct, but see Finding L1 | +| same, `s.g` also written outside the region | REJECTED — "`s` is driven on both sides" (base-of-lvalue rule confirmed for `Member`) | +| part-select write `x[3:0] = a` alone | ACCEPTED, `x` becomes `output` | +| same, `x[7:4]` also written outside | REJECTED — "`x` is driven on both sides" | +| interface signal write `b.data = a` (`bus_if.mp b` port) | REJECTED — "declared outside `m`" (see Finding L1: names the field, not the interface) | +| pure-function-read argument `twice(a) + twice(a)` | REJECTED — confirms the dev's documented over-refusal (any argument position, not just outputs) | +| hierarchical reference whose head instance is inside the selection | ACCEPTED — confirmed the allowed case | +| whole-module-body selection | ACCEPTED — M is left holding only the instantiation | +| `localparam` used inside | ACCEPTED — becomes a `parameter` of N with the default carried, matches README | +| comment on a standalone line between two selected items | travels into N with both items' own trailing comments, all three intact | +| `case` expression read | ACCEPTED as `input` | + +**Finding V2 (HIGH) — `region.rs::module_at` accepts a selection inside an `interface` or `program` body, contradicting the documented refusal ("a selection in an interface/program (refused)", TODO §53.1 and this README's refusal table), and produces a measurable correctness regression on real RTL.** +`vlog_parser`'s AST uses one `Module` node for `module`/`interface`/`program` +(`crates/vlog_parser/src/ast/module.rs:8-16`, distinguished only by +`Module::kw`). `Region::read`'s `module_at` +(`crates/vlog_refactor/src/extract/region.rs:80-92`) matches +`ItemKind::Module(module)` and never inspects `module.kw`, so it treats an +`interface` (or `program`) exactly like a `module`. Nothing downstream +catches it either — `extract_site` (the cheap gate offered as the code +action) uses the same `Region::read`, so the action is even *offered* inside +an interface. + +Minimal repro (ran directly, `extract_module` on a 5-line `interface`): +``` +interface bus_if; + logic [7:0] a; + logic [7:0] q; + assign q = a; +endinterface +``` +→ **ACCEPTED.** Produces `module n (...); assign q = a; endmodule` as a new +file, and rewrites the interface body to `n u_n (.a(a), .q(q));` — a module +instantiated inside what remains an `interface`. + +Confirmed as a **real regression, not just a spec gap**, via an independent +opentitan trial: copied `hw/ip/{aes,uart,spi_host,hmac}` (237 files, read-only +source, scratch copies only — `hw/ip/aes/dv/sva/aes_masking_reseed_if.sv` is +an `interface`) and ran the same automated region-scan the dev's own corpus +trial uses. The very first `interface` region it reached +(`aes_masking_reseed_if`'s `always_comb` block, driven off interface header +parameters/ports and package imports) extracted "successfully" — both halves +parsed, formatted and converged — **but the unresolved-name census over the +two files went from 10614 to 10618**, i.e. four names that used to resolve no +longer do. This is exactly the regression class the census assertion exists +to catch (same mechanism as the two defects the dev's own work log +documents), and it did: `cargo test -p vlog_refactor --test corpus +five_regions_of_real_rtl…` with `LUCISV_EXTRACT_ROOT` pointed at the scratch +copy fails at the census assertion, not the parse/format ones. (`opentitan` +repo left untouched — `git -C .../opentitan status --porcelain` before and +after this run shows only the three pre-existing baseline diffs named in the +task brief.) + +Fix is a one-line gate at the top of `region.rs::module_at` (refuse unless +`module.kw` is `"module"`/`"macromodule"`, with the existing `NO_MODULE` +sentence or a dedicated one) — left to the dev, along with a regression test +pinning both the direct refusal and the census non-regression on the +`aes_masking_reseed_if` shape (or a corpus-sized equivalent) once fixed. + +### Priority 3 — the server and extension over the wire + +Read `lucisv_server/src/extract.rs`, `server/dispatch.rs`, `server/mod.rs`, +`main.rs`'s `create_files_support`, `editors/vscode/{extract,extension}.js`. +Confirmed by reading and by the existing test suite (all green, see Gates): +`codeAction` for a whole-item range returns the `refactor.extract` action with +a `Command` and no `edit` (`a_selection_of_whole_items_is_offered_the_action_with_a_command_and_a_default_name`); +not offered for a half-item range +(`a_selection_that_covers_no_whole_item_is_offered_nothing`); `executeCommand +lucisv.extractModule` with `create_files=true` returns `documentChanges: +[CreateFile, TextDocumentEdit×2]` (`the_command_creates_the_new_file_for_a_client_that_can`); +with `create_files=false` a `changes` map writing N below M +(`the_command_writes_the_module_into_the_same_file_for_a_client_that_cannot`); +`create_files_support` needs both `documentChanges` and `resourceOperations` +containing `create` (`create_files_support_needs_both_halves_of_the_capability`, +5 sub-cases). The extract command is dispatched before `ports::execute` in +`server/dispatch.rs` as documented. `grep -n registerCommand +editors/vscode/*.js` shows no second registration of `lucisv.extractModule` — +only `extract.js`'s doc comment mentioning the collision it avoids, and +`hierarchyView.js`'s unrelated commands. `node --test +editors/vscode/extract_test.js` — 31 checks, OK; the full +`editors/vscode/*_test.js` run (extract, hierarchyModel, hierarchyView, +restart) — 4/4 suites pass, no regressions. + +### Priority 4 — trials + +- **Corpus** (`cargo test -p vlog_refactor --test corpus + five_regions_of_real_rtl…`, unmodified `corpus/`): **5 extracted, 6 + refused**, matches the dev's claim exactly. +- **Opentitan, dev's own claim**: not independently re-run at the dev's exact + 244-file selection (the checkout revision/subset used was not recorded + reproducibly in the README); instead ran the same automated trial against + an independently-chosen 237-file scratch subset + (`hw/ip/{aes,uart,spi_host,hmac}`, read-only source untouched) — this is + what surfaced Finding V2 above rather than reproducing "5/11". Given the + finding, the dev's original 244-file number cannot be taken as clean + either without knowing whether an interface region was among its refusals + or its "successes". +- **Five hand-picked opentitan-style regions** (struct member write, part + select, hierarchical head-inside, whole-body, localparam-in-expression) — + folded into the Priority 2 table above rather than run as a second batch, + given time budget; all passed parse/format/convergence where accepted. +- `lucisv check --select unused-signal,undriven-net,multiply-driven` + before/after was not run separately from the reference census (the + corpus/opentitan trials assert an equivalent, stronger, whole-reference + census rather than a three-lint-rule census); not flagged as a gap since + the stronger check subsumes it, but noted for completeness. + +### Gates (guarded, all via `tools/guard.sh`) + +| Gate | Result | +| --- | --- | +| `cargo clippy --all-targets` | clean | +| `cargo test --workspace` | **4 073 passed, 0 failed, 44 ignored** — matches the dev's claim exactly | +| `tools/corpus_check.sh` | **814/820 (99.3%)**, same six parse errors | +| `format --stdout` vs `~/.cache/lucisv-baselines/lucisv-0.46.0` over the 860 corpus files (independently scripted, not via corpus_check.sh) | **854 identical, 0 differing, 6 refused by both** — matches the dev's claim exactly | +| `cargo build --release -p lucisv -p lucisv_server` | ok | +| `node editors/vscode/smoke.js target/release/lucisv-server` | OK | +| `node --test editors/vscode/extract_test.js` | OK, 31 checks | +| `node --test editors/vscode/*_test.js` (full suite) | 4/4 suites, 0 failures | + +All temporary QA tests and scratch copies were removed before finishing; +`git diff --stat` on `check.rs` is back to exactly the dev's own diff +(416+/145-). `git -C .../opentitan status --porcelain` shows only the three +pre-existing files named in the task brief, both before and after this QA +pass. + +**Note to the lead, not this lane's to touch:** `CHANGELOG.md`, +`editors/vscode/CHANGELOG.md`, `editors/vscode/README.md`, `docs/topo.md`, +`docs/site/**`, and `TODO.md`'s `[x]` marks on "docs" and "Gates" changed +during this QA pass (not by this session) — merge-time docs work appears to +already be in flight in this tree. Given Finding V2 in particular, the +already-ticked `TODO.md` "Gates (guarded)" line should be revisited once the +dev fixes it, since the opentitan trial number behind that tick is now in +question. + +### Verdict: **REWORK** + +Two HIGH findings, both requiring a code change plus a regression test +before re-review: + +1. **V1** — the pooled ledger (`check.rs`, `Ledger::check`) can forgive a + masked corruption where one pooled file loses an untouched never-dropped + piece while another pooled file gains a duplicate, as long as the + aggregate count balances. Confirmed via the real `verify_move` entry + point, not just the `pooled()` test harness. +2. **V2** — `extract`'s selection gate (`region.rs::module_at`) does not + check `Module::kw`, so it accepts a selection inside an `interface` or + `program` body, contradicting the documented refusal and producing a + confirmed reference-resolution regression on real RTL + (`aes_masking_reseed_if.sv`, opentitan). + +One LOW note, not blocking: struct-member and interface-member-access +refusal sentences ("the selection uses `f`…") name the accessed field rather +than the type/port that is actually the crossing name, which is technically +correct (the field genuinely has its own symbol at file scope) but reads as +if `f` were expected to be a module-level signal. Cosmetic; no correctness +risk since the refusal (not an accept) is the safe direction. + +The §53.1 QA checkbox in `TODO.md` is left **unticked** pending a fix and a +second QA pass on V1 and V2. + +**2026-09-06 — QA re-attack of the rework (§53.1 only).** Read the dev's +"2026-09-06 — dev, rework" entry above, `check/{mod,ledger}.rs` in full (the +four equations, `Ledger`, `Transit`, `Split::positions_match`), the twelve +`verify_move` attack tests in `check/mod.rs`'s "the moved-piece rule" section, +and `extract/region.rs`'s `extractable`/`module_at`. Re-ran all twelve — all +still pass and all still go through the production `verify_move` (a real +`Scope`, raw `TextEdit`s, `positions_match` included; no `pooled()`-style +helper remains anywhere in the crate: `grep -rn "fn pooled" crates/vlog_refactor` +finds nothing). Then attacked the equations further with temporary tests +(`crates/vlog_refactor/src/check/mod.rs`'s test module, `crates/vlog_refactor/ +tests/extract.rs`; both removed before finishing — `git status --porcelain` +on both shows them as the dev's own untracked additions, unchanged in line +count from before this pass). + +### Attack table (all through production `verify_move`) + +| # | attack | result | +| --- | --- | --- | +| 1a | two real sources (`a.sv`, `b.sv`), one destination (`n.sv`), transit sums correctly | **accepted** | +| 1b | crosswise: `b`'s piece written into `a.sv` (a source, not the named destination) instead of `n.sv` | **rejected** — `a.sv` isn't credited to receive anything (`receives` is false for any file whose region is non-empty), so the write is an unexplained duplicate | +| 1c | can one file be both a source and a destination? | **no, structurally** — `region_of` (`check/ledger.rs:187`) returns the *first* `moving` entry for a file index, and `Moved::receives` (`check/ledger.rs:384`) is derived solely from whether that one range is empty; a file cannot carry a real region and the transit allowance at once | +| 2 | a source declares its own transit region as **empty** while its edit genuinely deletes-and-moves a piece | **rejected** (rule 1) — `within()` credits no `out` for an empty region, so the deletion has to balance on its own and can't | +| 3a | `moving` names the same file index **twice** with different ranges | **inert** — `region_of`'s `.find` only ever sees the first entry; the second is dead weight, confirmed by comparing the dup-list outcome to the single-entry outcome (identical); reversing the order (empty entry first) does change the outcome, as expected, since now *that* entry is the one `.find` returns | +| 3b | region covering the whole file | no panic, ordinary accept, nothing special about size | +| 4a | a region **honestly** containing two identical comments, both really moved | **accepted** | +| 4b | same byte shape, but framed as "the region was *widened* to swallow an unrelated second occurrence" | **also accepted** — the equations are byte-counting; they cannot and do not distinguish "the selection legitimately covers two occurrences" from "someone lied about what the selection covered." In production this never diverges because `extract/mod.rs:211,220` sets the edit's own delete-range and the `moving` region to the *same* `region.span` value, and `region.span` is built by `region.rs::Region::read` from real AST item spans — so the guarantee lives in the planner, not in the verifier. Recorded, not a new defect (same shape as the existing "region that does not cover what the edits delete" test, from the other side) | +| 4c | destination `n.sv` already has one occurrence of the moved text **before** the edit; plan writes it once more / zero more / twice more | once → **accepted** (after = 2); zero → **rejected**, "never dropped"; twice → **rejected**, "never duplicated" — matches the spec exactly | +| 5 | `/* TODO: connect */` **genuinely inside the moved region** (not merely coincidentally generated text absent from the source), deleted once from `m.sv`, written **twice** into `n.sv` | **rejected**, "never duplicated" — rule 2's `generated()` whitelist (`check/ledger.rs:312`) exempts only the *per-file* duplicate rule; `Transit::lands` (rule 4, `check/ledger.rs:413`) has no such exemption and still catches it, because the piece is present in `sent` (it really was deleted from inside the source's region). The whitelist only ever "wins" for text that was never in transit at all (`a_generated_placeholder_the_new_file_writes_is_not_a_duplicate`, where the key never enters `sent`) | +| 6 | a **same-file** relocation: a piece outside the transit region, deleted at one position and written back at a different position in the *same* source file, alongside a legitimate cross-file move | **accepted — see Finding QA-1 below** | + +### Finding QA-1 (MEDIUM) — `positions_match` cannot see a same-file relocation expressed as ordinary edits, through the production entry point + +Item 6 of the brief expected `positions_match` to refuse this ("the per-file +rule accepts, but positions_match should refuse the relocation — confirm"). +It does not. Reproduction (temporary test, `check/mod.rs`, +`qa_a_same_file_relocation_outside_the_region_is_caught_by_positions_match`, +removed after): `m.sv` legitimately sends one comment to `n.sv` in transit, +and — unrelated, outside the region — deletes a second, distinct comment +`// stray` from one position and re-inserts identical text a few lines later +in `m.sv` itself, as two ordinary, well-formed, non-overlapping `TextEdit`s. +`verify_move` returns `Ok(())`. + +Why: `verify_move` (`check/mod.rs:194-203`) always computes the post-edit text +itself, as `apply(scope.text(*i)?, edits)` — no production caller (`verify_move`, +`extract_module`, `convert_to_ansi`, `ports::*`) ever hands the verifier an +independently-authored "after" text. `Split::positions_match` +(`check/ledger.rs:101-165`) builds its `expected` piece sequence by re-walking +the *same* `edits` list and interleaving their own declared `written` pieces — +which is a second, piece-level implementation of "apply the edits," not an +independent oracle. Since both `apply()` and `positions_match`'s +reconstruction agree by construction whenever the edits are individually +well-formed (sorted, non-overlapping), there is no discrepancy left for +`positions_match` to catch: the relocation *is* what the (valid) edits define, +and both edits are innocent-looking in isolation. + +This means the one existing test that demonstrates a positional rejection — +`check::ledger::tests::a_move_that_left_the_comment_where_it_was_is_rejected` +— is not reachable through `verify_move` at all. It calls the lower-level, +test-only `pieces_match(before, after, edits, …)` directly with an `after` +built by hand-editing the honestly-applied text with `.replace(...)` *beyond* +what `move_edits()` declares — a shape no real caller can produce, because +every real caller derives `after` from `apply()` over its own `edits`. + +Consequence for invariant 4: **Eq3 (`after == before - gone + wrote`, +`check/ledger.rs:325-339`) is in the same position.** None of the twelve +`verify_move` attack tests isolates it (see the equation map below), and by +the same reasoning it cannot be reached in production either — any test that +would need Eq3 to fire (an "applied text disagrees with what the edits' +own bookkeeping predicts") requires an independently-supplied `after`, which +`verify_move` never receives. Eq1 (grounded in the truly re-lexed `after` +text) is the actual backstop for content loss/gain in production; Eq3 adds +protection only against a divergence between `apply()`'s byte-level splice and +the ledger's own piece-level counting (e.g. malformed/overlapping edits from a +buggy future planner) — a scenario I attempted to construct (deliberately +overlapping edits, exploiting `apply()`'s documented silent-skip of an +overlapping edit) and could not turn into a case where Eq1 didn't already +catch the resulting loss first. + +**Severity and recommendation, not a redesign:** this is not a regression +from the rework (the same structure predates it, in the non-move +`pieces_match`/`Ledger` too) and no current planner (`extract`'s `flow.rs`/ +`boundary.rs`/`region.rs`, `ports::ansi`) produces an edit pair shaped like +this — `extract`'s only same-file, non-transit edits are the instantiation +replacement and, for `Home::SameFile`, one pure append. But per CLAUDE.md +invariant 4 ("any equation no test proves is a finding"), Eq3 and +`positions_match`'s value in the **move** context are currently unproven by +any attack that goes through a real entry point, and a future bug in a +planner (§53.2's inline, or a second consumer of `verify_move`) that computes +correct *counts* but a wrong *position* for a never-dropped piece within one +file would pass silently. Left to the dev/lead to decide whether a follow-up +test (or accepting the gap as documented, since position-correctness for +extraction is `region.span`'s job, not the verifier's) is warranted — not +blocking this pass. + +### Equation-to-test map (the twelve `verify_move` tests, `check/mod.rs`) + +| equation | proves it via | +| --- | --- | +| Eq1 `after_f + out_f ≥ before_f` | `a_copy_deleted_outside_the_region_is_not_one_the_move_may_balance` (QA's V1 pin), `a_deletion_wider_than_the_region_is_an_ordinary_deletion`, `a_region_that_does_not_cover_what_the_edits_delete_is_rejected`, and negatively via `the_widening_is_opt_in_…` (same equation, no `out` credit at all without `moving`) | +| Eq2 `wrote_f ≤ (gone_f − out_f) + in_f`, generated-exempt | `a_comment_that_lands_twice_in_the_new_file_is_rejected`, `a_comment_left_behind_as_well_as_moved_is_rejected`, `a_comment_the_new_file_invents_with_nothing_in_transit_is_rejected`; positively (whitelist) `a_generated_placeholder_the_new_file_writes_is_not_a_duplicate`; and, via the *old*, unwidened per-file path (a file `moving` does not name), `a_piece_in_transit_to_a_file_the_move_did_not_name_is_rejected` | +| Eq3 `after_f == before_f − gone_f + wrote_f` | **none of the twelve** — see Finding QA-1; empirically and structurally unreachable via `verify_move` today | +| Eq4 `Σ_dest(wrote−gone) == Σ_src out` (`Transit::lands`) | `a_comment_the_move_carries_that_lands_nowhere_is_rejected`, `an_attribute_the_move_carries_that_lands_nowhere_is_rejected` (`a_comment_that_lands_twice_…` and the third-file test are caught earlier, by Eq2, before `lands()` ever runs) | +| (positive control) | `the_move_the_engine_actually_produces_verifies` needs all four to pass at once | + +### The `kw` gate (V2) and the opentitan reproduction + +`region.rs::extractable` (`region.rs:106-115`) accepts only `"module"` / +`"macromodule"` and refuses `"interface"`/`"program"` with the documented +sentences; `Region::read` calls it right after `module_at`, and `extract_site` +goes through the same `Region`, so the action is not offered either. Both +pinned tests (`a_selection_inside_an_interface_or_a_program_is_refused`, +`the_action_is_not_offered_inside_an_interface_or_a_program`, +`tests/extract.rs`) re-read and re-run, green. `macromodule` itself had no +dedicated test before this pass; added one temporarily +(`module.kw == "macromodule"`, closes with `endmodule` — a `macromodule`'s +`end` keyword is `endmodule`, not `endmacromodule`, which is exactly the kind +of thing worth having pinned) and confirmed it extracts and is offered +identically to `module`; removed with the rest of the temporary tests since +it wasn't asked for as a permanent addition, but worth the dev adding as a +one-line permanent case given `macromodule` is the *other* accepted keyword +and had zero coverage. + +A nested `module` declared inside a `generate` block: `region.rs::module_at` +(`region.rs:82-94`) only scans the file's *top-level* items, one level, not +recursively into a module's own `items` or a `GenBlock`'s. Read through by +hand rather than tested: a selection actually inside such a nested +declaration is always caught by the existing whole-item/`extent` machinery +first — the enclosing `generate` item (or the nested module item itself) is +treated as one indivisible item wider than any inner selection, so the result +is a **safe refusal** ("cuts an item in half" or "a declaration of its own"), +never a silent misattribution to the wrong module. Cosmetic at worst (the +refusal's stated reason may not name the real cause); no correctness risk +found. + +**Opentitan reproduction** (scratch copy, `hw/ip/{aes,uart,spi_host,hmac}`, +237 files, opentitan at the checkout named in the README, copied to +`/private/tmp/.../scratchpad/ot_reattack` and pointed to via +`LUCISV_EXTRACT_ROOT`, deleted after): `tools/guard.sh -- cargo test -p +vlog_refactor --test corpus five_regions_of_real_rtl… -- --nocapture` prints +**5 extracted, 5 refused**, both `aes_masking_reseed_if.sv` and +`aes_reseed_if.sv` refused for being inside an `interface`, and every +extraction holds the census at **10614 → 10614** — matches the README's table +row for row. `git -C .../opentitan status --porcelain` unchanged before and +after (the same three pre-existing files named in the task brief). The +default corpus trial (`corpus/`, no env var) reproduces **5 extracted, 6 +refused**, census 10268 → 10268, also matching. + +### Gates (guarded) + +| Gate | Result | +| --- | --- | +| `cargo fmt -p vlog_refactor -- --check` | clean | +| `cargo clippy --all-targets` | clean, no new `#[allow]` | +| `cargo test -p vlog_refactor -p lucisv_server` | all green | +| `cargo test --workspace` | **4081 passed, 0 failed, 44 ignored** — matches the dev's claim exactly (measured as 4090/44/0 with 9 temporary QA tests still in place, all of which also passed; 4090 − 9 = 4081) | +| opentitan extraction trial (scratch, 237 files) | 5 extracted, 5 refused, census 10614 → 10614, opentitan checkout untouched | +| corpus extraction trial (860 files) | 5 extracted, 6 refused, census 10268 → 10268 | + +All temporary tests removed before finishing (`check/mod.rs` back to 1025 +lines; `tests/extract.rs` has no `qa_`-prefixed test remaining); both files +remain the dev's own untracked additions, `git status --porcelain` confirms +no other tracked file was touched by this pass. + +### Verdict: **PASS** + +Both HIGH findings from the first QA pass are fixed and hold up under +re-attack through the real production entry point: + +1. **V1** (the pooled ledger) — confirmed fixed. All twelve attack pairs, + including two-source/one-destination sums, crosswise misdirection, empty + and duplicated `moving` entries, pre-existing destination content, and the + `generated` whitelist's interaction with the cross-file `lands` rule, come + out exactly as the equations promise. +2. **V2** (the `kw` gate) — confirmed fixed, including the opentitan + regression it was written against; `macromodule` (the gate's other accept + arm) checked too and found sound, just untested until now. + +One new, non-blocking finding (**QA-1, MEDIUM**): `positions_match`, and by +the same reasoning Eq3, provide no protection against a same-file relocation +of a never-dropped piece expressed as two well-formed edits, because in +production `after` is always internally derived from the very edits being +checked — this is pre-existing crate structure, not something the rework +introduced, and no current planner produces this shape, but it means neither +equation is currently *proven* by any attack that goes through a real entry +point. Left to the dev/lead as a documentation note or a follow-up test, not +a blocker. + +## Review + +**2026-09-06 — lead.** 53.1 accepted after one rework; ships in 0.47.0 +with §52. 53.2 is unstarted and runs as its own lane after §56, as the +plan allowed — a finished half over two unfinished ones. The dataflow rule +is the right reading (a routine argument refuses rather than guesses; a +positional or `.*` connection refuses), the new-file path reads both +halves of the client capability, and the naming flow goes through the +language client's middleware rather than a second command registration. +The two trial-found defects (a parameter named only by a port's type; a +header `import` recorded as `p::*`) are exactly why the trials assert on +the unresolved-name census and not on a parse. QA's two HIGHs were both +real: a whole-file pool balanced an unrelated deletion against a +duplicate write, and one AST node for `module`/`interface`/`program` let +an interface body extract. The rework binds the pool to the moved bytes — +four equations, twelve attack pairs through the production entry, the +opentitan trial reproducible file by file with the census held — and +QA's re-attack found only a MEDIUM that predates this lane (a same-file +relocation of a never-dropped piece written as two well-formed edits is +not caught, and equation 3 is unreachable through any real caller); no +planner produces that shape, so it is filed as topo §2.9-32 for a later +round rather than widened here. + +*(empty — for the lead)* diff --git a/docs/site/dist/pagefind/fragment/en_1a2f59a.pf_fragment b/docs/site/dist/pagefind/fragment/en_1a2f59a.pf_fragment deleted file mode 100644 index 37d0f04aecd6c47a2f7dff64ab5437838f1586b7..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2714 zcmV;L3T5>liwFP!00002|CLx>ZXCH0z6vo<_F{f)?IzAjPl_zZLX=%a@~$6(z~OXr zy1Bz9J0x49iD4jz$Q^Qz93>~oS4H;Ej3uuF!@#JEtpEC|imj~FM%(g3S(G1Voj0@7 z*~+Vp^2!!!Wu&b-99cx?Ojyn4v%=Y^Y{aqaOcP97iVN4YMnxqG*~+yxI_?EHtB0j{ zS1S>ezgJ#_R>^G;Axc|HUyAFy8{wD`OYN58jgqnRDhTP7D3#ausuUaV8sV%0zeS@O z=l7y?Mb|(PzHH=v4grm{Q5T|dr80AzElgJ`QF+h}7+LhvcEu+v8qM_dFUjFo2R1dKytfquF{5yyUM{GJ{#JbzS z$6}{rEn4q>QAJ!SDC6J=#h2jGTXrjDus z^B?UZ?%OZ0clI6VZyvEiZitUnJEIX3@*RAy;VEZD^t!5)5B+I`O$2$bj+pPXF?aa< zUh4Q0qGn*NLf~!S(~GDZCCDK`>}q9&dT5O;t z*|DcWPtM%?hvwSGi3y#5~a?G0gzdQs9Mp;!aGVkX#>0S501*HB(&6z$c`r?;k|_YnH6;jZO?ii8 zpxacMBx^wVW9kSh#G=;9OJCHQjB#D0N?wZhgGB?!!N^s}Z0;0YgmTdHpsYkWB6n~OiMaEOMa9RJY?^&&kHOd{3w>V$caoKE(E`@#wZ&;gXmIS^XF8GNnJ3Y0*^XXeE~4Y?v+Ib%?m)_5Xn7y z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esxh{Ajf{1&pNYCv8=wO&b3 zPU9Q`-;~)&XY-;E4{Vdj0pCLro}^Q@(T1iuz<7T_4$4G!XC8tY2;4`bVsfDk z7ersBzRd~kM1d6N47KhIOQhqO;t+c-Z%|T5$lX`T=5m^={4?9P3stq?9M7-}shX;O z4_(IpIy@X@O)=@Q3U)L5pU4*qde2hy7>3_YR-rxmd+Ao8#8Fr%I9nIZa*nt4)$D?) zjh3ux!fVr){RzC~I4T7xm0~a@PDqrym#lUvsb1#n0$}Q&m2V-K)ivS1mls)F17dX45f zeyj<^YwV6Z8j6eJ?Az2(AEO4fomhn_Ch~9NE=w3^Fi{VW*ic;@jK5dD#kr^KRSL43 zsC@K-t>2=f;?Q}v@M!IBf2txGLs9t?+Dh5e5Ff>Bu?agoiOBgi6MG)on>lbOap)sL zgJW}bg)NBOE9GNTc)29il*g2Rg`;P5CG?7Rktzi#K)NgdU(z`{LHgXErT~rO28U*Z znM~H^G8Pzc$P-D!vi+z>#TpZx>gsp=60^w%!Kd>p_R8v<&>fitqMN$%Us7a3K|v^k!`W| zL3@gSC2Fc|OkA+~i}+E}$s#e18YJZky(EuTSiw1p@S|JD7&1$uaO+tplYYHWP_Zap z8j@AAFF`m(bkx|t+)wezhggZ!L}q<4)sRm!?hH7C(9vt9p%Rh>QI*ioP5Sac)o ziPH0OQTzr+80u7Xv#jNX{&E11+C!p|d=>=)?H}k9c5D0rED8;<`EHYh*rF)WJj|9L zdI*DMfp&OZs)mhHF zEaopiK&EA?#`~^icQs9T-zLdoC3Nw6%5+8nkntcn!L6y+<$DNe?V=X=W*dAPo?!*X zVwe*`&3FwwCK9|m5Ds%-7q>sGjM$NIu<}!}`%Qd5-W~jrF&2>L@QK2uV>O`S>4oLF qY!I-;`G6O5Z9dggqEr>WggEpxB8?EqV#txx%l`*JWiSk$4gmoDbohG! diff --git a/docs/site/dist/pagefind/index/en_72ebf93.pf_index b/docs/site/dist/pagefind/index/en_72ebf93.pf_index new file mode 100644 index 0000000000000000000000000000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-entry.json index 3f66f9e..6f00512 100644 --- a/docs/site/dist/pagefind/pagefind-entry.json +++ b/docs/site/dist/pagefind/pagefind-entry.json @@ -1 +1 @@ -{"version":"1.5.2","languages":{"en":{"hash":"en_fc49ef3316","wasm":"en","page_count":12}},"include_characters":["_","‿","⁀","⁔","︳","︴","﹍","﹎","﹏","_"]} \ No newline at end of file +{"version":"1.5.2","languages":{"en":{"hash":"en_63f86fa784","wasm":"en","page_count":12}},"include_characters":["_","‿","⁀","⁔","︳","︴","﹍","﹎","﹏","_"]} \ No newline at end of file diff --git a/docs/site/dist/pagefind/pagefind.en_63f86fa784.pf_meta b/docs/site/dist/pagefind/pagefind.en_63f86fa784.pf_meta new file mode 100644 index 0000000000000000000000000000000000000000..9baceaa458f49be21cc11e2364ed6fd71ab343c1 GIT binary patch literal 223 zcmV<503iP#iwFP!00002|0U1CYQr!L24Irz5yq$=V#T)XB);svrwFno7nd#@B(au-W*H{XFe>=#39xyi-*xgbX&3SF1;1 z2td}r`cIT}wu@DL7W$4GaBlr8axr(&p{m}6xk&~ztLjIHuCsobt{#Mqv6hKd{d~LB zk^uwi?n%ginmnoca(mk(#N^fe`81=BlTr1rRuG%gbp- diff --git a/docs/site/dist/reference/language-tools/index.html b/docs/site/dist/reference/language-tools/index.html index 66451a5..78b0495 100644 --- a/docs/site/dist/reference/language-tools/index.html +++ b/docs/site/dist/reference/language-tools/index.html @@ -297,6 +297,11 @@ index scope when the defining module lives outside the default folder scope.

Removes the import pkg::*; lines nothing in the scope reaches through, merges exact duplicates and sorts the run at the top of a module, package or class; refuses rather than guesses wherever a macro, a conditional directive, an unknown package or a base class in another file could hide a use — lucisv.organizeImports +Extract module +code action (refactor.extract) / command +Select whole module items and name the module: ports and parameters inferred from what the selection reads and drives, imports carried across, the items moved byte for byte, the replacing instantiation rendered from the new module’s own text; a new file where the editor can create one, below the source module otherwise. Refuses with a sentence wherever a direction cannot be known — lucisv.extractModule + + Instantiate module inline completion / lucisv.instantiate Builds an instance from an indexed module interface, including in clients without ghost text @@ -347,4 +352,4 @@ index scope when the defining module lives outside the default folder scope.

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

- \ No newline at end of file + \ No newline at end of file diff --git a/docs/site/dist/reference/rules/index.html b/docs/site/dist/reference/rules/index.html index 97ccc5f..bc3790c 100644 --- a/docs/site/dist/reference/rules/index.html +++ b/docs/site/dist/reference/rules/index.html @@ -757,4 +757,4 @@

Reports a ; written after a `uvm_* macro invocation. The macros expand to a begin … end, so the ; is a null statement — usually inert, and not after if (x) uvm_info(…); else …, where the elsethen belongs to nothing. Off by default in both, because the semicolon is written everywhere in existing UVM code. No fix: deleting it is exactly the edit that is unsafe in the shape the rule exists for. Verible'suvm-macro-semicolon`, same default.

Reports a bare begin … end written directly inside a generate … endgenerate with no if, for or case around it. It opens an unnamed generate block — an invented path segment that renumbers when a block is added above it — and buys nothing, because the region is already a scope. Read from the same recovered block module-begin-block reads, one scope in. Verible’s v2001-generate-begin, same default.

- \ No newline at end of file + \ No newline at end of file diff --git a/docs/site/src/content/docs/reference/language-tools.md b/docs/site/src/content/docs/reference/language-tools.md index b962971..c4ed02c 100644 --- a/docs/site/src/content/docs/reference/language-tools.md +++ b/docs/site/src/content/docs/reference/language-tools.md @@ -70,6 +70,7 @@ index scope when the defining module lives outside the default folder scope. | 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`; 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` | | Organize imports | code action (`source.organizeImports`) / command | Removes the `import pkg::*;` lines nothing in the scope reaches through, merges exact duplicates and sorts the run at the top of a module, package or class; refuses rather than guesses wherever a macro, a conditional directive, an unknown package or a base class in another file could hide a use — `lucisv.organizeImports` | +| Extract module | code action (`refactor.extract`) / command | Select whole module items and name the module: ports and parameters inferred from what the selection reads and drives, `import`s carried across, the items moved byte for byte, the replacing instantiation rendered from the new module's own text; a new file where the editor can create one, below the source module otherwise. Refuses with a sentence wherever a direction cannot be known — `lucisv.extractModule` | | 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 | diff --git a/docs/topo.md b/docs/topo.md index 5cb118d..32eae1e 100644 --- a/docs/topo.md +++ b/docs/topo.md @@ -125,6 +125,7 @@ what a change on the pointed-to side must not silently break. | `vlog_refactor ──▶ vlog_semantic` (organize-imports) | depends | `imports::{import_usage, import_scopes, unused_imports, PackageExports, Exports}` — the one "is this import used" judgement, shared with the linter (§52, 2026-09-05). | | `vlog_linter ──▶ vlog_semantic` (organize-imports) | depends | the same `imports::*` judgement behind the `unused-import` rule; `MentionOracle::package_exports` is a new default method, so no implementor broke (§52). | | `lucisv_server ──▶ vlog_semantic` (organize-imports) | depends | `WorkspaceIndex::reexported_packages`, read by `lucisv_server::imports` to close the file set over re-exports (§52). | +| `lucisv_server ◀── vlog_refactor` (extract-module) | depends | `RefactorEdit::created` — the files an edit creates, read by `lucisv_server::extract` to emit `CreateFile` document changes when `ClientAbilities::create_files` (read at `initialize`: `workspace.workspaceEdit.documentChanges` + `resourceOperations: create`) allows, else the same-file fallback (§53.1, 2026-09-06). | | `vlog_refactor ──▶ vlog_parser` | depends | `tokenize`, `parse_source_tolerant` + diagnostics, `LineIndex`, `TextRange`, the port/instantiation/module AST shapes, `token::is_keyword` (new-name validity), `defines` via the index. Every edit span originates in a parsed node — no textual search-and-replace. | | `vlog_refactor ──▶ vlog_semantic` | depends | `Semantics` queries (`symbol_at`, `references_of`, `reference_id_at`, …), `Resolution` variants (three of them are refusal rules), `WorkspaceIndex` + `resolve_external` + `ExternalTarget`, and the exactness promise on `name_span` (re-checked before each edit is emitted). One historical exception: refactor-rename added `Target::Declaration` + end-label uses *into* `vlog_semantic` (lead-authorized, additive — see §2.6). | | `lucisv ──▶ lucisv_core` | depends | `config::{FileConfig, Discovery}` (lucisv.toml discovery — `config::parse` is reached through `Discovery`, not called directly), `walk::{collect_files, EXTENSIONS}` (the `.gitignore`/`--exclude` walk), `filelist::read` (`-f`), `cache` (the format cache), `atomic::write_atomic` (formatter and lint-fix replacement). (`walk::is_excluded` is `pub` but currently has no consumer outside the crate.) | @@ -666,6 +667,7 @@ update the filing README(s) and this file. | ~~29~~ | ~~An unknown rule name in the **editor's** `lucisv.lint.select`/`ignore` is still dropped silently, while §42 logs the same mistake in a project file (and `lucisv.lint.options` logs its bad entries). Wants the same once-only log through `notification.rs`.~~ — **delivered 2026-09-05 by small-items-4 (TODO §45.1):** `settings::rules` records every dropped name in `ClientSettings::lint_name_warnings` as `lucisv.lint.: unknown rule: `; `apply_settings` logs what the previous settings value did not already say — once per (setting, name), re-armed by a changed list. | lint-config-contract (QA) | lucisv_server | | ~~30~~ | ~~**An unreadable directory aborts the whole walk.** `Walk::dir` propagates `read_dir`'s error with `?`, so one permission-denied directory anywhere under the start — reachable now that a symlink to an outside directory is followed once (§2.9-8's ruling) — drops every file already found and fails the run. Found by walk-cycles' QA on a link to `/`. Wanted: skip the directory and say so through a warning channel the walk does not have today (the filelist-missing-file precedent), which is also where a dangling source link's warning belongs.~~ — **delivered 2026-09-05 by small-items-4 (TODO §45.2):** `walk::collect_files` takes a `&mut dyn FnMut(Warning)` sink; an unreadable directory, an unreadable `.gitignore` and a dangling source link are warned about (`warning: : ` on the CLI's stderr before the report, exit code unchanged; logged once per scan by the server through `report_scope`) and the walk continues. | walk-cycles (QA) | lucisv_core / lucisv / lucisv_server | | 31 | **DPI-export name binding remains open.** Package re-export resolution closed §2.9-16, but the name in a DPI export is still not a semantic reference. Keep this separate from the delivered package-member traversal. | dpi-export request (b); package-reexports | vlog_semantic | +| 32 | **The refactoring verifier does not catch a same-file relocation of a never-dropped piece written as two well-formed edits** (delete here, insert there): `verify_move` computes `after` by applying the edits, so `positions_match`'s reconstruction cannot diverge from it and equation 3 of the ledger is unreachable through any real caller. No planner produces the shape today. Wanted: an independent `after` (the client's applied text, or a second reconstruction) and a test that isolates equation 3. Found by extract-module's QA re-attack. | extract-inline-module (QA) | vlog_refactor | --- diff --git a/editors/vscode/extension.js b/editors/vscode/extension.js index 9cc055a..1dd84f6 100644 --- a/editors/vscode/extension.js +++ b/editors/vscode/extension.js @@ -13,6 +13,7 @@ const path = require('path'); const vscode = require('vscode'); const { LanguageClient, ProposedFeatures, TransportKind } = require('vscode-languageclient/node'); const { createRestarter } = require('./restart'); +const { executeCommand } = require('./extract'); const { HierarchyView } = require('./hierarchyView'); /** The single client, kept only so `deactivate` can stop it. */ @@ -187,6 +188,24 @@ function activate(context) { // still request a snapshot, but receive no unsolicited lucisv traffic. hierarchyView: true, }, + // The one place this extension steps between a server command and the + // server. `lucisv.extractModule` needs a name for the new module and LSP + // has no prompt, so the server's code action carries the command with a + // default name and this asks the user for a better one before it goes out + // (docs/features/extract-inline-module/README.md). Every other command + // passes through untouched. It has to be middleware rather than a command + // of our own: the language client registers every command the server + // advertises, so a second registration of the same id would collide with + // it at activation. + middleware: { + executeCommand: (command, args, next) => + executeCommand( + { showInputBox: (options) => vscode.window.showInputBox(options) }, + command, + args, + next, + ), + }, }; client = new LanguageClient('lucisv', 'lucisv', serverOptions, clientOptions); diff --git a/editors/vscode/extract.js b/editors/vscode/extract.js new file mode 100644 index 0000000..aca0279 --- /dev/null +++ b/editors/vscode/extract.js @@ -0,0 +1,74 @@ +// The one thing "extract into module" needs that LSP has no request for: +// asking the user what to call the new module. +// +// The server offers the code action with a `Command` rather than an edit — +// `lucisv.extractModule [uri, range, defaultName]` — precisely so a client can +// step in between the click and the edit. This file is that step. +// +// **Through the language client's middleware, not through a second command.** +// `vscode-languageclient` registers every command the server advertises in +// `executeCommandProvider` with `vscode.commands.registerCommand`, so an +// extension that registered `lucisv.extractModule` itself would collide with +// it at activation. `middleware.executeCommand` is the seam the client provides +// for exactly this: it sees the command on its way out, may change the +// arguments, and hands them to `next`. One command id, one server contract, +// and every other client — Vim, a CLI — runs the same command with the default +// name and gets the same edit. +// +// Nothing here knows about `vscode`: the dependencies come in as an object, so +// `extract_test.js` drives the whole flow headlessly. +// See docs/features/extract-inline-module/README.md. + +/** The command the server's code action carries. */ +const EXTRACT_MODULE = 'lucisv.extractModule'; + +/** + * A plain SystemVerilog identifier, which is the only thing the engine will + * name a module — and a file — with. Checked here as well as in the engine so + * the user is told while the box is open rather than by an error afterwards. + */ +const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_$]*$/; + +/** + * What the input box says about what has been typed so far, or `undefined` + * when it is a name lucisv would accept. + * + * The message is the one the engine would refuse with, in the present tense: + * an editor's validation is read while typing, not after. + */ +function validateModuleName(value) { + const name = (value || '').trim(); + if (name === '') return 'The new module needs a name.'; + if (!IDENTIFIER.test(name)) { + return 'A module name is a plain SystemVerilog identifier: a letter or `_`, then letters, digits, `_` or `$`.'; + } + return undefined; +} + +/** + * The language client's `executeCommand` middleware. + * + * - `deps.showInputBox` — `vscode.window.showInputBox`, which resolves to the + * typed string or to `undefined` when the user pressed Escape. + * - `command`, `args`, `next` — what the client hands every middleware. + * + * Every command but this one goes straight through. This one asks for a name, + * and a cancelled box resolves to `undefined` without ever reaching the + * server: an extraction nobody named is one nobody asked for. + */ +async function executeCommand(deps, command, args, next) { + if (command !== EXTRACT_MODULE) return next(command, args); + const [uri, range, suggested] = args || []; + const name = await deps.showInputBox({ + title: 'Extract into module', + prompt: 'Name for the new module', + value: typeof suggested === 'string' ? suggested : '', + validateInput: validateModuleName, + }); + if (name === undefined) return undefined; + const trimmed = name.trim(); + if (validateModuleName(trimmed) !== undefined) return undefined; + return next(command, [uri, range, trimmed]); +} + +module.exports = { EXTRACT_MODULE, executeCommand, validateModuleName }; diff --git a/editors/vscode/extract_test.js b/editors/vscode/extract_test.js new file mode 100644 index 0000000..ff943ad --- /dev/null +++ b/editors/vscode/extract_test.js @@ -0,0 +1,137 @@ +// Checks for `extract.js`: the input box that names the module the server is +// about to extract, and what it does when the user does not name one. +// +// node extract_test.js +// +// Exits 0 on success, 1 on any failure. Plain node, no dependencies and no +// test runner — the same style as `restart_test.js` next to it. +// +// The fakes below script only what `extract.js` is allowed to depend on: an +// input box that resolves to a string or to `undefined`, and a `next` that +// records what it was handed. Nothing here re-implements VS Code. +// See docs/features/extract-inline-module/README.md. + +const { EXTRACT_MODULE, executeCommand, validateModuleName } = require('./extract'); + +let checks = 0; + +function ok(condition, what) { + checks += 1; + if (!condition) fail(what); +} + +function equal(got, want, what) { + checks += 1; + const a = JSON.stringify(got); + const b = JSON.stringify(want); + if (a !== b) fail(`${what}: got ${a}, want ${b}`); +} + +function fail(message) { + console.error(`extract: FAIL — ${message}`); + process.exit(1); +} + +/** A `next` that records every call and answers with a marker. */ +function recorder() { + const calls = []; + const next = (command, args) => { + calls.push({ command, args }); + return Promise.resolve('applied'); + }; + return { calls, next }; +} + +/** An input box that answers `answer` and records the options it was given. */ +function box(answer) { + const seen = []; + const showInputBox = (options) => { + seen.push(options); + return Promise.resolve(answer); + }; + return { seen, showInputBox }; +} + +const ARGS = ['file:///rtl/m.sv', { start: { line: 6 }, end: { line: 6 } }, 'm_extracted']; + +async function aNameTypedIntoTheBoxReachesTheServer() { + const { calls, next } = recorder(); + const { seen, showInputBox } = box('adder'); + const result = await executeCommand({ showInputBox }, EXTRACT_MODULE, ARGS, next); + equal(result, 'applied', 'the server’s answer comes back to the client'); + equal(calls.length, 1, 'the command is sent once'); + equal(calls[0].command, EXTRACT_MODULE, 'under its own name'); + equal(calls[0].args[0], ARGS[0], 'the uri is passed through'); + equal(calls[0].args[1], ARGS[1], 'and so is the range'); + equal(calls[0].args[2], 'adder', 'the typed name replaces the default'); + equal(seen.length, 1, 'one box is shown'); + equal(seen[0].value, 'm_extracted', 'prefilled with the default the server proposed'); +} + +async function surroundingWhitespaceIsTrimmedOffTheName() { + const { calls, next } = recorder(); + const { showInputBox } = box(' adder\t'); + await executeCommand({ showInputBox }, EXTRACT_MODULE, ARGS, next); + equal(calls[0].args[2], 'adder', 'a name is what is left after the spaces'); +} + +async function anEscapedBoxSendsNothingAtAll() { + const { calls, next } = recorder(); + const { showInputBox } = box(undefined); + const result = await executeCommand({ showInputBox }, EXTRACT_MODULE, ARGS, next); + equal(result, undefined, 'a cancelled extraction answers nothing'); + equal(calls.length, 0, 'and reaches the server not at all'); +} + +async function aNameTheEngineWouldRefuseIsNotSentEither() { + // The box's own validator should stop this, but a client that ignores + // `validateInput` must not get a file called `2fast.sv` out of it. + for (const typed of ['', ' ', '2fast', 'with space', '\\odd-name']) { + const { calls, next } = recorder(); + const { showInputBox } = box(typed); + const result = await executeCommand({ showInputBox }, EXTRACT_MODULE, ARGS, next); + equal(result, undefined, `\`${typed}\` is not a module name`); + equal(calls.length, 0, `\`${typed}\` never reaches the server`); + } +} + +async function everyOtherCommandGoesStraightThrough() { + const { calls, next } = recorder(); + let shown = 0; + const showInputBox = () => { + shown += 1; + return Promise.resolve('never'); + }; + const args = ['file:///rtl/m.sv', { line: 3, character: 0 }]; + const result = await executeCommand({ showInputBox }, 'lucisv.organizeImports', args, next); + equal(result, 'applied', 'the other commands answer as they always did'); + equal(shown, 0, 'and no box is shown for them'); + equal(calls, [{ command: 'lucisv.organizeImports', args }], 'passed through unchanged'); +} + +function theValidatorSaysWhatTheEngineWouldSay() { + equal(validateModuleName('adder'), undefined, 'a plain identifier is fine'); + equal(validateModuleName('_adder$2'), undefined, 'so are `_`, digits and `$` after the first'); + ok(validateModuleName('').includes('needs a name'), 'an empty box says so'); + ok(validateModuleName(' ').includes('needs a name'), 'and so does a blank one'); + ok(validateModuleName('2fast').includes('plain SystemVerilog identifier'), 'a leading digit'); + ok(validateModuleName('a b').includes('plain SystemVerilog identifier'), 'a space'); + ok(validateModuleName('\\odd-name').includes('plain SystemVerilog identifier'), 'an escaped name'); +} + +async function main() { + const watchdog = setTimeout( + () => fail('timed out after 5s — a promise this test waits on never settled'), + 5000, + ); + theValidatorSaysWhatTheEngineWouldSay(); + await aNameTypedIntoTheBoxReachesTheServer(); + await surroundingWhitespaceIsTrimmedOffTheName(); + await anEscapedBoxSendsNothingAtAll(); + await aNameTheEngineWouldRefuseIsNotSentEither(); + await everyOtherCommandGoesStraightThrough(); + clearTimeout(watchdog); + console.log(`extract: OK — ${checks} checks over the extract input box`); +} + +main().catch((error) => fail(error.stack || String(error)));