From b9e0390cb2ba9580fcde55ca974fce29f9b7b617 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 18 Oct 2026 19:50:02 +0900 Subject: [PATCH] fix(sv): check native module indices and visit Veryl bodies once Follow up on review of #1488. parse_ir_with_external_hierarchy_and_native_modules indexed the IR directly with each caller-supplied component index, so a stale or out-of-range index panicked. An index that does not name a module is now reported as an external hierarchy error. Collecting the SV instances below each exported Veryl module walked the whole native subtree again for every exported root, which is quadratic for a chain of modules. The SV descendants of each analyzed body are now computed once and shared. They are keyed by body rather than by signature: instances with equal signatures can carry different aliases for their SV children. Validation: - cargo test -p celox -p celox-frontend-veryl --features celox/systemverilog --lib --test systemverilog - cargo clippy -p celox -p celox-frontend-veryl --all-targets --features celox/systemverilog --no-deps - cargo fmt --all -- --check - New tests: an out-of-range native index is an error, and two instances of one Veryl body keep their separately aliased SV leaves Change-Id: Ie4a691acb3bff0ca8d827ceaf1f6015bc4ccd0d4 --- crates/celox-frontend-veryl/src/artifact.rs | 44 ++++++++----- crates/celox-frontend-veryl/src/hierarchy.rs | 64 +++++++++++++++++-- .../tests/frontends/systemverilog/mixed.rs | 30 +++++++++ 3 files changed, 115 insertions(+), 23 deletions(-) diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index c20e05c05e4..2e73cae30ff 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -49,12 +49,14 @@ pub fn external_signatures_named( use veryl_analyzer::ir::Component; // Veryl children link through the IR, but the SV modules beneath them - // still have to be prepared by the SV frontend. - fn sv_descendants( - module: &veryl_analyzer::ir::Module, - names: &mut Vec, - seen: &mut crate::HashSet, - ) { + // still have to be prepared by the SV frontend. Instances of one analyzed + // body share it, so each body is visited once across all exported roots. + // Bodies are keyed by address: equal signatures can still differ in the + // aliases of their SV children. + type Memo = HashMap<*const veryl_analyzer::ir::Module, std::rc::Rc>>; + fn sv_descendants(module: &veryl_analyzer::ir::Module, memo: &mut Memo) -> Vec { + let mut names = Vec::new(); + let mut seen = crate::HashSet::default(); for declaration in &module.declarations { let veryl_analyzer::ir::Declaration::Inst(instance) = declaration else { continue; @@ -62,17 +64,27 @@ pub fn external_signatures_named( match instance.component.as_ref() { Component::SystemVerilog(child) => { if seen.insert(child.name) { - names.push( - veryl_parser::resource_table::get_str_value(child.name) - .unwrap_or_default(), - ); + names.push(child.name); } } - Component::Module(child) => sv_descendants(child, names, seen), + Component::Module(child) => { + let key: *const _ = child; + let nested = match memo.get(&key) { + Some(nested) => nested.clone(), + None => { + let nested = std::rc::Rc::new(sv_descendants(child, memo)); + memo.insert(key, nested.clone()); + nested + } + }; + names.extend(nested.iter().filter(|&&name| seen.insert(name))); + } Component::Interface(_) => {} } } + names } + let mut memo = Memo::default(); let mut external = ExternalHierarchy::default(); for component in &ir.components { @@ -113,12 +125,10 @@ pub fn external_signatures_named( let (mut sim_module, _) = project_module_with_ids(&empty, module, config, ids, &HashMap::default())?; sim_module.name = name(module); - let mut unresolved_instances = Vec::new(); - sv_descendants( - module, - &mut unresolved_instances, - &mut crate::HashSet::default(), - ); + let unresolved_instances = sv_descendants(module, &mut memo) + .into_iter() + .map(|name| veryl_parser::resource_table::get_str_value(name).unwrap_or_default()) + .collect(); let id = celox_design::ModuleId(external.modules.len()); external.roots.insert(sim_module.name.clone(), id); external.modules.insert( diff --git a/crates/celox-frontend-veryl/src/hierarchy.rs b/crates/celox-frontend-veryl/src/hierarchy.rs index 4eb67d792c7..4de2e4e6df9 100644 --- a/crates/celox-frontend-veryl/src/hierarchy.rs +++ b/crates/celox-frontend-veryl/src/hierarchy.rs @@ -176,12 +176,22 @@ fn parse_external_hierarchy<'a>( } module_names.insert(global_id, external_module.sim_module.name.clone()); let native_module = match native_modules { - Some(names) => names - .get(&external_module.sim_module.name) - .and_then(|&index| match &ir.components[index] { - Component::Module(module) => Some(module), - _ => None, - }), + Some(names) => match names.get(&external_module.sim_module.name) { + Some(&index) => match ir.components.get(index) { + Some(Component::Module(module)) => Some(module), + _ => { + return Err(ParserError::illegal_context( + "external module hierarchy", + format!( + "native module `{}` maps to component {index}, which is not a module", + external_module.sim_module.name + ), + None, + )); + } + }, + None => None, + }, None => name_to_ir .get(&resource_table::insert_str( &external_module.sim_module.name, @@ -527,3 +537,45 @@ fn reject_generic_interface_ports(module: &Module) -> Result<(), ParserError> { Some(&module.token), )) } + +#[cfg(test)] +mod tests { + use super::*; + use veryl_analyzer::{Analyzer, Context, attribute_table}; + use veryl_parser::Parser; + + #[test] + fn rejects_native_module_indices_outside_the_ir() { + symbol_table::clear(); + attribute_table::clear(); + let code = "module Top {} module Child {}"; + let metadata = veryl_metadata::Metadata::create_default("prj").unwrap(); + let parser = Parser::parse(code, &"top.veryl").unwrap(); + let analyzer = Analyzer::new(&metadata); + assert!(analyzer.analyze_pass1("prj", &parser.veryl).is_empty()); + assert!(Analyzer::analyze_post_pass1().is_empty()); + let mut ir = veryl_analyzer::ir::Ir::default(); + let mut context = Context::default(); + assert!( + analyzer + .analyze_pass2(&parser.veryl, &mut context, Some(&mut ir)) + .is_empty() + ); + let config = BuildConfig::default(); + let external = crate::external_signatures(&ir, &config).unwrap(); + let native = [("Child".to_string(), ir.components.len())] + .into_iter() + .collect::>(); + let error = parse_ir_with_external_hierarchy_and_native_modules( + &ir, + &LoopProvenance::default(), + &external, + &config, + &resource_table::insert_str("Top"), + &native, + ) + .err() + .expect("an out-of-range index must be rejected"); + assert!(error.to_string().contains("not a module"), "{error}"); + } +} diff --git a/crates/celox/tests/frontends/systemverilog/mixed.rs b/crates/celox/tests/frontends/systemverilog/mixed.rs index 4c3a83a0c0c..7feb18cf301 100644 --- a/crates/celox/tests/frontends/systemverilog/mixed.rs +++ b/crates/celox/tests/frontends/systemverilog/mixed.rs @@ -904,6 +904,36 @@ sv_backends! { assert_eq!(sim.get(sim.signal("y")), 0x76u8.into()); } + fn keeps_specialized_systemverilog_leaves_of_identical_veryl_children(sim) { + @setup { + let veryl = r#" + module Inner (a: input logic<8>, y: output logic<8>) { + inst leaf: $sv::SvLeaf #(K: 8'h0f) (a, y); + } + module Mid (a: input logic<8>, y0: output logic<8>, y1: output logic<8>) { + inst first: Inner (a, y: y0); + inst second: Inner (a: a + 8'd1, y: y1); + } + "#; + let sv = r#" + module Top(input logic [7:0] a, output logic [7:0] y0, y1); + prj_Mid mid(.a(a), .y0(y0), .y1(y1)); + endmodule + module SvLeaf #(parameter logic [7:0] K = 0)(input logic [7:0] a, output logic [7:0] y); + assign y = a ^ K; + endmodule + "#; + } + @build Simulator::from_mixed_sources( + vec![(veryl, Path::new("mid.veryl"))], + vec![(sv, Path::new("top.sv"))], "Top", + ); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 0x20u8)).unwrap(); + assert_eq!(sim.get(sim.signal("y0")), 0x2fu8.into()); + assert_eq!(sim.get(sim.signal("y1")), 0x2eu8.into()); + } + fn reaches_systemverilog_descendants_through_native_veryl_children(sim) { @setup { let veryl = r#"