Files
lucisv/crates/vlog_refactor/src/extract/mod.rs
T

558 lines
21 KiB
Rust

// Author: Guoliang Chen, a Senior Digital Design Engineer
//! 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::span::TextRange;
use vlog_parser::{parse_source_tolerant, ParseDiagnostic};
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);
extract_site_in(&tree, &diagnostics, text, start, end)
}
/// [`extract_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
/// (`Region::read` copies item text out by span). Take 5 §P1b; see
/// `docs/features/perf5-p1/README.md`.
pub fn extract_site_in(
tree: &SourceFile,
diagnostics: &[ParseDiagnostic],
text: &str,
start: u32,
end: u32,
) -> Option<ExtractSite> {
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 &region.items {
collect_instantiated(item, &mut units);
}
for import in &region.module.imports {
for path in &import.paths {
push(&mut units, path.pkg.text.clone());
}
}
for item in &region.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(does_not_parse(file, problem));
}
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, &region)?;
}
let semantics = analyze(&tree, text);
if let Some(path) = flow::hierarchical_escape(text, &semantics, &region) {
return Err(hierarchical(&path));
}
let flow = flow::read(&scope, text, &semantics, &region)?;
let packages = boundary::packages(&tree);
let crossing =
Crossing::read(text, &semantics, &region, &flow, &packages, created.is_some())?;
// The new module, then the instantiation read back out of it.
let eol = line_ending(text);
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, eol),
eol,
);
let instance = render::instantiation(new_name, &module_text, &region.indent, eol)?;
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<check::Moving> = 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![
check::Moving::source(here, region.span),
check::Moving::destination(there),
];
}
None => {
let append = TextEdit {
range: TextRange::empty(region.module_span.end),
new_text: format!("{eol}{eol}{module_text}"),
};
edits.push((here, vec![replace, append]));
}
}
edits.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)?;
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));
let created = created.as_deref().map(|path| scope.name_of(path));
let warnings = crossing.warnings(new_name, created.as_deref(), &scope.name_of(file));
Ok(Extraction { edits: out, warnings })
}
}
/// 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.",
scope.name_of(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 line_ending(text: &str) -> &'static str {
match text.contains("\r\n") {
true => "\r\n",
false => "\n",
}
}
fn ensure_newline(text: &str, eol: &str) -> String {
if text.ends_with(eol) {
text.to_string()
} else if let Some(prefix) = text.strip_suffix('\n') {
format!("{prefix}{eol}")
} else {
format!("{text}{eol}")
}
}
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))
}
/// Why a file lucisv cannot read is a file it will not extract from.
///
/// Reachable through `extract_module` alone: a server calls [`extract_site_in`]
/// first, and that answers `None` for a file with any parse diagnostic, so the
/// sentence is for the caller that comes straight to the engine.
fn does_not_parse(file: &Path, problem: &ParseDiagnostic) -> String {
format!(
"{} does not parse ({} at line {}), so lucisv will not extract from it.",
display(file),
problem.message,
problem.line
)
}
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}.")
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com