Files
lucisv/crates/vlog_refactor/src/inline/mod.rs
T
lucioandClaude Opus 5.5 ca83f6f99f Review lows L-1–L-4, L-12, L-13: end labels, duplicate generate labels, dotted comments, lex-failure fallbacks, file naming
- L-1: an unowned block's closing label is a use of a same-named block only
  for block constructs and only when it spells the construct's own opening
  label (use_block_end_label); a mismatched `end : a` or an `endfunction : g`
  beside block `g` records nothing.
- L-2: duplicate-declaration stays silent for two block labels only when
  both may be arms of one generate if/case; sibling `for` blocks and a
  procedural block beside a generate one are reported in either order.
  OpenTitan check: 1 158 findings, identical to 0.60.0.
- L-3: a block comment between `.` and the name is still dotted.
- L-4: a bind file that does not lex counts as binding (K2); a pasted
  fragment that does not lex is said, not skipped.
- L-12: no unchecked slice in rename/arms.rs.
- L-13: expand/ansi/inline/extract messages name files by Scope::name_of.

7 tests (L-3/L-4's fail with the fixes disabled). Per-crate suites under the
guard: 80 suites, 5 085 passed, 0 failed, 51 ignored (one combined run was
cut at 1 800 s in vlog_refactor/tests/corpus.rs with syspolicyd at 95 % —
the §65.3 stall).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 13:33:27 -07:00

386 lines
16 KiB
Rust

//! 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::ast::SourceFile;
use vlog_parser::span::TextRange;
use vlog_parser::token::TokenKind;
use vlog_parser::{parse_source_tolerant, tokenize, ParseDiagnostic};
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<String>,
}
/// 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<InlineSite> {
let (tree, diagnostics) = parse_source_tolerant(text);
inline_site_in(&tree, &diagnostics, text, offset)
}
/// [`inline_site`] over a parse the caller already has.
///
/// The same answer, refusal on parse diagnostics included — `diagnostics`
/// must be `tree`'s own list, and `text` the bytes both were built from
/// (`Site::read` reads the instantiation's connections out of the source).
/// Take 5 §P1b; see `docs/features/perf5-p1/README.md`.
pub fn inline_site_in(
tree: &SourceFile,
diagnostics: &[ParseDiagnostic],
text: &str,
offset: u32,
) -> Option<InlineSite> {
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<RefactorEdit, String> {
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, &scope.name_of(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, &scope.name_of(&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<render::Inlined, String> {
let taken: Vec<String> = {
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<String> {
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<usize, String> {
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,
scope.name_of(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<String> {
let mut out = None;
for line in text.lines().map(str::trim) {
if line.starts_with("`timescale") {
out = Some(line.split_whitespace().collect::<Vec<_>>().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,
scope.name_of(path)
));
}
}
}
Ok(())
}
// ----------------------------------------------------------------------
// odds and ends
// ----------------------------------------------------------------------
fn parsed(text: &str, shown: &str) -> Result<vlog_parser::ast::SourceFile, String> {
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.",
shown, 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<String> {
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<String> {
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<String> {
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.";