From b03076c40c73d28a32cff4b540841b9f33146f09 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 14:20:04 +0900 Subject: [PATCH] fix(vpi): expose interface parameters and lexical generate scopes Retain instance-local interface value parameters and localparams using declaration provenance, including indexed interface handles and authored dollar identifiers. Preserve package ownership. Build lexical generate scope prefixes for reflection separately from execution and VCD instance paths, inheriting timescales from the nearest real ancestor. The image container advances to version 49 for serialized lexical scope metadata. Validation covers specialized read-only parameters, escaped identifiers, interface arrays, generate iteration, timescales and native image roundtrips. Frontend, VPI and native library suites, owning-crate lint and formatting pass. This makes the unchanged original board tests discover all actual traffic models instead of passing with an empty MAC list. Keep the class-specialization depth guard reachable on the default stack: separate parameter binding, inherited-base resolution and body construction, with pending specialization metadata owned on the heap. Large temporary binding frames no longer accumulate across recursive inheritance. Preserve the existing depth-64 limit and diagnostics; test legitimate deep inheritance and a nonterminating specialization on an explicit 2 MiB thread stack. Validation after rebasing onto master 626dc7cb11: reproduce the CI SIGABRT with its full comparison-feature configuration, then pass the same test with the fix. All 842 analyzer unit tests (3 existing ignored), 372 class integration tests, 57 VPI tests, analyzer clippy and formatting pass. The host-runtime-disabled SystemVerilog build also passes. Change-Id: I3d0a6f889f3bc98503bbad44ab3bef8f52cab9c9 --- crates/celox-frontend-sv/src/lowering.rs | 108 ++++++++++++-- .../src/ast/classes/specializations.rs | 122 +++++++++++++++- .../celox-sv-analyzer/src/ast/interfaces.rs | 16 ++- crates/celox-vpi/tests/basic_vpi.rs | 132 ++++++++++++++++++ crates/celox/src/backend/native/image_file.rs | 4 +- crates/celox/src/ir.rs | 57 +++++++- crates/celox/src/parser.rs | 64 ++++++++- 7 files changed, 472 insertions(+), 31 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 77e3c065724..dc586ef7f0e 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -337,6 +337,7 @@ fn interface_signatures_collecting( &[], LevelLists::Processes, &HashMap::default(), + &HashMap::default(), )?; Ok(InterfaceSignature { name: prototype.name, @@ -949,6 +950,7 @@ fn lower_package_states( &[], LevelLists::Processes, &HashMap::default(), + &HashMap::default(), )?; lowered.sim_module.time_precision = Some( celox_design::TimePrecision::try_from(packages.global_time_precision()) @@ -3171,24 +3173,44 @@ fn demote_level_lists( changed } -// Use elaboration provenance rather than treating every '$' as a separator: -// legal authored identifiers may themselves contain '$'. +// Candidate indices only locate a declaration; source provenance decides +// whether this is an interface path. Authored '$' names stay intact. +fn restore_interface_path( + name: &str, + paths: &HashMap, +) -> Option> { + if let Some(path) = paths.get(name) { + return path.restore(name); + } + for (separator, _) in name.match_indices('$') { + let member = &name[separator + 1..]; + let mut handle = &name[..separator]; + while let Some(indexed) = handle.strip_suffix(']') { + let Some((base, index)) = indexed.rsplit_once('[') else { + break; + }; + if index.parse::().is_err() { + break; + } + let key = format!("{base}${member}"); + if let Some(path) = paths.get(&key).filter(|path| path.arrayed) + && let Some(restored) = path.restore(name) + { + return Some(restored); + } + handle = base; + } + } + None +} + 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) - .and_then(|path| path.restore(segment)) - .or_else(|| { - source - .interface_member_paths - .values() - .find_map(|path| path.restore(segment)) - }) + restore_interface_path(segment, &source.interface_member_paths) .unwrap_or_else(|| vec![segment.clone()]) }) .collect(); @@ -3367,6 +3389,7 @@ fn specialize_module( &local_forces, level_lists, hierarchical.foreign_writes, + &module.interface_member_paths, )?; propagate_force_signals(&mut lowered.instances, &key.force_signals); lowered.sim_module.time_precision = Some( @@ -3480,6 +3503,7 @@ fn lower_module( force_signals: &[String], level_lists: LevelLists<'_>, foreign_writes: &HashMap, + reflected_paths: &HashMap, ) -> Result { lower_module_with_overrides( module, @@ -3491,6 +3515,7 @@ fn lower_module( force_signals, level_lists, foreign_writes, + reflected_paths, ) } @@ -3573,6 +3598,7 @@ fn lower_module_with_overrides( force_signals: &[String], level_lists: LevelLists<'_>, foreign_writes: &HashMap, + reflected_paths: &HashMap, ) -> Result { let parameter_types = module_parameter_types(module); let constants = module_constants_with_overrides(module, parameter_overrides); @@ -3777,7 +3803,14 @@ fn lower_module_with_overrides( // Retain integral parameters for external observation, without adding them // to name_to_id: HDL expressions must still fold parameter references as // constants rather than introduce runtime loads. - for parameter in module.parameters() { + // Interface declarations are flattened into imported symbols, rather + // than authored module parameters. Retain their instance-local values as + // well; package imports remain owned by their package (IEEE 37.10). + let interface_parameters = module + .imported_parameters() + .iter() + .filter(|parameter| restore_interface_path(parameter.name(), reflected_paths).is_some()); + for parameter in module.parameters().iter().chain(interface_parameters) { let Some(width) = parameter.resolved_width().filter(|width| *width > 0) else { continue; }; @@ -11289,3 +11322,52 @@ endmodule ); } } + +#[cfg(test)] +mod interface_reflection_tests { + use super::*; + + #[test] + fn indexed_interface_paths_require_declaration_provenance() { + let paths = [ + ( + "authored$bus$extra$width", + ["authored$bus", "extra$width"], + false, + ), + ("lanes$extra$width", ["lanes", "extra$width"], true), + ("g[3].lanes$W", ["g[3].lanes", "W"], true), + ] + .into_iter() + .map(|(key, segments, arrayed)| { + ( + key.to_string(), + sv::InterfaceMemberPath { + segments: segments.into_iter().map(str::to_string).collect(), + arrayed, + }, + ) + }) + .collect(); + for (name, expected) in [ + ("authored$bus$extra$width", ["authored$bus", "extra$width"]), + ("lanes[1][-2]$extra$width", ["lanes[1][-2]", "extra$width"]), + ("g[3].lanes[7]$W", ["g[3].lanes[7]", "W"]), + ] { + assert_eq!( + restore_interface_path(name, &paths), + Some(expected.into_iter().map(str::to_string).collect()), + "{name}" + ); + } + for name in [ + "lanes$not_declared", + "lanes[foo]$extra$width", + "authored$bus[0]$extra$width", + "normal$parameter", + "g[2].lanes[7]$W", + ] { + assert_eq!(restore_interface_path(name, &paths), None, "{name}"); + } + } +} diff --git a/crates/celox-sv-analyzer/src/ast/classes/specializations.rs b/crates/celox-sv-analyzer/src/ast/classes/specializations.rs index 7fddf6b39ec..58db650b9d5 100644 --- a/crates/celox-sv-analyzer/src/ast/classes/specializations.rs +++ b/crates/celox-sv-analyzer/src/ast/classes/specializations.rs @@ -267,6 +267,43 @@ pub(in crate::ast) fn specialize( } depth.set(depth.get() + 1); let _nesting = Nesting(depth); + // Parameter binding and body construction have large temporary values. + // Keep those phases off the stack while resolving an inherited class. + let pending = match prepare(tree, generic, arguments, context)? { + Preparation::Existing(name) => return Ok(name), + Preparation::Pending(pending) => pending, + }; + tree.state + .class_specializations_building + .borrow_mut() + .push(pending.name.clone()); + let _building = Building(&tree.state.class_specializations_building); + let bases = bind_bases(tree, generic, &pending.env, &pending.aliases)?; + finish_specialization(tree, generic, pending, bases) +} + +struct PendingSpecialization { + name: String, + parameters: Parameters, + env: HashMap, + aliases: HashMap, +} + +enum Preparation { + Existing(String), + Pending(Box), +} + +// These boundaries keep the recursive inheritance frame small in debug and +// optimized builds alike; the specialization limit must produce a diagnostic +// before the host thread runs out of stack. +#[inline(never)] +fn prepare( + tree: &AnalysisContext<'_>, + generic: &str, + arguments: &[Argument], + context: &PackedDimensions, +) -> Converted { let native = tree.declarations(); let declaration = super::declaration(tree, generic) .ok_or_else(|| unsupported(format!("class `{generic}`")))?; @@ -375,7 +412,7 @@ pub(in crate::ast) fn specialize( .borrow() .contains(&name) { - return Ok(name); + return Ok(Preparation::Existing(name)); } if tree.state.class_specializations_frozen.get() { return Err(unsupported(format!( @@ -387,11 +424,24 @@ pub(in crate::ast) fn specialize( "more than {MAX_SPECIALIZATIONS} class specializations" ))); } - tree.state - .class_specializations_building - .borrow_mut() - .push(name.clone()); - let _building = Building(&tree.state.class_specializations_building); + Ok(Preparation::Pending(Box::new(PendingSpecialization { + name, + parameters, + env, + aliases, + }))) +} + +#[inline(never)] +fn bind_bases( + tree: &AnalysisContext<'_>, + generic: &str, + env: &HashMap, + aliases: &HashMap, +) -> Converted> { + let native = tree.declarations(); + let declaration = super::declaration(tree, generic) + .ok_or_else(|| unsupported(format!("class `{generic}`")))?; // The bases are named in the scope of the parameters; a class does not // inherit the declarations of the interface classes it implements. let inherited = match &declaration.base { @@ -401,12 +451,31 @@ pub(in crate::ast) fn specialize( }; let mut bases = Vec::new(); for id in inherited { - if let Some(base) = type_binding::procedural_type(id, native, tree, &env, &aliases)? + if let Some(base) = type_binding::procedural_type(id, native, tree, env, aliases)? .and_then(|ty| ty.class().map(str::to_owned)) { bases.push(base); } } + Ok(bases) +} + +#[inline(never)] +fn finish_specialization( + tree: &AnalysisContext<'_>, + generic: &str, + pending: Box, + bases: Vec, +) -> Converted { + let PendingSpecialization { + name, + mut parameters, + mut env, + mut aliases, + } = *pending; + let native = tree.declarations(); + let declaration = super::declaration(tree, generic) + .ok_or_else(|| unsupported(format!("class `{generic}`")))?; // The body sees the parameters and types of the bases, hidden by the // class's own, and the scope of the specialization (8.25.1). for base in &bases { @@ -1088,3 +1157,42 @@ pub(in crate::ast) fn collect(tree: &AnalysisContext<'_>, context: &PackedDimens } } } + +#[cfg(test)] +mod tests { + use std::path::Path; + + #[test] + fn inheritance_specialization_uses_the_default_thread_stack() { + std::thread::Builder::new() + .stack_size(2 * 1024 * 1024) + .spawn(|| { + let mut source = String::from("module Top;"); + for index in 0..16 { + source.push_str(&format!( + "class Layer{index} #(int N = 0) extends Layer{}#(N + 1); endclass ", + index + 1, + )); + } + source.push_str( + "class Layer16 #(int N = 0); localparam int VALUE = N; endclass + Layer0#() object; initial $display(Layer0#()::VALUE); endmodule", + ); + crate::analyze_source(&source, Path::new("deep-class-inheritance.sv")).unwrap(); + + let error = crate::analyze_source( + "module Top; + class Recursive #(int N = 0) extends Recursive#(N + 1); endclass + Recursive object; endmodule", + Path::new("unbounded-class-inheritance.sv"), + ) + .unwrap_err() + .to_string(); + assert!(error.contains("nested more than 64 deep"), "{error}"); + assert!(error.contains("class `Recursive`"), "{error}"); + }) + .unwrap() + .join() + .unwrap(); + } +} diff --git a/crates/celox-sv-analyzer/src/ast/interfaces.rs b/crates/celox-sv-analyzer/src/ast/interfaces.rs index dfe0c33870b..4750eb0768f 100644 --- a/crates/celox-sv-analyzer/src/ast/interfaces.rs +++ b/crates/celox-sv-analyzer/src/ast/interfaces.rs @@ -679,6 +679,8 @@ struct InterfaceDecl { /// Whether the declaration refers to compilation-unit items of its file. uses_unit_items: bool, parameters: Vec, + /// Value parameters and localparams whose instance paths VPI can observe. + reflected_parameters: Vec, type_parameters: Vec, parameter_order: Vec, items: Vec, @@ -2423,6 +2425,7 @@ impl InterfaceDecl { uses_unit_items: false, uses_macros: has_directive(file.text(span)), parameters: Vec::new(), + reflected_parameters: Vec::new(), type_parameters: Vec::new(), parameter_order: Vec::new(), items: Vec::new(), @@ -2614,6 +2617,7 @@ impl InterfaceDecl { }); return Ok(()); }; + self.reflected_parameters.push(native_name(¶meter.name)); if local { self.declare(native_name(¶meter.name))?; self.items.push(Item::Constant { @@ -3506,11 +3510,17 @@ pub fn plan_interfaces_with_member_paths( 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 { + let interface = &design.interfaces[&handle.interface]; + for member in interface + .members + .iter() + .map(|member| &member.name) + .chain(&interface.reflected_parameters) + { member_paths.insert( - format!("{handle_name}{SEPARATOR}{}", member.name), + format!("{handle_name}{SEPARATOR}{member}"), InterfaceMemberPath { - segments: vec![handle_name.clone(), member.name.clone()], + segments: vec![handle_name.clone(), member.clone()], arrayed: handle.arrayed, }, ); diff --git a/crates/celox-vpi/tests/basic_vpi.rs b/crates/celox-vpi/tests/basic_vpi.rs index 8f2971e3266..47c89a7fefd 100644 --- a/crates/celox-vpi/tests/basic_vpi.rs +++ b/crates/celox-vpi/tests/basic_vpi.rs @@ -76,6 +76,138 @@ fn systemverilog_parameters_are_typed_read_only_objects_at_o2() { clear_runtime(); } +#[cfg(feature = "systemverilog")] +#[test] +fn interface_parameters_keep_instance_paths_and_specialized_values() { + let _serial = lock_vpi(); + let source = r#" + package P; parameter PKG = 123; parameter axil_ctrl_bar$not_member = 99; endpackage + interface Bus #(parameter ADDR_W = 8, parameter extra$width = 3); + localparam HALF = ADDR_W / 2; + logic [ADDR_W-1:0] data; + endinterface + module Top #(parameter authored$width = 7)(output logic q); + import P::*; + Bus #(.ADDR_W(24)) axil_ctrl_bar(); + Bus #(.ADDR_W(12)) lanes[1:0](); + assign q = 1'b0; + endmodule + "#; + let simulator = Simulator::from_sv_sources( + vec![(source, std::path::Path::new("interface_params.sv"))], + "Top", + ) + .opt_level(celox::OptLevel::O1) + .build() + .unwrap(); + let image = simulator.shared_code().program_image().clone(); + let image = + celox::NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()) + .unwrap(); + let _session = install_runtime(trusted_instance(image)).unwrap(); + unsafe { + for (name, expected) in [ + (c"Top.axil_ctrl_bar.ADDR_W", 24), + (c"Top.axil_ctrl_bar.HALF", 12), + (c"Top.lanes[1].ADDR_W", 12), + (c"Top.lanes[0].HALF", 6), + (c"Top.lanes[0].extra$width", 3), + (c"Top.authored$width", 7), + ] { + let handle = vpi_handle_by_name(name.as_ptr(), ptr::null_mut()); + assert!(!handle.is_null(), "{name:?}"); + assert_eq!(vpi_get(VPI_TYPE, handle), VPI_PARAMETER); + let mut value = VpiValue { + format: VPI_INT_VAL, + value: VpiValueData { integer: 0 }, + }; + vpi_get_value(handle, &mut value); + assert_eq!(value.value.integer, expected, "{name:?}"); + value.value.integer = 0; + vpi_put_value(handle, &value, ptr::null(), VPI_NO_DELAY); + vpi_get_value(handle, &mut value); + assert_eq!(value.value.integer, expected, "{name:?} is read-only"); + vpi_free_object(handle); + } + // Imported package constants do not acquire module-instance names. + assert!(vpi_handle_by_name(c"Top.PKG".as_ptr(), ptr::null_mut()).is_null()); + assert!( + vpi_handle_by_name(c"Top.axil_ctrl_bar$not_member".as_ptr(), ptr::null_mut()).is_null() + ); + } + clear_runtime(); +} + +#[cfg(feature = "systemverilog")] +#[test] +fn generate_scopes_with_only_child_instances_are_iterable() { + let _serial = lock_vpi(); + let source = r#" + module Leaf #(parameter P = 0)(output logic q); + timeunit 1us; timeprecision 1ns; + assign q = P; + endmodule + module Top(output logic [1:0] q); + timeunit 1ns; timeprecision 1ps; + for (genvar n = 0; n < 2; n++) begin : bank + if (1) begin : shell + Leaf #(.P(n)) u(q[n]); + end + end + endmodule + "#; + let simulator = Simulator::from_sv_sources( + vec![(source, std::path::Path::new("generate_scopes.sv"))], + "Top", + ) + .opt_level(celox::OptLevel::O1) + .build() + .unwrap(); + let image = simulator.shared_code().program_image().clone(); + let image = + celox::NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()) + .unwrap(); + let _session = install_runtime(trusted_instance(image)).unwrap(); + unsafe { + let top = vpi_handle_by_name(c"Top".as_ptr(), ptr::null_mut()); + let iterator = vpi_iterate(VPI_INTERNAL_SCOPE, top); + assert!(!iterator.is_null()); + let mut names = Vec::new(); + loop { + let bank = vpi_scan(iterator); + if bank.is_null() { + break; + } + names.push( + CStr::from_ptr(vpi_get_str(VPI_NAME, bank)) + .to_str() + .unwrap() + .to_string(), + ); + assert_eq!(vpi_get(VPI_TIME_UNIT, bank), -9); + let nested = vpi_iterate(VPI_INTERNAL_SCOPE, bank); + assert!(!nested.is_null()); + let shell = vpi_scan(nested); + assert!(!shell.is_null()); + assert_eq!(CStr::from_ptr(vpi_get_str(VPI_NAME, shell)), c"shell"); + assert_eq!(vpi_get(VPI_TIME_UNIT, shell), -9); + assert!(vpi_scan(nested).is_null()); + let children = vpi_iterate(VPI_MODULE, shell); + let leaf = vpi_scan(children); + assert!(!leaf.is_null()); + assert_eq!(CStr::from_ptr(vpi_get_str(VPI_NAME, leaf)), c"u"); + assert_eq!(vpi_get(VPI_TIME_UNIT, leaf), -6); + assert!(vpi_scan(children).is_null()); + vpi_free_object(leaf); + vpi_free_object(shell); + vpi_free_object(bank); + } + assert_eq!(names, ["bank[0]", "bank[1]"]); + vpi_free_object(top); + } + clear_runtime(); +} + unsafe extern "C" fn reschedule_long_callback(data: *mut VpiCbData) -> i32 { let count = LONG_CALLBACK_COUNT.fetch_add(1, Ordering::SeqCst) + 1; let delay = LONG_CALLBACK_DELAY.load(Ordering::SeqCst); diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 51923540478..f812ecbcff4 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,8 +6,8 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -// Native kernel offsets extend the image metadata. -const CONTAINER_VERSION: u16 = 48; +// Native kernel offsets and lexical reflection scopes extend the image metadata. +const CONTAINER_VERSION: u16 = 49; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/ir.rs b/crates/celox/src/ir.rs index b577ebbabbd..23a062b2d34 100644 --- a/crates/celox/src/ir.rs +++ b/crates/celox/src/ir.rs @@ -93,6 +93,9 @@ pub struct RuntimeDesign { instance_ids: HashMap, variables: HashMap, package_instances: crate::HashSet, + /// Source-declared lexical scopes used only by reflection. Keep the + /// real-instance display path unchanged for lookup and VCD bookkeeping. + reflection_instance_paths: std::collections::BTreeMap>, } impl std::ops::Deref for RuntimeDesign { @@ -195,6 +198,7 @@ impl RuntimeDesign { instance_ids: frontend.instance_ids, variables, package_instances: frontend.package_instances, + reflection_instance_paths: Default::default(), }; design .validate() @@ -206,6 +210,14 @@ impl RuntimeDesign { &self.semantic } + #[cfg(feature = "systemverilog")] + pub(crate) fn set_reflection_instance_paths( + &mut self, + paths: std::collections::BTreeMap>, + ) { + self.reflection_instance_paths = paths; + } + pub fn instances(&self) -> impl Iterator { self.instances.values() } @@ -900,7 +912,11 @@ impl RuntimeProgram { .design .instances() .map(|instance| { - let segments = &instance.display_path; + let segments = self + .design + .reflection_instance_paths + .get(&instance.id) + .unwrap_or(&instance.display_path); let name = segments .last() .cloned() @@ -932,9 +948,42 @@ impl RuntimeProgram { // instances. Retain their source path segments as navigable scopes. let real_scopes = scope_sources .iter() - .map(|scope| scope.full_name.clone()) - .collect::>(); + .map(|scope| (scope.full_name.clone(), scope.instance_id)) + .collect::>(); let mut member_scopes = HashMap::default(); + let root_instance = self + .design + .root_instance() + .expect("top-level instance exists") + .id; + // A generate block can contain only child instances, without a local + // variable to create its scope. Materialize every declared prefix and + // inherit its time scale from the nearest real enclosing instance. + for segments in self.design.reflection_instance_paths.values() { + let mut owner = root_instance; + for depth in 1..segments.len() { + let full_name = format!("{root_name}.{}", segments[..depth].join(".")); + if let Some(&instance) = real_scopes.get(&full_name) { + owner = instance; + continue; + } + let parent_name = if depth == 1 { + root_name.clone() + } else { + format!("{root_name}.{}", segments[..depth - 1].join(".")) + }; + member_scopes + .entry(full_name.clone()) + .or_insert_with(|| ScopeSource { + is_instance: false, + instance_id: owner, + name: segments[depth - 1].clone(), + full_name, + parent_name: Some(parent_name), + module_name: String::new(), + }); + } + } for scope in &scope_sources { let instance = self.design.instance(scope.instance_id).unwrap(); for address in instance.state_addresses() { @@ -945,7 +994,7 @@ impl RuntimeProgram { for depth in 1..variable.path.len() { let full_name = format!("{}.{}", scope.full_name, variable.path[..depth].join(".")); - if real_scopes.contains(&full_name) { + if real_scopes.contains_key(&full_name) { continue; } let parent_name = if depth == 1 { diff --git a/crates/celox/src/parser.rs b/crates/celox/src/parser.rs index fd3e655c203..646d3e33a05 100644 --- a/crates/celox/src/parser.rs +++ b/crates/celox/src/parser.rs @@ -630,7 +630,7 @@ pub fn parse_sv( if let Some(trace) = trace.as_deref_mut() { trace.absorb_frontend(frontend_trace); } - finalize_scheduled_rtl( + let mut program = finalize_scheduled_rtl( scheduled, None, four_state, @@ -642,7 +642,43 @@ pub fn parse_sv( testbench_random_seed, component_libraries, component_file_base, - ) + )?; + let paths = program + .runtime + .design + .instances() + .filter_map(|instance| { + let scopes = sv_reflection_scope_segments(&instance.display_path); + (scopes != instance.display_path).then_some((instance.id, scopes)) + }) + .collect(); + program.runtime.design.set_reflection_instance_paths(paths); + Ok(program) +} + +/// Split only SystemVerilog hierarchy separators. Escaped identifiers retain +/// their spelling and whitespace terminator (IEEE 1800-2023 5.6.1). +#[cfg(feature = "systemverilog")] +fn sv_reflection_scope_segments(segments: &[String]) -> Vec { + let mut result = Vec::new(); + for segment in segments { + let mut start = 0; + let mut escaped = false; + for (index, character) in segment.char_indices() { + if escaped { + if character.is_ascii_whitespace() { + escaped = false; + } + } else if character == '\\' { + escaped = true; + } else if character == '.' { + result.push(segment[start..index].to_string()); + start = index + 1; + } + } + result.push(segment[start..].to_string()); + } + result } /// An analyzer error as a parser error: a construct the analyzer does not @@ -1135,3 +1171,27 @@ mod fused_hint_tests { ); } } + +#[cfg(all(test, feature = "systemverilog"))] +mod sv_scope_tests { + use super::sv_reflection_scope_segments; + + #[test] + fn lexical_scopes_preserve_escaped_dots_and_instance_paths() { + let slash = char::from(92u8); + let generated = format!("bank[2].{slash}literal.with.dots .u"); + let leaf = format!("{slash}leaf.with.dots"); + let source = vec![generated.clone(), leaf.clone()]; + let scopes = sv_reflection_scope_segments(&source); + assert_eq!( + scopes, + vec![ + "bank[2]".to_string(), + format!("{slash}literal.with.dots "), + "u".to_string(), + leaf + ] + ); + assert_eq!(scopes.join("."), source.join(".")); + } +}