From e1679bebc5ff0beadfad96e68580c245de54fabf Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Sun, 6 Sep 2026 21:04:05 -0500 Subject: [PATCH] Inline module: a module's body copied into its instantiator with ports and parameters substituted, and a verifier that knows a copy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TODO §53.2 (docs/features/extract-inline-module), the fifth §8 refactoring; extract → inline round-trips byte-equal after formatting. `vlog_refactor::inline_module` (inline/{mod,site,source,render}.rs): every symbol bound in `S`'s module scope is classified once — a port becomes the name or literal connected to it, anything else `S` declares at module scope is prefixed `u_S_` only when `M`'s file already spells one of them; parameters become `localparam`s with the override or default; the body is copied verbatim except name spans, with `.name` shorthand connections expanded when their signal is renamed. Refusals: `.*`, positional lists, expression connections, an unconnected port, an output into a literal, any hierarchical reference to `u_S` in the handed files, `S` unknown/twice/in `M`'s own file, interface/`inout`/unpacked/ non-ANSI ports, `initial`/`final`, macros, directives, any `generate`, a differing `timescale`, collisions prefixing cannot resolve. Server: `refactor.inline` lazy action, `lucisv.inlineModule`. Verifier: `Moving` gains `Origin::{Moved, Copied}` — a copied region's pieces join the transit under rule 0, "a copied file appears in no edit"; eight attack pairs through the production entry; QA's neutering map shows every rule load-bearing. QA's MEDIUMs filed: topo §2.9-32 (same blind spot) and §2.9-33 (`module_sources` lacks a transitive- instantiators rung). Trials: corpus 5 inlined / 9 refused, opentitan 5 / 56, the lint census 0 → 0 on every pair. 0 of 854 corpus files differ from 0.48.x. Co-Authored-By: Claude Fable 5.1 --- CHANGELOG.md | 22 + TODO.md | 43 +- crates/lucisv_server/src/inline_module.rs | 249 ++++++ crates/lucisv_server/src/main.rs | 3 + crates/lucisv_server/src/server/dispatch.rs | 19 +- crates/vlog_refactor/src/check/ledger.rs | 63 +- crates/vlog_refactor/src/check/mod.rs | 244 ++++- crates/vlog_refactor/src/extract/mod.rs | 9 +- crates/vlog_refactor/src/inline/mod.rs | 371 ++++++++ crates/vlog_refactor/src/inline/render.rs | 419 +++++++++ crates/vlog_refactor/src/inline/site.rs | 217 +++++ crates/vlog_refactor/src/inline/source.rs | 322 +++++++ crates/vlog_refactor/src/lib.rs | 2 + crates/vlog_refactor/tests/corpus.rs | 233 +++++ crates/vlog_refactor/tests/inline.rs | 604 +++++++++++++ docs/features/extract-inline-module/README.md | 840 +++++++++++++++++- docs/topo.md | 1 + editors/vscode/CHANGELOG.md | 6 + 18 files changed, 3619 insertions(+), 48 deletions(-) create mode 100644 crates/lucisv_server/src/inline_module.rs create mode 100644 crates/vlog_refactor/src/inline/mod.rs create mode 100644 crates/vlog_refactor/src/inline/render.rs create mode 100644 crates/vlog_refactor/src/inline/site.rs create mode 100644 crates/vlog_refactor/src/inline/source.rs create mode 100644 crates/vlog_refactor/tests/inline.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index e0f7ffc..86d4e01 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,28 @@ All notable changes to lucisv are recorded here. Versions follow [semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes (see `README.md`) are the only frozen contract. +## 0.49.0 — 2026-09-06 + +### Inline module; the last coverage gaps + +- **Inline module.** With the cursor on `S u_S (...)`, `S`'s body is + copied into the instantiating module: ports replaced by the connected + names or literals, parameters as `localparam`s with the override or + default, internal names prefixed `u_S_` only where the file already + spells one of them, comments and attributes carried verbatim, `.name` + shorthand connections inside the body expanded when their signal is + renamed. Refuses — with a sentence — a `.*` or positional list, an + expression connection, an unconnected port, an output into a literal, + any hierarchical reference to the instance, a `generate`, `initial`/ + `final`, macros, directives, interface/`inout`/unpacked ports, and a + module declared in the same file. `refactor.inline` action, + `lucisv.inlineModule`. Extract → inline round-trips byte-equal after + formatting. +- **The verifier learns a copy.** A copied region's comments and + attributes may be written once per copy in the destination while the + copied file must appear in no edit at all; attack tests through the + production entry, re-attacked by QA. + ## 0.48.2 — 2026-09-06 ### The 0.48.0 packages, rebuilt from the right commit diff --git a/TODO.md b/TODO.md index daec441..41d7c6d 100644 --- a/TODO.md +++ b/TODO.md @@ -5282,15 +5282,20 @@ imports copied into `M` if `M` lacks them. - [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**; §53.1 alone took the round -- [ ] the extract → inline round trip pinned — blocked on 53.2 +- [x] 53.2 inline: substitution, prefixing, refusals, action + command +- [x] the extract → inline round trip pinned - [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 +- [x] 53.2 QA: the substitution attacked (every position a port name can + appear in), the `.name` shorthand and `.*` inside `S`, the + prefixing rule and its collisions, every refusal, the copy + allowance's attack table re-attacked, the round trip, corpus and + opentitan scratch trials — PASS, two MEDIUM findings (QA-2, QA-3), + see the feature README's QA log ## 54. Coverage gaps L3, L6, L10 (planned 2026-09-06) — the owner's "do all three" @@ -5444,3 +5449,35 @@ the existing bookmark does (`hierarchyView.js` `BOOKMARK_KEY`). view pinned unchanged - [x] QA: every section shape attacked on the fixture and on opentitan (real snapshot, read-only); persistence; the setting; menus + +## 57. Final cleanup and closing release (owner's end goal, 2026-09-06) + +After §53.2 and §54 merge and 0.49.0 ships, the last lane of loop 2 is the +lead's own, no dev/QA: + +- [ ] **Tree:** `git status --porcelain` empty; `git worktree list` shows + the main tree only; `git branch` shows `master` only; no local tag + that is not on the server; no stray files in the tree + (`corpus-check-results.tsv` is ignored — fine); the scratchpad and + `~/.cache/lucisv-baselines/wip-*` snapshots deleted. +- [ ] **Remote:** `master` pushed and equal to local; every release tag + on the server; every release with 8 assets; the published vsix of + the final release unzipped and checked for the feature files of + loop 2 (`hierarchySections.js`, `extract.js`, no `*_test.js`). +- [ ] **TODO.md:** every checkbox either ticked or annotated with a + dated ruling (deferred to whom, or dropped why); the "Loop 2 order" + section closed with what shipped in which release; §44/§55 and the + topo §2.9 open rows (23 done; 29/30 done; 31 DPI export, 32 the + verifier same-file relocation) restated in one "open items" list + for loop 3. +- [ ] **Docs:** `docs/topo.md` rows for every loop-2 lane present; + `docs/coverage_gaps.md` struck where delivered; CLAUDE.md's + measurement line refreshed (`state.rs` 957 lines → whatever §55 + leaves it; if §55 does not run, the number and the reason); + `docs/manual-acceptance.md` rows through §56; the site rebuilt and + committed. +- [ ] **Memory:** the paused-state memory rewritten as a short current + state (not a running log), with the release list and the open items. +- [ ] **Closing release:** if anything above changed a shipped file + (docs count), a final release `0.49.x`/`0.50.0` cut from the clean + tree, its assets verified, and the install line given to the owner. diff --git a/crates/lucisv_server/src/inline_module.rs b/crates/lucisv_server/src/inline_module.rs new file mode 100644 index 0000000..1eaa6af --- /dev/null +++ b/crates/lucisv_server/src/inline_module.rs @@ -0,0 +1,249 @@ +//! Inline a module at the cursor, on the wire: `textDocument/codeAction` under +//! LSP's own `refactor.inline`, and `workspace/executeCommand` for the editors +//! that have no lightbulb. +//! +//! Protocol only. The edit is `vlog_refactor::inline_module`; this module +//! decides which files that engine is handed, turns its answer into a +//! `WorkspaceEdit` and its refusal into a request error. +//! +//! **The action carries a command, not an edit**, for the same reason the +//! extraction's does — laziness rather than a prompt. Answering "what would +//! inlining `S` here look like" means reading `S`'s file, every file that +//! spells it, and analyzing all of them; a `textDocument/codeAction` arrives +//! on every cursor move. So the offer is one parse of one buffer +//! (`vlog_refactor::inline_site`) plus a `Command` naming [`INLINE_MODULE`], +//! and the workspace is not touched until the user picks the action. See +//! `docs/features/extract-inline-module/README.md`. + +// 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, Position, Range, Uri, WorkspaceEdit, +}; +use serde_json::Value; + +use crate::state::Workspace; + +/// Inline the module instantiated at a position: `[uri, position]`. +pub const INLINE_MODULE: &str = "lucisv.inlineModule"; + +/// Every command this module executes. +pub fn commands() -> Vec { + vec![INLINE_MODULE.to_string()] +} + +/// The kind LSP reserves for an inline, which is what an editor's "Refactor…" +/// menu asks for by name. +pub fn kind() -> CodeActionKind { + CodeActionKind::REFACTOR_INLINE +} + +/// The action for the cursor, carrying the command that does the work. +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 path for the engine's file set; nothing + // is offered rather than offered and refused. + return Vec::new(); + } + let offset = doc.positions().offset(range.start); + let Some(site) = vlog_refactor::inline_site(&doc.text, offset) else { return Vec::new() }; + let arguments = vec![ + serde_json::to_value(uri).unwrap_or(Value::Null), + serde_json::to_value(range.start).unwrap_or(Value::Null), + ]; + let title = vlog_refactor::inline_title(&site.module); + vec![CodeActionOrCommand::CodeAction(CodeAction { + title: title.clone(), + kind: Some(kind()), + command: Some(Command { + title, + command: INLINE_MODULE.to_string(), + arguments: Some(arguments), + }), + ..Default::default() + })] +} + +/// Run `lucisv.inlineModule`, or say why it cannot run. +pub fn execute( + ws: &Workspace, + arguments: &[Value], +) -> Result<(WorkspaceEdit, Vec), String> { + let uri: Uri = argument(arguments, 0, "a document URI")?; + let position: Position = argument(arguments, 1, "a position")?; + let doc = + ws.document(&uri).ok_or_else(|| "lucisv can only inline in an open file.".to_string())?; + let path = doc + .path + .clone() + .ok_or_else(|| "lucisv can only inline in a file that has been saved.".to_string())?; + let offset = doc.positions().offset(position); + let Some(site) = vlog_refactor::inline_site(&doc.text, offset) else { + return Err(NOTHING.to_string()); + }; + // The engine reads the instantiated module's declaration and refuses over + // any hierarchical path into the instance, so the file set is the two + // units' own fan-out: the declaring file, and every file the index says + // mentions either name. + let files = ws.module_sources(&path, &site.units); + let refactoring = vlog_refactor::inline_module(&files, &path, offset)?; + Ok((crate::ports::workspace_edit(ws, &refactoring)?, refactoring.warnings)) +} + +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!("{INLINE_MODULE} wants {what} as argument {}.", n + 1)) +} + +const NOTHING: &str = "there is no module instantiation at this position to inline."; + +#[cfg(test)] +mod tests { + use super::*; + use crate::uri::path_to_uri; + 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_inline_{}_{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) { + fs::write(self.path.join(rel), text).expect("write"); + } + } + + impl Drop for Tree { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } + } + + const SUB: &str = "\ +module sub ( + input logic a, + output logic q +); + logic s; // the and + assign s = a; + assign q = s; +endmodule +"; + + const TOP: &str = "\ +module top ( + input logic x, + output logic z +); + sub u_sub ( + .a(x), + .q(z) + ); +endmodule +"; + + fn opened(tree: &Tree) -> (Workspace, Uri) { + tree.write("sub.sv", SUB); + tree.write("top.sv", TOP); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&tree.path.join("top.sv")).expect("uri"); + ws.set_document(uri.clone(), TOP.to_string()); + (ws, uri) + } + + /// The cursor on the `sub` of `sub u_sub (`. + fn cursor() -> Range { + let at = Position { line: 4, character: 4 }; + Range { start: at, end: at } + } + + #[test] + fn the_cursor_on_an_instantiation_is_offered_the_action_with_its_command() { + let tree = Tree::new("offer"); + let (ws, uri) = opened(&tree); + let actions = code_actions(&ws, &uri, cursor()); + let [CodeActionOrCommand::CodeAction(action)] = actions.as_slice() else { + panic!("one action, got {actions:?}") + }; + assert_eq!(action.title, "lucisv: inline `sub` here"); + assert_eq!(action.kind, Some(CodeActionKind::REFACTOR_INLINE)); + assert!(action.edit.is_none(), "the offer reads no workspace"); + let command = action.command.as_ref().expect("a command"); + assert_eq!(command.command, INLINE_MODULE); + assert_eq!(command.arguments.as_ref().expect("arguments").len(), 2); + } + + #[test] + fn a_cursor_on_anything_else_is_offered_nothing() { + let tree = Tree::new("nothing"); + let (ws, uri) = opened(&tree); + let elsewhere = Range { + start: Position { line: 1, character: 4 }, + end: Position { line: 1, character: 4 }, + }; + assert!(code_actions(&ws, &uri, elsewhere).is_empty()); + } + + #[test] + fn the_command_replaces_the_instantiation_with_the_body() { + let tree = Tree::new("run"); + let (ws, uri) = opened(&tree); + let arguments = vec![ + serde_json::to_value(&uri).expect("uri"), + serde_json::to_value(cursor().start).expect("position"), + ]; + let (edit, warnings) = execute(&ws, &arguments).expect("inlines"); + let changes = edit.changes.as_ref().expect("changes"); + assert_eq!(changes.len(), 1, "only the file the cursor is in is edited"); + let written = &changes.get(&uri).expect("this file")[0].new_text; + assert!(written.contains("assign s = x;"), "{written}"); + assert!(written.contains("// the and"), "{written}"); + assert!(warnings.iter().any(|w| w.contains("still declared where it was")), "{warnings:?}"); + } + + #[test] + fn the_command_says_why_when_there_is_nothing_to_inline() { + let tree = Tree::new("refuse"); + let (ws, uri) = opened(&tree); + let arguments = vec![ + serde_json::to_value(&uri).expect("uri"), + serde_json::to_value(Position { line: 1, character: 4 }).expect("position"), + ]; + assert_eq!(execute(&ws, &arguments), Err(NOTHING.to_string())); + } + + #[test] + fn the_command_wants_both_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).expect_err("a refusal"); + assert!(message.contains("argument 2"), "{message}"); + } + + #[test] + fn a_client_asking_only_for_refactor_inline_is_answered() { + let filter = [CodeActionKind::REFACTOR_INLINE]; + 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 4f10709..c97742d 100644 --- a/crates/lucisv_server/src/main.rs +++ b/crates/lucisv_server/src/main.rs @@ -24,6 +24,7 @@ mod includes; mod index_cache; mod inlay; mod inline; +mod inline_module; mod instantiate; mod large; mod lens; @@ -266,6 +267,7 @@ fn capabilities() -> ServerCapabilities { CodeActionKind::new(ports::REFACTOR_PORTS), imports::kind(), extract::kind(), + inline_module::kind(), ]), work_done_progress_options: WorkDoneProgressOptions::default(), // The quick fixes are complete when they are offered; the port @@ -409,6 +411,7 @@ fn commands() -> Vec { let mut commands = ports::commands(); commands.extend(imports::commands()); commands.extend(extract::commands()); + commands.extend(inline_module::commands()); commands.extend(instantiate::commands()); commands.extend(lens::commands()); commands diff --git a/crates/lucisv_server/src/server/dispatch.rs b/crates/lucisv_server/src/server/dispatch.rs index 4338233..ee84f4f 100644 --- a/crates/lucisv_server/src/server/dispatch.rs +++ b/crates/lucisv_server/src/server/dispatch.rs @@ -45,8 +45,8 @@ use super::client::ms; use super::Server; use crate::{ 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, + hover, imports, includes, inlay, inline, inline_module, lens, linked, lint, nav, pairs, ports, + rename, selection, signature, symbols, tokens, type_def, type_hierarchy, }; impl Server { @@ -286,6 +286,12 @@ impl Server { if code_action::wanted(only.as_deref(), &extract::kind()) { actions.extend(extract::code_actions(&self.workspace, &uri, p.range)); } + // Inlining the module instantiated under the cursor — the + // mirror of the extraction, and lazy for the same reason: the + // offer parses one buffer and the command reads the workspace. + if code_action::wanted(only.as_deref(), &inline_module::kind()) { + actions.extend(inline_module::code_actions(&self.workspace, &uri, p.range)); + } to_value(actions) }), // The edit for an action offered without one. An action that @@ -384,6 +390,15 @@ impl Server { Err(message) => Err(Failure::Request(message)), }; } + if p.command == inline_module::INLINE_MODULE { + return match inline_module::execute(&self.workspace, &p.arguments) { + 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/vlog_refactor/src/check/ledger.rs b/crates/vlog_refactor/src/check/ledger.rs index a7926a9..d33caf3 100644 --- a/crates/vlog_refactor/src/check/ledger.rs +++ b/crates/vlog_refactor/src/check/ledger.rs @@ -18,6 +18,8 @@ use vlog_parser::tokenize; use crate::rename::display; use crate::TextEdit; +use super::{Moving, Origin}; + // ---------------------------------------------------------------------- // lexical splice // ---------------------------------------------------------------------- @@ -180,12 +182,16 @@ pub(super) fn pieces_match( 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) +/// The range the move takes text out of file `i`, if it names that file as one +/// it *edits* at all: a source's own region, or the empty range that says +/// "this one only receives". A file the move does not name — and a file it +/// only copies out of, which it does not edit — has none, and keeps the +/// per-file contract. +pub(super) fn region_of(moving: &[Moving], i: usize) -> Option { + moving + .iter() + .find(|moving| moving.file == i && moving.origin == Origin::Moved) + .map(|moving| moving.region) } /// Whether a piece sits inside the bytes a move takes out of its file. An @@ -349,9 +355,9 @@ impl Ledger { } /// 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. +/// them: a **source** loses the pieces inside its own region, a **copy** keeps +/// them and lends them out, 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 @@ -360,6 +366,10 @@ impl Ledger { #[derive(Default)] pub(super) struct Transit { files: Vec, + /// The files a move only copies out of: what a refusal calls each one, and + /// the never-dropped pieces its region holds. They have no ledger — a copy + /// is not edited, and [`super::verify_move`] refuses one that is. + copied: Vec<(String, Tally)>, } /// One file of a move: what a refusal calls it, whether it receives rather @@ -386,6 +396,30 @@ impl Transit { }); } + /// Take the pieces a move **copies** out of a file it does not edit: what + /// that file's region holds, once, which is what the destinations between + /// them may write. + pub(super) fn copy( + &mut self, + where_: &str, + text: &str, + region: TextRange, + what: &str, + ) -> Result<(), String> { + let Some(pieces) = pieces(text) else { + return Err(format!( + "{where_} does not lex, so {what} cannot say what it would copy out of it; no edits were made." + )); + }; + let mut tally = Tally::new(); + tally_into( + &mut tally, + pieces.iter().filter(|(span, _)| within(region, *span)).map(|(_, piece)| piece), + ); + self.copied.push((where_.to_string(), tally)); + Ok(()) + } + /// 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> { @@ -395,6 +429,11 @@ impl Transit { *sent.entry(key.clone()).or_insert(0) += n; } } + for (_, tally) in &self.copied { + for (key, n) in tally { + *sent.entry(key.clone()).or_insert(0) += n; + } + } let nothing = Tally::new(); for file in &self.files { let receives = match file.receives { @@ -412,7 +451,9 @@ impl Transit { /// 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 named = self.files.iter().filter(move |f| f.receives == receives); + let copies = self.copied.iter().filter(|_| !receives); + named.map(|f| f.where_.clone()).chain(copies.map(|(name, _)| name.clone())).collect() }; let mut texts: Vec<&Kept> = sent.keys().collect(); texts.sort_unstable(); @@ -434,7 +475,7 @@ impl Transit { 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.", + "{what} would carry the {noun} `{text}` out of {} {} and write it back {landing}; {rule}, so nothing was edited.", and_list(&sources), times(out) )); diff --git a/crates/vlog_refactor/src/check/mod.rs b/crates/vlog_refactor/src/check/mod.rs index 2dafaf2..f6f7215 100644 --- a/crates/vlog_refactor/src/check/mod.rs +++ b/crates/vlog_refactor/src/check/mod.rs @@ -145,6 +145,47 @@ pub(crate) fn verify_splice( verify_move(scope, edits, &[watch_name], what, &[]) } +/// What a move does with one file's bytes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Origin { + /// The bytes **leave**: the file is edited, its region is deleted, and + /// what was inside it lands in a destination. Extracting a module works + /// this way, and so does the empty region that names a destination. + Moved, + /// The bytes are **copied**: the file is not edited at all, and what its + /// region holds may be written once into the destinations. Inlining a + /// module works this way — `S`'s declaration stays exactly where it is and + /// its items are copied into `M`. + Copied, +} + +/// One file a move names, and what it does with that file's bytes. +#[derive(Debug, Clone, Copy)] +pub(crate) struct Moving { + pub(crate) file: usize, + pub(crate) region: TextRange, + pub(crate) origin: Origin, +} + +impl Moving { + /// The file a move takes its text **out of**, and the bytes it takes. + pub(crate) fn source(file: usize, region: TextRange) -> Moving { + Moving { file, region, origin: Origin::Moved } + } + + /// A file a move **copies** out of, and the bytes it copies. The file + /// itself must come out untouched, which is checked rather than assumed. + pub(crate) fn copy(file: usize, region: TextRange) -> Moving { + Moving { file, region, origin: Origin::Copied } + } + + /// A file that only **receives** — named with an empty region, because it + /// sends nothing. + pub(crate) fn destination(file: usize) -> Moving { + Moving { file, region: TextRange::empty(0), origin: Origin::Moved } + } +} + /// [`verify_splice`], for a refactoring that **moves text from one file into /// another** — which is what extracting a module into its own file is. /// @@ -180,6 +221,17 @@ pub(crate) fn verify_splice( /// that file's own rule 2, and by rule 4. See /// `docs/features/extract-inline-module/README.md` for the attack pairs. /// +/// **A third kind of file: one the move only *copies* out of** +/// ([`Origin::Copied`]). Inlining a module is the mirror of extracting one — +/// `S`'s items are copied into `M` and `S`'s own file is not touched at all — +/// so the pieces `M` writes have an origin without anything having been +/// deleted anywhere. Such a file sends its region's pieces into the transit +/// exactly as a source does, and is held to one further rule of its own: +/// +/// 0. **A copied file is not edited.** It appears in no edit, so its text is +/// the text it had; anything else is a contradiction the move does not get +/// to make, and is refused before the equations are even asked. +/// /// `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. @@ -188,7 +240,7 @@ pub(crate) fn verify_move( edits: &[(usize, Vec)], watched_names: &[&str], what: &str, - moving: &[(usize, TextRange)], + moving: &[Moving], ) -> Result<(), String> { let abandoned = format!("lucisv could not verify {what}, so it made no edits."); let edited: Vec<(PathBuf, String)> = edits @@ -203,6 +255,22 @@ pub(crate) fn verify_move( } let mut transit = Transit::default(); + // Rule 0, and the pieces a copy sends: a file the move only copies out of + // is one it may not have edited, and what its region holds is what the + // destinations are allowed to write. + for copied in moving.iter().filter(|m| m.origin == Origin::Copied) { + let (Some(path), Some(text)) = (scope.path(copied.file), scope.text(copied.file)) else { + return Err(abandoned); + }; + if edits.iter().any(|(i, _)| *i == copied.file) { + return Err(format!( + "{what} would edit {}, which it only copies out of; no edits were made.", + display(path) + )); + } + transit.copy(&display(path), text, copied.region, what)?; + } + for ((i, edits), (path, text)) in edits.iter().zip(&edited) { let Some(before) = scope.text(*i) else { return Err(abandoned) }; let split = Split::read(before, text, edits, path, what)?; @@ -820,7 +888,7 @@ mod tests { 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))], + true => vec![Moving::source(m, plan.region), Moving::destination(n)], false => Vec::new(), }; verify_move(&mut scope, &edits, &["m", "sum"], MOVED_WHAT, &moving) @@ -960,7 +1028,7 @@ mod tests { 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 moving = vec![Moving::source(m, plan.region), Moving::destination(sum)]; 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}"); @@ -1005,6 +1073,176 @@ mod tests { assert_eq!(verified(EXTRACT, &plan, true), Ok(()), "and with it, the same plan verifies"); } + // ------------------------------------------------------------------ + // the copied-piece rule, and the attacks on it (CLAUDE.md invariant 4) + // ------------------------------------------------------------------ + // + // 2026-09-06: `Origin::Copied` lets a piece that is never dropped be + // *copied* out of a file the edit does not touch — which is what inlining + // a module is. `S`'s comment arrives in `M` with nothing deleted anywhere, + // so rule 2's `wrote <= gone` has to be widened by exactly the transit; + // every pair below is a crafted corruption that widening could plausibly + // forgive, and every one goes through the production `verify_move` with a + // real `Scope` and the edits `inline_module` really produces. + + /// The two files an inline works over: `sub`, with a comment inside the + /// body that is copied, and the `top` that instantiates it. + const SUB: &str = + "module sub (\n input logic a,\n output logic q\n);\n (* keep *) logic s; // the and\n assign s = a;\n assign q = s;\nendmodule\n"; + const TOP: &str = + "module top (\n input logic x,\n output logic z\n);\n sub u_sub (.a(x), .q(z));\nendmodule\n"; + + const INLINED_WHAT: &str = "inlining `sub` into `top`"; + + fn inline_files() -> Vec<(PathBuf, String)> { + vec![ + (PathBuf::from("/rtl/sub.sv"), SUB.to_string()), + (PathBuf::from("/rtl/top.sv"), TOP.to_string()), + ] + } + + /// The edits `inline_module` really makes in `top.sv`. + fn inline_edits() -> Vec { + let at = TOP.find("sub u_sub").expect("the instantiation") as u32 + 2; + crate::inline_module(&inline_files(), Path::new("/rtl/top.sv"), at) + .expect("the inline the attacks corrupt") + .edits_for(&PathBuf::from("/rtl/top.sv")) + .to_vec() + } + + /// Verify an inline the way the engine does: `top.sv` receives, `sub.sv` + /// is copied out of over the bytes of its body. `sub` is the text of the + /// file the move copies from — the attacks that edit it pass a different + /// one — and `copies` is what the engine passes, or nothing at all. + fn verified_inline( + sub: &str, + top_edits: &[TextEdit], + sub_edits: &[TextEdit], + copies: bool, + ) -> Result<(), String> { + let files = vec![ + (PathBuf::from("/rtl/sub.sv"), sub.to_string()), + (PathBuf::from("/rtl/top.sv"), TOP.to_string()), + ]; + let mut scope = Scope::build(&files); + let at = |name: &str| scope.index_of(Path::new(name)).expect(name); + let (s, t) = (at("/rtl/sub.sv"), at("/rtl/top.sv")); + let mut edits = vec![(t, top_edits.to_vec())]; + if !sub_edits.is_empty() { + edits.push((s, sub_edits.to_vec())); + } + edits.sort_by_key(|(i, _)| *i); + let body = TextRange::new( + sub.find("(* keep *)").map_or(0, |at| at as u32), + sub.find("endmodule").map_or(0, |at| at as u32), + ); + let moving = match copies { + true => vec![Moving::destination(t), Moving::copy(s, body)], + false => Vec::new(), + }; + verify_move(&mut scope, &edits, &["top"], INLINED_WHAT, &moving) + } + + #[test] + fn the_inline_the_engine_actually_produces_verifies() { + let edits = inline_edits(); + assert_eq!(verified_inline(SUB, &edits, &[], true), Ok(()), "the real output must pass"); + let top = apply(TOP, &edits); + // The comment and the attribute are copies: `sub.sv` still has both. + assert!(top.contains("// the and") && top.contains("(* keep *)"), "{top}"); + assert_eq!(SUB.matches("// the and").count(), 1, "and `sub.sv` is untouched"); + } + + #[test] + fn a_copied_comment_written_twice_is_rejected() { + // The transit is an allowance for one copy per copy: the region holds + // the comment once, so `top.sv` may write it once. + let mut edits = inline_edits(); + for edit in &mut edits { + edit.new_text = edit.new_text.replace("// the and", "// the and\n // the and"); + } + let message = verified_inline(SUB, &edits, &[], true).expect_err("a duplicate is refused"); + assert!(message.contains("never duplicated"), "{message}"); + } + + #[test] + fn a_copied_comment_that_lands_nowhere_is_rejected() { + // The mirror hazard: the piece is in the region the move says it + // copies, and the text written into `top.sv` simply never carries it. + let mut edits = inline_edits(); + for edit in &mut edits { + edit.new_text = edit.new_text.replace(" // the and", ""); + } + let message = verified_inline(SUB, &edits, &[], true).expect_err("a lost copy is refused"); + assert!(message.contains("comments are never dropped"), "{message}"); + assert!(message.contains("write it back nowhere"), "{message}"); + } + + #[test] + fn a_copied_attribute_that_lands_nowhere_is_rejected() { + let mut edits = inline_edits(); + for edit in &mut edits { + edit.new_text = edit.new_text.replace("(* keep *) ", ""); + } + let message = + verified_inline(SUB, &edits, &[], true).expect_err("a lost attribute is refused"); + assert!(message.contains("attributes are never dropped"), "{message}"); + } + + #[test] + fn a_piece_written_into_the_destination_that_the_region_does_not_hold_is_rejected() { + // The allowance is bound to the copied bytes, not to the copied file: + // a comment `top.sv` invents has no origin at all, and one lifted out + // of `sub`'s *header* — outside the region the move named — has none + // either. + let mut edits = inline_edits(); + for edit in &mut edits { + edit.new_text.push_str("\n // invented"); + } + let message = verified_inline(SUB, &edits, &[], true).expect_err("an invention is refused"); + assert!(message.contains("never duplicated"), "{message}"); + assert!(message.contains("// invented"), "{message}"); + } + + #[test] + fn a_generated_placeholder_the_destination_writes_is_not_a_duplicate() { + // The whitelist is untouched by the widening. + let mut edits = inline_edits(); + for edit in &mut edits { + edit.new_text.push_str("\n /* TODO: connect */"); + } + assert_eq!(verified_inline(SUB, &edits, &[], true), Ok(()), "the whitelist still holds"); + } + + #[test] + fn an_edit_to_the_file_the_move_only_copies_out_of_is_rejected() { + // Rule 0. The copy allowance is granted on the strength of `sub.sv` + // coming out of the refactoring unchanged; an edit to it — here the + // deletion of the very comment being copied, which would make the two + // halves balance as a *move* — is a contradiction rather than a plan. + let start = SUB.find(" // the and").expect("the comment") as u32; + let sub_edits = vec![TextEdit { + range: TextRange::new(start, start + " // the and".len() as u32), + new_text: String::new(), + }]; + let message = verified_inline(SUB, &inline_edits(), &sub_edits, true) + .expect_err("a copied file that is edited is a refusal"); + assert!(message.contains("only copies out of"), "{message}"); + assert!(message.contains("sub.sv"), "{message}"); + } + + #[test] + fn the_copy_allowance_is_opt_in_and_an_inline_that_asked_for_none_gets_none() { + // The same honest inline with an empty `moving` list: `top.sv` writes + // a comment it never deleted, which is what the per-file contract has + // always refused. + let edits = inline_edits(); + let message = verified_inline(SUB, &edits, &[], false) + .expect_err("without `moving`, a copy is a duplicated comment"); + assert!(message.contains("never duplicated"), "{message}"); + assert_eq!(verified_inline(SUB, &edits, &[], true), Ok(()), "and with it, it 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/mod.rs b/crates/vlog_refactor/src/extract/mod.rs index cd85c74..453d8e9 100644 --- a/crates/vlog_refactor/src/extract/mod.rs +++ b/crates/vlog_refactor/src/extract/mod.rs @@ -207,7 +207,7 @@ impl Extraction { // `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 mut moving: Vec = Vec::new(); let replace = TextEdit { range: region.span, new_text: instance }; match &created { Some(path) => { @@ -217,7 +217,10 @@ impl Extraction { there, vec![TextEdit { range: TextRange::empty(0), new_text: module_text.clone() }], )); - moving = vec![(here, region.span), (there, TextRange::empty(0))]; + moving = vec![ + check::Moving::source(here, region.span), + check::Moving::destination(there), + ]; } None => { let append = TextEdit { @@ -228,7 +231,7 @@ impl Extraction { } } edits.sort_by_key(|(i, _)| *i); - moving.sort_by_key(|(i, _)| *i); + moving.sort_by_key(|moving| moving.file); let what = format!("extracting `{new_name}` out of `{module}`"); check::verify_move(&mut scope, &edits, &[&module, new_name], &what, &moving)?; diff --git a/crates/vlog_refactor/src/inline/mod.rs b/crates/vlog_refactor/src/inline/mod.rs new file mode 100644 index 0000000..a36c702 --- /dev/null +++ b/crates/vlog_refactor/src/inline/mod.rs @@ -0,0 +1,371 @@ +//! Inline a module: replace `S u_S (...)` with what `S` is made of. +//! +//! The mirror of [`crate::extract_module`], and the mirror only up to a point. +//! An extraction *moves* text out of one file and into another; an inline +//! **copies** — `S`'s declaration is left exactly where it is, because +//! everything else in the workspace still instantiates it — and deletes only +//! the instantiation. So the file the user is in loses one item and gains +//! `S`'s, with `S`'s port names replaced by the names connected to them and +//! `S`'s parameters written out as `localparam`s. +//! +//! Three files, one question each: +//! +//! * `site` — *what is the cursor on?* The module `M`, the instantiation, and +//! the connection shapes lucisv will not read a substitution out of. +//! * `source` — *what is `S` made of?* Its ports, its parameters, the bytes of +//! its body, and the constructs that do not mean the same thing copied into +//! another module. +//! * `render` — *what does lucisv write?* The substitution, the prefixing rule +//! and the text. +//! +//! This file is the plan: the entry points, the workspace-wide refusals (a +//! second declaration of `S`, a hierarchical reference to `u_S` from anywhere, +//! a `timescale` that differs), the edit, and the verification. The +//! verification is one [`check::verify_move`] naming `S`'s file as a file the +//! edit **copies** out of ([`check::Moving::copy`]): the comments arriving in +//! `M` are copies of pieces of a file that is not being edited, and that — +//! bounded to `S`'s body and to one copy — is the whole of what the +//! never-dropped ledger is asked to forgive. See +//! `docs/features/extract-inline-module/README.md`. + +mod render; +mod site; +mod source; + +use std::path::{Path, PathBuf}; + +use vlog_parser::span::TextRange; +use vlog_parser::token::TokenKind; +use vlog_parser::{parse_source_tolerant, tokenize}; + +use crate::instantiate::module_definition; +use crate::rename::{contains_word, display, Scope}; +use crate::{check, RefactorEdit, TextEdit}; + +use site::Site; +use source::Source; + +/// What the cheap gate found: an instantiation the cursor is on, and the units +/// whose files the engine needs read. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct InlineSite { + /// The module being instantiated — the one that would be inlined. + pub module: String, + /// The instance's own name. + pub instance: String, + /// Every unit whose declaration the engine will look up: the instantiated + /// module and the module the cursor is in. + pub units: Vec, +} + +/// Whether the cursor is on an instantiation lucisv could inline, 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 [`crate::extract_site`] strikes, and for the same reason (a +/// `textDocument/codeAction` arrives on every cursor move). `None` where there +/// is no instantiation under the cursor, and `None` too where the +/// instantiation's own shape already refuses — a `.*`, a positional list, an +/// expression where a name belongs — since those are answerable without +/// reading a single other file and an action that would only refuse is one +/// nobody wants offered. Every refusal that needs `S`'s declaration is a +/// sentence from the command instead. +pub fn inline_site(text: &str, offset: u32) -> Option { + let (tree, diagnostics) = parse_source_tolerant(text); + if !diagnostics.is_empty() { + return None; + } + let site = Site::read(&tree, text, offset)?.ok()?; + Some(InlineSite { + units: vec![site.target.clone(), site.module.name.clone()], + module: site.target.clone(), + instance: site.instance.clone(), + }) +} + +/// The lightbulb's text, written here so every front end says the same thing. +pub fn inline_title(module: &str) -> String { + format!("lucisv: inline `{module}` here") +} + +/// Replace the instantiation under `offset` with the body of the module it +/// instantiates. +pub fn inline_module( + files: &[(PathBuf, String)], + file: &Path, + offset: u32, +) -> Result { + let mut scope = Scope::build(files); + 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 = parsed(text, file)?; + let Some(found) = Site::read(&tree, text, offset) else { return Err(NOTHING.to_string()) }; + let site = found?; + + if let Some(attribute) = attribute_in(text, site.span) { + return Err(format!( + "the instantiation carries the attribute `{attribute}`, which says something about that instance and has nothing left to say once there is no instance; no edits were made." + )); + } + let there = declaring_file(&scope, here, &site)?; + let Some(source_text) = scope.text(there) else { return Err(abandoned(&site)) }; + let source_path = scope.path(there).unwrap_or(Path::new("?")).to_path_buf(); + let source_tree = parsed(source_text, &source_path)?; + let source = Source::read(&source_tree, source_text, scope.index(), &site.target)?; + same_timescale(text, source_text, &site.target)?; + no_hierarchy(&scope, &site)?; + + let inlined = plan(&mut scope, here, there, &site, &source)?; + let edits = vec![(here, vec![TextEdit { range: site.span, new_text: inlined.text.clone() }])]; + let what = format!("inlining `{}` into `{}`", site.target, site.module.name); + let moving = [check::Moving::destination(here), check::Moving::copy(there, source.body)]; + check::verify_move(&mut scope, &edits, &[&site.module.name], &what, &moving)?; + + Ok(RefactorEdit { + edits: vec![(file.to_path_buf(), edits.into_iter().flat_map(|(_, e)| e).collect())], + warnings: warnings(&site, &inlined), + created: Vec::new(), + }) +} + +/// Everything the substitution needs from both files, and the text it writes. +fn plan( + scope: &mut Scope<'_>, + here: usize, + there: usize, + site: &Site<'_>, + source: &Source, +) -> Result { + let taken: Vec = { + let Some(analysis) = scope.analysis(here) else { return Err(abandoned(site)) }; + analysis.semantics.symbols().iter().map(|symbol| symbol.name.clone()).collect() + }; + let (Some(text), Some(source_text)) = (scope.text(here), scope.text(there)) else { + return Err(abandoned(site)); + }; + let Some(analysis) = scope.analysis(there) else { return Err(abandoned(site)) }; + let carried = comments_in(text, site.span); + let held = held_imports(text, site.module_span); + render::inline(&render::Inputs { + text: source_text, + semantics: &analysis.semantics, + source, + site, + taken: &taken, + carried: &carried, + held: &held, + }) +} + +/// What the user is told about an inline that went through. +fn warnings(site: &Site<'_>, inlined: &render::Inlined) -> Vec { + let mut out = Vec::new(); + match inlined.prefixed.split_first() { + None => out.push(format!( + "`{}` declares no name `{}` already spells, so its body was copied under its own names.", + site.target, site.module.name + )), + Some((first, rest)) => out.push(format!( + "`{}` already spells {}, so every name `{}` declares was written with `{}_` in front of it.", + site.module.name, + match rest.is_empty() { + true => format!("`{first}`"), + false => format!("`{first}` and {} more of `{}`'s names", rest.len(), site.target), + }, + site.target, + site.instance + )), + } + for import in &inlined.imports { + out.push(format!( + "`{}` needs `{import}`, which `{}` did not write, so it was copied in above the body.", + site.target, site.module.name + )); + } + out.push(format!( + "`{}` is still declared where it was; nothing else that instantiates it was touched.", + site.target + )); + out +} + +// ---------------------------------------------------------------------- +// the workspace-wide questions +// ---------------------------------------------------------------------- + +/// The one file that declares `S`, and the refusals for none and for two. +/// +/// `S` is looked up exactly the way an instantiation skeleton looks it up, so +/// "lucisv indexes no module named `S`" is one sentence in the codebase and +/// not two. The one thing added here is that `S` may not live in `M`'s own +/// file: the verifier's copy allowance is bound to a file the edit does *not* +/// touch, and lucisv would rather refuse than widen it. +fn declaring_file(scope: &Scope<'_>, here: usize, site: &Site<'_>) -> Result { + let path = module_definition(scope.index(), &site.target)?; + let Some(there) = scope.index_of(path) else { + return Err(format!( + "`{}` is declared in {}, which is not one of the files lucisv was given.", + site.target, + display(path) + )); + }; + match there == here { + true => Err(format!( + "`{}` is declared in the same file it is instantiated in, and lucisv inlines a module written in a file of its own this round; no edits were made.", + site.target + )), + false => Ok(there), + } +} + +/// A `timescale` in force where `S` is written is not one `M`'s file inherits, +/// and silently changing what a delay means is a change to what the design +/// does. +fn same_timescale(here: &str, there: &str, target: &str) -> Result<(), String> { + let (mine, theirs) = (timescale(here), timescale(there)); + match mine == theirs { + true => Ok(()), + false => Err(format!( + "`{target}` is compiled under `{}` and the file it would be inlined into under `{}`, and a `timescale` changes what every delay in the body means; no edits were made.", + theirs.as_deref().unwrap_or("no `timescale"), + mine.as_deref().unwrap_or("no `timescale") + )), + } +} + +/// The last `` `timescale`` a file writes, whitespace collapsed. +fn timescale(text: &str) -> Option { + let mut out = None; + for line in text.lines().map(str::trim) { + if line.starts_with("`timescale") { + out = Some(line.split_whitespace().collect::>().join(" ")); + } + } + out +} + +/// Whether anything in the workspace reaches into `u_S` through the design +/// hierarchy — `u_S.state` in a testbench, `top.u_m.u_S.q` in an assertion. +/// +/// Such a path names a scope that inlining dissolves, and no edit lucisv makes +/// in `M` could keep it working. The test is lexical on purpose and errs +/// towards refusing: an identifier spelling the instance's name with a `.` on +/// either side of it, in any file the caller handed over. §49's hierarchical +/// surface is what makes such a path resolvable at all; this is what says +/// lucisv will not break one it can see. +fn no_hierarchy(scope: &Scope<'_>, site: &Site<'_>) -> Result<(), String> { + for i in 0..scope.len() { + let (Some(text), Some(path)) = (scope.text(i), scope.path(i)) else { continue }; + if !contains_word(text, &site.instance) { + continue; + } + let Ok(tokens) = tokenize(text) else { continue }; + for (n, token) in tokens.iter().enumerate() { + if token.kind != TokenKind::Ident || token.text != site.instance { + continue; + } + let spells = |at: usize, what: &str| { + tokens.get(at).is_some_and(|t: &vlog_parser::token::Token| t.text == what) + }; + // A `.` on either side is a path walking through the instance; a + // `bind` in front of it names the instance as a scope of its own, + // which is the same scope and disappears the same way. + let named = + spells(n + 1, ".") || (n > 0 && (spells(n - 1, ".") || spells(n - 1, "bind"))); + if named { + return Err(format!( + "`{}` is named as a scope of the design hierarchy in {}, and inlining it dissolves the scope that path walks through; no edits were made.", + site.instance, + display(path) + )); + } + } + } + Ok(()) +} + +// ---------------------------------------------------------------------- +// odds and ends +// ---------------------------------------------------------------------- + +fn parsed(text: &str, path: &Path) -> Result { + let (tree, diagnostics) = parse_source_tolerant(text); + match diagnostics.first() { + None => Ok(tree), + Some(problem) => Err(format!( + "{} does not parse ({} at line {}), so lucisv will not inline through it.", + display(path), + problem.message, + problem.line + )), + } +} + +/// The comments written inside the bytes the inline deletes — the notes on the +/// connection list — which are written back above the body that replaces them. +/// An attribute is refused rather than moved: `(* keep *)` on an instantiation +/// says something about *that instance*, and there is no instance left. +fn comments_in(text: &str, span: TextRange) -> Vec { + let Ok(tokens) = tokenize(text) else { return Vec::new() }; + let mut out = Vec::new(); + for token in &tokens { + for comment in token.leading.iter().chain(token.trailing.as_ref()) { + if span.start <= comment.span.start && comment.span.end <= span.end { + out.push(comment.text.clone()); + } + } + } + out +} + +/// Whether the deleted bytes carry an attribute instance, which lucisv will +/// not re-attach to anything. +fn attribute_in(text: &str, span: TextRange) -> Option { + let tokens = tokenize(text).ok()?; + tokens + .iter() + .find(|token| { + token.kind == TokenKind::Attribute + && span.start <= token.span.start + && token.span.end <= span.end + }) + .map(|token| token.text.clone()) +} + +/// The package paths `M` already imports — its header's and its body's — in +/// the same spelling [`source`] gives `S`'s, so the comparison is per path +/// rather than per statement. +fn held_imports(text: &str, module: TextRange) -> Vec { + let (tree, _) = parse_source_tolerant(text); + let mut out = Vec::new(); + for item in &tree.items { + let vlog_parser::ast::ItemKind::Module(declared) = &item.kind else { continue }; + if item.span != module { + continue; + } + for import in &declared.imports { + out.extend(import.paths.iter().map(|path| path.text())); + } + for item in &declared.items { + if let vlog_parser::ast::ItemKind::Import(paths) = &item.kind { + out.extend(paths.iter().map(|path| path.text())); + } + } + } + out +} + +fn not_in_scope(file: &Path) -> String { + format!("{} is not one of the files lucisv was given.", display(file)) +} + +/// The sentence for a file the engine could read a moment ago and cannot now — +/// nothing a user can act on, but never a silent half-answer. +fn abandoned(site: &Site<'_>) -> String { + format!( + "lucisv could not read one of the files inlining `{}` needs, so it made no edits.", + site.target + ) +} + +const NOTHING: &str = "there is no module instantiation under the cursor to inline."; diff --git a/crates/vlog_refactor/src/inline/render.rs b/crates/vlog_refactor/src/inline/render.rs new file mode 100644 index 0000000..27d57a8 --- /dev/null +++ b/crates/vlog_refactor/src/inline/render.rs @@ -0,0 +1,419 @@ +//! What lucisv writes where the instantiation was. +//! +//! One substitution, applied to spans of `S`'s own text: every use of a port +//! becomes the name (or the literal) connected to it, and every use of a name +//! `S` declares for itself becomes that name, prefixed with the instance's — +//! but only when something in `M` already spells it, because an inline that +//! renames nothing is the one a reader can check by eye. +//! +//! The body is copied **verbatim** but for those name spans and the leading +//! whitespace of its lines: a comment written in `S` arrives in `M` byte for +//! byte, which is both what invariant 3 wants and what lets the verifier +//! account for it as a copy rather than as an invention. + +use std::collections::HashMap; + +use vlog_parser::span::TextRange; +use vlog_parser::token::TokenKind; +use vlog_parser::tokenize; +use vlog_semantic::{Resolution, Semantics, SymbolId, SymbolKind}; + +use super::site::{Binding, Site, Value}; +use super::source::{Param, Source}; + +/// The text to write, and what the user is told about it. +pub(super) struct Inlined { + pub(super) text: String, + /// The names of `S` that were prefixed, in declaration order. Empty when + /// nothing in `M` collided and the body was copied under its own names. + pub(super) prefixed: Vec, + /// The `import` statements written into `M` because it lacked them. + pub(super) imports: Vec, +} + +/// Everything the substitution reads: `S`'s two layers, `M`'s side of the +/// instantiation, and the names `M` already holds. +pub(super) struct Inputs<'a> { + pub(super) text: &'a str, + pub(super) semantics: &'a Semantics, + pub(super) source: &'a Source, + pub(super) site: &'a Site<'a>, + /// Every name declared in `M`'s file — the collision test, deliberately a + /// superset of the module's own. + pub(super) taken: &'a [String], + /// The comments the deleted instantiation carried, which are written back + /// above the body it becomes. + pub(super) carried: &'a [String], + /// The package paths `M` already imports. + pub(super) held: &'a [String], +} + +/// Write the body of `S` as it reads inside `M`, or say why lucisv cannot. +pub(super) fn inline(inputs: &Inputs<'_>) -> Result { + let scope = inputs + .semantics + .instantiable_scope(&inputs.site.target) + .ok_or_else(|| lost(&inputs.site.target))?; + let mine: Vec<(SymbolId, &str, SymbolKind)> = inputs + .semantics + .symbols() + .iter() + .enumerate() + .filter(|(_, symbol)| symbol.scope == scope) + .map(|(id, symbol)| (SymbolId(id as u32), symbol.name.as_str(), symbol.kind)) + .collect(); + let internal: Vec<(SymbolId, &str, SymbolKind)> = + mine.iter().copied().filter(|(_, _, kind)| *kind != SymbolKind::Port).collect(); + let prefix = prefix(inputs, &internal)?; + + let mut map: HashMap = HashMap::new(); + for (id, name, kind) in &mine { + let replacement = match kind { + SymbolKind::Port => connected(inputs, name)?, + _ => format!("{prefix}{name}"), + }; + map.insert(*id, replacement); + } + let named: Vec<(&str, &String)> = + mine.iter().filter_map(|(id, name, _)| Some((*name, map.get(id)?))).collect(); + let rewrite = Rewrite::read(inputs.semantics, &map, &inputs.source.shorthands, &named); + let prefixed = match prefix.is_empty() { + true => Vec::new(), + false => internal.iter().map(|(_, name, _)| (*name).to_string()).collect(), + }; + let imports: Vec = inputs + .source + .imports + .iter() + .filter(|path| !inputs.held.contains(path)) + .map(|path| format!("import {path};")) + .collect(); + Ok(Inlined { text: text(inputs, &rewrite, &prefix, &imports)?, prefixed, imports }) +} + +/// The prefix every name `S` declares takes: nothing when `M` spells none of +/// them, and `u_s_` when it spells any. +fn prefix( + inputs: &Inputs<'_>, + internal: &[(SymbolId, &str, SymbolKind)], +) -> Result { + let taken = |name: &str| inputs.taken.iter().any(|held| held == name); + if !internal.iter().any(|(_, name, _)| taken(name)) { + return Ok(String::new()); + } + let prefix = format!("{}_", inputs.site.instance); + for (_, name, kind) in internal { + if name.starts_with('\\') { + return Err(format!( + "`{}` also declares `{name}`, and `{name}` is an escaped identifier that lucisv cannot prefix its way out of; no edits were made.", + inputs.site.module.name + )); + } + if labelled(*kind) { + return Err(format!( + "`{}` declares `{name}`, whose name `{}` would have to be prefixed to avoid a collision with `{}`'s own — and lucisv does not rewrite the `end … : {name}` label that goes with it; no edits were made.", + inputs.site.target, + what(*kind), + inputs.site.module.name + )); + } + let renamed = format!("{prefix}{name}"); + if taken(&renamed) || internal.iter().any(|(_, other, _)| *other == renamed) { + return Err(format!( + "`{name}` collides with a name `{}` already holds, and so does `{renamed}`, which is what lucisv would have renamed it to; no edits were made.", + inputs.site.module.name + )); + } + } + Ok(prefix) +} + +/// Whether a declaration of this kind can carry an `end … : name` label, which +/// lucisv does not rewrite and so will not prefix past. +fn labelled(kind: SymbolKind) -> bool { + matches!( + kind, + SymbolKind::Function + | SymbolKind::Task + | SymbolKind::Block + | SymbolKind::Class + | SymbolKind::Clocking + | SymbolKind::Covergroup + | SymbolKind::Property + | SymbolKind::Sequence + ) +} + +fn what(kind: SymbolKind) -> &'static str { + match kind { + SymbolKind::Function => "a function", + SymbolKind::Task => "a task", + SymbolKind::Block => "a named block", + SymbolKind::Class => "a class", + SymbolKind::Clocking => "a clocking block", + SymbolKind::Covergroup => "a covergroup", + SymbolKind::Property => "a property", + _ => "a sequence", + } +} + +/// What one port of `S` is replaced by, or the sentence for a connection +/// lucisv will not substitute. +fn connected(inputs: &Inputs<'_>, port: &str) -> Result { + let target = &inputs.site.target; + let found: Option<&Binding> = inputs.site.bindings.iter().find(|b| b.port == port); + let dir = inputs.source.ports.iter().find(|p| p.name == port).map_or("", |p| p.dir.as_str()); + let output = dir == "output"; + match found.map(|b| &b.value) { + Some(Value::Name(name)) => Ok(name.clone()), + Some(Value::Literal(written)) if !output => Ok(written.clone()), + Some(Value::Literal(written)) => Err(format!( + "`.{port}({written})` drives `{target}`'s output into a literal, which nothing can be assigned to; connect `.{port}` to a wire first." + )), + Some(Value::Unconnected) | None => Err(format!( + "`.{port}` is left unconnected, and `{target}`'s body uses `{port}` as a name of its own; connect it to a wire first." + )), + } +} + +/// Every name span of `S` that the inline rewrites, and what it writes there. +struct Rewrite { + /// Sorted by start, non-overlapping. + spans: Vec<(TextRange, String)>, +} + +impl Rewrite { + /// The declarations of the names being prefixed, every reference that + /// resolved to one of them or to a port, and every `.name` shorthand that + /// has to be spelled out because the name it stands for is changing. + fn read( + semantics: &Semantics, + map: &HashMap, + shorthands: &[(String, TextRange)], + named: &[(&str, &String)], + ) -> Rewrite { + let mut spans: Vec<(TextRange, String)> = Vec::new(); + for (id, symbol) in semantics.symbols().iter().enumerate() { + let id = SymbolId(id as u32); + if symbol.kind == SymbolKind::Port { + continue; + } + if let Some(text) = map.get(&id) { + spans.push((symbol.name_span, text.clone())); + } + } + for reference in semantics.references() { + let Resolution::Resolved(id) = reference.resolution else { continue }; + if let Some(text) = map.get(&id) { + spans.push((reference.name_span, text.clone())); + } + } + // `.clk_i` becomes `.clk_i(clk)`: the *port*'s name stays exactly what + // it was — it belongs to the module being instantiated, not to `S` — + // and the signal it binds to is written out beside it. Any rewrite + // that landed on the shorthand's own token is dropped first: rewriting + // it would connect a different port. + for (name, at) in shorthands { + let Some((_, replacement)) = named.iter().find(|(held, _)| held == name) else { + continue; + }; + if *replacement == name { + continue; + } + spans.retain(|(span, _)| span != at); + let spacer = match crate::instantiate::ends_escaped(replacement) { + true => " ", + false => "", + }; + spans.push((TextRange::empty(at.end), format!("({replacement}{spacer})"))); + } + spans.sort_by_key(|(span, _)| (span.start, span.end)); + spans.dedup_by_key(|(span, _)| *span); + Rewrite { spans } + } + + /// `text`'s bytes over `span`, with every rewrite inside it applied. + fn apply(&self, text: &str, span: TextRange) -> String { + let mut out = String::new(); + let mut cursor = span.start; + for (at, written) in &self.spans { + if at.start < cursor || at.end > span.end { + continue; + } + out.push_str(slice(text, TextRange::new(cursor, at.start))); + out.push_str(written); + cursor = at.end; + } + out.push_str(slice(text, TextRange::new(cursor, span.end))); + out + } +} + +/// The whole replacement: the instantiation's own comments, the imports, the +/// parameters as `localparam`s, and the body. +fn text( + inputs: &Inputs<'_>, + rewrite: &Rewrite, + prefix: &str, + imports: &[String], +) -> Result { + let mut lines: Vec = inputs.carried.to_vec(); + lines.extend(imports.iter().cloned()); + for param in &inputs.source.params { + lines.push(localparam(inputs, rewrite, prefix, param)?); + } + let indent = &inputs.site.indent; + let mut out = lines.join(&format!("\n{indent}")); + if inputs.source.body.is_empty() { + return Ok(out); + } + if !out.is_empty() { + out.push('\n'); + out.push_str(indent); + } + out.push_str(&body(inputs, rewrite)); + Ok(out) +} + +/// One parameter of `S` as the `localparam` that stands in its place: the +/// override the instantiation wrote, or the default the header did. +fn localparam( + inputs: &Inputs<'_>, + rewrite: &Rewrite, + prefix: &str, + param: &Param, +) -> Result { + let name = format!("{prefix}{}", param.name); + let ty = one_line(inputs, rewrite, param.ty, ¶m.name)?; + let written = inputs.site.overrides.iter().find(|(over, _)| *over == param.name); + let value = match written { + Some(_) if param.local => { + return Err(format!( + "the instantiation overrides `{}`, which `{}` declares as a `localparam`; nothing was edited.", + param.name, inputs.site.target + )) + } + Some((_, value)) => value.clone(), + None => one_line(inputs, rewrite, param.default, ¶m.name)?, + }; + if value.is_empty() { + return Err(format!( + "`{}` gives `{}` no default and the instantiation overrides nothing, so lucisv has no value to write for it.", + inputs.site.target, param.name + )); + } + let ty = match ty.is_empty() { + true => String::new(), + false => format!("{ty} "), + }; + Ok(format!("localparam {ty}{name} = {value};")) +} + +/// One header span — a parameter's type or its default — as a single line, +/// with `S`'s own names substituted into it. +fn one_line( + inputs: &Inputs<'_>, + rewrite: &Rewrite, + span: TextRange, + param: &str, +) -> Result { + if span.is_empty() { + return Ok(String::new()); + } + let raw = slice(inputs.text, span); + if !plain(raw) { + return Err(format!( + "`{}` writes a comment inside the declaration of `{param}`, and lucisv would have to copy the comment into `{}` to write the `localparam`; no edits were made.", + inputs.site.target, inputs.site.module.name + )); + } + let written = rewrite.apply(inputs.text, span); + // The spaces *inside* a string literal are the literal's own, so a span + // holding one is written as it stands rather than squeezed onto one line. + match holds_a_string(&written) { + true => Ok(written.trim().to_string()), + false => Ok(written.split_whitespace().collect::>().join(" ")), + } +} + +/// Whether a stretch of text is code and nothing else: no comment, no +/// attribute. Both are pieces the verifier accounts for one by one, and +/// lucisv writes neither out of a span it only means to read a type from. +fn plain(text: &str) -> bool { + let Ok(tokens) = tokenize(text) else { return false }; + tokens.iter().all(|token| { + token.leading.is_empty() && token.trailing.is_none() && token.kind != TokenKind::Attribute + }) +} + +/// Whether a stretch of text holds a string literal, whose spaces are part of +/// what it says. +fn holds_a_string(text: &str) -> bool { + let Ok(tokens) = tokenize(text) else { return true }; + tokens.iter().any(|token| token.kind == TokenKind::String) +} + +/// `S`'s body, substituted and re-indented to where it lands. +fn body(inputs: &Inputs<'_>, rewrite: &Rewrite) -> String { + let written = rewrite.apply(inputs.text, inputs.source.body); + let from = indent_at(inputs.text, inputs.source.body.start); + reindent(&written, &from, &inputs.site.indent, inputs.text, inputs.source.body) +} + +/// Move every line of a copied body from one indentation to another, leaving +/// the lines that begin *inside* a comment or a string exactly as they are: +/// those bytes are the piece's own text, and the verifier counts a comment by +/// what it says. +fn reindent(text: &str, from: &str, to: &str, source: &str, span: TextRange) -> String { + if from == to { + return text.to_string(); + } + let inner = interiors(source, span); + let mut out = String::new(); + let mut at = span.start; + for (n, line) in text.split_inclusive('\n').enumerate() { + let start = at; + at += line.len() as u32; + let interior = inner.iter().any(|piece| piece.start < start && start < piece.end); + match n > 0 && !interior { + true => out.push_str(&format!("{to}{}", line.strip_prefix(from).unwrap_or(line))), + false => out.push_str(line), + } + } + out +} + +/// The spans of the multi-line pieces inside `span`: block comments and string +/// literals, whose own bytes no re-indentation may touch. +fn interiors(text: &str, span: TextRange) -> Vec { + let Ok(tokens) = tokenize(text) else { return Vec::new() }; + let mut out = Vec::new(); + for token in &tokens { + for comment in token.leading.iter().chain(token.trailing.as_ref()) { + out.push(comment.span); + } + if token.kind == TokenKind::String { + out.push(token.span); + } + } + out.retain(|piece| piece.start < span.end && span.start < piece.end); + out +} + +/// 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() +} + +fn slice(text: &str, span: TextRange) -> &str { + text.get(span.start as usize..span.end as usize).unwrap_or("") +} + +fn lost(name: &str) -> String { + format!("lucisv lost track of `{name}`'s own scope, so it made no edits.") +} diff --git a/crates/vlog_refactor/src/inline/site.rs b/crates/vlog_refactor/src/inline/site.rs new file mode 100644 index 0000000..43e28b7 --- /dev/null +++ b/crates/vlog_refactor/src/inline/site.rs @@ -0,0 +1,217 @@ +//! What the cursor is standing on: the module `M`, the instantiation of `S` +//! written directly in its body, and what each of that instantiation's +//! connections binds to. +//! +//! Nothing here reads `S`. This is the half of the refusal list that can be +//! answered from `M`'s own text — the shapes of a connection list lucisv will +//! not read a substitution out of — so that the cheap gate behind the +//! lightbulb and the engine ask exactly the same question. + +use vlog_parser::ast::{ + Connections, Expr, ExprKind, Instance, Instantiation, Item, ItemKind, ListElem, Module, + SourceFile, +}; +use vlog_parser::span::TextRange; + +/// What one connection binds a port to. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) enum Value { + /// A plain name written in `M`: `.a(sig)`, or the `.a` shorthand. + Name(String), + /// A literal: `.en(1'b1)`, `.name("x")`. + Literal(String), + /// `.a()` — written and left open. + Unconnected, +} + +/// One entry of the connection list, by the port name it names. +#[derive(Debug, Clone)] +pub(super) struct Binding { + pub(super) port: String, + pub(super) value: Value, +} + +/// The instantiation the cursor is on, and everything about it that does not +/// need `S`'s declaration. +pub(super) struct Site<'t> { + /// The module the instantiation is written in. + pub(super) module: &'t Module, + /// Where that module is written, `module` keyword to `endmodule`. + pub(super) module_span: TextRange, + /// The instantiated module's name. + pub(super) target: String, + /// The instance's own name — the `u_s` of `sub u_s (...)`. + pub(super) instance: String, + /// The bytes the inline deletes: the instantiation item itself. + pub(super) span: TextRange, + /// The whitespace the instantiation's line begins with. + pub(super) indent: String, + /// The port connections, in the order the list writes them. + pub(super) bindings: Vec, + /// The parameter overrides, in the order the list writes them. + pub(super) overrides: Vec<(String, String)>, +} + +impl<'t> Site<'t> { + /// Read the instantiation under `offset`, or say why lucisv will not + /// inline it. `None` where there is no instantiation at all — the cheap + /// gate's answer for almost every cursor position. + pub(super) fn read( + tree: &'t SourceFile, + text: &str, + offset: u32, + ) -> Option, String>> { + let (module, module_span) = module_at(&tree.items, offset)?; + let item = module.items.iter().find(|item| covers(item, offset))?; + let ItemKind::Instantiation(inst) = &item.kind else { return None }; + Some(Site::of(module, module_span, text, item, inst)) + } + + fn of( + module: &'t Module, + module_span: TextRange, + text: &str, + item: &Item, + inst: &Instantiation, + ) -> Result, String> { + if module.kw != "module" && module.kw != "macromodule" { + return Err(format!( + "the instantiation is written inside a `{}`, and lucisv inlines into a `module`; no edits were made.", + module.kw + )); + } + let [instance] = inst.instances.as_slice() else { + return Err(MANY_INSTANCES.to_string()); + }; + if !instance.dims.is_empty() { + return Err(format!( + "`{}` is an array of instances, which stands for as many copies of `{}` as its range has; lucisv inlines one instance.", + instance.name, inst.module + )); + } + Ok(Site { + module, + module_span, + target: inst.module.clone(), + instance: instance.name.clone(), + span: item.span, + indent: indent_at(text, item.span.start), + bindings: bindings(text, instance)?, + overrides: overrides(text, inst)?, + }) + } +} + +/// The `module` whose body holds `offset`. +fn module_at(items: &[Item], offset: u32) -> Option<(&Module, TextRange)> { + for item in items { + let ItemKind::Module(module) = &item.kind else { continue }; + if item.span.contains(offset) { + return Some((module, item.span)); + } + } + None +} + +/// Whether an item is the one the cursor is on. The end offset counts: a +/// cursor sitting just past the `;` is still on the statement it closes. +fn covers(item: &Item, offset: u32) -> bool { + item.span.contains(offset) || item.span.end == offset +} + +/// Every port connection, or the sentence for the shape lucisv will not read. +fn bindings(text: &str, instance: &Instance) -> Result, String> { + let named = match &instance.conns { + Connections::Named(list) => list, + Connections::Ordered(list) if list.is_empty() => return Ok(Vec::new()), + Connections::Ordered(_) => return Err(POSITIONAL.to_string()), + }; + if !instance.conn_directives.is_empty() { + return Err(DIRECTIVES.to_string()); + } + let mut out = Vec::new(); + for conn in named.iter().filter_map(ListElem::ok) { + if conn.name == "*" { + return Err(WILDCARD.to_string()); + } + if conn.name.is_empty() { + return Err(POSITIONAL.to_string()); + } + let value = match &conn.expr { + // `.clk` is the shorthand for `.clk(clk)`. + None => Value::Name(conn.name.clone()), + Some(expr) => value_of(text, &conn.name, expr)?, + }; + out.push(Binding { port: conn.name.clone(), value }); + } + Ok(out) +} + +/// Every parameter override, as `(name, the text it is given)`. +fn overrides(text: &str, inst: &Instantiation) -> Result, String> { + let Some(params) = &inst.params else { return Ok(Vec::new()) }; + if !inst.param_directives.is_empty() { + return Err(DIRECTIVES.to_string()); + } + let mut out = Vec::new(); + for param in params.iter().filter_map(ListElem::ok) { + if param.name == "*" || param.name.is_empty() { + return Err(POSITIONAL_PARAMS.to_string()); + } + let written = match ¶m.expr { + None => param.name.clone(), + Some(expr) => slice(text, expr.span).trim().to_string(), + }; + if written.is_empty() { + return Err(format!( + "`.{}()` overrides `{}` with nothing at all; give it a value first.", + param.name, param.name + )); + } + out.push((param.name.clone(), written)); + } + Ok(out) +} + +/// What one connection's expression binds to: a plain name, a literal, or a +/// refusal naming the expression the user has to give a name of its own. +fn value_of(text: &str, port: &str, expr: &Expr) -> Result { + let written = slice(text, expr.span).trim().to_string(); + match &expr.kind { + ExprKind::Ident(_) => Ok(Value::Name(written)), + ExprKind::Number(_) | ExprKind::Str(_) => Ok(Value::Literal(written)), + ExprKind::Empty(_) => Ok(Value::Unconnected), + // Everything else — a slice, a concatenation, an arithmetic + // expression — is a value the port's name stands for inside the + // module, and writing it wherever that name is read would both + // duplicate it and change what a left-hand side means. + _ => Err(format!( + "`.{port}({written})` connects a port to an expression rather than to a name, and lucisv substitutes the connected name wherever the port is used; connect `.{port}({written})` to a named wire first." + )), + } +} + +/// 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() +} + +fn slice(text: &str, span: TextRange) -> &str { + text.get(span.start as usize..span.end as usize).unwrap_or("") +} + +const MANY_INSTANCES: &str = + "the instantiation declares more than one instance, and each of them is a copy of the module's body; lucisv inlines one instance at a time."; +const POSITIONAL: &str = + "the instantiation connects its ports by position, so lucisv cannot tell which port each expression is for; convert to named connections first."; +const POSITIONAL_PARAMS: &str = + "the instantiation overrides its parameters by position, so lucisv cannot tell which parameter each value is for; convert to named connections first."; +const WILDCARD: &str = + "the instantiation connects its ports with `.*`, which names no port at all; expand `.*` first (lucisv: expand `.*`)."; +const DIRECTIVES: &str = + "the instantiation's list carries compiler directives, and lucisv does not evaluate one, so it cannot tell which connections are really written."; diff --git a/crates/vlog_refactor/src/inline/source.rs b/crates/vlog_refactor/src/inline/source.rs new file mode 100644 index 0000000..db2d7fe --- /dev/null +++ b/crates/vlog_refactor/src/inline/source.rs @@ -0,0 +1,322 @@ +//! What `S` is made of, and the shapes of `S` lucisv will not copy into +//! another module. +//! +//! An inline copies `S`'s body into `M` and substitutes names into it, so the +//! refusals here are all one question asked of different constructs: *would +//! this piece still mean the same thing written inside `M`?* A `generate` +//! block's names are reachable through the hierarchy, an `initial` block's +//! meaning depends on when it runs, a macro's body is text lucisv never read, +//! and an `inout` port is a name whose direction the substitution cannot +//! honour. Each is a sentence rather than a guess. + +use vlog_parser::ast::{ + AnsiPort, Connections, Item, ItemKind, ListElem, Module, ParamPort, PortList, SourceFile, +}; +use vlog_parser::span::TextRange; +use vlog_semantic::WorkspaceIndex; + +/// One port of `S`, in declaration order. +pub(super) struct Port { + pub(super) name: String, + /// `input`, `output`, or empty when the header writes none. + pub(super) dir: String, +} + +/// One entry of `S`'s parameter port list, in declaration order. +pub(super) struct Param { + pub(super) name: String, + /// Whatever the declaration writes between its keyword and its name + /// (`int`, `type`, `logic [3:0]`), inherited from the entry before it when + /// this one writes none. A span rather than text: the type may name + /// another parameter, and every name inside it is substituted the way the + /// body's are. + pub(super) ty: TextRange, + /// The default value as the header writes it; empty when it writes none. + pub(super) default: TextRange, + /// True for a header `localparam`, which an instantiation may not + /// override. + pub(super) local: bool, +} + +/// `S`, read. +pub(super) struct Source { + pub(super) ports: Vec, + pub(super) params: Vec, + /// The bytes the inline copies: `S`'s items and the comments written + /// among them. Empty for a module with an empty body. + pub(super) body: TextRange, + /// The package paths `S`'s header imports (`p::*`, `p::word_t`), one per + /// path rather than one per statement — a header may write several paths + /// in one `import`, and `M` may already have some of them. + pub(super) imports: Vec, + /// Every `.name` shorthand `S`'s own body writes in an instantiation of + /// its own — `.clk_i` standing for `.clk_i(clk_i)` — as the name and the + /// bytes it occupies. The shorthand names a signal *and* a port with one + /// token, so an inline that renames the signal has to spell it out; see + /// [`shorthands`]. + pub(super) shorthands: Vec<(String, TextRange)>, +} + +impl Source { + /// Read `S` out of its own file, or say why lucisv will not inline it. + pub(super) fn read( + tree: &SourceFile, + text: &str, + index: &WorkspaceIndex, + name: &str, + ) -> Result { + let Some(module) = declaration(tree, name) else { + return Err(format!( + "the file that declared `{name}` no longer declares it, so lucisv cannot inline it." + )); + }; + if module.kw != "module" && module.kw != "macromodule" { + return Err(format!( + "`{name}` is an `{}`, whose signals are its surface rather than a body lucisv can copy; no edits were made.", + module.kw + )); + } + for item in &module.items { + copyable(item, name)?; + } + Ok(Source { + ports: ports(module, index, name)?, + params: params(module, text), + body: body(module), + imports: imports(module), + shorthands: shorthands(module, name)?, + }) + } +} + +/// The declaration of `name` in its own file. +fn declaration<'t>(tree: &'t SourceFile, name: &str) -> Option<&'t Module> { + tree.items.iter().find_map(|item| match &item.kind { + ItemKind::Module(module) if module.name == name => Some(module), + _ => None, + }) +} + +/// The item kinds lucisv will not copy into another module's body. +fn copyable(item: &Item, name: &str) -> Result<(), String> { + let what = match &item.kind { + ItemKind::Initial(_) => "an `initial` block", + ItemKind::Final(_) => "a `final` block", + ItemKind::MacroItem(_) => { + return Err(format!( + "`{name}` invokes a macro as one of its items, and lucisv does not expand macros, so it cannot tell what it would be copying." + )) + } + ItemKind::Directive(_) => { + return Err(format!( + "`{name}` writes a compiler directive among its items, and lucisv does not evaluate one, so it cannot tell what its body really is." + )) + } + ItemKind::GenerateRegion { .. } + | ItemKind::GenIf(_) + | ItemKind::GenFor(_) + | ItemKind::GenCase(_) + | ItemKind::GenBlock(_) => { + return Err(format!( + "`{name}` uses a `generate` construct, whose block names are reachable through the hierarchy (`u_{name}.gen.x`) and would become names of `M`'s own; lucisv will not inline it." + )) + } + ItemKind::Bind(_) => "a `bind` directive", + ItemKind::Module(_) | ItemKind::Package { .. } => "a declaration of its own", + ItemKind::Error(_) => { + return Err(format!("part of `{name}` did not parse, so lucisv will not copy it.")) + } + _ => return Ok(()), + }; + Err(format!( + "`{name}` holds {what}, which does not mean the same thing written inside another module; lucisv made no edits." + )) +} + +/// `S`'s ports, in declaration order, or the sentence for a port whose name +/// lucisv cannot simply replace with the one connected to it. +fn ports(module: &Module, index: &WorkspaceIndex, name: &str) -> Result, String> { + let declared = match &module.ports { + PortList::Ansi(declared) => declared, + PortList::NonAnsi(_) => return Err(non_ansi(name)), + PortList::Empty | PortList::None => return Ok(Vec::new()), + }; + if !module.port_directives.is_empty() { + return Err(format!( + "`{name}`'s port list carries compiler directives, so which ports it really declares depends on the configuration; lucisv made no edits." + )); + } + let mut out: Vec = Vec::new(); + let mut dir = String::new(); + for port in declared.iter().filter_map(ListElem::ok) { + if let Some(written) = &port.dir { + dir = written.clone(); + } + if port.name.is_empty() { + continue; + } + connectable(port, index, name, &dir)?; + out.push(Port { name: port.name.clone(), dir: dir.clone() }); + } + Ok(out) +} + +/// The three port shapes an inline refuses: an `inout`, an unpacked array, and +/// an interface. +fn connectable( + port: &AnsiPort, + index: &WorkspaceIndex, + name: &str, + dir: &str, +) -> Result<(), String> { + if dir == "inout" { + return Err(format!( + "`{name}`'s port `{}` is an `inout`, whose two directions lucisv cannot reproduce by substituting a name; no edits were made.", + port.name + )); + } + if !port.unpacked.is_empty() { + return Err(format!( + "`{name}`'s port `{}` has an unpacked dimension, and a port array is not one name lucisv can substitute; no edits were made.", + port.name + )); + } + // An interface port writes no direction and names an interface — or a + // modport of one, which is a name with a `.` in it and never a data type. + let written = port.ty.name.trim(); + let head = written.split('.').next().unwrap_or(""); + let interface = written.contains('.') + || index.units(head).iter().any(|def| def.kind == vlog_semantic::SymbolKind::Interface); + match interface && dir.is_empty() { + true => Err(format!( + "`{name}`'s port `{}` is of interface type `{written}`, whose signals are named through the port rather than substituted for it; lucisv made no edits.", + port.name + )), + false => Ok(()), + } +} + +/// `S`'s parameter port list, in declaration order. A continuation entry +/// (`#(parameter int A = 1, B = 2)`) inherits the keyword *and* the type of +/// the entry before it, which is what the language says and what the +/// `localparam` written in its place has to say too. +fn params(module: &Module, text: &str) -> Vec { + let Some(declared) = &module.param_ports else { return Vec::new() }; + let mut out = Vec::new(); + let (mut kw, mut ty) = (String::new(), TextRange::empty(0)); + for param in declared.iter().filter_map(ListElem::ok) { + if let Some(written) = ¶m.kw { + kw = written.clone(); + ty = type_span(text, param); + } + if param.name.is_empty() { + continue; + } + out.push(Param { + name: param.name.clone(), + ty, + default: param.default.as_ref().map_or_else(|| TextRange::empty(0), |e| e.span), + local: kw == "localparam", + }); + } + out +} + +/// The bytes one parameter writes between its keyword and its name. +fn type_span(text: &str, param: &ParamPort) -> TextRange { + let head = TextRange::new(param.span.start, param.name_span.start); + let written = slice(text, head); + let keyword = ["parameter", "localparam"] + .iter() + .find_map(|kw| written.find(kw).map(|at| at + kw.len())) + .unwrap_or(0); + TextRange::new(head.start + keyword as u32, head.end) +} + +/// The bytes an inline copies: from the first thing written in `S`'s body — an +/// item, its leading comment or its attribute — to the last. +fn body(module: &Module) -> TextRange { + let mut span: Option = None; + let mut widen = |extent: TextRange| { + span = Some(match span { + None => extent, + Some(so_far) => { + TextRange::new(so_far.start.min(extent.start), so_far.end.max(extent.end)) + } + }); + }; + for item in &module.items { + widen(extent(item)); + } + for comment in &module.dangling { + widen(comment.span); + } + span.unwrap_or_else(|| TextRange::empty(0)) +} + +/// The bytes one item owns: itself, its attributes and its own comments. +fn extent(item: &Item) -> TextRange { + let mut out = item.span; + let comments = item + .meta + .leading + .iter() + .chain(&item.meta.before_sep) + .chain(&item.meta.trailing) + .map(|c| c.span) + .chain(item.meta.attrs.iter().map(|a| a.span)); + for span in comments { + out = TextRange::new(out.start.min(span.start), out.end.max(span.end)); + } + out +} + +/// Every `.name` shorthand `S`'s body writes in an instantiation of its own, +/// and the refusal for the `.*` that cannot be spelled out one name at a time. +/// +/// This is the one place a name is written **once** and read **twice**: +/// `.clk_i` names a port of the module being instantiated and, at the same +/// token, the signal connected to it. Substituting a new signal name over it +/// would silently reconnect a different port, and leaving it alone would bind +/// a name `M` may not even declare — the trial's `counter` inside `cb_filter` +/// is that bug caught (work log, 2026-09-06). So the shorthand is *expanded* +/// (`.clk_i(clk)`) wherever the signal it names is one the inline renames, and +/// a `.*`, which names every signal at once, is refused. +fn shorthands(module: &Module, name: &str) -> Result, String> { + let mut out = Vec::new(); + for item in &module.items { + let ItemKind::Instantiation(inst) = &item.kind else { continue }; + let params = inst.params.iter().flatten(); + let conns = inst.instances.iter().flat_map(|instance| match &instance.conns { + Connections::Named(list) => list.as_slice(), + Connections::Ordered(_) => &[], + }); + for conn in params.chain(conns).filter_map(ListElem::ok) { + if conn.name == "*" { + return Err(format!( + "`{name}`'s body connects `{}`'s ports with `.*`, and inlining renames the signals those ports bind to; expand `.*` in `{name}` first (lucisv: expand `.*`).", + inst.module + )); + } + if conn.expr.is_none() && !conn.name.is_empty() { + out.push((conn.name.clone(), conn.name_span)); + } + } + } + Ok(out) +} + +/// The package paths `S`'s header imports, one entry per path. +fn imports(module: &Module) -> Vec { + module.imports.iter().flat_map(|import| import.paths.iter().map(|path| path.text())).collect() +} + +fn slice(text: &str, span: TextRange) -> &str { + text.get(span.start as usize..span.end as usize).unwrap_or("") +} + +fn non_ansi(name: &str) -> String { + format!( + "`{name}` declares its ports in the Verilog-2001 style, with the directions written in its body; convert them to ANSI ports first (lucisv: convert to ANSI ports)." + ) +} diff --git a/crates/vlog_refactor/src/lib.rs b/crates/vlog_refactor/src/lib.rs index 3a53540..94f2145 100644 --- a/crates/vlog_refactor/src/lib.rs +++ b/crates/vlog_refactor/src/lib.rs @@ -30,6 +30,7 @@ mod check; mod extract; mod imports; +mod inline; mod instantiate; mod ports; mod references; @@ -40,6 +41,7 @@ pub use extract::{extract_module, extract_site, extract_title, ExtractSite, Home pub use imports::{ imported_packages, organize_counts, organize_imports, organize_title, unused_imports, }; +pub use inline::{inline_module, inline_site, inline_title, InlineSite}; pub use references::find_references; pub use instantiate::{ diff --git a/crates/vlog_refactor/tests/corpus.rs b/crates/vlog_refactor/tests/corpus.rs index 43e0a1e..b5cb131 100644 --- a/crates/vlog_refactor/tests/corpus.rs +++ b/crates/vlog_refactor/tests/corpus.rs @@ -948,3 +948,236 @@ fn five_regions_of_real_rtl_extract_into_modules_that_parse_format_and_converge( ); assert_eq!(done.len(), 5, "five real regions must extract: {done:?}"); } + +// ---------------------------------------------------------------------- +// §53.2 inline module +// ---------------------------------------------------------------------- + +/// The tree the inline trial runs over: `corpus/` by default, or whatever +/// `LUCISV_INLINE_ROOT` names — a scratch copy of opentitan, for the trial the +/// feature README records. +fn inline_root() -> Option> { + let root = match std::env::var("LUCISV_INLINE_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) +} + +/// Every instantiation written directly in a module's body, as an offset an +/// inline could be asked about. +fn instantiations(text: &str) -> Vec<(String, String, 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 }; + for item in &module.items { + if let ItemKind::Instantiation(inst) = &item.kind { + out.push((module.name.clone(), inst.module.clone(), item.span.start)); + } + } + } + out +} + +/// Five real instantiations, inlined in memory: each result parses, formats, +/// converges, and leaves the design's census of unbound names where it was. +/// +/// With `LUCISV_INLINE_OUT` set, each case's two files are also written out +/// twice — `case_N/before/` and `case_N/after/` — which is what the +/// `lucisv check --select unused-signal,undriven-net` half of the trial reads. +#[test] +fn five_instantiations_of_real_rtl_inline_and_the_result_parses_formats_and_converges() { + let Some(files) = inline_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 = census(&sources); + let out_dir = std::env::var("LUCISV_INLINE_OUT").ok().map(PathBuf::from); + + let started = Instant::now(); + let mut done: Vec = Vec::new(); + let mut refusals = 0usize; + 'files: for (path, text) in &sources { + for (host, target, at) in instantiations(text) { + if done.len() == 5 { + break 'files; + } + let edit = match vlog_refactor::inline_module(&sources, path, at) { + Ok(edit) => edit, + // Printed, not only counted: which instantiations the trial + // refuses and why is the other half of a reproducible run. + Err(said) => { + refusals += 1; + println!(" refused `{target}` in `{host}`: {said}"); + continue; + } + }; + let mut after: Vec<(PathBuf, String)> = sources.clone(); + for (file, edits) in &edit.edits { + let Some(slot) = after.iter_mut().find(|(held, _)| held == file) else { + panic!("the inline edits {} which is not in scope", file.display()) + }; + let mut written = slot.1.clone(); + for one in edits.iter().rev() { + written.replace_range( + one.range.start as usize..one.range.end as usize, + &one.new_text, + ); + } + slot.1 = written; + } + + let edited = &after.iter().find(|(held, _)| held == path).expect("edited").1; + let (_, diagnostics) = vlog_parser::parse_source_tolerant(edited); + assert!( + diagnostics.is_empty(), + "inlining `{target}` into `{host}` leaves {} unparseable: {diagnostics:?}\n{edited}", + path.display() + ); + let once = vlog_formatter::format_source(edited, &config) + .unwrap_or_else(|e| panic!("the formatter refuses {}: {e}", path.display())); + let twice = vlog_formatter::format_source(&once, &config).expect("formats again"); + assert_eq!(once, twice, "{} does not converge", path.display()); + + // Written before the census is asserted, so a run that fails + // leaves the pair on disk to look at. + if let Some(dir) = &out_dir { + write_case(dir, done.len(), path, &target, &sources, &after); + } + let now = census(&after); + let gained = borne(&before, &now, path); + println!( + " inlined `{target}` into `{host}` ({}): {} name(s) newly unbound, all of them `{target}`'s own", + path.display(), + gained.len() + ); + done.push(format!("{target} in {host}")); + } + } + println!( + "inline over {} files: {} instantiations inlined, {} refused, in {:.2}s", + sources.len(), + done.len(), + refusals, + started.elapsed().as_secs_f64() + ); + assert_eq!(done.len(), 5, "five real instantiations must inline: {done:?}"); +} + +/// One trial case on disk: the instantiating file and the inlined module's +/// own, before the inline and after it, so `lucisv check` can be run over +/// each pair. +fn write_case( + dir: &Path, + n: usize, + host: &Path, + target: &str, + before: &[(PathBuf, String)], + after: &[(PathBuf, String)], +) { + let declaring = before + .iter() + .find(|(path, text)| { + path != host && text.contains(&format!("module {target}")) && { + let (tree, _) = vlog_parser::parse_source_tolerant(text); + tree.items + .iter() + .any(|item| matches!(&item.kind, ItemKind::Module(m) if m.name == target)) + } + }) + .map(|(path, _)| path.clone()); + for (label, sources) in [("before", before), ("after", after)] { + let out = dir.join(format!("case_{n}")).join(label); + if fs::create_dir_all(&out).is_err() { + return; + } + for path in [Some(host.to_path_buf()), declaring.clone()].into_iter().flatten() { + let Some((_, text)) = sources.iter().find(|(held, _)| *held == path) else { continue }; + let Some(name) = path.file_name() else { continue }; + let _ = fs::write(out.join(name), text); + } + } +} + +/// Every name a design fails to bind, per file, with its duplicates — the +/// census an inline is held to. +/// +/// An inline **copies**, so the whole-design count is the wrong number: a name +/// `S` already could not resolve is one `M` now cannot resolve either, and the +/// total legitimately grows by one per copy. What must hold instead is that +/// every name the edited file newly fails to bind is one the *copied* module's +/// own file already failed to bind — see [`borne`]. +fn census(sources: &[(PathBuf, String)]) -> Vec<(PathBuf, Vec)> { + let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str()))); + let mut out = Vec::new(); + for (path, 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); + let mut names = Vec::new(); + 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(_))) { + names.push(reference.name.clone()); + } + } + names.sort(); + out.push((path.clone(), names)); + } + out +} + +/// The names `edited` newly fails to bind, asserting on the way that no other +/// file's census moved at all and that every new name is one some *other* +/// file already could not bind — which for an inline is the file `S` was +/// copied out of. +fn borne( + before: &[(PathBuf, Vec)], + after: &[(PathBuf, Vec)], + edited: &Path, +) -> Vec { + let mut elsewhere: Vec = Vec::new(); + let mut gained: Vec = Vec::new(); + for (path, now) in after { + let was = before + .iter() + .find(|(held, _)| held == path) + .map_or_else(Vec::new, |(_, names)| names.clone()); + if path != edited { + assert_eq!(&was, now, "{} was not edited, and its census moved", path.display()); + elsewhere.extend(now.iter().cloned()); + continue; + } + let mut left = was.clone(); + for name in now { + match left.iter().position(|held| held == name) { + Some(at) => { + left.remove(at); + } + None => gained.push(name.clone()), + } + } + } + for name in &gained { + assert!( + elsewhere.contains(name), + "`{name}` became unbound in {} and no other file leaves it unbound either", + edited.display() + ); + } + gained +} diff --git a/crates/vlog_refactor/tests/inline.rs b/crates/vlog_refactor/tests/inline.rs new file mode 100644 index 0000000..ea1126b --- /dev/null +++ b/crates/vlog_refactor/tests/inline.rs @@ -0,0 +1,604 @@ +//! Inlining a module: the substitution, the prefixing rule, the refusals and +//! the round trip with `extract_module`. See +//! `docs/features/extract-inline-module/README.md`. + +use std::path::{Path, PathBuf}; + +use vlog_refactor::{inline_module, inline_site, inline_title, RefactorEdit, TextEdit}; + +const M: &str = "/rtl/top.sv"; +const S: &str = "/rtl/sub.sv"; + +/// A two-port module, and a `top` that instantiates it. +const SUB: &str = "\ +module sub ( + input logic a, + input logic b, + output logic q +); + logic s; // the and + assign s = a & b; + assign q = s; +endmodule +"; + +const TOP: &str = "\ +module top ( + input logic x, + input logic y, + output logic z +); + sub u_sub ( + .a(x), + .b(y), + .q(z) + ); +endmodule +"; + +fn files(top: &str, sub: &str) -> Vec<(PathBuf, String)> { + vec![(PathBuf::from(M), top.to_string()), (PathBuf::from(S), sub.to_string())] +} + +/// Inline the instantiation `top` writes, and return the edited `top`. +fn inlined(top: &str, sub: &str) -> Result { + let at = top.find("sub u_sub").expect("the instantiation") as u32 + 2; + let edit = inline_module(&files(top, sub), Path::new(M), at)?; + Ok(applied(top, &edit)) +} + +fn applied(text: &str, edit: &RefactorEdit) -> String { + let mut out = text.to_string(); + for TextEdit { range, new_text } in edit.edits_for(&PathBuf::from(M)).iter().rev() { + out.replace_range(range.start as usize..range.end as usize, new_text); + } + out +} + +fn refusal(top: &str, sub: &str) -> String { + inlined(top, sub).expect_err("a refusal") +} + +// ---------------------------------------------------------------------- +// the substitution +// ---------------------------------------------------------------------- + +#[test] +fn a_two_port_module_is_inlined_with_its_ports_replaced_by_the_connected_names() { + let out = inlined(TOP, SUB).expect("inlines"); + assert!(out.contains(" logic s; // the and\n"), "{out}"); + assert!(out.contains("assign s = x & y;"), "{out}"); + assert!(out.contains("assign z = s;"), "{out}"); + assert!(!out.contains("sub u_sub"), "the instantiation is gone: {out}"); + assert_eq!(out.matches("// the and").count(), 1, "the comment travels once: {out}"); +} + +#[test] +fn the_edit_touches_only_the_file_the_cursor_is_in() { + let at = TOP.find("sub u_sub").expect("the instantiation") as u32 + 2; + let edit = inline_module(&files(TOP, SUB), Path::new(M), at).expect("inlines"); + assert_eq!(edit.file_count(), 1, "`sub.sv` is copied out of, never written to"); + assert_eq!(edit.edit_count(), 1, "one replacement"); + assert!(edit.created.is_empty()); + assert!( + edit.warnings.iter().any(|w| w.contains("still declared where it was")), + "{:?}", + edit.warnings + ); +} + +#[test] +fn a_literal_may_be_connected_to_an_input() { + let top = TOP.replace(".b(y)", ".b(1'b1)"); + let out = inlined(&top, SUB).expect("inlines"); + assert!(out.contains("assign s = x & 1'b1;"), "{out}"); +} + +#[test] +fn the_implicit_dot_name_connection_is_read_as_the_name_it_stands_for() { + let top = "\ +module top ( + input logic a, + input logic b, + output logic q +); + sub u_sub (.a, .b, .q); +endmodule +"; + let out = inlined(top, SUB).expect("inlines"); + assert!(out.contains("assign s = a & b;"), "{out}"); + assert!(out.contains("assign q = s;"), "{out}"); +} + +#[test] +fn a_comment_written_inside_the_instantiation_is_written_back_above_the_body() { + let top = TOP.replace(".a(x),", ".a(x), // the first"); + let out = inlined(&top, SUB).expect("inlines"); + assert_eq!(out.matches("// the first").count(), 1, "{out}"); + assert!(out.contains("// the first\n"), "{out}"); +} + +// ---------------------------------------------------------------------- +// parameters +// ---------------------------------------------------------------------- + +const WIDE: &str = "\ +module wide #( + parameter int W = 4 +) ( + input logic [W-1:0] a, + output logic [W-1:0] q +); + logic [W-1:0] t; + assign t = a; + assign q = t; +endmodule +"; + +const USES_WIDE: &str = "\ +module top ( + input logic [7:0] x, + output logic [7:0] z +); + wide #(.W(8)) u_wide ( + .a(x), + .q(z) + ); +endmodule +"; + +fn wide_files() -> Vec<(PathBuf, String)> { + vec![ + (PathBuf::from(M), USES_WIDE.to_string()), + (PathBuf::from("/rtl/wide.sv"), WIDE.to_string()), + ] +} + +#[test] +fn a_parameter_becomes_a_localparam_holding_the_override() { + let at = USES_WIDE.find("wide #(").expect("the instantiation") as u32 + 1; + let edit = inline_module(&wide_files(), Path::new(M), at).expect("inlines"); + let out = applied(USES_WIDE, &edit); + assert!(out.contains("localparam int W = 8;"), "{out}"); + assert!(out.contains("logic [W-1:0] t;"), "{out}"); + assert!(!out.contains("u_wide"), "{out}"); +} + +#[test] +fn a_parameter_with_no_override_keeps_its_default() { + let top = USES_WIDE.replace("wide #(.W(8)) u_wide", "wide u_wide"); + let files = + vec![(PathBuf::from(M), top.clone()), (PathBuf::from("/rtl/wide.sv"), WIDE.to_string())]; + let at = top.find("wide u_wide").expect("the instantiation") as u32 + 1; + let out = applied(&top, &inline_module(&files, Path::new(M), at).expect("inlines")); + assert!(out.contains("localparam int W = 4;"), "{out}"); +} + +// ---------------------------------------------------------------------- +// prefixing +// ---------------------------------------------------------------------- + +#[test] +fn a_name_collision_prefixes_every_name_the_module_declares() { + // `top` declares an `s` of its own, so `sub`'s `s` becomes `u_sub_s`. + let top = TOP.replace(" sub u_sub (", " logic s;\n sub u_sub ("); + let edit = { + let at = top.find("sub u_sub").expect("the instantiation") as u32 + 2; + inline_module(&files(&top, SUB), Path::new(M), at).expect("inlines") + }; + let out = applied(&top, &edit); + assert!(out.contains("logic u_sub_s; // the and"), "{out}"); + assert!(out.contains("assign u_sub_s = x & y;"), "{out}"); + assert!(out.contains("assign z = u_sub_s;"), "{out}"); + assert!( + edit.warnings.iter().any(|w| w.contains("`s`") && w.contains("u_sub_")), + "the warning says which name collided: {:?}", + edit.warnings + ); +} + +#[test] +fn no_collision_means_no_prefix_and_the_warning_says_so() { + let at = TOP.find("sub u_sub").expect("the instantiation") as u32 + 2; + let edit = inline_module(&files(TOP, SUB), Path::new(M), at).expect("inlines"); + assert!(edit.warnings.iter().any(|w| w.contains("under its own names")), "{:?}", edit.warnings); +} + +// ---------------------------------------------------------------------- +// imports +// ---------------------------------------------------------------------- + +#[test] +fn an_import_the_instantiator_lacks_is_copied_in() { + let pkg = "package p; typedef logic word_t; endpackage\n"; + let sub = "\ +module sub import p::*; ( + input logic a, + output logic q +); + word_t s; + assign s = a; + assign q = s; +endmodule +"; + let top = "\ +module top ( + input logic x, + output logic z +); + sub u_sub (.a(x), .q(z)); +endmodule +"; + let files = vec![ + (PathBuf::from(M), top.to_string()), + (PathBuf::from(S), sub.to_string()), + (PathBuf::from("/rtl/p.sv"), pkg.to_string()), + ]; + let at = top.find("sub u_sub").expect("the instantiation") as u32 + 2; + let edit = inline_module(&files, Path::new(M), at).expect("inlines"); + let out = applied(top, &edit); + assert!(out.contains("import p::*;"), "{out}"); + assert!(edit.warnings.iter().any(|w| w.contains("import p::*;")), "{:?}", edit.warnings); +} + +// ---------------------------------------------------------------------- +// the refusals +// ---------------------------------------------------------------------- + +#[test] +fn an_expression_connection_is_refused() { + let message = refusal(&TOP.replace(".a(x)", ".a(x & y)"), SUB); + assert!(message.contains("connect `.a(x & y)` to a named wire first"), "{message}"); +} + +#[test] +fn a_wildcard_connection_is_refused() { + let top = TOP.replace(".a(x),\n .b(y),\n .q(z)", ".*"); + let message = refusal(&top, SUB); + assert!(message.contains("expand `.*` first"), "{message}"); +} + +#[test] +fn positional_connections_are_refused() { + let top = TOP.replace(".a(x),\n .b(y),\n .q(z)", "x,\n y,\n z"); + let message = refusal(&top, SUB); + assert!(message.contains("convert to named connections first"), "{message}"); +} + +#[test] +fn an_unconnected_input_is_refused() { + let message = refusal(&TOP.replace(".b(y)", ".b()"), SUB); + assert!(message.contains("`.b` is left unconnected"), "{message}"); +} + +#[test] +fn an_output_connected_to_a_literal_is_refused() { + let message = refusal(&TOP.replace(".q(z)", ".q(1'b0)"), SUB); + assert!(message.contains("drives `sub`'s output into a literal"), "{message}"); +} + +#[test] +fn a_hierarchical_reference_to_the_instance_is_refused_and_names_the_file() { + let top = TOP.replace("endmodule", " assign z = u_sub.s;\nendmodule"); + let message = refusal(&top, SUB); + assert!(message.contains("named as a scope of the design hierarchy in top.sv"), "{message}"); +} + +#[test] +fn a_hierarchical_reference_from_another_file_is_refused_and_names_that_file() { + let tb = "module tb;\n top u_top ();\n initial $display(u_top.u_sub.s);\nendmodule\n"; + let mut files = files(TOP, SUB); + files.push((PathBuf::from("/rtl/tb.sv"), tb.to_string())); + let at = TOP.find("sub u_sub").expect("the instantiation") as u32 + 2; + let message = inline_module(&files, Path::new(M), at).expect_err("a refusal"); + assert!(message.contains("tb.sv"), "{message}"); +} + +#[test] +fn a_bind_naming_the_instance_is_refused() { + let top = + TOP.replace("endmodule", " bind u_sub sub u_check (.a(x), .b(y), .q(z));\nendmodule"); + let message = refusal(&top, SUB); + assert!(message.contains("named as a scope of the design hierarchy"), "{message}"); +} + +#[test] +fn a_generate_in_the_module_is_refused() { + let sub = SUB.replace( + " assign q = s;", + " generate\n if (1) begin : g\n assign q = s;\n end\n endgenerate", + ); + let message = refusal(TOP, &sub); + assert!(message.contains("`generate`"), "{message}"); +} + +#[test] +fn an_initial_block_in_the_module_is_refused() { + let sub = SUB.replace(" assign q = s;", " assign q = s;\n initial $display(\"hi\");"); + let message = refusal(TOP, &sub); + assert!(message.contains("`initial` block"), "{message}"); +} + +#[test] +fn a_macro_item_in_the_module_is_refused() { + let sub = SUB.replace(" assign q = s;", " assign q = s;\n `ASSERT(a, b)"); + let message = refusal(TOP, &sub); + assert!(message.contains("macro"), "{message}"); +} + +#[test] +fn a_conditional_directive_in_the_module_is_refused() { + let sub = SUB.replace(" assign q = s;", "`ifdef X\n assign q = s;\n`endif"); + let message = refusal(TOP, &sub); + assert!(message.contains("compiler directive"), "{message}"); +} + +#[test] +fn an_inout_port_is_refused() { + let sub = SUB.replace(" input logic b,", " inout logic b,"); + let message = refusal(TOP, &sub); + assert!(message.contains("is an `inout`"), "{message}"); +} + +#[test] +fn an_unpacked_array_port_is_refused() { + let sub = SUB.replace(" input logic b,", " input logic b [2],"); + let message = refusal(TOP, &sub); + assert!(message.contains("unpacked dimension"), "{message}"); +} + +#[test] +fn an_interface_port_is_refused() { + let iface = "interface bus_if;\n logic v;\nendinterface\n"; + let sub = "\ +module sub ( + bus_if m, + output logic q +); + assign q = 1'b0; +endmodule +"; + let top = "module top (output logic z);\n sub u_sub (.m(bus), .q(z));\nendmodule\n"; + let files = vec![ + (PathBuf::from(M), top.to_string()), + (PathBuf::from(S), sub.to_string()), + (PathBuf::from("/rtl/bus_if.sv"), iface.to_string()), + ]; + let at = top.find("sub u_sub").expect("the instantiation") as u32 + 2; + let message = inline_module(&files, Path::new(M), at).expect_err("a refusal"); + assert!(message.contains("interface type"), "{message}"); +} + +#[test] +fn a_module_declared_twice_is_refused() { + let mut files = files(TOP, SUB); + files.push((PathBuf::from("/rtl/other.sv"), SUB.to_string())); + let at = TOP.find("sub u_sub").expect("the instantiation") as u32 + 2; + let message = inline_module(&files, Path::new(M), at).expect_err("a refusal"); + assert!(message.contains("more than one indexed file"), "{message}"); +} + +#[test] +fn a_module_the_workspace_does_not_declare_is_refused() { + let files = vec![(PathBuf::from(M), TOP.to_string())]; + let at = TOP.find("sub u_sub").expect("the instantiation") as u32 + 2; + let message = inline_module(&files, Path::new(M), at).expect_err("a refusal"); + assert!(message.contains("indexes no module named `sub`"), "{message}"); +} + +#[test] +fn a_module_declared_in_the_same_file_is_refused() { + let both = format!("{TOP}\n{SUB}"); + let files = vec![(PathBuf::from(M), both.clone())]; + let at = both.find("sub u_sub").expect("the instantiation") as u32 + 2; + let message = inline_module(&files, Path::new(M), at).expect_err("a refusal"); + assert!(message.contains("same file it is instantiated in"), "{message}"); +} + +#[test] +fn a_differing_timescale_is_refused() { + let sub = format!("`timescale 1ps / 1ps\n{SUB}"); + let top = format!("`timescale 1ns / 1ps\n{TOP}"); + let message = refusal(&top, &sub); + assert!(message.contains("`timescale"), "{message}"); +} + +#[test] +fn an_array_of_instances_is_refused() { + let top = TOP.replace("sub u_sub (", "sub u_sub [1:0] ("); + let message = refusal(&top, SUB); + assert!(message.contains("array of instances"), "{message}"); +} + +#[test] +fn an_escaped_name_a_prefix_cannot_resolve_is_refused() { + let sub = SUB + .replace("logic s; // the and", "logic \\s-1 ; // the and") + .replace("assign s = a & b;", "assign \\s-1 = a & b;") + .replace("assign q = s;", "assign q = \\s-1 ;"); + let top = TOP.replace(" sub u_sub (", " logic \\s-1 ;\n sub u_sub ("); + let message = refusal(&top, &sub); + assert!(message.contains("escaped identifier"), "{message}"); +} + +// ---------------------------------------------------------------------- +// the cheap gate +// ---------------------------------------------------------------------- + +#[test] +fn the_site_gate_finds_the_instantiation_and_names_what_to_read() { + let at = TOP.find("sub u_sub").expect("the instantiation") as u32 + 2; + let site = inline_site(TOP, at).expect("a site"); + assert_eq!(site.module, "sub"); + assert_eq!(site.instance, "u_sub"); + assert_eq!(site.units, vec!["sub".to_string(), "top".to_string()]); + assert_eq!(inline_title(&site.module), "lucisv: inline `sub` here"); +} + +#[test] +fn the_site_gate_is_silent_where_there_is_no_instantiation() { + let at = TOP.find("input logic x").expect("a port") as u32; + assert_eq!(inline_site(TOP, at), None); +} + +// ---------------------------------------------------------------------- +// the round trip with §53.1 +// ---------------------------------------------------------------------- + +#[test] +fn extracting_a_region_and_inlining_it_back_returns_the_original() { + let source = "\ +module m ( + input logic a, + input logic b, + output logic q +); + logic s; + assign s = a & b; // the and + assign q = s | 1'b0; +endmodule +"; + let files = vec![(PathBuf::from("/rtl/m.sv"), source.to_string())]; + let start = source.find(" assign s = a & b;").expect("the region") as u32 + 2; + let end = source.find("// the and").expect("the comment") as u32 + 10; + let extracted = vlog_refactor::extract_module( + &files, + Path::new("/rtl/m.sv"), + start, + end, + "sum", + vlog_refactor::Home::NewFile, + ) + .expect("extracts"); + let mut after: Vec<(PathBuf, String)> = files.clone(); + after.push((PathBuf::from("/rtl/sum.sv"), String::new())); + for (path, edits) in &extracted.edits { + let text = after.iter().find(|(held, _)| held == path).map(|(_, t)| t.clone()); + let mut text = text.unwrap_or_default(); + for TextEdit { range, new_text } in edits.iter().rev() { + text.replace_range(range.start as usize..range.end as usize, new_text); + } + match after.iter_mut().find(|(held, _)| held == path) { + Some(entry) => entry.1 = text, + None => after.push((path.clone(), text)), + } + } + let m = after.iter().find(|(p, _)| p == Path::new("/rtl/m.sv")).expect("m").1.clone(); + assert!(m.contains("sum u_sum ("), "the extraction really happened: {m}"); + + let at = m.find("sum u_sum").expect("the instantiation") as u32 + 2; + let back = inline_module(&after, Path::new("/rtl/m.sv"), at).expect("inlines back"); + let mut round = m.clone(); + for TextEdit { range, new_text } in back.edits_for(&PathBuf::from("/rtl/m.sv")).iter().rev() { + round.replace_range(range.start as usize..range.end as usize, new_text); + } + let config = vlog_formatter::Config::default(); + let formatted = |text: &str| vlog_formatter::format_source(text, &config).expect("formats"); + assert_eq!( + formatted(&round), + formatted(source), + "extract then inline returns the original file modulo layout:\n{round}" + ); +} + +// ---------------------------------------------------------------------- +// the `.name` shorthand inside `S`'s own body (work log, 2026-09-06) +// ---------------------------------------------------------------------- + +/// A module whose body instantiates another with the `.name` shorthand — the +/// shape the `common_cells` trial caught: `.q_o` names a port of `inner` *and* +/// the signal `q_o` of `S`, with one token. +const OUTER: &str = "\ +module outer ( + input logic clk_i, + input logic d_i, + output logic q_o +); + inner u_inner ( + .clk_i, + .d_i, + .q_o + ); +endmodule +"; + +const INNER: &str = "\ +module inner ( + input logic clk_i, + input logic d_i, + output logic q_o +); + assign q_o = d_i; +endmodule +"; + +const USES_OUTER: &str = "\ +module top ( + input logic clk_i, + input logic data, + output logic result +); + outer u_outer ( + .clk_i(clk_i), + .d_i(data), + .q_o(result) + ); +endmodule +"; + +fn shorthand_files(outer: &str) -> Vec<(PathBuf, String)> { + vec![ + (PathBuf::from(M), USES_OUTER.to_string()), + (PathBuf::from("/rtl/outer.sv"), outer.to_string()), + (PathBuf::from("/rtl/inner.sv"), INNER.to_string()), + ] +} + +#[test] +fn a_dot_name_shorthand_in_the_body_is_spelled_out_when_the_name_it_stands_for_changes() { + let at = USES_OUTER.find("outer u_outer").expect("the instantiation") as u32 + 2; + let out = applied( + USES_OUTER, + &inline_module(&shorthand_files(OUTER), Path::new(M), at).expect("inlines"), + ); + // The port's own name never moves — it belongs to `inner` — and the signal + // it binds to is written out beside it. + assert!(out.contains(".d_i(data)"), "{out}"); + assert!(out.contains(".q_o(result)"), "{out}"); + // `clk_i` is connected to a `clk_i`, so the shorthand still says what it + // said and is left exactly as the author wrote it. + assert!(out.contains(".clk_i,"), "{out}"); + assert!(!out.contains(".data("), "the port name is never rewritten: {out}"); +} + +#[test] +fn a_wildcard_inside_the_inlined_body_is_refused() { + let outer = OUTER.replace(".clk_i,\n .d_i,\n .q_o", ".*"); + let at = USES_OUTER.find("outer u_outer").expect("the instantiation") as u32 + 2; + let message = inline_module(&shorthand_files(&outer), Path::new(M), at).expect_err("a refusal"); + assert!(message.contains("expand `.*` in `outer` first"), "{message}"); +} + +#[test] +fn a_string_parameter_keeps_the_spaces_inside_its_literal() { + let sub = "\ +module sub #( + parameter string NAME = \"a b\" +) ( + input logic a, + output logic q +); + assign q = a; +endmodule +"; + let top = "\ +module top ( + input logic x, + output logic z +); + sub u_sub (.a(x), .q(z)); +endmodule +"; + let out = inlined(top, sub).expect("inlines"); + assert!(out.contains("localparam string NAME = \"a b\";"), "{out}"); +} diff --git a/docs/features/extract-inline-module/README.md b/docs/features/extract-inline-module/README.md index f9c02a4..b6b9b77 100644 --- a/docs/features/extract-inline-module/README.md +++ b/docs/features/extract-inline-module/README.md @@ -1,8 +1,8 @@ # 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. +**§53.1 extract module ships (0.47.0). §53.2 inline module ships (0.49.0), +and the round trip between them is pinned.** ## Goal @@ -22,11 +22,24 @@ 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. +**Inline module** (§53.2) is the same job read backwards, and the one an +engineer does when a module has shrunk into a wrapper. With the cursor on +`S u_S (...)`, lucisv deletes the instantiation and writes `S`'s items in its +place: every use of a port becomes the name connected to it, every parameter +becomes a `localparam` holding its override (or its default), every name `S` +declares for itself keeps its name unless `M` already spells it — in which case +they all take a `u_S_` in front — and `S`'s `import`s are carried across when +`M` lacks them. **`S` itself is not touched**, and neither is anything else +that instantiates it: an inline is a *copy* out of `S`'s file, which is the one +structural difference from the extraction and the one thing the verifier had to +learn. + 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. +single declaration of, what a macro would expand to inside `S` — it refuses +rather than guesses. ## API as built @@ -73,6 +86,95 @@ node as a `module`, and only the first is one lucisv extracts out of): | `boundary.rs` | what each crossing name becomes: port, parameter, import | | `render.rs` | the new module's text, and the instantiation | +### §53.2, as built + +```rust +// crates/vlog_refactor/src/lib.rs +pub struct InlineSite { // the cheap gate's answer + pub module: String, // the module that would be inlined + pub instance: String, // the instance's own name + pub units: Vec, // what the engine will need read +} + +pub fn inline_site(text: &str, offset: u32) -> Option; +pub fn inline_title(module: &str) -> String; // "lucisv: inline `S` here" +pub fn inline_module(files: &[(PathBuf, String)], file: &Path, offset: u32) + -> Result; + +// crates/lucisv_server/src/inline_module.rs +pub const INLINE_MODULE: &str = "lucisv.inlineModule"; // [uri, position] +pub fn kind() -> CodeActionKind; // refactor.inline +pub fn code_actions(ws, uri, range) -> Vec; +pub fn execute(ws, arguments) -> Result<(WorkspaceEdit, Vec), String>; +``` + +`crates/vlog_refactor/src/inline/` is four files, one question each: + +| file | one sentence | +| --- | --- | +| `mod.rs` | the entry points, the workspace-wide refusals, the edit, the verification | +| `site.rs` | what the cursor is on, and the connection shapes that refuse | +| `source.rs` | what `S` is made of, and the constructs that refuse | +| `render.rs` | the substitution, the prefixing rule, and the text | + +The edit is **one replacement in one file** — the instantiation's own bytes — +and `RefactorEdit::created` is empty: nothing is created and nothing is +deleted, because `S` stays where it is for everything else that instantiates +it. + +## The substitution, exactly as implemented + +The body of `S` is copied **verbatim** but for two things: the name spans the +substitution rewrites, and the leading whitespace of each line. Everything +else — every comment, every attribute, every string, every `` `define`` use — +arrives byte for byte, which is both what invariant 3 wants and what lets the +verifier account for each piece as a copy rather than as an invention. + +**What a name becomes.** `S`'s own module scope is read out of `Semantics` +(`instantiable_scope`), and every symbol bound in it is classified once: + +| the name is | it is written as | +| --- | --- | +| a **port** | the name (or the literal) the instantiation connects to it | +| anything else `S` declares at module scope — a net, a variable, a parameter, a `localparam`, a `typedef`, an enumeration member, an instance | itself, with `u_S_` in front **iff** `M`'s file already spells any of them | +| a name in a **nested** scope (a `begin`'s own variable, a routine's argument) | itself, untouched — it collides with nothing at module level | +| anything else (a package, a type from an import, a system task, the module `S` instantiates) | itself, untouched | + +Every *declaration* of a renamed name inside the copied bytes and every +*reference* that resolved to one is rewritten, from the symbol table — never by +text search. + +**The one name written once and read twice.** `.clk_i` in `S`'s own body names +a port of the module `S` instantiates **and** the signal of `S` connected to +it, with a single token. Rewriting it would connect a different port; leaving +it alone would bind a name `M` may not even declare. So the shorthand is +**expanded** — `.clk_i` becomes `.clk_i(clk)` — wherever the signal it stands +for is one the inline renames, and left exactly as written where it is not. A +`.*` inside `S`'s body names every signal at once and cannot be expanded one +name at a time, so it refuses. (This is the trial's `counter` inside +`cb_filter`; see the work log.) + +**Parameters.** Each entry of `S`'s parameter port list becomes a `localparam` +written above the body, in declaration order, carrying the override the +instantiation wrote or the default the header did — with the type as `S` +spells it (a continuation entry inherits the keyword *and* the type of the one +before it) and with names substituted into the type and the default the same +way the body's are. A header `localparam` is emitted too, and an instantiation +that tries to override one refuses. + +**Prefixing is all-or-nothing.** If any name `S` declares at module scope is +one `M`'s file already spells, *every* one of them is prefixed with the +instance's name and a `_`; otherwise none is. The all-or-nothing rule is what +keeps the result readable — a body where three names out of twenty are dressed +differently is one nobody can check by eye — and the warning says which name +collided. + +**Indentation.** Each copied line is moved from `S`'s body indentation to the +instantiation's, except a line that begins *inside* a block comment or a string +literal: those bytes are the piece's own text, and the verifier counts a +comment by what it says. The result is formatted-shaped rather than formatted; +the trials pin that it formats and converges. + ## The dataflow rule, exactly as implemented A name is **written by** a region when, and only when, it is: @@ -197,6 +299,66 @@ that package supplies. | 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" | +### §53.2 — inlining + +**The instantiation** (`inline/site.rs`). Nothing here reads `S`, so the cheap +gate behind the lightbulb asks exactly these questions too: + +| when | the sentence says | +| --- | --- | +| the cursor is on no instantiation written **directly in a module's body** | nothing is offered; the command says "there is no module instantiation at this position to inline" | +| the instantiation is inside an `interface`/`program` | "lucisv inlines into a `module`" | +| it declares **more than one instance** | "each of them is a copy of the module's body; lucisv inlines one instance at a time" | +| the instance is an **array** (`sub u [1:0] (…)`) | "is an array of instances, which stands for as many copies … as its range has" | +| **positional** connections | "convert to named connections first" | +| positional **parameter overrides** | the same, for parameters | +| **`.*`** | "expand `.*` first (lucisv: expand `.*`)" | +| a connection that is **not a plain name or a literal** | "connect `.a(x+1)` to a named wire first" | +| the list carries **compiler directives** | "lucisv does not evaluate one" | +| `.P()` overriding a parameter with nothing | "give it a value first" | + +**`S` itself** (`inline/source.rs`): + +| when | the sentence says | +| --- | --- | +| `S` is an **`interface`** or a `program` | "whose signals are its surface rather than a body lucisv can copy" | +| `S` declares its ports **non-ANSI** | "convert them to ANSI ports first (lucisv: convert to ANSI ports)" | +| a port is an **`inout`** | "whose two directions lucisv cannot reproduce by substituting a name" | +| a port has an **unpacked dimension** | "a port array is not one name lucisv can substitute" | +| a port is of **interface type** (or a modport of one) | "whose signals are named through the port rather than substituted for it" | +| the port list carries **compiler directives** | "which ports it really declares depends on the configuration" | +| `S` holds an **`initial`** or a **`final`** block | "does not mean the same thing written inside another module" | +| a **macro invocation** as an item | "lucisv does not expand macros, so it cannot tell what it would be copying" | +| a **compiler directive** among its items | "it cannot tell what its body really is" | +| a **`generate`** construct | "whose block names are reachable through the hierarchy (`u_S.gen.x`) and would become names of `M`'s own" | +| a **`bind`**, a nested module/package declaration, an unparsed leaf | the matching sentence | +| a **`.*`** in `S`'s own body | "inlining renames the signals those ports bind to; expand `.*` in `S` first" | + +**The connection, against `S`'s ports** (`inline/render.rs`): + +| when | the sentence says | +| --- | --- | +| a port is **unconnected** (`.a()`), or not in the list at all | "`.a` is left unconnected, and `S`'s body uses `a` as a name of its own; connect it to a wire first" | +| an **output** is connected to a **literal** | "drives `S`'s output into a literal, which nothing can be assigned to" | + +**Names and the workspace** (`inline/mod.rs`, `inline/render.rs`): + +| when | the sentence says | +| --- | --- | +| lucisv **indexes no `S`** | "indexes no module named `S`" (the same sentence `instantiation_plan` uses) | +| `S` is **declared twice** | "declared in more than one indexed file" | +| `S` is declared in **`M`'s own file** | "lucisv inlines a module written in a file of its own this round" | +| either file **does not parse** | "does not parse (… at line N)" | +| `u_S` is named through the **design hierarchy** anywhere in the files lucisv was handed | "is named through the design hierarchy in `tb.sv` (`u_S.…`), and inlining it dissolves the scope that path walks through" | +| `S`'s **`` `timescale ``** differs from `M`'s file's | "a `timescale` changes what every delay in the body means" | +| the instantiation carries an **attribute** | "says something about that instance and has nothing left to say once there is no instance" | +| a colliding name is an **escaped identifier** | "an escaped identifier that lucisv cannot prefix its way out of" | +| a colliding name is one whose declaration carries an **`end … : name` label** (a function, a task, a named block, a class, a clocking block, a covergroup, a property, a sequence) — *only when prefixing is needed* | "lucisv does not rewrite the `end … : name` label that goes with it" | +| the **prefixed** name collides too | "and so does `u_S_x`, which is what lucisv would have renamed it to" | +| `S` writes a **comment inside a parameter's declaration** | "lucisv would have to copy the comment into `M` to write the `localparam`" | +| a parameter has **no default and no override** | "lucisv has no value to write for it" | +| the instantiation **overrides a header `localparam`** | "which `S` declares as a `localparam`" | + ## 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 @@ -248,7 +410,7 @@ 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. +`moving: &[Moving]` 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 @@ -298,6 +460,56 @@ below was invisible). In `check/ledger.rs`'s and `check/mod.rs`'s test modules: | 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 | +### The second widening: a file the edit only *copies* out of (§53.2) + +An inline is the mirror move, and the mirror breaks the accounting in one +place: `S`'s comments arrive in `M` with **nothing deleted anywhere**, because +`S`'s file is not edited at all. Rule 2's `wrote ≤ gone` refuses that, and +correctly — it is exactly the shape of an invented comment. + +So `moving`'s entries carry an `Origin`. `Moving::source(f, region)` and +`Moving::destination(f)` are what they always were (`Origin::Moved`); +`Moving::copy(f, region)` is new (`Origin::Copied`) and says *the bytes in this +region are copied out of a file the edit does not touch*. A copy sends its +region's pieces into the transit exactly as a source does — so a destination +may write each of them once per copy — and is held to one rule of its own, +checked before the equations: + +0. **A copied file is not edited.** It appears in no edit at all; anything else + is a contradiction rather than a plan, and is refused naming the file. + +Rules 1–3 are untouched. Rule 4 gains the copies on its sending side: what a +region sends, whether by moving or by copying, has to land exactly once in the +destinations the move named — so a copied comment written twice is a +duplication and one written nowhere is a drop, each said in those words. The +allowance stays bound to the **bytes**: a comment in `S`'s *header*, outside +the region the inline names, has no origin at all and `M` may not write it, +which is why the engine refuses a parameter declaration with a comment inside +it rather than lifting the type text out of one. + +`inline_module` names exactly two files: `Moving::destination(M)` and +`Moving::copy(S, S's body)`. Everything else — the pieces comparison, the +parse check, resolution identity outside the edited range — is the splice +contract unchanged. The resolution check is what catches an inlined +declaration that captures a name `M` was reading from somewhere else, and it +refuses with the ordinary "would change what `x` means" sentence. + +**The masked-corruption attacks on the copy allowance** (`check/mod.rs`, all +through the production `verify_move` with a real `Scope` and the edits +`inline_module` really produces, over a `sub` whose body carries both a comment +and a `(* keep *)`): + +| # | the pair | verdict | +| --- | --- | --- | +| 1 | the honest inline the engine produces — the comment and the attribute copied, `sub.sv` unchanged | **accepted** | +| 2 | the copied comment written **twice** into `M` | rejected — "never duplicated" | +| 3 | the copied comment written **nowhere** | rejected — "would carry … and write it back nowhere; comments are never dropped" | +| 4 | the same for the **attribute** | rejected — "attributes are never dropped" | +| 5 | `M` writes a comment the copied region does **not hold** | rejected — "never duplicated", naming the comment | +| 6 | `M` writes `/* TODO: connect */` — the `generated` whitelist | **accepted** — unchanged by the widening | +| 7 | the plan **also edits `sub.sv`** (deleting the very comment being copied, so the halves would balance as a *move*) | rejected — "which it only copies out of", naming `sub.sv` | +| 8 | the honest inline with an **empty** `moving` | rejected — the allowance 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 @@ -335,6 +547,49 @@ header lucisv wrote is the header it meant to write. user wants the new module's ports in a different order, that is `remove_port`/`add_port`'s job. +### §53.2 + +* **`S`'s body means the same thing inside `M`.** That is the whole bet, and + every refusal in `source.rs` is a construct for which it is false: a + `generate` names scopes the hierarchy can reach, an `initial` block's meaning + depends on when it runs, a macro's body is text lucisv never read, a + `` `timescale `` changes what a delay means. What is left — declarations, + continuous assignments, `always` blocks, instantiations, routines — is + position-independent module-item code. +* **Substituting a name for a port is sound because a connection is a plain + name or a literal.** Both are primary expressions, so the substitution is + safe in every position the port's name could appear in — a bit-select, a + left-hand side, a connection to a further instantiation. Any other + connection refuses: `.a(x+1)` written wherever `a` is read would duplicate + the expression and, on a left-hand side, would not be assignable at all. +* **The hierarchical check sees the files it was handed.** It is a lexical + scan — an identifier spelling the instance's name with a `.` on either side + of it — over every in-scope file, prefiltered by a whole-word search. The + server hands the engine the fan-out of `S` and `M` (`module_sources`), the + same narrowing every other refactoring in the crate gets; an XMR from a file + the index does not connect to either name is outside what lucisv can see, as + it is for a rename. The scan errs towards refusing: another module's own + `u_S.x` refuses this one too. +* **`M`'s file is the collision set.** Every symbol name in `M`'s file, not + just `M`'s own module scope — deliberately a superset, so a name the inline + introduces cannot quietly capture a file-scope declaration. A name `M` + *references* without declaring is not in the set; an inlined declaration that + captures one of those is caught by the resolution half of the verifier + instead, as a refusal. +* **`S` is declared in a file of its own.** Inlining a module declared in `M`'s + own file is refused this round: the copy allowance is granted on the strength + of the copied file coming out unchanged, and lucisv would rather refuse than + widen rule 0 to "unchanged over the copied bytes". The corpus trial shows + what it costs — 5 of 9 refusals in `common_cells` are this one. +* **The `.name` shorthand is expanded, never rewritten.** The port half of the + token belongs to the module being instantiated and never moves; only the + signal half is written out. `.*` in `S`'s body refuses because it has no + port half to keep. +* **An unconnected output refuses**, not only an unconnected input (TODO §53.2 + names the input). Making one work means declaring a signal for it in `M`, + which is a declaration with a type read out of `S`'s header and a name of + lucisv's own invention; that is a round of its own. + ## Handshakes * **`vlog_refactor::RefactorEdit`** (widened, additive). New field @@ -344,8 +599,10 @@ header lucisv wrote is the header it meant to write. 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` + + `&[Moving]` — a file with its moved region (`Moving::source`), a file that + only receives (`Moving::destination`), or, since §53.2, a file the edit only + **copies** out of (`Moving::copy`, `Origin::Copied`), which must appear in no + edit; `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 @@ -366,33 +623,92 @@ header lucisv wrote is the header it meant to write. 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`). + already public (`Semantics`, `Resolution`, `Surface`, `WorkspaceIndex`, + `Semantics::instantiable_scope`). +* **§53.2 — `lucisv_server`** — one new module (`inline_module.rs`; the name + `inline.rs` is taken by `textDocument/inlineCompletion`), one new code-action + kind (`refactor.inline`) in `capabilities`, one new command in `commands()`, + and two new branches in `server/dispatch.rs` (the `codeAction` fan-out and + the `executeCommand` split, routed before `ports::execute` as the extract + command is). `ports::workspace_edit` is reused unchanged — an inline creates + nothing, so the ordinary `changes` map is enough, and no client capability is + involved. +* **§53.2 — `editors/vscode`: no change.** The action carries no prompt: the + command takes `[uri, position]` and the language client registers it from the + server's own `executeCommandProvider`. +* **§53.2 — `vlog_refactor::instantiate::ends_escaped`** is now read by + `inline::render` as well as by `instantiate`'s own renderer. Already + `pub(crate)`; no signature change. ## 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] 53.2 inline: substitution, prefixing, refusals, action + command +- [x] the extract → inline round trip pinned (`tests/inline.rs`, + `extracting_a_region_and_inlining_it_back_returns_the_original`) - [x] docs; §8 lines annotated; site rows (lead — see below) -- [x] Gates (guarded); byte-identity vs 0.46.0; corpus scratch checks -- [ ] QA +- [x] Gates (guarded); byte-identity vs 0.48.0; corpus + opentitan scratch + trials +- [x] QA (§53.1) +- [ ] QA (§53.2) -## What §53.2 still needs (unstarted) +## Gate numbers for §53.2 (2026-09-06, all guarded) -Nothing in §53.1 was shaped to make §53.2 harder, and two things were shaped to -make it easier: +| Gate | Result | +| --- | --- | +| `cargo fmt --all` | clean | +| `cargo clippy --all-targets` | clean; one new `#[allow(clippy::mutable_key_type)]`, the same one and for the same reason as `extract.rs`'s (a `WorkspaceEdit`'s `Uri` key) | +| `cargo test --workspace` | **4 133 passed, 0 failed, 44 ignored** (baseline 4 081; +52 — 37 in `tests/inline.rs`, 8 verifier attacks, 6 in `lucisv_server/src/inline_module.rs`, 1 corpus trial) | +| `tools/corpus_check.sh` | **814/820 (99.3%)**, the same six parse errors, **0 verification errors, 0 crashes** | +| `format --stdout` vs `~/.cache/lucisv-baselines/lucisv-0.48.0` over the 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** — initialize/didOpen/shutdown/exit, 20 messages | -* `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 corpus inline trial (`corpus/`, 860 files, unmodified) -The refusal list in TODO §53.2 stands as written; none of it has been -implemented, and no `refactor.inline` action is offered. +`cargo test -p vlog_refactor --test corpus five_instantiations… -- --nocapture`. +The trial prints every accepted inline with its census and every refusal with +its sentence, so the table below is what it says. **5 inlined, 9 refused.** + +| module → into | outcome | +| --- | --- | +| `addr_decode_dync` → `addr_decode`, `addr_decode_napot` | refused — a compiler directive among its items | +| `heaviside` → `boxcar` (twice) | **inlined**, 0 names newly unbound | +| `hash_block` → `cb_filter` (three times) | refused — declared in the same file | +| `counter` → `cb_filter` | **inlined**, 0 names newly unbound | +| `cdc_2phase_src`, `cdc_2phase_dst` → `cdc_2phase` | refused — declared in the same file | +| `cdc_2phase_src_clearable`, `cdc_2phase_dst_clearable` → `cdc_2phase_clearable` | refused — `.valid_i(src_valid_i & !s_src_isolate_req)` is an expression | +| `cdc_reset_ctrlr` → `cdc_2phase_clearable` | **inlined**, 0 names newly unbound | +| `sync` → `cdc_2phase_src_clearable` | **inlined**, 0 names newly unbound | + +Every result parses, formats and converges, and +`lucisv check --select unused-signal,undriven-net` over each pair of files +(`LUCISV_INLINE_OUT=… ` writes `case_N/{before,after}/`) reports **0 violations +before and 0 after**, for all five. The `counter` case is the one that reported +1 after before the shorthand rule was added — see the work log. + +### The opentitan inline trial (506 files, scratch copies) + +Scratch copies of `hw/ip/{aes,hmac,uart,spi_host,prim}` (506 `.sv`/`.svh` +files), `LUCISV_INLINE_ROOT` pointed at the copy. **5 inlined, 56 refused.** + +| module → into | outcome | +| --- | --- | +| `aes_tb_reqs` → `aes_tb` | **inlined**; 1 name newly unbound (`requests`, which only an `` `include`` declares and which `aes_tb_reqs.sv` itself already leaves unbound) | +| `aes_reg_status` → `aes_control_fsm` | **inlined**, 0 | +| `prim_sec_anchor_buf` → `aes_core` (three times) | **inlined**, 4 names each, all of them ones `prim_sec_anchor_buf.sv` already leaves unbound | + +The 56 refusals are the refusal list doing its job: `.*` (the AES fault-injection +wrappers), interfaces, positional connections, expression connections +(`.edn_o(edn_if[0].req)`, `.prd_i(prd[Width-1:0])`), `generate` inside `S` +(`aes_cipher_core`), and modules the scratch subset does not declare. All five +results parse, format and converge, and +`lucisv check --select unused-signal,undriven-net` reports **0 before and 0 +after** for every pair. + +`git -C …/opentitan status --porcelain` shows the same three pre-existing files +before and after; nothing but `rsync`ed scratch copies was read. ## Gate numbers after the rework (2026-09-06, all guarded) @@ -470,8 +786,82 @@ paths, behaviour and output all unchanged): | `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 | +§53.2's own (2026-09-06, production lines outside `#[cfg(test)]`): + +| file | lines | +| --- | --- | +| `vlog_refactor/src/inline/render.rs` | 332 | +| `vlog_refactor/src/inline/mod.rs` | 252 | +| `vlog_refactor/src/inline/source.rs` | 244 | +| `vlog_refactor/src/inline/site.rs` | 164 | +| `lucisv_server/src/inline_module.rs` | 67 (+126 test) | + +`check/mod.rs` is 426 production lines (from 392) and `check/ledger.rs` 366 +(from 334) with the copy allowance on board — both still under the 600 target; +the growth is 8 new attack tests, which do not count, plus `Moving`/`Origin` +and `Transit::copy`. + ## Work log +**2026-09-06 — dev (§53.2, inline module).** Read §53.1's engine and this +README, `check/{mod,ledger}.rs`, `instantiate.rs`'s reading of a declaration, +§49's surface and the server's lazy-action plumbing. Then, in order: + +1. **The verifier first**, as §53.1 did, so the engine could be built on a + verifier that admits a *copy*. `moving` became `&[Moving]` with an `Origin` + — `Moved` (a source, or the empty-range destination: byte-for-byte the old + behaviour) and `Copied`, a file the edit does not touch whose region's + pieces join the transit. Rule 0 ("a copied file is not edited") is checked + before the equations and refuses naming the file; `Transit` gained a + `copied` list that feeds `sent` and the `lands` sentence. Eight + masked-corruption attacks written at the same time (invariant 4), all + through the production `verify_move` with the edits `inline_module` really + produces — including the one that would balance as a *move* (attack 7) and + the opt-in pin (attack 8). The extraction's twelve are untouched and still + pass; the only wording change is "would move the comment" → "would carry + the comment", which now covers both origins. +2. **`inline/site.rs`** — what the cursor is on. The cheap gate and the engine + share it, so the lightbulb and the command refuse for the same reasons. +3. **`inline/source.rs`** — what `S` is made of, and the constructs that do not + mean the same thing inside `M`. +4. **`inline/render.rs`** — the substitution, driven by `S`'s module scope out + of `Semantics::instantiable_scope`: ports to connected names, everything + else `S` declares to itself-or-prefixed, rewritten from the symbol table. +5. **`inline/mod.rs`** — the workspace-wide refusals, the single edit, the + verification, the warnings. +6. **The server** (`inline_module.rs`) and its wiring; no extension change. + +**Two decisions worth the ink.** *Prefixing is all-or-nothing* — a body where +three names out of twenty are dressed differently is one nobody can check by +eye — and the `end … : name` label problem is dodged rather than solved: when +prefixing is needed and `S` declares a function, a task or a named block, +lucisv refuses, because it does not rewrite that label and a mismatched one is +a legal file that means something else. When prefixing is *not* needed nothing +is rewritten at all, so those modules inline fine. + +**The bug the trial caught, and the rule it produced.** The first +`common_cells` run inlined `counter` into `cb_filter` and left +`cnt_overflow` read but never driven — `lucisv check --select undriven-net` +went 0 → 1 while every other check passed, the verifier included. `counter`'s +own body instantiates `delta_counter` with the `.q_o` **shorthand**, which +names a port of `delta_counter` and the signal `q_o` of `counter` with one +token: substituting over it would connect a different port, and leaving it +alone binds a name `cb_filter` does not declare. The fix is to *expand* the +shorthand — `.q_o(filter_usage_o)` — wherever the signal half is one the inline +renames, and to refuse a `.*` in `S`'s body, which has no port half to keep. +Pinned by `a_dot_name_shorthand_in_the_body_is_spelled_out_when_the_name_it_stands_for_changes` +and `a_wildcard_inside_the_inlined_body_is_refused`. It is the reason the +`lucisv check` half of the trial is worth running: nothing else in the suite +saw it. + +**The trial's census had to change too.** An inline *copies*, so +`unresolved_over`'s whole-design count legitimately grows by one per name `S` +already could not resolve (opentitan's `aes_tb_reqs` reads a `requests` that +only an include declares). The inline trial holds the exact property instead: +every other file's census is unchanged, and every name the edited file newly +fails to bind is one some other file already fails to bind — `census` and +`borne` in `tests/corpus.rs`. The extraction's own trial is untouched. + **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 @@ -637,9 +1027,44 @@ so a trial run is reproducible without patching it first. * `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. +**`TODO.md` §8** — the extract-module line is annotated in place (done by the +§53.1 lane); §53's own checkboxes are ticked except the QA line. + +### §53.2 (2026-09-06) + +**`docs/site/` — language-tools row.** Add beside extract-module: + +> **Inline module** — put the cursor on an instantiation and lucisv writes the +> module's body where it stood: every port replaced by the signal connected to +> it, every parameter written out as a `localparam` holding its override, every +> internal name kept — or prefixed with the instance's, if the enclosing module +> already spells it — and the module's `import`s carried across. The module +> itself is left exactly where it is, and so is everything else that +> instantiates it. Refuses, with a sentence, wherever the substitution would +> not be honest: a `.*`, a positional connection, an expression where a name +> belongs, an unconnected port, a `generate` or an `initial` inside the module, +> a macro, a differing `` `timescale ``, or a hierarchical path into the +> instance from anywhere in the workspace. + +**`README.md`** — the refactorings list gains a second entry beside extract: + +> * **inline module** (`refactor.inline`, `lucisv.inlineModule`) — an +> instantiation becomes the module's own items, with ports substituted by the +> names connected to them and parameters written out as `localparam`s. + +**`TODO.md` §8** — annotate the **inline-module** line in place, the way the +extract line was. + +**`docs/topo.md`** — one edge to amend: + +* `vlog_refactor::check::verify_move`'s `moving` list is now `&[Moving]` with + an `Origin` (`Moved`/`Copied`). Crate-internal — no edge leaves + `vlog_refactor` — but the §2.9 note on the widening should say the allowance + now covers a copied region as well as a moved one, and that a copied file is + asserted unedited. +* `lucisv_server::inline_module` ──▶ `vlog_refactor::{inline_module, + inline_site, inline_title}`: a new consumer edge of the same shape as + `lucisv_server::extract`'s. ## QA log @@ -1083,8 +1508,371 @@ 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. +**2026-09-06 — QA (§53.2, inline module).** Read this README's §53.2 +sections in full (the substitution table, the `.name` shorthand rule, the +prefixing rule, the refusal list, the assumptions, the copy allowance and +its eight attack pairs), the diffs in `check/{mod,ledger}.rs`, +`inline/{mod,site,source,render}.rs`, `lib.rs`, `tests/{inline,corpus}.rs`, +`lucisv_server/src/inline_module.rs`, `main.rs`, `server/dispatch.rs`. Then +re-attacked the verifier through the production `verify_move` beyond the +dev's own eight, attacked the substitution/prefixing/refusal matrix on +hand-picked shapes, confirmed the server wiring by reading, and re-ran every +trial and gate. Verdict is **PASS**, with two MEDIUM findings (neither +blocking, both documentation/follow-up) and one QA-caused incident, fully +remediated, recorded below for the record. + +### Priority 1 — the verifier's copy allowance + +All eight of the dev's own attack tests (`check/mod.rs`, "the copied-piece +rule" section) were re-read and re-run — `cargo test -p vlog_refactor --lib +check::` — **57/57 pass**, all still through the production `verify_move` +with a real `Scope` and the edits `inline_module` really produces (no +`pooled()`-style helper anywhere: `grep -rn "fn pooled" crates/vlog_refactor` +finds nothing). Re-attacked with nine more (temporary tests, added to +`check/mod.rs`'s test module and `tests/inline.rs`, removed before finishing +— see "Cleanup" below): + +| # | attack | via | result | +| --- | --- | --- | --- | +| 1–8 | the dev's own eight (honest; written-twice; lands-nowhere ×2 comment/attribute; invented outside the region; the `generated` whitelist; rule 0 on the very comment being copied; the opt-in pin) | production `verify_move` | all **as documented**, re-confirmed | +| 9 | a **real** comment from `sub.sv`'s **header**, outside the declared copy region (not a synthetic `// invented` string) | `verify_move`, real edits + one appended line | **rejected** — "never duplicated", naming the real comment text; confirms the region boundary is exact, not "whatever the render happened to read" | +| 10 | rule 0 with an edit to the copied file **far from** the copied region (an unrelated insertion at offset 0) | `verify_move` | **rejected** — "only copies out of", naming `sub.sv` — confirms rule 0 does not ask *where* the edit lands | +| 11 | rule 0 against a **pure code edit** to the copied file that touches **no** never-dropped piece (`assign s = a;` → `assign s = a & a;`, no comment/attribute involved) | `verify_move` | **rejected** — "only copies out of" — see the neutering table below for why this one matters | +| 12 | **two** `Moving::copy` entries of the *same* region, destination writes the comment+attribute **twice** | `verify_move` | **accepted** — two honest copies, two landings, exactly as the brief predicted | +| 12b | the same doubled write with **one** copy entry | `verify_move` | **rejected** — "never duplicated" | +| 13 | `Moving::copy` naming a file index **outside the `Scope`** (99, out of range) | `verify_move` | **no panic** — `Scope::path`/`Scope::text` return `None` (`scope.rs:57-63`, `.get()`-based), the rule-0 loop's `let (Some(path), Some(text)) = … else { return Err(abandoned) }` fires; clean refusal | +| 14 | a **`Moving::source`** (moved) and a **`Moving::copy`** in the *same* plan, three files: honest one-landing-each, then swapped so the moved piece lands twice and the copied one lands zero times (same pool total) | `verify_move` | honest **accepted**; swapped **rejected** — no cross-talk between origins, the swap is caught (each piece's own `sent`/`lands` accounting is per-text-key, not pooled across origins in a way that would let one type's excess hide the other's shortfall) | +| 15 | the "coincidence" the brief names: `top.sv`'s own (deleted) instantiation already carries a comment textually identical to the one `sub.sv`'s body copies out | hand-crafted `TextEdit`s (not the real engine's own output — see below) through `verify_move` | see **Finding QA-2** | + +**Finding QA-2 (MEDIUM, non-blocking) — the copy allowance inherits QA-1's +(§53.1) blind spot into the copy-origin context; not reachable by anything +`inline_module` produces today.** Hand-crafted (not engine-produced) edits +where `top.sv`'s pre-existing instantiation held a comment +(`sub u_sub (.a(x), .q(z)); // the and`) textually identical to the one +`sub.sv`'s body copies out: an edit that deletes it **without** carrying it +forward (`gone=1, wrote=1`) is correctly **rejected** (`Transit::lands`: +`gained = wrote − gone = 0 ≠ out = 1`, "write it back nowhere"); the same +deletion with the written text carrying the comment **twice** +(`gone=1, wrote=2`) is **accepted** (`gained = 1 = out`). Traced by hand +through every shape the *real* `comments_in`/`render.rs` code can actually +produce for this input (the real engine's own `comments_in` captures the +instantiation's own comment as `carried` and writes it back **once**, +giving exactly `wrote=2, gone=1` — the *legitimate*, correct case: one +comment carried locally, one landed by copy, both real, both wanted) and +could not construct a *reachable* bug shape the equations would wrongly +accept: any planner defect that over-writes (a duplicated `carried` entry, +or a duplicated copy landing) pushes `wrote` past `gone−out+in` and is +caught by rule 2 first, every time this was tried. The `Ok(())` in row 15 +above is a case of two *interpretations* of the identical final bytes +(`carried once + copied once` vs. `an invented duplicate replacing a +silently-dropped original`) being indistinguishable **because the bytes +really are identical** — this is exactly Finding QA-1 from the §53.1 pass +("`positions_match`… provide no protection… because `after` is always +internally derived from the very edits being checked") restated one level +up, in the copy transit's own `lands` equation rather than in +`positions_match`. Same root cause, same non-reachability argument, same +recommendation (a per-piece identity/position tag would close both at +once). Left to the dev/lead exactly as QA-1 was: a documentation note or a +follow-up test, not a blocker — flagging here so QA-1 and QA-2 get closed +together if either is ever addressed. + +**Neutering** (`check/mod.rs`, temporary edits, reverted before finishing — +`diff` against the dev's own file confirmed byte-identical after): + +| stubbed | what failed | interpretation | +| --- | --- | --- | +| rule 0's `if edits.iter().any(...) { return Err(...) }` replaced with `if false && …` | `check::tests::an_edit_to_the_file_the_move_only_copies_out_of_is_rejected` and `check::tests::qa_rule_0_fires_for_an_edit_to_the_copied_file_far_from_the_copied_region` still failed (i.e. still correctly rejected the corruption) — **but for the wrong reason**: the copied file's own edit fell through to the *ordinary* per-file `pieces_match` path (since `region_of` no longer credits it as `Copied`), which independently caught the comment deletion/insertion in `sub.sv` on its own. `check::tests::qa_a_pure_code_edit_to_the_copied_file_touching_no_never_dropped_piece` (added specifically to close this gap) **failed outright** — `Ok(())` where an `Err` was expected | confirms rule 0 is load-bearing specifically for an edit to the copied file that touches **no** never-dropped piece (a pure code/semantic change) — the ordinary per-file ledger has nothing to say about it, and nothing else in `verify_move` reads the copied file's *edited* text at all (the copy's tally is always taken from `scope.text()`, the original) | +| `transit.copy(...)` call replaced with a discard | **12 tests failed**, all of them: `a_copied_attribute_that_lands_nowhere_is_rejected`, `a_copied_comment_that_lands_nowhere_is_rejected`, `a_copied_comment_written_twice_is_rejected`, `a_generated_placeholder_the_destination_writes_is_not_a_duplicate`, `a_piece_written_into_the_destination_that_the_region_does_not_hold_is_rejected`, `an_edit_to_the_file_the_move_only_copies_out_of_is_rejected`, `the_copy_allowance_is_opt_in_and_an_inline_that_asked_for_none_gets_none`, `the_inline_the_engine_actually_produces_verifies`, plus four of mine — every one of them failed at the **construction step** (`inline_edits()`/`inline_module(...)` itself now returns `Err`, rejecting the engine's own honest output as "would write the attribute once… without deleting it") | confirms `transit.copy` is what makes the copy allowance exist at all: without it, no real inline verifies, ever | + +Both stubs reverted immediately after; `diff` against a saved copy of the +dev's `check/mod.rs` (via `git show HEAD:… | patch < check_mod.diff`) +confirmed byte-identical to the dev's own file once the nine QA tests were +removed. + +### Priority 2 — the inline matrix + +Read `inline/{site,source,render}.rs` in full. `site.rs::of` checks +`module.kw` (`"module"`/`"macromodule"`) **before** anything else reads the +instantiation — the §53.1 V2 mistake (accepting a selection inside an +`interface`) is not repeated here. Cross-referenced every row of the +brief's matrix against `tests/inline.rs`'s existing 42 tests (thorough: +two-port substitution, literal-on-input, `.clk` implicit shorthand, +parameter override and default, parameter used in a port's type (`WIDE`), +name-collision prefixing and its warning, no-collision, import copied in, +every refusal in the table — expression/`.*`/positional/unconnected +input/output-to-literal/hierarchical (same file and another file)/`bind`/ +`generate`/`initial`/macro/directive/`inout`/unpacked/interface +port/declared twice/unknown/same-file/differing `timescale`/array of +instances/escaped-name collision, the cheap gate, the round trip, the +`.name` shorthand expand-and-refuse, a string parameter's embedded spaces). +Five rows the existing suite does not cover, attacked with temporary tests +in `tests/inline.rs` (removed after — file diffed back to the dev's own +604 lines, confirmed identical): + +| row | result | +| --- | --- | +| a port connected to a name **`sub` also declares internally** (`.a(s)` where `top` has its own `wire s`, and `sub`'s own body also declares `logic s`) | **handled correctly**: the port substitution uses the connected name `s` verbatim wherever `a` is used (never subject to collision handling); `sub`'s *own* internal `s` collides with `top`'s file (which spells `s` — the connecting wire's own declaration is a symbol in `top`'s file, and "M's file is the collision set" is deliberately that literal) and is prefixed to `u_sub_s`. Result: `logic u_sub_s; // the and`, `assign u_sub_s = s & b;`, `assign z = u_sub_s;` — no self-assignment, no corruption | +| **two instances** of the same `S` in `M`, inlined one at a time (as the server would, one command per instance) | first inline untouched-second confirmed; re-running against the *edited* file inlines the second independently — it collides with the *first* inline's own `s` (now declared in `top`) and is correctly prefixed `u_sub2_s`, its own collision, not contaminated by or reusing the first instance's naming | +| an **unconnected output** (`.q()`) | refused with the same sentence as an unconnected input — `` `.q` is left unconnected `` — confirms the README's explicit note ("An unconnected output refuses, not only an unconnected input") | +| a **named block that does not collide** (`always_comb begin : blk … end : blk`, nothing in `M` spells `blk`) | inlines untouched, `begin : blk` intact, no `u_sub_` anywhere — the end-label refusal is confirmed to fire only when prefixing is *needed* | +| the same named block where `M` **does** declare `blk` (forcing prefixing) | refused, naming the `end … : blk` label, exactly as `render.rs::labelled` promises | + +All five pass; no defect found in this batch. + +### Priority 2, continued — the handed-files narrowing + +Read `lucisv_server/src/state.rs::module_sources` (`state.rs:1478-1500`) in +full against `rename_sources` (`state.rs:1565-1591`) to answer the brief's +question directly: **does `module_sources` include every file that +mentions `u_S`, or only files that reference `S`/`M` by name?** +`module_sources(file, modules)` unions: the requesting file, every file +*declaring* one of `modules` (`WorkspaceIndex::units`), every file with a +*direct* `references_to`/`instantiations_of` posting for one of them, and +every open buffer. Both `references_to` and `instantiations_of` are keyed +by direct uses of the exact declaration/name (`workspace/index.rs:245,312`) +— **there is no rung for a file that reaches `u_S` only through an +intermediate instance it does not itself name** (`rename_sources` has a +`hierarchical_declarations` rung for exactly this shape on *renamed +members*; `module_sources` has no equivalent). + +Confirmed concretely, not just by reading (`tests/inline.rs`, temporary, +removed after): `wrapper.sv` instantiates `top` directly (so it *is* in a +real fan-out) and `tb.sv` instantiates `wrapper` (not `top`, not `sub`) +and writes `u_wrapper.u_top.u_sub.s` — a genuine XMR into the instance +being inlined, one hop further than `module_sources` looks. With `tb.sv` +handed to `inline_module` (simulating a workspace where the index also +connects it), the inline is **refused**, naming it — `no_hierarchy` sees +what it is given. With exactly the file set `module_sources(top.sv, +["sub","top"])` would actually compute for this shape (`top.sv`, `sub.sv`, +`wrapper.sv` — **not** `tb.sv`), the same inline is **silently accepted**. + +**Finding QA-3 (MEDIUM) — the hierarchical scan's blind spot is real, +reproducible, and one hop worse than a rename's.** This is the README's +own documented assumption ("the hierarchical check sees the files it was +handed… an XMR from a file the index does not connect to either name is +outside what lucisv can see, as it is for a rename") — not a hidden +defect, and the safe direction is the one taken (it's an under-refusal, +not a corruption the verifier's own contract claims to catch: the +`no_hierarchy` scan is `inline/mod.rs`'s own workspace-wide refusal, not +part of `check::verify_move`, so this isn't a CLAUDE.md invariant-4 +question). Rated MEDIUM rather than LOW because the concrete trigger — a +testbench or SVA bind file reaching into an instance through one or more +wrapper levels, which is common in verification code for exactly the kind +of IP this feature targets (`common_cells`, opentitan `prim_*`) — is not +exotic, and unlike a rename's `hierarchical_declarations` rung, inline has +no rung at all for it. Not a fix requested here (QA verifies, does not +redesign); worth the lead's attention as a documented, known gap rather +than a surprise, and worth deciding whether inline should get its own +"instantiates something that (transitively) instantiates `M`" rung the way +rename's does for members. + +### Priority 3 — the round trip + +`extracting_a_region_and_inlining_it_back_returns_the_original` +(`tests/inline.rs`) re-run — passes, part of the full suite (see Gates). +Traced by hand: extract writes `sum u_sum (...)` from the region's own +dataflow-inferred ports; inline reads that same instantiation back and +substitutes the identical names, since nothing renamed anything on the way +out. `format_source` twice on both sides confirms byte-equal after +formatting, for the one pinned shape (combinational, single file). The +brief's "three shapes" (sequential-with-parameters, with-imports) are not +separately pinned — only the one shape has a dedicated round-trip test — +but both underlying halves (extract's parameter/import handling, inline's +`localparam`/import copying) are independently tested and nothing in +either side is shape-specific to the combinational case; not re-litigated +given the time budget, flagged rather than silently assumed clean. + +### Priority 4 — the server, over the wire + +Read `lucisv_server/src/inline_module.rs`, `main.rs`, `server/dispatch.rs` +in full (diffs above). Confirmed by reading and the existing (green) test +suite: `code_actions` returns `refactor.inline` with a `Command` and +**no `edit`** (`the_cursor_on_an_instantiation_is_offered_the_action_with_its_command`) +— the offer is exactly one parse of one buffer +(`vlog_refactor::inline_site`), no workspace read, matching the "lazy" +cost claim; not offered elsewhere +(`a_cursor_on_anything_else_is_offered_nothing`); `execute` reads +`ws.module_sources(&path, &site.units)` and calls `inline_module`, wiring +confirmed identical in shape to `extract`'s. `server/dispatch.rs`: the +`inline_module::kind()` branch in the `codeAction` fan-out and the +`INLINE_MODULE` branch in `executeCommand` are both routed **before** +`ports::execute`, matching the README and the same ordering `extract` +uses. `ports::workspace_edit` reused unchanged — confirmed by reading +(`ports.rs:435-458`): an ordinary `changes` map, no `Uri`/`CreateFile` +capability read anywhere in the inline path, matching "no client +capability is involved". No same-title-key collision risk analogous to +§50 was found: `commands()` appends `inline_module::commands()` once, and +`grep -rn "lucisv.inlineModule"` finds it declared in exactly one place. +The "one parse" cost claim was not independently profiled against a real +opentitan buffer (time budget); the code path matches `extract_site`'s +(same cheap-gate shape, same `parse_source_tolerant` call), so this is a +reading-based confirmation, not a measurement. + +### Priority 5 — the trials + +**Corpus** (`cargo test -p vlog_refactor --test corpus +five_instantiations_of_real_rtl_inline…`, unmodified `corpus/`, 860 +files): **5 inlined, 9 refused**, the exact module-pair table the README +prints, reproduced line for line. The extraction trial +(`five_regions_of_real_rtl_extract…`) re-run alongside it as a sanity +check: **5 extracted, 6 refused**, unchanged. + +**Opentitan** — not independently reproducible at the dev's exact 506-file +selection for the same reason the §53.1 pass flagged for the extraction +trial: the checkout subset used was not pinned reproducibly. Ran the same +automated trial against an independently-built scratch copy of +`hw/ip/{aes,hmac,uart,spi_host,prim}` — **741 `.sv`/`.svh` files** (more +than the dev's 506; `prim/` alone is 504 files in this checkout, so the +subsets evidently differ) — read-only source, scratch copies only: +**5 inlined, 356 refused** (`prim_secded_22_16_enc`→`_tb`, +`prim_secded_28_22_enc`→`_tb`, and three more not re-derived here since +the trial stops at five). Every accepted case parses, formats, converges, +and the census property (`borne`) holds. `356` vs. the README's `56` is +almost entirely `prim/`'s own `` `ifdef``/macro/`generate``-heavy FPV +testbenches contributing many refusals per file (`prim_alert_*`, +`prim_esc_*`, `prim_fifo_sync` with indexed connections, etc.) — not a +discrepancy in behaviour, a difference in what was scanned. + +**Three different opentitan instantiations, inlined and checked +independently** (the same parse/format/converge/census checks, over +targeted scratch copies of just the files each needs): + +| module → into | outcome | +| --- | --- | +| `prim_secded_22_16_enc` → `prim_secded_22_16_tb` | inlined, 0 names newly unbound | +| `prim_secded_28_22_enc` → `prim_secded_28_22_tb` | inlined, 0 names newly unbound | +| `prim_secded_39_32_enc` → `prim_secded_39_32_tb` | inlined, 0 names newly unbound (confirmed via the same test harness pointed at a 3-file scratch copy; the harness's own "exactly five" assertion was expected to — and did — fail on this deliberately tiny set, after the parse/format/converge/census checks for the one accepted case had already run clean) | + +All three are `.name`-shorthand connections (`.data_i`) into a module +whose instance is named the same as the module itself +(`prim_secded_39_32_enc prim_secded_39_32_enc (...)`) and whose `endmodule` +carries its own `: name` label — a shape not in the dev's or the first +three's own trial rows, and it inlines cleanly. + +**Incident, fully remediated.** Building the 741-file scratch copy, a +first `rsync` invocation omitted a trailing destination argument +(`rsync … opentitan/hw/ip/aes/ … opentitan/hw/ip/prim/`, five source-only +arguments), so rsync silently treated the **last** path +(`opentitan/hw/ip/prim/`) as the destination and copied `aes/`'s, `hmac/`'s, +`uart/`'s and `spi_host/`'s `.sv`/`.svh` files **into the real, +read-only opentitan checkout** at `hw/ip/prim/{rtl,dv,pre_dv}/` — caught +immediately by the mandatory post-read `git -C …/opentitan status +--porcelain` check, which showed ~130 unexpected untracked +files/directories under `hw/ip/prim/` beyond the three baseline diffs. +Nothing tracked was modified (every stray entry was a new, untracked +file), nothing was committed or pushed. Remediated by removing exactly the +paths `git status --porcelain -- hw/ip/prim/` listed as untracked (`rm -rf` +per path — `git clean` itself is denied by this environment's own +permission classifier for a QA session, which is the correct behaviour); +`git -C …/opentitan status --porcelain` re-checked clean afterward, back +to exactly the three pre-existing baseline diffs +(`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/ast.sv`, +`hw/top_earlgrey/ip/ast/rtl/ast.sv`). Recorded here in full rather than +quietly fixed, per the spirit of the task's own read-only rule. + +A second, unrelated slip in the same vein: the first byte-identity pass +(below) was run as a plain shell loop without `tools/guard.sh` and without +redirecting the CLI's stdin, and one corpus file left it blocked on a +stdin read for what `ps` reported as an implausible multi-hour elapsed +time with near-zero CPU consumed — a hang, not a slow computation. Killed +by hand (`kill -9`), re-run through `tools/guard.sh -t 600` with +`< /dev/null` on both invocations, and it completed in well under a +minute. No repo state was affected (it only ever read corpus files and a +release binary); flagged because CLAUDE.md's guard rule exists for exactly +this shape of mistake and it is the QA lane's own job to model following +it, not only to enforce it on the dev. + +### Gates (guarded throughout, all via `tools/guard.sh`) + +| Gate | Result | +| --- | --- | +| `cargo fmt --all -- --check` | clean | +| `cargo clippy --all-targets` | clean, no new `#[allow]` | +| `cargo test --workspace` | **4 133 passed, 0 failed, 44 ignored** — matches the dev's claim exactly | +| `tools/corpus_check.sh` | **814/820 (99.3%)**, the same six parse errors, 0 verification errors, 0 crashes — matches | +| `format --stdout` vs `~/.cache/lucisv-baselines/lucisv-0.48.1` over 860 corpus files (independently scripted) | **854 identical, 0 differing, 6 refused by both** — matches (see the incident note above for the first, failed attempt at this) | +| `cargo build --release -p lucisv -p lucisv_server` | ok | +| `node editors/vscode/smoke.js target/release/lucisv-server` | OK — 20 messages | +| `cargo test -p vlog_refactor --lib check::` / `--test inline` / `--test corpus` / `-p lucisv_server inline_module` (post-cleanup, on the restored tree) | 57/57, 37/37, 11/11, 6/6 — all green | + +All temporary tests and scratch copies removed before finishing. +`check/mod.rs` diffed against the dev's own (`git show HEAD:… | patch < +check_mod.diff`) — byte-identical. `tests/inline.rs` (604 lines) and +`tests/corpus.rs` (233-line diff) both confirmed identical to their state +at the start of this pass. `git -C …/opentitan status --porcelain` shows +only the three baseline diffs, both before and after (see the incident +note). `git status --porcelain` on this tree shows exactly the dev's own +file set plus this README's QA-log edit and the `TODO.md` checkbox — +`CHANGELOG.md` and `editors/vscode/CHANGELOG.md` are modified in the +working tree by what reads as the lead's own in-flight 0.49.0 +release-notes work (a `## 0.49.0` section already describing this +feature), present when this pass started and untouched by it — flagged +per the file-ownership rule, exactly as the §53.1 pass flagged +`docs/coverage_gaps.md`. + +### Verdict: **PASS** + +No blocking defect found. Two MEDIUM, non-blocking findings, both +documentation/follow-up rather than fixes: + +1. **QA-2** — the copy allowance's `Transit::lands` equation cannot, in + principle, distinguish "a piece landed twice" from "one piece landed + locally (carried) and a second, textually-identical one landed by copy" + when both share the same `(noun, text)` key — the exact same root cause + as §53.1's QA-1, one level up. Traced through every shape + `inline_module`'s real code produces today and found not reachable by + any current planner; a hand-crafted edit is needed to exhibit it. Same + recommendation as QA-1: a per-piece identity/position tag, if either is + ever addressed. +2. **QA-3** — `module_sources`'s fan-out (`lucisv_server/src/state.rs`) + has no rung for a file that reaches the instance being inlined through + an intermediate module it does not itself instantiate, so + `no_hierarchy`'s scan can silently miss a real XMR one hop further out + than a direct reference — confirmed reproducible, not hypothetical. + Matches the README's own documented assumption; flagged with severity + because the trigger shape (testbench/SVA reaching through a wrapper) is + ordinary in the RTL this feature targets, not exotic. + +Every priority-1 verifier attack the brief named was run through the +production entry point (dev's eight re-confirmed, nine more added); the +neutering table shows both rule 0 and the copy transit are load-bearing, +each catching a distinct, real class of corruption nothing else in +`verify_move` would. The inline substitution/prefixing/refusal matrix was +attacked on five previously-uncovered shapes and none of them broke. The +handed-files narrowing was confirmed concretely rather than left as a +reading-based guess. Corpus and opentitan trials reproduce the dev's +claims (or, where the exact file set could not be reproduced, an +independently-built and larger one gives the same qualitative result plus +three genuinely new accepted inlines). All gates are green and match the +dev's own numbers exactly. One QA-caused incident (a stray `rsync` +briefly touching the read-only opentitan checkout, and an unguarded, +unredirected shell loop that hung) is recorded in full and was fully +remediated before this pass finished. + ## Review +**2026-09-06 — lead (53.1).** Accepted after one rework; see the 53.1 +paragraph below for the record. 53.1 shipped in 0.47.0. + +**2026-09-06 — lead (53.2).** Accepted; ships in 0.49.0 with §54. Inline +is the mirror of extract and is built as one: substitution from the +symbol table rather than text search, prefixing only where the file +already spells a name, the `.name` shorthand expanded rather than +rewritten — that last one found by the corpus trial, which is what the +trials are for. The verifier's `Copied` origin is the honest model of a +copy (the source file must appear in no edit; each copied piece lands once +per copy), pinned by eight attack pairs through the production entry, and +QA's neutering map shows every rule load-bearing. The deviations are all +in the conservative direction (same-file `S`, unconnected outputs, any +`generate`, prefixing past an end label refuse). QA's two MEDIUMs are +recorded, not actioned here: QA-2 is topo §2.9-32's blind spot in a new +coat, same fix; QA-3 — the hierarchical scan sees only the files +`module_sources` hands over, and a bench reaching `u_S` through a wrapper +it does not instantiate is not among them — is filed as topo §2.9-33 with +the rung it wants. The extract → inline round trip is pinned byte-equal +after formatting. + + **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 diff --git a/docs/topo.md b/docs/topo.md index 3a286c9..b295358 100644 --- a/docs/topo.md +++ b/docs/topo.md @@ -669,6 +669,7 @@ update the filing README(s) and this file. | ~~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 | +| 33 | **`module_sources`' fan-out has no rung for a file that reaches an instance through an intermediate module it does not itself instantiate** (a bench naming `wrap.u_S.x` where `wrap` instantiates `S`): inline-module's hierarchical-reference refusal sees only the handed files, so such a reference is missed. Wanted: a transitive-instantiators rung (§49's hierarchical surface knows the path) in `module_sources` for the refactorings that must see every hierarchical use. Found by §53.2's QA. | extract-inline-module (QA) | lucisv_server / vlog_refactor | --- diff --git a/editors/vscode/CHANGELOG.md b/editors/vscode/CHANGELOG.md index c0386f3..002dfbf 100644 --- a/editors/vscode/CHANGELOG.md +++ b/editors/vscode/CHANGELOG.md @@ -5,6 +5,12 @@ for you. The extension and its bundled language server share one version number; the full engineering notes live in the [project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md). +## 0.49.0 — 2026-09-06 + +- **Inline module** from the lightbulb on an instantiation: the module's + body is copied in with ports and parameters substituted and every + comment kept; the reverse of extract module. + ## 0.48.2 — 2026-09-06 - The 0.48.0 package was built without the DUT-centred hierarchy view