TODO §53.1 (docs/features/extract-inline-module), the fourth §8
refactoring; §53.2 inline module is unstarted and runs as its own lane.
`vlog_refactor::extract` (region, flow, boundary, render): a selection
of whole module items becomes a new module — a name declared outside
and read inside is an `input`, written inside an `output` (assign and
procedural LHS, for init/step, ++/--, force/release/deassign, `-> ev`,
an initialiser, an output/inout connection through the index), written
on both sides refused; parameters passed through `#(.P(P))`, used
imports copied, the port's type taken from the declaration's own text;
the selection replaced by an instantiation rendered from the new
module's text. Forty-three refusal sentences. `RefactorEdit::created`;
the server emits `CreateFile` document changes when the client reads
both halves of the capability, else writes the module below its source;
`refactor.extract` action carrying `lucisv.extractModule [uri, range,
name]`, and a name prompt in the VS Code extension through the language
client's middleware.
The verifier's never-dropped ledger follows the move (review rework of
QA's two HIGHs): `verify_move(moving: &[(file, region)])` — a piece
deleted inside the moved region must land exactly once in the file the
move names, a deletion outside the region stays an ordinary deletion,
four equations, twelve attack pairs through the production entry;
`check.rs` split (pure move) into `check/{mod,ledger}.rs`. `interface`
and `program` bodies are refused (one AST node, gated on `kw`). QA's
re-attack: PASS; its MEDIUM (a same-file relocation as two edits) is
filed as topo §2.9-32.
Trials: corpus 5 extracted / 6 refused, opentitan `hw/ip/{aes,uart,
spi_host,hmac}` 5 / 5, the unresolved-name census held for every
accepted extraction. 0 of 820 corpus files differ from 0.46.0.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
512 lines
20 KiB
Rust
512 lines
20 KiB
Rust
//! Extract a selection of whole module items into a module of its own.
|
|
//!
|
|
//! The user selects one or more contiguous items of a module `M` — an
|
|
//! `always` block, an `assign`, an instantiation, a declaration, a generate
|
|
//! construct — and names the module `N` they want them in. lucisv works out
|
|
//! `N`'s ports from the dataflow across the selection's boundary, writes `N`
|
|
//! into a file of its own beside `M`'s (or below `M`, for a client that cannot
|
|
//! create files), and replaces the selection with an instantiation of `N`
|
|
//! **rendered from `N`'s own text**, so the skeleton and the module can never
|
|
//! disagree about what `N`'s ports are.
|
|
//!
|
|
//! Three files, one question each:
|
|
//!
|
|
//! * `region` — *what does the selection cover?* The module, the run of whole
|
|
//! items, and the item kinds lucisv will not carry into another module.
|
|
//! * `flow` — *which names cross the boundary, and in which direction?* The
|
|
//! dataflow rule, and the two positions it refuses to guess at.
|
|
//! * `render` — *what does lucisv write?* A port's type as its declaration
|
|
//! spells it, the new module, and the instantiation.
|
|
//!
|
|
//! This file is the plan: the entry points, the classification of each
|
|
//! crossing name into a port, a parameter or a refusal, the edits, and the
|
|
//! verification. Everything is one [`check::verify_move`] over the whole edit,
|
|
//! which for a new file is the ordinary splice contract plus one deliberate
|
|
//! widening: the comments the selection carries are deleted in `M`'s file and
|
|
//! written in `N`'s, so the never-dropped ledger is kept over the pair rather
|
|
//! than over each file alone. See
|
|
//! `docs/features/extract-inline-module/README.md`.
|
|
|
|
mod boundary;
|
|
mod flow;
|
|
mod region;
|
|
mod render;
|
|
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use vlog_parser::ast::{Item, ItemKind, SourceFile};
|
|
use vlog_parser::parse_source_tolerant;
|
|
use vlog_parser::span::TextRange;
|
|
use vlog_semantic::{analyze, SymbolKind};
|
|
|
|
use crate::rename::{display, Scope};
|
|
use crate::{check, RefactorEdit, TextEdit};
|
|
|
|
use boundary::Crossing;
|
|
use region::Region;
|
|
|
|
/// Where the extracted module is written.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum Home {
|
|
/// A file `N.sv` beside `M`'s own — what a client that advertises
|
|
/// `workspace.workspaceEdit.documentChanges` with `CreateFile` support
|
|
/// gets, because only such a client can apply the creation.
|
|
NewFile,
|
|
/// Below `M`, in `M`'s own file — the fallback for every other client,
|
|
/// and for a caller that asked for it.
|
|
SameFile,
|
|
}
|
|
|
|
/// What the cheap gate found: the selection is in a module, and these are the
|
|
/// units whose files the engine needs read.
|
|
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
|
pub struct ExtractSite {
|
|
/// The module the selection is written in.
|
|
pub module: String,
|
|
/// The name the action proposes when the caller has none: `M_extracted`.
|
|
pub default_name: String,
|
|
/// Every unit whose declaration the engine will look up: the module
|
|
/// itself, the modules the selection instantiates, and the packages the
|
|
/// module imports.
|
|
pub units: Vec<String>,
|
|
}
|
|
|
|
/// Whether a selection is one lucisv could extract, and what it would need to
|
|
/// read to try.
|
|
///
|
|
/// **The cheap gate**: one parse of one buffer, no workspace and no I/O — the
|
|
/// bargain `port_action_modules` and `imported_packages` strike, and for the
|
|
/// same reason (a `textDocument/codeAction` arrives on every cursor move).
|
|
/// Empty exactly where [`extract_module`] would refuse for want of a module or
|
|
/// a whole item to move.
|
|
pub fn extract_site(text: &str, start: u32, end: u32) -> Option<ExtractSite> {
|
|
let (tree, diagnostics) = parse_source_tolerant(text);
|
|
if !diagnostics.is_empty() {
|
|
return None;
|
|
}
|
|
let region = Region::read(&tree, text, TextRange::new(start, end)).ok()?;
|
|
let module = region.module_name().to_string();
|
|
let mut units = vec![module.clone()];
|
|
for item in ®ion.items {
|
|
collect_instantiated(item, &mut units);
|
|
}
|
|
for import in ®ion.module.imports {
|
|
for path in &import.paths {
|
|
push(&mut units, path.pkg.text.clone());
|
|
}
|
|
}
|
|
for item in ®ion.module.items {
|
|
if let ItemKind::Import(paths) = &item.kind {
|
|
for path in paths {
|
|
push(&mut units, path.pkg.text.clone());
|
|
}
|
|
}
|
|
}
|
|
Some(ExtractSite { default_name: format!("{module}_extracted"), module, units })
|
|
}
|
|
|
|
/// The lightbulb's text, written here so every front end says the same thing.
|
|
pub fn extract_title() -> String {
|
|
"lucisv: extract selection into module…".to_string()
|
|
}
|
|
|
|
/// Extract the items `[start, end)` covers out of the module that holds them,
|
|
/// into a module called `new_name`.
|
|
pub fn extract_module(
|
|
files: &[(PathBuf, String)],
|
|
file: &Path,
|
|
start: u32,
|
|
end: u32,
|
|
new_name: &str,
|
|
home: Home,
|
|
) -> Result<RefactorEdit, String> {
|
|
plain_identifier(new_name)?;
|
|
// The new file joins the in-scope set as an *empty* file, so that every
|
|
// question below — the index, the analysis, the verification — is asked
|
|
// about it exactly the way it is asked about a file that was always there.
|
|
let mut sources: Vec<(PathBuf, String)> = files.to_vec();
|
|
let created = match home {
|
|
Home::SameFile => None,
|
|
Home::NewFile => {
|
|
let path = beside(file, new_name);
|
|
match sources.iter().find(|(held, _)| *held == path) {
|
|
Some((_, text)) if !text.trim().is_empty() => return Err(occupied(&path)),
|
|
Some(_) => {}
|
|
None => sources.push((path.clone(), String::new())),
|
|
}
|
|
Some(path)
|
|
}
|
|
};
|
|
let plan = Extraction::plan(&sources, file, start, end, new_name, created.clone())?;
|
|
Ok(RefactorEdit {
|
|
edits: plan.edits,
|
|
warnings: plan.warnings,
|
|
created: created.into_iter().collect(),
|
|
})
|
|
}
|
|
|
|
/// What the extraction produced, before it is dressed as a [`RefactorEdit`].
|
|
struct Extraction {
|
|
edits: Vec<(PathBuf, Vec<TextEdit>)>,
|
|
warnings: Vec<String>,
|
|
}
|
|
|
|
impl Extraction {
|
|
fn plan(
|
|
sources: &[(PathBuf, String)],
|
|
file: &Path,
|
|
start: u32,
|
|
end: u32,
|
|
new_name: &str,
|
|
created: Option<PathBuf>,
|
|
) -> Result<Extraction, String> {
|
|
let mut scope = Scope::build(sources);
|
|
let Some(here) = scope.index_of(file) else { return Err(not_in_scope(file)) };
|
|
let Some(text) = scope.text(here) else { return Err(not_in_scope(file)) };
|
|
let (tree, diagnostics) = parse_source_tolerant(text);
|
|
if let Some(problem) = diagnostics.first() {
|
|
return Err(format!(
|
|
"{} does not parse ({} at line {}), so lucisv will not extract from it.",
|
|
display(file),
|
|
problem.message,
|
|
problem.line
|
|
));
|
|
}
|
|
let region = Region::read(&tree, text, TextRange::new(start, end))?;
|
|
let module = region.module_name().to_string();
|
|
declared_once(&scope, &module)?;
|
|
undeclared(&scope, new_name)?;
|
|
if new_name == module {
|
|
return Err(format!("`{module}` is already the name of the module you are in."));
|
|
}
|
|
if created.is_some() {
|
|
no_directive(&tree, text, ®ion)?;
|
|
}
|
|
let semantics = analyze(&tree, text);
|
|
if let Some(path) = flow::hierarchical_escape(text, &semantics, ®ion) {
|
|
return Err(hierarchical(&path));
|
|
}
|
|
let flow = flow::read(&scope, text, &semantics, ®ion)?;
|
|
let packages = boundary::packages(&tree);
|
|
let crossing =
|
|
Crossing::read(text, &semantics, ®ion, &flow, &packages, created.is_some())?;
|
|
|
|
// The new module, then the instantiation read back out of it.
|
|
let body = format!("{}{}", region.indent, slice(text, region.span));
|
|
let module_text = render::new_module(
|
|
new_name,
|
|
&crossing.imports,
|
|
&crossing.params,
|
|
&crossing.ports,
|
|
&ensure_newline(&body),
|
|
);
|
|
let instance = render::instantiation(new_name, &module_text, ®ion.indent)?;
|
|
|
|
let mut edits: Vec<(usize, Vec<TextEdit>)> = Vec::new();
|
|
// What the verifier is allowed to let travel, and between which bytes:
|
|
// `M`'s file loses exactly the pieces inside the region, and the new
|
|
// file — named with an empty range, because it has no region of its
|
|
// own — is the only place they may land.
|
|
let mut moving: Vec<(usize, TextRange)> = Vec::new();
|
|
let replace = TextEdit { range: region.span, new_text: instance };
|
|
match &created {
|
|
Some(path) => {
|
|
let Some(there) = scope.index_of(path) else { return Err(not_in_scope(path)) };
|
|
edits.push((here, vec![replace]));
|
|
edits.push((
|
|
there,
|
|
vec![TextEdit { range: TextRange::empty(0), new_text: module_text.clone() }],
|
|
));
|
|
moving = vec![(here, region.span), (there, TextRange::empty(0))];
|
|
}
|
|
None => {
|
|
let append = TextEdit {
|
|
range: TextRange::empty(region.module_span.end),
|
|
new_text: format!("\n\n{module_text}"),
|
|
};
|
|
edits.push((here, vec![replace, append]));
|
|
}
|
|
}
|
|
edits.sort_by_key(|(i, _)| *i);
|
|
moving.sort_by_key(|(i, _)| *i);
|
|
|
|
let what = format!("extracting `{new_name}` out of `{module}`");
|
|
check::verify_move(&mut scope, &edits, &[&module, new_name], &what, &moving)?;
|
|
confirm(&scope, &edits, new_name, &crossing, &what)?;
|
|
|
|
let mut out: Vec<(PathBuf, Vec<TextEdit>)> = Vec::new();
|
|
for (i, file_edits) in edits {
|
|
let Some(path) = scope.path(i) else { return Err(lost(&what)) };
|
|
out.push((path.to_path_buf(), file_edits));
|
|
}
|
|
out.sort_by(|a, b| a.0.cmp(&b.0));
|
|
Ok(Extraction { edits: out, warnings: crossing.warnings(new_name, &created, file) })
|
|
}
|
|
}
|
|
|
|
/// Read the edited text back and require the new module to declare exactly the
|
|
/// ports and parameters the plan promised.
|
|
///
|
|
/// `verify_move` proves the edit is lexically and semantically honest; nothing
|
|
/// in it proves the header lucisv wrote is the header it meant to write.
|
|
fn confirm(
|
|
scope: &Scope<'_>,
|
|
edits: &[(usize, Vec<TextEdit>)],
|
|
new_name: &str,
|
|
crossing: &Crossing,
|
|
what: &str,
|
|
) -> Result<(), String> {
|
|
for (i, file_edits) in edits {
|
|
let (Some(text), Some(path)) = (scope.text(*i), scope.path(*i)) else {
|
|
return Err(lost(what));
|
|
};
|
|
let edited = crate::apply(text, file_edits);
|
|
let Ok(plan) = crate::instantiate::instantiation_plan(new_name, &edited, None) else {
|
|
continue;
|
|
};
|
|
let ports: Vec<&str> = plan.ports.iter().map(|port| port.name.as_str()).collect();
|
|
let params: Vec<&str> = plan.params.iter().map(|param| param.name.as_str()).collect();
|
|
let wanted_ports: Vec<&str> = crossing.ports.iter().map(|p| p.name.as_str()).collect();
|
|
let wanted_params: Vec<&str> = crossing.params.iter().map(|p| p.name.as_str()).collect();
|
|
if ports != wanted_ports || params != wanted_params {
|
|
return Err(format!(
|
|
"{what} would not leave `{new_name}` with the header lucisv intended in {}; no edits were made.",
|
|
display(path)
|
|
));
|
|
}
|
|
return Ok(());
|
|
}
|
|
Err(lost(what))
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// odds and ends
|
|
// ----------------------------------------------------------------------
|
|
|
|
fn inside(region: &Region<'_>, span: TextRange) -> bool {
|
|
region.span.start <= span.start && span.end <= region.span.end
|
|
}
|
|
|
|
fn inside_module(region: &Region<'_>, span: TextRange) -> bool {
|
|
region.module_span.start <= span.start && span.end <= region.module_span.end
|
|
}
|
|
|
|
fn slice(text: &str, span: TextRange) -> &str {
|
|
text.get(span.start as usize..span.end as usize).unwrap_or("")
|
|
}
|
|
|
|
fn ensure_newline(text: &str) -> String {
|
|
match text.ends_with('\n') {
|
|
true => text.to_string(),
|
|
false => format!("{text}\n"),
|
|
}
|
|
}
|
|
|
|
fn push(out: &mut Vec<String>, name: String) {
|
|
if !out.contains(&name) {
|
|
out.push(name);
|
|
}
|
|
}
|
|
|
|
/// Every module an item instantiates, nested generate constructs included.
|
|
fn collect_instantiated(item: &Item, out: &mut Vec<String>) {
|
|
match &item.kind {
|
|
ItemKind::Instantiation(inst) => push(out, inst.module.clone()),
|
|
ItemKind::GenerateRegion { items, .. } => {
|
|
for item in items {
|
|
collect_instantiated(item, out);
|
|
}
|
|
}
|
|
ItemKind::GenBlock(block) => {
|
|
for item in &block.items {
|
|
collect_instantiated(item, out);
|
|
}
|
|
}
|
|
ItemKind::GenIf(gen_if) => {
|
|
for item in &gen_if.then.items {
|
|
collect_instantiated(item, out);
|
|
}
|
|
let mut els = gen_if.els.as_deref();
|
|
while let Some(branch) = els {
|
|
match branch {
|
|
vlog_parser::ast::GenElse::If(_, nested) => {
|
|
for item in &nested.then.items {
|
|
collect_instantiated(item, out);
|
|
}
|
|
els = nested.els.as_deref();
|
|
}
|
|
vlog_parser::ast::GenElse::Block(block) => {
|
|
for item in &block.items {
|
|
collect_instantiated(item, out);
|
|
}
|
|
els = None;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
ItemKind::GenFor(gen_for) => {
|
|
for item in &gen_for.body.items {
|
|
collect_instantiated(item, out);
|
|
}
|
|
}
|
|
ItemKind::GenCase(gen_case) => {
|
|
for case_item in &gen_case.items {
|
|
for item in &case_item.body.items {
|
|
collect_instantiated(item, out);
|
|
}
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
/// The file the new module goes in: `N.sv`, beside the file it came out of.
|
|
fn beside(file: &Path, new_name: &str) -> PathBuf {
|
|
let parent = file.parent().map_or_else(PathBuf::new, Path::to_path_buf);
|
|
parent.join(format!("{new_name}.sv"))
|
|
}
|
|
|
|
/// A module name lucisv will write into a file name and a header: a plain
|
|
/// identifier, never an escaped one.
|
|
fn plain_identifier(name: &str) -> Result<(), String> {
|
|
let mut chars = name.chars();
|
|
let head = chars.next().filter(|c| c.is_ascii_alphabetic() || *c == '_');
|
|
let tail = chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$');
|
|
match head.is_some() && tail {
|
|
true => Ok(()),
|
|
false => Err(format!(
|
|
"`{name}` is not a plain SystemVerilog identifier, and lucisv will not name a module — or a file — with anything else."
|
|
)),
|
|
}
|
|
}
|
|
|
|
/// The module the selection is in must be declared exactly once in the
|
|
/// workspace: an extraction rewrites *this* `M`, and two of them means lucisv
|
|
/// does not know whose ports the selection reads.
|
|
fn declared_once(scope: &Scope<'_>, module: &str) -> Result<(), String> {
|
|
let defs = scope.index().units(module).iter().filter(|def| def.kind.is_instantiable()).count();
|
|
match defs {
|
|
1 => Ok(()),
|
|
0 => Err(format!("lucisv indexes no module named `{module}`.")),
|
|
_ => Err(format!(
|
|
"`{module}` is declared in more than one indexed file, so lucisv cannot tell which one the selection belongs to."
|
|
)),
|
|
}
|
|
}
|
|
|
|
fn undeclared(scope: &Scope<'_>, name: &str) -> Result<(), String> {
|
|
match scope.index().units(name).is_empty() {
|
|
true => Ok(()),
|
|
false => {
|
|
Err(format!("the workspace already declares `{name}`; pick a name nothing else uses."))
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A `timescale` or a `default_nettype` in force where `M` is written does not
|
|
/// follow the items into a file of their own, and silently changing either one
|
|
/// changes what the design does.
|
|
fn no_directive(tree: &SourceFile, text: &str, region: &Region<'_>) -> Result<(), String> {
|
|
for item in &tree.items {
|
|
let ItemKind::Directive(raw) = &item.kind else { continue };
|
|
if item.span.start > region.module_span.end {
|
|
continue;
|
|
}
|
|
let word = raw.text.split_whitespace().next().unwrap_or("");
|
|
if word == "`timescale" || word == "`default_nettype" || word == "`resetall" {
|
|
return Err(format!(
|
|
"`{}` writes `{word}` before the module the selection is in, and a new file would not inherit it; extract into the same file, or move the directive into an include both files use.",
|
|
first_line(text, item.span.start)
|
|
));
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// The file's own name is not to hand here, so a directive refusal names the
|
|
/// line the directive is on instead.
|
|
fn first_line(text: &str, at: u32) -> String {
|
|
let line = text.get(..at as usize).map_or(0, |head| head.matches('\n').count()) + 1;
|
|
format!("line {line}")
|
|
}
|
|
|
|
fn count(n: usize, noun: &str) -> String {
|
|
match n {
|
|
1 => format!("1 {noun}"),
|
|
n => format!("{n} {noun}s"),
|
|
}
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// sentences
|
|
// ----------------------------------------------------------------------
|
|
|
|
fn not_in_scope(file: &Path) -> String {
|
|
format!("{} is not one of the files lucisv was given.", display(file))
|
|
}
|
|
|
|
fn occupied(path: &Path) -> String {
|
|
format!("there is already a `{}` beside this file; pick another name.", display(path))
|
|
}
|
|
|
|
fn escaped(name: &str) -> String {
|
|
format!(
|
|
"`{name}` is declared inside the selection and used outside it; move the declaration of `{name}` out of the selection first."
|
|
)
|
|
}
|
|
|
|
fn outside_module(name: &str, module: &str) -> String {
|
|
format!(
|
|
"the selection uses `{name}`, which is declared outside `{module}` in the same file; a module in a file of its own would not see it, so lucisv made no edits."
|
|
)
|
|
}
|
|
|
|
/// The same refusal for a **member access**, which names the head first.
|
|
/// `s.f` and `bus.data` cross the boundary as `s` and `bus` — the port or the
|
|
/// variable — and `f` and `data` are names of *their* types; a sentence that
|
|
/// leads with the field reads as if the field were a signal of `M`'s own.
|
|
fn outside_module_member(head: &str, name: &str, module: &str) -> String {
|
|
format!(
|
|
"the selection uses `{head}.{name}`, and `{head}` is declared with a type written outside `{module}` in the same file; a module in a file of its own would not see it, so lucisv made no edits."
|
|
)
|
|
}
|
|
|
|
fn unmovable(name: &str, module: &str, kind: SymbolKind) -> String {
|
|
let what = match kind {
|
|
SymbolKind::Genvar => "a `genvar`",
|
|
SymbolKind::Function => "a function",
|
|
SymbolKind::Task => "a task",
|
|
SymbolKind::Typedef => "a type",
|
|
SymbolKind::EnumVariant => "an enumeration member",
|
|
SymbolKind::Instance => "an instance",
|
|
SymbolKind::Modport => "a modport",
|
|
SymbolKind::Clocking => "a clocking block",
|
|
SymbolKind::Class => "a class",
|
|
SymbolKind::Block => "a named block",
|
|
_ => "a declaration",
|
|
};
|
|
format!(
|
|
"the selection uses `{name}`, {what} `{module}` declares outside it; lucisv makes ports out of signals and parameters and nothing else, so it made no edits."
|
|
)
|
|
}
|
|
|
|
fn header_names(module: &str, owner: &str, word: &str) -> String {
|
|
format!(
|
|
"`{module}` declares `{owner}` with something that names `{word}`, which is neither a parameter nor a name a module in another file could reach; lucisv made no edits."
|
|
)
|
|
}
|
|
|
|
fn hierarchical(path: &str) -> String {
|
|
format!(
|
|
"the selection reads `{path}` through the design hierarchy, and a hierarchical path does not survive being moved into another module; lucisv made no edits."
|
|
)
|
|
}
|
|
|
|
fn lost_name(name: &str) -> String {
|
|
format!("lucisv lost track of the declaration of `{name}`, so it made no edits.")
|
|
}
|
|
|
|
fn lost(what: &str) -> String {
|
|
format!("lucisv could not name one of the files it edited for {what}.")
|
|
}
|