// Author: Guoliang Chen, a Senior Digital Design Engineer //! Inlining a module: the substitution, the prefixing rule, the refusals and //! the round trip with `extract_module`. See //! `docs/features/extract-inline-module/README.md`. use std::path::{Path, PathBuf}; use vlog_refactor::{inline_module, inline_site, inline_title, RefactorEdit, TextEdit}; const M: &str = "/rtl/top.sv"; const S: &str = "/rtl/sub.sv"; /// A two-port module, and a `top` that instantiates it. const SUB: &str = "\ module sub ( input logic a, input logic b, output logic q ); logic s; // the and assign s = a & b; assign q = s; endmodule "; const TOP: &str = "\ module top ( input logic x, input logic y, output logic z ); sub u_sub ( .a(x), .b(y), .q(z) ); endmodule "; fn files(top: &str, sub: &str) -> Vec<(PathBuf, String)> { vec![(PathBuf::from(M), top.to_string()), (PathBuf::from(S), sub.to_string())] } /// Inline the instantiation `top` writes, and return the edited `top`. fn inlined(top: &str, sub: &str) -> Result { let at = top.find("sub u_sub").expect("the instantiation") as u32 + 2; let edit = inline_module(&files(top, sub), Path::new(M), at)?; Ok(applied(top, &edit)) } fn applied(text: &str, edit: &RefactorEdit) -> String { let mut out = text.to_string(); for TextEdit { range, new_text } in edit.edits_for(&PathBuf::from(M)).iter().rev() { out.replace_range(range.start as usize..range.end as usize, new_text); } out } fn refusal(top: &str, sub: &str) -> String { inlined(top, sub).expect_err("a refusal") } // ---------------------------------------------------------------------- // the substitution // ---------------------------------------------------------------------- #[test] fn a_two_port_module_is_inlined_with_its_ports_replaced_by_the_connected_names() { let out = inlined(TOP, SUB).expect("inlines"); assert!(out.contains(" logic s; // the and\n"), "{out}"); assert!(out.contains("assign s = x & y;"), "{out}"); assert!(out.contains("assign z = s;"), "{out}"); assert!(!out.contains("sub u_sub"), "the instantiation is gone: {out}"); assert_eq!(out.matches("// the and").count(), 1, "the comment travels once: {out}"); } #[test] fn the_edit_touches_only_the_file_the_cursor_is_in() { let at = TOP.find("sub u_sub").expect("the instantiation") as u32 + 2; let edit = inline_module(&files(TOP, SUB), Path::new(M), at).expect("inlines"); assert_eq!(edit.file_count(), 1, "`sub.sv` is copied out of, never written to"); assert_eq!(edit.edit_count(), 1, "one replacement"); assert!(edit.created.is_empty()); assert!( edit.warnings.iter().any(|w| w.contains("still declared where it was")), "{:?}", edit.warnings ); } #[test] fn a_literal_may_be_connected_to_an_input() { let top = TOP.replace(".b(y)", ".b(1'b1)"); let out = inlined(&top, SUB).expect("inlines"); assert!(out.contains("assign s = x & 1'b1;"), "{out}"); } #[test] fn the_implicit_dot_name_connection_is_read_as_the_name_it_stands_for() { let top = "\ module top ( input logic a, input logic b, output logic q ); sub u_sub (.a, .b, .q); endmodule "; let out = inlined(top, SUB).expect("inlines"); assert!(out.contains("assign s = a & b;"), "{out}"); assert!(out.contains("assign q = s;"), "{out}"); } #[test] fn a_comment_written_inside_the_instantiation_is_written_back_above_the_body() { let top = TOP.replace(".a(x),", ".a(x), // the first"); let out = inlined(&top, SUB).expect("inlines"); assert_eq!(out.matches("// the first").count(), 1, "{out}"); assert!(out.contains("// the first\n"), "{out}"); } // ---------------------------------------------------------------------- // parameters // ---------------------------------------------------------------------- const WIDE: &str = "\ module wide #( parameter int W = 4 ) ( input logic [W-1:0] a, output logic [W-1:0] q ); logic [W-1:0] t; assign t = a; assign q = t; endmodule "; const USES_WIDE: &str = "\ module top ( input logic [7:0] x, output logic [7:0] z ); wide #(.W(8)) u_wide ( .a(x), .q(z) ); endmodule "; fn wide_files() -> Vec<(PathBuf, String)> { vec![ (PathBuf::from(M), USES_WIDE.to_string()), (PathBuf::from("/rtl/wide.sv"), WIDE.to_string()), ] } #[test] fn a_parameter_becomes_a_localparam_holding_the_override() { let at = USES_WIDE.find("wide #(").expect("the instantiation") as u32 + 1; let edit = inline_module(&wide_files(), Path::new(M), at).expect("inlines"); let out = applied(USES_WIDE, &edit); assert!(out.contains("localparam int W = 8;"), "{out}"); assert!(out.contains("logic [W-1:0] t;"), "{out}"); assert!(!out.contains("u_wide"), "{out}"); } #[test] fn a_parameter_with_no_override_keeps_its_default() { let top = USES_WIDE.replace("wide #(.W(8)) u_wide", "wide u_wide"); let files = vec![(PathBuf::from(M), top.clone()), (PathBuf::from("/rtl/wide.sv"), WIDE.to_string())]; let at = top.find("wide u_wide").expect("the instantiation") as u32 + 1; let out = applied(&top, &inline_module(&files, Path::new(M), at).expect("inlines")); assert!(out.contains("localparam int W = 4;"), "{out}"); } // ---------------------------------------------------------------------- // prefixing // ---------------------------------------------------------------------- #[test] fn a_name_collision_prefixes_every_name_the_module_declares() { // `top` declares an `s` of its own, so `sub`'s `s` becomes `u_sub_s`. let top = TOP.replace(" sub u_sub (", " logic s;\n sub u_sub ("); let edit = { let at = top.find("sub u_sub").expect("the instantiation") as u32 + 2; inline_module(&files(&top, SUB), Path::new(M), at).expect("inlines") }; let out = applied(&top, &edit); assert!(out.contains("logic u_sub_s; // the and"), "{out}"); assert!(out.contains("assign u_sub_s = x & y;"), "{out}"); assert!(out.contains("assign z = u_sub_s;"), "{out}"); assert!( edit.warnings.iter().any(|w| w.contains("`s`") && w.contains("u_sub_")), "the warning says which name collided: {:?}", edit.warnings ); } #[test] fn no_collision_means_no_prefix_and_the_warning_says_so() { let at = TOP.find("sub u_sub").expect("the instantiation") as u32 + 2; let edit = inline_module(&files(TOP, SUB), Path::new(M), at).expect("inlines"); assert!(edit.warnings.iter().any(|w| w.contains("under its own names")), "{:?}", edit.warnings); } // ---------------------------------------------------------------------- // imports // ---------------------------------------------------------------------- #[test] fn an_import_the_instantiator_lacks_is_copied_in() { let pkg = "package p; typedef logic word_t; endpackage\n"; let sub = "\ module sub import p::*; ( input logic a, output logic q ); word_t s; assign s = a; assign q = s; endmodule "; let top = "\ module top ( input logic x, output logic z ); sub u_sub (.a(x), .q(z)); endmodule "; let files = vec![ (PathBuf::from(M), top.to_string()), (PathBuf::from(S), sub.to_string()), (PathBuf::from("/rtl/p.sv"), pkg.to_string()), ]; let at = top.find("sub u_sub").expect("the instantiation") as u32 + 2; let edit = inline_module(&files, Path::new(M), at).expect("inlines"); let out = applied(top, &edit); assert!(out.contains("import p::*;"), "{out}"); assert!(edit.warnings.iter().any(|w| w.contains("import p::*;")), "{:?}", edit.warnings); } // ---------------------------------------------------------------------- // the refusals // ---------------------------------------------------------------------- #[test] fn an_expression_connection_is_refused() { let message = refusal(&TOP.replace(".a(x)", ".a(x & y)"), SUB); assert!(message.contains("connect `.a(x & y)` to a named wire first"), "{message}"); } #[test] fn a_wildcard_connection_is_refused() { let top = TOP.replace(".a(x),\n .b(y),\n .q(z)", ".*"); let message = refusal(&top, SUB); assert!(message.contains("expand `.*` first"), "{message}"); } #[test] fn positional_connections_are_refused() { let top = TOP.replace(".a(x),\n .b(y),\n .q(z)", "x,\n y,\n z"); let message = refusal(&top, SUB); assert!(message.contains("convert to named connections first"), "{message}"); } #[test] fn an_unconnected_input_is_refused() { let message = refusal(&TOP.replace(".b(y)", ".b()"), SUB); assert!(message.contains("`.b` is left unconnected"), "{message}"); } #[test] fn an_output_connected_to_a_literal_is_refused() { let message = refusal(&TOP.replace(".q(z)", ".q(1'b0)"), SUB); assert!(message.contains("drives `sub`'s output into a literal"), "{message}"); } #[test] fn a_hierarchical_reference_to_the_instance_is_refused_and_names_the_file() { let top = TOP.replace("endmodule", " assign z = u_sub.s;\nendmodule"); let message = refusal(&top, SUB); assert!(message.contains("named as a scope of the design hierarchy in top.sv"), "{message}"); } #[test] fn a_hierarchical_reference_from_another_file_is_refused_and_names_that_file() { let tb = "module tb;\n top u_top ();\n initial $display(u_top.u_sub.s);\nendmodule\n"; let mut files = files(TOP, SUB); files.push((PathBuf::from("/rtl/tb.sv"), tb.to_string())); let at = TOP.find("sub u_sub").expect("the instantiation") as u32 + 2; let message = inline_module(&files, Path::new(M), at).expect_err("a refusal"); assert!(message.contains("tb.sv"), "{message}"); } #[test] fn a_bind_naming_the_instance_is_refused() { let top = TOP.replace("endmodule", " bind u_sub sub u_check (.a(x), .b(y), .q(z));\nendmodule"); let message = refusal(&top, SUB); assert!(message.contains("named as a scope of the design hierarchy"), "{message}"); } #[test] fn a_generate_in_the_module_is_refused() { let sub = SUB.replace( " assign q = s;", " generate\n if (1) begin : g\n assign q = s;\n end\n endgenerate", ); let message = refusal(TOP, &sub); assert!(message.contains("`generate`"), "{message}"); } #[test] fn an_initial_block_in_the_module_is_refused() { let sub = SUB.replace(" assign q = s;", " assign q = s;\n initial $display(\"hi\");"); let message = refusal(TOP, &sub); assert!(message.contains("`initial` block"), "{message}"); } #[test] fn a_macro_item_in_the_module_is_refused() { let sub = SUB.replace(" assign q = s;", " assign q = s;\n `ASSERT(a, b)"); let message = refusal(TOP, &sub); assert!(message.contains("macro"), "{message}"); } #[test] fn a_conditional_directive_in_the_module_is_refused() { let sub = SUB.replace(" assign q = s;", "`ifdef X\n assign q = s;\n`endif"); let message = refusal(TOP, &sub); assert!(message.contains("compiler directive"), "{message}"); } #[test] fn an_inout_port_is_refused() { let sub = SUB.replace(" input logic b,", " inout logic b,"); let message = refusal(TOP, &sub); assert!(message.contains("is an `inout`"), "{message}"); } #[test] fn an_unpacked_array_port_is_refused() { let sub = SUB.replace(" input logic b,", " input logic b [2],"); let message = refusal(TOP, &sub); assert!(message.contains("unpacked dimension"), "{message}"); } #[test] fn an_interface_port_is_refused() { let iface = "interface bus_if;\n logic v;\nendinterface\n"; let sub = "\ module sub ( bus_if m, output logic q ); assign q = 1'b0; endmodule "; let top = "module top (output logic z);\n sub u_sub (.m(bus), .q(z));\nendmodule\n"; let files = vec![ (PathBuf::from(M), top.to_string()), (PathBuf::from(S), sub.to_string()), (PathBuf::from("/rtl/bus_if.sv"), iface.to_string()), ]; let at = top.find("sub u_sub").expect("the instantiation") as u32 + 2; let message = inline_module(&files, Path::new(M), at).expect_err("a refusal"); assert!(message.contains("interface type"), "{message}"); } #[test] fn a_module_declared_twice_is_refused() { let mut files = files(TOP, SUB); files.push((PathBuf::from("/rtl/other.sv"), SUB.to_string())); let at = TOP.find("sub u_sub").expect("the instantiation") as u32 + 2; let message = inline_module(&files, Path::new(M), at).expect_err("a refusal"); assert!(message.contains("more than one indexed file"), "{message}"); } #[test] fn a_module_the_workspace_does_not_declare_is_refused() { let files = vec![(PathBuf::from(M), TOP.to_string())]; let at = TOP.find("sub u_sub").expect("the instantiation") as u32 + 2; let message = inline_module(&files, Path::new(M), at).expect_err("a refusal"); assert!(message.contains("indexes no module named `sub`"), "{message}"); } #[test] fn a_module_declared_in_the_same_file_is_refused() { let both = format!("{TOP}\n{SUB}"); let files = vec![(PathBuf::from(M), both.clone())]; let at = both.find("sub u_sub").expect("the instantiation") as u32 + 2; let message = inline_module(&files, Path::new(M), at).expect_err("a refusal"); assert!(message.contains("same file it is instantiated in"), "{message}"); } #[test] fn a_differing_timescale_is_refused() { let sub = format!("`timescale 1ps / 1ps\n{SUB}"); let top = format!("`timescale 1ns / 1ps\n{TOP}"); let message = refusal(&top, &sub); assert!(message.contains("`timescale"), "{message}"); } #[test] fn an_array_of_instances_is_refused() { let top = TOP.replace("sub u_sub (", "sub u_sub [1:0] ("); let message = refusal(&top, SUB); assert!(message.contains("array of instances"), "{message}"); } #[test] fn an_escaped_name_a_prefix_cannot_resolve_is_refused() { let sub = SUB .replace("logic s; // the and", "logic \\s-1 ; // the and") .replace("assign s = a & b;", "assign \\s-1 = a & b;") .replace("assign q = s;", "assign q = \\s-1 ;"); let top = TOP.replace(" sub u_sub (", " logic \\s-1 ;\n sub u_sub ("); let message = refusal(&top, &sub); assert!(message.contains("escaped identifier"), "{message}"); } // ---------------------------------------------------------------------- // the cheap gate // ---------------------------------------------------------------------- #[test] fn the_site_gate_finds_the_instantiation_and_names_what_to_read() { let at = TOP.find("sub u_sub").expect("the instantiation") as u32 + 2; let site = inline_site(TOP, at).expect("a site"); assert_eq!(site.module, "sub"); assert_eq!(site.instance, "u_sub"); assert_eq!(site.units, vec!["sub".to_string(), "top".to_string()]); assert_eq!(inline_title(&site.module), "lucisv: inline `sub` here"); } #[test] fn the_site_gate_is_silent_where_there_is_no_instantiation() { let at = TOP.find("input logic x").expect("a port") as u32; assert_eq!(inline_site(TOP, at), None); } // ---------------------------------------------------------------------- // the round trip with ยง53.1 // ---------------------------------------------------------------------- #[test] fn extracting_a_region_and_inlining_it_back_returns_the_original() { let source = "\ module m ( input logic a, input logic b, output logic q ); logic s; assign s = a & b; // the and assign q = s | 1'b0; endmodule "; let files = vec![(PathBuf::from("/rtl/m.sv"), source.to_string())]; let start = source.find(" assign s = a & b;").expect("the region") as u32 + 2; let end = source.find("// the and").expect("the comment") as u32 + 10; let extracted = vlog_refactor::extract_module( &files, Path::new("/rtl/m.sv"), start, end, "sum", vlog_refactor::Home::NewFile, ) .expect("extracts"); let mut after: Vec<(PathBuf, String)> = files.clone(); after.push((PathBuf::from("/rtl/sum.sv"), String::new())); for (path, edits) in &extracted.edits { let text = after.iter().find(|(held, _)| held == path).map(|(_, t)| t.clone()); let mut text = text.unwrap_or_default(); for TextEdit { range, new_text } in edits.iter().rev() { text.replace_range(range.start as usize..range.end as usize, new_text); } match after.iter_mut().find(|(held, _)| held == path) { Some(entry) => entry.1 = text, None => after.push((path.clone(), text)), } } let m = after.iter().find(|(p, _)| p == Path::new("/rtl/m.sv")).expect("m").1.clone(); assert!(m.contains("sum u_sum ("), "the extraction really happened: {m}"); let at = m.find("sum u_sum").expect("the instantiation") as u32 + 2; let back = inline_module(&after, Path::new("/rtl/m.sv"), at).expect("inlines back"); let mut round = m.clone(); for TextEdit { range, new_text } in back.edits_for(&PathBuf::from("/rtl/m.sv")).iter().rev() { round.replace_range(range.start as usize..range.end as usize, new_text); } let config = vlog_formatter::Config::default(); let formatted = |text: &str| vlog_formatter::format_source(text, &config).expect("formats"); assert_eq!( formatted(&round), formatted(source), "extract then inline returns the original file modulo layout:\n{round}" ); } // ---------------------------------------------------------------------- // the `.name` shorthand inside `S`'s own body (work log, 2026-09-06) // ---------------------------------------------------------------------- /// A module whose body instantiates another with the `.name` shorthand โ€” the /// shape the `common_cells` trial caught: `.q_o` names a port of `inner` *and* /// the signal `q_o` of `S`, with one token. const OUTER: &str = "\ module outer ( input logic clk_i, input logic d_i, output logic q_o ); inner u_inner ( .clk_i, .d_i, .q_o ); endmodule "; const INNER: &str = "\ module inner ( input logic clk_i, input logic d_i, output logic q_o ); assign q_o = d_i; endmodule "; const USES_OUTER: &str = "\ module top ( input logic clk_i, input logic data, output logic result ); outer u_outer ( .clk_i(clk_i), .d_i(data), .q_o(result) ); endmodule "; fn shorthand_files(outer: &str) -> Vec<(PathBuf, String)> { vec![ (PathBuf::from(M), USES_OUTER.to_string()), (PathBuf::from("/rtl/outer.sv"), outer.to_string()), (PathBuf::from("/rtl/inner.sv"), INNER.to_string()), ] } #[test] fn a_dot_name_shorthand_in_the_body_is_spelled_out_when_the_name_it_stands_for_changes() { let at = USES_OUTER.find("outer u_outer").expect("the instantiation") as u32 + 2; let out = applied( USES_OUTER, &inline_module(&shorthand_files(OUTER), Path::new(M), at).expect("inlines"), ); // The port's own name never moves โ€” it belongs to `inner` โ€” and the signal // it binds to is written out beside it. assert!(out.contains(".d_i(data)"), "{out}"); assert!(out.contains(".q_o(result)"), "{out}"); // `clk_i` is connected to a `clk_i`, so the shorthand still says what it // said and is left exactly as the author wrote it. assert!(out.contains(".clk_i,"), "{out}"); assert!(!out.contains(".data("), "the port name is never rewritten: {out}"); } #[test] fn a_wildcard_inside_the_inlined_body_is_refused() { let outer = OUTER.replace(".clk_i,\n .d_i,\n .q_o", ".*"); let at = USES_OUTER.find("outer u_outer").expect("the instantiation") as u32 + 2; let message = inline_module(&shorthand_files(&outer), Path::new(M), at).expect_err("a refusal"); assert!(message.contains("expand `.*` in `outer` first"), "{message}"); } #[test] fn a_string_parameter_keeps_the_spaces_inside_its_literal() { let sub = "\ module sub #( parameter string NAME = \"a b\" ) ( input logic a, output logic q ); assign q = a; endmodule "; let top = "\ module top ( input logic x, output logic z ); sub u_sub (.a(x), .q(z)); endmodule "; let out = inlined(top, sub).expect("inlines"); assert!(out.contains("localparam string NAME = \"a b\";"), "{out}"); } // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com