Files
lucisv/crates/vlog_refactor/src/extract/flow.rs
T
lucioandClaude Fable 5.1 acf20f7e62 Extract module: dataflow-inferred ports, a new file where the client can create one, and a verifier ledger that follows the move
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]>
2026-09-05 23:04:14 -05:00

665 lines
25 KiB
Rust

//! Which names cross the selection's boundary, and in which direction.
//!
//! The whole of "what ports does the new module need" is here, and it is one
//! question asked of two tables: `vlog_semantic`'s references say *which
//! declaration* each name in the module means, and the tree says whether each
//! use of it is a **write** or a **read**. A name declared outside the
//! selection and used inside it becomes a port — `input` when the selection
//! only reads it, `output` when the selection writes it.
//!
//! **A name is written by the selection when, and only when, it is:** the
//! left-hand side of a continuous assignment; the left-hand side of a
//! blocking or non-blocking assignment (or of a `for` initialiser or step, or
//! the target of a `++`/`--`) anywhere inside an `always` block; the target of
//! a `force`, a `release` or a `deassign`; the target of a `-> ev`; the
//! declarator's own initialiser; or connected to an `output` or `inout` port
//! of an instantiated module — which is a fact only that module's own
//! declaration holds, so it is looked up through the workspace index and the
//! extraction is **refused** when the index cannot answer. Everything else is
//! a read. Two positions are neither, and both refuse rather than guess: an
//! argument of a task or function call, whose direction only the routine's
//! prototype knows, and a positional or `.*` connection, which names no port
//! at all.
//!
//! Nothing here edits. It answers, or it refuses with a sentence.
use std::collections::HashMap;
use vlog_parser::ast::{
Connections, Expr, ExprKind, ForStep, Instantiation, Item, ItemKind, ListElem, Stmt, StmtKind,
};
use vlog_parser::span::TextRange;
use vlog_semantic::{Reference, Resolution, Semantics, Surface, SymbolId, SymbolKind};
use crate::instantiate::{instantiation_plan, module_definition};
use crate::rename::Scope;
use super::region::Region;
/// What one use of a name is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Use {
Read,
Write,
/// A position whose direction lucisv cannot know: a call argument, a
/// connection to a port it could not read.
Unknown,
}
/// Everything done to one declaration, on each side of the boundary.
#[derive(Debug, Default, Clone, Copy)]
pub(super) struct Sides {
pub(super) inside_read: bool,
pub(super) inside_write: bool,
pub(super) inside_unknown: bool,
pub(super) outside_read: bool,
pub(super) outside_write: bool,
pub(super) outside_unknown: bool,
}
impl Sides {
pub(super) fn used_inside(&self) -> bool {
self.inside_read || self.inside_write || self.inside_unknown
}
pub(super) fn used_outside(&self) -> bool {
self.outside_read || self.outside_write || self.outside_unknown
}
}
/// The boundary table: what each declaration the module holds has done to it
/// on each side of the selection, and which of the module's own references sit
/// inside it.
pub(super) struct Flow {
sides: HashMap<SymbolId, Sides>,
/// The references written inside the region, in source order.
pub(super) inside: Vec<usize>,
}
impl Flow {
pub(super) fn sides(&self, symbol: SymbolId) -> Sides {
self.sides.get(&symbol).copied().unwrap_or_default()
}
}
/// Classify every use of every name in the module, on both sides of the
/// selection.
pub(super) fn read(
scope: &Scope<'_>,
text: &str,
semantics: &Semantics,
region: &Region<'_>,
) -> Result<Flow, String> {
let mut marks = Marks::default();
marks.items(scope, region, &region.module.items)?;
// Every reference in the file, placed on its side of the boundary and
// given the direction the tree marked its span with.
let mut sides: HashMap<SymbolId, Sides> = HashMap::new();
let mut inside = Vec::new();
for (n, reference) in semantics.references().iter().enumerate() {
let span = reference.name_span;
let within = region.span.start <= span.start && span.end <= region.span.end;
if within {
inside.push(n);
}
let Resolution::Resolved(symbol) = reference.resolution else { continue };
let use_ = marks.use_of(span);
let entry = sides.entry(symbol).or_default();
match (within, use_) {
(true, Use::Read) => entry.inside_read = true,
(true, Use::Write) => entry.inside_write = true,
(true, Use::Unknown) => entry.inside_unknown = true,
(false, Use::Read) => entry.outside_read = true,
(false, Use::Write) => entry.outside_write = true,
(false, Use::Unknown) => entry.outside_unknown = true,
}
}
// A declarator's own initialiser writes the declaration rather than
// referring to it, so it is not in the reference table at all.
for (span, within) in marks.initialised.drain(..) {
let Some(symbol) = semantics.symbol_at(span.start) else { continue };
let entry = sides.entry(symbol).or_default();
match within {
true => entry.inside_write = true,
false => entry.outside_write = true,
}
}
let _ = text;
Ok(Flow { sides, inside })
}
/// Whether any reference inside the region is a **hierarchical** one whose
/// head instance the region does not itself declare — `u_x.sig` reaching out
/// of the selection, which lucisv will not move across a module boundary.
///
/// The §49 surface is what says a tail is hierarchical at all
/// ([`Surface::Hierarchical`] is recorded exactly when the head resolved to an
/// instance); the head is then the nearest reference before it that resolved
/// to an [`SymbolKind::Instance`] with nothing but the dots of the path
/// between them.
pub(super) fn hierarchical_escape(
text: &str,
semantics: &Semantics,
region: &Region<'_>,
) -> Option<String> {
let refs = semantics.references();
for reference in refs {
let span = reference.name_span;
if span.start < region.span.start || region.span.end < span.end {
continue;
}
let Resolution::ExternalCandidate { surface: Surface::Hierarchical, .. } =
&reference.resolution
else {
continue;
};
match head_of(text, semantics, refs, reference) {
// The instance the path starts at moves with the selection, so
// the path is not crossing anything. It is the *declaration* that
// has to move, not the mention of it.
Some(head) if declared_inside(semantics, region, head) => continue,
Some(head) => return Some(format!("{}.{}", head.name, reference.name)),
None => return Some(format!("\u{2026}.{}", reference.name)),
}
}
None
}
/// The instance a hierarchical tail hangs off: the nearest earlier reference
/// that resolved to an instance, with only a dotted path between the two.
fn head_of<'r>(
text: &str,
semantics: &Semantics,
refs: &'r [Reference],
tail: &Reference,
) -> Option<&'r Reference> {
let mut best: Option<&Reference> = None;
for candidate in refs {
if candidate.name_span.end > tail.name_span.start {
continue;
}
let is_instance = candidate
.resolved()
.and_then(|id| semantics.symbol(id))
.is_some_and(|symbol| symbol.kind == SymbolKind::Instance);
if !is_instance {
continue;
}
if best.is_none_or(|found| candidate.name_span.end > found.name_span.end) {
best = Some(candidate);
}
}
let head = best?;
let between = text.get(head.name_span.end as usize..tail.name_span.start as usize)?;
// A dotted path, index selects included: `u_a.u_b`, `u_q[0].sig`.
let dotted = between
.chars()
.all(|c| c == '.' || c == '[' || c == ']' || c == ':' || c.is_alphanumeric() || c == '_');
dotted.then_some(head)
}
fn inside(region: &Region<'_>, span: TextRange) -> bool {
region.span.start <= span.start && span.end <= region.span.end
}
/// Whether the declaration a reference names is written inside the region.
fn declared_inside(semantics: &Semantics, region: &Region<'_>, reference: &Reference) -> bool {
reference
.resolved()
.and_then(|id| semantics.symbol(id))
.is_some_and(|symbol| inside(region, symbol.name_span))
}
// ----------------------------------------------------------------------
// marking the tree
// ----------------------------------------------------------------------
/// Where the tree says a name is written, and where it says lucisv cannot
/// know. Both are sets of *name spans*, which is what lets the reference table
/// be read straight off them.
#[derive(Default)]
struct Marks {
writes: Vec<TextRange>,
unknown: Vec<TextRange>,
/// `(declared name's span, inside the region)` for every declarator whose
/// own initialiser drives it.
initialised: Vec<(TextRange, bool)>,
}
impl Marks {
fn use_of(&self, span: TextRange) -> Use {
if self.unknown.iter().any(|marked| covers(*marked, span)) {
return Use::Unknown;
}
match self.writes.contains(&span) {
true => Use::Write,
false => Use::Read,
}
}
fn items(
&mut self,
scope: &Scope<'_>,
region: &Region<'_>,
items: &[Item],
) -> Result<(), String> {
for item in items {
self.item(scope, region, item)?;
}
Ok(())
}
fn item(&mut self, scope: &Scope<'_>, region: &Region<'_>, item: &Item) -> Result<(), String> {
match &item.kind {
ItemKind::DataDecl(decl) => {
for declarator in &decl.declarators {
if declarator.init.is_some() {
self.initialised
.push((declarator.name_span, inside(region, declarator.name_span)));
}
}
}
ItemKind::ContAssign(assign) => {
for pair in &assign.assigns {
self.write(&pair.lhs);
}
}
ItemKind::Always { stmt, .. } => self.body(stmt),
ItemKind::Initial(stmt) | ItemKind::Final(stmt) => self.body(stmt),
ItemKind::Function(decl) => {
for stmt in &decl.stmts {
self.body(stmt);
}
}
ItemKind::Task(decl) => {
for stmt in &decl.stmts {
self.body(stmt);
}
}
ItemKind::Instantiation(inst) => self.instantiation(scope, region, inst)?,
ItemKind::GateInstantiation(gates) => {
for instance in &gates.instances {
for arg in &instance.args {
self.unknown.push(arg.span);
}
}
}
ItemKind::GenerateRegion { items, .. } => self.items(scope, region, items)?,
ItemKind::GenBlock(block) => self.items(scope, region, &block.items)?,
ItemKind::GenIf(gen_if) => {
self.items(scope, region, &gen_if.then.items)?;
let mut els = gen_if.els.as_deref();
while let Some(branch) = els {
match branch {
vlog_parser::ast::GenElse::If(_, nested) => {
self.items(scope, region, &nested.then.items)?;
els = nested.els.as_deref();
}
vlog_parser::ast::GenElse::Block(block) => {
self.items(scope, region, &block.items)?;
els = None;
}
}
}
}
ItemKind::GenFor(gen_for) => self.items(scope, region, &gen_for.body.items)?,
ItemKind::GenCase(gen_case) => {
for case_item in &gen_case.items {
self.items(scope, region, &case_item.body.items)?;
}
}
_ => {}
}
Ok(())
}
/// Every write inside one procedural block, at any statement depth.
fn body(&mut self, stmt: &Stmt) {
walk(stmt, &mut |stmt| match &stmt.kind {
StmtKind::Assign { lhs, .. } | StmtKind::ForceRelease { lhs, .. } => self.write(lhs),
StmtKind::EventTrigger(expr) => self.write(expr),
StmtKind::For { init, step, .. } => {
for entry in init {
self.write(&entry.assign.lhs);
}
for entry in step {
match entry {
ForStep::Assign(assign) => self.write(&assign.lhs),
ForStep::Expr(expr) => match increment_target(expr) {
Some(target) => self.write(target),
None => self.unknown.push(expr.span),
},
}
}
}
// `x++;` is a write; every other expression statement is a call,
// whose arguments may be `output` arguments.
StmtKind::ExprStmt(expr) => match increment_target(expr) {
Some(target) => self.write(target),
None => self.unknown.push(expr.span),
},
_ => {}
});
// A call written anywhere in the block — in a condition, on the
// right-hand side of an assignment — passes arguments whose direction
// only the routine's own prototype knows.
walk(stmt, &mut |stmt| stmt_exprs(stmt, &mut |expr| self.calls(expr)));
}
/// An instantiation's connections, whose direction the instantiated
/// module's declaration holds.
fn instantiation(
&mut self,
scope: &Scope<'_>,
region: &Region<'_>,
inst: &Instantiation,
) -> Result<(), String> {
let touches = inst.instances.iter().any(|instance| inside(region, instance.name_span));
for instance in &inst.instances {
match &instance.conns {
Connections::Ordered(conns) => {
if touches {
return Err(positional(&inst.module, &instance.name));
}
for conn in conns {
self.unknown.push(match conn {
ListElem::Ok(conn) => conn.span,
ListElem::Error(raw) => raw.span,
});
}
}
Connections::Named(conns) => {
let ports = match touches {
true => Some(ports_of(scope, &inst.module)?),
false => None,
};
for conn in conns {
let conn = match conn {
ListElem::Ok(conn) => conn,
ListElem::Error(raw) => {
if touches {
return Err(unreadable(&inst.module, &instance.name));
}
self.unknown.push(raw.span);
continue;
}
};
let Some(ports) = ports.as_deref() else {
self.unknown.push(conn.span);
continue;
};
if conn.name == "*" {
return Err(wildcard(&inst.module, &instance.name));
}
// `.p` with no expression connects the same-named
// signal, whose own name is not written down here;
// the connection's port name is the signal's name.
let Some(port) = ports.iter().find(|(name, _)| *name == conn.name) else {
return Err(no_such_port(&inst.module, &conn.name));
};
let Some(expr) = &conn.expr else {
return Err(implicit(&inst.module, &instance.name, &conn.name));
};
match port.1.as_str() {
"output" | "inout" => self.write(expr),
"input" => {}
_ => return Err(no_direction(&inst.module, &conn.name)),
}
}
}
}
}
Ok(())
}
/// Every argument of every call in an expression, marked unknown.
fn calls(&mut self, expr: &Expr) {
walk_expr(expr, &mut |expr| {
if let ExprKind::Call { args, .. } = &expr.kind {
for arg in args {
self.unknown.push(arg.span);
}
}
});
}
/// Records every name an assignment's left-hand side writes.
fn write(&mut self, lhs: &Expr) {
lvalue_targets(lhs, &mut self.writes);
}
}
/// Whether `outer` covers `inner` entirely.
fn covers(outer: TextRange, inner: TextRange) -> bool {
outer.start <= inner.start && inner.end <= outer.end
}
/// The names one left-hand side writes. `a.b[3] = x` writes `a`, which is
/// what resolves.
fn lvalue_targets(expr: &Expr, out: &mut Vec<TextRange>) {
match &expr.kind {
ExprKind::Ident(_) => out.push(expr.span),
ExprKind::Paren { inner, .. } => lvalue_targets(inner, out),
ExprKind::Cast { expr, .. } => lvalue_targets(expr, out),
ExprKind::Index { base, .. } | ExprKind::Range { base, .. } => lvalue_targets(base, out),
ExprKind::Member { base, .. } => lvalue_targets(base, out),
ExprKind::Concat(items) | ExprKind::Stream { inner: items, .. } => {
for item in items {
lvalue_targets(&item.expr, out);
}
}
_ => {}
}
}
/// The target of `x++` / `x--` / `++x`, which is a write dressed as an
/// expression.
fn increment_target(expr: &Expr) -> Option<&Expr> {
match &expr.kind {
ExprKind::Postfix { expr, op, .. } | ExprKind::Unary { expr, op, .. }
if op == "++" || op == "--" =>
{
Some(expr)
}
_ => None,
}
}
/// The ports of an instantiated module: name and direction, read from the
/// file the workspace index says declares it.
fn ports_of(scope: &Scope<'_>, module: &str) -> Result<Vec<(String, String)>, String> {
let path =
module_definition(scope.index(), module).map_err(|_| unknown_module(module))?.to_path_buf();
let Some(text) = scope.index_of(&path).and_then(|i| scope.text(i)) else {
return Err(unknown_module(module));
};
let plan = instantiation_plan(module, text, None).map_err(|_| unknown_module(module))?;
Ok(plan.ports.into_iter().map(|port| (port.name, port.dir)).collect())
}
// ----------------------------------------------------------------------
// walks
// ----------------------------------------------------------------------
fn walk(stmt: &Stmt, f: &mut dyn FnMut(&Stmt)) {
f(stmt);
match &stmt.kind {
StmtKind::Block { stmts, .. } | StmtKind::ForkJoin { stmts, .. } => {
for stmt in stmts {
walk(stmt, f);
}
}
StmtKind::If { then, els, .. } => {
walk(then, f);
if let Some(els) = els {
walk(els, f);
}
}
StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => {
for item in items {
walk(&item.stmt, f);
}
}
StmtKind::Labeled { stmt, .. } => walk(stmt, f),
StmtKind::For { body, .. }
| StmtKind::While { body, .. }
| StmtKind::DoWhile { body, .. }
| StmtKind::Repeat { body, .. }
| StmtKind::Forever { body }
| StmtKind::Foreach { body, .. } => walk(body, f),
StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => {
walk(inner, f)
}
StmtKind::Assert { then, els, .. } => {
if let Some(then) = then {
walk(then, f);
}
if let Some(els) = els {
walk(els, f);
}
}
_ => {}
}
}
/// The expressions one statement writes directly — not its children's.
fn stmt_exprs(stmt: &Stmt, f: &mut dyn FnMut(&Expr)) {
match &stmt.kind {
StmtKind::Assign { lhs, rhs, .. } => {
f(lhs);
f(rhs);
}
StmtKind::If { cond, .. } | StmtKind::While { cond, .. } | StmtKind::Wait { cond, .. } => {
f(cond)
}
StmtKind::DoWhile { cond, .. } => f(cond),
StmtKind::Case { expr, items, .. } => {
f(expr);
for item in items {
for label in &item.labels {
f(&label.expr);
}
}
}
StmtKind::Repeat { count, .. } => f(count),
StmtKind::ExprStmt(expr) | StmtKind::EventTrigger(expr) => f(expr),
StmtKind::ForceRelease { lhs, rhs, .. } => {
f(lhs);
if let Some(rhs) = rhs {
f(rhs);
}
}
StmtKind::For { init, cond, step, .. } => {
for entry in init {
f(&entry.assign.rhs);
}
if let Some(cond) = cond {
f(cond);
}
for entry in step {
match entry {
ForStep::Assign(assign) => f(&assign.rhs),
ForStep::Expr(expr) => f(expr),
}
}
}
StmtKind::Return { expr: Some(expr), .. } => f(expr),
StmtKind::Assert { cond, .. } => f(cond),
_ => {}
}
}
fn walk_expr(expr: &Expr, f: &mut dyn FnMut(&Expr)) {
f(expr);
match &expr.kind {
ExprKind::Unary { expr, .. } | ExprKind::Postfix { expr, .. } => walk_expr(expr, f),
ExprKind::Binary { lhs, rhs, .. } => {
walk_expr(lhs, f);
walk_expr(rhs, f);
}
ExprKind::Ternary { cond, then, els, .. } => {
walk_expr(cond, f);
walk_expr(then, f);
walk_expr(els, f);
}
ExprKind::Call { callee, args, .. } => {
walk_expr(callee, f);
for arg in args {
walk_expr(&arg.expr, f);
}
}
ExprKind::Index { base, index, .. } => {
walk_expr(base, f);
walk_expr(index, f);
}
ExprKind::Range { base, msb, lsb, .. } => {
walk_expr(base, f);
walk_expr(msb, f);
walk_expr(lsb, f);
}
ExprKind::Member { base, .. } | ExprKind::Scope { base, .. } => walk_expr(base, f),
ExprKind::Concat(items) | ExprKind::Stream { inner: items, .. } => {
for item in items {
walk_expr(&item.expr, f);
}
}
ExprKind::Repl { count, inner, .. } => {
walk_expr(count, f);
for item in inner {
walk_expr(&item.expr, f);
}
}
ExprKind::Paren { inner, .. } => walk_expr(inner, f),
ExprKind::Cast { expr, .. } => walk_expr(expr, f),
ExprKind::New(inner) => walk_expr(inner, f),
_ => {}
}
}
// ----------------------------------------------------------------------
// sentences
// ----------------------------------------------------------------------
fn positional(module: &str, instance: &str) -> String {
format!(
"`{instance}` connects `{module}` by position, so lucisv cannot tell which of its connections are outputs; convert it to named connections first."
)
}
fn wildcard(module: &str, instance: &str) -> String {
format!(
"`{instance}` connects `{module}` with `.*`, which names no signals; expand the `.*` first (lucisv offers that as its own refactoring)."
)
}
fn implicit(module: &str, instance: &str, port: &str) -> String {
format!(
"`{instance}` connects `{module}`'s `{port}` implicitly (`.{port}`), which names no expression for lucisv to move; write the signal out first."
)
}
fn unreadable(module: &str, instance: &str) -> String {
format!(
"lucisv could not read one of `{instance}`'s connections to `{module}`, so it cannot tell what the selection drives."
)
}
fn unknown_module(module: &str) -> String {
format!(
"the selection instantiates `{module}`, and lucisv has no single indexed declaration of it, so it cannot tell which of its connections are outputs."
)
}
fn no_such_port(module: &str, port: &str) -> String {
format!(
"the selection connects `.{port}`, which `{module}`'s declaration does not name, so lucisv cannot tell whether it is driven."
)
}
fn no_direction(module: &str, port: &str) -> String {
format!(
"`{module}` declares `{port}` without a direction, so lucisv cannot tell whether the selection drives it."
)
}