From e16ef23701dad143b55c3a5cab5ff0678190cdfb Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 20 Oct 2026 04:42:52 +0900 Subject: [PATCH] fix(vpi): preserve SystemVerilog interface member hierarchy Expose declared SystemVerilog interfaces as navigable scopes in native image reflection. Previously Taxi's s_axis.tdata was published as a flat s_axis$tdata signal, so cocotb could not resolve dut.s_axis and failed before driving the design. Carry interface member paths from elaboration through standalone and mixed-language scheduling, then construct reflection scopes from structured variable paths. Use declaration provenance to preserve legal dollar characters in ordinary identifiers, interface names and member names. Add a native-image round-trip VPI regression covering scoped lookup, enumeration, parent relationships and read/write aliases through interface ports. Validation: - 38 VPI regressions, including the new interface hierarchy regression. - 249 interface-related backend regressions passed; 20 existing cases remain ignored. - 44 analyzer interface tests and 24 native execution tests. - Native addon build and all 108 TypeScript E2E tests. - Clippy for the affected crates and tests, cargo fmt --all -- --check, and git diff --check. - All 9 upstream fpganinja/taxi AXI Stream register cocotb tests passed in an isolated validation worktree combining this change with #1441's SV event metadata and #1570's clock callback ordering. The configuration matches upstream pytest's DATA_W=8, REG_TYPE=2 case; a local testbench copy selects ID_EN=1 and DEST_EN=1, while RTL and Python tests remain unchanged. This PR alone fixes hierarchy discovery; the full workload also needs those existing event-handling changes. Depends-On: https://github.com/celox-sim/celox/pull/1573 Change-Id: I22a3f6f9ca55b53dbf0dbcf3f2399f4655ed7af1 --- crates/celox-frontend-sv/src/lowering.rs | 51 ++++---- .../celox-sv-analyzer/src/ast/interfaces.rs | 28 ++++- crates/celox-sv-analyzer/src/lib.rs | 4 +- crates/celox-vpi/tests/basic_vpi.rs | 115 ++++++++++++++++++ crates/celox/src/ir.rs | 74 ++++++++--- 5 files changed, 231 insertions(+), 41 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 6438f34a334..d815098a48e 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -121,7 +121,7 @@ pub(crate) struct LoweredSvModule { #[derive(Clone)] struct AnalyzedSvModule { name: String, - interface_ports: HashSet, + interface_member_paths: HashMap>, source: std::rc::Rc, implicit_nets_allowed: bool, /// The positional interface of every module in all sources, used to bind @@ -390,7 +390,8 @@ fn analyze_sources_with_requests( ) }) .collect::>(); - let elaboration = sv::plan_interfaces(sources, &bindings)?; + let (elaboration, interface_member_paths) = + sv::plan_interfaces_with_member_paths(sources, &bindings)?; let root_names = elaboration.root_names.clone(); let mut modules = HashMap::default(); let sources: Vec<_> = sources @@ -487,10 +488,9 @@ fn analyze_sources_with_requests( modules.insert( name, AnalyzedSvModule { - interface_ports: elaboration - .modules + interface_member_paths: interface_member_paths .get(&module_name) - .map(|plan| plan.ports.iter().map(|port| port.name.clone()).collect()) + .cloned() .unwrap_or_default(), implicit_nets_allowed: implicit_net_permissions .get( @@ -1656,25 +1656,9 @@ fn prepare_external_hierarchy_collecting( } } } - // Structured paths carry the original interface port identity to foreign - // consumers. Ordinary identifiers containing '$' remain a single segment. for (key, id) in &module_ids { - let Some(base) = analyzed.get(&key.name) else { - continue; - }; - for port in &lowered_modules[id].port_order { - let variable = modules - .get_mut(id) - .unwrap() - .sim_module - .variables - .get_mut(port) - .unwrap(); - if let Some((root, member)) = variable.path[0].split_once('$') - && base.interface_ports.contains(root) - { - variable.path = vec![root.to_string(), member.to_string()]; - } + if let Some(base) = analyzed.get(&key.name) { + restore_interface_member_paths(&mut modules.get_mut(id).unwrap().sim_module, base); } } Ok(ExternalHierarchy { @@ -1903,6 +1887,9 @@ fn schedule_sources_collecting( .map(|(&module_id, lowered)| (module_id, lowered)), &package_states, )?; + for (key, id) in &module_ids { + restore_interface_member_paths(modules.get_mut(id).unwrap(), &analyzed[&key.name]); + } let symbolic = SymbolicRtl { modules, module_names, @@ -1922,6 +1909,24 @@ fn schedule_sources_collecting( .map_err(FrontendError::from) } +// Use elaboration provenance rather than treating every '$' as a separator: +// legal authored identifiers may themselves contain '$'. +fn restore_interface_member_paths(module: &mut SimModule, source: &AnalyzedSvModule) { + for variable in module.variables.values_mut() { + variable.path = variable + .path + .iter() + .flat_map(|segment| { + source + .interface_member_paths + .get(segment) + .cloned() + .unwrap_or_else(|| vec![segment.clone()]) + }) + .collect(); + } +} + fn sv_specialization_limit_error(name: String) -> ParserError { ParserError::unsupported( sv::SV_FRONTEND_TRACKING_ISSUE, diff --git a/crates/celox-sv-analyzer/src/ast/interfaces.rs b/crates/celox-sv-analyzer/src/ast/interfaces.rs index 1b2f7aa96c9..945f9e1528d 100644 --- a/crates/celox-sv-analyzer/src/ast/interfaces.rs +++ b/crates/celox-sv-analyzer/src/ast/interfaces.rs @@ -3069,14 +3069,26 @@ pub fn plan_interfaces( sources: &[(&str, &Path)], bindings: &[(String, String, Vec<(String, String)>)], ) -> Converted { + plan_interfaces_with_member_paths(sources, bindings).map(|(plan, _)| plan) +} + +/// Original paths of flattened interface fields, indexed by bound module name. +pub type InterfaceMemberPaths = HashMap>>; + +/// Build the interface plan and retain source member paths for reflection. +pub fn plan_interfaces_with_member_paths( + sources: &[(&str, &Path)], + bindings: &[(String, String, Vec<(String, String)>)], +) -> Converted<(NativeInterfacePlan, InterfaceMemberPaths)> { let files = sources .iter() .map(|(code, path)| File::new(code, path)) .collect::>>()?; let design = Design::collect(&files)?; let mut result = NativeInterfacePlan::default(); + let mut reflected_paths = HashMap::default(); if design.interfaces.is_empty() { - return Ok(result); + return Ok((result, reflected_paths)); } let mut queue = design .modules @@ -3402,6 +3414,18 @@ pub fn plan_interfaces( queue.push((child_name.clone(), generic)); } } + let mut member_paths = HashMap::default(); + for (handle_name, declarations) in &handles.by_name { + for (_, handle) in declarations { + for member in &design.interfaces[&handle.interface].members { + member_paths.insert( + format!("{handle_name}{SEPARATOR}{}", member.name), + vec![handle_name.clone(), member.name.clone()], + ); + } + } + } + reflected_paths.insert(bound_name.clone(), member_paths); result.modules.insert( bound_name, NativeModulePlan { @@ -3411,5 +3435,5 @@ pub fn plan_interfaces( }, ); } - Ok(result) + Ok((result, reflected_paths)) } diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index 3eb556a805e..4f8fa0b85bb 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -27,11 +27,13 @@ pub mod syntax; pub mod system_functions; pub mod typecheck; +pub use ast::interfaces::{ + InterfaceMemberPaths, NativeInterfacePlan, plan_interfaces, plan_interfaces_with_member_paths, +}; pub use ast::interfaces::{ InterfacePrototype, interface_prototypes, interface_prototypes_for, interface_prototypes_with_options, }; -pub use ast::interfaces::{NativeInterfacePlan, plan_interfaces}; pub use ast::packages::Packages; pub use ast::{ModuleInterface, ModuleInterfaces}; pub use ir::Ir; diff --git a/crates/celox-vpi/tests/basic_vpi.rs b/crates/celox-vpi/tests/basic_vpi.rs index e1d8a32eb27..4fa69954160 100644 --- a/crates/celox-vpi/tests/basic_vpi.rs +++ b/crates/celox-vpi/tests/basic_vpi.rs @@ -2804,3 +2804,118 @@ fn callback_teardown_keeps_its_host_selected_until_dispatch_returns() { assert!(info.argv.is_null()); } } + +#[cfg(feature = "systemverilog")] +#[test] +fn interface_members_are_navigable_after_native_image_round_trip() { + let _serial = lock_vpi(); + let source = r#" + interface Axis; + logic [7:0] data, cost$usd; + logic valid, ready; + modport sink(input data, valid, output ready); + endinterface + module Child(Axis.sink s_axis, output logic [7:0] y); + assign s_axis.ready = 1; + assign y = s_axis.valid ? s_axis.data + 1 : 0; + endmodule + module Top(output logic [7:0] y); + Axis s_axis(), s$axis(); + logic [7:0] cash$flow; + assign cash$flow = 3; + Child uut(s_axis, y); + endmodule + "#; + let simulator = + Simulator::from_sv_sources(vec![(source, std::path::Path::new("axis.sv"))], "Top") + .native_force_support(true) + .four_state(true) + .build_native() + .unwrap(); + let container = simulator + .shared_code() + .program_image() + .to_container_bytes() + .unwrap(); + let runtime = unsafe { NativeProgramInstance::from_attached_bytes(&container) }.unwrap(); + drop(simulator); + let _session = install_runtime(runtime).unwrap(); + unsafe { + let top = vpi_handle_by_name(c"Top".as_ptr(), ptr::null_mut()); + let bus = vpi_handle_by_name(c"s_axis".as_ptr(), top); + assert!(!bus.is_null(), "the declared interface must have a scope"); + let data = vpi_handle_by_name(c"data".as_ptr(), bus); + let valid = vpi_handle_by_name(c"valid".as_ptr(), bus); + let ready = vpi_handle_by_name(c"ready".as_ptr(), bus); + assert!(!data.is_null() && !valid.is_null() && !ready.is_null()); + assert_eq!(CStr::from_ptr(vpi_get_str(VPI_NAME, data)), c"data"); + assert_eq!( + CStr::from_ptr(vpi_get_str(VPI_FULL_NAME, data)), + c"Top.s_axis.data" + ); + assert_eq!(vpi_get(VPI_SIZE, data), 8); + let parent = vpi_handle(VPI_SCOPE, data); + assert_eq!( + CStr::from_ptr(vpi_get_str(VPI_FULL_NAME, parent)), + c"Top.s_axis" + ); + let child_data = vpi_handle_by_name(c"Top.uut.s_axis.data".as_ptr(), ptr::null_mut()); + assert!( + !child_data.is_null(), + "interface ports must retain their paths too" + ); + put_int(data, 41); + put_int(valid, 1); + let y = vpi_handle_by_name(c"y".as_ptr(), top); + let mut value = VpiValue { + format: VPI_INT_VAL, + value: VpiValueData { integer: 0 }, + }; + vpi_get_value(y, &mut value); + assert_eq!(value.value.integer, 42); + vpi_get_value(child_data, &mut value); + assert_eq!( + value.value.integer, 41, + "child member alias must see the deposited value" + ); + let members = vpi_iterate(VPI_REG, bus); + let mut names = Vec::new(); + loop { + let member = vpi_scan(members); + if member.is_null() { + break; + } + names.push( + CStr::from_ptr(vpi_get_str(VPI_NAME, member)) + .to_str() + .unwrap() + .to_owned(), + ); + vpi_free_object(member); + } + names.sort(); + assert_eq!(names, ["cost$usd", "data", "ready", "valid"]); + let dollar_member = vpi_handle_by_name(c"cost$usd".as_ptr(), bus); + let dollar_interface = vpi_handle_by_name(c"Top.s$axis.data".as_ptr(), ptr::null_mut()); + let dollar_signal = vpi_handle_by_name(c"Top.cash$flow".as_ptr(), ptr::null_mut()); + assert!( + !dollar_member.is_null() && !dollar_interface.is_null() && !dollar_signal.is_null() + ); + assert!(vpi_handle_by_name(c"Top.cash".as_ptr(), ptr::null_mut()).is_null()); + for handle in [ + top, + bus, + data, + valid, + ready, + parent, + child_data, + y, + dollar_member, + dollar_interface, + dollar_signal, + ] { + vpi_free_object(handle); + } + } +} diff --git a/crates/celox/src/ir.rs b/crates/celox/src/ir.rs index 9336c758cd3..7a04c29481c 100644 --- a/crates/celox/src/ir.rs +++ b/crates/celox/src/ir.rs @@ -841,6 +841,7 @@ impl RuntimeProgram { layout: &crate::backend::MemoryLayout, ) -> DesignReflection { struct ScopeSource { + is_instance: bool, instance_id: InstanceId, name: String, full_name: String, @@ -877,6 +878,7 @@ impl RuntimeProgram { } }); ScopeSource { + is_instance: true, instance_id: instance.id, name, full_name, @@ -885,6 +887,50 @@ impl RuntimeProgram { } }) .collect::>(); + // A module instance can own structured variables (interface members, + // generate scopes, and aggregate members) without owning child module + // instances. Retain their source path segments as navigable scopes. + let real_scopes = scope_sources + .iter() + .map(|scope| scope.full_name.clone()) + .collect::>(); + let mut member_scopes = HashMap::default(); + for scope in &scope_sources { + let instance = self.design.instance(scope.instance_id).unwrap(); + for address in instance.state_addresses() { + let variable = self.design.variable(address).unwrap(); + if instance.path_index.get(&variable.path) != Some(&Some(*address)) { + continue; + } + for depth in 1..variable.path.len() { + let full_name = + format!("{}.{}", scope.full_name, variable.path[..depth].join(".")); + if real_scopes.contains(&full_name) { + continue; + } + let parent_name = if depth == 1 { + scope.full_name.clone() + } else { + format!( + "{}.{}", + scope.full_name, + variable.path[..depth - 1].join(".") + ) + }; + member_scopes + .entry(full_name.clone()) + .or_insert_with(|| ScopeSource { + is_instance: false, + instance_id: scope.instance_id, + name: variable.path[depth - 1].clone(), + full_name, + parent_name: Some(parent_name), + module_name: String::new(), + }); + } + } + } + scope_sources.extend(member_scopes.into_values()); scope_sources.sort_by(|left, right| left.full_name.cmp(&right.full_name)); let scope_ids = scope_sources @@ -897,16 +943,6 @@ impl RuntimeProgram { ) }) .collect::>(); - let instance_scopes = scope_sources - .iter() - .enumerate() - .map(|(index, scope)| { - ( - scope.instance_id, - ReflectionScopeId(u32::try_from(index).expect("scope count exceeds u32")), - ) - }) - .collect::>(); let mut scopes = scope_sources .iter() .map(|scope| ReflectionScope { @@ -942,7 +978,7 @@ impl RuntimeProgram { let event_kinds = self.design.event_kinds(); let mut signals = Vec::new(); - for scope in &scope_sources { + for scope in scope_sources.iter().filter(|scope| scope.is_instance) { let instance = self.design.instance(scope.instance_id).unwrap(); for state_address in instance.state_addresses() { let variable = self.design.variable(state_address).unwrap(); @@ -956,7 +992,15 @@ impl RuntimeProgram { continue; } let metadata = &self.design.state_objects[state_address]; - let name = variable.path.join("."); + let (name, parents) = variable + .path + .split_last() + .expect("visible variable has a source path"); + let parent_name = if parents.is_empty() { + scope.full_name.clone() + } else { + format!("{}.{}", scope.full_name, parents.join(".")) + }; let array_layout = layout .unpacked_arrays @@ -974,9 +1018,9 @@ impl RuntimeProgram { _ => SignalDirection::Internal, }; signals.push(ReflectionSignal { - full_name: format!("{}.{}", scope.full_name, name), - name, - parent: instance_scopes[&scope.instance_id], + full_name: format!("{parent_name}.{name}"), + name: name.clone(), + parent: scope_ids[&parent_name], state_address: *state_address, signal: SignalRef { offset: layout.offsets[state_address],