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 <[email protected]>
218 lines
8.7 KiB
Rust
218 lines
8.7 KiB
Rust
//! 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<Binding>,
|
|
/// 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<Result<Site<'t>, 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<Site<'t>, 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<Vec<Binding>, 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<Vec<(String, String)>, 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<Value, String> {
|
|
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.";
|