//! Writing the new module, and the instantiation that stands where its items //! used to be. //! //! Two rules govern everything here. A **port's type is the declaration's own //! text**, reassembled from the tree in the order `vlog_formatter`'s ANSI port //! printer writes it (direction, net, type, signing, packed dimensions, name), //! so what lucisv writes is what the formatter would; anything the tree says is //! not a plain name-signing-dimensions type — an anonymous aggregate, a //! parameterized reference, a virtual interface, an unpacked dimension — is //! refused rather than approximated. And the **instantiation is rendered from //! the new module's own text**, through //! [`instantiation_plan`](crate::instantiate::instantiation_plan), so the two //! halves of the edit cannot disagree about what `N`'s ports are. use vlog_parser::ast::{ AnsiPort, DataDecl, DataType, Declarator, Dim, ItemKind, ListElem, Module, ParamDecl, ParamPort, PortDecl, PortList, }; use vlog_parser::span::TextRange; use crate::instantiate::{instantiation_plan, Layout}; /// Where a name that crosses the boundary is declared in the module. pub(super) enum Site<'t> { /// An ANSI port of the header. Ansi(&'t AnsiPort), /// A name-only header port, with the body declarations that describe it. NonAnsi(&'t PortDecl, &'t Declarator, Option<(&'t DataDecl, &'t Declarator)>), /// A net or variable declared in the body. Data(&'t DataDecl, &'t Declarator), /// A parameter or localparam declared in the body. Param(&'t ParamDecl, &'t Declarator), /// A parameter declared in the header's `#( ... )`. ParamPort(&'t ParamPort), } /// Every declaration of the module that a crossing name could name. pub(super) fn site_of<'t>(module: &'t Module, name: &str) -> Option> { if let PortList::Ansi(ports) = &module.ports { if let Some(port) = ports.iter().filter_map(ListElem::ok).find(|p| p.name == name) { return Some(Site::Ansi(port)); } } if let Some(params) = &module.param_ports { if let Some(param) = params.iter().filter_map(ListElem::ok).find(|p| p.name == name) { return Some(Site::ParamPort(param)); } } let mut port: Option<(&PortDecl, &Declarator)> = None; let mut data: Option<(&DataDecl, &Declarator)> = None; for item in &module.items { match &item.kind { ItemKind::PortDecl(decl) => { if let Some(d) = decl.declarators.iter().find(|d| d.name == name) { port = Some((decl, d)); } } ItemKind::DataDecl(decl) => { if let Some(d) = decl.declarators.iter().find(|d| d.name == name) { data = Some((decl, d)); } } ItemKind::ParamDecl(decl) => { if let Some(d) = decl.declarators.iter().find(|d| d.name == name) { return Some(Site::Param(decl, d)); } } _ => {} } } match (port, data) { (Some((decl, declarator)), other) => Some(Site::NonAnsi(decl, declarator, other)), (None, Some((decl, declarator))) => Some(Site::Data(decl, declarator)), (None, None) => None, } } /// One port of the new module, ready to be written. pub(super) struct Port { pub(super) name: String, /// `input logic [7:0] `, the name's own text excluded. pub(super) prefix: String, /// Every identifier that prefix spells — the direction and the type /// keywords among them. A port whose width is `[N-1:0]` names `N`, and /// `N` has to cross the boundary with it or the new module names nothing. pub(super) names: Vec, } /// One parameter of the new module. pub(super) struct Param { pub(super) name: String, /// `parameter int `, the name's own text excluded. pub(super) prefix: String, /// The default as `M` writes it, or an empty string when it writes none. pub(super) default: String, /// Every identifier its type and its default name, for the closure that /// carries the parameters one parameter depends on across with it. pub(super) names: Vec, } /// The declaration of a crossing signal, written as an ANSI port of the new /// module. pub(super) fn port( text: &str, module: &str, name: &str, site: &Site<'_>, dir: &str, ) -> Result { let (net, ty, unpacked) = match site { Site::Ansi(port) => (port.net.as_deref(), &port.ty, port.unpacked.as_slice()), Site::NonAnsi(decl, declarator, var) => { let (net, ty) = match var { Some((data, _)) if decl.net.is_none() && decl.ty.name.is_empty() => { (data.net.as_deref().or(decl.net.as_deref()), &data.ty) } _ => (decl.net.as_deref(), &decl.ty), }; if let Some((data, other)) = var { if !data.qualifiers.is_empty() { return Err(qualified(module, name)); } if !other.unpacked.is_empty() { return Err(unpacked_refusal(module, name)); } } (net, ty, declarator.unpacked.as_slice()) } Site::Data(decl, declarator) => { if !decl.qualifiers.is_empty() { return Err(qualified(module, name)); } if decl.delay.is_some() { return Err(delayed(module, name)); } (decl.net.as_deref(), &decl.ty, declarator.unpacked.as_slice()) } Site::Param(..) | Site::ParamPort(_) => return Err(lost(name)), }; if !unpacked.is_empty() { return Err(unpacked_refusal(module, name)); } let ty = type_text(text, module, name, ty)?; let mut prefix = String::new(); let mut word = |part: &str| { prefix.push_str(part); prefix.push(' '); }; word(dir); if let Some(net) = net { word(net); } if !ty.is_empty() { word(&ty); } let names = words(&prefix); Ok(Port { name: name.to_string(), prefix, names }) } /// The declaration of a crossing parameter, written as a parameter of the new /// module. pub(super) fn param( text: &str, module: &str, name: &str, site: &Site<'_>, ) -> Result { let (is_type, ty, default) = match site { Site::Param(decl, declarator) => { (decl.is_type, &decl.ty, declarator.init.as_ref().map(|e| e.span)) } Site::ParamPort(param) => { (param.is_type, ¶m.ty, param.default.as_ref().map(|e| e.span)) } _ => return Err(lost(name)), }; if is_type { return Err(format!( "`{module}`'s `{name}` is a type parameter, and lucisv does not carry one into a new module this round." )); } let ty = type_text(text, module, name, ty)?; let mut prefix = String::from("parameter "); if !ty.is_empty() { prefix.push_str(&ty); prefix.push(' '); } let default = default.map(|span| slice(text, span).trim().to_string()).unwrap_or_default(); if default.contains('\n') { return Err(format!( "`{module}` writes `{name}`'s default across several lines, and lucisv does not re-flow one into a new module's header." )); } let mut names = words(&prefix); names.extend(words(&default)); Ok(Param { name: name.to_string(), prefix, default, names }) } /// Everything a declaration writes between the direction and the name, as the /// source spells it: `logic [7:0]`, `my_pkg::word_t`, `signed [31:0]`. fn type_text(text: &str, module: &str, name: &str, ty: &DataType) -> Result { if ty.virt.is_some() || ty.extra.is_some() { return Err(format!( "`{module}` declares `{name}` with a type lucisv does not move into a port list (an anonymous aggregate, a parameterized reference or a virtual interface)." )); } let mut out = String::new(); for part in [ty.name.as_str(), ty.signing.as_deref().unwrap_or("")] { if part.is_empty() { continue; } if !out.is_empty() { out.push(' '); } out.push_str(part); } let packed = dims(text, &ty.packed); if !packed.is_empty() { if !out.is_empty() { out.push(' '); } out.push_str(&packed); } Ok(out) } fn dims(text: &str, list: &[Dim]) -> String { list.iter().map(|dim| slice(text, dim.span)).collect() } fn slice(text: &str, span: TextRange) -> &str { text.get(span.start as usize..span.end as usize).unwrap_or("") } /// Every whole word of an expression's text — what a parameter default may /// depend on. fn words(text: &str) -> Vec { let mut out: Vec = Vec::new(); let bytes = text.as_bytes(); let mut i = 0usize; while i < bytes.len() { if !is_word_byte(bytes[i]) { i += 1; continue; } let start = i; while i < bytes.len() && is_word_byte(bytes[i]) { i += 1; } let leading_digit = bytes[start].is_ascii_digit(); let after_tick = start > 0 && bytes[start - 1] == b'\''; if !leading_digit && !after_tick { if let Some(word) = text.get(start..i) { out.push(word.to_string()); } } } out } fn is_word_byte(byte: u8) -> bool { byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$' } // ---------------------------------------------------------------------- // the two texts // ---------------------------------------------------------------------- /// The whole new module: header, the imports it needs, and the selection's own /// bytes, verbatim. /// /// Verbatim is the point. The items are module items in `M` and module items /// in `N`, at the same nesting depth, so the source's own indentation is /// already right — and every comment, every attribute and every string travels /// byte for byte, which is what lets the splice verifier count them. pub(super) fn new_module( name: &str, imports: &[String], params: &[Param], ports: &[Port], body: &str, ) -> String { let mut out = format!("module {name}"); for path in imports { out.push_str("\n import "); out.push_str(path); out.push(';'); } // A header import is written on its own line, which is where the formatter // puts one; the list after it then starts a line of its own rather than // continuing with a space. let sep = match imports.is_empty() { true => " ", false => "\n", }; if !params.is_empty() { out.push_str(sep); out.push_str("#(\n"); for (i, param) in params.iter().enumerate() { out.push_str(" "); out.push_str(¶m.prefix); out.push_str(¶m.name); if !param.default.is_empty() { out.push_str(" = "); out.push_str(¶m.default); } out.push_str(if i + 1 < params.len() { ",\n" } else { "\n" }); } out.push(')'); } let sep = match params.is_empty() { true => sep, false => " ", }; match ports.is_empty() { true => { out.push_str(sep); out.push_str("();\n"); } false => { out.push_str(sep); out.push_str("(\n"); for (i, port) in ports.iter().enumerate() { out.push_str(" "); out.push_str(&port.prefix); out.push_str(&port.name); out.push_str(if i + 1 < ports.len() { ",\n" } else { "\n" }); } out.push_str(");\n"); } } out.push_str(body); if !body.ends_with('\n') { out.push('\n'); } out.push_str("endmodule\n"); out } /// The instantiation that replaces the selection, read back out of the new /// module's own text. /// /// Every port connects to the signal of the same name — which is what the /// extraction just made true — and every parameter to the parameter of the /// same name. pub(super) fn instantiation(name: &str, module_text: &str, indent: &str) -> Result { let mut plan = instantiation_plan(name, module_text, None)?; for port in &mut plan.ports { port.auto_connect = true; } let params = plan.params.len(); let names: Vec = plan.params.iter().map(|param| param.name.clone()).collect(); let layout = Layout { base: indent.to_string(), step: " ".to_string() }; Ok(plan.render_with(&layout, &mut |n, default| match n <= params { true => names.get(n - 1).cloned().unwrap_or_default(), false => default.to_string(), })) } // ---------------------------------------------------------------------- // sentences // ---------------------------------------------------------------------- fn unpacked_refusal(module: &str, name: &str) -> String { format!( "`{name}` crosses the selection's boundary and `{module}` declares it with an unpacked dimension; lucisv does not turn one into a port this round." ) } fn qualified(module: &str, name: &str) -> String { format!( "`{module}` declares `{name}` with a qualifier (`var`, `const`, `automatic`), and lucisv does not move a qualifier into a port list." ) } fn delayed(module: &str, name: &str) -> String { format!( "`{module}` declares `{name}` with a net delay, and lucisv does not move a delay into a port list." ) } fn lost(name: &str) -> String { format!("lucisv lost track of the declaration of `{name}`, so it made no edits.") }