//! What `S` is made of, and the shapes of `S` lucisv will not copy into //! another module. //! //! An inline copies `S`'s body into `M` and substitutes names into it, so the //! refusals here are all one question asked of different constructs: *would //! this piece still mean the same thing written inside `M`?* A `generate` //! block's names are reachable through the hierarchy, an `initial` block's //! meaning depends on when it runs, a macro's body is text lucisv never read, //! and an `inout` port is a name whose direction the substitution cannot //! honour. Each is a sentence rather than a guess. use vlog_parser::ast::{ AnsiPort, Connections, Item, ItemKind, ListElem, Module, ParamPort, PortList, SourceFile, }; use vlog_parser::span::TextRange; use vlog_semantic::WorkspaceIndex; /// One port of `S`, in declaration order. pub(super) struct Port { pub(super) name: String, /// `input`, `output`, or empty when the header writes none. pub(super) dir: String, } /// One entry of `S`'s parameter port list, in declaration order. pub(super) struct Param { pub(super) name: String, /// Whatever the declaration writes between its keyword and its name /// (`int`, `type`, `logic [3:0]`), inherited from the entry before it when /// this one writes none. A span rather than text: the type may name /// another parameter, and every name inside it is substituted the way the /// body's are. pub(super) ty: TextRange, /// The default value as the header writes it; empty when it writes none. pub(super) default: TextRange, /// True for a header `localparam`, which an instantiation may not /// override. pub(super) local: bool, } /// `S`, read. pub(super) struct Source { pub(super) ports: Vec, pub(super) params: Vec, /// The bytes the inline copies: `S`'s items and the comments written /// among them. Empty for a module with an empty body. pub(super) body: TextRange, /// The package paths `S`'s header imports (`p::*`, `p::word_t`), one per /// path rather than one per statement — a header may write several paths /// in one `import`, and `M` may already have some of them. pub(super) imports: Vec, /// Every `.name` shorthand `S`'s own body writes in an instantiation of /// its own — `.clk_i` standing for `.clk_i(clk_i)` — as the name and the /// bytes it occupies. The shorthand names a signal *and* a port with one /// token, so an inline that renames the signal has to spell it out; see /// [`shorthands`]. pub(super) shorthands: Vec<(String, TextRange)>, } impl Source { /// Read `S` out of its own file, or say why lucisv will not inline it. pub(super) fn read( tree: &SourceFile, text: &str, index: &WorkspaceIndex, name: &str, ) -> Result { let Some(module) = declaration(tree, name) else { return Err(format!( "the file that declared `{name}` no longer declares it, so lucisv cannot inline it." )); }; if module.kw != "module" && module.kw != "macromodule" { return Err(format!( "`{name}` is an `{}`, whose signals are its surface rather than a body lucisv can copy; no edits were made.", module.kw )); } for item in &module.items { copyable(item, name)?; } Ok(Source { ports: ports(module, index, name)?, params: params(module, text), body: body(module), imports: imports(module), shorthands: shorthands(module, name)?, }) } } /// The declaration of `name` in its own file. fn declaration<'t>(tree: &'t SourceFile, name: &str) -> Option<&'t Module> { tree.items.iter().find_map(|item| match &item.kind { ItemKind::Module(module) if module.name == name => Some(module), _ => None, }) } /// The item kinds lucisv will not copy into another module's body. fn copyable(item: &Item, name: &str) -> Result<(), String> { let what = match &item.kind { ItemKind::Initial(_) => "an `initial` block", ItemKind::Final(_) => "a `final` block", ItemKind::MacroItem(_) => { return Err(format!( "`{name}` invokes a macro as one of its items, and lucisv does not expand macros, so it cannot tell what it would be copying." )) } ItemKind::Directive(_) => { return Err(format!( "`{name}` writes a compiler directive among its items, and lucisv does not evaluate one, so it cannot tell what its body really is." )) } ItemKind::GenerateRegion { .. } | ItemKind::GenIf(_) | ItemKind::GenFor(_) | ItemKind::GenCase(_) | ItemKind::GenBlock(_) => { return Err(format!( "`{name}` uses a `generate` construct, whose block names are reachable through the hierarchy (`u_{name}.gen.x`) and would become names of `M`'s own; lucisv will not inline it." )) } ItemKind::Bind(_) => "a `bind` directive", ItemKind::Module(_) | ItemKind::Package { .. } => "a declaration of its own", ItemKind::Error(_) => { return Err(format!("part of `{name}` did not parse, so lucisv will not copy it.")) } _ => return Ok(()), }; Err(format!( "`{name}` holds {what}, which does not mean the same thing written inside another module; lucisv made no edits." )) } /// `S`'s ports, in declaration order, or the sentence for a port whose name /// lucisv cannot simply replace with the one connected to it. fn ports(module: &Module, index: &WorkspaceIndex, name: &str) -> Result, String> { let declared = match &module.ports { PortList::Ansi(declared) => declared, PortList::NonAnsi(_) => return Err(non_ansi(name)), PortList::Empty | PortList::None => return Ok(Vec::new()), }; if !module.port_directives.is_empty() { return Err(format!( "`{name}`'s port list carries compiler directives, so which ports it really declares depends on the configuration; lucisv made no edits." )); } let mut out: Vec = Vec::new(); let mut dir = String::new(); for port in declared.iter().filter_map(ListElem::ok) { if let Some(written) = &port.dir { dir = written.clone(); } if port.name.is_empty() { continue; } connectable(port, index, name, &dir)?; out.push(Port { name: port.name.clone(), dir: dir.clone() }); } Ok(out) } /// The three port shapes an inline refuses: an `inout`, an unpacked array, and /// an interface. fn connectable( port: &AnsiPort, index: &WorkspaceIndex, name: &str, dir: &str, ) -> Result<(), String> { if dir == "inout" { return Err(format!( "`{name}`'s port `{}` is an `inout`, whose two directions lucisv cannot reproduce by substituting a name; no edits were made.", port.name )); } if !port.unpacked.is_empty() { return Err(format!( "`{name}`'s port `{}` has an unpacked dimension, and a port array is not one name lucisv can substitute; no edits were made.", port.name )); } // An interface port writes no direction and names an interface — or a // modport of one, which is a name with a `.` in it and never a data type. let written = port.ty.name.trim(); let head = written.split('.').next().unwrap_or(""); let interface = written.contains('.') || index.units(head).iter().any(|def| def.kind == vlog_semantic::SymbolKind::Interface); match interface && dir.is_empty() { true => Err(format!( "`{name}`'s port `{}` is of interface type `{written}`, whose signals are named through the port rather than substituted for it; lucisv made no edits.", port.name )), false => Ok(()), } } /// `S`'s parameter port list, in declaration order. A continuation entry /// (`#(parameter int A = 1, B = 2)`) inherits the keyword *and* the type of /// the entry before it, which is what the language says and what the /// `localparam` written in its place has to say too. fn params(module: &Module, text: &str) -> Vec { let Some(declared) = &module.param_ports else { return Vec::new() }; let mut out = Vec::new(); let (mut kw, mut ty) = (String::new(), TextRange::empty(0)); for param in declared.iter().filter_map(ListElem::ok) { if let Some(written) = ¶m.kw { kw = written.clone(); ty = type_span(text, param); } if param.name.is_empty() { continue; } out.push(Param { name: param.name.clone(), ty, default: param.default.as_ref().map_or_else(|| TextRange::empty(0), |e| e.span), local: kw == "localparam", }); } out } /// The bytes one parameter writes between its keyword and its name. fn type_span(text: &str, param: &ParamPort) -> TextRange { let head = TextRange::new(param.span.start, param.name_span.start); let written = slice(text, head); let keyword = ["parameter", "localparam"] .iter() .find_map(|kw| written.find(kw).map(|at| at + kw.len())) .unwrap_or(0); TextRange::new(head.start + keyword as u32, head.end) } /// The bytes an inline copies: from the first thing written in `S`'s body — an /// item, its leading comment or its attribute — to the last. fn body(module: &Module) -> TextRange { let mut span: Option = None; let mut widen = |extent: TextRange| { span = Some(match span { None => extent, Some(so_far) => { TextRange::new(so_far.start.min(extent.start), so_far.end.max(extent.end)) } }); }; for item in &module.items { widen(extent(item)); } for comment in &module.dangling { widen(comment.span); } span.unwrap_or_else(|| TextRange::empty(0)) } /// The bytes one item owns: itself, its attributes and its own comments. fn extent(item: &Item) -> TextRange { let mut out = item.span; let comments = item .meta .leading .iter() .chain(&item.meta.before_sep) .chain(&item.meta.trailing) .map(|c| c.span) .chain(item.meta.attrs.iter().map(|a| a.span)); for span in comments { out = TextRange::new(out.start.min(span.start), out.end.max(span.end)); } out } /// Every `.name` shorthand `S`'s body writes in an instantiation of its own, /// and the refusal for the `.*` that cannot be spelled out one name at a time. /// /// This is the one place a name is written **once** and read **twice**: /// `.clk_i` names a port of the module being instantiated and, at the same /// token, the signal connected to it. Substituting a new signal name over it /// would silently reconnect a different port, and leaving it alone would bind /// a name `M` may not even declare — the trial's `counter` inside `cb_filter` /// is that bug caught (work log, 2026-09-06). So the shorthand is *expanded* /// (`.clk_i(clk)`) wherever the signal it names is one the inline renames, and /// a `.*`, which names every signal at once, is refused. fn shorthands(module: &Module, name: &str) -> Result, String> { let mut out = Vec::new(); for item in &module.items { let ItemKind::Instantiation(inst) = &item.kind else { continue }; let params = inst.params.iter().flatten(); let conns = inst.instances.iter().flat_map(|instance| match &instance.conns { Connections::Named(list) => list.as_slice(), Connections::Ordered(_) => &[], }); for conn in params.chain(conns).filter_map(ListElem::ok) { if conn.name == "*" { return Err(format!( "`{name}`'s body connects `{}`'s ports with `.*`, and inlining renames the signals those ports bind to; expand `.*` in `{name}` first (lucisv: expand `.*`).", inst.module )); } if conn.expr.is_none() && !conn.name.is_empty() { out.push((conn.name.clone(), conn.name_span)); } } } Ok(out) } /// The package paths `S`'s header imports, one entry per path. fn imports(module: &Module) -> Vec { module.imports.iter().flat_map(|import| import.paths.iter().map(|path| path.text())).collect() } fn slice(text: &str, span: TextRange) -> &str { text.get(span.start as usize..span.end as usize).unwrap_or("") } fn non_ansi(name: &str) -> String { format!( "`{name}` declares its ports in the Verilog-2001 style, with the directions written in its body; convert them to ANSI ports first (lucisv: convert to ANSI ports)." ) }