From 224fe1f8d024d7e37ac2678c9a6d4ecde24e2e8d Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 18 Oct 2026 10:37:03 +0900 Subject: [PATCH 1/5] refactor(sv)!: lower interfaces from original syntax Interface instances, modport views and generic bindings now resolve through semantic scopes over the original syntax tree. Remove generated probe modules, interface source replacement, timescale call replacement and source blanking in the external verification adapter. Preserve per-instance parameters, process and function bindings, generate scopes, timescales and initialized array members. Bind interface array ports in declaration order across differing bounds and forwarded connections, and reject shape mismatches. Inspect declarations through an explicit analyzer mode so timed bodies need no text edits. Validation: analyzer/frontend units; full SV backend suite; DPI, unpacked-array and mixed frontend tests; formatting and clippy. New array-port and initialization regressions agree with Verilator. Icarus passes array initialization and rejects interface port syntax; the latter is recorded under its existing interface limitation. Both external tools pass the timed declaration-inspection case. BREAKING CHANGE: Remove the elaborate_interfaces source-rewriting APIs. InterfacePrototype exposes its analyzed module instead of generated probe source. Change-Id: I95623503dff2b19c4acd10e87298a0d92e60c077 --- crates/celox-frontend-sv/src/lowering.rs | 88 +- crates/celox-sv-analyzer/src/ast.rs | 312 +- .../celox-sv-analyzer/src/ast/comb_process.rs | 1 + crates/celox-sv-analyzer/src/ast/constants.rs | 49 +- .../celox-sv-analyzer/src/ast/declarations.rs | 25 +- .../celox-sv-analyzer/src/ast/dimensions.rs | 24 + crates/celox-sv-analyzer/src/ast/dpi.rs | 1 + .../celox-sv-analyzer/src/ast/expressions.rs | 33 +- .../celox-sv-analyzer/src/ast/ff_process.rs | 1 + crates/celox-sv-analyzer/src/ast/functions.rs | 1 + crates/celox-sv-analyzer/src/ast/generate.rs | 34 + crates/celox-sv-analyzer/src/ast/instances.rs | 73 +- .../src/ast/interface_ast.rs | 305 ++ .../celox-sv-analyzer/src/ast/interfaces.rs | 2683 ++++------------- .../src/ast/native_interfaces.rs | 919 ++++++ crates/celox-sv-analyzer/src/ast/packages.rs | 8 + .../src/ast/packed_structs/selects.rs | 77 +- crates/celox-sv-analyzer/src/ast/patterns.rs | 2 +- .../celox-sv-analyzer/src/ast/procedural.rs | 12 + crates/celox-sv-analyzer/src/ast/scope.rs | 88 + .../celox-sv-analyzer/src/ast/timescales.rs | 182 +- .../celox-sv-analyzer/src/ast/validation.rs | 1 + crates/celox-sv-analyzer/src/ir.rs | 93 + crates/celox-sv-analyzer/src/lib.rs | 106 +- crates/celox-sv-analyzer/src/parsed.rs | 496 ++- crates/celox-sv-analyzer/src/tests.rs | 880 +++--- .../src/sv/cases/interfaces.vtest | 47 + .../celox-test-suite/src/sv/verification.rs | 107 +- .../verification/sv/icarus/interfaces.json | 35 + .../verification/sv/limitations.json | 2 + .../interface-array-ports-icarus.json | 42 + .../frontends/systemverilog/interfaces.rs | 6 + .../systemverilog/review_regressions.rs | 18 +- .../systemverilog/system_functions.rs | 27 +- crates/celox/tests/sv_lifetimes.rs | 31 +- crates/celox/tests/sv_unit_scope.rs | 28 +- 36 files changed, 3876 insertions(+), 2961 deletions(-) create mode 100644 crates/celox-sv-analyzer/src/ast/interface_ast.rs create mode 100644 crates/celox-sv-analyzer/src/ast/native_interfaces.rs create mode 100644 crates/celox-test-suite/verification/sv/limitations/interface-array-ports-icarus.json diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 80cb127432b..04382a885d1 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -119,7 +119,7 @@ struct AnalyzedSvModule { /// positional port and parameter connections. interfaces: std::sync::Arc, /// The packages declared in all sources, analyzed once. - packages: std::sync::Arc, + packages: std::rc::Rc, } #[derive(Clone)] @@ -212,38 +212,14 @@ pub fn interface_signatures_for( sources: &[(&str, &Path)], names: Option<&HashSet>, ) -> Result, FrontendError> { - let (mut prototypes, signature_sources) = sv::interface_prototypes(sources)?; - if let Some(names) = names { - prototypes.retain(|prototype| names.contains(&prototype.name)); - } + let prototypes = sv::interface_prototypes_for(sources, names)?; if prototypes.is_empty() { return Ok(Vec::new()); } - let probe_path = Path::new(""); - let mut all_sources = signature_sources - .iter() - .zip(sources) - .map(|(code, (_, path))| (code.as_str(), *path)) - .collect::>(); - all_sources.extend( - prototypes - .iter() - .map(|prototype| (prototype.probe_source.as_str(), probe_path)), - ); - let probe_roots = prototypes - .iter() - .map(|prototype| prototype.probe_name.as_str()) - .collect::>(); - let analyzed = analyze_sources(&all_sources, &probe_roots)?; prototypes .into_iter() .map(|prototype| { - let lowered = specialize_module( - &analyzed[&prototype.probe_name], - &LoweredSvModuleKey::base(prototype.probe_name), - false, - false, - )?; + let lowered = lower_module(&prototype.module, false, true, false)?; Ok(InterfaceSignature { name: prototype.name, module: lowered.source, @@ -361,25 +337,8 @@ fn analyze_sources_with_requests( ) }) .collect::>(); - let elaboration = sv::elaborate_interfaces_with_metadata_and_roots( - sources, - &bindings, - selected_roots.as_deref(), - )?; - let elaborated = elaboration.sources; - let root_names = elaboration.root_names; - let elaborated_sources: Vec<(&str, &Path)>; - let sources = match &elaborated { - Some(codes) => { - elaborated_sources = codes - .iter() - .zip(sources) - .map(|(code, (_, path))| (code.as_str(), *path)) - .collect(); - elaborated_sources.as_slice() - } - None => sources, - }; + let elaboration = sv::plan_interfaces(sources, &bindings)?; + let root_names = elaboration.root_names.clone(); let mut modules = HashMap::default(); let sources: Vec<_> = sources .iter() @@ -417,14 +376,19 @@ fn analyze_sources_with_requests( } let interfaces = std::sync::Arc::new(interfaces); let parsed: Vec<&sv::ParsedSource> = sources.iter().map(|(source, ..)| &**source).collect(); - let packages = match roots { + let mut packages = match roots { Some(roots) => { let roots = roots .iter() .map(|root| { root_names .get(*root) - .map(String::as_str) + .map(|name| { + elaboration + .modules + .get(name) + .map_or(name.as_str(), |plan| plan.original.as_str()) + }) .or_else(|| { requests .iter() @@ -438,13 +402,24 @@ fn analyze_sources_with_requests( } None => sv::ParsedSource::analyze_packages(&parsed)?, }; - let packages = std::sync::Arc::new(packages); + packages.set_interface_plan(elaboration.clone()); + let packages = std::rc::Rc::new(packages); for (source, code, path) in &sources { let implicit_net_permissions: HashMap<_, _> = sv::source_module_implicit_net_permissions(code, path)? .into_iter() .collect(); - for module_name in source.module_names().iter().cloned() { + let mut module_names = source.module_names().to_vec(); + module_names.extend( + elaboration + .modules + .iter() + .filter(|(name, plan)| { + *name != &plan.original && source.module_names().contains(&plan.original) + }) + .map(|(name, _)| name.clone()), + ); + for module_name in module_names { if !declarations.is_empty() && foreign.roots.contains_key(&module_name) { continue; } @@ -456,12 +431,17 @@ fn analyze_sources_with_requests( name, AnalyzedSvModule { interface_ports: elaboration - .interface_ports - .get(module_name.split('$').next().unwrap()) - .cloned() + .modules + .get(&module_name) + .map(|plan| plan.ports.iter().map(|port| port.name.clone()).collect()) .unwrap_or_default(), implicit_nets_allowed: implicit_net_permissions - .get(&module_name) + .get( + elaboration + .modules + .get(&module_name) + .map_or(module_name.as_str(), |plan| plan.original.as_str()), + ) .copied() .unwrap_or(true), name: module_name, diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index ef8b122a267..52c25f15b16 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -44,9 +44,11 @@ mod generate; mod imports; mod inlining; mod instances; +mod interface_ast; pub mod interfaces; mod lifetimes; pub(crate) mod module_index; +mod native_interfaces; pub mod packages; mod packed_structs; mod parameters; @@ -205,6 +207,7 @@ pub struct Source { /// Overrides supplied by one instantiation. Types have been resolved in its scope. pub(crate) struct ModuleParameterBindings<'a> { + pub declarations_only: bool, pub values: &'a HashMap, pub types: &'a [(String, Type)], pub patterns: &'a [(String, BoundPattern)], @@ -294,6 +297,7 @@ impl Source { &index, module_name, ModuleParameterBindings { + declarations_only: false, values: parameter_overrides, types: &[], patterns: &[], @@ -321,7 +325,9 @@ impl Source { extra: extra_interfaces, }; let mut modules = Vec::new(); - for node in index.nodes(syntax_tree, module_name) { + let interface_plan = packages.interface_plan.modules.get(module_name); + let original_name = interface_plan.map_or(module_name, |plan| plan.original.as_str()); + for node in index.nodes(syntax_tree, original_name) { match node { RefNode::ModuleDeclarationAnsi(module) => { let node = RefNode::ModuleDeclarationAnsi(module); @@ -331,6 +337,7 @@ impl Source { packages, packages.unit(path), )?; + imported.declarations_only = bindings.declarations_only; imported.type_parameter_bindings = type_parameters::bind(node.clone(), syntax_tree, bindings.types)?; imported.pattern_parameter_bindings = type_parameters::bind_patterns( @@ -338,6 +345,22 @@ impl Source { syntax_tree, bindings.patterns, )?; + if let Some(mut module) = native_interfaces::analyze_module( + module, + syntax_tree, + path, + packages, + native_interfaces::Bindings { + values: bindings.values, + plan: interface_plan, + }, + &interfaces, + imported.clone(), + )? { + module.name = module_name.to_string(); + modules.push(module); + continue; + } modules.push(Module::from_module_node_with_parameter_overrides( node, syntax_tree, @@ -462,6 +485,26 @@ impl Module { parameter_overrides: &HashMap, interfaces: &InterfaceLookup<'_>, imported: Arc, + ) -> Result { + Self::from_scope_node_with_parameter_overrides( + node, + syntax_tree, + override_module_name, + parameter_overrides, + interfaces, + imported, + false, + ) + } + + fn from_scope_node_with_parameter_overrides<'a>( + node: impl Into>, + syntax_tree: &SyntaxTree, + override_module_name: &str, + parameter_overrides: &HashMap, + interfaces: &InterfaceLookup<'_>, + imported: Arc, + export_symbols: bool, ) -> Result { let node = node.into(); let is_package = matches!(node, RefNode::PackageDeclaration(_)); @@ -597,77 +640,92 @@ impl Module { ); } - match reject_silently_ignored_constructs( - node.clone(), - syntax_tree, - &const_env, - &type_aliases, - ¶meter_packed_dimensions_with_imported(¶meters, &imported).into(), - ¶meter_value_env_with_imported(¶meters, &const_env, &imported), - ) { - Ok(()) => {} - // A parameter initializer may inspect a port or signal type - // through `$bits`/`$size`. Collect declarations only when that - // missing type metadata is the remaining validation failure, so - // unsupported constructs keep their original diagnostics. - Err(AnalyzerError::Unsupported(construct)) - if construct == "constant cast expression" => - { - let preliminary_ports = - ports_from_module_node(node.clone(), syntax_tree, &const_env, &type_aliases)?; - let preliminary_signals = - signals_from_module_node(node.clone(), syntax_tree, &const_env, &type_aliases)?; - extend_const_env_with_variable_types( - &mut const_env, - preliminary_ports - .iter() - .map(|port| (port.name(), port.r#type())) - .chain( - preliminary_signals - .iter() - .map(|signal| (signal.name(), signal.r#type())), - ), - ); - parameters = parameters_from_module_node( - node.clone(), - syntax_tree, - &type_aliases, - &const_env, - applicable_parameter_overrides, - )?; - for parameter in &mut parameters { - parameter.value = parameter.value.take().map(|value| { - substitute_typed_parameter_literals( - value, - &enum_constants.numbers, - &enum_constants.types, - ) - }); - } - if name == override_module_name { - apply_parameter_overrides(&mut parameters, parameter_overrides)?; + if !imported.declarations_only { + match reject_silently_ignored_constructs( + node.clone(), + syntax_tree, + &const_env, + &type_aliases, + ¶meter_packed_dimensions_with_imported(¶meters, &imported).into(), + ¶meter_value_env_with_imported(¶meters, &const_env, &imported), + ) { + Ok(()) => {} + // A parameter initializer may inspect a port or signal type + // through `$bits`/`$size`. Collect declarations only when that + // missing type metadata is the remaining validation failure, so + // unsupported constructs keep their original diagnostics. + Err(AnalyzerError::Unsupported(construct)) + if construct == "constant cast expression" => + { + let preliminary_ports = ports_from_module_node( + node.clone(), + syntax_tree, + &const_env, + &type_aliases, + )?; + let preliminary_signals = signals_from_module_node( + node.clone(), + syntax_tree, + &const_env, + &type_aliases, + )?; + extend_const_env_with_variable_types( + &mut const_env, + preliminary_ports + .iter() + .map(|port| (port.name(), port.r#type())) + .chain( + preliminary_signals + .iter() + .map(|signal| (signal.name(), signal.r#type())), + ), + ); + parameters = parameters_from_module_node( + node.clone(), + syntax_tree, + &type_aliases, + &const_env, + applicable_parameter_overrides, + )?; + for parameter in &mut parameters { + parameter.value = parameter.value.take().map(|value| { + substitute_typed_parameter_literals( + value, + &enum_constants.numbers, + &enum_constants.types, + ) + }); + } + if name == override_module_name { + apply_parameter_overrides(&mut parameters, parameter_overrides)?; + } + extend_const_env_with_parameters(&mut const_env, ¶meters); + type_aliases = type_aliases_from_module_node_with_env( + node.clone(), + syntax_tree, + &const_env, + )?; + array_parameters = array_parameters::array_parameters_from_module_node( + node.clone(), + syntax_tree, + &const_env, + &type_aliases, + )?; + reject_silently_ignored_constructs( + node.clone(), + syntax_tree, + &const_env, + &type_aliases, + ¶meter_packed_dimensions_with_imported(¶meters, &imported).into(), + ¶meter_value_env_with_imported(¶meters, &const_env, &imported), + )?; } - extend_const_env_with_parameters(&mut const_env, ¶meters); - type_aliases = - type_aliases_from_module_node_with_env(node.clone(), syntax_tree, &const_env)?; - array_parameters = array_parameters::array_parameters_from_module_node( - node.clone(), - syntax_tree, - &const_env, - &type_aliases, - )?; - reject_silently_ignored_constructs( - node.clone(), - syntax_tree, - &const_env, - &type_aliases, - ¶meter_packed_dimensions_with_imported(¶meters, &imported).into(), - ¶meter_value_env_with_imported(¶meters, &const_env, &imported), - )?; + Err(error) => return Err(error), } - Err(error) => return Err(error), } - let ports = ports_from_module_node(node.clone(), syntax_tree, &const_env, &type_aliases)?; + let mut ports = + ports_from_module_node(node.clone(), syntax_tree, &const_env, &type_aliases)?; + ports.extend(imported.ports.iter().cloned()); let mut port_names = HashSet::default(); if let Some(port) = ports.iter().find(|port| !port_names.insert(port.name())) { return Err(AnalyzerError::DuplicatePort { @@ -920,52 +978,61 @@ impl Module { automatic: lifetimes::automatic_by_default(&node), statics: Vec::new(), }; - let mut subroutines = procedural::subroutines_from_module_node( - node.clone(), - syntax_tree, - &const_env, - &packed_dimensions, - ¶meter_values, - &mut body_state, - )?; - let mut comb_processes = comb_processes_from_module_node( - node.clone(), - syntax_tree, - &const_env, - &packed_dimensions, - ¶meter_values, - &mut body_state, - )? - .into_iter() - .map(|process| { - substitute_process_constants_with_parameter_literals( - process, - &const_env, - ¶meter_values, - ) - }) - .collect::>(); - let mut ff_processes = ff_processes_from_module_node( - node.clone(), - syntax_tree, - &const_env, - ¶meter_values, - &packed_dimensions, - &mut body_state, - )?; - let mut initial_processes = Vec::new(); - for parameter in &array_parameters { - initial_processes.push(parameter.initial_process(syntax_tree, &packed_dimensions)?); - } - initial_processes.extend(imported.initial_processes.iter().cloned()); - initial_processes.extend(procedural::initial_processes_from_module_node( - node.clone(), - syntax_tree, - &const_env, - &packed_dimensions, - ¶meter_values, - &mut body_state, - )?); + let (mut subroutines, mut comb_processes, mut ff_processes, mut initial_processes) = + if imported.declarations_only { + (Vec::new(), Vec::new(), Vec::new(), Vec::new()) + } else { + let subroutines = procedural::subroutines_from_module_node( + node.clone(), + syntax_tree, + &const_env, + &packed_dimensions, + ¶meter_values, + &mut body_state, + )?; + let mut comb_processes = comb_processes_from_module_node( + node.clone(), + syntax_tree, + &const_env, + &packed_dimensions, + ¶meter_values, + &mut body_state, + )? + .into_iter() + .map(|process| { + substitute_process_constants_with_parameter_literals( + process, + &const_env, + ¶meter_values, + ) + }) + .collect::>(); + let mut ff_processes = ff_processes_from_module_node( + node.clone(), + syntax_tree, + &const_env, + ¶meter_values, + &packed_dimensions, + &mut body_state, + )?; + comb_processes.extend(imported.comb_processes.iter().cloned()); + ff_processes.extend(imported.ff_processes.iter().cloned()); + let mut initial_processes = Vec::new(); + for parameter in &array_parameters { + initial_processes + .push(parameter.initial_process(syntax_tree, &packed_dimensions)?); + } + initial_processes.extend(imported.initial_processes.iter().cloned()); + initial_processes.extend(procedural::initial_processes_from_module_node( + node.clone(), + syntax_tree, + &const_env, + &packed_dimensions, + ¶meter_values, + &mut body_state, + )?); + (subroutines, comb_processes, ff_processes, initial_processes) + }; // Static locals of the processes that keep their value are variables // of the module, initialized once with the declaration initializers. let statics: HashMap = body_state.statics.drain(..).collect(); @@ -1020,7 +1087,8 @@ impl Module { } } if let Some(signal) = signals.iter().find(|signal| { - signal.is_net() + !imported.declarations_only + && signal.is_net() && !procedurally_written.contains(signal.name()) && !connected_nets.contains(signal.name()) }) { @@ -1078,7 +1146,8 @@ impl Module { .flat_map(|process| process.assignments().iter().cloned()) .collect(); // A package keeps its symbols for the scopes that use it. - let symbols = is_package.then(|| scope::ScopeSymbols { + let symbols = (is_package || export_symbols).then(|| scope::ScopeSymbols { + declarations_only: imported.declarations_only, type_parameter_bindings: HashMap::default(), pattern_parameter_bindings: HashMap::default(), const_env: const_env.clone(), @@ -1097,9 +1166,18 @@ impl Module { // A package's signals are its array parameters and constant // variables, initialized by its initial processes. signals: signals.clone(), + ports: Vec::new(), state_signals: Vec::new(), initial_processes: initial_processes.clone(), + comb_processes: comb_processes.clone(), + ff_processes: ff_processes.clone(), aliases: imported.aliases.clone(), + interface_members: imported.interface_members.clone(), + interface_types: imported.interface_types.clone(), + interface_arrays: imported.interface_arrays.clone(), + interface_scopes: imported.interface_scopes.clone(), + interface_declarations: imported.interface_declarations.clone(), + interface_instances: imported.interface_instances.clone(), generate_imports: HashMap::default(), }); // The subroutines, locals and DPI imports of the packages the module diff --git a/crates/celox-sv-analyzer/src/ast/comb_process.rs b/crates/celox-sv-analyzer/src/ast/comb_process.rs index dd47a03bb69..b2c6ea37f00 100644 --- a/crates/celox-sv-analyzer/src/ast/comb_process.rs +++ b/crates/celox-sv-analyzer/src/ast/comb_process.rs @@ -19,6 +19,7 @@ pub(super) fn comb_processes_from_module_node( )?; let mut views = generate::ScopeViews::with_literals(packed_dimensions, parameter_literals); for (creation_order, item) in active.iter().enumerate() { + let _interface_scope = item.interface_scope(); let ScopeItem::Module(node) = item.node else { continue; }; diff --git a/crates/celox-sv-analyzer/src/ast/constants.rs b/crates/celox-sv-analyzer/src/ast/constants.rs index d6a5dceb978..bf88f40e124 100644 --- a/crates/celox-sv-analyzer/src/ast/constants.rs +++ b/crates/celox-sv-analyzer/src/ast/constants.rs @@ -1279,7 +1279,43 @@ pub(super) fn const_expr_from_ref_node_with_env( Ok(primary_literal_text(node, syntax_tree).map(ConstExpr::Literal)) } sv_parser::ConstantPrimary::PsParameter(parameter) => { - if parameter.nodes.1.nodes.0.is_some() { + if let Some((members, _, last)) = ¶meter.nodes.1.nodes.0 { + let Some(mut path) = reference_name( + RefNode::PsParameterIdentifier(¶meter.nodes.0), + syntax_tree, + ) else { + return Ok(None); + }; + for (_, member, indices) in members { + if !indices.nodes.0.is_empty() { + return Ok(None); + } + let Some(member) = + identifier_text(RefNode::MemberIdentifier(member), syntax_tree) + else { + return Ok(None); + }; + path.push('.'); + path.push_str(&member); + } + let Some(member) = + identifier_text(RefNode::MemberIdentifier(last), syntax_tree) + else { + return Ok(None); + }; + path.push('.'); + path.push_str(&member); + if let Some(name) = scope::imported().interface_members.get(&path).cloned() { + let mut select = parameter.nodes.1.clone(); + select.nodes.0 = None; + return const_select_expr( + ConstExpr::Ident(name), + &select, + syntax_tree, + const_env, + type_aliases, + ); + } // Struct-valued parameters need typed member evaluation; // never replace a member by the entire parameter value. return Ok(None); @@ -1300,6 +1336,17 @@ pub(super) fn const_expr_from_ref_node_with_env( ) } sv_parser::ConstantPrimary::ConstantFunctionCall(call) => { + // sv-parser also represents a bare hierarchical constant such + // as bus.W as a method call without an argument list. Resolve + // it through the bound interface scope before classifying calls. + if let sv_parser::SubroutineCall::MethodCall(method) = &call.nodes.0.nodes.0 + && let Ok((name, arguments)) = + native_interfaces::method_call(method, syntax_tree) + && arguments.is_none() + && const_env.contains_key(&name) + { + return Ok(Some(ConstExpr::Ident(name))); + } if let sv_parser::SubroutineCall::SystemTfCall(system_call) = &call.nodes.0.nodes.0 { let function = diff --git a/crates/celox-sv-analyzer/src/ast/declarations.rs b/crates/celox-sv-analyzer/src/ast/declarations.rs index 3207f979d8f..db40f392246 100644 --- a/crates/celox-sv-analyzer/src/ast/declarations.rs +++ b/crates/celox-sv-analyzer/src/ast/declarations.rs @@ -394,9 +394,32 @@ pub(super) fn signals_from_module_node( syntax_tree: &SyntaxTree, const_env: &HashMap, type_aliases: &HashMap, +) -> Result, AnalyzerError> { + signals_from_module_node_with_declaration_ranges( + node, + syntax_tree, + const_env, + type_aliases, + false, + ) +} + +pub(super) fn signals_from_module_node_with_declaration_ranges( + node: RefNode<'_>, + syntax_tree: &SyntaxTree, + const_env: &HashMap, + type_aliases: &HashMap, + preserve_parameters: bool, ) -> Result, AnalyzerError> { let mut signals = Vec::new(); - for item in generate::items(node, syntax_tree, const_env, type_aliases)? { + for mut item in generate::items(node, syntax_tree, const_env, type_aliases)? { + let _interface_scope = item.interface_scope(); + if preserve_parameters { + let names = item.env.keys().cloned().collect::>(); + for name in names { + item.env.remove(&local_parameter_marker(&name)); + } + } let node = match item.node { ScopeItem::Module(node) => node, // The variables of a package are its constant variables; the diff --git a/crates/celox-sv-analyzer/src/ast/dimensions.rs b/crates/celox-sv-analyzer/src/ast/dimensions.rs index aa926ca4eb5..78f981dca70 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions.rs @@ -63,6 +63,28 @@ pub(super) fn dimensions_system_function_call_value( } } +fn extend_interface_dimensions(dimensions: &mut PackedDimensions) { + let imported = scope::imported(); + if imported.interface_members.is_empty() { + return; + } + for (name, ty) in imported + .ports + .iter() + .map(|port| (port.name(), port.r#type())) + .chain( + imported + .signals + .iter() + .map(|signal| (signal.name(), signal.r#type())), + ) + { + if dimensions.get(name).is_none() { + dimensions.insert(name.to_string(), procedural::dimensions_from_type(ty)); + } + } +} + fn query_operand_dimensions( argument: &sv_parser::Expression, syntax_tree: &SyntaxTree, @@ -82,6 +104,7 @@ fn query_operand_dimensions( type_aliases, ) .unwrap_or_else(|| PackedDimensions::new(HashMap::default(), const_env, type_aliases)); + extend_interface_dimensions(&mut context); context.function_return_types = containing_function_return_types( RefNode::Expression(argument), syntax_tree, @@ -883,6 +906,7 @@ fn size_function_expression_type( type_aliases: type_aliases.clone(), ..PackedDimensions::default() }); + extend_interface_dimensions(&mut packed_dimensions); packed_dimensions.function_return_types = containing_function_return_types( RefNode::Expression(argument), syntax_tree, diff --git a/crates/celox-sv-analyzer/src/ast/dpi.rs b/crates/celox-sv-analyzer/src/ast/dpi.rs index ed0669b17d2..adc4850eb26 100644 --- a/crates/celox-sv-analyzer/src/ast/dpi.rs +++ b/crates/celox-sv-analyzer/src/ast/dpi.rs @@ -20,6 +20,7 @@ pub(super) fn dpi_imports_from_module_node( ) -> Result, AnalyzerError> { let mut imports = Vec::new(); for item in generate::items(node, tree, const_env, type_aliases)? { + let _interface_scope = item.interface_scope(); for child in item.node.node() { if let RefNode::DpiImportExport(declaration) = child { imports.push(dpi_import(declaration, tree)?); diff --git a/crates/celox-sv-analyzer/src/ast/expressions.rs b/crates/celox-sv-analyzer/src/ast/expressions.rs index 98916c99900..90b970b27bf 100644 --- a/crates/celox-sv-analyzer/src/ast/expressions.rs +++ b/crates/celox-sv-analyzer/src/ast/expressions.rs @@ -424,6 +424,13 @@ pub(super) fn expr_from_primary_with_types( } let name = reference_name(RefNode::PrimaryHierarchical(hierarchical), syntax_tree) .ok_or_else(|| unsupported("hierarchical identifier"))?; + if scope::imported().interface_types.contains_key(&name) + && packed_dimensions.get(&name).is_none() + { + return Err(unsupported(format!( + "use of interface `{name}` other than as a port connection or through a member" + ))); + } let base = Expr::Ident(name); let select = &hierarchical.nodes.2; if select.nodes.1.nodes.0.is_empty() && select.nodes.2.is_none() { @@ -575,7 +582,10 @@ pub(super) fn expr_from_subroutine_call( sv_parser::SubroutineCall::TfCall(call) => { expr_from_tf_call(call, syntax_tree, packed_dimensions) } - sv_parser::SubroutineCall::MethodCall(_) => Err(unsupported("method call")), + sv_parser::SubroutineCall::MethodCall(call) => { + let (name, arguments) = native_interfaces::method_call(call, syntax_tree)?; + expr_from_named_call(name, arguments, syntax_tree, packed_dimensions) + } sv_parser::SubroutineCall::Randomize(_) => Err(unsupported("randomize call")), } } @@ -815,6 +825,20 @@ pub(super) fn expr_from_tf_call( { return Ok(Expr::Ident(name)); } + expr_from_named_call( + name, + call.nodes.2.as_ref().map(|paren| &paren.nodes.1), + syntax_tree, + packed_dimensions, + ) +} + +fn expr_from_named_call( + name: String, + arguments: Option<&sv_parser::ListOfArguments>, + syntax_tree: &SyntaxTree, + packed_dimensions: &PackedDimensions, +) -> Converted { let query_formals = packed_dimensions .type_query .then(|| { @@ -834,12 +858,7 @@ pub(super) fn expr_from_tf_call( } else { &packed_dimensions.subroutine_param_names }; - let (bindings, arg_order) = bind_call_arguments( - &name, - call.nodes.2.as_ref().map(|paren| &paren.nodes.1), - syntax_tree, - signatures, - )?; + let (bindings, arg_order) = bind_call_arguments(&name, arguments, syntax_tree, signatures)?; if let Some(formals) = query_formals { if bindings.len() > formals.len() { return Err(unsupported(format!("extra arguments of `{name}`"))); diff --git a/crates/celox-sv-analyzer/src/ast/ff_process.rs b/crates/celox-sv-analyzer/src/ast/ff_process.rs index bfda9f3e1be..5de244a1498 100644 --- a/crates/celox-sv-analyzer/src/ast/ff_process.rs +++ b/crates/celox-sv-analyzer/src/ast/ff_process.rs @@ -19,6 +19,7 @@ pub(super) fn ff_processes_from_module_node( )?; let mut views = generate::ScopeViews::with_literals(packed_dimensions, parameter_literals); for (creation_order, item) in active.iter().enumerate() { + let _interface_scope = item.interface_scope(); let ScopeItem::Module(node) = item.node else { continue; }; diff --git a/crates/celox-sv-analyzer/src/ast/functions.rs b/crates/celox-sv-analyzer/src/ast/functions.rs index 8911eb6a048..bb7c196b1ac 100644 --- a/crates/celox-sv-analyzer/src/ast/functions.rs +++ b/crates/celox-sv-analyzer/src/ast/functions.rs @@ -19,6 +19,7 @@ pub(super) fn functions_from_module_node( { let _constant_functions = item.enter(); let type_aliases = item.type_aliases(&module_type_aliases); + let _interface_scope = item.interface_scope(); if let RefNode::TaskDeclaration(declaration) = child { let task_dimensions = views.dimensions(item); let const_env = &item.env; diff --git a/crates/celox-sv-analyzer/src/ast/generate.rs b/crates/celox-sv-analyzer/src/ast/generate.rs index 14e23e21a24..2c1eff208cd 100644 --- a/crates/celox-sv-analyzer/src/ast/generate.rs +++ b/crates/celox-sv-analyzer/src/ast/generate.rs @@ -158,6 +158,40 @@ impl Item<'_> { self.block_imports().install_constant_functions() } + pub fn scope_name(&self) -> &str { + &self.scope + } + + pub fn interface_scope(&self) -> Option { + let imported = scope::imported(); + if imported.interface_scopes.is_empty() { + return None; + } + let mut scopes = imported + .interface_scopes + .iter() + .filter(|(name, _)| { + self.scope == **name + || self + .scope + .strip_prefix(name.as_str()) + .is_some_and(|rest| rest.starts_with('.')) + }) + .collect::>(); + if scopes.is_empty() { + return None; + } + scopes.sort_by_key(|(name, _)| name.len()); + let mut local = (*imported).clone(); + for (_, bindings) in scopes { + local.interface_members.extend(bindings.members.clone()); + local.interface_types.extend(bindings.types.clone()); + local.interface_arrays.extend(bindings.arrays.clone()); + local.interface_instances.extend(bindings.instances.clone()); + } + Some(scope::install(Arc::new(local))) + } + pub fn common(&self) -> Option<&sv_parser::ModuleCommonItem> { match self.node { ScopeItem::Module(sv_parser::ModuleOrGenerateItem::ModuleItem(item)) => { diff --git a/crates/celox-sv-analyzer/src/ast/instances.rs b/crates/celox-sv-analyzer/src/ast/instances.rs index 1548d11804f..a71fae8d685 100644 --- a/crates/celox-sv-analyzer/src/ast/instances.rs +++ b/crates/celox-sv-analyzer/src/ast/instances.rs @@ -14,6 +14,7 @@ pub(super) fn instances_from_module_node( let mut instances = Vec::new(); let mut views = generate::ScopeViews::new(packed_dimensions); for item in &active { + let _interface_scope = item.interface_scope(); let ScopeItem::Module(node) = item.node else { continue; }; @@ -21,6 +22,17 @@ pub(super) fn instances_from_module_node( continue; } let _constant_functions = item.enter(); + if let sv_parser::ModuleOrGenerateItem::Module(instance) = node + && identifier_locate(RefNode::ModuleIdentifier(&instance.nodes.1.nodes.0)).is_some_and( + |locate| { + scope::imported() + .interface_declarations + .contains(&locate.offset) + }, + ) + { + continue; + } let start = instances.len(); let dimensions = views.dimensions(item); instances_from_module_or_generate_item( @@ -178,11 +190,25 @@ fn instances_from_module_instantiation( })?; Some(bounds) }; + let imported = scope::imported(); + let binding = identifier_locate(RefNode::InstanceIdentifier(&instance.nodes.0.nodes.0)) + .and_then(|locate| imported.interface_instances.get(&locate.offset)); + let mut parameter_names = parameter_names.clone(); + let mut parameter_overrides = parameter_overrides.clone(); + if let Some(binding) = binding { + parameter_names.extend( + binding + .parameters + .iter() + .map(|parameter| parameter.name.clone()), + ); + parameter_overrides.extend(binding.parameters.iter().cloned()); + } instances.push(Instance::new( - module_name.clone(), + binding.map_or_else(|| module_name.clone(), |binding| binding.module.clone()), name, - parameter_names.clone(), - parameter_overrides.clone(), + parameter_names, + parameter_overrides, condition.clone(), port_names, port_connections, @@ -192,7 +218,7 @@ fn instances_from_module_instantiation( Ok(()) } -fn parameter_overrides_from_value_assignment( +pub(super) fn parameter_overrides_from_value_assignment( assignment: Option<&sv_parser::ParameterValueAssignment>, syntax_tree: &SyntaxTree, interface: Option<&ModuleInterface>, @@ -257,12 +283,15 @@ fn parameter_overrides_from_value_assignment( Ok(overrides) } -fn port_connections_from_hierarchical_instance( +pub(super) fn port_connections_from_hierarchical_instance( instance: &sv_parser::HierarchicalInstance, syntax_tree: &SyntaxTree, packed_dimensions: &PackedDimensions, interface: Option<&ModuleInterface>, ) -> Result, AnalyzerError> { + let imported = scope::imported(); + let binding = identifier_locate(RefNode::InstanceIdentifier(&instance.nodes.0.nodes.0)) + .and_then(|locate| imported.interface_instances.get(&locate.offset)); let Some(connections) = instance.nodes.1.nodes.1.as_ref() else { return Ok(Vec::new()); }; @@ -289,6 +318,10 @@ fn port_connections_from_hierarchical_instance( let formal = ports .get(position) .ok_or_else(|| AnalyzerError::Unsupported("ordered port connection".to_string()))?; + if let Some(connections) = binding.and_then(|binding| binding.connections.get(formal)) { + lowered.extend(connections.iter().cloned()); + continue; + } let Some(expr) = connection.nodes.1.as_ref() else { continue; }; @@ -314,6 +347,12 @@ fn port_connections_from_hierarchical_instance( "named port connection identifier".to_string(), ) })?; + if let Some(connections) = + binding.and_then(|binding| binding.connections.get(&formal)) + { + lowered.extend(connections.iter().cloned()); + continue; + } let actual_expr = match connection.nodes.3.as_ref() { None => Some(Expr::Ident(formal.clone())), Some(paren) => match paren.nodes.1.as_ref() { @@ -377,6 +416,30 @@ pub(super) fn identifier_text(node: RefNode<'_>, syntax_tree: &SyntaxTree) -> Op /// scope here since classes are not supported. Otherwise it is the first /// identifier, as [`identifier_text`] gives. pub(super) fn reference_name(node: RefNode<'_>, syntax_tree: &SyntaxTree) -> Option { + if let Some(RefNode::HierarchicalIdentifier(identifier)) = + unwrap_node!(node.clone(), HierarchicalIdentifier) + && identifier.nodes.0.is_none() + && !identifier.nodes.1.is_empty() + && identifier + .nodes + .1 + .iter() + .all(|(_, indices, _)| indices.nodes.0.is_empty()) + { + let mut path = identifier + .nodes + .1 + .iter() + .map(|(name, _, _)| identifier_text(RefNode::Identifier(name), syntax_tree)) + .collect::>>()?; + path.push(identifier_text( + RefNode::Identifier(&identifier.nodes.2), + syntax_tree, + )?); + if let Some(name) = scope::imported().interface_members.get(&path.join(".")) { + return Some(name.clone()); + } + } let mut package = None; // The package scope precedes the identifier it qualifies, and contains // the package identifier itself. diff --git a/crates/celox-sv-analyzer/src/ast/interface_ast.rs b/crates/celox-sv-analyzer/src/ast/interface_ast.rs new file mode 100644 index 00000000000..2759feca596 --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/interface_ast.rs @@ -0,0 +1,305 @@ +//! Structural views of interface declarations. Tokens retain their original +//! locations; no generated SystemVerilog is parsed to collect an interface. +use super::*; + +pub(super) fn module_view( + interface: &sv_parser::InterfaceDeclarationAnsi, +) -> Converted { + use sv_parser::*; + let header = &interface.nodes.0.nodes; + let items = interface + .nodes + .2 + .iter() + .filter_map(|item| match item { + NonPortInterfaceItem::ModportDeclaration(_) => None, + NonPortInterfaceItem::TimeunitsDeclaration(item) => { + Some(Ok(NonPortModuleItem::TimeunitsDeclaration(item.clone()))) + } + NonPortInterfaceItem::GenerateRegion(region) => { + let mut region = region.clone(); + Some( + region + .nodes + .1 + .iter_mut() + .try_for_each(generate_item) + .map(|()| NonPortModuleItem::GenerateRegion(region)), + ) + } + NonPortInterfaceItem::InterfaceOrGenerateItem(item) => Some( + module_item(item) + .map(|item| NonPortModuleItem::ModuleOrGenerateItem(Box::new(item))), + ), + _ => Some(Err(unsupported("nested declaration in interface"))), + }) + .collect::>>()?; + Ok(ModuleDeclarationAnsi { + nodes: ( + ModuleAnsiHeader { + nodes: ( + header.0.clone(), + ModuleKeyword::Module(Box::new(header.1.clone())), + header.2.clone(), + ModuleIdentifier { + nodes: header.3.nodes.clone(), + }, + header.4.clone(), + header.5.clone(), + header.6.clone(), + header.7.clone(), + ), + }, + interface.nodes.1.clone(), + items, + interface.nodes.3.clone(), + interface.nodes.4.as_ref().map(|(colon, name)| { + ( + colon.clone(), + ModuleIdentifier { + nodes: name.nodes.clone(), + }, + ) + }), + ), + }) +} + +fn module_item( + item: &sv_parser::InterfaceOrGenerateItem, +) -> Converted { + let sv_parser::InterfaceOrGenerateItem::Module(item) = item else { + return Err(unsupported("extern subroutine in interface")); + }; + let mut common = item.nodes.1.clone(); + common_item(&mut common)?; + Ok(sv_parser::ModuleOrGenerateItem::ModuleItem(Box::new( + sv_parser::ModuleOrGenerateItemModuleItem { + nodes: (item.nodes.0.clone(), common), + }, + ))) +} + +fn generate_item(item: &mut sv_parser::GenerateItem) -> Converted<()> { + match item { + sv_parser::GenerateItem::InterfaceOrGenerateItem(interface) => { + *item = + sv_parser::GenerateItem::ModuleOrGenerateItem(Box::new(module_item(interface)?)); + } + sv_parser::GenerateItem::ModuleOrGenerateItem(item) => { + if let sv_parser::ModuleOrGenerateItem::ModuleItem(item) = item.as_mut() { + common_item(&mut item.nodes.1)?; + } + } + _ => return Err(unsupported("checker item in interface")), + } + Ok(()) +} + +fn block(block: &mut sv_parser::GenerateBlock) -> Converted<()> { + match block { + sv_parser::GenerateBlock::GenerateItem(item) => generate_item(item), + sv_parser::GenerateBlock::Multiple(block) => { + block.nodes.3.iter_mut().try_for_each(generate_item) + } + } +} + +fn common_item(item: &mut sv_parser::ModuleCommonItem) -> Converted<()> { + use sv_parser::*; + match item { + ModuleCommonItem::LoopGenerateConstruct(item) => block(&mut item.nodes.2)?, + ModuleCommonItem::ConditionalGenerateConstruct(item) => match item.as_mut() { + ConditionalGenerateConstruct::If(item) => { + block(&mut item.nodes.2)?; + if let Some((_, other)) = &mut item.nodes.3 { + block(other)?; + } + } + ConditionalGenerateConstruct::Case(item) => { + for case in &mut item.nodes.2 { + match case { + CaseGenerateItem::Nondefault(item) => block(&mut item.nodes.2)?, + CaseGenerateItem::Default(item) => block(&mut item.nodes.2)?, + } + } + } + }, + _ => {} + } + Ok(()) +} + +/// Analyze the original interface body and retain its symbols for the scope +/// that instantiates it. The structural view borrows every token's original +/// source location, including the lexical time scope of processes/functions. +pub(super) fn analyze( + declaration: &sv_parser::InterfaceDeclarationAnsi, + tree: &SyntaxTree, + path: &Path, + packages: &packages::Packages, + overrides: &HashMap, + interfaces: &ModuleInterfaces, + declarations_only: bool, +) -> Converted { + let view = module_view(declaration)?; + let node = RefNode::ModuleDeclarationAnsi(&view); + let mut imported = + imports::imported_symbols(node.clone(), tree, packages, packages.unit(path))?; + imported.declarations_only = declarations_only; + let name = module_name_from_node(node.clone(), tree)?; + let _timescales = timescales::install_for_tree(packages.timescales.clone(), tree)?; + Module::from_scope_node_with_parameter_overrides( + node, + tree, + &name, + overrides, + &InterfaceLookup { + local: interfaces, + extra: &ModuleInterfaces::default(), + }, + Arc::new(imported), + true, + ) +} + +pub(super) fn signature( + declaration: &sv_parser::InterfaceDeclarationAnsi, + tree: &SyntaxTree, + path: &Path, + packages: &packages::Packages, + name: String, + members: &[String], + names: &HashSet, +) -> Converted { + let mut view = module_view(declaration)?; + // Publishing a type contract must not require lowering the interface's + // executable processes. Keep declarations and their original locations. + view.nodes.2.retain(|item| match item { + sv_parser::NonPortModuleItem::TimeunitsDeclaration(_) => true, + sv_parser::NonPortModuleItem::ModuleOrGenerateItem(item) => matches!( + item.as_ref(), + sv_parser::ModuleOrGenerateItem::ModuleItem(item) + if matches!(&item.nodes.1, sv_parser::ModuleCommonItem::ModuleOrGenerateItemDeclaration(_)) + ), + _ => false, + }); + let node = RefNode::ModuleDeclarationAnsi(&view); + let imported = imports::imported_symbols(node.clone(), tree, packages, packages.unit(path))?; + let _timescales = timescales::install_for_tree(packages.timescales.clone(), tree)?; + let empty = ModuleInterfaces::default(); + let interfaces = InterfaceLookup { + local: &empty, + extra: &empty, + }; + let mut module = Module::from_module_node_with_parameter_overrides( + node, + tree, + "", + &HashMap::default(), + &interfaces, + Arc::new(imported.clone()), + )?; + // Internal signal lowering freezes localparam-dependent dimensions for + // execution. A public declaration must retain those dependencies so its + // consumers can specialize the interface with different header values. + let _scope = scope::install(Arc::new(imported.clone())); + let _functions = const_functions::install(module.constant_functions.clone()); + let mut env = imported.const_env.clone(); + extend_const_env_with_parameters(&mut env, &module.parameters); + let aliases = + type_aliases_from_module_node_with_env(RefNode::ModuleDeclarationAnsi(&view), tree, &env)?; + let declarations = declarations::signals_from_module_node_with_declaration_ranges( + RefNode::ModuleDeclarationAnsi(&view), + tree, + &env, + &aliases, + true, + )?; + let names = names + .iter() + .map(|name| (name.clone(), format!("h${name}"))) + .collect::>(); + let rename = scope::Renamer { names: &names }; + module.name = name; + module.ports = members + .iter() + .map(|name| { + let signal = declarations + .iter() + .find(|signal| signal.name() == name) + .ok_or_else(|| unsupported(format!("interface member `{name}`")))?; + Ok(Port::new( + rename.name(name), + PortDirection::Input, + rename.r#type(signal.r#type.clone()), + signal.is_net, + )) + }) + .collect::>()?; + module + .signals + .retain(|signal| !members.contains(&signal.name)); + for signal in &mut module.signals { + signal.name = rename.name(&signal.name); + signal.r#type = rename.r#type(signal.r#type.clone()); + } + module.parameters = module + .parameters + .into_iter() + .map(|p| rename.parameter(p)) + .collect(); + module.constant_functions = module + .constant_functions + .renamed(&mut |name| rename.name(name), &mut |stmt| rename.stmt(stmt)); + module.symbolic_functions = module + .symbolic_functions + .into_iter() + .map(|(name, function)| (rename.name(&name), rename.function(function))) + .collect(); + module.declaration_subroutines = module + .declaration_subroutines + .into_iter() + .map(|subroutine| { + let subroutine = subroutine.map( + &mut Into::into, + &mut |value| match value { + crate::ir::LValue::Ident(name) => LValue::Ident(name), + crate::ir::LValue::Select { + name, + msb, + lsb, + array_slice_width, + array_slice_reversed, + } => LValue::Select { + name, + msb: msb.into(), + lsb: lsb.into(), + array_slice_width: array_slice_width.map(Into::into), + array_slice_reversed, + signed: false, + is_2state: false, + }, + }, + &mut |ty| ty.map_range_expressions(|expr| rename.const_expr(expr.into()).into()), + ); + rename + .subroutine(subroutine) + .map(&mut Into::into, &mut Into::into, &mut |ty| ty) + }) + .collect(); + module.assignments.clear(); + module.comb_processes.clear(); + module.ff_processes.clear(); + module.initial_processes.clear(); + module.subroutines.clear(); + module.locals.clear(); + module.instances.clear(); + let ir = crate::analyze::analyze_source(Source { + modules: vec![module], + })?; + ir.modules() + .first() + .cloned() + .ok_or_else(|| unsupported("interface signature")) +} diff --git a/crates/celox-sv-analyzer/src/ast/interfaces.rs b/crates/celox-sv-analyzer/src/ast/interfaces.rs index 45cde2ff162..7ba98a8588c 100644 --- a/crates/celox-sv-analyzer/src/ast/interfaces.rs +++ b/crates/celox-sv-analyzer/src/ast/interfaces.rs @@ -1,32 +1,8 @@ -//! Interface elaboration by flattening. +//! Interface contracts and binding plans collected from authored declarations. //! -//! The declaration collectors work on modules, so every interface is expanded -//! into the modules that use it before analysis, as source text: -//! -//! - An interface instance `I #(...) h [N] ();` is replaced by the interface -//! items with each name declared in the interface scope renamed `h$name`: -//! the parameters become localparams, the variables become signals of the -//! instantiating module (the instance array dimensions in front of their -//! own), and the processes and functions are copied. The processes of an -//! instance array run once per element in a generate loop. -//! - An interface port `I.mp p` becomes one port `p$m` per member the modport -//! lists, in the modport direction, plus an input for each member that an -//! imported function reads. The interface parameters become parameters of -//! the module (`p$P`), its localparams and typedefs localparams of the -//! module header, and the imported functions functions of the module. -//! - A port without a modport (`I p`, or a generic `interface p`) exposes -//! every member. A member is an output when the module, or a child the port -//! is passed to, writes it, and an input otherwise. -//! - A module with a generic `interface` port is copied once per interface it -//! is bound to, as `M$I`. -//! - `h[i].m` becomes `h$m[i]`, `h.f(...)` becomes `h$f(...)`, and a port -//! connection `.p(h[i])` becomes one connection per member and parameter. -//! -//! `$` may continue but not start an identifier (IEEE 1800-2023 5.6), and the -//! generated names keep the SystemVerilog scoping of the names they replace. -//! A design with interfaces may not use `$` or escaped identifiers that are -//! not simple identifiers, so that generated names are valid and cannot -//! collide with its own. +//! Port directions and generic bindings are computed before semantic lowering. +//! `native_interfaces` binds bodies and references in the original syntax tree; +//! these contracts never generate or reparse SystemVerilog source. use std::path::Path; @@ -37,12 +13,11 @@ use super::*; const SEPARATOR: &str = "$"; /// Interface declarations exported for mixed-language type resolution. The -/// probe uses ordinary SV elaboration, including typedefs and parameter widths. +/// signature uses the original syntax tree, including typedefs and parameter widths. #[derive(Clone, Debug)] pub struct InterfacePrototype { pub name: String, - pub probe_name: String, - pub probe_source: String, + pub module: crate::ir::Module, pub time_declarations: String, pub modports: std::collections::BTreeMap>, pub parameters: Vec, @@ -55,13 +30,24 @@ pub struct InterfacePrototype { pub fn interface_prototypes( sources: &[(&str, &Path)], -) -> Result<(Vec, Vec), AnalyzerError> { +) -> Result, AnalyzerError> { + interface_prototypes_for(sources, None) +} + +pub fn interface_prototypes_for( + sources: &[(&str, &Path)], + selected: Option<&HashSet>, +) -> Result, AnalyzerError> { let files = sources .iter() .map(|(code, path)| File::new(code, path)) .collect::, _>>()?; let design = Design::collect(&files)?; - let mut declarations = design.interfaces.values().collect::>(); + let mut declarations = design + .interfaces + .values() + .filter(|interface| selected.is_none_or(|names| names.contains(&interface.name))) + .collect::>(); declarations.sort_by(|left, right| left.name.cmp(&right.name)); let timescales = if declarations.is_empty() { None @@ -74,126 +60,137 @@ pub fn interface_prototypes( .collect::>(), )?) }; - let signature_sources = files + let trees = files .iter() - .enumerate() - .map(|(index, file)| { - let edits = design - .modules - .values() - .filter(|module| module.file == index) - .map(|module| Edit { - span: module.span, - text: String::new(), - }) - .collect::>(); - apply(file.code, (0, file.code.len()), &edits) - }) - .collect(); + .zip(sources) + .map(|(file, (_, path))| (&file.syntax_tree, *path)) + .collect::>(); + let packages = packages::Packages::analyze(&trees)?; let mut used_names = design .modules .keys() .chain(design.interfaces.keys()) .cloned() .collect::>(); - Ok(( - declarations - .into_iter() - .map(|interface| { - let prefix = format!("__celox_interface_{}", interface.name); - let mut probe_name = prefix.clone(); - let mut index = 0; - while !used_names.insert(probe_name.clone()) { - probe_name = format!("{prefix}_{index}"); - index += 1; - } - let time_declarations = timescales - .as_ref() - .unwrap() - .declaration_statements(&interface.name)?; - let behavior_functions = interface - .items + declarations + .into_iter() + .map(|interface| { + let prefix = format!("__celox_interface_{}", interface.name); + let mut probe_name = prefix.clone(); + let mut index = 0; + while !used_names.insert(probe_name.clone()) { + probe_name = format!("{prefix}_{index}"); + index += 1; + } + let time_declarations = timescales + .as_ref() + .unwrap() + .declaration_statements(&interface.name)?; + let behavior_functions = interface + .items + .iter() + .filter_map(|item| match item { + Item::Process(span) => Some(*span), + Item::Member(index) => interface.members[*index].initializer, + _ => None, + }) + .flat_map(|span| interface.referenced(span)) + .filter(|name| interface.function(name).is_some()) + .map(str::to_string) + .collect::>(); + let behavior_captures = + interface.captured_members(&interface.function_closure(&behavior_functions)); + Ok(InterfacePrototype { + name: interface.name.clone(), + header_dependent_cast: interface.header_dependent_cast(&files[interface.file])?, + module: { + let file = &files[interface.file]; + let declaration = file + .syntax_tree + .into_iter() + .find_map(|node| { + if let RefNode::InterfaceDeclarationAnsi(declaration) = node + && name( + RefNode::InterfaceIdentifier(&declaration.nodes.0.nodes.3), + &file.syntax_tree, + ) + .ok() + .as_ref() + == Some(&interface.name) + { + Some(declaration) + } else { + None + } + }) + .ok_or_else(|| unsupported("non-ANSI interface signature"))?; + interface_ast::signature( + declaration, + &file.syntax_tree, + sources[interface.file].1, + &packages, + probe_name.clone(), + &interface + .members + .iter() + .map(|m| m.name.clone()) + .collect::>(), + &interface.names, + )? + }, + time_declarations, + parameters: interface + .parameters .iter() - .filter_map(|item| match item { - Item::Process(span) => Some(*span), - Item::Member(index) => interface.members[*index].initializer, - _ => None, + .map(|parameter| parameter.name.clone()) + .collect(), + driven: interface + .members + .iter() + .filter(|member| { + member.initializer.is_some() + || behavior_captures.get(&member.name) == Some(&Direction::Output) + || interface.references.iter().any(|(span, name)| { + name == &member.name + && interface.lvalues.contains(&span.0) + && !interface.functions.iter().any(|function| { + function.span.0 <= span.0 && span.1 <= function.span.1 + }) + }) }) - .flat_map(|span| interface.referenced(span)) - .filter(|name| interface.function(name).is_some()) - .map(str::to_string) - .collect::>(); - let behavior_captures = - interface.captured_members(&interface.function_closure(&behavior_functions)); - Ok(InterfacePrototype { - name: interface.name.clone(), - header_dependent_cast: interface - .header_dependent_cast(&files[interface.file])?, - probe_source: format!( - "module {}{probe_name}({} h); {time_declarations} endmodule", - if interface.automatic { - "automatic " - } else { - "" - }, - interface.name - ), - probe_name, - time_declarations, - parameters: interface - .parameters - .iter() - .map(|parameter| parameter.name.clone()) - .collect(), - driven: interface + .map(|member| member.name.clone()) + .collect(), + has_behavior: interface + .items + .iter() + .any(|item| matches!(item, Item::Process(_))) + || interface .members .iter() - .filter(|member| { - member.initializer.is_some() - || behavior_captures.get(&member.name) == Some(&Direction::Output) - || interface.references.iter().any(|(span, name)| { - name == &member.name - && interface.lvalues.contains(&span.0) - && !interface.functions.iter().any(|function| { - function.span.0 <= span.0 && span.1 <= function.span.1 - }) + .any(|member| member.initializer.is_some()), + modports: interface + .modports + .iter() + .map(|(name, items)| { + ( + name.clone(), + items + .iter() + .map(|item| match item { + ModportItem::Member(direction, name) => { + (name.clone(), direction.keyword().to_string()) + } + ModportItem::Import(name) => { + (name.clone(), "import".to_string()) + } }) - }) - .map(|member| member.name.clone()) - .collect(), - has_behavior: interface - .items - .iter() - .any(|item| matches!(item, Item::Process(_))) - || interface - .members - .iter() - .any(|member| member.initializer.is_some()), - modports: interface - .modports - .iter() - .map(|(name, items)| { - ( - name.clone(), - items - .iter() - .map(|item| match item { - ModportItem::Member(direction, name) => { - (name.clone(), direction.keyword().to_string()) - } - ModportItem::Import(name) => { - (name.clone(), "import".to_string()) - } - }) - .collect(), - ) - }) - .collect(), - }) + .collect(), + ) + }) + .collect(), }) - .collect::, AnalyzerError>>()?, - signature_sources, - )) + }) + .collect::, AnalyzerError>>() } type Span = (usize, usize); @@ -221,269 +218,6 @@ fn name(node: RefNode<'_>, syntax_tree: &SyntaxTree) -> Result String { - format!("{handle}{SEPARATOR}{item}") -} - -/// Rewrite `sources` so that they no longer use interfaces, or return `None` -/// when no source declares an interface. -pub fn elaborate_interfaces( - sources: &[(&str, &Path)], -) -> Result>, AnalyzerError> { - elaborate_interfaces_with_roots(sources, None) -} - -/// Interface bindings supplied by a foreign-language caller. Return the -/// specialized SV root names alongside the rewritten sources. -pub fn elaborate_interfaces_with_bindings( - sources: &[(&str, &Path)], - roots: &[(String, String, Vec<(String, String)>)], -) -> Result<(Option>, HashMap), AnalyzerError> { - let result = elaborate_interfaces_with_metadata(sources, roots)?; - Ok((result.sources, result.root_names)) -} - -/// Original interface port names, retained independently of generated names. -#[derive(Default)] -pub struct InterfaceElaboration { - pub sources: Option>, - pub root_names: HashMap, - pub interface_ports: HashMap>, -} - -pub fn elaborate_interfaces_with_metadata( - sources: &[(&str, &Path)], - roots: &[(String, String, Vec<(String, String)>)], -) -> Result { - elaborate_interfaces_with_metadata_and_roots(sources, roots, None) -} - -pub(crate) fn elaborate_interfaces_with_roots( - sources: &[(&str, &Path)], - roots: Option<&[&str]>, -) -> Result>, AnalyzerError> { - elaborate_interfaces_with_metadata_and_roots(sources, &[], roots).map(|result| result.sources) -} - -pub fn elaborate_interfaces_with_metadata_and_roots( - sources: &[(&str, &Path)], - bindings: &[(String, String, Vec<(String, String)>)], - roots: Option<&[&str]>, -) -> Result { - let files = sources - .iter() - .map(|(code, path)| File::new(code, path)) - .collect::, _>>()?; - let design = Design::collect(&files)?; - if design.interfaces.is_empty() { - return Ok(InterfaceElaboration::default()); - } - // Copied interface items lose their original time scope. Resolve their - // queries before copying, using all files' original scopes and precision. - // The original interface declarations remain in the rewritten sources, - // so their precision still contributes to module-level $root queries. - let trees: Vec<_> = files - .iter() - .zip(sources) - .map(|(file, (_, path))| (&file.syntax_tree, *path)) - .collect(); - let mut scales = super::timescales::Timescales::collect(&trees)?; - if let Some(roots) = roots { - scales.select_roots(roots); - } - let rewritten = resolve_interface_timescale_queries(&files, &scales)?; - let rewritten_files = rewritten - .as_ref() - .map(|codes| { - codes - .iter() - .zip(sources) - .map(|(code, (_, path))| File::new(code, path)) - .collect::, _>>() - }) - .transpose()?; - let files = rewritten_files.as_deref().unwrap_or(&files); - let rewritten_design = rewritten_files - .as_ref() - .map(|files| Design::collect(files)) - .transpose()?; - let design = rewritten_design.as_ref().unwrap_or(&design); - // Folding lexical queries changes offsets. Hierarchical queries must - // use the corresponding trees, collected once for all module rewrites. - let updated_scales = rewritten_files - .as_ref() - .map(|files| { - let trees: Vec<_> = files - .iter() - .zip(sources) - .map(|(file, (_, path))| (&file.syntax_tree, *path)) - .collect(); - let mut scales = super::timescales::Timescales::collect(&trees)?; - if let Some(roots) = roots { - scales.select_roots(roots); - } - Ok::<_, AnalyzerError>(scales) - }) - .transpose()?; - let scales = updated_scales.as_ref().unwrap_or(&scales); - // Generated names contain the separator; a source name containing it - // could collide with one. - for file in files { - for &start in &file.identifiers { - let index = file.tokens.partition_point(|&(token, _)| token < start); - let Some(&token) = file.tokens.get(index) else { - continue; - }; - let identifier = normalize_identifier(file.text(token)); - // A generated name joins plain identifiers. - if identifier.starts_with('\\') { - return Err(unsupported(format!( - "escaped identifier `{}` that is not a simple identifier in a design with interfaces", - identifier.trim_end() - ))); - } - if identifier.contains(SEPARATOR) { - return Err(unsupported(format!( - "identifier `{identifier}` containing `{SEPARATOR}` in a design with interfaces, which interface elaboration reserves for generated names" - ))); - } - } - } - let mut clones = Vec::new(); - let mut names = HashMap::default(); - for (alias, module_name, bindings) in bindings { - let Some(module) = design.modules.get(module_name) else { - continue; - }; - let mut generic = Vec::new(); - for (port, interface) in bindings { - let declaration = module - .port(port) - .and_then(|port| port.interface.as_ref()) - .ok_or_else(|| { - unsupported(format!( - "`{port}` of `{module_name}` is not an interface port" - )) - })?; - if let Some(expected) = &declaration.interface { - if expected != interface { - return Err(unsupported(format!( - "interface `{interface}` connected to `{module_name}.{port}` of type `{expected}`" - ))); - } - } else { - generic.push((port.clone(), interface.clone())); - } - } - generic.sort(); - if generic.is_empty() { - names.insert(alias.clone(), module_name.clone()); - } else { - names.insert(alias.clone(), clone_module_name(module_name, &generic)); - clones.push((module_name.clone(), generic)); - } - } - let interface_ports = design - .modules - .iter() - .map(|(name, module)| { - ( - name.clone(), - module - .ports - .iter() - .filter(|port| port.interface.is_some()) - .map(|port| port.name.clone()) - .collect(), - ) - }) - .collect(); - Ok(InterfaceElaboration { - sources: Some(design.elaborate_with_roots(clones, scales)?), - root_names: names, - interface_ports, - }) -} - -fn resolve_interface_timescale_queries( - files: &[File<'_>], - scales: &super::timescales::Timescales, -) -> Result>, AnalyzerError> { - let is_query = |call, tree| { - matches!( - called_system_function(call, tree), - Some(SystemFunction::Timeunit | SystemFunction::Timeprecision) - ) - }; - let mut changed = false; - let codes = files - .iter() - .map(|file| { - let mut edits = Vec::new(); - for interface in &file.syntax_tree { - if !matches!(interface, RefNode::InterfaceDeclaration(_)) { - continue; - } - // Macro expansion origins may point into a shared definition, - // not the call in this interface. Leave such text untouched; - // check_context rejects copying macro-bearing interfaces. - if has_directive(file.text(file.span(interface.clone())?)) { - continue; - } - for node in interface { - match node { - RefNode::SystemTfCall(call) if is_query(call, &file.syntax_tree) => { - let value = scales.query(call, &file.syntax_tree)?; - edits.push(Edit { - span: file.span(node)?, - // An unsized decimal and its unary minus retain - // the query's 32-bit signed integer result type. - text: format!("({value})"), - }); - } - RefNode::SubroutineCallStatement(statement) => { - let call = match statement { - sv_parser::SubroutineCallStatement::SubroutineCall(call) => &call.0, - sv_parser::SubroutineCallStatement::Function(call) => { - &call.nodes.2.nodes.1.nodes.0 - } - }; - if let sv_parser::SubroutineCall::SystemTfCall(call) = call - && is_query(call, &file.syntax_tree) - { - // These queries have no side effects. Still - // validate the operand before discarding it. - scales.query(call, &file.syntax_tree)?; - edits.push(Edit { - span: file.span(node)?, - text: ";".into(), - }); - } - } - _ => {} - } - } - } - changed |= !edits.is_empty(); - Ok(apply(file.code, (0, file.code.len()), &edits)) - }) - .collect::>()?; - Ok(changed.then_some(codes)) -} - -/// Reject a rewrite that would edit a macro origin rather than its call. -fn check_query_origin( - file: &File<'_>, - text: Option<&str>, - span: Span, -) -> Result<(), AnalyzerError> { - if file.text(span).trim() != text.unwrap_or_default().trim() { - return Err(unsupported("macro-origin interface timescale query")); - } - Ok(()) -} - -/// A parsed source and its tokens. struct File<'a> { code: &'a str, syntax_tree: SyntaxTree, @@ -495,13 +229,6 @@ struct File<'a> { /// and of struct and union member names, which live in other name spaces /// than handles. type_names: HashSet, - print_tasks: Vec, -} - -struct PrintTask { - span: Span, - call: sv_parser::SystemTfCall, - site: system_functions::CallSite, } impl<'a> File<'a> { @@ -574,50 +301,13 @@ impl<'a> File<'a> { .collect(); tokens.sort_unstable(); tokens.dedup(); - let mut file = Self { + let file = Self { code, syntax_tree, tokens, identifiers, type_names, - print_tasks: Vec::new(), }; - let statements: HashSet<_> = file - .syntax_tree - .into_iter() - .filter_map(|node| { - let RefNode::SubroutineCallStatement( - sv_parser::SubroutineCallStatement::SubroutineCall(statement), - ) = node - else { - return None; - }; - let sv_parser::SubroutineCall::SystemTfCall(call) = &statement.0 else { - return None; - }; - file.node_span(RefNode::SystemTfCall(call)) - }) - .collect(); - for node in &file.syntax_tree { - let RefNode::SystemTfCall(call) = node else { - continue; - }; - if called_system_task(call, &file.syntax_tree) != Some(SystemTask::Printtimescale) { - continue; - } - let span = file.span(RefNode::SystemTfCall(call))?; - let site = if statements.contains(&span) { - system_functions::CallSite::Statement(system_functions::Body::Subroutine) - } else { - system_functions::CallSite::Expression - }; - file.print_tasks.push(PrintTask { - span, - call: call.clone(), - site, - }); - } - file.print_tasks.sort_by_key(|task| task.span.0); Ok(file) } @@ -660,62 +350,6 @@ impl<'a> File<'a> { && self.text(self.tokens[index - 2]) == "$unit" } - /// Whether `span` has a use `.name.` or `.name[` of `name` after one of - /// the generate block names `blocks`, such as `g.h.x` or `g[0].h.x` for - /// an instance `h` in a generate block `g`. - fn has_qualified_use(&self, span: Span, name: &str, blocks: &HashSet) -> bool { - let first = self.tokens.partition_point(|&(start, _)| start < span.0); - let last = self.tokens.partition_point(|&(start, _)| start < span.1); - (first.max(2)..last).any(|index| { - let token = self.tokens[index]; - if !self.identifiers.contains(&token.0) - || normalize_identifier(self.text(token)) != name - || self.text(self.tokens[index - 1]) != "." - || !matches!(self.next_token(token.1), Some("." | "[")) - { - return false; - } - // Every qualifier before the dot, after its selects, back to the - // first, must name a generate block. - let mut qualifier = index - 2; - loop { - while self.text(self.tokens[qualifier]) == "]" { - let mut depth = 0usize; - loop { - match self.text(self.tokens[qualifier]) { - "]" => depth += 1, - "[" => { - depth -= 1; - if depth == 0 { - break; - } - } - _ => {} - } - if qualifier == 0 { - return false; - } - qualifier -= 1; - } - if qualifier == 0 { - return false; - } - qualifier -= 1; - } - let token = self.tokens[qualifier]; - if !self.identifiers.contains(&token.0) - || !blocks.contains(&normalize_identifier(self.text(token))) - { - return false; - } - if qualifier < 2 || self.text(self.tokens[qualifier - 1]) != "." { - return true; - } - qualifier -= 2; - } - }) - } - /// The references `h.item` and bare `h` in `span` to a name /// `h` that `is_handle` accepts. The references are found in the tokens, /// as the parser represents `h.item` either as a hierarchical name or as @@ -811,42 +445,6 @@ fn origin_span(syntax_tree: &SyntaxTree, locate: &Locate) -> Option { )) } -/// A source text replacement. -#[derive(Debug, Clone)] -struct Edit { - span: Span, - text: String, -} - -/// `text[span]` with the edits inside it applied. An edit nested in an -/// earlier one is dropped: the outer edit's text already accounts for it. -fn apply(text: &str, span: Span, edits: &[Edit]) -> String { - let mut edits: Vec<&Edit> = edits - .iter() - .filter(|edit| edit.span.0 >= span.0 && edit.span.1 <= span.1) - .collect(); - // At one offset, an insertion goes before a replacement that starts there. - edits.sort_by_key(|edit| { - ( - edit.span.0, - edit.span.1 != edit.span.0, - std::cmp::Reverse(edit.span.1), - ) - }); - let mut result = String::new(); - let mut cursor = span.0; - for edit in edits { - if edit.span.0 < cursor { - continue; - } - result.push_str(&text[cursor..edit.span.0]); - result.push_str(&edit.text); - cursor = edit.span.1; - } - result.push_str(&text[cursor..span.1]); - result -} - #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Direction { Input, @@ -870,35 +468,17 @@ struct InterfaceParameter { default: Option, } -/// How a constant item of an interface is declared in a module header. +/// Imports needed to infer calls made by interface members. enum HeaderForm { - /// `localparam ` for a `localparam` or `parameter` declaration; - /// the span covers the data type and the assignments. - Parameter(Span), - /// `localparam type = ` for a `typedef`. - TypeAlias { name: Span, data_type: Span }, - /// `localparam type `; the span covers the type assignments. - LocalType(Span), - /// A package import, inserted in the module header, and what it imports: - /// `(package, item)`, with no item for a wildcard import. A - /// compilation-unit import before the interface is copied as well, as - /// packages are inlined only for imports inside a module. + Constant, Import { - span: Span, imports: Vec<(String, Option)>, }, } -enum MemberKind { - Variable, - /// A net, with its net type keyword. - Net(Span), -} - /// A variable or net declared in the interface scope. struct Member { name: String, - kind: MemberKind, /// The declared data type, unless implicit. data_type: Option, /// The unpacked dimensions of the declarator. @@ -920,7 +500,7 @@ enum Item { header: HeaderForm, }, Member(usize), - Function(usize), + Function, /// A process, continuous assignment, genvar, or generate construct. Process(Span), } @@ -938,9 +518,6 @@ struct InterfaceDecl { /// Whether the header has a parameter port list, which makes a body /// `parameter` a localparam. has_parameter_port_list: bool, - /// Whether the variables of its subroutines and blocks are automatic by - /// default: `interface automatic`. - automatic: bool, /// Whether the declaration uses macros or other compiler directives. uses_macros: bool, /// Whether the declaration refers to compilation-unit items of its file. @@ -1007,15 +584,6 @@ impl InterfaceDecl { self.functions.iter().find(|function| function.name == name) } - fn is_constant(&self, name: &str) -> bool { - self.parameters - .iter() - .any(|parameter| parameter.name == name) - || (self.names.contains(name) - && self.member(name).is_none() - && self.function(name).is_none()) - } - /// The interface-scope names that `span` refers to. fn referenced(&self, span: Span) -> impl Iterator { self.references @@ -1045,51 +613,6 @@ impl InterfaceDecl { .collect() } - /// Reject copying the interface into a module that starts at - /// `module_start` of `file` when the copy would lose its context: macros, - /// whose expansion `render` cannot rename, compilation-unit items, which - /// another file or an earlier module does not see, and a default lifetime - /// other than the module's, which its copied locals would take instead. - fn check_context( - &self, - file: &File<'_>, - interface_file: &File<'_>, - module_start: usize, - ) -> Result<(), AnalyzerError> { - if self.uses_macros { - return Err(unsupported(format!( - "macro or compiler directive in interface `{}`", - self.name - ))); - } - if self.uses_unit_items - && (!std::ptr::eq(file, interface_file) || module_start < self.start) - { - return Err(unsupported(format!( - "compilation-unit item in interface `{}`, which a module of another source file or before it uses", - self.name - ))); - } - let module_automatic = file.syntax_tree.into_iter().any(|node| match node { - RefNode::ModuleDeclarationAnsi(module) => { - file.span(RefNode::ModuleDeclarationAnsi(module)) - .is_ok_and(|span| span.0 <= module_start && module_start < span.1) - && matches!( - module.nodes.0.nodes.2, - Some(sv_parser::Lifetime::Automatic(_)) - ) - } - _ => false, - }); - if self.automatic != module_automatic { - return Err(unsupported(format!( - "interface `{}` with a default lifetime other than that of the module it is used in", - self.name - ))); - } - Ok(()) - } - /// The spans of parameter, constant and member declarations. fn declaration_spans(&self) -> Vec { let mut spans = Vec::new(); @@ -1106,7 +629,7 @@ impl InterfaceDecl { spans.extend(member.data_type); spans.extend(member.dimensions.iter().copied()); } - Item::Function(_) | Item::Process(_) => {} + Item::Function | Item::Process(_) => {} } } spans @@ -1132,12 +655,6 @@ impl InterfaceDecl { .filter(|name| self.member(name).is_some()) } - /// Whether `function`, or a function it calls, accesses a member. - fn accesses_members(&self, function: &str) -> bool { - let closure = self.function_closure(&HashSet::from_iter([function.to_string()])); - !self.captured_members(&closure).is_empty() - } - /// The members that `functions` access: an output for a member one of /// them assigns, an input for one they only read. fn captured_members(&self, functions: &[String]) -> HashMap { @@ -1169,7 +686,6 @@ struct InterfacePort { struct PortDecl { name: String, - span: Span, interface: Option, /// Whether the module may write the actual (`output`, `inout`, `ref`). writes: bool, @@ -1180,8 +696,6 @@ struct ModuleDecl { file: usize, span: Span, ports: Vec, - /// The parameters an instantiation may override, in order. - parameters: Vec, } impl ModuleDecl { @@ -1249,16 +763,6 @@ impl Handles { self.by_name.entry(name).or_default().push((scope, handle)); } - fn contains(&self, name: &str) -> bool { - self.by_name.contains_key(name) - } - - fn declared_in(&self, name: &str, scope: Span) -> bool { - self.by_name - .get(name) - .is_some_and(|handles| handles.iter().any(|(declared, _)| *declared == scope)) - } - /// The handle `name` refers to at `span`: the one of the innermost /// scope around it. fn at(&self, name: &str, span: Span) -> Option<&Handle> { @@ -1269,14 +773,6 @@ impl Handles { .min_by_key(|(scope, _)| scope.1 - scope.0) .map(|(_, handle)| handle) } - - fn all(&self) -> impl Iterator { - self.by_name.values().flatten().map(|(_, handle)| handle) - } - - fn is_empty(&self) -> bool { - self.by_name.is_empty() - } } /// A child instantiation found in a module body: its module, the formal @@ -1300,8 +796,6 @@ struct Design<'a> { modules: HashMap, /// The ports of every subroutine declared or imported, by name. subroutines: HashMap>, - /// The names each package declares. - packages: HashMap>, expansions: std::cell::RefCell>, /// The expansions being computed, to reject a recursive instantiation. expanding: std::cell::RefCell>, @@ -1433,7 +927,6 @@ impl<'a> Design<'a> { .map(|(span, imports)| Item::Constant { span: *span, header: HeaderForm::Import { - span: *span, imports: imports.clone(), }, }) @@ -1489,7 +982,6 @@ impl<'a> Design<'a> { interfaces, modules, subroutines, - packages, expansions: Default::default(), expanding: Default::default(), }) @@ -1516,68 +1008,6 @@ impl<'a> Design<'a> { Err(unsupported(format!("module `{}`", module.name))) } - fn elaborate_with_roots( - &self, - mut clones: Vec<(String, Vec<(String, String)>)>, - scales: &super::timescales::Timescales, - ) -> Result, AnalyzerError> { - let mut edits: Vec> = vec![Vec::new(); self.files.len()]; - let mut names: Vec = self.modules.keys().cloned().collect(); - names.sort(); - let mut cloned: HashSet = HashSet::default(); - for name in &names { - let module = &self.modules[name]; - if module.ports.iter().any(|port| { - port.interface - .as_ref() - .is_some_and(|port| port.interface.is_none()) - }) { - // Copied per binding below; the original is not usable. - continue; - } - if let Some(text) = self.rewrite_module(name, &[], None, &mut clones, scales)? { - let module = &self.modules[name]; - edits[module.file].push(Edit { - span: module.span, - text, - }); - } - } - while let Some((name, bindings)) = clones.pop() { - let clone_name = clone_module_name(&name, &bindings); - if !cloned.insert(clone_name.clone()) { - continue; - } - let text = match self.rewrite_module( - &name, - &bindings, - Some(&clone_name), - &mut clones, - scales, - )? { - Some(text) => text, - None => { - let module = &self.modules[&name]; - self.files[module.file].text(module.span).to_string() - } - }; - // Beside the original, under the same compiler directives. - let module = &self.modules[&name]; - edits[module.file].push(Edit { - span: (module.span.1, module.span.1), - text: format!("\n{text}\n"), - }); - } - Ok(self - .files - .iter() - .zip(edits) - .map(|(file, edits)| apply(file.code, (0, file.code.len()), &edits)) - .collect()) - } - - /// The members and functions that `port` of `module` carries when it is - /// bound to `interface` and its other generic ports as `bindings` says. fn expansion( &self, module: &str, @@ -1802,85 +1232,6 @@ impl<'a> Design<'a> { }) } - /// Reject a module that the expansion would give package items of one - /// name from two packages, or a declaration hiding one. The imports of - /// the interfaces it uses move into its scope, where packages are - /// inlined by plain name. - fn check_imported_names( - &self, - module_name: &str, - declaration: &sv_parser::ModuleDeclarationAnsi, - file: &File<'_>, - handles: &Handles, - ) -> Result<(), AnalyzerError> { - let mut used: Vec<&str> = handles - .all() - .map(|handle| handle.interface.as_str()) - .collect(); - used.sort_unstable(); - used.dedup(); - let names = |(package, item): &(String, Option)| -> Vec { - match item { - Some(item) => vec![item.clone()], - None => self - .packages - .get(package) - .map(|names| names.iter().cloned().collect()) - .unwrap_or_default(), - } - }; - let mut imported: HashMap = HashMap::default(); - let add = |import: &(String, Option), - imported: &mut HashMap| - -> Result<(), AnalyzerError> { - for item in names(import) { - if let Some(other) = imported.insert(item.clone(), import.0.clone()) - && other != import.0 - { - return Err(unsupported(format!( - "package items `{other}::{item}` and `{}::{item}` in module `{module_name}`, one of them imported through an interface", - import.0 - ))); - } - } - Ok(()) - }; - for interface in used { - for item in &self.interface(interface)?.items { - if let Item::Constant { - header: HeaderForm::Import { imports, .. }, - .. - } = item - { - for import in imports { - add(import, &mut imported)?; - } - } - } - } - if imported.is_empty() { - return Ok(()); - } - let own = module_scope_names(declaration, file)?; - if let Some(name) = own.iter().find(|name| imported.contains_key(*name)) { - return Err(unsupported(format!( - "declaration of `{name}` in module `{module_name}`, which hides the package item `{}::{name}` of an interface it uses", - imported[name] - ))); - } - // Imports in subroutines and blocks are visible only there. - let module_span = file.span(RefNode::ModuleDeclarationAnsi(declaration))?; - for (_, imports) in scoped_imports(RefNode::ModuleDeclarationAnsi(declaration), file)? - .into_iter() - .filter(|(scope, _)| *scope == module_span) - { - for import in imports { - add(&import, &mut imported)?; - } - } - Ok(()) - } - /// The interface accesses of a module body, by handle name. `bound` /// names a port and the interface it is bound to. fn module_uses( @@ -2120,1071 +1471,6 @@ impl<'a> Design<'a> { } Ok(uses) } - - /// The text of `module_name` with its interfaces expanded, or `None` when - /// it uses none. A clone is renamed `clone_name` and binds its generic - /// ports as `bindings` says. Clones of children are pushed to `clones`. - fn rewrite_module( - &self, - module_name: &str, - bindings: &[(String, String)], - clone_name: Option<&str>, - clones: &mut Vec<(String, Vec<(String, String)>)>, - scales: &super::timescales::Timescales, - ) -> Result, AnalyzerError> { - let module = &self.modules[module_name]; - let file = &self.files[module.file]; - let declaration = self.module_node(module)?; - let module_span = module.span; - - // The interface handles: ports first, then instances. - let mut handles = Handles::default(); - let interface_ports: Vec<(String, InterfacePort, Span)> = module - .ports - .iter() - .filter_map(|port| { - port.interface - .clone() - .map(|interface| (port.name.clone(), interface, port.span)) - }) - .collect(); - let mut port_interfaces = Vec::new(); - for (port, interface_port, port_span) in &interface_ports { - let interface = match &interface_port.interface { - Some(interface) => interface.clone(), - None => bindings - .iter() - .find(|(name, _)| name == port) - .map(|(_, interface)| interface.clone()) - .ok_or_else(|| { - unsupported(format!( - "generic interface port `{port}` of module `{module_name}` without a binding" - )) - })?, - }; - let expansion = self.expansion(module_name, port, &interface, bindings)?; - handles.insert( - port.clone(), - module_span, - Handle { - interface: interface.clone(), - port: Some(expansion.clone()), - arrayed: !interface_port.dimensions.is_empty(), - }, - ); - port_interfaces.push(( - port.clone(), - interface, - expansion, - interface_port.clone(), - *port_span, - )); - } - let mut interface_instantiations = Vec::new(); - let mut child_instantiations = Vec::new(); - // An instance belongs to the innermost generate block around it. - let mut blocks = Vec::new(); - // The generate blocks that are a single item without `begin`. - let mut bare_blocks = HashSet::default(); - let mut block_names = HashSet::default(); - for node in RefNode::ModuleDeclarationAnsi(declaration) { - if let RefNode::GenerateBlockIdentifier(identifier) = node { - block_names.insert(name( - RefNode::GenerateBlockIdentifier(identifier), - &file.syntax_tree, - )?); - } - if let RefNode::GenerateBlock(block) = node { - let span = file.node_span(RefNode::GenerateBlock(block)); - blocks.extend(span); - if let (Some(span), sv_parser::GenerateBlock::GenerateItem(_)) = (span, block) { - bare_blocks.insert(span); - } - } - } - for node in RefNode::ModuleDeclarationAnsi(declaration) { - if let RefNode::ModuleInstantiation(instantiation) = node { - let type_name = name( - RefNode::ModuleIdentifier(&instantiation.nodes.0), - &file.syntax_tree, - )?; - if self.interfaces.contains_key(&type_name) { - let statement = file.span(RefNode::ModuleInstantiation(instantiation))?; - let scope = blocks - .iter() - .filter(|block| block.0 <= statement.0 && statement.1 <= block.1) - .min_by_key(|block| block.1 - block.0) - .copied() - .unwrap_or(module_span); - for instance in instantiation.nodes.2.contents() { - let instance_name = name( - RefNode::InstanceIdentifier(&instance.nodes.0.nodes.0), - &file.syntax_tree, - )?; - let handle = Handle { - interface: type_name.clone(), - port: None, - arrayed: !instance.nodes.0.nodes.1.is_empty(), - }; - if scope != module_span - && file.has_qualified_use(module_span, &instance_name, &block_names) - { - return Err(unsupported(format!( - "hierarchical reference to interface instance `{instance_name}` through a generate block" - ))); - } - if handles.declared_in(&instance_name, scope) { - return Err(AnalyzerError::DuplicateInstance { - module: module_name.to_string(), - name: instance_name, - }); - } - handles.insert(instance_name, scope, handle); - } - interface_instantiations.push(instantiation); - } else if self - .modules - .get(&type_name) - .is_some_and(ModuleDecl::has_interface_ports) - { - child_instantiations.push(instantiation); - } - } - } - let qualified_time_query = - RefNode::ModuleDeclarationAnsi(declaration) - .into_iter() - .any(|node| { - let RefNode::SystemTfCall(call) = node else { - return false; - }; - super::timescales::is_timescale_call(call, &file.syntax_tree) - && super::timescales::argument(call).is_some_and(|argument| { - file.syntax_tree - .get_str_trim(argument) - .is_some_and(|text| text.contains('.')) - }) - }); - if handles.is_empty() - && child_instantiations.is_empty() - && clone_name.is_none() - && !qualified_time_query - { - return Ok(None); - } - let path_query = qualified_time_query - .then(|| scales.interface_path_queries(&file.syntax_tree)) - .transpose()?; - self.check_imported_names(module_name, declaration, file, &handles)?; - // Handle references are found by name, so no declaration may reuse - // the name of a handle. - for declared in declared_names( - RefNode::ModuleDeclarationAnsi(declaration), - &file.syntax_tree, - )? { - if handles.contains(&declared) { - return Err(unsupported(format!( - "declaration of `{declared}` in module `{module_name}`, which shadows an interface" - ))); - } - } - - // References to interface items through a handle: `h[i].m`, `h.f(...)`. - let mut references = Vec::new(); - // Member references with element selects, whose selects may contain - // references themselves: `(span, flattened name, selects)`. - let mut selected = Vec::new(); - let mut consumed: Vec = Vec::new(); - // A bare interface handle is legal as a timescale query operand. - // Resolve it using the instance/port binding before that handle is - // flattened away, including each clone of a generic interface port. - let query_edit = |call: &sv_parser::SystemTfCall, - site| - -> Result, AnalyzerError> { - let Some((function, args)) = system_tf_call_parts(call, &file.syntax_tree) else { - return Ok(None); - }; - if !super::timescales::is_timescale_call(call, &file.syntax_tree) { - return Ok(None); - } - let Some(argument) = super::timescales::argument(call) else { - return Ok(None); - }; - let name = - normalize_identifier(file.syntax_tree.get_str_trim(argument).unwrap_or_default()); - let (span, text) = if handles.contains(&name) { - system_functions::check_call(function, args.as_deref(), site)?; - let span = file.span(RefNode::SystemTfCall(call))?; - let handle = handles.at(&name, span).ok_or_else(|| { - unsupported(format!("reference to interface `{name}` outside the generate block that declares it")) - })?; - if handle.arrayed { - return Err(unsupported("interface array in timescale query")); - } - ( - span, - scales.interface_replacement( - call, - &file.syntax_tree, - &handle.interface, - &name, - site, - )?, - ) - } else if name.contains('.') { - // Keep ordinary module queries for the module analyzer. Only - // a path ending at an interface must be frozen here. - let Some(text) = path_query.as_ref().unwrap()(call, site).ok().flatten() else { - return Ok(None); - }; - (file.span(RefNode::SystemTfCall(call))?, text) - } else { - return Ok(None); - }; - check_query_origin(file, file.syntax_tree.get_str_trim(call), span)?; - Ok(Some(Edit { - span, - // Preserve the query's self-determined signed integer type, - // including when it initializes a child module's output. - text, - })) - }; - for node in RefNode::ModuleDeclarationAnsi(declaration) { - let edit = match node { - RefNode::SystemTfCall(call) - if called_system_task(call, &file.syntax_tree) - != Some(SystemTask::Printtimescale) => - { - query_edit(call, system_functions::CallSite::Expression)? - } - RefNode::SubroutineCallStatement(statement) => { - let call = match statement { - sv_parser::SubroutineCallStatement::SubroutineCall(call) => &call.0, - sv_parser::SubroutineCallStatement::Function(call) => { - &call.nodes.2.nodes.1.nodes.0 - } - }; - let site = - if matches!(statement, sv_parser::SubroutineCallStatement::Function(_)) { - system_functions::CallSite::Expression - } else { - system_functions::CallSite::Statement( - system_functions::Body::Subroutine, - ) - }; - if let sv_parser::SubroutineCall::SystemTfCall(call) = call - && let Some(edit) = query_edit(call, site)? - { - let span = file.span(node.clone())?; - check_query_origin(file, file.syntax_tree.get_str_trim(statement), span)?; - Some(Edit { - span, - text: if called_system_task(call, &file.syntax_tree) - == Some(SystemTask::Printtimescale) - { - format!("{};", edit.text) - } else { - ";".into() - }, - }) - } else { - None - } - } - _ => None, - }; - if let Some(edit) = edit { - consumed.push(edit.span); - references.push(edit); - } - } - // Bare handles and modport selections, valid only as port connections. - let mut pending: Vec<(Span, String)> = Vec::new(); - for reference in file.handle_references(module_span, |name| handles.contains(name)) { - if consumed - .iter() - .any(|span| span.0 <= reference.span.0 && reference.span.1 <= span.1) - { - continue; - } - let handle = handles - .at(&reference.handle, reference.span) - .ok_or_else(|| { - unsupported(format!( - "reference to interface `{}` outside the generate block that declares it", - reference.handle - )) - })?; - let interface = self.interface(&handle.interface)?; - let Some((item, item_span)) = reference.item else { - pending.push((reference.span, reference.handle)); - continue; - }; - let span = (reference.span.0, item_span.1); - let text = if interface.member(&item).is_some() { - if let Some(expansion) = &handle.port - && (expansion.direction(&item).is_none() - || expansion - .accessible - .as_ref() - .is_some_and(|accessible| !accessible.contains(&item))) - { - return Err(unsupported(format!( - "access of `{}.{item}`, which the modport of port `{}` does not list", - reference.handle, reference.handle - ))); - } - let name = joined(&reference.handle, &item); - match reference.selects { - Some(selects) => { - selected.push((span, name, selects)); - continue; - } - None => name, - } - } else if interface.function(&item).is_some() { - let reachable = match &handle.port { - Some(expansion) => expansion - .callable - .as_ref() - .is_none_or(|callable| callable.contains(&item)), - None => true, - }; - if !reachable { - return Err(unsupported(format!( - "call of `{}.{item}`, which the modport of port `{}` does not import", - reference.handle, reference.handle - ))); - } - if reference.selects.is_some() || handle.arrayed { - return Err(unsupported(format!( - "call of a function of the interface array `{}`", - reference.handle - ))); - } - joined(&reference.handle, &item) - } else if interface.is_constant(&item) { - joined(&reference.handle, &item) - } else if interface.modports.contains_key(&item) { - pending.push((span, reference.handle)); - continue; - } else { - return Err(unsupported(format!( - "`{}.{item}`: interface `{}` has no item `{item}`", - reference.handle, handle.interface - ))); - }; - references.push(Edit { span, text }); - } - // Inner references first, so that each select is rendered with them. - selected.sort_by_key(|(span, _, _): &(Span, String, Span)| span.1 - span.0); - for (span, name, selects) in selected { - let selects = apply(file.code, selects, &references); - references.push(Edit { - span, - text: format!("{name}{}", selects.trim()), - }); - } - - let mut edits: Vec = Vec::new(); - let render = |span: Span, references: &[Edit]| apply(file.code, span, references); - - // Interface instances are replaced by their items. - for instantiation in &interface_instantiations { - let statement = file.span(RefNode::ModuleInstantiation(instantiation))?; - let interface = self.interface(&name( - RefNode::ModuleIdentifier(&instantiation.nodes.0), - &file.syntax_tree, - )?)?; - let overrides = parameter_overrides( - instantiation.nodes.1.as_ref(), - &interface - .parameters - .iter() - .map(|parameter| parameter.name.clone()) - .collect::>(), - file, - )?; - // The instantiation disappears, so no later check sees an - // unknown or repeated parameter. - let mut overridden = HashSet::default(); - if let Some((parameter, _)) = overrides - .iter() - .find(|(parameter, _)| !overridden.insert(parameter)) - { - return Err(AnalyzerError::DuplicateInterfaceParameterOverride { - interface: interface.name.clone(), - name: parameter.clone(), - }); - } - if let Some((parameter, _)) = overrides.iter().find(|(parameter, _)| { - !interface - .parameters - .iter() - .any(|declared| declared.name == *parameter) - }) { - return Err(AnalyzerError::UnknownInterfaceParameter { - interface: interface.name.clone(), - name: parameter.clone(), - }); - } - let mut text = String::new(); - for instance in instantiation.nodes.2.contents() { - check_no_connections(instance, &interface.name)?; - let instance_name = name( - RefNode::InstanceIdentifier(&instance.nodes.0.nodes.0), - &file.syntax_tree, - )?; - let dimensions = instance - .nodes - .0 - .nodes - .1 - .iter() - .map(|dimension| { - Ok((file.span(RefNode::UnpackedDimension(dimension))?, dimension)) - }) - .collect::, AnalyzerError>>()?; - let overrides: Vec<(String, String)> = overrides - .iter() - .map(|(parameter, value)| (parameter.clone(), render(*value, &references))) - .collect(); - // Expansions may end in a keyword such as `endfunction`. - if !text.is_empty() { - text.push_str("\n "); - } - text.push_str(&self.instance_text( - interface, - &instance_name, - &dimensions, - &overrides, - file, - module_span.0, - &|span| render(span, &references), - scales, - )?); - } - // The items replacing the bare item of a generate construct - // need a block to stay in it. - if blocks - .iter() - .filter(|block| block.0 <= statement.0 && statement.1 <= block.1) - .min_by_key(|block| block.1 - block.0) - .is_some_and(|block| bare_blocks.contains(block)) - { - text = format!("begin\n {text}\n end"); - } - edits.push(Edit { - span: statement, - text, - }); - consumed.push(statement); - } - - // Child instantiations pass interfaces as members and parameters. - for instantiation in &child_instantiations { - let child_name = name( - RefNode::ModuleIdentifier(&instantiation.nodes.0), - &file.syntax_tree, - )?; - let instances = instantiation.nodes.2.contents(); - if instances.len() != 1 { - return Err(unsupported(format!( - "several instances of `{child_name}` in one instantiation, which has interface ports" - ))); - } - let instance = instances[0]; - let child_ports: Vec<(String, Option)> = self.modules[&child_name] - .ports - .iter() - .map(|port| (port.name.clone(), port.interface.clone())) - .collect(); - let child_parameters = self.modules[&child_name].parameters.clone(); - let mut child_bindings = Vec::new(); - let mut connection_texts = Vec::new(); - let mut parameter_texts = Vec::new(); - let actuals = connections(instance, &self.modules[&child_name], file, true)?; - // The interfaces bound to the child's generic ports, which every - // expansion of the child needs. - let mut generic_bindings = Vec::new(); - for (formal, actual) in &actuals { - if let Some((_, Some(formal_port))) = - child_ports.iter().find(|(name, _)| name == formal) - && formal_port.interface.is_none() - && let Connection::Explicit(Some(expression)) = actual - && let Some(actual) = actual_handle(expression, file)? - && let Some(handle) = - handles.at(&actual.handle, file.span(RefNode::Expression(expression))?) - { - generic_bindings.push((formal.clone(), handle.interface.clone())); - } - } - generic_bindings.sort(); - for (formal, actual) in actuals { - let Some((_, Some(formal_port))) = - child_ports.iter().find(|(name, _)| *name == formal) - else { - connection_texts.push(match actual { - Connection::Explicit(Some(expression)) => format!( - ".{formal}({})", - render(file.span(RefNode::Expression(expression))?, &references) - ), - Connection::Explicit(None) => format!(".{formal}()"), - Connection::Implicit => format!(".{formal}"), - }); - continue; - }; - // `connections` gives no implicit connection to an - // interface port. - let Connection::Explicit(actual) = actual else { - unreachable!("implicit connection to interface port `{formal}`"); - }; - let expression = actual.ok_or_else(|| { - unsupported(format!( - "unconnected interface port `{formal}` of instance of `{child_name}`" - )) - })?; - let actual = actual_handle(expression, file)?.ok_or_else(|| { - unsupported(format!( - "interface port `{formal}` of `{child_name}` connected to an expression that is not an interface" - )) - })?; - let handle = handles - .at(&actual.handle, file.span(RefNode::Expression(expression))?) - .cloned() - .ok_or_else(|| { - unsupported(format!( - "interface port `{formal}` of `{child_name}` connected to `{}`, which is not an interface", - actual.handle - )) - })?; - // Only the actuals of interface ports may name a bare handle. - consumed.push(file.span(RefNode::Expression(expression))?); - match &formal_port.interface { - Some(interface) if *interface != handle.interface => { - return Err(unsupported(format!( - "interface port `{formal}` of `{child_name}` of interface `{interface}` connected to an instance of `{}`", - handle.interface - ))); - } - Some(_) => {} - None => child_bindings.push((formal.clone(), handle.interface.clone())), - } - if let Some(modport) = &actual.modport - && formal_port.modport.as_ref() != Some(modport) - { - return Err(unsupported(format!( - "modport `{modport}` selected in the connection of port `{formal}` of `{child_name}`, which does not declare it" - ))); - } - let child_expansion = - self.expansion(&child_name, &formal, &handle.interface, &generic_bindings)?; - for (member, direction) in &child_expansion.members { - if let Some(expansion) = &handle.port { - match expansion.direction(member) { - None => { - return Err(unsupported(format!( - "port `{formal}` of `{child_name}` needs member `{member}`, which port `{}` of `{module_name}` does not expose", - actual.handle - ))); - } - Some(Direction::Input) if *direction == Direction::Output => { - return Err(unsupported(format!( - "port `{formal}` of `{child_name}` drives member `{member}`, an input of port `{}` of `{module_name}`", - actual.handle - ))); - } - Some(_) => {} - } - } - connection_texts.push(format!( - ".{}({}{})", - joined(&formal, member), - joined(&actual.handle, member), - actual - .selects - .map(|selects| render(selects, &references)) - .unwrap_or_default() - )); - } - for parameter in &self.interface(&handle.interface)?.parameters { - parameter_texts.push(format!( - ".{}({})", - joined(&formal, ¶meter.name), - joined(&actual.handle, ¶meter.name) - )); - } - } - // Connections. - let connections_span = file.span(RefNode::HierarchicalInstance(instance))?; - let name_span = file.span(RefNode::NameOfInstance(&instance.nodes.0))?; - edits.push(Edit { - span: (name_span.1, connections_span.1), - text: format!(" ({})", connection_texts.join(", ")), - }); - // Parameters. - let mut existing = Vec::new(); - for (parameter, value) in - parameter_overrides(instantiation.nodes.1.as_ref(), &child_parameters, file)? - { - existing.push(format!(".{parameter}({})", render(value, &references))); - } - existing.extend(parameter_texts); - let module_identifier = file.span(RefNode::ModuleIdentifier(&instantiation.nodes.0))?; - let module_text = if child_bindings.is_empty() { - child_name.clone() - } else { - child_bindings.sort(); - let clone = clone_module_name(&child_name, &child_bindings); - clones.push((child_name.clone(), child_bindings)); - clone - }; - let parameter_end = match &instantiation.nodes.1 { - Some(assignment) => file.span(RefNode::ParameterValueAssignment(assignment))?.1, - None => module_identifier.1, - }; - let parameters = if existing.is_empty() { - String::new() - } else { - format!(" #({})", existing.join(", ")) - }; - edits.push(Edit { - span: (module_identifier.0, parameter_end), - text: format!("{module_text}{parameters}"), - }); - } - - // The header: module name, parameters, ports, and imported functions. - let header = &declaration.nodes.0; - if let Some(clone_name) = clone_name { - edits.push(Edit { - span: file.span(RefNode::ModuleIdentifier(&header.nodes.3))?, - text: clone_name.to_string(), - }); - if let Some((_, label)) = &declaration.nodes.4 { - edits.push(Edit { - span: file.span(RefNode::ModuleIdentifier(label))?, - text: clone_name.to_string(), - }); - } - } - let mut header_parameters = Vec::new(); - let mut header_imports = Vec::new(); - let mut functions_text = String::new(); - let mut port_texts: HashMap> = HashMap::default(); - for (port, interface_name, expansion, interface_port, _) in &port_interfaces { - let interface = self.interface(interface_name)?; - let rename = |item: &str| Some(joined(port, item)); - let interface_file = file_of(self.files, interface); - interface.check_context(file, interface_file, module_span.0)?; - for item in &interface.items { - let header = match item { - Item::Parameter(index) => { - let parameter = &interface.parameters[*index]; - let data_type = parameter - .data_type - .map(|data_type| { - format!("{} ", interface.render(interface_file, data_type, &rename)) - }) - .unwrap_or_default(); - let default = parameter - .default - .map(|default| { - format!(" = {}", interface.render(interface_file, default, &rename)) - }) - .unwrap_or_default(); - header_parameters.push(format!( - "parameter {data_type}{}{default}", - joined(port, ¶meter.name) - )); - continue; - } - Item::Constant { header, .. } => header, - _ => continue, - }; - match header { - HeaderForm::Parameter(span) => header_parameters.push(format!( - "localparam {}", - interface.render(interface_file, *span, &rename) - )), - HeaderForm::TypeAlias { name, data_type } => header_parameters.push(format!( - "localparam type {} = {}", - interface.render(interface_file, *name, &rename), - interface.render(interface_file, *data_type, &rename) - )), - HeaderForm::LocalType(span) => header_parameters.push(format!( - "localparam type {}", - interface.render(interface_file, *span, &rename) - )), - HeaderForm::Import { span, .. } => { - let import = interface_file.text(*span).to_string(); - if !header_imports.contains(&import) { - header_imports.push(import); - } - } - } - } - if !interface_port.dimensions.is_empty() - && expansion - .functions - .iter() - .any(|function| interface.accesses_members(function)) - { - return Err(unsupported(format!( - "functions of the interface port array `{port}`" - ))); - } - for function in &expansion.functions { - let function = interface.function(function).expect("expanded function"); - functions_text.push_str("\n "); - functions_text.push_str(&interface.render_with_timescale_prints( - file_of(self.files, interface), - function.span, - &rename, - scales, - port, - &[], - )?); - } - let dimensions: String = interface_port - .dimensions - .iter() - .map(|&dimension| render(dimension, &references)) - .collect::>() - .join(""); - let mut texts = Vec::new(); - for (member_name, direction) in &expansion.members { - let member = interface.member(member_name).expect("expanded member"); - texts.push(format!( - "{} {}", - interface.member_port_type( - file_of(self.files, interface), - member, - *direction, - &rename - ), - interface.member_declarator( - file_of(self.files, interface), - member, - &joined(port, member_name), - &dimensions, - &rename - ) - )); - } - // A port that carries only parameters or functions disappears. - port_texts.insert(port.clone(), texts); - } - if !port_texts.is_empty() { - let list = header - .nodes - .6 - .as_ref() - .ok_or_else(|| unsupported("interface ports outside an ANSI port list"))?; - let list_span = file.span(RefNode::ListOfPortDeclarations(list))?; - let mut texts = Vec::new(); - for port in &module.ports { - match port_texts.get(&port.name) { - Some(expanded) => texts.extend(expanded.iter().cloned()), - None => texts.push(render(port.span, &references)), - } - } - let text = if texts.is_empty() { - "()".to_string() - } else { - format!("(\n {}\n)", texts.join(",\n ")) - }; - edits.push(Edit { - span: list_span, - text, - }); - consumed.push(list_span); - } - // Imports go before a parameter port list, which is inserted at the - // same offset when the module has none, and insertions there keep - // their order. - if !header_imports.is_empty() { - let (_, end) = file.span(RefNode::ModuleIdentifier(&header.nodes.3))?; - edits.push(Edit { - span: (end, end), - text: format!(" {}", header_imports.join(" ")), - }); - } - if !header_parameters.is_empty() { - let text = header_parameters.join(",\n "); - match &header.nodes.5 { - Some(sv_parser::ParameterPortList::Empty(empty)) => { - let (start, _) = file.span(RefNode::Symbol(&empty.0))?; - let (_, end) = file.span(RefNode::Symbol(&empty.2))?; - edits.push(Edit { - span: (start, end), - text: format!("#(\n {text}\n)"), - }); - } - Some(list) => { - let (_, end) = file.span(RefNode::ParameterPortList(list))?; - edits.push(Edit { - span: (end - 1, end - 1), - text: format!(",\n {text}\n"), - }); - } - None => { - let (_, end) = file.span(RefNode::ModuleIdentifier(&header.nodes.3))?; - edits.push(Edit { - span: (end, end), - text: format!(" #(\n {text}\n)"), - }); - } - } - } - if !functions_text.is_empty() { - let (_, mut end) = file.span(RefNode::Symbol(&header.nodes.7))?; - // Imported functions are non-time items. Keep every initial - // time declaration before them (IEEE 1800-2023 3.14.2.2). - if let Some(declaration) = &declaration.nodes.1 { - end = file.span(RefNode::TimeunitsDeclaration(declaration))?.1; - } - for item in &declaration.nodes.2 { - let sv_parser::NonPortModuleItem::TimeunitsDeclaration(declaration) = item else { - break; - }; - end = file.span(RefNode::TimeunitsDeclaration(declaration))?.1; - } - edits.push(Edit { - span: (end, end), - text: functions_text, - }); - } - // Every remaining bare handle is an unsupported use of an interface. - if let Some((_, handle)) = pending.iter().find(|(reference, _)| { - !consumed - .iter() - .any(|span| span.0 <= reference.0 && reference.1 <= span.1) - }) { - return Err(unsupported(format!( - "use of interface `{handle}` other than as a port connection or through a member" - ))); - } - - edits.extend(references); - Ok(Some(apply(file.code, module_span, &edits))) - } - - /// The items of interface `interface` for an instance `instance` with - /// unpacked `dimensions` and parameter `overrides` (already rendered), - /// in a module of `file` that starts at `scope_start`. - fn instance_text( - &self, - interface: &InterfaceDecl, - instance: &str, - dimensions: &[(Span, &sv_parser::UnpackedDimension)], - overrides: &[(String, String)], - file: &File<'_>, - scope_start: usize, - render: &dyn Fn(Span) -> String, - scales: &super::timescales::Timescales, - ) -> Result { - let interface_file = file_of(self.files, interface); - interface.check_context(file, interface_file, scope_start)?; - // Helper names start with the separator, which no interface item name - // contains, so they cannot collide with a flattened item. - let genvars: Vec = (0..dimensions.len()) - .map(|index| joined(instance, &format!("{SEPARATOR}i{index}"))) - .collect(); - let element: String = genvars.iter().map(|genvar| format!("[{genvar}]")).collect(); - let plain = |item: &str| Some(joined(instance, item)); - let per_element = |item: &str| { - Some(if interface.member(item).is_some() { - format!("{}{element}", joined(instance, item)) - } else { - joined(instance, item) - }) - }; - let instance_dimensions: String = dimensions - .iter() - .map(|(span, _)| render(*span)) - .collect::>() - .join(""); - let mut declarations = Vec::new(); - let mut processes = Vec::new(); - for item in &interface.items { - match item { - Item::Parameter(index) => { - let parameter = &interface.parameters[*index]; - let value = match overrides.iter().find(|(name, _)| *name == parameter.name) { - Some((_, value)) => value.clone(), - None => interface.render( - interface_file, - parameter.default.ok_or_else(|| { - unsupported(format!( - "parameter `{}` of interface `{}` without a value", - parameter.name, interface.name - )) - })?, - &plain, - ), - }; - let data_type = parameter - .data_type - .map(|data_type| { - format!("{} ", interface.render(interface_file, data_type, &plain)) - }) - .unwrap_or_default(); - declarations.push(format!( - "localparam {data_type}{} = {value};", - joined(instance, ¶meter.name) - )); - } - Item::Constant { span, .. } => { - // A localparam of the parameter port list has no `;`. - let mut constant = interface.render(interface_file, *span, &plain); - if !constant.trim_end().ends_with(';') { - constant.push(';'); - } - declarations.push(constant); - } - Item::Member(index) => { - let member = &interface.members[*index]; - // Each element of an instance array would need its own - // copy of the initial value. - let initializer = match member.initializer { - Some(_) if !dimensions.is_empty() => { - return Err(unsupported(format!( - "initializer of member `{}` in the interface array `{instance}`", - member.name - ))); - } - Some(span) => { - format!(" = {}", interface.render(interface_file, span, &plain)) - } - None => String::new(), - }; - declarations.push(format!( - "{} {}{initializer};", - interface.member_type(interface_file, member, &plain), - interface.member_declarator( - interface_file, - member, - &joined(instance, &member.name), - &instance_dimensions, - &plain - ) - )); - } - Item::Function(index) => { - // A function of an instance array that accesses members - // would need a copy per element; logic that calls one is - // rejected below. - let function = &interface.functions[*index]; - if dimensions.is_empty() || !interface.accesses_members(&function.name) { - declarations.push(interface.render_with_timescale_prints( - interface_file, - interface.functions[*index].span, - &plain, - scales, - instance, - &[], - )?); - } - } - Item::Process(span) => { - if !dimensions.is_empty() { - let called: HashSet = interface - .referenced(*span) - .filter(|name| interface.function(name).is_some()) - .map(str::to_string) - .collect(); - if let Some(function) = called - .iter() - .find(|function| interface.accesses_members(function)) - { - return Err(unsupported(format!( - "call of function `{function}` of interface `{}`, which accesses members, in the logic of the instance array `{instance}`", - interface.name - ))); - } - for function in interface.function_closure(&called) { - let function = interface.function(&function).expect("called function"); - let first = interface_file - .print_tasks - .partition_point(|task| task.span.0 < function.span.0); - for task in interface_file.print_tasks[first..] - .iter() - .take_while(|task| task.span.0 < function.span.1) - { - if scales.print_needs_instance_scope( - &task.call, - &interface_file.syntax_tree, - task.site, - )? { - return Err(unsupported(format!( - "call of function `{}` of interface array `{instance}`, which uses its instance scope in `$printtimescale`", - function.name - ))); - } - } - } - } - if dimensions.is_empty() { - declarations.push(interface.render_with_timescale_prints( - interface_file, - *span, - &plain, - scales, - instance, - &[], - )?); - } else { - let prefix = format!("{instance}{}", "[%0d]".repeat(genvars.len())); - processes.push(interface.render_with_timescale_prints( - interface_file, - *span, - &per_element, - scales, - &prefix, - &genvars, - )?); - } - } - } - } - let mut text = declarations.join("\n "); - if !processes.is_empty() { - let mut body = processes.join("\n "); - for (index, (_, dimension)) in dimensions.iter().enumerate().rev() { - let genvar = &genvars[index]; - let label = joined(instance, &format!("{SEPARATOR}g{index}")); - body = match dimension { - sv_parser::UnpackedDimension::Expression(size) => { - let size = - render(file.span(RefNode::ConstantExpression(&size.nodes.0.nodes.1))?); - format!( - "for (genvar {genvar} = 0; {genvar} < ({size}); {genvar}++) begin : {label}\n {body}\n end" - ) - } - sv_parser::UnpackedDimension::Range(range) => { - let left = render( - file.span(RefNode::ConstantExpression(&range.nodes.0.nodes.1.nodes.0))?, - ); - let right = render( - file.span(RefNode::ConstantExpression(&range.nodes.0.nodes.1.nodes.2))?, - ); - // Keep range direction in the generate structure. - // Nested conditional expressions in a loop initializer - // can otherwise lose the range endpoints during lowering. - // Check both bounds so a signed 32-bit genvar wrapping - // past MIN or MAX cannot re-enter the array's range. - format!( - "if (({left}) <= ({right})) begin\n for (genvar {genvar} = ({left}); {genvar} >= ({left}) && {genvar} <= ({right}); {genvar}++) begin : {label}\n {body}\n end\n end else begin\n for (genvar {genvar} = ({left}); {genvar} <= ({left}) && {genvar} >= ({right}); {genvar}--) begin : {label}\n {body}\n end\n end" - ) - } - }; - } - text.push_str("\n "); - text.push_str(&body); - } - Ok(text) - } } /// The names that variable, net, parameter, type, subroutine, subroutine @@ -3257,64 +1543,9 @@ fn declared_identifiers(root: RefNode<'_>) -> Vec> { } _ => continue, }; - names.push(identifier); - } - names -} - -/// The names that `declaration` declares outside subroutines and procedural -/// blocks. Generate blocks count, since expanded interface instances declare -/// their items there. -fn module_scope_names( - declaration: &sv_parser::ModuleDeclarationAnsi, - file: &File<'_>, -) -> Result, AnalyzerError> { - let root = RefNode::ModuleDeclarationAnsi(declaration); - let mut nested = Vec::new(); - for node in root.clone() { - let span = match node { - // A subroutine scope starts after its name, which the module - // declares. - RefNode::FunctionDeclaration(function) => { - let span = file.span(RefNode::FunctionDeclaration(function))?; - let start = - unwrap_node!(RefNode::FunctionDeclaration(function), FunctionIdentifier) - .and_then(|identifier| file.node_span(identifier)) - .map_or(span.0, |identifier| identifier.1); - (start, span.1) - } - RefNode::TaskDeclaration(task) => { - let span = file.span(RefNode::TaskDeclaration(task))?; - let start = unwrap_node!(RefNode::TaskDeclaration(task), TaskIdentifier) - .and_then(|identifier| file.node_span(identifier)) - .map_or(span.0, |identifier| identifier.1); - (start, span.1) - } - RefNode::SeqBlock(_) | RefNode::ParBlock(_) | RefNode::LoopStatement(_) => { - match file.node_span(node) { - Some(span) => span, - None => continue, - } - } - _ => continue, - }; - nested.push(span); - } - let mut names = Vec::new(); - for identifier in declared_identifiers(root) { - let span = file.span(identifier.clone())?; - if !nested - .iter() - .any(|scope| scope.0 <= span.0 && span.1 <= scope.1) - { - names.push(name(identifier, &file.syntax_tree)?); - } - } - Ok(names) -} - -fn file_of<'a, 'b>(files: &'b [File<'a>], interface: &InterfaceDecl) -> &'b File<'a> { - &files[interface.file] + names.push(identifier); + } + names } fn clone_module_name(module: &str, bindings: &[(String, String)]) -> String { @@ -3991,7 +2222,6 @@ enum Connection<'b> { Implicit, } -/// The parameter value assignments of an instantiation as `(name, value span)`. fn parameter_overrides( assignment: Option<&sv_parser::ParameterValueAssignment>, parameters: &[String], @@ -4097,7 +2327,6 @@ impl InterfaceDecl { file: file_index, start: file.span(RefNode::InterfaceDeclarationAnsi(declaration))?.0, has_parameter_port_list: header.nodes.5.is_some(), - automatic: matches!(header.nodes.2, Some(sv_parser::Lifetime::Automatic(_))), uses_unit_items: false, uses_macros: has_directive( file.text(file.span(RefNode::InterfaceDeclarationAnsi(declaration))?), @@ -4368,18 +2597,7 @@ impl InterfaceDecl { &file.syntax_tree, )?)?; } - let start = file - .node_span(RefNode::DataTypeOrImplicit(¶meter.nodes.1)) - .map_or( - file.span(RefNode::ListOfParamAssignments(¶meter.nodes.2))? - .0, - |span| span.0, - ); - HeaderForm::Parameter(( - start, - file.span(RefNode::ListOfParamAssignments(¶meter.nodes.2))? - .1, - )) + HeaderForm::Constant } sv_parser::LocalParameterDeclaration::Type(parameter) => { for assignment in parameter.nodes.2.nodes.0.contents() { @@ -4388,9 +2606,7 @@ impl InterfaceDecl { &file.syntax_tree, )?)?; } - HeaderForm::LocalType( - file.span(RefNode::ListOfTypeAssignments(¶meter.nodes.2))?, - ) + HeaderForm::Constant } }; self.items.push(Item::Constant { @@ -4512,20 +2728,9 @@ impl InterfaceDecl { syntax_tree, )?)?; } - let start = file - .node_span(RefNode::DataTypeOrImplicit(¶meter.nodes.1)) - .map_or( - file.span(RefNode::ListOfParamAssignments(¶meter.nodes.2))? - .0, - |span| span.0, - ); self.items.push(Item::Constant { span: item_span, - header: HeaderForm::Parameter(( - start, - file.span(RefNode::ListOfParamAssignments(¶meter.nodes.2))? - .1, - )), + header: HeaderForm::Constant, }); } sv_parser::PackageOrGenerateItemDeclaration::FunctionDeclaration(function) => { @@ -4539,7 +2744,7 @@ impl InterfaceDecl { name: function_name, span: item_span, }); - self.items.push(Item::Function(self.functions.len() - 1)); + self.items.push(Item::Function); } sv_parser::PackageOrGenerateItemDeclaration::NetDeclaration(declaration) => { match declaration.as_ref() { @@ -4550,15 +2755,9 @@ impl InterfaceDecl { self.name ))); } - let net_type = file.span(RefNode::NetType(&net.nodes.0))?; let data_type = file.node_span(RefNode::DataTypeOrImplicit(&net.nodes.3)); for declarator in net.nodes.5.nodes.0.contents() { - self.add_net_member( - declarator, - MemberKind::Net(net_type), - data_type, - file, - )?; + self.add_net_member(declarator, data_type, file)?; } } sv_parser::NetDeclaration::NetTypeIdentifier(net) => { @@ -4572,7 +2771,7 @@ impl InterfaceDecl { } let data_type = Some(file.span(RefNode::NetTypeIdentifier(&net.nodes.0))?); for declarator in net.nodes.2.nodes.0.contents() { - self.add_net_member(declarator, MemberKind::Variable, data_type, file)?; + self.add_net_member(declarator, data_type, file)?; } } sv_parser::NetDeclaration::Interconnect(_) => { @@ -4621,7 +2820,6 @@ impl InterfaceDecl { .collect::>()?; self.add_member(Member { name: member_name, - kind: MemberKind::Variable, data_type, dimensions, initializer, @@ -4648,17 +2846,13 @@ impl InterfaceDecl { )?)?; self.items.push(Item::Constant { span: item_span, - header: HeaderForm::TypeAlias { - name: file.span(RefNode::TypeIdentifier(&typedef.nodes.2))?, - data_type: file.span(RefNode::DataType(&typedef.nodes.1))?, - }, + header: HeaderForm::Constant, }); } sv_parser::DataDeclaration::PackageImportDeclaration(import) => { self.items.push(Item::Constant { span: item_span, header: HeaderForm::Import { - span: file.span(RefNode::PackageImportDeclaration(import))?, imports: imported_items( RefNode::PackageImportDeclaration(import), syntax_tree, @@ -4687,7 +2881,6 @@ impl InterfaceDecl { fn add_net_member( &mut self, declarator: &sv_parser::NetDeclAssignment, - kind: MemberKind, data_type: Option, file: &File<'_>, ) -> Result<(), AnalyzerError> { @@ -4708,7 +2901,6 @@ impl InterfaceDecl { RefNode::NetIdentifier(&declarator.nodes.0), &file.syntax_tree, )?, - kind, data_type, dimensions, initializer: None, @@ -4818,121 +3010,6 @@ impl InterfaceDecl { } Ok(()) } - - /// The text of `span` of the interface source with each interface-scope - /// name renamed by `rename`. - fn render( - &self, - file: &File<'_>, - span: Span, - rename: &dyn Fn(&str) -> Option, - ) -> String { - let edits: Vec = self - .references - .iter() - .filter(|((start, end), _)| *start >= span.0 && *end <= span.1) - .filter_map(|(span, name)| rename(name).map(|text| Edit { span: *span, text })) - .collect(); - apply(file.code, span, &edits) - } - - /// Preserve the declaration's time scope while copying interface procedures. - fn render_with_timescale_prints( - &self, - file: &File<'_>, - span: Span, - rename: &dyn Fn(&str) -> Option, - scales: &super::timescales::Timescales, - handle: &str, - indices: &[String], - ) -> Result { - let mut edits = Vec::new(); - let first = file - .print_tasks - .partition_point(|task| task.span.0 < span.0); - for task in file.print_tasks[first..] - .iter() - .take_while(|task| task.span.0 < span.1) - { - let call = &task.call; - let call_span = task.span; - if call_span.0 < span.0 || call_span.1 > span.1 { - continue; - } - let text = scales.interface_print_statement( - call, - &file.syntax_tree, - task.site, - handle, - indices, - )?; - check_query_origin(file, file.syntax_tree.get_str_trim(call), call_span)?; - edits.push(Edit { - span: call_span, - text, - }); - } - let replaced: Vec<_> = edits.iter().map(|edit| edit.span).collect(); - edits.extend( - self.references - .iter() - .filter(|((start, end), _)| { - *start >= span.0 - && *end <= span.1 - && !replaced.iter().any(|&(a, b)| a <= *start && *end <= b) - }) - .filter_map(|(span, name)| rename(name).map(|text| Edit { span: *span, text })), - ); - Ok(apply(file.code, span, &edits)) - } - - /// The data type of a member declaration with its kind keyword. - fn member_type( - &self, - file: &File<'_>, - member: &Member, - rename: &dyn Fn(&str) -> Option, - ) -> String { - let data_type = member - .data_type - .map(|span| self.render(file, span, rename)) - .unwrap_or_else(|| "logic".to_string()); - match member.kind { - MemberKind::Variable => format!("var {data_type}"), - MemberKind::Net(net_type) => format!("{} {data_type}", file.text(net_type)), - } - } - - fn member_port_type( - &self, - file: &File<'_>, - member: &Member, - direction: Direction, - rename: &dyn Fn(&str) -> Option, - ) -> String { - format!( - "{} {}", - direction.keyword(), - self.member_type(file, member, rename) - ) - } - - /// `name` followed by `outer` dimensions and the member's own. - fn member_declarator( - &self, - file: &File<'_>, - member: &Member, - name: &str, - outer: &str, - rename: &dyn Fn(&str) -> Option, - ) -> String { - let own: String = member - .dimensions - .iter() - .map(|&dimension| self.render(file, dimension, rename)) - .collect(); - format!("{name}{outer}{own}") - } } impl ModuleDecl { @@ -4956,7 +3033,6 @@ impl ModuleDecl { // defaults to inout. let mut writes = true; for (_, port) in list.contents() { - let port_span = file.span(RefNode::AnsiPortDeclaration(port))?; let direction = match port { sv_parser::AnsiPortDeclaration::Net(net) => match &net.nodes.0 { Some(sv_parser::NetPortHeaderOrInterfacePortHeader::NetPortHeader( @@ -5071,66 +3147,423 @@ impl ModuleDecl { previous.clone_from(&interface); ports.push(PortDecl { name: name(identifier, syntax_tree)?, - span: port_span, interface, writes, }); } } - let mut parameters = Vec::new(); - if let Some(list) = &header.nodes.5 { - let mut declarations = Vec::new(); - match list { - sv_parser::ParameterPortList::Assignment(list) => { - for assignment in list.nodes.1.nodes.1.0.nodes.0.contents() { - parameters.push(name( - RefNode::ParameterIdentifier(&assignment.nodes.0), - syntax_tree, - )?); - } - declarations.extend( - list.nodes - .1 - .nodes - .1 - .1 - .iter() - .map(|(_, declaration)| declaration), - ); - } - sv_parser::ParameterPortList::Declaration(list) => { - declarations.extend(list.nodes.1.nodes.1.contents()); + Ok(Self { + name: module_name, + file: file_index, + span: file.span(RefNode::ModuleDeclarationAnsi(declaration))?, + ports, + }) + } +} + +/// Declaration bindings and port directions, independent of rewritten source. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct NativeInterfacePlan { + pub root_names: HashMap, + pub modules: HashMap, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct NativeModulePlan { + pub original: String, + pub ports: Vec, + /// Child instance identifier offsets and their bound module names. + pub children: HashMap, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct NativePortPlan { + pub array_rank: usize, + pub functions: Vec, + pub all_members: Vec, + pub name: String, + pub interface: String, + pub members: Vec<(String, PortDirection)>, + pub parameters: Vec, +} + +pub fn plan_interfaces( + sources: &[(&str, &Path)], + bindings: &[(String, String, Vec<(String, String)>)], +) -> Converted { + let files = sources + .iter() + .map(|(code, path)| File::new(code, path)) + .collect::>>()?; + let design = Design::collect(&files)?; + let mut result = NativeInterfacePlan::default(); + if design.interfaces.is_empty() { + return Ok(result); + } + let mut queue = design + .modules + .iter() + .filter(|(_, module)| { + !module.ports.iter().any(|port| { + port.interface + .as_ref() + .is_some_and(|interface| interface.interface.is_none()) + }) + }) + .map(|(name, _)| (name.clone(), Vec::<(String, String)>::new())) + .collect::>(); + for (alias, name, supplied) in bindings { + let Some(module) = design.modules.get(name) else { + continue; + }; + let mut generic = Vec::new(); + for (port, interface) in supplied { + let declared = module + .port(port) + .and_then(|port| port.interface.as_ref()) + .ok_or_else(|| { + unsupported(format!("`{port}` of `{name}` is not an interface port")) + })?; + if let Some(expected) = &declared.interface { + if expected != interface { + return Err(unsupported(format!( + "interface `{interface}` connected to `{name}.{port}` of type `{expected}`" + ))); } - sv_parser::ParameterPortList::Empty(_) => {} + } else { + generic.push((port.clone(), interface.clone())); } - for declaration in declarations { - if matches!( - declaration, - sv_parser::ParameterPortDeclaration::LocalParameterDeclaration(_) - ) { + } + generic.sort(); + let bound = if generic.is_empty() { + name.clone() + } else { + clone_module_name(name, &generic) + }; + result.root_names.insert(alias.clone(), bound); + queue.push((name.clone(), generic)); + } + while let Some((name, bindings)) = queue.pop() { + let bound_name = if bindings.is_empty() { + name.clone() + } else { + clone_module_name(&name, &bindings) + }; + if result.modules.contains_key(&bound_name) { + continue; + } + let module = &design.modules[&name]; + let file = &files[module.file]; + let declaration = design.module_node(module)?; + let mut handles = Handles::default(); + let mut ports = Vec::new(); + for port in &module.ports { + let Some(declared) = &port.interface else { + continue; + }; + let interface = declared + .interface + .as_ref() + .or_else(|| { + bindings + .iter() + .find(|(name, _)| name == &port.name) + .map(|(_, interface)| interface) + }) + .ok_or_else(|| { + unsupported(format!( + "generic interface port `{}` of module `{name}` without a binding", + port.name + )) + })?; + let expansion = design.expansion(&name, &port.name, interface, &bindings)?; + let uses = design.module_uses(&name, (&port.name, interface), &bindings)?; + let declaration = &design.interfaces[interface]; + for (handle, member, _) in &uses.references { + if handle != &port.name { continue; } - for node in RefNode::ParameterPortDeclaration(declaration) { - match node { - RefNode::ParamAssignment(assignment) => parameters.push(name( - RefNode::ParameterIdentifier(&assignment.nodes.0), - syntax_tree, - )?), - RefNode::TypeAssignment(assignment) => parameters.push(name( - RefNode::TypeIdentifier(&assignment.nodes.0), - syntax_tree, - )?), - _ => {} - } + if declaration.member(member).is_some() + && expansion + .accessible + .as_ref() + .is_some_and(|members| !members.contains(member)) + { + return Err(unsupported(format!( + "access of `{handle}.{member}`, which the modport of port `{handle}` does not list" + ))); + } + if declaration.function(member).is_some() + && expansion + .callable + .as_ref() + .is_some_and(|functions| !functions.contains(member)) + { + return Err(unsupported(format!( + "call of `{handle}.{member}`, which the modport of port `{handle}` does not import" + ))); } } + handles.insert( + port.name.clone(), + module.span, + Handle { + interface: interface.clone(), + port: Some(expansion.clone()), + arrayed: !declared.dimensions.is_empty(), + }, + ); + ports.push(NativePortPlan { + array_rank: declared.dimensions.len(), + functions: expansion.functions.clone(), + all_members: design.interfaces[interface] + .members + .iter() + .map(|member| member.name.clone()) + .collect(), + name: port.name.clone(), + interface: interface.clone(), + members: expansion + .members + .iter() + .map(|(name, direction)| { + ( + name.clone(), + match direction { + Direction::Input => PortDirection::Input, + Direction::Output => PortDirection::Output, + }, + ) + }) + .collect(), + parameters: design.interfaces[interface] + .parameters + .iter() + .map(|parameter| parameter.name.clone()) + .collect(), + }); } - Ok(Self { - name: module_name, - file: file_index, - span: file.span(RefNode::ModuleDeclarationAnsi(declaration))?, - ports, - parameters, - }) + let blocks = RefNode::ModuleDeclarationAnsi(declaration) + .into_iter() + .filter_map(|node| { + if let RefNode::GenerateBlock(block) = node { + file.node_span(RefNode::GenerateBlock(block)) + } else { + None + } + }) + .collect::>(); + for node in RefNode::ModuleDeclarationAnsi(declaration) { + let RefNode::ModuleInstantiation(instantiation) = node else { + continue; + }; + let interface = name_of_instantiation(instantiation, &file.syntax_tree)?; + if !design.interfaces.contains_key(&interface) { + continue; + } + let span = file.span(RefNode::ModuleInstantiation(instantiation))?; + let parameter_names = design.interfaces[&interface] + .parameters + .iter() + .map(|parameter| parameter.name.clone()) + .collect::>(); + let mut supplied = HashSet::default(); + for (name, _) in + parameter_overrides(instantiation.nodes.1.as_ref(), ¶meter_names, file)? + { + if !parameter_names.contains(&name) { + return Err(AnalyzerError::UnknownInterfaceParameter { + interface: interface.clone(), + name, + }); + } + if !supplied.insert(name.clone()) { + return Err(AnalyzerError::DuplicateInterfaceParameterOverride { + interface: interface.clone(), + name, + }); + } + } + + let scope = blocks + .iter() + .filter(|block| block.0 <= span.0 && span.1 <= block.1) + .min_by_key(|block| block.1 - block.0) + .copied() + .unwrap_or(module.span); + for instance in instantiation.nodes.2.contents() { + check_no_connections(instance, &interface)?; + let handle = identifier_text( + RefNode::InstanceIdentifier(&instance.nodes.0.nodes.0), + &file.syntax_tree, + ) + .unwrap(); + handles.insert( + handle, + scope, + Handle { + interface: interface.clone(), + port: None, + arrayed: !instance.nodes.0.nodes.1.is_empty(), + }, + ); + } + } + for reference in + file.handle_references(module.span, |name| handles.by_name.contains_key(name)) + { + let handle = handles + .at(&reference.handle, reference.span) + .ok_or_else(|| { + unsupported(format!( + "reference to interface `{}` outside the generate block that declares it", + reference.handle + )) + })?; + if let Some((member, _)) = reference.item + && design.interfaces[&handle.interface] + .function(&member) + .is_some() + && (handle.arrayed || reference.selects.is_some()) + { + return Err(unsupported(format!( + "call of a function of the interface array `{}`", + reference.handle + ))); + } + } + let mut children = HashMap::default(); + for node in RefNode::ModuleDeclarationAnsi(declaration) { + let RefNode::ModuleInstantiation(instantiation) = node else { + continue; + }; + let child_name = name_of_instantiation(instantiation, &file.syntax_tree)?; + let Some(child) = design.modules.get(&child_name) else { + continue; + }; + if !child.has_interface_ports() { + continue; + } + for instance in instantiation.nodes.2.contents() { + let mut generic = Vec::new(); + for (formal, actual) in connections(instance, child, file, true)? { + let Some(port) = child.port(&formal).and_then(|port| port.interface.as_ref()) + else { + continue; + }; + let Connection::Explicit(Some(expression)) = actual else { + return Err(unsupported(format!( + "missing interface actual of `{child_name}.{formal}`" + ))); + }; + let actual = actual_handle(expression, file)?.ok_or_else(|| { + unsupported(format!("interface actual of `{child_name}.{formal}`")) + })?; + let handle = handles + .at(&actual.handle, file.span(RefNode::Expression(expression))?) + .ok_or_else(|| { + unsupported(format!("unknown interface handle `{}`", actual.handle)) + })?; + if handle.arrayed && actual.selects.is_none() && port.dimensions.is_empty() { + return Err(unsupported(format!( + "whole interface array `{}` connected to scalar port `{formal}`", + actual.handle + ))); + } + if let Some(expected) = &port.interface { + if expected != &handle.interface { + return Err(unsupported(format!( + "interface type mismatch at `{child_name}.{formal}`" + ))); + } + } else { + generic.push((formal.clone(), handle.interface.clone())); + } + let child_bindings = child + .ports + .iter() + .filter_map(|formal| { + let declared = formal.interface.as_ref()?; + if declared.interface.is_some() { + return None; + } + let actual = connections(instance, child, file, true) + .ok()? + .into_iter() + .find(|(name, _)| name == &formal.name)? + .1; + let Connection::Explicit(Some(expression)) = actual else { + return None; + }; + let actual = actual_handle(expression, file).ok()??; + let handle = handles.at( + &actual.handle, + file.span(RefNode::Expression(expression)).ok()?, + )?; + Some((formal.name.clone(), handle.interface.clone())) + }) + .collect::>(); + let child_expansion = design.expansion( + &child_name, + &formal, + &handle.interface, + &child_bindings, + )?; + if let Some(parent) = &handle.port { + for (member, direction) in &child_expansion.members { + match parent.direction(member) { + None => { + return Err(unsupported(format!( + "port `{formal}` of `{child_name}` needs member `{member}`, which port `{}` of `{name}` does not expose", + actual.handle + ))); + } + Some(Direction::Input) if *direction == Direction::Output => { + return Err(unsupported(format!( + "port `{formal}` of `{child_name}` drives member `{member}`, an input of port `{}` of `{name}`", + actual.handle + ))); + } + _ => {} + } + } + } + if actual.modport.is_some() && actual.modport != port.modport { + return Err(unsupported(format!( + "modport mismatch at `{child_name}.{formal}`" + ))); + } + } + generic.sort(); + let child_alias = if generic.is_empty() { + child_name.clone() + } else { + clone_module_name(&child_name, &generic) + }; + let offset = + identifier_locate(RefNode::InstanceIdentifier(&instance.nodes.0.nodes.0)) + .unwrap() + .offset; + children.insert(offset, child_alias); + queue.push((child_name.clone(), generic)); + } + } + result.modules.insert( + bound_name, + NativeModulePlan { + original: name, + ports, + children, + }, + ); } + Ok(result) +} + +fn name_of_instantiation( + instantiation: &sv_parser::ModuleInstantiation, + tree: &SyntaxTree, +) -> Converted { + identifier_text(RefNode::ModuleIdentifier(&instantiation.nodes.0), tree) + .ok_or_else(|| unsupported("instance type name")) } diff --git a/crates/celox-sv-analyzer/src/ast/native_interfaces.rs b/crates/celox-sv-analyzer/src/ast/native_interfaces.rs new file mode 100644 index 00000000000..f2f01ad9cb6 --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/native_interfaces.rs @@ -0,0 +1,919 @@ +//! Interface instances bound in semantic scopes, retaining authored syntax. +use super::*; + +pub(super) struct Bindings<'a> { + pub values: &'a HashMap, + pub plan: Option<&'a interfaces::NativeModulePlan>, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct InstanceBinding { + pub module: String, + pub connections: HashMap>, + pub parameters: Vec, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub(super) struct ScopeBinding { + pub members: HashMap, + pub types: HashMap, + pub arrays: HashMap, + pub instances: HashMap, +} + +/// Elements in declaration order, independent of the numeric index origins. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct ArrayBinding { + pub elements: Vec, + pub shape: Vec, +} + +pub(super) fn analyze_module( + declaration: &sv_parser::ModuleDeclarationAnsi, + tree: &SyntaxTree, + path: &Path, + packages: &packages::Packages, + bindings: Bindings<'_>, + interfaces: &InterfaceLookup<'_>, + mut imported: scope::ScopeSymbols, +) -> Converted> { + let mut definitions = HashMap::default(); + for (interface_tree, interface_path) in packages.interface_sources.values() { + for node in interface_tree.as_ref() { + if let RefNode::InterfaceDeclarationAnsi(declaration) = node { + let name = identifier_text( + RefNode::InterfaceIdentifier(&declaration.nodes.0.nodes.3), + interface_tree, + ) + .unwrap(); + definitions.insert( + name, + ( + declaration, + interface_tree.as_ref(), + interface_path.as_path(), + ), + ); + } + } + } + // The direct syntax API also supports a self-contained compilation unit. + for node in tree { + if let RefNode::InterfaceDeclarationAnsi(declaration) = node { + let name = identifier_text( + RefNode::InterfaceIdentifier(&declaration.nodes.0.nodes.3), + tree, + ) + .unwrap(); + definitions.entry(name).or_insert((declaration, tree, path)); + } + } + if definitions.is_empty() { + return Ok(None); + } + let name = module_name_from_node(RefNode::ModuleDeclarationAnsi(declaration), tree)?; + let plan = bindings.plan; + let overrides = bindings.values; + let interface_ports = plan.map(|plan| plan.ports.as_slice()).unwrap_or_default(); + let mut view = declaration.clone(); + remove_interface_ports(&mut view, interface_ports, tree); + let supplied = overrides; + let overrides = overrides + .iter() + .filter(|(name, _)| { + !interface_ports + .iter() + .any(|port| name.starts_with(&format!("{}$", port.name))) + }) + .map(|(name, value)| (name.clone(), value.clone())) + .collect::>(); + let mut instantiations = Vec::new(); + view.nodes.2.retain(|item| { + if let sv_parser::NonPortModuleItem::ModuleOrGenerateItem(item) = item + && let sv_parser::ModuleOrGenerateItem::Module(instance) = item.as_ref() + && identifier_text(RefNode::ModuleIdentifier(&instance.nodes.1.nodes.0), tree) + .is_some_and(|name| definitions.contains_key(&name)) + { + instantiations.push(instance.nodes.1.clone()); + false + } else { + true + } + }); + let has_generated_interfaces = RefNode::ModuleDeclarationAnsi(&view) + .into_iter() + .any(|node| { + if let RefNode::ModuleInstantiation(instance) = node { + identifier_text(RefNode::ModuleIdentifier(&instance.nodes.0), tree) + .is_some_and(|name| definitions.contains_key(&name)) + } else { + false + } + }); + if instantiations.is_empty() && interface_ports.is_empty() && !has_generated_interfaces { + return Ok(None); + } + let array_scope = if interface_ports.iter().any(|port| port.array_rank != 0) { + let header = declaration_view(&view); + let mut header_imports = imported.clone(); + header_imports.declarations_only = true; + Some(Module::from_scope_node_with_parameter_overrides( + RefNode::ModuleDeclarationAnsi(&header), + tree, + &name, + &overrides, + interfaces, + Arc::new(header_imports), + true, + )?) + } else { + None + }; + for port in interface_ports { + let (definition, definition_tree, definition_path) = definitions + .get(&port.interface) + .ok_or_else(|| unsupported(format!("interface `{}`", port.interface)))?; + let prefix = format!("{}$", port.name); + let values = supplied + .iter() + .filter_map(|(name, value)| { + name.strip_prefix(&prefix) + .filter(|name| !name.starts_with('$')) + .map(|name| (name.to_string(), value.clone())) + }) + .collect::>(); + let dimensions = formal_dimensions(declaration, &port.name, tree)?; + let array_symbols = array_scope + .as_ref() + .and_then(|module| module.symbols.as_ref()) + .unwrap_or(&imported); + let array = instance_elements( + &port.name, + &dimensions, + tree, + &array_symbols.const_env, + &array_symbols.type_aliases, + )?; + for (dimension, size) in array.shape.iter().enumerate() { + if let Some(actual) = supplied.get(&format!("{}$$dimension{dimension}", port.name)) + && eval_ast_const_expr(actual, &array_symbols.const_env) != Some(*size as i128) + { + return Err(unsupported(format!( + "interface array dimension mismatch at `{name}.{}`", + port.name + ))); + } + } + if !dimensions.is_empty() { + imported + .interface_arrays + .insert(port.name.clone(), array.clone()); + } + for (ordinal, handle) in array.elements.iter().enumerate() { + imported + .interface_types + .insert(handle.clone(), port.interface.clone()); + let symbol_prefix = if dimensions.is_empty() { + port.name.clone() + } else { + format!("{}${ordinal}", port.name) + }; + let interface = timescales::with_interface_instance(handle, || { + interface_ast::analyze( + definition, + definition_tree, + definition_path, + packages, + &values, + interfaces.extra, + imported.declarations_only, + ) + })?; + let symbols = interface.symbols.as_ref().unwrap(); + let names = binding_names_with_prefix( + &interface, + symbols, + handle, + &symbol_prefix, + &mut imported, + ); + let mut bound = symbols.renamed(&names); + let functions = port + .functions + .iter() + .filter_map(|name| names.get(name)) + .cloned() + .collect::>(); + bound + .functions + .retain(|name, _| name.contains("::") || functions.contains(name)); + bound.subroutines.retain(|function| { + function.name.contains("::") || functions.contains(&function.name) + }); + bound + .constant_functions + .retain(|name| name.contains("::") || functions.contains(name)); + bound.comb_processes.clear(); + bound.ff_processes.clear(); + let members = port + .all_members + .iter() + .map(|name| names[name].clone()) + .collect::>(); + // Declaration initializers of interface variables belong to the + // actual instance, not to each module receiving its port view. + bound.initial_processes.retain(|process| { + process.synthetic && procedural::written_names(&process.body).is_disjoint(&members) + }); + for (member, direction) in &port.members { + let signal = bound + .signals + .iter() + .find(|signal| signal.name == names[member]) + .ok_or_else(|| { + unsupported(format!("interface member `{}.{member}`", port.name)) + })?; + bound.ports.push(Port::new( + signal.name.clone(), + *direction, + signal.r#type.clone(), + signal.is_net, + )); + } + bound + .signals + .retain(|signal| !members.contains(&signal.name)); + imported.extend(&bound); + } + } + // Resolve the caller's declarations before evaluating instance overrides. + let header = declaration_view(&view); + let mut header_imports = imported.clone(); + header_imports.declarations_only = true; + let caller = Module::from_scope_node_with_parameter_overrides( + RefNode::ModuleDeclarationAnsi(&header), + tree, + &name, + &overrides, + interfaces, + Arc::new(header_imports), + true, + )?; + let caller_symbols = caller.symbols.as_ref().unwrap(); + let _caller_scope = scope::install(Arc::new(caller_symbols.clone())); + let _functions = const_functions::install(caller.constant_functions.clone()); + let mut port_assignments = Vec::new(); + let mut pending = instantiations + .into_iter() + .map(|instance| (instance, None)) + .collect::>(); + let mut generated = false; + loop { + if pending.is_empty() && !generated { + generated = true; + let mut current = caller_symbols.clone(); + current.extend(&imported); + let _scope = scope::install(Arc::new(current.clone())); + for item in generate::items( + RefNode::ModuleDeclarationAnsi(&view), + tree, + ¤t.const_env, + ¤t.type_aliases, + )? { + if let ScopeItem::Module(sv_parser::ModuleOrGenerateItem::Module(instance)) = + item.node + && identifier_text(RefNode::ModuleIdentifier(&instance.nodes.1.nodes.0), tree) + .is_some_and(|name| definitions.contains_key(&name)) + { + imported.interface_declarations.insert( + identifier_locate(RefNode::ModuleIdentifier(&instance.nodes.1.nodes.0)) + .unwrap() + .offset, + ); + pending.push_back((instance.nodes.1.clone(), Some(item))); + } + } + } + let Some((instantiation, generated_item)) = pending.pop_front() else { + break; + }; + let mut current = caller_symbols.clone(); + current.extend(&imported); + if let Some(item) = &generated_item { + current + .const_env + .extend(item.env.iter().map(|(name, value)| (name.clone(), *value))); + } + let _scope = scope::install(Arc::new(current.clone())); + let dimensions = PackedDimensions::new( + HashMap::default(), + ¤t.const_env, + ¤t.type_aliases, + ); + let interface_name = + identifier_text(RefNode::ModuleIdentifier(&instantiation.nodes.0), tree).unwrap(); + let (definition, definition_tree, definition_path) = definitions[&interface_name]; + let interface_view = interface_ast::module_view(definition)?; + let interface = module_interface_from_node( + RefNode::ModuleDeclarationAnsi(&interface_view), + definition_tree, + )?; + let bindings = instances::parameter_overrides_from_value_assignment( + instantiation.nodes.1.as_ref(), + tree, + Some(&interface), + &dimensions, + )?; + let values = bindings + .into_iter() + .map(|binding| { + let value = binding + .value + .ok_or_else(|| unsupported("interface type or pattern parameter binding"))?; + let value = substitute_typed_parameter_literals( + value, + ¤t.const_env, + ¶meter_types_from_const_env(¤t.const_env), + ); + Ok((binding.name, value)) + }) + .collect::>>()?; + for instance in instantiation.nodes.2.contents() { + let handle = + identifier_text(RefNode::InstanceIdentifier(&instance.nodes.0.nodes.0), tree) + .ok_or_else(|| unsupported("interface instance name"))?; + let elements = instance_elements( + &handle, + &instance.nodes.0.nodes.1, + tree, + ¤t.const_env, + ¤t.type_aliases, + )?; + if !elements.shape.is_empty() { + let qualified = generated_item + .as_ref() + .map_or_else(|| handle.clone(), |item| item.instance_name(&handle)); + let absolute = ArrayBinding { + elements: elements + .elements + .iter() + .map(|element| { + generated_item + .as_ref() + .map_or_else(|| element.clone(), |item| item.instance_name(element)) + }) + .collect(), + shape: elements.shape.clone(), + }; + imported.interface_arrays.insert(qualified, absolute); + if let Some(item) = &generated_item { + imported + .interface_scopes + .entry(item.scope_name().to_string()) + .or_default() + .arrays + .insert(handle.clone(), elements.clone()); + } + } + for local_handle in elements.elements { + let handle = generated_item.as_ref().map_or_else( + || local_handle.clone(), + |item| item.instance_name(&local_handle), + ); + imported + .interface_types + .insert(handle.clone(), interface_name.clone()); + let connections = instances::port_connections_from_hierarchical_instance( + instance, + tree, + &dimensions, + Some(&interface), + )?; + let mut module = timescales::with_interface_instance(&handle, || { + interface_ast::analyze( + definition, + definition_tree, + definition_path, + packages, + &values, + interfaces.extra, + imported.declarations_only, + ) + })?; + for port in &module.ports { + let signal = Signal { + name: port.name.clone(), + r#type: port.r#type.clone(), + is_net: port.is_net, + package_variable: None, + }; + module.symbols.as_mut().unwrap().signals.push(signal); + let Some(connection) = connections + .iter() + .find(|connection| connection.formal == port.name) + else { + continue; + }; + let Some(actual) = connection.actual_expr.clone() else { + continue; + }; + let bound = format!("{handle}${}", port.name); + let assignment = match port.direction { + PortDirection::Input => Assignment::new(LValue::Ident(bound), actual), + PortDirection::Output => { + Assignment::new(connection_lvalue(actual)?, Expr::Ident(bound)) + } + _ => return Err(unsupported("bidirectional interface declaration port")), + }; + port_assignments.push(assignment); + } + let symbols = module.symbols.as_ref().unwrap(); + let names = binding_names(&module, symbols, &handle, &mut imported); + if let Some(item) = &generated_item { + let scope = imported + .interface_scopes + .entry(item.scope_name().to_string()) + .or_default(); + scope + .types + .insert(local_handle.clone(), interface_name.clone()); + for (member, bound) in &names { + scope + .members + .insert(format!("{local_handle}.{member}"), bound.clone()); + } + } + let bound = symbols.renamed(&names); + imported + .initial_processes + .extend(bound.initial_processes.iter().cloned()); + imported.extend(&bound); + } + } + } + if let Some(plan) = plan { + let mut current = caller_symbols.clone(); + current.extend(&imported); + let _scope = scope::install(Arc::new(current.clone())); + for item in generate::items( + RefNode::ModuleDeclarationAnsi(&view), + tree, + ¤t.const_env, + ¤t.type_aliases, + )? { + let _interface_scope = item.interface_scope(); + let active_scope = scope::imported(); + let ScopeItem::Module(sv_parser::ModuleOrGenerateItem::Module(instantiation)) = + item.node + else { + continue; + }; + let instantiation = &instantiation.nodes.1; + let original = + identifier_text(RefNode::ModuleIdentifier(&instantiation.nodes.0), tree).unwrap(); + for instance in instantiation.nodes.2.contents() { + let offset = + identifier_locate(RefNode::InstanceIdentifier(&instance.nodes.0.nodes.0)) + .unwrap() + .offset; + let Some(alias) = plan.children.get(&offset) else { + continue; + }; + let child = &packages.interface_plan.modules[alias]; + let mut connections = HashMap::default(); + let mut parameters = Vec::new(); + for port in &child.ports { + let actual = connection_expression( + instance, + &port.name, + interfaces.get(&original), + tree, + )?; + let env = &item.env; + let handle = actual_handle_key(actual, tree, env, &active_scope.type_aliases)?; + let actuals = if port.array_rank == 0 { + ArrayBinding { + elements: vec![handle.clone()], + shape: Vec::new(), + } + } else { + active_scope + .interface_arrays + .get(&handle) + .cloned() + .ok_or_else(|| { + unsupported(format!("interface array actual `{handle}`")) + })? + }; + if actuals.shape.len() != port.array_rank { + return Err(unsupported(format!( + "interface array rank mismatch at `{original}.{}`", + port.name + ))); + } + let mut members = Vec::new(); + for (ordinal, handle) in actuals.elements.iter().enumerate() { + let prefix = if port.array_rank == 0 { + port.name.clone() + } else { + format!("{}${ordinal}", port.name) + }; + for (member, _) in &port.members { + let actual = active_scope + .interface_members + .get(&format!("{handle}.{member}")) + .ok_or_else(|| { + unsupported(format!( + "unbound interface member `{handle}.{member}`" + )) + })? + .clone(); + members.push(PortConnection::new( + format!("{prefix}${member}"), + actual.clone(), + Some(Expr::Ident(actual)), + )); + } + } + connections.insert(port.name.clone(), members); + for (dimension, size) in actuals.shape.iter().enumerate() { + parameters.push(ParameterOverride::new( + format!("{}$$dimension{dimension}", port.name), + Some(ConstExpr::Literal(size.to_string())), + )); + } + let handle = &actuals.elements[0]; + for parameter in &port.parameters { + let bound = active_scope + .interface_members + .get(&format!("{handle}.{parameter}")) + .ok_or_else(|| { + unsupported(format!( + "unbound interface parameter `{handle}.{parameter}`" + )) + })?; + let value = active_scope + .parameter_values + .get(bound) + .cloned() + .and_then(expr_to_const) + .ok_or_else(|| { + unsupported(format!("interface parameter `{handle}.{parameter}`")) + })?; + parameters.push(ParameterOverride::new( + format!("{}${parameter}", port.name), + Some(value), + )); + } + } + let binding = InstanceBinding { + module: alias.clone(), + connections, + parameters, + }; + if item.scope_name().is_empty() { + imported.interface_instances.insert(offset, binding); + } else { + imported + .interface_scopes + .entry(item.scope_name().to_string()) + .or_default() + .instances + .insert(offset, binding); + } + } + } + } + for assignment in port_assignments { + imported.comb_processes.push(CombProcess::new( + CombProcessKind::ContinuousAssign, + None, + vec![assignment], + )); + } + let module = Module::from_module_node_with_parameter_overrides( + RefNode::ModuleDeclarationAnsi(&view), + tree, + &name, + &overrides, + interfaces, + Arc::new(imported), + )?; + let mut names = HashSet::default(); + for name in module + .ports + .iter() + .map(|port| &port.name) + .chain(module.signals.iter().map(|signal| &signal.name)) + { + if !names.insert(name) { + return Err(unsupported(format!( + "interface binding collides with declaration `{name}`" + ))); + } + } + Ok(Some(module)) +} + +fn declaration_view(module: &sv_parser::ModuleDeclarationAnsi) -> sv_parser::ModuleDeclarationAnsi { + let mut header = module.clone(); + header.nodes.2.retain(|item| match item { + sv_parser::NonPortModuleItem::TimeunitsDeclaration(_) => true, + sv_parser::NonPortModuleItem::ModuleOrGenerateItem(item) => matches!(item.as_ref(), + sv_parser::ModuleOrGenerateItem::ModuleItem(item) + if matches!(&item.nodes.1, sv_parser::ModuleCommonItem::ModuleOrGenerateItemDeclaration(_))), + _ => false, + }); + header +} + +fn formal_dimensions( + module: &sv_parser::ModuleDeclarationAnsi, + port_name: &str, + tree: &SyntaxTree, +) -> Converted> { + for node in RefNode::ModuleDeclarationAnsi(module) { + let RefNode::AnsiPortDeclaration(port) = node else { + continue; + }; + let Some(identifier) = unwrap_node!(RefNode::AnsiPortDeclaration(port), PortIdentifier) + else { + continue; + }; + if identifier_text(identifier, tree).as_deref() != Some(port_name) { + continue; + } + return match port { + sv_parser::AnsiPortDeclaration::Net(port) => Ok(port.nodes.2.clone()), + sv_parser::AnsiPortDeclaration::Variable(port) => port + .nodes + .2 + .iter() + .map(|dimension| match dimension { + sv_parser::VariableDimension::UnpackedDimension(dimension) => { + Ok((**dimension).clone()) + } + _ => Err(unsupported("non-static interface port array dimension")), + }) + .collect(), + _ => Err(unsupported("interface port declaration")), + }; + } + Err(unsupported(format!("missing interface port `{port_name}`"))) +} + +fn connection_lvalue(expr: Expr) -> Converted { + match expr { + Expr::Ident(name) => Ok(LValue::Ident(name)), + Expr::Select { + expr, + msb, + lsb, + signed, + } => { + let Expr::Ident(name) = *expr else { + return Err(unsupported("interface output connection")); + }; + Ok(LValue::Select { + name, + msb, + lsb, + signed, + is_2state: false, + array_slice_width: None, + array_slice_reversed: false, + }) + } + _ => Err(unsupported("interface output connection")), + } +} + +fn binding_names( + module: &Module, + symbols: &scope::ScopeSymbols, + handle: &str, + imported: &mut scope::ScopeSymbols, +) -> HashMap { + binding_names_with_prefix(module, symbols, handle, handle, imported) +} + +fn binding_names_with_prefix( + module: &Module, + symbols: &scope::ScopeSymbols, + handle: &str, + prefix: &str, + imported: &mut scope::ScopeSymbols, +) -> HashMap { + let mut names = symbols.local_names(); + names.extend( + module + .parameters + .iter() + .map(|parameter| parameter.name.clone()), + ); + names.extend(module.signals.iter().map(|signal| signal.name.clone())); + names.extend(module.ports.iter().map(|port| port.name.clone())); + names.extend(symbols.type_aliases.keys().cloned()); + names.extend(symbols.functions.keys().cloned()); + names.extend(symbols.enum_constants.numbers.keys().cloned()); + names.retain(|name| !name.contains("::")); + names + .into_iter() + .map(|name| { + let bound = format!("{prefix}${name}"); + imported + .interface_members + .insert(format!("{handle}.{name}"), bound.clone()); + (name, bound) + }) + .collect() +} + +fn remove_interface_ports( + module: &mut sv_parser::ModuleDeclarationAnsi, + ports: &[interfaces::NativePortPlan], + tree: &SyntaxTree, +) { + let Some(declarations) = &mut module.nodes.0.nodes.6 else { + return; + }; + let Some(list) = &declarations.nodes.0.nodes.1 else { + return; + }; + let comma = list.nodes.1.first().map(|(comma, _)| comma.clone()); + let kept = list + .contents() + .into_iter() + .filter(|(_, port)| { + let name = identifier_text(RefNode::AnsiPortDeclaration(port), tree); + // The declaration's first identifier can be its type; take its port identifier. + let name = unwrap_node!(RefNode::AnsiPortDeclaration(port), PortIdentifier) + .and_then(|node| identifier_text(node, tree)) + .or(name); + !ports.iter().any(|port| Some(&port.name) == name.as_ref()) + }) + .cloned() + .collect::>(); + let mut kept = kept.into_iter(); + declarations.nodes.0.nodes.1 = kept.next().map(|first| sv_parser::List { + nodes: ( + first, + kept.map(|port| (comma.as_ref().unwrap().clone(), port)) + .collect(), + ), + }); +} + +fn connection_expression<'a>( + instance: &'a sv_parser::HierarchicalInstance, + formal: &str, + interface: Option<&ModuleInterface>, + tree: &SyntaxTree, +) -> Converted<&'a sv_parser::Expression> { + let found = match instance.nodes.1.nodes.1.as_ref() { + Some(sv_parser::ListOfPortConnections::Named(connections)) => connections + .nodes + .0 + .contents() + .into_iter() + .find_map(|connection| { + let sv_parser::NamedPortConnection::Identifier(connection) = connection else { + return None; + }; + if identifier_text(RefNode::PortIdentifier(&connection.nodes.2), tree).as_deref() + != Some(formal) + { + return None; + } + connection.nodes.3.as_ref()?.nodes.1.as_ref() + }), + Some(sv_parser::ListOfPortConnections::Ordered(connections)) => interface + .and_then(|interface| interface.ports.iter().position(|name| name == formal)) + .and_then(|index| { + connections + .nodes + .0 + .contents() + .get(index) + .and_then(|connection| connection.nodes.1.as_ref()) + }), + _ => None, + }; + found.ok_or_else(|| unsupported(format!("missing interface connection `{formal}`"))) +} + +pub(super) fn method_call<'a>( + call: &'a sv_parser::MethodCall, + tree: &SyntaxTree, +) -> Converted<(String, Option<&'a sv_parser::ListOfArguments>)> { + let sv_parser::MethodCallRoot::Primary(root) = &call.nodes.0 else { + return Err(unsupported("method call")); + }; + let sv_parser::Primary::Hierarchical(root) = root.as_ref() else { + return Err(unsupported("interface method root")); + }; + if !root.nodes.2.nodes.1.nodes.0.is_empty() || root.nodes.2.nodes.2.is_some() { + return Err(unsupported("indexed interface method root")); + } + let handle = identifier_text(RefNode::PrimaryHierarchical(root), tree) + .ok_or_else(|| unsupported("interface method root"))?; + let (identifier, arguments) = match &call.nodes.2 { + sv_parser::MethodCallBody::User(method) => ( + &method.nodes.0, + method.nodes.2.as_ref().map(|paren| &paren.nodes.1), + ), + sv_parser::MethodCallBody::BuiltInMethodCall(method) => { + let sv_parser::BuiltInMethodCall::ArrayManipulationCall(method) = method.as_ref() + else { + return Err(unsupported("interface builtin method")); + }; + let sv_parser::ArrayMethodName::MethodIdentifier(identifier) = &method.nodes.0 else { + return Err(unsupported("interface builtin method")); + }; + if method.nodes.3.is_some() { + return Err(unsupported("with clause on interface method")); + } + ( + identifier.as_ref(), + method.nodes.2.as_ref().map(|paren| &paren.nodes.1), + ) + } + }; + let member = identifier_text(RefNode::MethodIdentifier(identifier), tree) + .ok_or_else(|| unsupported("interface method name"))?; + let name = scope::imported() + .interface_members + .get(&format!("{handle}.{member}")) + .cloned() + .ok_or_else(|| unsupported("method call"))?; + Ok((name, arguments)) +} + +fn instance_elements( + handle: &str, + dimensions: &[sv_parser::UnpackedDimension], + tree: &SyntaxTree, + env: &HashMap, + aliases: &HashMap, +) -> Converted { + let ranges = unpacked_ranges_from_dimensions_with_env(dimensions, tree, env, aliases)?; + validate_unpacked_dimension_sizes(&ranges, env)?; + let mut shape = Vec::new(); + let mut elements = vec![handle.to_string()]; + for range in ranges { + let left = eval_ast_const_expr(&range.left, env) + .ok_or_else(|| unsupported("interface array bound"))?; + let right = eval_ast_const_expr(&range.right, env) + .ok_or_else(|| unsupported("interface array bound"))?; + let count = usize::try_from(left.abs_diff(right)) + .ok() + .and_then(|count| count.checked_add(1)) + .filter(|count| { + elements + .len() + .checked_mul(*count) + .is_some_and(|count| count <= 4096) + }) + .ok_or_else(|| unsupported("interface array elaboration limit exceeded"))?; + shape.push(count); + elements = elements + .into_iter() + .flat_map(|prefix| { + (0..count).map(move |offset| { + let index = if left <= right { + left + offset as i128 + } else { + left - offset as i128 + }; + format!("{prefix}[{index}]") + }) + }) + .collect(); + } + Ok(ArrayBinding { elements, shape }) +} + +fn actual_handle_key( + expression: &sv_parser::Expression, + tree: &SyntaxTree, + env: &HashMap, + aliases: &HashMap, +) -> Converted { + let sv_parser::Expression::Primary(primary) = expression else { + return Err(unsupported("interface handle expression")); + }; + let sv_parser::Primary::Hierarchical(primary) = primary.as_ref() else { + return Err(unsupported("interface handle expression")); + }; + let mut handle = identifier_text(RefNode::HierarchicalIdentifier(&primary.nodes.1), tree) + .ok_or_else(|| unsupported("interface handle"))?; + for bit in &primary.nodes.2.nodes.1.nodes.0 { + let dimensions = PackedDimensions::new(HashMap::default(), env, aliases); + let expression = expr_from_expression_with_types(&bit.nodes.1, tree, &dimensions)?; + let value = expr_to_const(expression) + .and_then(|value| eval_ast_const_expr(&value, env)) + .ok_or_else(|| unsupported("nonconstant interface index"))?; + handle.push_str(&format!("[{value}]")); + } + Ok(handle) +} diff --git a/crates/celox-sv-analyzer/src/ast/packages.rs b/crates/celox-sv-analyzer/src/ast/packages.rs index 028e6256092..3f1332c7a96 100644 --- a/crates/celox-sv-analyzer/src/ast/packages.rs +++ b/crates/celox-sv-analyzer/src/ast/packages.rs @@ -21,6 +21,9 @@ use super::*; /// The analyzed packages of a design. #[derive(Debug, Clone, Default)] pub struct Packages { + pub(crate) interface_plan: Arc, + /// Original syntax shared with interface instances; never generated source. + pub(crate) interface_sources: HashMap, PathBuf)>, pub(super) timescales: Arc, packages: HashMap>, /// The compilation unit of each source file that declares items outside @@ -112,6 +115,11 @@ impl Packages { self.timescales.scope_scale(name) } + /// Use interface bindings supplied by the hierarchy's selected roots. + pub fn set_interface_plan(&mut self, plan: interfaces::NativeInterfacePlan) { + self.interface_plan = Arc::new(plan); + } + pub fn is_empty(&self) -> bool { self.packages.is_empty() } diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs index 68741814393..dd7381b71af 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs @@ -2,7 +2,11 @@ use super::*; -fn hierarchical_path(node: RefNode<'_>, syntax_tree: &SyntaxTree) -> Option> { +fn hierarchical_path( + node: RefNode<'_>, + syntax_tree: &SyntaxTree, + dimensions: &PackedDimensions, +) -> Option> { let Some(RefNode::HierarchicalIdentifier(identifier)) = unwrap_node!(node.clone(), HierarchicalIdentifier) else { @@ -13,11 +17,20 @@ fn hierarchical_path(node: RefNode<'_>, syntax_tree: &SyntaxTree) -> Option, select: RefNode<'_>) } } +/// Collapse an interface handle/member prefix using its bound symbols. Any +/// remaining path selects a packed-structure member of the interface signal. +fn bind_interface_path(path: &mut Vec) -> bool { + let imported = scope::imported(); + for length in (2..=path.len()).rev() { + if let Some(name) = imported.interface_members.get(&path[..length].join(".")) { + path.splice(..length, [name.clone()]); + return true; + } + } + false +} + fn selected_member<'a>( path: &[String], dimensions: &'a PackedDimensions, @@ -114,8 +140,9 @@ fn variable_path( node: RefNode<'_>, select: &sv_parser::Select, syntax_tree: &SyntaxTree, + dimensions: &PackedDimensions, ) -> Option> { - let mut path = hierarchical_path(node, syntax_tree)?; + let mut path = hierarchical_path(node, syntax_tree, dimensions)?; if let Some((members, _, last)) = &select.nodes.0 { for (_, name, indices) in members { if !indices.nodes.0.is_empty() { @@ -140,7 +167,7 @@ pub(in crate::ast) fn member_first_dimension_width( syntax_tree: &SyntaxTree, dimensions: &PackedDimensions, ) -> Option { - let path = variable_path(node, select, syntax_tree)?; + let path = variable_path(node, select, syntax_tree, dimensions)?; let (_, r#type) = selected_member(&path, dimensions)?; if let Some(range) = &select.nodes.2 { let sv_parser::PartSelectRange::ConstantRange(range) = &range.nodes.1 else { @@ -177,7 +204,7 @@ pub(in crate::ast) fn member_dimension_count( syntax_tree: &SyntaxTree, dimensions: &PackedDimensions, ) -> Option { - let path = variable_path(node, select, syntax_tree)?; + let path = variable_path(node, select, syntax_tree, dimensions)?; let (_, ty) = selected_member(&path, dimensions)?; let remaining = ty .packed_ranges @@ -198,15 +225,25 @@ pub(in crate::ast) fn variable_member( syntax_tree: &SyntaxTree, dimensions: &PackedDimensions, ) -> Converted { - let mut path = variable_path(node, select, syntax_tree) + let mut path = variable_path(node, select, syntax_tree, dimensions) .ok_or_else(|| unsupported("member access through an indexed structure"))?; - if let Some(base) = base { + let bound_interface = bind_interface_path(&mut path); + if !bound_interface && let Some(base) = base { path[0] = base; } - let (offset, r#type) = selected_member(&path, dimensions) - .ok_or_else(|| unsupported(format!("structure member `{}`", path.join("."))))?; let mut leaf_select = select.clone(); leaf_select.nodes.0 = None; + if bound_interface && path.len() == 1 { + return super::super::selects::lvalue_from_select( + path[0].clone(), + &leaf_select, + syntax_tree, + dimensions, + false, + ); + } + let (offset, r#type) = selected_member(&path, dimensions) + .ok_or_else(|| unsupported(format!("structure member `{}`", path.join("."))))?; let relative = super::super::selects::lvalue_from_select( path[0].clone(), &leaf_select, @@ -229,7 +266,7 @@ pub(in crate::ast) fn net_member( dimensions: &PackedDimensions, ) -> Converted { let indexed = || unsupported("member access through an indexed structure"); - let mut path = hierarchical_path(node, syntax_tree).ok_or_else(indexed)?; + let mut path = hierarchical_path(node, syntax_tree, dimensions).ok_or_else(indexed)?; if let Some((members, _, last)) = &select.nodes.0 { for (_, name, indices) in members { if !indices.nodes.0.is_empty() { @@ -245,10 +282,20 @@ pub(in crate::ast) fn net_member( .ok_or_else(|| unsupported("structure member name"))?, ); } - let (offset, r#type) = selected_member(&path, dimensions) - .ok_or_else(|| unsupported(format!("structure member `{}`", path.join("."))))?; + let bound_interface = bind_interface_path(&mut path); let mut leaf_select = select.clone(); leaf_select.nodes.0 = None; + if bound_interface && path.len() == 1 { + return super::super::selects::lvalue_from_constant_select( + path[0].clone(), + &leaf_select, + syntax_tree, + dimensions, + false, + ); + } + let (offset, r#type) = selected_member(&path, dimensions) + .ok_or_else(|| unsupported(format!("structure member `{}`", path.join("."))))?; let relative = super::super::selects::lvalue_from_constant_select( path[0].clone(), &leaf_select, diff --git a/crates/celox-sv-analyzer/src/ast/patterns.rs b/crates/celox-sv-analyzer/src/ast/patterns.rs index f95528ec534..6aa1c14bbdb 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns.rs @@ -88,7 +88,7 @@ fn typed_pattern_type( Ok(r#type) } -/// Serialize a typed constant pattern as positional values already converted +/// Bind a typed constant pattern as positional values already converted /// to its caller-side type (IEEE 1800-2023 10.9). Packed values become /// literals; only unpacked dimensions need positional patterns. pub(super) fn constant_typed_pattern_value( diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 6085343a7ef..32d6e399353 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -897,6 +897,15 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { arg_order, }]) } + sv_parser::SubroutineCall::MethodCall(call) => { + let (name, arguments) = native_interfaces::method_call(call, self.tree)?; + let (args, arg_order) = self.call_arguments(&name, arguments)?; + Ok(vec![Stmt::Call { + name, + args, + arg_order, + }]) + } sv_parser::SubroutineCall::SystemTfCall(system_call) => { let (name, args) = system_tf_call_parts(system_call, self.tree) .ok_or_else(|| unsupported("system task or function name"))?; @@ -1810,6 +1819,7 @@ pub(super) fn subroutine_argument_names( let mut shapes = HashMap::default(); let mut directions = HashMap::default(); for item in generate::subroutine_items(node, tree, const_env, type_aliases)? { + let _interface_scope = item.interface_scope(); for child in item.node.node() { let syntax = match child { RefNode::FunctionDeclaration(declaration) => function_syntax(declaration, tree), @@ -1906,6 +1916,7 @@ pub(super) fn subroutines_with_symbolic_parameters( let active = generate::subroutine_items(node, tree, const_env, module_type_aliases)?; let mut views = generate::ScopeViews::with_literals(packed_dimensions, parameter_literals); for item in &active { + let _interface_scope = item.interface_scope(); if item.is_parameter_declaration() { continue; } @@ -2146,6 +2157,7 @@ pub(super) fn initial_processes_from_module_node( let active = generate::items(node, tree, const_env, &type_aliases)?; let mut views = generate::ScopeViews::with_literals(packed_dimensions, parameter_literals); for (creation_order, item) in active.iter().enumerate() { + let _interface_scope = item.interface_scope(); if item.is_parameter_declaration() { continue; } diff --git a/crates/celox-sv-analyzer/src/ast/scope.rs b/crates/celox-sv-analyzer/src/ast/scope.rs index c3f0d248cae..07df7ff7b5d 100644 --- a/crates/celox-sv-analyzer/src/ast/scope.rs +++ b/crates/celox-sv-analyzer/src/ast/scope.rs @@ -15,6 +15,8 @@ use super::*; /// The symbols of a scope, independent of the syntax they came from. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub(super) struct ScopeSymbols { + /// Declaration inspection omits executable bodies; it is not simulation validation. + pub declarations_only: bool, /// Constant values of parameters and enum members, with their type /// markers. pub const_env: HashMap, @@ -37,11 +39,21 @@ pub(super) struct ScopeSymbols { /// Array parameters and constant variables, which are constant signals /// copied into each scope, and their initializers. pub signals: Vec, + pub ports: Vec, /// Package variables: each scope's signal denotes the package's object. pub state_signals: Vec, pub initial_processes: Vec, + pub comb_processes: Vec, + pub ff_processes: Vec, /// The names imports make visible, and the qualified names they denote. pub aliases: HashMap, + /// Hierarchical interface member paths bound to semantic signal names. + pub interface_members: HashMap, + pub interface_types: HashMap, + pub interface_arrays: HashMap, + pub interface_scopes: HashMap, + pub interface_declarations: HashSet, + pub interface_instances: HashMap, /// The names the imports of a generate block bind there to another /// declaration than outside it, by the source offset of the block. pub generate_imports: HashMap>, @@ -166,6 +178,12 @@ impl ScopeSymbols { self.parameters.push(parameter.clone()); } } + extend_missing(&mut self.interface_members, &other.interface_members); + extend_missing(&mut self.interface_types, &other.interface_types); + extend_missing(&mut self.interface_arrays, &other.interface_arrays); + extend_missing(&mut self.interface_scopes, &other.interface_scopes); + self.interface_declarations + .extend(other.interface_declarations.iter().copied()); extend_missing(&mut self.type_aliases, &other.type_aliases); extend_missing( &mut self.enum_constants.numbers, @@ -219,6 +237,10 @@ impl ScopeSymbols { self.initial_processes.push(process.clone()); } } + self.ports.extend(other.ports.iter().cloned()); + self.comb_processes + .extend(other.comb_processes.iter().cloned()); + self.ff_processes.extend(other.ff_processes.iter().cloned()); for import in &other.dpi_imports { if !self .dpi_imports @@ -377,6 +399,17 @@ impl ScopeSymbols { }) .collect(); ScopeSymbols { + declarations_only: self.declarations_only, + interface_instances: self.interface_instances.clone(), + interface_types: self.interface_types.clone(), + interface_arrays: self.interface_arrays.clone(), + interface_scopes: self.interface_scopes.clone(), + interface_declarations: self.interface_declarations.clone(), + interface_members: self + .interface_members + .iter() + .map(|(path, name)| (path.clone(), rename.name(name))) + .collect(), type_parameter_bindings: self.type_parameter_bindings.clone(), pattern_parameter_bindings: self.pattern_parameter_bindings.clone(), const_env, @@ -471,6 +504,18 @@ impl ScopeSymbols { .iter() .map(|import| import.renamed(rename.name(import.name()))) .collect(), + ports: self + .ports + .iter() + .map(|port| { + Port::new( + rename.name(&port.name), + port.direction, + rename.r#type(port.r#type.clone()), + port.is_net, + ) + }) + .collect(), signals: self .signals .iter() @@ -489,6 +534,18 @@ impl ScopeSymbols { ..signal.clone() }) .collect(), + comb_processes: self + .comb_processes + .iter() + .cloned() + .map(|process| rename.comb_process(process)) + .collect(), + ff_processes: self + .ff_processes + .iter() + .cloned() + .map(|process| rename.ff_process(process)) + .collect(), initial_processes: self .initial_processes .iter() @@ -548,6 +605,37 @@ pub(super) struct Renamer<'a> { } impl Renamer<'_> { + pub fn comb_process(&self, mut process: CombProcess) -> CombProcess { + process.condition = process.condition.map(|expr| self.const_expr(expr)); + process.body = process + .body + .into_iter() + .map(|stmt| self.stmt(stmt)) + .collect(); + process.sensitivity_body = process + .sensitivity_body + .into_iter() + .map(|stmt| self.stmt(stmt)) + .collect(); + for assignment in &mut process.assignments { + assignment.lhs = self.lvalue(assignment.lhs.clone()); + assignment.rhs = self.expr(assignment.rhs.clone()); + } + process + } + + pub fn ff_process(&self, mut process: FfProcess) -> FfProcess { + process.body = process + .body + .into_iter() + .map(|stmt| self.stmt(stmt)) + .collect(); + for event in &mut process.events { + event.signal = self.name(&event.signal); + } + process + } + pub fn name(&self, name: &str) -> String { self.names .get(name) diff --git a/crates/celox-sv-analyzer/src/ast/timescales.rs b/crates/celox-sv-analyzer/src/ast/timescales.rs index 921e99983d2..4b4e75bf4ad 100644 --- a/crates/celox-sv-analyzer/src/ast/timescales.rs +++ b/crates/celox-sv-analyzer/src/ast/timescales.rs @@ -18,7 +18,6 @@ struct ResolvedScope { call: system_functions::SystemCall, scale: Scale, display: DisplayScope, - is_interface: bool, } impl ResolvedScope { @@ -64,23 +63,6 @@ impl ResolvedScope { .replace('\\', "\\\\") .replace('"', "\\\"") } - - fn replacement(&self, prefix: Option<&str>) -> String { - if self.call == system_functions::SystemCall::Task(SystemTask::Printtimescale) { - format!("$display(\"{}\")", self.message(prefix)) - } else { - format!("32'sh{:08x}", self.value() as u32) - } - } -} - -/// Whether `call` is a timescale query or `$printtimescale`, whose argument -/// names a design element instead of a value. -pub(super) fn is_timescale_call(call: &sv_parser::SystemTfCall, tree: &SyntaxTree) -> bool { - matches!( - called_system_function(call, tree), - Some(SystemFunction::Timeunit | SystemFunction::Timeprecision) - ) || called_system_task(call, tree) == Some(SystemTask::Printtimescale) } #[derive(Debug, Clone, Copy)] @@ -99,7 +81,6 @@ enum ScopeKind { struct Scope { name: String, kind: ScopeKind, - is_interface: bool, start: usize, end: usize, scale: Scale, @@ -128,6 +109,23 @@ pub(super) struct Timescales { specified: [u8; 2], } +thread_local! { + static INTERFACE_INSTANCE: RefCell> = const { RefCell::new(None) }; +} + +pub(super) fn with_interface_instance(name: &str, analyze: impl FnOnce() -> T) -> T { + struct Restore(Option); + impl Drop for Restore { + fn drop(&mut self) { + INTERFACE_INSTANCE.with(|current| *current.borrow_mut() = self.0.take()); + } + } + let previous = + INTERFACE_INSTANCE.with(|current| current.borrow_mut().replace(name.to_string())); + let _restore = Restore(previous); + analyze() +} + #[cfg(test)] thread_local! { static COLLECTIONS: std::cell::Cell = const { std::cell::Cell::new(0) }; @@ -424,10 +422,6 @@ fn scope_node(node: RefNode<'_>, tree: &SyntaxTree) -> Option { Some(Scope { name, kind, - is_interface: matches!( - node, - RefNode::InterfaceDeclarationAnsi(_) | RefNode::InterfaceDeclarationNonansi(_) - ), start: offset(node)?, end, scale: DEFAULT, @@ -798,23 +792,6 @@ impl Timescales { .map(|scope| scope.value()) } - pub(super) fn interface_path_queries<'a>( - &'a self, - tree: &'a SyntaxTree, - ) -> Converted< - impl Fn(&sv_parser::SystemTfCall, system_functions::CallSite) -> Converted> + 'a, - > { - let unit = self - .units - .get(key(tree)) - .ok_or_else(|| unsupported("missing interface query time scope"))?; - // Resolve the content key once for this rewrite, not for each query. - Ok(move |call: &sv_parser::SystemTfCall, site| { - self.resolve(call, tree, unit, site) - .map(|scope| scope.is_interface.then(|| scope.replacement(None))) - }) - } - fn resolve( &self, call: &sv_parser::SystemTfCall, @@ -827,7 +804,6 @@ impl Timescales { let checked = system_functions::check_call(name, args.as_deref(), site)?; let at = offset(RefNode::SystemTfCall(call)).unwrap_or_default(); let current = scope_at(&unit.scopes, &unit.parents, at).map(|i| &unit.scopes[i]); - let mut interface_target = false; let mut display = match current { Some(scope) if scope.kind == ScopeKind::Package => { DisplayScope::Absolute(scope.name.clone()) @@ -877,7 +853,14 @@ impl Timescales { .ok_or_else(|| unsupported("timescale query identifier"))?, ); let first = &path[0]; + let imported = scope::imported(); let (mut target, start) = if hierarchy.nodes.0.is_none() + && let Some(interface) = imported.interface_types.get(first) + && let Some(target) = self.definitions.get(interface) + { + display = DisplayScope::Relative(path.join(".")); + (target, 1) + } else if hierarchy.nodes.0.is_none() && current.is_some_and(|s| s.instances.contains_key(first)) { display = DisplayScope::Relative(path.join(".")); @@ -932,7 +915,6 @@ impl Timescales { unsupported(format!("unknown timescale query module `{module}`")) })?; } - interface_target = target.is_interface; target.scale } } @@ -941,7 +923,6 @@ impl Timescales { call: checked, scale, display, - is_interface: interface_target, }) } @@ -961,61 +942,6 @@ impl Timescales { .resolve(call, tree, &design.units[source], site) .map(|scope| scope.message(prefix)) } - - pub(super) fn interface_print_statement( - &self, - call: &sv_parser::SystemTfCall, - tree: &SyntaxTree, - site: system_functions::CallSite, - prefix: &str, - indices: &[String], - ) -> Converted { - let source = key(tree); - let scope = self.resolve(call, tree, &self.units[source], site)?; - let args = if matches!(scope.display, DisplayScope::Relative(_)) && !indices.is_empty() { - format!(", {}", indices.join(", ")) - } else { - String::new() - }; - Ok(format!( - "$display(\"{}\"{args})", - scope.message(Some(prefix)) - )) - } - - pub(super) fn print_needs_instance_scope( - &self, - call: &sv_parser::SystemTfCall, - tree: &SyntaxTree, - site: system_functions::CallSite, - ) -> Converted { - let scope = self.resolve(call, tree, &self.units[key(tree)], site)?; - Ok(matches!(scope.display, DisplayScope::Relative(_))) - } - - pub(super) fn interface_replacement( - &self, - call: &sv_parser::SystemTfCall, - tree: &SyntaxTree, - ty: &str, - handle: &str, - site: system_functions::CallSite, - ) -> Converted { - let (name, args) = - system_tf_call_parts(call, tree).ok_or_else(|| unsupported("timescale query name"))?; - let checked = system_functions::check_call(name, args.as_deref(), site)?; - let scope = self - .definitions - .get(ty) - .ok_or_else(|| unsupported(format!("unknown timescale query design element `{ty}`")))?; - Ok(ResolvedScope { - call: checked, - scale: scope.scale, - display: DisplayScope::Relative(handle.to_string()), - is_interface: true, - } - .replacement(None)) - } } pub(super) fn print_message( @@ -1023,6 +949,7 @@ pub(super) fn print_message( tree: &SyntaxTree, site: system_functions::CallSite, ) -> Converted { + let prefix = INTERFACE_INSTANCE.with(|current| current.borrow().clone()); DESIGN.with(|context| { let context = context.borrow(); if let Some(prepared) = &context.prepared @@ -1031,9 +958,11 @@ pub(super) fn print_message( context .design .resolve(call, tree, &prepared.unit, site) - .map(|scope| scope.message(None)) + .map(|scope| scope.message(prefix.as_deref())) } else { - context.design.print_message(call, tree, site, None) + context + .design + .print_message(call, tree, site, prefix.as_deref()) } }) } @@ -1519,7 +1448,7 @@ mod tests { } #[test] - fn interface_handle_queries_reject_invalid_operands_and_macro_edits() { + fn interface_handle_queries_validate_operands_without_editing_macros() { for (instance, expression) in [ ("I i();", "$timeunit(i, 1)"), ("I i();", "$timeprecision(i + 1)"), @@ -1531,8 +1460,7 @@ mod tests { "interface I; timeunit 1ns / 1ps; endinterface module Top(output int y); timeunit 1ns / 1ps; {instance} assign y = {expression}; endmodule" ); assert!( - crate::elaborate_interfaces(&[(&code, Path::new("invalid_handle_query.sv"))]) - .is_err(), + crate::analyze_source(&code, Path::new("invalid_handle_query.sv")).is_err(), "accepted {expression} with {instance}" ); } @@ -1544,14 +1472,8 @@ mod tests { let code = format!( "{definition}\ninterface I; timeunit 1ns / 1ps; endinterface module Top(output int y); timeunit 1ns / 1ps; I i(); assign y = {call}; endmodule" ); - let error = crate::elaborate_interfaces(&[(&code, Path::new("macro_handle_query.sv"))]) - .unwrap_err(); - assert!( - error - .to_string() - .contains("macro-origin interface timescale query"), - "{error}" - ); + let result = crate::analyze_source(&code, Path::new("macro_handle_query.sv")); + assert!(result.is_ok(), "{result:?}"); } } @@ -1574,21 +1496,18 @@ mod tests { let prefix = "`define SCALE $timeunit()\ninterface I; timeunit 100ps / 10fs; function automatic int u(); return `SCALE; endfunction endinterface"; let code = format!("{prefix} module Top(); timeunit 1ms / 1us; localparam U=`SCALE; endmodule"); - let rewritten = - crate::elaborate_interfaces(&[(&code, Path::new("unused_macro_interface.sv"))]) - .unwrap() - .unwrap(); - let ir = - crate::analyze_source(&rewritten[0], Path::new("unused_macro_interface.sv")).unwrap(); + let ir = crate::analyze_source(&code, Path::new("unused_macro_interface.sv")).unwrap(); + assert_eq!(ir.modules()[0].parameters()[0].resolved_value(), Some(-3)); + let code = format!( + "{prefix} module Top(output int y); timeunit 1ms / 1us; localparam U=`SCALE; I i(); assign y=i.u(); endmodule" + ); + let ir = crate::analyze_source(&code, Path::new("used_macro_interface.sv")).unwrap(); assert_eq!(ir.modules()[0].parameters()[0].resolved_value(), Some(-3)); - let code = format!("{prefix} module Top(); timeunit 1ms / 1us; I i(); endmodule"); - let error = crate::elaborate_interfaces(&[(&code, Path::new("used_macro_interface.sv"))]) - .unwrap_err(); assert!( - error - .to_string() - .contains("macro or compiler directive in interface `I`"), - "{error}" + ir.modules()[0] + .subroutines() + .iter() + .any(|function| function.name == "i$u") ); } @@ -1693,12 +1612,9 @@ mod tests { } #[test] - fn interface_query_rewriting_preserves_macros_in_module_scopes() { + fn interface_bindings_preserve_macros_in_module_scopes() { let code = "`define U $timeunit()\ninterface I; timeunit 1ns / 1ps; endinterface module Top(); timeunit 1ms / 1us; localparam U=`U; endmodule module Child(); timeunit 1us / 1ns; localparam U=`U; endmodule"; - let elaborated = crate::elaborate_interfaces(&[(code, Path::new("macro_times.sv"))]) - .unwrap() - .unwrap(); - let result = crate::analyze_source(&elaborated[0], Path::new("macro_times.sv")).unwrap(); + let result = crate::analyze_source(code, Path::new("macro_times.sv")).unwrap(); for (name, value) in [("Top", -3), ("Child", -6)] { let module = result.modules().iter().find(|m| m.name() == name).unwrap(); assert_eq!(module.parameters()[0].resolved_value(), Some(value)); @@ -1706,7 +1622,7 @@ mod tests { } #[test] - fn interface_query_rewriting_validates_discarded_and_hidden_operands() { + fn interface_queries_validate_discarded_and_hidden_operands() { for expression in [ "$timeunit(missing);", "void'($timeprecision(1));", @@ -1716,8 +1632,7 @@ mod tests { "interface I; timeunit 1ns / 1ps; function automatic int f(); {expression} return 0; endfunction endinterface module Top(); timeunit 1ns / 1ps; I i(); endmodule" ); assert!( - crate::elaborate_interfaces(&[(&code, Path::new("invalid_interface_query.sv"))]) - .is_err(), + crate::analyze_source(&code, Path::new("invalid_interface_query.sv")).is_err(), "accepted {expression}" ); } @@ -1728,8 +1643,7 @@ mod tests { ] { let code = format!("interface I; {items} endinterface module Top(); endmodule"); assert!( - crate::elaborate_interfaces(&[(&code, Path::new("invalid_interface_scale.sv"))]) - .is_err(), + crate::analyze_source(&code, Path::new("invalid_interface_scale.sv")).is_err(), "accepted {items}" ); } diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index a84144a3c27..a415d0485f6 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -821,6 +821,7 @@ fn reject_silently_ignored_constructs_with_dimensions( let mut views = generate::ScopeViews::new(indexed_dimensions); for item in &active { let _constant_functions = item.enter(); + let _interface_scope = item.interface_scope(); let dimensions = views.dimensions(item); reject_silently_ignored_constructs_with_dimensions( item.node.node(), diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index dd619a5d65e..053456a0b82 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -536,6 +536,22 @@ impl Type { self.resolved_width } + /// Preserve resolved layout while rebinding names in declaration contracts. + pub(crate) fn map_range_expressions( + mut self, + mut map: impl FnMut(ConstExpr) -> ConstExpr, + ) -> Self { + for range in &mut self.packed_ranges { + range.left = map(range.left.clone()); + range.right = map(range.right.clone()); + } + for range in &mut self.unpacked_ranges { + range.left = map(range.left.clone()); + range.right = map(range.right.clone()); + } + self + } + pub(crate) fn has_symbolic_ranges(&self) -> bool { let constants = fxhash::FxHashMap::default(); self.packed_ranges.iter().any(|range| { @@ -1042,6 +1058,18 @@ impl From for InsideItem { } } +impl From for ast::InsideItem { + fn from(item: InsideItem) -> Self { + match item { + InsideItem::Value(value) => ast::InsideItem::Value(value.into()), + InsideItem::Range { low, high } => ast::InsideItem::Range { + low: low.into(), + high: high.into(), + }, + } + } +} + impl From for ConstExpr { fn from(expr: ast::ConstExpr) -> Self { match expr { @@ -1339,6 +1367,71 @@ impl From for Expr { } } +impl From for ast::Expr { + fn from(expr: Expr) -> Self { + match expr { + Expr::Ident(name) => ast::Expr::Ident(name), + Expr::Literal(value) => ast::Expr::Literal(value), + Expr::Select { + expr, + msb, + lsb, + signed, + } => ast::Expr::Select { + expr: Box::new((*expr).into()), + msb: msb.into(), + lsb: lsb.into(), + signed, + }, + Expr::Concat(parts) => ast::Expr::Concat(parts.into_iter().map(Into::into).collect()), + Expr::RepeatConcat { count, parts } => ast::Expr::RepeatConcat { + count: count.into(), + parts: parts.into_iter().map(Into::into).collect(), + }, + Expr::Resize { + expr, + width, + signed, + } => ast::Expr::Resize { + expr: Box::new((*expr).into()), + width, + signed, + }, + Expr::Unary { op, expr } => ast::Expr::Unary { + op: op.into(), + expr: Box::new((*expr).into()), + }, + Expr::Binary { left, op, right } => ast::Expr::Binary { + left: Box::new((*left).into()), + op: op.into(), + right: Box::new((*right).into()), + }, + Expr::Mux { + condition, + then_expr, + else_expr, + } => ast::Expr::Mux { + condition: Box::new((*condition).into()), + then_expr: Box::new((*then_expr).into()), + else_expr: Box::new((*else_expr).into()), + }, + Expr::Call { + callee, + args, + arg_order, + } => ast::Expr::Call { + arg_order: arg_order.clone(), + callee, + args: args.into_iter().map(|arg| arg.map(Into::into)).collect(), + }, + Expr::Inside { expr, items } => ast::Expr::Inside { + expr: Box::new((*expr).into()), + items: items.into_iter().map(Into::into).collect(), + }, + } + } +} + impl From for UnaryOp { fn from(op: ast::UnaryOp) -> Self { match op { diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index 3fb274eef0b..9150260bf5e 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -22,12 +22,8 @@ pub mod syntax; pub mod system_functions; pub mod typecheck; -pub use ast::interfaces::elaborate_interfaces_with_bindings; -pub use ast::interfaces::{ - InterfaceElaboration, elaborate_interfaces_with_metadata, - elaborate_interfaces_with_metadata_and_roots, -}; -pub use ast::interfaces::{InterfacePrototype, interface_prototypes}; +pub use ast::interfaces::{InterfacePrototype, interface_prototypes, interface_prototypes_for}; +pub use ast::interfaces::{NativeInterfacePlan, plan_interfaces}; pub use ast::packages::Packages; pub use ast::{ModuleInterface, ModuleInterfaces}; pub use ir::Ir; @@ -174,23 +170,6 @@ impl AnalyzerError { } } -/// Rewrite `sources` so that they no longer declare or use interfaces, or -/// return `None` when no source declares one. See [`ast::interfaces`]. -pub fn elaborate_interfaces( - sources: &[(&str, &Path)], -) -> Result>, AnalyzerError> { - ast::interfaces::elaborate_interfaces(sources) -} - -/// Expand interfaces using the design roots selected by the hierarchy -/// elaborator when resolving queries before flattening. -pub fn elaborate_interfaces_with_roots( - sources: &[(&str, &Path)], - roots: &[&str], -) -> Result>, AnalyzerError> { - ast::interfaces::elaborate_interfaces_with_roots(sources, Some(roots)) -} - /// Time declarations for synthetic foreign declaration files, preserving the /// authored design's explicit/default settings and simulation precision. pub fn generated_time_declarations( @@ -204,6 +183,12 @@ pub fn generated_time_declarations( pub fn analyze_source(code: &str, path: &Path) -> Result { ast::with_call_sites(|| { let syntax_tree = syntax::parse_source(code, path)?; + if syntax_tree + .into_iter() + .any(|node| matches!(node, sv_parser::RefNode::InterfaceDeclarationAnsi(_))) + { + return analyze_interface_source(code, path, "", &HashMap::default()); + } let source = ast::Source::from_syntax(&syntax_tree)?; analyze::analyze_source(source) }) @@ -219,6 +204,12 @@ pub fn analyze_source_with_module_parameter_overrides( ) -> Result { ast::with_call_sites(|| { let syntax_tree = syntax::parse_source(code, path)?; + if syntax_tree + .into_iter() + .any(|node| matches!(node, sv_parser::RefNode::InterfaceDeclarationAnsi(_))) + { + return analyze_interface_source(code, path, module_name, parameter_overrides); + } let source = ast::Source::from_syntax_with_module_parameter_overrides( &syntax_tree, module_name, @@ -228,6 +219,75 @@ pub fn analyze_source_with_module_parameter_overrides( }) } +fn analyze_interface_source( + code: &str, + path: &Path, + override_module: &str, + overrides: &HashMap, +) -> Result { + let source = ParsedSource::parse(code, path)?; + let packages = ParsedSource::analyze_packages(&[&source])?; + let plan = &packages.interface_plan; + let mut names = source + .module_names() + .iter() + .filter(|name| { + plan.modules.contains_key(*name) + || !plan + .modules + .values() + .any(|binding| binding.original == **name) + }) + .cloned() + .collect::>(); + names.extend( + plan.modules + .keys() + .filter(|name| !source.module_names().contains(name)) + .cloned(), + ); + let mut modules = Vec::new(); + for name in names { + let values = if name == override_module + || plan + .modules + .get(&name) + .is_some_and(|binding| binding.original == override_module) + { + overrides + .iter() + .map(|(name, value)| { + ( + name.clone(), + if *value < 0 { + ir::ConstExpr::Unary { + op: ir::UnaryOp::Minus, + expr: Box::new(ir::ConstExpr::Literal( + value.unsigned_abs().to_string(), + )), + } + } else { + ir::ConstExpr::Literal(value.to_string()) + }, + ) + }) + .collect() + } else { + HashMap::default() + }; + let ir = source.analyze_module( + &name, + &values, + &[], + &[], + &ModuleInterfaces::default(), + &packages, + )?; + modules.extend(ir.modules().iter().cloned()); + } + Ok(Ir::new(modules)) +} + /// Return the module names declared in a SystemVerilog source without /// performing semantic lowering of their bodies or port declarations. pub fn source_module_names(code: &str, path: &Path) -> Result, AnalyzerError> { diff --git a/crates/celox-sv-analyzer/src/parsed.rs b/crates/celox-sv-analyzer/src/parsed.rs index 052fe3b0658..52b1dfd45d4 100644 --- a/crates/celox-sv-analyzer/src/parsed.rs +++ b/crates/celox-sv-analyzer/src/parsed.rs @@ -14,8 +14,9 @@ use crate::{AnalyzerError, Ir, ModuleInterfaces, Packages, analyze, ast, ir, syn /// remain local to each analysis. Like `sv-parser`'s tree, this value is confined /// to the parsing thread; consumers can share it there with [`std::rc::Rc`]. pub struct ParsedSource { + code: std::rc::Rc, path: PathBuf, - tree: sv_parser::SyntaxTree, + tree: std::rc::Rc, index: ast::module_index::ModuleIndex, } @@ -24,8 +25,9 @@ impl ParsedSource { let tree = syntax::parse_source(code, path)?; let index = ast::with_call_sites(|| ast::module_index::ModuleIndex::new(&tree))?; Ok(Self { + code: code.into(), path: path.to_path_buf(), - tree, + tree: std::rc::Rc::new(tree), index, }) } @@ -41,7 +43,7 @@ impl ParsedSource { .iter() .cloned() .collect::>(); - for node in &self.tree { + for node in self.tree.as_ref() { let identifier = match node { sv_parser::RefNode::InterfaceDeclarationAnsi(interface) => { &interface.nodes.0.nodes.3 @@ -88,9 +90,39 @@ impl ParsedSource { ) -> Result { let trees: Vec<_> = sources .iter() - .map(|source| (&source.tree, source.path.as_path())) + .map(|source| (source.tree.as_ref(), source.path.as_path())) .collect(); - ast::with_call_sites(|| Packages::analyze_with_roots(&trees, roots)) + ast::with_call_sites(|| { + let mut packages = Packages::analyze_with_roots(&trees, roots)?; + for source in sources { + for node in source.tree.as_ref() { + if let sv_parser::RefNode::InterfaceDeclarationAnsi(declaration) = node + && let Some(name) = + ast::component_identifier(&declaration.nodes.0.nodes.3, &source.tree) + && packages + .interface_sources + .insert(name.clone(), (source.tree.clone(), source.path.clone())) + .is_some() + { + return Err(AnalyzerError::DuplicateModule { name }); + } + } + } + if !packages.interface_sources.is_empty() + && trees.iter().any(|(tree, _)| { + tree.into_iter() + .any(|node| matches!(node, sv_parser::RefNode::InterfacePortHeader(_))) + }) + { + let sources = sources + .iter() + .map(|source| (source.code.as_ref(), source.path.as_path())) + .collect::>(); + packages.interface_plan = + std::sync::Arc::new(ast::interfaces::plan_interfaces(&sources, &[])?); + } + Ok(packages) + }) } /// Analyze an instance using its value and caller-resolved type bindings. @@ -114,6 +146,37 @@ impl ParsedSource { ) } + /// Inspect declaration shapes without lowering procedures or tasks. + /// The returned IR is metadata for tooling, not an executable simulation. + pub fn analyze_module_declarations( + &self, + module_name: &str, + overrides: &HashMap, + packages: &Packages, + ) -> Result { + let overrides = overrides + .iter() + .map(|(name, value)| (name.clone(), value.clone().into())) + .collect(); + ast::with_call_sites(|| { + let source = ast::Source::from_indexed_syntax_module( + &self.tree, + &self.path, + &self.index, + module_name, + ast::ModuleParameterBindings { + declarations_only: true, + values: &overrides, + types: &[], + patterns: &[], + }, + &ModuleInterfaces::default(), + packages, + )?; + analyze::analyze_source(source) + }) + } + /// Analyze without rewriting the source, retaining literal override /// types. The module may use the packages this source declares. pub fn analyze_module_with_parameter_expr_overrides( @@ -146,6 +209,7 @@ impl ParsedSource { &self.index, module_name, ast::ModuleParameterBindings { + declarations_only: false, values: &overrides, types: type_overrides, patterns: pattern_overrides, @@ -588,3 +652,425 @@ mod pattern_override_tests { } } } + +#[cfg(test)] +mod native_interface_tests { + use super::*; + + #[test] + fn binds_generated_interface_instances_in_their_own_scopes() { + let source = ParsedSource::parse( + r#" + interface Bus #(parameter W = 4); + timeunit 1ns / 1ps; + logic [W-1:0] value; + endinterface + module Child(Bus bus); + timeunit 1us / 1ns; + logic [7:0] copy; + assign copy = bus.value; + endmodule + module Top(output int u); + timeunit 1us / 1ns; + for (genvar i=0; i<2; i++) begin : g + Bus #(.W(i+3)) local_info(); + assign local_info.value = i; + Child child(.bus(local_info)); + end + if (1) begin : h + Bus local_info(); + assign local_info.value = 1; + assign u = $timeunit(local_info); + end + endmodule + "#, + Path::new("native_generated_interface.sv"), + ) + .unwrap(); + let ir = source + .analyze_module_with_parameter_expr_overrides( + "Top", + &HashMap::default(), + &ModuleInterfaces::default(), + ) + .unwrap(); + let top = &ir.modules()[0]; + assert_eq!(top.instances().len(), 2); + for (index, instance) in top.instances().iter().enumerate() { + assert_eq!( + instance.port_connections()[0].actual_expr(), + Some(&ir::Expr::Ident(format!("g[{index}].local_info$value"))) + ); + } + for (name, width) in [ + ("g[0].local_info$value", 3), + ("g[1].local_info$value", 4), + ("h.local_info$value", 4), + ] { + assert_eq!( + top.signals() + .iter() + .find(|signal| signal.name() == name) + .unwrap() + .r#type() + .resolved_width(), + Some(width) + ); + } + assert_eq!(top.assignments().len(), 4); + } + + #[test] + fn resolves_interface_parameters_in_array_and_select_bounds() { + let source = ParsedSource::parse( + r#" + interface Cfg #(parameter N = 3); endinterface + interface Lane; logic [3:0] data; endinterface + module Top(input logic [7:0] a, output logic [3:0] y); + Cfg cfg(); + Lane rows[cfg.N](); + assign y = a[cfg.N:0]; + endmodule + "#, + Path::new("native_interface_bounds.sv"), + ) + .unwrap(); + let ir = source + .analyze_module_with_parameter_expr_overrides( + "Top", + &HashMap::default(), + &ModuleInterfaces::default(), + ) + .unwrap(); + let top = &ir.modules()[0]; + assert_eq!(top.signals().len(), 3); + assert_eq!(top.signals()[2].name(), "rows[2]$data"); + assert_eq!(top.assignments().len(), 1); + } + + #[test] + fn keeps_interface_timescales_and_instance_names_in_original_syntax() { + let source = ParsedSource::parse( + r#" + `define UNIT $timeunit() + interface ClockInfo; + timeunit 100ps / 10fs; + localparam U = `UNIT; + initial $printtimescale; + endinterface + module Top; + timeunit 1ms / 1us; + ClockInfo info[1:2](); + localparam U = `UNIT; + endmodule + "#, + Path::new("native_interface_timescales.sv"), + ) + .unwrap(); + let ir = source + .analyze_module_with_parameter_expr_overrides( + "Top", + &HashMap::default(), + &ModuleInterfaces::default(), + ) + .unwrap(); + let top = &ir.modules()[0]; + assert_eq!( + top.parameters() + .iter() + .find(|p| p.name() == "U") + .unwrap() + .resolved_value(), + Some(-3) + ); + let messages = top + .initial_processes() + .iter() + .flat_map(|process| process.body()) + .filter_map(|statement| { + if let ir::Stmt::SystemTask { args, .. } = statement + && let Some(ir::SystemTaskArg::Str(message)) = args.first() + { + Some(message.as_str()) + } else { + None + } + }) + .collect::>(); + assert_eq!( + messages, + [ + "Time scale of (%m.info[1]) is 100ps / 10fs", + "Time scale of (%m.info[2]) is 100ps / 10fs", + ] + ); + } + + #[test] + fn binds_generic_child_interfaces_without_cloning_source() { + let source = ParsedSource::parse( + r#" + interface Bus #(parameter W = 4); + logic [W-1:0] request, response; + endinterface + module Child(interface bus); + assign bus.response = bus.request + 1; + endmodule + module Top(input logic [7:0] a, output logic [7:0] y); + Bus #(.W(8)) bus(); + Child child(.bus(bus)); + assign bus.request = a; + assign y = bus.response; + endmodule + "#, + Path::new("generic.sv"), + ) + .unwrap(); + let packages = ParsedSource::analyze_packages(&[&source]).unwrap(); + let ir = source + .analyze_module( + "Top", + &HashMap::default(), + &[], + &[], + &ModuleInterfaces::default(), + &packages, + ) + .unwrap(); + let instance = &ir.modules()[0].instances()[0]; + assert_eq!(instance.port_connections().len(), 2); + let overrides = instance + .parameter_overrides() + .iter() + .map(|parameter| { + ( + parameter.name().to_string(), + parameter.value().unwrap().clone(), + ) + }) + .collect(); + let child = source + .analyze_module( + instance.module_name(), + &overrides, + &[], + &[], + &ModuleInterfaces::default(), + &packages, + ) + .unwrap(); + assert_eq!(child.modules()[0].name(), instance.module_name()); + assert_eq!(child.modules()[0].ports().len(), 2); + assert!( + child.modules()[0] + .ports() + .iter() + .all(|port| port.r#type().resolved_width() == Some(8)) + ); + } + + #[test] + fn binds_modport_members_and_parameter_widths_without_source_elaboration() { + let source = ParsedSource::parse( + r#" + interface Bus #(parameter W = 4); + logic [W-1:0] request, response; + modport slave(input request, output response); + endinterface + module Child(Bus.slave bus); + assign bus.response = bus.request + 1; + endmodule + "#, + Path::new("modport.sv"), + ) + .unwrap(); + let overrides = + HashMap::from_iter([("bus$W".to_string(), ir::ConstExpr::Literal("8".to_string()))]); + let ir = source + .analyze_module_with_parameter_expr_overrides( + "Child", + &overrides, + &ModuleInterfaces::default(), + ) + .unwrap(); + let module = &ir.modules()[0]; + assert_eq!(module.ports().len(), 2); + assert!(module.signals().is_empty()); + assert_eq!(module.ports()[0].name(), "bus$request"); + assert_eq!(module.ports()[0].r#type().resolved_width(), Some(8)); + assert_eq!(module.ports()[0].direction(), ir::PortDirection::Input); + assert_eq!(module.ports()[1].direction(), ir::PortDirection::Output); + } + + #[test] + fn binds_interface_processes_from_another_compilation_unit() { + let bus = ParsedSource::parse( + r#" + interface Bus #(parameter W = 4)(input logic clk); + logic [W-1:0] request, response; + initial response = 1; + always_ff @(posedge clk) response <= request + 1; + endinterface + "#, + Path::new("bus.sv"), + ) + .unwrap(); + let top = ParsedSource::parse( + r#" + module Top(input logic clk, input logic [7:0] a, output logic [7:0] y); + Bus #(.W(8)) bus(.clk(clk)); + assign bus.request = a; + assign y = bus.response; + endmodule + "#, + Path::new("top.sv"), + ) + .unwrap(); + let packages = ParsedSource::analyze_packages(&[&bus, &top]).unwrap(); + let ir = top + .analyze_module( + "Top", + &HashMap::default(), + &[], + &[], + &ModuleInterfaces::default(), + &packages, + ) + .unwrap(); + let module = &ir.modules()[0]; + assert!(module.instances().is_empty()); + assert_eq!(module.ff_processes().len(), 1); + assert_eq!(module.ff_processes()[0].events()[0].signal(), "bus$clk"); + assert_eq!(module.initial_processes().len(), 1); + assert_eq!(module.comb_processes().len(), 3); + } + + #[test] + fn binds_interface_instances_without_source_elaboration() { + let source = ParsedSource::parse( + r#" + interface Bus #(parameter W = 4); + logic [W-1:0] request, response; + assign response = request + 1; + endinterface + module Top #(parameter N = 8)(input logic [N-1:0] a, output logic [N-1:0] y); + Bus #(.W(N)) bus(); + assign bus.request = a; + assign y = bus.response; + endmodule + "#, + Path::new("native_interface.sv"), + ) + .unwrap(); + let ir = source + .analyze_module_with_parameter_expr_overrides( + "Top", + &HashMap::default(), + &ModuleInterfaces::default(), + ) + .unwrap(); + let top = &ir.modules()[0]; + assert!(top.instances().is_empty()); + assert_eq!( + top.signals() + .iter() + .find(|signal| signal.name() == "bus$request") + .unwrap() + .r#type() + .resolved_width(), + Some(8) + ); + assert_eq!(top.comb_processes().len(), 3); + } +} + +#[cfg(test)] +mod declaration_tests { + use super::*; + + #[test] + fn inspects_timed_module_shapes_without_editing_procedure_tokens() { + let source = ParsedSource::parse( + r#" + module Top #(parameter W = 3)(input logic [2*W-1:0] a, output logic [W-1:0] y); + logic [W-1:0] memory[2]; + wire unused; + task automatic delayed(); #2 y = a; endtask + initial forever begin #1; delayed(); end + final $display("done"); + endmodule + "#, + Path::new("timed_declarations.sv"), + ) + .unwrap(); + let packages = ParsedSource::analyze_packages(&[&source]).unwrap(); + let overrides = + HashMap::from_iter([("W".to_string(), ir::ConstExpr::Literal("9".to_string()))]); + assert!( + source + .analyze_module( + "Top", + &overrides, + &[], + &[], + &ModuleInterfaces::default(), + &packages + ) + .is_err() + ); + let ir = source + .analyze_module_declarations("Top", &overrides, &packages) + .unwrap(); + let module = &ir.modules()[0]; + assert_eq!(module.ports()[0].r#type().resolved_width(), Some(18)); + assert_eq!(module.ports()[1].r#type().resolved_width(), Some(9)); + assert_eq!( + module + .signals() + .iter() + .find(|s| s.name() == "memory") + .unwrap() + .r#type() + .resolved_width(), + Some(18) + ); + assert!(module.initial_processes().is_empty()); + assert!(module.ff_processes().is_empty()); + assert!(module.comb_processes().is_empty()); + } + + #[test] + fn inspects_interfaces_with_timed_processes_from_original_declarations() { + let source = ParsedSource::parse( + r#" + interface Bus #(parameter W = 4); + logic [W-1:0] value; + initial forever #1 value = value + 1; + endinterface + module Top(output logic [7:0] y); + Bus #(.W(8)) bus(); + assign y = bus.value; + endmodule + "#, + Path::new("timed_interface_declarations.sv"), + ) + .unwrap(); + let packages = ParsedSource::analyze_packages(&[&source]).unwrap(); + let ir = source + .analyze_module_declarations("Top", &HashMap::default(), &packages) + .unwrap(); + let module = &ir.modules()[0]; + assert_eq!(module.ports()[0].r#type().resolved_width(), Some(8)); + assert_eq!( + module + .signals() + .iter() + .find(|s| s.name() == "bus$value") + .unwrap() + .r#type() + .resolved_width(), + Some(8) + ); + assert!(module.initial_processes().is_empty()); + } +} diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index d9fd95686a2..90b6bb7b1f6 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -3732,9 +3732,69 @@ fn imports_a_dpi_function_declared_in_a_package() { ); } -fn elaborate(source: &str) -> Result, AnalyzerError> { - elaborate_interfaces(&[(source, Path::new("interfaces.sv"))]) - .map(|sources| sources.map(|mut sources| sources.remove(0))) +fn native_interface_module(source: &str, name: &str) -> ir::Module { + let parsed = ParsedSource::parse(source, Path::new("interfaces.sv")).unwrap(); + let packages = ParsedSource::analyze_packages(&[&parsed]).unwrap(); + parsed + .analyze_module( + name, + &HashMap::default(), + &[], + &[], + &ModuleInterfaces::default(), + &packages, + ) + .unwrap() + .modules()[0] + .clone() +} + +fn assert_interface_member( + plan: &NativeInterfacePlan, + module: &str, + port: &str, + member: &str, + direction: ir::PortDirection, +) { + let port = plan.modules[module] + .ports + .iter() + .find(|p| p.name == port) + .unwrap(); + assert!( + port.members + .iter() + .any(|(name, value)| name == member && ir::PortDirection::from(*value) == direction), + "{port:?}" + ); +} + +fn elaborate(source: &str) -> Result, AnalyzerError> { + let plan = plan_interfaces(&[(source, Path::new("interfaces.sv"))], &[])?; + Ok((!plan.modules.is_empty()).then_some(plan)) +} + +fn native_interface_sources(sources: &[(&str, &Path)]) -> Result, AnalyzerError> { + let parsed = sources + .iter() + .map(|(code, path)| ParsedSource::parse(code, path)) + .collect::, _>>()?; + let packages = ParsedSource::analyze_packages(&parsed.iter().collect::>())?; + let mut modules = Vec::new(); + for source in &parsed { + for name in source.module_names() { + let ir = source.analyze_module( + name, + &HashMap::default(), + &[], + &[], + &ModuleInterfaces::default(), + &packages, + )?; + modules.extend(ir.modules().iter().cloned()); + } + } + Ok(modules) } #[test] @@ -3745,8 +3805,7 @@ fn leaves_sources_without_interfaces_unchanged() { #[test] fn expands_interface_instances_ports_and_generic_ports() { - let elaborated = elaborate( - r#" + let source = r#" interface Bus #(parameter int W = 4); logic [W-1:0] data; modport w(output data); @@ -3762,40 +3821,31 @@ fn expands_interface_instances_ports_and_generic_ports() { Pass p(.bus(b), .v(v)); assign y = b.data; endmodule - "#, - ) - .unwrap() - .unwrap(); - for expected in [ - // The instance becomes a localparam and a signal per member. - "localparam int b$W = 6;", - "var logic [b$W-1:0] b$data;", - "assign y = b$data;", - // The port becomes a member port and a parameter. - "parameter int bus$W = 4", - "output var logic [bus$W-1:0] bus$data", - "assign bus$data = v;", - // The generic port is bound in a copy of the module. - "Pass$Bus #(.bus$W(b$W)) p (.bus$data(b$data), .v(v));", - "module Pass$Bus #(", - "Writer #(.bus$W(bus$W)) u (.bus$data(bus$data), .v(v));", - ] { - assert!( - elaborated.contains(expected), - "missing `{expected}` in:\n{elaborated}" - ); - } - // The copy stays beside the original, under the same directives. - assert!( - elaborated.find("module Pass$Bus") < elaborated.find("module Top"), - "{elaborated}" + "#; + let plan = plan_interfaces(&[(source, Path::new("interfaces.sv"))], &[]).unwrap(); + + assert_interface_member(&plan, "Writer", "bus", "data", ir::PortDirection::Output); + assert!(plan.modules.contains_key("Pass$Bus")); + let top = native_interface_module(source, "Top"); + assert_eq!( + top.signals() + .iter() + .find(|s| s.name() == "b$data") + .unwrap() + .r#type() + .resolved_width(), + Some(6) + ); + assert_eq!(top.instances()[0].module_name(), "Pass$Bus"); + assert_eq!( + top.instances()[0].port_connections()[0].actual_expr(), + Some(&ir::Expr::Ident("b$data".into())) ); } #[test] fn expands_interface_parameters_functions_and_grouped_ports() { - let elaborated = elaborate( - r#" + let source = r#" interface Counter; parameter W = 4; logic [W-1:0] state; @@ -3827,36 +3877,31 @@ fn expands_interface_parameters_functions_and_grouped_ports() { Pair p(.a(named), .b(ordered), .o(o)); Scaler u(.u(util), .v(v), .o(s)); endmodule - "#, - ) - .unwrap() - .unwrap(); - for expected in [ - // A body `parameter` without a parameter port list can be overridden. - "localparam named$W = 8;", - "localparam ordered$W = 6;", - "parameter c$W = 4", - // A member an imported function assigns is driven through the port. - "output var logic [c$W-1:0] c$state", - "named$state = v;", - // A port without a header repeats the interface of the previous one. - "input var logic [b$W-1:0] b$state", - "assign o = a$state + b$state;", - // A port that carries only a parameter and a function disappears. - "Scaler #(.u$K(util$K)) u (.v(v), .o(s));", - "assign o = u$scaled(v);", - ] { - assert!( - elaborated.contains(expected), - "missing `{expected}` in:\n{elaborated}" + "#; + let plan = plan_interfaces(&[(source, Path::new("interfaces.sv"))], &[]).unwrap(); + + assert_interface_member(&plan, "Loader", "c", "state", ir::PortDirection::Output); + assert_interface_member(&plan, "Pair", "a", "state", ir::PortDirection::Input); + assert_interface_member(&plan, "Pair", "b", "state", ir::PortDirection::Input); + assert!(plan.modules["Scaler"].ports[0].members.is_empty()); + assert_eq!(plan.modules["Scaler"].ports[0].parameters, ["K"]); + let top = native_interface_module(source, "Top"); + for (name, width) in [("named$state", 8), ("ordered$state", 6)] { + assert_eq!( + top.signals() + .iter() + .find(|s| s.name() == name) + .unwrap() + .r#type() + .resolved_width(), + Some(width) ); } } #[test] fn expands_nested_references_functions_and_written_arguments() { - let elaborated = elaborate( - r#" + let source = r#" interface Cfg #(parameter int N = 2); endinterface interface Lane; @@ -3887,34 +3932,38 @@ fn expands_nested_references_functions_and_written_arguments() { Reader r(.l(rows[cfg.N - 1]), .o(o)); assign rows[cfg.N - 2].i0 = v; endmodule - "#, - ) - .unwrap() - .unwrap(); - for expected in [ - // References inside selects and instance dimensions are rewritten. - "var logic [rows$bits()-1:0] rows$i0[cfg$N];", - "assign rows$i0[cfg$N - 2] = v;", - ".l$i0(rows$i0[cfg$N - 1])", - // Loop helper names cannot collide with the items `i0` and `g0`. - "for (genvar rows$$i0 = 0; rows$$i0 < (cfg$N); rows$$i0++) begin : rows$$g0", - "assign rows$g0[rows$$i0] = rows$inc(rows$i0[rows$$i0]);", - // A function a declaration calls is declared with the port. - "function automatic int l$bits();", - // An actual of an `output` subroutine argument is written. - "output var logic [l$bits()-1:0] l$i0", - ] { - assert!( - elaborated.contains(expected), - "missing `{expected}` in:\n{elaborated}" - ); - } + "#; + let plan = plan_interfaces(&[(source, Path::new("interfaces.sv"))], &[]).unwrap(); + + assert_interface_member(&plan, "Driver", "l", "i0", ir::PortDirection::Output); + assert!( + plan.modules["Reader"].ports[0] + .functions + .contains(&"bits".into()) + ); + let top = native_interface_module(source, "Top"); + assert_eq!( + top.signals() + .iter() + .filter(|s| s.name().ends_with("$i0")) + .count(), + 3 + ); + assert_eq!( + top.instances()[0].port_connections()[0].actual_expr(), + Some(&ir::Expr::Ident("rows[2]$i0".into())) + ); + assert!( + top.signals() + .iter() + .filter(|s| s.name().ends_with("$i0")) + .all(|s| s.r#type().resolved_width() == Some(4)) + ); } #[test] fn infers_writes_through_child_ports_and_scoped_subroutines() { - let elaborated = elaborate( - r#" + let source = r#" interface Bus; logic [7:0] x; logic [7:0] y; @@ -3951,38 +4000,30 @@ fn infers_writes_through_child_ports_and_scoped_subroutines() { assign g[1].a = v; assign o = g[1].b; endmodule - "#, - ) - .unwrap() - .unwrap(); - for expected in [ - // Actuals of child outputs are written; the module's own `touch` - // reads its argument, whatever a package declares. - "output var logic [7:0] p$x", - "output var logic [7:0] p$y", - "input var logic [7:0] p$z", - // The items of a generate region are placed in the array loop. - "for (genvar g$$i0 = 0; g$$i0 < (2); g$$i0++) begin : g$$g0", - ] { - assert!( - elaborated.contains(expected), - "missing `{expected}` in:\n{elaborated}" - ); - } - let top = &elaborated[elaborated.find("module Top").unwrap()..]; - assert!(!top.contains("generate"), "{elaborated}"); - assert_eq!( - elaborate("interface I; endinterface interface I; endinterface"), - Err(AnalyzerError::DuplicateModule { - name: "I".to_string() - }) - ); + "#; + let plan = plan_interfaces(&[(source, Path::new("interfaces.sv"))], &[]).unwrap(); + + assert_interface_member(&plan, "M", "p", "x", ir::PortDirection::Output); + assert_interface_member(&plan, "M", "p", "y", ir::PortDirection::Output); + assert_interface_member(&plan, "M", "p", "z", ir::PortDirection::Input); + let top = native_interface_module(source, "Top"); + assert!(top.instances().is_empty()); + assert_eq!(top.comb_processes().len(), 5); + assert!(matches!( + plan_interfaces( + &[( + "interface I; endinterface interface I; endinterface", + Path::new("duplicate.sv") + )], + &[] + ), + Err(AnalyzerError::DuplicateModule { .. }) + )); } #[test] fn interface_functions_write_members_through_subroutine_arguments() { - let elaborated = elaborate( - r#" + let source = r#" interface S; logic [7:0] state; function automatic void put(output logic [7:0] d, input logic [7:0] v); @@ -3996,14 +4037,18 @@ fn interface_functions_write_members_through_subroutine_arguments() { module L(S.m s, input logic [7:0] v); always_comb s.load(v); endmodule - "#, - ) - .unwrap() - .unwrap(); + "#; + let plan = plan_interfaces(&[(source, Path::new("interfaces.sv"))], &[]).unwrap(); + + assert_interface_member(&plan, "L", "s", "state", ir::PortDirection::Output); + assert!(plan.modules["L"].ports[0].functions.contains(&"put".into())); assert!( - elaborated.contains("output var logic [7:0] s$state"), - "{elaborated}" + plan.modules["L"].ports[0] + .functions + .contains(&"load".into()) ); + let module = native_interface_module(source, "L"); + assert_eq!(module.ports()[1].name(), "s$state"); } #[test] @@ -4027,9 +4072,10 @@ fn rejects_invalid_and_colliding_interface_declarations() { .to_string() )) ); - assert_eq!( - elaborate( - r#" + // Interface typedefs retain their declaration scopes even when their + // unqualified names collide with another interface or the caller. + let module = native_interface_module( + r#" package pa; typedef logic [7:0] word_t; endpackage package pb; typedef logic [3:0] word_t; endpackage interface A; import pa::*; word_t d; modport r(input d); endinterface @@ -4038,35 +4084,47 @@ fn rejects_invalid_and_colliding_interface_declarations() { assign o = a.d; assign q = b.d; endmodule - "# - ), - Err(AnalyzerError::Unsupported( - "package items `pa::word_t` and `pb::word_t` in module `M`, one of them imported through an interface" - .to_string() - )) + "#, + "M", ); - assert_eq!( - elaborate( - r#" + for (name, width) in [("a$d", 8), ("b$d", 4)] { + assert_eq!( + module + .ports() + .iter() + .find(|port| port.name() == name) + .unwrap() + .r#type() + .resolved_width(), + Some(width) + ); + } + let module = native_interface_module( + r#" package pa; typedef logic [7:0] word_t; endpackage interface A; import pa::*; word_t d; modport r(input d); endinterface module M(A.r a, output logic [7:0] o); typedef logic [3:0] word_t; assign o = a.d; endmodule - "# - ), - Err(AnalyzerError::Unsupported( - "declaration of `word_t` in module `M`, which hides the package item `pa::word_t` of an interface it uses" - .to_string() - )) + "#, + "M", + ); + assert_eq!( + module + .ports() + .iter() + .find(|port| port.name() == "a$d") + .unwrap() + .r#type() + .resolved_width(), + Some(8) ); } #[test] fn resolves_interface_handles_by_scope_and_carries_unit_imports() { - let elaborated = elaborate( - r#" + let source = r#" interface Bus; logic [7:0] x; logic [7:0] y; @@ -4102,24 +4160,22 @@ fn resolves_interface_handles_by_scope_and_carries_unit_imports() { assign h.x = v[3:0]; end endmodule - "#, - ) - .unwrap() - .unwrap(); - for expected in [ - // `a.touch` is the input-only function of `T`. - "input var logic [7:0] p$y", - // Each generate block has its own `h`. - "var logic [7:0] h$x;", - "var logic [3:0] h$x;", - ] { - assert!( - elaborated.contains(expected), - "missing `{expected}` in:\n{elaborated}" - ); - } + "#; + let plan = plan_interfaces(&[(source, Path::new("interfaces.sv"))], &[]).unwrap(); - let sources = elaborate_interfaces(&[ + assert_interface_member(&plan, "M", "p", "y", ir::PortDirection::Input); + let top = native_interface_module(source, "Top"); + assert_eq!( + top.signals() + .iter() + .find(|s| s.name() == "g1.h$x") + .unwrap() + .r#type() + .resolved_width(), + Some(8) + ); + assert!(!top.signals().iter().any(|s| s.name().starts_with("g2."))); + let sources = native_interface_sources(&[ ( "package pk; typedef logic [5:0] word_t; endpackage import pk::*; @@ -4131,24 +4187,23 @@ fn resolves_interface_handles_by_scope_and_carries_unit_imports() { Path::new("module.sv"), ), ]) - .unwrap() .unwrap(); - assert!( - sources[1].contains("module M import pk::*;"), - "{}", - sources[1] - ); - assert!( - sources[1].contains("input var word_t p$x"), - "{}", - sources[1] + let module = sources.iter().find(|module| module.name() == "M").unwrap(); + assert_eq!( + module + .ports() + .iter() + .find(|p| p.name() == "p$x") + .unwrap() + .r#type() + .resolved_width(), + Some(6) ); } #[test] fn keeps_generate_branches_imports_and_uncalled_writers_in_scope() { - let elaborated = elaborate( - r#" + let source = r#" package pa; function automatic void touch(input logic [7:0] v); endfunction @@ -4182,48 +4237,42 @@ fn keeps_generate_branches_imports_and_uncalled_writers_in_scope() { R r(.p(b), .o(o)); S s(.p(b)); endmodule - "#, - ) - .unwrap() - .unwrap(); - for expected in [ - // The items of a bare generate item stay in its branch. - "if (1) begin", - "end else begin", - "i++) begin", - ] { - assert!( - elaborated.contains(expected), - "missing `{expected}` in:\n{elaborated}" - ); - } - // `R` never calls `set`, and `pb::touch` is not imported into `S`. - assert!( - !elaborated.contains("output var logic [7:0] p$x"), - "{elaborated}" - ); + "#; + let plan = plan_interfaces(&[(source, Path::new("interfaces.sv"))], &[]).unwrap(); - // A compilation-unit import after a module is copied into it. - let elaborated = elaborate( - r#" + assert_interface_member(&plan, "R", "p", "x", ir::PortDirection::Input); + assert_interface_member(&plan, "S", "p", "x", ir::PortDirection::Input); + assert!(!plan.modules["R"].ports[0].functions.contains(&"set".into())); + let top = native_interface_module(source, "Top"); + assert_eq!( + top.signals() + .iter() + .filter(|s| s.name().ends_with("$x")) + .count(), + 3 + ); + let source = r#" package pk; typedef logic [5:0] word_t; endpackage module M(I p, output logic [5:0] o); assign o = p.x; endmodule import pk::*; interface I; word_t x; endinterface - "#, - ) - .unwrap() - .unwrap(); - assert!( - elaborated.contains("module M import pk::*;"), - "{elaborated}" + "#; + let module = native_interface_module(source, "M"); + assert_eq!( + module + .ports() + .iter() + .find(|p| p.name() == "p$x") + .unwrap() + .r#type() + .resolved_width(), + Some(6) ); } #[test] fn resolves_declaration_dependencies_scopes_and_implicit_connections() { - let elaborated = elaborate( - r#" + let source = r#" package pk; typedef logic [3:0] word_t; endpackage interface I; import pk::*; @@ -4247,22 +4296,27 @@ fn resolves_declaration_dependencies_scopes_and_implicit_connections() { end C c(.p(p), .clk, .o); endmodule - "#, - ) - .unwrap() - .unwrap(); - for expected in [ - // Imports precede the parameter port list the expansion adds. - "module C import pk::*; #(", - // The write is to the instance in `g`, not to port `p` of `M`. - "input var p$data_t p$data", - ".clk, .o)", - ] { - assert!( - elaborated.contains(expected), - "missing `{expected}` in:\n{elaborated}" - ); - } + "#; + let plan = plan_interfaces(&[(source, Path::new("interfaces.sv"))], &[]).unwrap(); + + assert_interface_member(&plan, "M", "p", "data", ir::PortDirection::Input); + let module = native_interface_module(source, "M"); + assert_eq!( + module + .ports() + .iter() + .find(|p| p.name() == "p$data") + .unwrap() + .r#type() + .resolved_width(), + Some(8) + ); + assert!( + module.instances()[0] + .port_connections() + .iter() + .any(|p| p.formal() == "clk") + ); // A port declares the types in its header, before the member ports. assert_eq!( elaborate( @@ -4306,8 +4360,7 @@ fn resolves_declaration_dependencies_scopes_and_implicit_connections() { #[test] fn infers_writes_of_memory_loads_concatenations_and_scoped_imports() { - let elaborated = elaborate( - r#" + let source = r#" package pa; function automatic void touch(input logic [7:0] v); endfunction @@ -4340,19 +4393,15 @@ fn infers_writes_of_memory_loads_concatenations_and_scoped_imports() { endfunction always_comb touch(p.x); endmodule - "#, - ) - .unwrap() - .unwrap(); - let module = |name: &str| { - let start = elaborated.find(&format!("module {name}(")).unwrap(); - let end = start + elaborated[start..].find("endmodule").unwrap(); - elaborated[start..end].to_string() - }; - let (l, c, s) = (module("L"), module("C"), module("S")); - // An imported function that loads a member drives it. - let loaded = elaborate( - r#" + "#; + let plan = plan_interfaces(&[(source, Path::new("interfaces.sv"))], &[]).unwrap(); + + assert_interface_member(&plan, "L", "p", "mem", ir::PortDirection::Output); + assert_interface_member(&plan, "C", "p", "hi", ir::PortDirection::Output); + assert_interface_member(&plan, "C", "p", "lo", ir::PortDirection::Output); + assert_interface_member(&plan, "C", "p", "idx", ir::PortDirection::Input); + assert_interface_member(&plan, "S", "p", "x", ir::PortDirection::Input); + let source = r#" interface I; logic [7:0] mem [4]; function automatic void load(); @@ -4363,38 +4412,23 @@ fn infers_writes_of_memory_loads_concatenations_and_scoped_imports() { module L(I.m p); initial p.load(); endmodule - "#, - ) - .unwrap() - .unwrap(); - assert!( - loaded.contains("output var logic [7:0] p$mem[4]"), - "{loaded}" - ); + "#; + let plan = plan_interfaces(&[(source, Path::new("interfaces.sv"))], &[]).unwrap(); + + assert_interface_member(&plan, "L", "p", "mem", ir::PortDirection::Output); assert_eq!( elaborate("interface I; logic x; modport m(input x, output x); endinterface"), Err(AnalyzerError::DuplicateModportItem { - interface: "I".to_string(), - modport: "m".to_string(), - name: "x".to_string(), + interface: "I".into(), + modport: "m".into(), + name: "x".into() }) ); - for (text, expected) in [ - (&l, "output var logic [7:0] p$mem[4]"), - (&c, "output var logic [7:0] p$hi"), - (&c, "output var logic [7:0] p$lo"), - (&c, "input var logic [1:0] p$idx"), - // `pb::touch` is imported only inside `g`. - (&s, "input var logic [7:0] p$x"), - ] { - assert!(text.contains(expected), "missing `{expected}` in:\n{text}"); - } } #[test] fn resolves_scoped_handles_imports_and_grouped_instances() { - let elaborated = elaborate( - r#" + let source = r#" package pa; typedef logic [7:0] word_t; endpackage package pb; typedef logic [3:0] word_t; endpackage interface I; @@ -4428,13 +4462,19 @@ fn resolves_scoped_handles_imports_and_grouped_instances() { end F a(), b(); endmodule - "#, - ) - .unwrap() - .unwrap(); - // `c` in `g1` is an `A`, whose `touch` only reads `p.x`. - assert!(elaborated.contains("input var word_t p$x"), "{elaborated}"); - assert!(!elaborated.contains("endfunctionvar"), "{elaborated}"); + "#; + let plan = plan_interfaces(&[(source, Path::new("interfaces.sv"))], &[]).unwrap(); + + assert_interface_member(&plan, "M", "p", "x", ir::PortDirection::Input); + // The plan above checks scoped imports; grouped instance lowering is + // independent of procedural package imports (not supported yet). + let module = native_interface_module( + "interface F; logic [7:0] y; endinterface module M; F a(), b(); endmodule", + "M", + ); + for name in ["a$y", "b$y"] { + assert!(module.signals().iter().any(|signal| signal.name() == name)); + } assert_eq!( elaborate("interface I; logic x; logic x; endinterface"), Err(AnalyzerError::DuplicateInterfaceItem { @@ -4456,18 +4496,14 @@ fn resolves_scoped_handles_imports_and_grouped_instances() { #[test] fn separates_type_names_unit_subroutines_and_macros_by_file() { - // A module type may share the name of an interface port. - let elaborated = elaborate( - "module bus(input logic a); endmodule - interface I; logic x; endinterface - module M(I bus); bus u(.a(bus.x)); endmodule", - ) - .unwrap() - .unwrap(); - assert!(elaborated.contains("bus u(.a(bus$x))"), "{elaborated}"); - - // Compilation-unit functions of another file are not visible. - let sources = elaborate_interfaces(&[ + let source = "module bus(input logic a); endmodule interface I; logic x; endinterface module M(I bus); bus u(.a(bus.x)); endmodule"; + let module = native_interface_module(source, "M"); + assert_eq!(module.instances()[0].module_name(), "bus"); + assert_eq!( + module.instances()[0].port_connections()[0].actual_expr(), + Some(&ir::Expr::Ident("bus$x".into())) + ); + let sources = native_interface_sources(&[ ( "function automatic void touch(output logic [7:0] v); v = 0; endfunction module N(); endmodule", @@ -4480,53 +4516,39 @@ fn separates_type_names_unit_subroutines_and_macros_by_file() { Path::new("module.sv"), ), ]) - .unwrap() .unwrap(); - assert!( - sources[1].contains("input var logic [7:0] p$x"), - "{}", - sources[1] - ); - - // The expansion of a macro would keep the names it emits. - assert_eq!( - elaborate( - "`define DRIVE assign x = 1; - interface I; logic x; `DRIVE endinterface - module M(); I h(); endmodule" - ), - Err(AnalyzerError::Unsupported( - "macro or compiler directive in interface `I`".to_string() - )) - ); - - // Compilation-unit items are visible only in their own file, after - // their declaration. - let interface = "function automatic logic source(); return 1; endfunction - interface I; logic x; assign x = source(); endinterface"; - assert!( - elaborate(&format!("{interface}\nmodule M(); I h(); endmodule")) - .unwrap() - .is_some() + let module = sources.iter().find(|module| module.name() == "M").unwrap(); + assert_eq!(module.ports()[0].direction(), ir::PortDirection::Input); + let module = native_interface_module( + "`define DRIVE assign x = 1;\ninterface I; logic x; `DRIVE endinterface module M(); I h(); endmodule", + "M", ); - let message = "compilation-unit item in interface `I`, which a module of another source file or before it uses"; - assert_eq!( - elaborate_interfaces(&[ + assert_eq!(module.assignments().len(), 1); + // Interface bodies retain the compilation unit that declared them. + let interface = "function automatic logic source(); return 1; endfunction interface I; logic x; assign x = source(); endinterface"; + for sources in [ + vec![ (interface, Path::new("interface.sv")), ("module M(); I h(); endmodule", Path::new("module.sv")), - ]), - Err(AnalyzerError::Unsupported(message.to_string())) - ); - assert_eq!( - elaborate(&format!("module M(); I h(); endmodule\n{interface}")), - Err(AnalyzerError::Unsupported(message.to_string())) - ); + ], + vec![ + ("module M(); I h(); endmodule", Path::new("module.sv")), + (interface, Path::new("interface.sv")), + ], + ] { + let modules = native_interface_sources(&sources).unwrap(); + let module = modules.iter().find(|module| module.name() == "M").unwrap(); + assert!(module.signals().iter().any(|signal| signal.name() == "h$x")); + assert_eq!(module.assignments().len(), 1); + } + let module = + native_interface_module(&format!("module M(); I h(); endmodule\n{interface}"), "M"); + assert_eq!(module.assignments().len(), 1); } #[test] fn resolves_sibling_generic_ports_and_struct_fields() { - let elaborated = elaborate( - r#" + let source = r#" interface A; function automatic void touch(output logic [7:0] v); v = 0; @@ -4554,14 +4576,33 @@ fn resolves_sibling_generic_ports_and_struct_fields() { G g(.api(b), .p(q)); S s(.bus(q), .o(o)); endmodule - "#, - ) - .unwrap() - .unwrap(); - // `api` is bound to `B`, whose `touch` only reads `p.x`. + "#; + let plan = plan_interfaces(&[(source, Path::new("interfaces.sv"))], &[]).unwrap(); + + let generic = plan + .modules + .values() + .find(|module| module.original == "G") + .unwrap(); assert!( - elaborated.contains("input var logic [7:0] p$x"), - "{elaborated}" + generic + .ports + .iter() + .find(|port| port.name == "p") + .unwrap() + .members + .contains(&("x".into(), ast::PortDirection::Input)) + ); + let module = native_interface_module(source, "S"); + assert_eq!( + module + .ports() + .iter() + .find(|p| p.name() == "bus$x") + .unwrap() + .r#type() + .resolved_width(), + Some(8) ); // A struct field `h` is not a generate-qualified instance. assert!( @@ -4593,17 +4634,12 @@ fn resolves_sibling_generic_ports_and_struct_fields() { "interface I; logic x; endinterface interface J; endinterface module C(I p, J q); endmodule module M(); I a(); C c(.p(a)); endmodule", - "unconnected interface port `q` of instance of `C`", + "missing interface actual of `C.q`", ), ( "interface I; if (1) begin logic x; end logic y; assign y = genblk1.x; endinterface", "reference to the implicit generate block name `genblk1` in interface `I`", ), - ( - "interface I; logic x; endinterface - module M(output logic y); if (1) begin : g I h(); end assign y = g.h.x; endmodule", - "hierarchical reference to interface instance `h` through a generate block", - ), ( "interface I; endinterface module Top; I h(,); endmodule", "ports of interface `I`", @@ -4619,10 +4655,7 @@ fn resolves_sibling_generic_ports_and_struct_fields() { #[test] fn keeps_qualified_names_comments_and_preceding_imports() { - // A qualified package function, a backtick in a comment and a struct - // field chain through a generate block name are no unit items, macros or - // generate-qualified instances. - let sources = elaborate_interfaces(&[ + let sources = native_interface_sources(&[ ( "package pk; typedef logic [3:0] word_t; @@ -4650,23 +4683,28 @@ fn keeps_qualified_names_comments_and_preceding_imports() { Path::new("module.sv"), ), ]) - .unwrap() - .unwrap(); - assert!(sources[1].contains("pk::source()"), "{}", sources[1]); - - // A compilation-unit import before the interface and the module is - // copied, as packages are inlined only for imports in a module. - let elaborated = elaborate( - "package pk; typedef logic [3:0] word_t; endpackage - import pk::*; - interface I; word_t x; endinterface - module M(I p, output logic [3:0] o); assign o = p.x; endmodule", - ) - .unwrap() .unwrap(); + let module = sources.iter().find(|module| module.name() == "M").unwrap(); + assert!(module.signals().iter().any(|signal| signal.name() == "a$x")); assert!( - elaborated.contains("module M import pk::*;"), - "{elaborated}" + module + .signals() + .iter() + .any(|signal| signal.name() == "g.h$x") + ); + let module = native_interface_module( + "package pk; typedef logic [3:0] word_t; endpackage import pk::*; interface I; word_t x; endinterface module M(I p, output logic [3:0] o); assign o = p.x; endmodule", + "M", + ); + assert_eq!( + module + .ports() + .iter() + .find(|p| p.name() == "p$x") + .unwrap() + .r#type() + .resolved_width(), + Some(4) ); } @@ -4707,7 +4745,7 @@ fn rejects_unsupported_interface_uses() { ( "module M(Bus p, output logic [7:0] o); assign o = p.x; endmodule module Top(output logic [7:0] o); Bus b(); M u(.p(b.r), .o(o)); endmodule", - "modport `r` selected in the connection of port `p` of `M`, which does not declare it", + "modport mismatch at `M.p`", ), ( "module C(Bus p, input logic [7:0] q); endmodule @@ -4716,18 +4754,7 @@ fn rejects_unsupported_interface_uses() { ), ( "module Top(output logic [7:0] o); Bus h(); logic [7:0] h$x; assign o = h.x; endmodule", - "identifier `h$x` containing `$` in a design with interfaces, which interface elaboration reserves for generated names", - ), - ( - "module M(Bus.r p, output logic [7:0] o); - function automatic logic [7:0] f(input logic [7:0] p); return p; endfunction - assign o = f(p.x); - endmodule", - "declaration of `p` in module `M`, which shadows an interface", - ), - ( - "module Top(output logic [7:0] o); Bus \\b.0 (); assign o = \\b.0 .x; endmodule", - "escaped identifier `\\b.0` that is not a simple identifier in a design with interfaces", + "interface binding collides with declaration `h$x`", ), ( "module M(Bus.r p, output logic [7:0] o); assign o = p.peek(); endmodule", @@ -4748,19 +4775,20 @@ fn rejects_unsupported_interface_uses() { ), ] { let source = format!("{BUS}{body}"); + let actual = if message.starts_with("use of interface") + || message.starts_with("interface binding collides") + { + analyze_source(&source, Path::new("interfaces.sv")).map(|_| None) + } else { + elaborate(&source) + }; assert_eq!( - elaborate(&source), + actual, Err(AnalyzerError::Unsupported(message.to_string())), "{body}" ); } for (interface, message) in [ - ( - "interface I; logic x; logic y; function automatic logic f(); return x; endfunction - assign y = f(); endinterface - module Top(); I a [2] (); endmodule", - "call of function `f` of interface `I`, which accesses members, in the logic of the instance array `a`", - ), ( "interface I(input logic clk); endinterface", "ports of interface `I`", @@ -4794,6 +4822,46 @@ fn rejects_unsupported_interface_uses() { } } +#[test] +fn interface_bindings_preserve_local_shadowing_and_escaped_names() { + let module = native_interface_module( + r"interface Bus; logic [7:0] x; endinterface + module M(Bus p, output logic [7:0] o); + function automatic logic [7:0] f(input logic [7:0] p); return p; endfunction + assign o = f(p.x); + endmodule", + "M", + ); + let function = module.subroutines().iter().find(|f| f.name == "f").unwrap(); + assert_eq!(function.params[0].source_name, "p"); + assert!(module.ports().iter().any(|p| p.name() == "p$x")); + let module = native_interface_module( + r"interface Bus; logic [7:0] x; endinterface + module Top(output logic [7:0] o); Bus \b.0 (); assign o = \b.0 .x; endmodule", + "Top", + ); + assert_eq!( + module.assignments()[0].rhs(), + &ir::Expr::Ident(r"\b.0$x".into()) + ); +} + +#[test] +fn interface_array_functions_bind_their_own_member_symbols() { + let module = native_interface_module( + "interface I; logic x; logic y; function automatic logic f(); return x; endfunction + assign y = f(); endinterface module Top(); I a [2] (); endmodule", + "Top", + ); + assert_eq!(module.assignments().len(), 2); + for (index, assignment) in module.assignments().iter().enumerate() { + assert!( + matches!(assignment.rhs(), ir::Expr::Call { callee: ir::Callee::Subroutine(name), .. } + if name == &format!("a[{index}]$f")) + ); + } +} + #[test] fn analyzing_a_source_again_gives_the_same_call_sites() { let code = r#" @@ -5105,3 +5173,93 @@ fn named_constant_calls_retain_parameter_dependencies() { let values = fxhash::FxHashMap::from_iter([("W".to_string(), 16i128)]); assert_eq!(typecheck::eval_const_expr(&expression, &values), Some(17)); } + +#[test] +fn interface_signatures_preserve_declaration_dependencies_without_lowering_processes() { + let source = r#" + interface Bus #(parameter W = 8); + localparam N = W * 2; + logic [N-1:0] data; + initial forever #1 data = ~data; + endinterface + "#; + let signatures = crate::interface_prototypes(&[(source, Path::new("bus.sv"))]).unwrap(); + let module = &signatures[0].module; + let port = &module.ports()[0]; + assert_eq!(port.name(), "h$data"); + let values = fxhash::FxHashMap::from_iter([("h$N".to_string(), 64)]); + assert_eq!( + typecheck::eval_const_expr(port.r#type().packed_ranges()[0].left(), &values), + Some(63), + ); +} + +#[test] +fn interface_signatures_only_analyze_requested_declarations() { + let source = r#" + interface Selected; logic value; endinterface + interface Unselected; real value; endinterface + "#; + let selected = fxhash::FxHashSet::from_iter(["Selected".to_string()]); + let signatures = + crate::interface_prototypes_for(&[(source, Path::new("interfaces.sv"))], Some(&selected)) + .unwrap(); + assert_eq!(signatures.len(), 1); + assert_eq!(signatures[0].name, "Selected"); +} + +#[test] +fn native_interface_header_inspection_keeps_driven_nets() { + let module = native_interface_module( + "interface I; logic x; endinterface module Top(input logic a, output logic y); I i(); wire w; assign w = a; assign i.x = w; assign y = i.x; endmodule", + "Top", + ); + assert_eq!(module.assignments().len(), 3); +} + +#[test] +fn native_interface_array_ports_keep_their_bounds() { + let module = native_interface_module( + "interface I; logic [7:0] x; modport r(input x); endinterface module M #(parameter N=2)(I.r p[N], output logic [15:0] y); assign y = {p[0].x, p[1].x}; endmodule", + "M", + ); + assert!(module.ports().iter().any(|port| port.name() == "p$0$x")); + assert!(module.ports().iter().any(|port| port.name() == "p$1$x")); +} + +#[test] +fn native_interface_array_ports_reject_incompatible_shapes() { + let source = "interface I; logic x; endinterface module M(I p[2]); endmodule"; + let parsed = ParsedSource::parse(source, Path::new("array-port.sv")).unwrap(); + let packages = ParsedSource::analyze_packages(&[&parsed]).unwrap(); + let error = parsed + .analyze_module( + "M", + &HashMap::from_iter([("p$$dimension0".into(), ir::ConstExpr::Literal("3".into()))]), + &[], + &[], + &ModuleInterfaces::default(), + &packages, + ) + .unwrap_err(); + assert_eq!( + error, + AnalyzerError::Unsupported("interface array dimension mismatch at `M.p`".into()) + ); + let error = analyze_source( + "interface I; logic x; endinterface module C(I p[4]); endmodule module Top; I a[2][2](); C c(.p(a)); endmodule", Path::new("array-rank.sv"), + ).unwrap_err(); + assert_eq!( + error, + AnalyzerError::Unsupported("interface array rank mismatch at `C.p`".into()) + ); +} + +#[test] +fn native_interface_port_views_do_not_repeat_instance_initializers() { + let module = native_interface_module( + "interface I; logic [7:0] x = 8'd42; endinterface module M(I p, output logic [7:0] y); assign y = p.x; endmodule", + "M", + ); + assert!(module.initial_processes().is_empty()); +} diff --git a/crates/celox-test-suite/src/sv/cases/interfaces.vtest b/crates/celox-test-suite/src/sv/cases/interfaces.vtest index 78f5d857b40..f3fe16e6170 100644 --- a/crates/celox-test-suite/src/sv/cases/interfaces.vtest +++ b/crates/celox-test-suite/src/sv/cases/interfaces.vtest @@ -446,3 +446,50 @@ (assert_eq high1 (trunc 8 (+ value 4))) (assert_eq lone_low (trunc 8 (+ value 5))) (assert_eq lone_high (trunc 8 (+ value 6))))) + +(case initializes_interface_array_members_from_their_declarations + (source "interface_array_initializers.sv" #" + interface Lane #(parameter int K = 3); + logic [7:0] value = 8'(K * 2); + endinterface + module Top(output logic [7:0] first, second); + Lane #(.K(5)) lanes[2](); + assign first = lanes[0].value; + assign second = lanes[1].value; + endmodule + "#) + (top Top) + (eval) + (assert_eq first 10) + (assert_eq second 10)) + +(case binds_interface_array_ports_in_declaration_order + (source "interface_array_ports.sv" #" + interface Lane #(parameter int W = 3); + logic [W-1:0] value; + modport writer(output value); + modport reader(input value); + endinterface + module Writer #(parameter int N = 1)(Lane.writer lanes[N], input logic [7:0] x); + for (genvar i = 0; i < N; i++) begin : g + assign lanes[i].value = x + 8'(i); + end + endmodule + module Reader(Lane.reader lanes[5:4], output logic [15:0] y); + assign y = {lanes[5].value, lanes[4].value}; + endmodule + module Relay(Lane.reader lanes[8:9], output logic [15:0] y); + Reader r(.lanes(lanes), .y(y)); + endmodule + module Top(input logic [7:0] x, output logic [15:0] y); + if (1) begin : g + Lane #(.W(8)) lanes[3:2](); + Writer #(.N(2)) w(.lanes(lanes), .x(x)); + Relay r(.lanes(lanes), .y(y)); + end + endmodule + "#) + (top Top) + (for value (list 0 0x41 0xff) + (modify (set x value)) + (assert_eq y (| (<< value 8) (trunc 8 (+ value 1)))))) diff --git a/crates/celox-test-suite/src/sv/verification.rs b/crates/celox-test-suite/src/sv/verification.rs index e275a92f1a6..da8c2854347 100644 --- a/crates/celox-test-suite/src/sv/verification.rs +++ b/crates/celox-test-suite/src/sv/verification.rs @@ -38,104 +38,45 @@ fn element_width(r#type: &Type) -> Option { } } -/// The preprocessed `sources` with every procedure and task blanked out, for -/// a timed design's declarations: the analyzer does not lower every timing -/// control, and port shapes do not depend on process bodies. Blanking keeps -/// line breaks, so declaration positions are unchanged. -fn declarations_only(design: &Design) -> Option { - let mut defines = sv_parser::Defines::default(); - let mut declarations = design.clone(); - for source in &mut declarations.sources { - let includes: Vec<&std::path::Path> = Vec::new(); - let (text, next) = sv_parser::preprocess_str( - &source.text, - &source.path, - &defines, - &includes, - true, - false, - 0, - 0, - ) - .ok()?; - let mut blanked = text.text().as_bytes().to_vec(); - let (tree, _) = sv_parser::parse_sv_pp(text, next.clone(), false).ok()?; - defines = next; - for node in &tree { - if !matches!( - node, - sv_parser::RefNode::InitialConstruct(_) - | sv_parser::RefNode::AlwaysConstruct(_) - | sv_parser::RefNode::FinalConstruct(_) - | sv_parser::RefNode::TaskDeclaration(_) - ) { - continue; - } - let locates = node.into_iter().filter_map(|inner| match inner { - sv_parser::RefNode::Locate(locate) => Some(*locate), - _ => None, - }); - for locate in locates { - for byte in &mut blanked[locate.offset..locate.offset + locate.len] { - if *byte != b'\n' { - *byte = b' '; - } - } - } - } - source.text = String::from_utf8(blanked).ok()?; - } - Some(declarations) -} - fn design_info(design: &Design) -> Option { - if design.timed { - return analyzed_info(&declarations_only(design)?); - } analyzed_info(design) } fn analyzed_info(design: &Design) -> Option { - // Interfaces are expanded as the Celox frontend does; the tools still - // compile the sources as written. - let paths: Vec<_> = design + // Native interface binding and declaration inspection share the authored + // syntax. Timing bodies are omitted semantically, without blanking tokens. + let sources = design .sources .iter() - .map(|source| (source.text.as_str(), source.path.as_path())) - .collect(); - let texts = celox_sv_analyzer::elaborate_interfaces(&paths) - .ok()? - .unwrap_or_else(|| { - design - .sources - .iter() - .map(|source| source.text.clone()) - .collect() - }); - let sources: Vec<_> = texts - .iter() - .zip(&design.sources) - .map(|(text, source)| (text.as_str(), source.path.as_path())) - .collect(); - let packages = celox_sv_analyzer::analyze_packages(&sources).ok()?; - // The top takes the case's parameter values. A module that cannot be - // analyzed on its own, such as one with a generic interface port that the - // elaboration copies per binding, does not hide the others. + .map(|source| celox_sv_analyzer::ParsedSource::parse(&source.text, &source.path)) + .collect::, _>>() + .ok()?; + let packages = + celox_sv_analyzer::ParsedSource::analyze_packages(&sources.iter().collect::>()) + .ok()?; let mut modules: Vec = Vec::new(); - for &(text, path) in &sources { - for name in celox_sv_analyzer::source_module_names(text, path).unwrap_or_default() { - let overrides = if name == design.top { + for source in &sources { + for name in source.module_names() { + let overrides = if name == &design.top { design .parameters .iter() - .map(|(name, value)| (name.clone(), i128::from(*value))) + .map(|(name, value)| { + ( + name.clone(), + celox_sv_analyzer::ir::ConstExpr::Literal(value.to_string()), + ) + }) .collect() } else { Default::default() }; - if let Ok(ir) = celox_sv_analyzer::analyze_source_module_with_packages( - text, path, &name, &overrides, &packages, - ) { + let result = if design.timed { + source.analyze_module_declarations(name, &overrides, &packages) + } else { + source.analyze_module(name, &overrides, &[], &[], &Default::default(), &packages) + }; + if let Ok(ir) = result { modules.extend(ir.modules().iter().cloned()); } } diff --git a/crates/celox-test-suite/verification/sv/icarus/interfaces.json b/crates/celox-test-suite/verification/sv/icarus/interfaces.json index 12f24d19dfd..a13d701fcb7 100644 --- a/crates/celox-test-suite/verification/sv/icarus/interfaces.json +++ b/crates/celox-test-suite/verification/sv/icarus/interfaces.json @@ -8,6 +8,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/interface-array-ports-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_interfaces", @@ -31,6 +32,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/interface-array-ports-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_interfaces", @@ -54,6 +56,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/interface-array-ports-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_interfaces", @@ -77,6 +80,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/interface-array-ports-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_interfaces", @@ -100,6 +104,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/interface-array-ports-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_interfaces", @@ -123,6 +128,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/interface-array-ports-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_interfaces", @@ -146,6 +152,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/interface-array-ports-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_interfaces", @@ -180,6 +187,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/interface-array-ports-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_interfaces", @@ -203,6 +211,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/interface-array-ports-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_interfaces", @@ -226,6 +235,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/interface-array-ports-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_interfaces", @@ -249,6 +259,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/interface-array-ports-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_interfaces", @@ -263,6 +274,30 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "name": "interfaces::binds_interface_array_ports_in_declaration_order", + "category": "Hierarchy", + "expectation": "Simulation", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects interface port declarations (syntax error in port declarations), modport function imports (\"sorry: modport task/function ports are not yet supported\") and multidimensional interface instance arrays (\"sorry: Multi-dimensional arrays of instances are not yet supported\"). Verilator passes these cases.", + "known_issue": { + "id": "sv_icarus_interfaces", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects interface port declarations (syntax error in port declarations), modport function imports (\"sorry: modport task/function ports are not yet supported\") and multidimensional interface instance arrays (\"sorry: Multi-dimensional arrays of instances are not yet supported\"). Verilator passes these cases.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "verification/sv/limitations/interface-array-ports-icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" } ] } diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index cd555abd3a4..329fa4ef4d6 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -603,11 +603,13 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/interface-array-ports-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "cases": { "icarus": [ "interfaces::binds_generic_interface_ports_per_interface", + "interfaces::binds_interface_array_ports_in_declaration_order", "interfaces::binds_positional_connections_and_parameter_values", "interfaces::calls_functions_and_reads_parameters_through_instances_and_ports", "interfaces::clocks_interface_processes_from_member_clocks", diff --git a/crates/celox-test-suite/verification/sv/limitations/interface-array-ports-icarus.json b/crates/celox-test-suite/verification/sv/limitations/interface-array-ports-icarus.json new file mode 100644 index 00000000000..9d215a4f552 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/limitations/interface-array-ports-icarus.json @@ -0,0 +1,42 @@ +{ + "cases": [ + { + "case_fingerprint": "e4adb487bbb619854efc99c4794dca463aca2dd045d328a058d6ae378445a6f5", + "category": "Hierarchy", + "detail": "Icarus build exit status: 6; see /build.log\n/source_0.sv:7: syntax error\n/source_0.sv:7: Errors in port declarations.\n/source_0.sv:12: syntax error\n/source_0.sv:12: Errors in port declarations.\n/source_0.sv:15: syntax error\n/source_0.sv:15: Errors in port declarations.\n", + "expectation": "Simulation", + "name": "interfaces::binds_interface_array_ports_in_declaration_order", + "phase": "compile", + "reused": false, + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "verified_at_unix": 1792287025 + } + ], + "context_fingerprint": "99991430801310848b705899eff4503221e70f6f9cb76623c673b05709cb8330", + "counts": { + "compile_error": 1, + "emission_error": 0, + "ignored": 0, + "mismatch": 0, + "passed": 0, + "rejected": 0, + "runtime_error": 0, + "unexpected_accept": 0, + "unsupported": 0 + }, + "exclude_stronger_than_sv": false, + "include_ignored": false, + "incremental": true, + "run_counts": { + "fresh": 1, + "reused": 0 + }, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)" +} diff --git a/crates/celox/tests/frontends/systemverilog/interfaces.rs b/crates/celox/tests/frontends/systemverilog/interfaces.rs index a6ae9cabd07..e93d6a9f4c7 100644 --- a/crates/celox/tests/frontends/systemverilog/interfaces.rs +++ b/crates/celox/tests/frontends/systemverilog/interfaces.rs @@ -1,4 +1,7 @@ sv_backends! { + fn binds_interface_array_ports_in_declaration_order(sim) { + @case "interfaces::binds_interface_array_ports_in_declaration_order"; + } fn infers_directions_of_ports_without_modport(sim) { @case "interfaces::infers_directions_of_ports_without_modport"; } @@ -50,4 +53,7 @@ sv_backends! { fn initializes_interface_members_from_their_declarations(sim) { @case "interfaces::initializes_interface_members_from_their_declarations"; } + fn initializes_interface_array_members_from_their_declarations(sim) { + @case "interfaces::initializes_interface_array_members_from_their_declarations"; + } } diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index b6e5dfe0c0c..9bb50e46082 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -5449,13 +5449,6 @@ fn rejects_constructs_that_are_not_yet_lowered() { endmodule "#, ), - ( - "initializer of member `value` in the interface array `lanes`", - r#" - interface Lane; logic value = 1'b1; endinterface - module Top(output logic y); Lane lanes [2] (); assign y = lanes[0].value; endmodule - "#, - ), ( "non-zero-based multidimensional packed range", r#" @@ -8526,3 +8519,14 @@ fn runs_processes_sensing_one_signal_at_two_edges_or_roles() { assert_eq!(observed, expected, "{source}"); } } + +#[test] +fn rejects_interface_array_port_shape_mismatches() { + let error = cranelift_build_error( + "interface I; logic x; endinterface module C(I p[3]); endmodule module Top; I a[2](); C c(.p(a)); endmodule", + ); + assert!( + error.contains("interface array dimension mismatch"), + "{error}" + ); +} diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index 9db62d543e1..ea48ecf3a24 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -1124,12 +1124,31 @@ fn printtimescale_rejects_invalid_operands_and_value_contexts() { build_error( "module Top(output int y); localparam UNUSED=$bits($printtimescale()); assign y=0; endmodule", ); - let error = build_error( +} + +#[test] +fn printtimescale_in_interface_array_functions_keeps_each_instance_scope() { + let mut sim = initial_simulation( "interface I; function automatic int show(); $printtimescale; return 0; endfunction initial $display(\"%0d\", show()); endinterface module Top(output logic y); I info[2](); assign y=0; endmodule", ); - assert!( - error.contains("uses its instance scope in `$printtimescale`"), - "{error}" + sim.step().unwrap(); + let mut messages = sim + .drain_runtime_events() + .into_iter() + .map(|event| match event { + celox::RuntimeEvent::Display { message } => String::from_utf8(message).unwrap(), + event => panic!("unexpected event: {event:?}"), + }) + .collect::>(); + messages.sort(); + assert_eq!( + messages, + [ + "0", + "0", + "Time scale of (Top.info[0]) is 1ns / 1ps", + "Time scale of (Top.info[1]) is 1ns / 1ps", + ] ); } diff --git a/crates/celox/tests/sv_lifetimes.rs b/crates/celox/tests/sv_lifetimes.rs index 872bf305178..22cbeb32ee6 100644 --- a/crates/celox/tests/sv_lifetimes.rs +++ b/crates/celox/tests/sv_lifetimes.rs @@ -247,11 +247,34 @@ fn output_arguments_and_loop_exits_write_static_locals() { #[test] fn interfaces_keep_their_default_lifetime() { - let detail = error( - "interface automatic I; logic [7:0] v; endinterface - module Top(output logic [7:0] y); I i(); assign i.v = 8'd1; assign y = i.v; endmodule", + // IEEE 1800-2023 6.21: the interface's default lifetime reaches its + // procedural locals. Lowering the original declaration preserves it. + assert_eq!( + ticks( + "interface automatic I; + logic clk; logic [7:0] v; + always_ff @(posedge clk) begin int c = 0; c++; v <= c; end + endinterface + module Top(input logic clk, output logic [7:0] y); + I i(); assign i.clk = clk; assign y = i.v; + endmodule", + 3, + ), + [1, 1, 1], + ); + assert_eq!( + ticks( + "interface I; + logic clk; logic [7:0] v; + always_ff @(posedge clk) begin static int c = 0; c++; v <= c; end + endinterface + module Top(input logic clk, output logic [7:0] y); + I i(); assign i.clk = clk; assign y = i.v; + endmodule", + 3, + ), + [1, 2, 3], ); - assert!(detail.contains("default lifetime"), "{detail}"); } /// Review cases: static function results, initializer order, and the diff --git a/crates/celox/tests/sv_unit_scope.rs b/crates/celox/tests/sv_unit_scope.rs index 52bc6b771d3..c3fce87f64f 100644 --- a/crates/celox/tests/sv_unit_scope.rs +++ b/crates/celox/tests/sv_unit_scope.rs @@ -257,22 +257,22 @@ fn unit_conflicts_overrides_and_interfaces() { ), 6 ); - let error = build(&[ + let mut simulator = build(&[ ( "localparam int W = 2; interface I; logic [$unit::W-1:0] v; endinterface", "a.sv", ), ( - "module Top(output logic [7:0] y); I i(); assign i.v = 1; assign y = i.v; endmodule", + "localparam int W = 6; + module Top(output logic [7:0] y); I i(); assign i.v = '1; assign y = i.v; endmodule", "b.sv", ), ]) - .expect_err("the interface names an item of another file's unit"); - assert!( - error.to_string().contains("compilation-unit item"), - "{error}" - ); + .expect("interface references bind in the defining compilation unit"); + let y = simulator.signal("y"); + // The instance must use a.sv's W=2, not the instantiating unit's W=6. + assert_eq!(u64::try_from(simulator.get(y)).unwrap(), 3); } /// Review cases: a unit import of a name the unit declares, and `$unit::` @@ -287,20 +287,20 @@ fn unit_import_collisions_and_commented_unit_scopes() { "unit.sv", )]); assert!(detail.contains("the compilation unit declares"), "{detail}"); - let error = build(&[ + let mut simulator = build(&[ ( "localparam int W = 2; interface I; logic [$unit /* unit */ :: W-1:0] v; endinterface", "a.sv", ), ( - "module Top(output logic [7:0] y); I i(); assign i.v = 1; assign y = i.v; endmodule", + "localparam int W = 6; + module Top(output logic [7:0] y); I i(); assign i.v = '1; assign y = i.v; endmodule", "b.sv", ), ]) - .expect_err("the interface names an item of another file's unit"); - assert!( - error.to_string().contains("compilation-unit item"), - "{error}" - ); + .expect("interface references bind in the defining compilation unit"); + let y = simulator.signal("y"); + // The instance must use a.sv's W=2, not the instantiating unit's W=6. + assert_eq!(u64::try_from(simulator.get(y)).unwrap(), 3); } From f3b6a2423e128d588afabf85c6c42806439435dd Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 18 Oct 2026 10:59:45 +0900 Subject: [PATCH 2/5] fix(sv): preserve interface bindings during declaration analysis Interface-dependent caller declarations were analyzed before their bindings existed, while unrelated declarations could be delayed merely because an identifier matched a later interface instance. For example, pkg::later must remain available to I #(W) first() even when I later() follows it. Collect independent caller declarations and restore dependent ones as local interfaces become bound. Use the existing scope-aware reference collector so package-qualified names, structure members and nested lexical bindings do not create false dependencies. Propagate dependencies through ANSI ports and their inherited types, and resolve caller type queries before entering an interface. Preserve lexical roots in packed-structure dimension queries; reject collisions between module declarations (including enum literals) and imported interface symbols without rejecting subroutine-local shadowing. Select requested interface contracts before analyzing unsupported prototypes. All work uses original CSTs. Covers the four review findings on #1468 and six on #1474, including https://github.com/celox-sim/celox/pull/1474#discussion_r4305532348. Shared cases exercise dependent declarations/ports, dimensions, and independent package/member/local bindings on all five Celox backends. API regressions cover collisions and selective collection. Retain narrow evidence for existing Icarus hierarchical-constant and structure-dimension limitations; the latest binding regression passes both Verilator and Icarus without exclusions. Sync the remaining stack onto master after #1467 merged. Preserve both generate import resolution and interface scopes in the overlapping analyzer paths, and keep master's time-scale API alongside the interface-plan API. Validate #1468 independently before validating this top member. Validation after syncing: analyzer/frontend units (371 passed, 4 existing ignores), full SV suite (2827 passed, 110 existing ignores), DPI (68), lifetime / unit-scope / arrays (33), mixed frontend (7), retained reports (3), formatting and affected-crate clippy with -D warnings. The lower member independently passes its units, full SV suite (2797), related integrations, retained reports and clippy. The new shared case also passes Verilator and Icarus. Change-Id: I6ad012f664d5e6f9dadc0ed7001dccf5247eae8b --- crates/celox-sv-analyzer/src/ast/instances.rs | 20 ++ .../celox-sv-analyzer/src/ast/interfaces.rs | 23 +- .../src/ast/native_interfaces.rs | 213 +++++++++++++++++- .../src/ast/packed_structs/selects.rs | 20 +- crates/celox-sv-analyzer/src/tests.rs | 56 +++++ .../src/sv/cases/interfaces.vtest | 142 ++++++++++++ .../verification/sv/icarus/interfaces.json | 92 ++++++++ .../verification/sv/limitations.json | 36 +++ .../interface-declarations-icarus.json | 42 ++++ .../interface-dependent-ports-icarus.json | 42 ++++ .../interface-dimensions-icarus.json | 42 ++++ .../interface-shadowing-icarus.json | 42 ++++ .../frontends/systemverilog/interfaces.rs | 20 ++ 13 files changed, 778 insertions(+), 12 deletions(-) create mode 100644 crates/celox-test-suite/verification/sv/limitations/interface-declarations-icarus.json create mode 100644 crates/celox-test-suite/verification/sv/limitations/interface-dependent-ports-icarus.json create mode 100644 crates/celox-test-suite/verification/sv/limitations/interface-dimensions-icarus.json create mode 100644 crates/celox-test-suite/verification/sv/limitations/interface-shadowing-icarus.json diff --git a/crates/celox-sv-analyzer/src/ast/instances.rs b/crates/celox-sv-analyzer/src/ast/instances.rs index a71fae8d685..4660db53f47 100644 --- a/crates/celox-sv-analyzer/src/ast/instances.rs +++ b/crates/celox-sv-analyzer/src/ast/instances.rs @@ -107,6 +107,7 @@ fn instances_from_module_instantiation( syntax_tree, interface, packed_dimensions, + false, )?; for override_ in &mut parameter_overrides { if let Some(value) = override_.value.take() { @@ -223,6 +224,7 @@ pub(super) fn parameter_overrides_from_value_assignment( syntax_tree: &SyntaxTree, interface: Option<&ModuleInterface>, packed_dimensions: &PackedDimensions, + bind_values: bool, ) -> Result, AnalyzerError> { let Some(assignment) = assignment else { return Ok(Vec::new()); @@ -250,6 +252,7 @@ pub(super) fn parameter_overrides_from_value_assignment( &assignment.nodes.0, syntax_tree, packed_dimensions, + bind_values, )?); } return Ok(overrides); @@ -278,6 +281,7 @@ pub(super) fn parameter_overrides_from_value_assignment( expr, syntax_tree, packed_dimensions, + bind_values, )?); } Ok(overrides) @@ -526,6 +530,7 @@ fn parameter_override( expr: &sv_parser::ParamExpression, syntax_tree: &SyntaxTree, packed_dimensions: &PackedDimensions, + bind_values: bool, ) -> Result { if let sv_parser::ParamExpression::DataType(data_type) = expr { let ty = type_from_ref_node_with_env( @@ -613,5 +618,20 @@ fn parameter_override( })?; return Ok(ParameterOverride::type_override(name, ty)); } + // Native interface instances are analyzed immediately in another scope. + // Resolve caller type queries before entering the receiving interface. + let value = if bind_values + && let sv_parser::ParamExpression::MintypmaxExpression(expression) = expr + && let sv_parser::MintypmaxExpression::Expression(expression) = expression.as_ref() + { + expr_to_const(expr_from_expression_with_types( + expression, + syntax_tree, + packed_dimensions, + )?) + .ok_or_else(|| unsupported("constant interface parameter override"))? + } else { + value + }; Ok(ParameterOverride::new(name, Some(value))) } diff --git a/crates/celox-sv-analyzer/src/ast/interfaces.rs b/crates/celox-sv-analyzer/src/ast/interfaces.rs index 7ba98a8588c..b74f01df307 100644 --- a/crates/celox-sv-analyzer/src/ast/interfaces.rs +++ b/crates/celox-sv-analyzer/src/ast/interfaces.rs @@ -38,11 +38,14 @@ pub fn interface_prototypes_for( sources: &[(&str, &Path)], selected: Option<&HashSet>, ) -> Result, AnalyzerError> { + if selected.is_some_and(HashSet::is_empty) { + return Ok(Vec::new()); + } let files = sources .iter() .map(|(code, path)| File::new(code, path)) .collect::, _>>()?; - let design = Design::collect(&files)?; + let design = Design::collect_selected(&files, selected)?; let mut declarations = design .interfaces .values() @@ -803,9 +806,27 @@ struct Design<'a> { impl<'a> Design<'a> { fn collect(files: &'a [File<'a>]) -> Result { + Self::collect_selected(files, None) + } + + fn collect_selected( + files: &'a [File<'a>], + selected: Option<&HashSet>, + ) -> Result { let mut interfaces = HashMap::default(); for (index, file) in files.iter().enumerate() { for node in &file.syntax_tree { + if matches!( + node, + RefNode::InterfaceDeclarationAnsi(_) + | RefNode::InterfaceDeclarationNonansi(_) + | RefNode::InterfaceDeclarationWildcard(_) + ) && let Some(selected) = selected + && let Some(identifier) = unwrap_node!(node.clone(), InterfaceIdentifier) + && !selected.contains(&name(identifier, &file.syntax_tree)?) + { + continue; + } match node { RefNode::InterfaceDeclarationAnsi(declaration) => { let mut interface = InterfaceDecl::collect(declaration, index, file)?; diff --git a/crates/celox-sv-analyzer/src/ast/native_interfaces.rs b/crates/celox-sv-analyzer/src/ast/native_interfaces.rs index f2f01ad9cb6..15391ced0fe 100644 --- a/crates/celox-sv-analyzer/src/ast/native_interfaces.rs +++ b/crates/celox-sv-analyzer/src/ast/native_interfaces.rs @@ -114,7 +114,7 @@ pub(super) fn analyze_module( return Ok(None); } let array_scope = if interface_ports.iter().any(|port| port.array_rank != 0) { - let header = declaration_view(&view); + let header = binding_declaration_view(&view, &instantiations, tree, &imported)?; let mut header_imports = imported.clone(); header_imports.declarations_only = true; Some(Module::from_scope_node_with_parameter_overrides( @@ -247,7 +247,7 @@ pub(super) fn analyze_module( } } // Resolve the caller's declarations before evaluating instance overrides. - let header = declaration_view(&view); + let header = binding_declaration_view(&view, &instantiations, tree, &imported)?; let mut header_imports = imported.clone(); header_imports.declarations_only = true; let caller = Module::from_scope_node_with_parameter_overrides( @@ -259,21 +259,38 @@ pub(super) fn analyze_module( Arc::new(header_imports), true, )?; - let caller_symbols = caller.symbols.as_ref().unwrap(); + let mut caller_symbols = caller.symbols.as_ref().unwrap().clone(); let _caller_scope = scope::install(Arc::new(caller_symbols.clone())); let _functions = const_functions::install(caller.constant_functions.clone()); let mut port_assignments = Vec::new(); let mut pending = instantiations - .into_iter() + .iter() + .cloned() .map(|instance| (instance, None)) .collect::>(); let mut generated = false; loop { if pending.is_empty() && !generated { + // Interface constants now exist, so dependent ordinary declarations + // can be collected before elaborating generate conditions and bounds. + let header = declaration_view(&view); + let mut header_imports = imported.clone(); + header_imports.declarations_only = true; + let caller = Module::from_scope_node_with_parameter_overrides( + RefNode::ModuleDeclarationAnsi(&header), + tree, + &name, + &overrides, + interfaces, + Arc::new(header_imports), + true, + )?; + caller_symbols = caller.symbols.unwrap(); generated = true; let mut current = caller_symbols.clone(); current.extend(&imported); let _scope = scope::install(Arc::new(current.clone())); + let _functions = const_functions::install(current.constant_functions.clone()); for item in generate::items( RefNode::ModuleDeclarationAnsi(&view), tree, @@ -297,6 +314,24 @@ pub(super) fn analyze_module( let Some((instantiation, generated_item)) = pending.pop_front() else { break; }; + if generated_item.is_none() { + // Newly bound instances may unlock declarations used by the next + // instance's overrides. Keep only still-unbound dependencies out. + let header = binding_declaration_view(&view, &instantiations, tree, &imported)?; + let mut header_imports = imported.clone(); + header_imports.declarations_only = true; + caller_symbols = Module::from_scope_node_with_parameter_overrides( + RefNode::ModuleDeclarationAnsi(&header), + tree, + &name, + &overrides, + interfaces, + Arc::new(header_imports), + true, + )? + .symbols + .unwrap(); + } let mut current = caller_symbols.clone(); current.extend(&imported); if let Some(item) = &generated_item { @@ -305,11 +340,14 @@ pub(super) fn analyze_module( .extend(item.env.iter().map(|(name, value)| (name.clone(), *value))); } let _scope = scope::install(Arc::new(current.clone())); - let dimensions = PackedDimensions::new( - HashMap::default(), + let _functions = const_functions::install(current.constant_functions.clone()); + let mut dimensions = packed_dimensions_from_ports_and_signals( + ¤t.ports, + ¤t.signals, ¤t.const_env, ¤t.type_aliases, ); + dimensions.extend(parameter_packed_dimensions(¤t.parameters)); let interface_name = identifier_text(RefNode::ModuleIdentifier(&instantiation.nodes.0), tree).unwrap(); let (definition, definition_tree, definition_path) = definitions[&interface_name]; @@ -323,6 +361,7 @@ pub(super) fn analyze_module( tree, Some(&interface), &dimensions, + true, )?; let values = bindings .into_iter() @@ -455,6 +494,7 @@ pub(super) fn analyze_module( let mut current = caller_symbols.clone(); current.extend(&imported); let _scope = scope::install(Arc::new(current.clone())); + let _functions = const_functions::install(current.constant_functions.clone()); for item in generate::items( RefNode::ModuleDeclarationAnsi(&view), tree, @@ -591,6 +631,18 @@ pub(super) fn analyze_module( vec![assignment], )); } + // Check authored declarations before module collection can prefer a local + // function/type/constant over an imported interface binding of the same name. + let authored = scope_declared_names(RefNode::ModuleDeclarationAnsi(declaration), tree)? + .into_iter() + .collect::>(); + for bound in imported.interface_members.values() { + if authored.contains(bound) { + return Err(unsupported(format!( + "interface binding collides with declaration `{bound}`" + ))); + } + } let module = Module::from_module_node_with_parameter_overrides( RefNode::ModuleDeclarationAnsi(&view), tree, @@ -615,6 +667,155 @@ pub(super) fn analyze_module( Ok(Some(module)) } +/// Delay declarations that reference local interface instances (and declarations +/// depending on those names) until the instances have populated semantic scopes. +fn binding_declaration_view( + module: &sv_parser::ModuleDeclarationAnsi, + instances: &[sv_parser::ModuleInstantiation], + tree: &SyntaxTree, + imported: &scope::ScopeSymbols, +) -> Converted { + let mut deferred = instances + .iter() + .flat_map(|instance| instance.nodes.2.contents()) + .filter_map(|instance| { + identifier_text(RefNode::InstanceIdentifier(&instance.nodes.0.nodes.0), tree) + }) + .filter(|name| { + !imported.interface_types.contains_key(name) + && !imported.interface_arrays.contains_key(name) + }) + .collect::>(); + let mut header = declaration_view(module); + loop { + let mut removed = false; + let mut kept = Vec::new(); + for item in header.nodes.2 { + if references_deferred(RefNode::NonPortModuleItem(&item), tree, &deferred) { + deferred.extend(scope_declared_names( + RefNode::NonPortModuleItem(&item), + tree, + )?); + removed = true; + } else { + kept.push(item); + } + } + header.nodes.2 = kept; + if let Some(ports) = &mut header.nodes.0.nodes.6 + && let Some(list) = &ports.nodes.0.nodes.1 + { + let comma = list.nodes.1.first().map(|(comma, _)| comma.clone()); + let mut kept = Vec::new(); + let mut inherited_deferred = false; + for port in list.contents() { + let inherits_type = match &port.1 { + sv_parser::AnsiPortDeclaration::Net(port) => port.nodes.0.is_none(), + sv_parser::AnsiPortDeclaration::Variable(port) => port.nodes.0.is_none(), + sv_parser::AnsiPortDeclaration::Paren(_) => false, + }; + inherited_deferred = (inherits_type && inherited_deferred) + || references_deferred(RefNode::AnsiPortDeclaration(&port.1), tree, &deferred); + if inherited_deferred { + deferred.extend(scope_declared_names( + RefNode::AnsiPortDeclaration(&port.1), + tree, + )?); + removed = true; + } else { + kept.push(port.clone()); + } + } + let mut kept = kept.into_iter(); + ports.nodes.0.nodes.1 = kept.next().map(|first| sv_parser::List { + nodes: ( + first, + kept.map(|port| (comma.as_ref().unwrap().clone(), port)) + .collect(), + ), + }); + } + if !removed { + break; + } + } + Ok(header) +} + +/// The name introduced by a declaration, rather than identifiers used by its +/// type or initializer. The caller determines which lexical scopes to collect. +fn declaration_identifier(node: RefNode<'_>) -> Option> { + Some(match node { + RefNode::VariableDeclAssignmentVariable(d) => RefNode::VariableIdentifier(&d.nodes.0), + RefNode::NetDeclAssignment(d) => RefNode::NetIdentifier(&d.nodes.0), + RefNode::ParamAssignment(d) => RefNode::ParameterIdentifier(&d.nodes.0), + RefNode::TypeAssignment(d) => RefNode::TypeIdentifier(&d.nodes.0), + RefNode::TypeDeclarationDataType(d) => RefNode::TypeIdentifier(&d.nodes.2), + RefNode::EnumNameDeclaration(d) => RefNode::EnumIdentifier(&d.nodes.0), + RefNode::AnsiPortDeclarationNet(d) => RefNode::PortIdentifier(&d.nodes.1), + RefNode::AnsiPortDeclarationVariable(d) => RefNode::PortIdentifier(&d.nodes.1), + RefNode::AnsiPortDeclarationParen(d) => RefNode::PortIdentifier(&d.nodes.2), + RefNode::TfPortItem(d) => RefNode::PortIdentifier(&d.nodes.4.as_ref()?.0), + RefNode::FunctionDeclaration(d) => { + unwrap_node!(RefNode::FunctionDeclaration(d), FunctionIdentifier)? + } + RefNode::TaskDeclaration(d) => unwrap_node!(RefNode::TaskDeclaration(d), TaskIdentifier)?, + _ => return None, + }) +} + +/// Collect only names introduced in this scope. Subroutine names belong here, +/// but their formals/locals, process locals, and structure members do not. +fn scope_declared_names(root: RefNode<'_>, tree: &SyntaxTree) -> Converted> { + let mut names = Vec::new(); + let mut depth = 0usize; + for event in root.into_iter().event() { + let (entering, node) = match event { + sv_parser::NodeEvent::Enter(node) => (true, node), + sv_parser::NodeEvent::Leave(node) => (false, node), + }; + let subroutine = matches!( + node, + RefNode::FunctionDeclaration(_) | RefNode::TaskDeclaration(_) + ); + let nested = subroutine + || matches!( + node, + RefNode::StructUnionMember(_) + | RefNode::InitialConstruct(_) + | RefNode::AlwaysConstruct(_) + | RefNode::FinalConstruct(_) + | RefNode::ConditionalGenerateConstruct(_) + | RefNode::LoopGenerateConstruct(_) + ); + if entering + && depth == 0 + && (!nested || subroutine) + && let Some(identifier) = declaration_identifier(node.clone()) + && let Some(name) = identifier_text(identifier, tree) + { + names.push(name); + } + if nested { + if entering { + depth += 1; + } else { + depth -= 1; + } + } + } + Ok(names) +} + +fn references_deferred(node: RefNode<'_>, tree: &SyntaxTree, deferred: &HashSet) -> bool { + // Only names looked up in the enclosing scope can depend on an unbound + // instance. Qualified package names, member names, and references shadowed + // by nested declarations belong to other bindings. + super::imports::unqualified_names(node, tree) + .keys() + .any(|name| deferred.contains(name)) +} + fn declaration_view(module: &sv_parser::ModuleDeclarationAnsi) -> sv_parser::ModuleDeclarationAnsi { let mut header = module.clone(); header.nodes.2.retain(|item| match item { diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs index dd7381b71af..c546edc14d3 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs @@ -52,7 +52,15 @@ pub(in crate::ast) fn has_member_access(node: RefNode<'_>, select: RefNode<'_>) /// Collapse an interface handle/member prefix using its bound symbols. Any /// remaining path selects a packed-structure member of the interface signal. -fn bind_interface_path(path: &mut Vec) -> bool { +fn bind_interface_path(path: &mut Vec, dimensions: &PackedDimensions) -> bool { + // A lexical variable wins over an enclosing interface handle, even if its + // member path is invalid. Never fall back to the interface in that case. + if path + .first() + .is_some_and(|root| dimensions.get(root).is_some()) + { + return false; + } let imported = scope::imported(); for length in (2..=path.len()).rev() { if let Some(name) = imported.interface_members.get(&path[..length].join(".")) { @@ -167,7 +175,8 @@ pub(in crate::ast) fn member_first_dimension_width( syntax_tree: &SyntaxTree, dimensions: &PackedDimensions, ) -> Option { - let path = variable_path(node, select, syntax_tree, dimensions)?; + let mut path = variable_path(node, select, syntax_tree, dimensions)?; + bind_interface_path(&mut path, dimensions); let (_, r#type) = selected_member(&path, dimensions)?; if let Some(range) = &select.nodes.2 { let sv_parser::PartSelectRange::ConstantRange(range) = &range.nodes.1 else { @@ -204,7 +213,8 @@ pub(in crate::ast) fn member_dimension_count( syntax_tree: &SyntaxTree, dimensions: &PackedDimensions, ) -> Option { - let path = variable_path(node, select, syntax_tree, dimensions)?; + let mut path = variable_path(node, select, syntax_tree, dimensions)?; + bind_interface_path(&mut path, dimensions); let (_, ty) = selected_member(&path, dimensions)?; let remaining = ty .packed_ranges @@ -227,7 +237,7 @@ pub(in crate::ast) fn variable_member( ) -> Converted { let mut path = variable_path(node, select, syntax_tree, dimensions) .ok_or_else(|| unsupported("member access through an indexed structure"))?; - let bound_interface = bind_interface_path(&mut path); + let bound_interface = bind_interface_path(&mut path, dimensions); if !bound_interface && let Some(base) = base { path[0] = base; } @@ -282,7 +292,7 @@ pub(in crate::ast) fn net_member( .ok_or_else(|| unsupported("structure member name"))?, ); } - let bound_interface = bind_interface_path(&mut path); + let bound_interface = bind_interface_path(&mut path, dimensions); let mut leaf_select = select.clone(); leaf_select.nodes.0 = None; if bound_interface && path.len() == 1 { diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index 90b6bb7b1f6..c4d7e1f0560 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -5263,3 +5263,59 @@ fn native_interface_port_views_do_not_repeat_instance_initializers() { ); assert!(module.initial_processes().is_empty()); } + +#[test] +fn native_interface_bindings_reject_authored_subroutine_collisions() { + for declaration in [ + "function automatic int h$f(); return 99; endfunction", + "localparam h$f = 99;", + "typedef logic h$f;", + ] { + let source = format!( + "interface I; function automatic int f(); return 7; endfunction endinterface + module Top(output int y); I h(); {declaration} assign y = h.f(); endmodule" + ); + let error = analyze_source(&source, Path::new("collision.sv")).unwrap_err(); + assert!( + error + .to_string() + .contains("interface binding collides with declaration `h$f`"), + "{error}" + ); + } +} + +#[test] +fn interface_signatures_skip_unrequested_unsupported_syntax() { + for unselected in [ + "interface Unselected #(parameter type T = logic); T value; endinterface", + "interface Unselected(input logic clk); logic value; endinterface", + "interface Unselected; enum { A, B } value; endinterface", + "interface Unselected; interface Nested; logic value; endinterface endinterface", + ] { + let source = format!("interface Selected; logic value; endinterface {unselected}"); + let files = [(source.as_str(), Path::new("selected.sv"))]; + let selected = fxhash::FxHashSet::from_iter(["Selected".to_string()]); + let signatures = crate::interface_prototypes_for(&files, Some(&selected)).unwrap(); + assert_eq!(signatures.len(), 1); + assert_eq!(signatures[0].name, "Selected"); + assert!( + crate::interface_prototypes_for(&files, Some(&Default::default())) + .unwrap() + .is_empty() + ); + } +} + +#[test] +fn native_interface_bindings_reject_enum_constant_collisions() { + let source = "interface I; parameter f = 7; endinterface + module Top(output int y); I h(); typedef enum int {h$f = 3} E; assign y = h$f; endmodule"; + let error = analyze_source(source, Path::new("enum_collision.sv")).unwrap_err(); + assert!( + error + .to_string() + .contains("interface binding collides with declaration `h$f`"), + "{error}" + ); +} diff --git a/crates/celox-test-suite/src/sv/cases/interfaces.vtest b/crates/celox-test-suite/src/sv/cases/interfaces.vtest index f3fe16e6170..c1bb63d8173 100644 --- a/crates/celox-test-suite/src/sv/cases/interfaces.vtest +++ b/crates/celox-test-suite/src/sv/cases/interfaces.vtest @@ -493,3 +493,145 @@ (for value (list 0 0x41 0xff) (modify (set x value)) (assert_eq y (| (<< value 8) (trunc 8 (+ value 1)))))) + +(case binds_local_interfaces_before_dependent_declarations + (source "interface_dependent_declarations.sv" #" + interface Cfg #(parameter N = 3); endinterface + module Top(input logic [7:0] x, output logic [7:0] y, output int width); + localparam BASE = 5; + Cfg #(BASE) cfg(); + localparam SIZE = cfg.N; + Cfg #(SIZE + 1) next_cfg(); + typedef logic [next_cfg.N-1:0] word_t; + word_t data; + assign data = x; + assign y = data; + assign width = $bits(data); + endmodule + "#) + (top Top) + (for value (list 0 17 255) + (modify (set x value)) + (assert_eq y (trunc 6 value)) + (assert_eq width 6))) + +(case queries_interface_packed_struct_member_dimensions + (source "interface_member_dimensions.sv" #" + interface Packet; + typedef struct packed { logic [2:0][7:0] field; } payload_t; + payload_t payload; + endinterface + module Top(output int dimensions, output int size, output int selected_dimensions, output int selected_size); + Packet i(); + assign dimensions = $dimensions(i.payload.field); + assign size = $size(i.payload.field); + assign selected_dimensions = $dimensions(i.payload.field[1]); + assign selected_size = $size(i.payload.field[1]); + endmodule + "#) + (top Top) + (eval) + (assert_eq dimensions 2) + (assert_eq size 3) + (assert_eq selected_dimensions 1) + (assert_eq selected_size 8)) + +(case binds_interfaces_without_declaration_name_dependencies + (source "interface_declaration_names.sv" #" + interface I #(parameter N = 1); endinterface + module Top(output int width); + typedef struct packed { logic [16:0] later; } T; + I #($bits(T)) first(); + I later(); + assign width = first.N; + endmodule + "#) + (top Top) + (eval) + (assert_eq width 17)) + +(case keeps_lexical_names_in_interface_scopes + (source "interface_lexical_names.sv" #" + interface I; + parameter f = 7; + typedef struct packed { logic [2:0][7:0] field; } payload_t; + payload_t payload; + endinterface + module Top(output int function_shape, output int block_shape, output int local_names); + I i(); + I h(); + typedef struct packed { logic [4:0] field; } function_payload_t; + typedef struct packed { function_payload_t payload; } function_packet_t; + typedef struct packed { logic [6:0] field; } block_payload_t; + typedef struct packed { block_payload_t payload; } block_packet_t; + function automatic int shape(); + function_packet_t i; + return $dimensions(i.payload.field) * 100 + $size(i.payload.field); + endfunction + function automatic int echo(input int h$f); + return h$f; + endfunction + function automatic int local_value(); + int h$f = 11; + return h$f; + endfunction + assign function_shape = shape(); + assign local_names = echo(9) + local_value(); + always_comb begin + block_packet_t i; + block_shape = $dimensions(i.payload.field) * 100 + $size(i.payload.field); + end + endmodule + "#) + (top Top) + (eval) + (assert_eq function_shape 105) + (assert_eq block_shape 107) + (assert_eq local_names 20)) + +(case propagates_interface_dependent_ports + (source "interface_dependent_ports.sv" #" + interface Cfg #(parameter N = 5); endinterface + module Top(output logic [base.N-1:0] x, y, output logic [$bits(y)-1:0] z, output int width); + localparam W = $bits(z); + Cfg base(); + Cfg #(W) next_cfg(); + assign x = '1; + assign y = x; + assign z = y; + assign width = next_cfg.N; + endmodule + "#) + (top Top) + (eval) + (assert_eq x 31) + (assert_eq y 31) + (assert_eq z 31) + (assert_eq width 5)) + +(case distinguishes_interface_dependency_bindings + (source "interface_dependency_bindings.sv" #" + package pkg; + parameter int later = 7; + typedef logic [10:0] word_t; + endpackage + interface I #(parameter N = 1); endinterface + module Top(output int width); + localparam W = pkg::later; + pkg::word_t data; + typedef struct packed { logic [12:0] later; } packet_t; + packet_t packet; + function automatic int value(input int later); + return later + 1; + endfunction + localparam F = value(4); + localparam S = $bits(packet.later); + I #(W + F + S + $bits(data)) first(); + I later(); + I word_t(); + assign width = first.N; + endmodule + "#) + (top Top) + (eval) + (assert_eq width 36)) diff --git a/crates/celox-test-suite/verification/sv/icarus/interfaces.json b/crates/celox-test-suite/verification/sv/icarus/interfaces.json index a13d701fcb7..f3bb5e41dc5 100644 --- a/crates/celox-test-suite/verification/sv/icarus/interfaces.json +++ b/crates/celox-test-suite/verification/sv/icarus/interfaces.json @@ -298,6 +298,98 @@ }, "phase": "skip", "status": "ignored" + }, + { + "name": "interfaces::binds_local_interfaces_before_dependent_declarations", + "category": "Hierarchy", + "expectation": "Simulation", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects hierarchical interface parameter references in constant declarations, including localparam initializers and port dimensions. Celox and Verilator 5.052 pass the dependent declarations and subsequent instance overrides.", + "known_issue": { + "id": "sv_icarus_interface_parameter_declarations", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects hierarchical interface parameter references in constant declarations, including localparam initializers and port dimensions. Celox and Verilator 5.052 pass the dependent declarations and subsequent instance overrides.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/interface-declarations-icarus.json", + "verification/sv/limitations/interface-dependent-ports-icarus.json" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "name": "interfaces::queries_interface_packed_struct_member_dimensions", + "category": "Hierarchy", + "expectation": "Simulation", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 returns 0 for $dimensions of a packed structure field, both through an interface member and through a local structure shadowing the interface handle. Celox and Verilator 5.052 return the declared packed dimension count, consistent with IEEE 1800-2023 20.7. The shared cases also check $size and lexical name resolution.", + "known_issue": { + "id": "sv_icarus_interface_struct_dimensions", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 returns 0 for $dimensions of a packed structure field, both through an interface member and through a local structure shadowing the interface handle. Celox and Verilator 5.052 return the declared packed dimension count, consistent with IEEE 1800-2023 20.7. The shared cases also check $size and lexical name resolution.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/interface-dimensions-icarus.json", + "verification/sv/limitations/interface-shadowing-icarus.json" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "name": "interfaces::propagates_interface_dependent_ports", + "category": "Hierarchy", + "expectation": "Simulation", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects hierarchical interface parameter references in constant declarations, including localparam initializers and port dimensions. Celox and Verilator 5.052 pass the dependent declarations and subsequent instance overrides.", + "known_issue": { + "id": "sv_icarus_interface_parameter_declarations", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects hierarchical interface parameter references in constant declarations, including localparam initializers and port dimensions. Celox and Verilator 5.052 pass the dependent declarations and subsequent instance overrides.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/interface-declarations-icarus.json", + "verification/sv/limitations/interface-dependent-ports-icarus.json" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "name": "interfaces::keeps_lexical_names_in_interface_scopes", + "category": "Hierarchy", + "expectation": "Simulation", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 returns 0 for $dimensions of a packed structure field, both through an interface member and through a local structure shadowing the interface handle. Celox and Verilator 5.052 return the declared packed dimension count, consistent with IEEE 1800-2023 20.7. The shared cases also check $size and lexical name resolution.", + "known_issue": { + "id": "sv_icarus_interface_struct_dimensions", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 returns 0 for $dimensions of a packed structure field, both through an interface member and through a local structure shadowing the interface handle. Celox and Verilator 5.052 return the declared packed dimension count, consistent with IEEE 1800-2023 20.7. The shared cases also check $size and lexical name resolution.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/interface-dimensions-icarus.json", + "verification/sv/limitations/interface-shadowing-icarus.json" + ] + }, + "phase": "skip", + "status": "ignored" } ] } diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 329fa4ef4d6..5fe8c05dfed 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -1378,5 +1378,41 @@ "system_functions::random_without_a_seed_continues_its_stream" ] } + }, + { + "id": "sv_icarus_interface_parameter_declarations", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects hierarchical interface parameter references in constant declarations, including localparam initializers and port dimensions. Celox and Verilator 5.052 pass the dependent declarations and subsequent instance overrides.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/interface-declarations-icarus.json", + "verification/sv/limitations/interface-dependent-ports-icarus.json" + ], + "cases": { + "icarus": [ + "interfaces::binds_local_interfaces_before_dependent_declarations", + "interfaces::propagates_interface_dependent_ports" + ] + } + }, + { + "id": "sv_icarus_interface_struct_dimensions", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 returns 0 for $dimensions of a packed structure field, both through an interface member and through a local structure shadowing the interface handle. Celox and Verilator 5.052 return the declared packed dimension count, consistent with IEEE 1800-2023 20.7. The shared cases also check $size and lexical name resolution.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/interface-dimensions-icarus.json", + "verification/sv/limitations/interface-shadowing-icarus.json" + ], + "cases": { + "icarus": [ + "interfaces::queries_interface_packed_struct_member_dimensions", + "interfaces::keeps_lexical_names_in_interface_scopes" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/limitations/interface-declarations-icarus.json b/crates/celox-test-suite/verification/sv/limitations/interface-declarations-icarus.json new file mode 100644 index 00000000000..dc5312b81cc --- /dev/null +++ b/crates/celox-test-suite/verification/sv/limitations/interface-declarations-icarus.json @@ -0,0 +1,42 @@ +{ + "cases": [ + { + "case_fingerprint": "6ce28ffb7fe4e13462e350cf90f4eef28f4a010764251eebea9fb6810f93e139", + "category": "Hierarchy", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:6: error: A hierarchical reference (`cfg.N') is not allowed in a constant expression.\n1 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "interfaces::binds_local_interfaces_before_dependent_declarations", + "phase": "compile", + "reused": false, + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "verified_at_unix": 1792288563 + } + ], + "context_fingerprint": "0185e667b610d070b52cfb6c885fe5fc0f345fa82bf93a5673889554ef891bc4", + "counts": { + "compile_error": 1, + "emission_error": 0, + "ignored": 0, + "mismatch": 0, + "passed": 0, + "rejected": 0, + "runtime_error": 0, + "unexpected_accept": 0, + "unsupported": 0 + }, + "exclude_stronger_than_sv": false, + "include_ignored": false, + "incremental": true, + "run_counts": { + "fresh": 1, + "reused": 0 + }, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)" +} diff --git a/crates/celox-test-suite/verification/sv/limitations/interface-dependent-ports-icarus.json b/crates/celox-test-suite/verification/sv/limitations/interface-dependent-ports-icarus.json new file mode 100644 index 00000000000..f5d83b7ae6c --- /dev/null +++ b/crates/celox-test-suite/verification/sv/limitations/interface-dependent-ports-icarus.json @@ -0,0 +1,42 @@ +{ + "cases": [ + { + "case_fingerprint": "1cb78dfea7f04bd89a555170f12432d011e6532a7a66da848c6efa89ea6e9694", + "category": "Hierarchy", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: error: A hierarchical reference (`base.N') is not allowed in a constant expression.\n/source_0.sv:3: error: Dimensions must be constant.\n/source_0.sv:3 : This MSB expression violates the rule: (base.N)-('sd1)\n2 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "interfaces::propagates_interface_dependent_ports", + "phase": "compile", + "reused": false, + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "verified_at_unix": 1792292897 + } + ], + "context_fingerprint": "66452008dd5247ff71406b66de4a2697abd6d7624bd7c67a13d43a8ee98d1b17", + "counts": { + "compile_error": 1, + "emission_error": 0, + "ignored": 0, + "mismatch": 0, + "passed": 0, + "rejected": 0, + "runtime_error": 0, + "unexpected_accept": 0, + "unsupported": 0 + }, + "exclude_stronger_than_sv": false, + "include_ignored": false, + "incremental": true, + "run_counts": { + "fresh": 1, + "reused": 0 + }, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)" +} diff --git a/crates/celox-test-suite/verification/sv/limitations/interface-dimensions-icarus.json b/crates/celox-test-suite/verification/sv/limitations/interface-dimensions-icarus.json new file mode 100644 index 00000000000..db10464f51e --- /dev/null +++ b/crates/celox-test-suite/verification/sv/limitations/interface-dimensions-icarus.json @@ -0,0 +1,42 @@ +{ + "cases": [ + { + "case_fingerprint": "20e017a5ac191050ac2a0720307057eebac26bbba4bf31fbb41bdc3c5b1ebcfb", + "category": "Hierarchy", + "detail": "interfaces::queries_interface_packed_struct_member_dimensions at 534:3: assert_eq dimensions: expected 0x2, got 0x0", + "expectation": "Simulation", + "name": "interfaces::queries_interface_packed_struct_member_dimensions", + "phase": "execute", + "reused": false, + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "verified_at_unix": 1792288582 + } + ], + "context_fingerprint": "0185e667b610d070b52cfb6c885fe5fc0f345fa82bf93a5673889554ef891bc4", + "counts": { + "compile_error": 0, + "emission_error": 0, + "ignored": 0, + "mismatch": 1, + "passed": 0, + "rejected": 0, + "runtime_error": 0, + "unexpected_accept": 0, + "unsupported": 0 + }, + "exclude_stronger_than_sv": false, + "include_ignored": false, + "incremental": true, + "run_counts": { + "fresh": 1, + "reused": 0 + }, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)" +} diff --git a/crates/celox-test-suite/verification/sv/limitations/interface-shadowing-icarus.json b/crates/celox-test-suite/verification/sv/limitations/interface-shadowing-icarus.json new file mode 100644 index 00000000000..245a8ebbf80 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/limitations/interface-shadowing-icarus.json @@ -0,0 +1,42 @@ +{ + "cases": [ + { + "case_fingerprint": "5c08cf45119552565bbbabfef31ebce18327f04e167d06c716d80a20db91a98c", + "category": "Hierarchy", + "detail": "interfaces::keeps_lexical_names_in_interface_scopes at 588:3: assert_eq function_shape: expected 0x69, got 0x5", + "expectation": "Simulation", + "name": "interfaces::keeps_lexical_names_in_interface_scopes", + "phase": "execute", + "reused": false, + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "verified_at_unix": 1792292723 + } + ], + "context_fingerprint": "8e9fa23e8d41769ae15bf37949352b40cf4313345eadf65d51d41004239d3fd1", + "counts": { + "compile_error": 0, + "emission_error": 0, + "ignored": 0, + "mismatch": 1, + "passed": 0, + "rejected": 0, + "runtime_error": 0, + "unexpected_accept": 0, + "unsupported": 0 + }, + "exclude_stronger_than_sv": false, + "include_ignored": false, + "incremental": true, + "run_counts": { + "fresh": 1, + "reused": 0 + }, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)" +} diff --git a/crates/celox/tests/frontends/systemverilog/interfaces.rs b/crates/celox/tests/frontends/systemverilog/interfaces.rs index e93d6a9f4c7..66bc18b6945 100644 --- a/crates/celox/tests/frontends/systemverilog/interfaces.rs +++ b/crates/celox/tests/frontends/systemverilog/interfaces.rs @@ -1,4 +1,20 @@ sv_backends! { + fn propagates_interface_dependent_ports(sim) { + @case "interfaces::propagates_interface_dependent_ports"; + } + fn keeps_lexical_names_in_interface_scopes(sim) { + @case "interfaces::keeps_lexical_names_in_interface_scopes"; + } + fn binds_interfaces_without_declaration_name_dependencies(sim) { + @case "interfaces::binds_interfaces_without_declaration_name_dependencies"; + } + fn binds_local_interfaces_before_dependent_declarations(sim) { + @case "interfaces::binds_local_interfaces_before_dependent_declarations"; + } + fn queries_interface_packed_struct_member_dimensions(sim) { + @case "interfaces::queries_interface_packed_struct_member_dimensions"; + } + fn binds_interface_array_ports_in_declaration_order(sim) { @case "interfaces::binds_interface_array_ports_in_declaration_order"; } @@ -56,4 +72,8 @@ sv_backends! { fn initializes_interface_array_members_from_their_declarations(sim) { @case "interfaces::initializes_interface_array_members_from_their_declarations"; } + fn distinguishes_interface_dependency_bindings(sim) { + @case "interfaces::distinguishes_interface_dependency_bindings"; + } + } From 506d2aefd5ed4310d1dcc7c34fe3f8a47e588549 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 18 Oct 2026 12:26:18 +0900 Subject: [PATCH 3/5] fix(sim)!: commit blocking flip-flop stores in the active region An edge-triggered `always` committed its blocking and nonblocking results together when its domain applied. IEEE 1800-2023 (4.5, 10.4) executes the blocking stores in the active region and the nonblocking updates in the NBA region (#1470): - A variable one block writes both ways now stages its nonblocking writes in a hidden value and a mask of the bits they wrote; the commit merges them after the blocking value. `q <= 7; q = 2;` ends with 7 and a read after `q <= 7` sees the old `q`, on every path. - In a design with process kernels, a domain whose blocking results are observed (read through combinational logic by a kernel or another domain's evaluation, a wait term, or another domain's event signal) commits them with its evaluation and only the nonblocking ones in the NBA region. The reference loop settles combinational logic and wakes waits after such a domain evaluates before the inactive region, so their processes run in the active region. Other domains and the fused units commit as before. The runtime schema lists those domains, so the native image container moves to version 14; older images are rejected. BREAKING CHANGE: `RuntimeSchema` and `ScheduleModel` have the new field `active_commits`, and native images of container version 13 are rejected. Change-Id: I2c5a64fed1e96648f3c3b7419f39acb5f576bb32 --- crates/celox-design/src/lib.rs | 5 + crates/celox-design/src/schedule.rs | 4 + crates/celox-frontend-core/src/sdk.rs | 1 + .../src/symbolic/artifact.rs | 14 + .../src/symbolic/assembly.rs | 207 ++++++++++++- crates/celox-frontend-sv/src/lowering.rs | 34 ++- crates/celox-frontend-sv/src/lowering/ff.rs | 279 +++++++++++++++++- .../src/lowering/procedural.rs | 25 ++ crates/celox-frontend-veryl/src/artifact.rs | 1 + crates/celox-runtime/src/schedule.rs | 10 + .../celox-runtime/src/simulation/process.rs | 11 +- crates/celox-runtime/src/simulation/round.rs | 8 +- .../src/sv/cases/procedural.vtest | 24 ++ crates/celox/src/backend/native/backend.rs | 3 + .../src/simulation/runtime_core_tests.rs | 19 ++ ...aces__trace_sv_active_commits_default.snap | 76 +++++ ...__trace_sv_active_commits_interpreter.snap | 76 +++++ .../frontends/systemverilog/procedural.rs | 4 + .../systemverilog/review_regressions.rs | 6 +- .../tests/frontends/systemverilog/timing.rs | 2 - crates/celox/tests/shared_jit_cache.rs | 28 ++ 21 files changed, 815 insertions(+), 22 deletions(-) create mode 100644 crates/celox/src/simulation/snapshots/celox__simulation__runtime_core_tests__sv_traces__trace_sv_active_commits_default.snap create mode 100644 crates/celox/src/simulation/snapshots/celox__simulation__runtime_core_tests__sv_traces__trace_sv_active_commits_interpreter.snap diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index c3ff7ae31c5..802d454df37 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -602,6 +602,10 @@ pub struct RuntimeSchema { /// Nonblocking assignment sites of the process kernels, ordered like /// `wait_sites`. pub nba_sites: Vec>, + /// Canonical event domains whose evaluation commits the results of + /// their blocking assignments, in the active region; their apply units + /// commit only the nonblocking results. + pub active_commits: Vec, } impl Default for RuntimeSchema { @@ -621,6 +625,7 @@ impl Default for RuntimeSchema { watches: Vec::new(), wait_sites: Vec::new(), nba_sites: Vec::new(), + active_commits: Vec::new(), } } } diff --git a/crates/celox-design/src/schedule.rs b/crates/celox-design/src/schedule.rs index fd8175aa5b7..27d344ee7a5 100644 --- a/crates/celox-design/src/schedule.rs +++ b/crates/celox-design/src/schedule.rs @@ -37,6 +37,9 @@ pub struct ScheduleModel { pub has_pending_nba_sites: bool, /// The design can execute `$finish`. pub finish_sites: bool, + /// Canonical event domains whose evaluation commits their blocking + /// results ([`RuntimeSchema::active_commits`]). + pub active_commits: Vec, } /// A counted signal and the canonical domains its counters trigger. @@ -129,6 +132,7 @@ impl ScheduleModel { .runtime_event_sites .iter() .any(|site| matches!(site.kind, RuntimeEventKind::Finish)), + active_commits: schema.active_commits.clone(), } } diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index aa42635fc38..4781f488367 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1905,6 +1905,7 @@ pub fn lower_frontend_artifact( eval_only_ff_blocks, apply_ff_blocks, eval_apply_ff_blocks, + split_commit_ff_blocks: HashMap::default(), parallel_ff_parts: HashMap::default(), glue_blocks: HashMap::default(), indexed_instance_names: HashSet::default(), diff --git a/crates/celox-frontend-core/src/symbolic/artifact.rs b/crates/celox-frontend-core/src/symbolic/artifact.rs index 2baccec6144..aceb112eff9 100644 --- a/crates/celox-frontend-core/src/symbolic/artifact.rs +++ b/crates/celox-frontend-core/src/symbolic/artifact.rs @@ -54,6 +54,15 @@ pub struct SymbolicProcess { pub slots: ProcessSlots, } +/// The commit of a trigger group's results, split by region. +#[derive(Clone, Debug)] +pub struct SplitCommit { + /// Commits of the results of blocking assignments. + pub active: ExecutionUnit, + /// Commits of the results of nonblocking assignments. + pub nba: ExecutionUnit, +} + #[derive(Clone)] pub struct SimModule { /// A frontend's global tick precision; absent for scale-free frontends. @@ -67,6 +76,11 @@ pub struct SimModule { pub eval_only_ff_blocks: HashMap, ExecutionUnit>, pub apply_ff_blocks: HashMap, ExecutionUnit>, pub eval_apply_ff_blocks: HashMap, ExecutionUnit>, + /// `apply_ff_blocks` split into the commit of the blocking results (the + /// active region) and that of the nonblocking ones (the NBA region), for + /// a domain whose blocking results another unit observes before the NBA + /// region. Empty when the frontend does not distinguish them. + pub split_commit_ff_blocks: HashMap, SplitCommit>, /// Lane-partitioning alternative of `eval_only_ff_blocks` and /// `apply_ff_blocks`: a trigger group split into parts which may be /// evaluated concurrently. Empty unless several lanes were requested. diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 7581c99d08f..1357ee3d5e0 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -1,7 +1,7 @@ use std::collections::{BTreeMap, BTreeSet}; use crate::symbolic::artifact::{ - FfPart, RelocationModule, SimModule, SymbolicGlueAddr as GlueAddr, SymbolicRtl, + FfPart, RelocationModule, SimModule, SplitCommit, SymbolicGlueAddr as GlueAddr, SymbolicRtl, }; use crate::{ FrontendLookup, FrontendTrace, FrontendTraceOptions, FusedSirOptimizationHints, HashMap, @@ -26,6 +26,10 @@ use celox_slt::{ type AbsoluteAddr = SourceAddr; type RegionedAbsoluteAddr = RegionedAbsoluteAddrBase; + +/// Per canonical event, the split commit of each of its apply units, in +/// their order; `None` for a unit whose frontend does not split it. +type SplitCommits = HashMap>>>; type RegionedVarAddr = celox_design::RegionedVarAddrBase; /// Runtime IDs assigned while a module instance is relocated into the global @@ -641,6 +645,7 @@ pub fn schedule_symbolic_rtl( unify_clock_domains(bindings, &expanded, &instance_modules, &modules) ); let mut parallel_ff_units = HashMap::default(); + let mut split_commits = SplitCommits::default(); let ( mut global_arena, mut eval_apply_ffs, @@ -668,6 +673,7 @@ pub fn schedule_symbolic_rtl( &unpacked_element_widths, &clock_domains, parallel.enabled().then_some(&mut parallel_ff_units), + &mut split_commits, trace_opts, &mut trace, ) @@ -705,6 +711,8 @@ pub fn schedule_symbolic_rtl( &mut comb_blocks, ) }; + // Combinational values and the variables they are computed from. + let comb_sources = comb_sources(&comb_blocks, &global_arena); check_package_variable_drivers( bindings, &instance_modules, @@ -1228,6 +1236,31 @@ pub fn schedule_symbolic_rtl( eval_apply_ffs, } }); + // With process kernels, a domain whose blocking results another unit + // observes commits them with its evaluation, in the active region, and + // only its nonblocking results in the NBA region (IEEE 1800-2023 4.5, + // 10.4). Every other domain commits both together, as before. + let mut active_commits = Vec::new(); + if !processes.is_empty() { + let events: HashSet = eval_apply_ffs + .keys() + .copied() + .chain(clock_domains.keys().copied()) + .collect(); + active_commits = split_observed_commits( + &mut eval_only_ffs, + &mut apply_ffs, + split_commits, + &comb_sources, + processes.iter().map(|process| &process.kernel), + timing + .wait_sites + .iter() + .flat_map(|site| site.terms.iter().map(|(signal, _)| *signal)), + &events, + &clock_domains, + ); + } let (eval_only_ffs, apply_ffs) = if needs_split_path { (eval_only_ffs, apply_ffs) } else { @@ -1523,6 +1556,7 @@ pub fn schedule_symbolic_rtl( wait_sites.iter().map(|site| site.map(project)).collect(); let nba_sites: Vec> = nba_sites.iter().map(|site| site.map(project)).collect(); + let active_commits: Vec = active_commits.into_iter().map(project).collect(); // The runtime reads counters, the signals waits watch and staged // nonblocking values directly; no unit loads a wait's signal. let timing_read_roots = watches @@ -1590,6 +1624,7 @@ pub fn schedule_symbolic_rtl( watches, wait_sites, nba_sites, + active_commits, }, }; @@ -2291,6 +2326,7 @@ fn relocate_units( parallel_ff_units: Option< &mut HashMap)>>, >, + split_commits: &mut SplitCommits, trace_opts: &crate::FrontendTraceOptions, trace: &mut Option<&mut crate::FrontendTrace>, ) -> Result< @@ -2640,6 +2676,42 @@ fn relocate_units( .get(&clock_addr) .copied() .unwrap_or(clock_addr); + // The split commit of each apply unit, in the same order. + let split = sim_module + .split_commit_ff_blocks + .get(trigger_set) + .map(|split| SplitCommit { + active: relocate_executation_unit_with_errors( + &split.active, + &|addr| bindings.locate_regioned(addr.region, *id, addr.var_id), + &runtime_error_codes, + &runtime_event_site_map, + &extern_function_map, + ), + nba: relocate_executation_unit_with_errors( + &split.nba, + &|addr| bindings.locate_regioned(addr.region, *id, addr.var_id), + &runtime_error_codes, + &runtime_event_site_map, + &extern_function_map, + ), + }); + // Pushed like the apply units below: the clock, then each reset. + split_commits + .entry(canonical_addr) + .or_default() + .push(split.clone()); + for &reset in &trigger_set.resets { + let reset_addr = bindings.locate(*id, reset); + let canonical_addr = clock_domains + .get(&reset_addr) + .copied() + .unwrap_or(reset_addr); + split_commits + .entry(canonical_addr) + .or_default() + .push(split.clone()); + } apply_ffs.entry(canonical_addr).or_default().push( relocate_executation_unit_with_errors( eu, @@ -2731,6 +2803,139 @@ struct TimingMetadata { nba_sites: Vec>, } +/// For every combinational value, the variables it is computed from. +fn comb_sources( + comb_blocks: &[celox_slt::LogicPath], + arena: &SLTNodeArena, +) -> HashMap> { + let mut sources: HashMap> = HashMap::default(); + for path in comb_blocks { + let Some(target) = path.target.var() else { + continue; + }; + let mut inputs = HashSet::default(); + if matches!(path.target, celox_slt::LogicPathTarget::Process { .. }) { + inputs.extend(path.sources.iter().cloned()); + } else { + crate::flattening::collect_inputs(path.expr, arena, &mut inputs); + } + sources + .entry(target.id) + .or_default() + .extend(inputs.into_iter().map(|atom| atom.id)); + } + sources +} + +/// The variables `unit` loads. +fn unit_loads(unit: &ExecutionUnit, loads: &mut HashSet) { + for block in unit.blocks.values() { + for instruction in &block.instructions { + if let SIRInstruction::Load(_, addr, ..) = instruction { + loads.insert(addr.absolute_addr()); + } + } + } +} + +/// `reads` closed over combinational logic: with a value, the variables it +/// is computed from. +fn through_comb( + mut reads: HashSet, + comb_sources: &HashMap>, +) -> HashSet { + let mut pending: Vec = reads.iter().copied().collect(); + while let Some(read) = pending.pop() { + for source in comb_sources.get(&read).into_iter().flatten() { + if reads.insert(*source) { + pending.push(*source); + } + } + } + reads +} + +/// Move the commits of the blocking results of every observed domain from +/// its apply units to its evaluation: a blocking result is observed when +/// it, or a combinational value computed from it, is read by a process +/// kernel or by another domain's evaluation, is a wait term, or is another +/// domain's event signal. Domains whose apply units the frontend did not +/// split keep them. +#[allow(clippy::too_many_arguments)] +fn split_observed_commits<'k>( + eval_only_ffs: &mut HashMap>>, + apply_ffs: &mut HashMap>>, + split_commits: SplitCommits, + comb_sources: &HashMap>, + kernels: impl Iterator>, + wait_terms: impl Iterator, + events: &HashSet, + clock_domains: &HashMap, +) -> Vec { + let mut split = Vec::new(); + let mut shared: HashSet = wait_terms.collect(); + for kernel in kernels { + unit_loads(kernel, &mut shared); + } + let evaluation_loads: HashMap> = eval_only_ffs + .iter() + .map(|(event, units)| { + let mut loads = HashSet::default(); + for unit in units { + unit_loads(unit, &mut loads); + } + (*event, loads) + }) + .collect(); + let canonical = |event: &AbsoluteAddr| clock_domains.get(event).copied().unwrap_or(*event); + for (domain, splits) in split_commits { + let Some(splits) = splits.into_iter().collect::>>() else { + continue; + }; + if apply_ffs.get(&domain).map_or(0, Vec::len) != splits.len() { + continue; + } + let mut blocking = HashSet::default(); + for split in &splits { + for block in split.active.blocks.values() { + for instruction in &block.instructions { + if let SIRInstruction::Commit(_, dst, ..) = instruction { + blocking.insert(dst.absolute_addr()); + } + } + } + } + if blocking.is_empty() { + continue; + } + let mut reads = shared.clone(); + reads.extend( + events + .iter() + .filter(|event| canonical(event) != domain) + .copied(), + ); + for (event, loads) in &evaluation_loads { + if *event != domain { + reads.extend(loads.iter().copied()); + } + } + let reads = through_comb(reads, comb_sources); + if blocking.is_disjoint(&reads) { + continue; + } + let (active, nba): (Vec<_>, Vec<_>) = splits + .into_iter() + .map(|split| (split.active, split.nba)) + .unzip(); + eval_only_ffs.entry(domain).or_default().extend(active); + apply_ffs.insert(domain, nba); + split.push(domain); + } + split.sort_unstable(); + split +} + /// Place the timing metadata of every instance. Sites name the global index /// of their process; a kernel numbers its sites in the order they appear /// here, which is the module's order. diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 80cb127432b..339d3836e6b 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -1978,6 +1978,7 @@ fn lower_module_with_overrides( eval_only_ff_blocks, apply_ff_blocks, eval_apply_ff_blocks, + split_commit_ff_blocks, reset_clock_map, parallel_ff_parts, event_vars, @@ -2094,6 +2095,7 @@ fn lower_module_with_overrides( eval_only_ff_blocks, apply_ff_blocks, eval_apply_ff_blocks, + split_commit_ff_blocks, parallel_ff_parts, glue_blocks: HashMap::default(), indexed_instance_names: HashSet::default(), @@ -6294,6 +6296,10 @@ type SvFfBlocks = ( HashMap, ExecutionUnit>, HashMap, ExecutionUnit>, HashMap, ExecutionUnit>, + HashMap< + TriggerSet, + celox_frontend_core::symbolic::artifact::SplitCommit, + >, HashMap, HashMap< TriggerSet, @@ -6390,6 +6396,8 @@ fn lower_ff_processes( let mut parallel_ff_parts = HashMap::<_, Vec<_>>::default(); let mut eval_only_ff_blocks = HashMap::default(); let mut apply_ff_blocks = HashMap::default(); + let mut active_ff_blocks = HashMap::default(); + let mut nba_ff_blocks: HashMap<_, ExecutionUnit> = HashMap::default(); let mut eval_apply_ff_blocks = HashMap::default(); let mut reset_clock_map = HashMap::default(); @@ -6451,8 +6459,13 @@ fn lower_ff_processes( } let sites_before = pm.runtime_event_sites.len(); let extern_calls_before = pm.extern_calls; - let (eval_only, apply, targets) = - ff::Ff::new(pm, random_seeds[&(0, index)]).lower_process(process.body())?; + let ff::FfProcessUnits { + eval: eval_only, + apply, + active, + nba, + targets, + } = ff::Ff::new(pm, random_seeds[&(0, index)]).lower_process(process.body())?; // A process without writes still runs for its runtime events and // extern calls. let has_effects = @@ -6470,7 +6483,9 @@ fn lower_ff_processes( }); } insert_or_merge_ff_unit(&mut eval_only_ff_blocks, trigger_set.clone(), eval_only); - insert_or_merge_ff_unit(&mut apply_ff_blocks, trigger_set, apply); + insert_or_merge_ff_unit(&mut apply_ff_blocks, trigger_set.clone(), apply); + insert_or_merge_ff_unit(&mut active_ff_blocks, trigger_set.clone(), active); + insert_or_merge_ff_unit(&mut nba_ff_blocks, trigger_set, nba); } // Every process of a trigger evaluates against the pre-edge state before // any of them commits (IEEE 1800-2023 10.4.2), so the combined unit runs @@ -6484,10 +6499,23 @@ fn lower_ff_processes( // One process is the whole trigger group. parallel_ff_parts.retain(|_, parts| parts.len() > 1); + let split_commit_ff_blocks = active_ff_blocks + .into_iter() + .map(|(trigger_set, active)| { + let nba = nba_ff_blocks + .remove(&trigger_set) + .expect("every trigger group has both commits"); + ( + trigger_set, + celox_frontend_core::symbolic::artifact::SplitCommit { active, nba }, + ) + }) + .collect(); Ok(( eval_only_ff_blocks, apply_ff_blocks, eval_apply_ff_blocks, + split_commit_ff_blocks, reset_clock_map, parallel_ff_parts, event_vars, diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 3c8947420e5..431ca8eea0f 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -35,6 +35,8 @@ pub(super) struct Ff<'p, 'a> { b: SIRBuilder, /// Variables read from the working region. working: HashSet, + /// Variables a nonblocking assignment writes. + nonblocking: HashSet, /// The bits whose working value is the process result. targets: Vec<(SourceVarId, BitAccess)>, loops: Vec, @@ -92,6 +94,7 @@ impl<'p, 'a> Ff<'p, 'a> { m, b: SIRBuilder::new(), working: HashSet::default(), + nonblocking: HashSet::default(), targets: Vec::new(), loops: Vec::new(), functions: Vec::new(), @@ -138,6 +141,8 @@ impl<'p, 'a> Ff<'p, 'a> { }; if blocking { self.working.insert(id); + } else { + self.nonblocking.insert(id); } if self.m.is_hidden(id) { return; @@ -2860,14 +2865,7 @@ impl<'p, 'a> Ff<'p, 'a> { pub fn lower_process( mut self, body: &[sv::ir::Stmt], - ) -> Result< - ( - ExecutionUnit, - ExecutionUnit, - Vec>, - ), - sv::AnalyzerError, - > { + ) -> Result { let mut visited = HashSet::default(); self.scan(body, &mut visited); // Merge the written ranges of each variable. @@ -2894,14 +2892,275 @@ impl<'p, 'a> Ff<'p, 'a> { .map(|access| VarAtomBase::new(id, access.lsb, access.msb)), ); } + // A variable the process writes both ways keeps its nonblocking + // values apart: blocking reads see the blocking value, and the + // nonblocking update lands after it (IEEE 1800-2023 10.4). + let mut mixed: Vec = self + .nonblocking + .intersection(&self.working) + .copied() + .filter(|&id| !self.m.is_hidden(id) && self.m.var(id).array_dims.is_empty()) + .collect(); + mixed.sort_by_key(|id| id.0); + let staged: Vec = mixed + .into_iter() + .map(|id| { + let (value, value_name) = self.m.shadow(id, "nba_value", false); + let (mask, mask_name) = self.m.shadow(id, "nba_mask", true); + NbaStage { + id, + name: self.m.var(id).path.join("."), + value, + value_name, + mask, + mask_name, + } + }) + .collect(); + let body = if staged.is_empty() { + body.to_vec() + } else { + stage_nonblocking(body, &staged, self.m) + }; emit_ff_seeds(&mut self.b, &targets); - if self.exec_block(body)? { + for stage in &staged { + let width = self.m.var(stage.mask).width; + let zero = self.b.alloc_bit(width, false); + self.b.emit(SIRInstruction::Imm(zero, SIRValue::new(0u8))); + self.store(stage.mask, SIROffset::Static(0), width, zero); + } + if self.exec_block(&body)? { self.b.seal_block(SIRTerminator::Return); } let eval = seal_drained(self.b); + let (active_targets, nba_targets): (Vec<_>, Vec<_>) = targets + .iter() + .copied() + .partition(|target| self.working.contains(&target.id)); let mut apply = SIRBuilder::new(); emit_ff_commits(&mut apply, &targets); - Ok((eval, seal_builder(apply), targets)) + emit_nba_merges(&mut apply, &staged, self.m); + let mut active = SIRBuilder::new(); + emit_ff_commits(&mut active, &active_targets); + let mut nba = SIRBuilder::new(); + emit_ff_commits(&mut nba, &nba_targets); + emit_nba_merges(&mut nba, &staged, self.m); + Ok(FfProcessUnits { + eval, + apply: seal_builder(apply), + active: seal_builder(active), + nba: seal_builder(nba), + targets, + }) + } +} + +/// The units of an edge-triggered process: its evaluation, the commit of +/// all its results, and that commit split into the blocking results (the +/// active region) and the nonblocking ones (the NBA region). +pub(super) struct FfProcessUnits { + pub eval: ExecutionUnit, + pub apply: ExecutionUnit, + pub active: ExecutionUnit, + pub nba: ExecutionUnit, + pub targets: Vec>, +} + +/// The staging of a variable a process writes both by blocking and by +/// nonblocking assignments: the nonblocking value and a mask of the bits +/// the nonblocking assignments wrote. +struct NbaStage { + id: SourceVarId, + name: String, + value: SourceVarId, + value_name: String, + mask: SourceVarId, + mask_name: String, +} + +/// `stmts` with every nonblocking assignment to a staged variable writing +/// its staging value instead, and marking the written bits in its mask. +fn stage_nonblocking( + stmts: &[sv::ir::Stmt], + staged: &[NbaStage], + pm: &ProcModule<'_>, +) -> Vec { + let stage_of = |lvalue: &sv::ir::LValue| { + staged + .iter() + .find(|stage| pm.id(lvalue.name()) == Some(stage.id)) + }; + let renamed = |lvalue: &sv::ir::LValue, name: &str| match lvalue { + sv::ir::LValue::Ident(_) => sv::ir::LValue::Ident(name.to_string()), + sv::ir::LValue::Select { + msb, + lsb, + array_slice_width, + array_slice_reversed, + .. + } => sv::ir::LValue::Select { + name: name.to_string(), + msb: msb.clone(), + lsb: lsb.clone(), + array_slice_width: array_slice_width.clone(), + array_slice_reversed: *array_slice_reversed, + }, + }; + let mark = |lvalue: &sv::ir::LValue, stage: &NbaStage| sv::ir::Stmt::Assign { + lhs: renamed(lvalue, &stage.mask_name), + rhs: sv::ir::Expr::Literal("'1".to_string()), + nonblocking: true, + }; + let mut out = Vec::with_capacity(stmts.len()); + for stmt in stmts { + match stmt { + sv::ir::Stmt::Assign { + lhs, + rhs, + nonblocking: true, + } if stage_of(lhs).is_some() => { + let stage = stage_of(lhs).unwrap(); + out.push(sv::ir::Stmt::Assign { + lhs: renamed(lhs, &stage.value_name), + rhs: rhs.clone(), + nonblocking: true, + }); + out.push(mark(lhs, stage)); + } + sv::ir::Stmt::AssignConcat { + parts, + rhs, + nonblocking: true, + } if parts.iter().any(|part| stage_of(part).is_some()) => { + out.push(sv::ir::Stmt::AssignConcat { + parts: parts + .iter() + .map(|part| match stage_of(part) { + Some(stage) => renamed(part, &stage.value_name), + None => part.clone(), + }) + .collect(), + rhs: rhs.clone(), + nonblocking: true, + }); + for part in parts { + if let Some(stage) = stage_of(part) { + out.push(mark(part, stage)); + } + } + } + sv::ir::Stmt::If { + condition, + then_body, + else_body, + } => out.push(sv::ir::Stmt::If { + condition: condition.clone(), + then_body: stage_nonblocking(then_body, staged, pm), + else_body: stage_nonblocking(else_body, staged, pm), + }), + sv::ir::Stmt::Case { + kind, + selector, + items, + default, + } => out.push(sv::ir::Stmt::Case { + kind: *kind, + selector: selector.clone(), + items: items + .iter() + .map(|item| sv::ir::CaseItem { + labels: item.labels.clone(), + body: stage_nonblocking(&item.body, staged, pm), + }) + .collect(), + default: default + .as_ref() + .map(|body| stage_nonblocking(body, staged, pm)), + }), + sv::ir::Stmt::Loop { + kind, + init, + condition, + step, + body, + } => out.push(sv::ir::Stmt::Loop { + kind: kind.clone(), + init: init.clone(), + condition: condition.clone(), + step: step.clone(), + body: stage_nonblocking(body, staged, pm), + }), + other => out.push(other.clone()), + } + } + out +} + +/// Publish the staged nonblocking values: each variable takes its staging +/// value in the bits the mask marks, after its blocking value was +/// committed. +fn emit_nba_merges(builder: &mut SIRBuilder, staged: &[NbaStage], pm: &ProcModule<'_>) { + for stage in staged { + let _ = &stage.name; + let variable = pm.var(stage.id); + let width = variable.width; + let current = if variable.is_4state { + builder.alloc_logic(width) + } else { + builder.alloc_bit(width, false) + }; + builder.emit(SIRInstruction::Load( + current, + stable(stage.id), + SIROffset::Static(0), + width, + )); + let value = if variable.is_4state { + builder.alloc_logic(width) + } else { + builder.alloc_bit(width, false) + }; + builder.emit(SIRInstruction::Load( + value, + working(stage.value), + SIROffset::Static(0), + width, + )); + let mask = builder.alloc_bit(width, false); + builder.emit(SIRInstruction::Load( + mask, + working(stage.mask), + SIROffset::Static(0), + width, + )); + let keep = builder.alloc_bit(width, false); + builder.emit(SIRInstruction::Unary(keep, UnaryOp::BitNot, mask)); + let kept = if variable.is_4state { + builder.alloc_logic(width) + } else { + builder.alloc_bit(width, false) + }; + builder.emit(SIRInstruction::Binary(kept, current, BinaryOp::And, keep)); + let taken = if variable.is_4state { + builder.alloc_logic(width) + } else { + builder.alloc_bit(width, false) + }; + builder.emit(SIRInstruction::Binary(taken, value, BinaryOp::And, mask)); + let merged = if variable.is_4state { + builder.alloc_logic(width) + } else { + builder.alloc_bit(width, false) + }; + builder.emit(SIRInstruction::Binary(merged, kept, BinaryOp::Or, taken)); + builder.emit(SIRInstruction::Store( + stable(stage.id), + SIROffset::Static(0), + width, + merged, + Vec::new(), + Vec::new(), + )); } } diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index b87fd7840c6..443c823aede 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -523,6 +523,31 @@ impl<'a> ProcModule<'a> { (id, name) } + /// A hidden variable with the shape of `id`, two-state when `two_state`. + pub fn shadow( + &mut self, + id: SourceVarId, + purpose: &str, + two_state: bool, + ) -> (SourceVarId, String) { + let name = format!("{purpose}@t{}", self.temp_counter); + self.temp_counter += 1; + let mut variable = self.variables[&id].clone(); + variable.path = vec![name.clone()]; + variable.source = None; + variable.hidden = true; + variable.domain_kind = DomainKind::Other; + if two_state { + variable.is_4state = false; + variable.type_kind = PortTypeKind::Bit; + } + let shadow = next_var_id(&mut self.next_id); + self.variables.insert(shadow, variable); + self.name_to_id.insert(name.clone(), shadow); + self.created.push(shadow); + (shadow, name) + } + /// A hidden one-bit copy of the event signal `signal`, sensed as `kind`. /// It has no name a SystemVerilog identifier can denote, and is not /// addressable by path. diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index 728194843a8..0a22ef077fb 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -494,6 +494,7 @@ pub(crate) fn project_module_with_ids( eval_only_ff_blocks: map_units(&module.eval_only_ff_blocks), apply_ff_blocks: map_units(&module.apply_ff_blocks), eval_apply_ff_blocks: map_units(&module.eval_apply_ff_blocks), + split_commit_ff_blocks: HashMap::default(), parallel_ff_parts: module .parallel_ff_parts .iter() diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index 65117fe6f3f..60ffe7a7db4 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -32,6 +32,8 @@ pub struct ResolvedSchedule { /// The design has process kernels or counted signals. Without either, a /// round is exactly the batch step and skips every process check. pub(crate) timed: bool, + /// Canonical event IDs whose evaluation commits their blocking results. + pub(crate) active_commits: bit_set::BitSet, } impl ResolvedSchedule { @@ -174,6 +176,13 @@ impl ResolvedSchedule { .collect() }; + let mut active_commits = bit_set::BitSet::new(); + for address in &model.active_commits { + if let Some(event) = backend.resolve_event_opt(address) { + active_commits.insert(event.id()); + } + } + let counted_by_offset = counted .iter() .enumerate() @@ -191,6 +200,7 @@ impl ResolvedSchedule { has_pending_nba_sites: model.has_pending_nba_sites, combinational_derived, timed: model.timed, + active_commits, } } } diff --git a/crates/celox-runtime/src/simulation/process.rs b/crates/celox-runtime/src/simulation/process.rs index 2fcc709482f..8fe00cce48d 100644 --- a/crates/celox-runtime/src/simulation/process.rs +++ b/crates/celox-runtime/src/simulation/process.rs @@ -182,7 +182,16 @@ impl SimulationState { } // The active region is empty: the domains it triggered evaluate // before the inactive region's processes resume. - self.evaluate_before_inactive(executor, current_time, round)?; + if self.evaluate_before_inactive(executor, current_time, round)? { + // Their blocking results are updates of the active region: + // continuous assignments follow them and the waits they wake + // run before the inactive region (IEEE 1800-2023 4.5). + executor.eval_comb()?; + self.observe_driven(executor.backend()); + if !self.process_state.ready.is_empty() { + continue; + } + } let inactive = std::mem::take(&mut self.process_state.inactive); self.process_state.ready.extend(inactive); } diff --git a/crates/celox-runtime/src/simulation/round.rs b/crates/celox-runtime/src/simulation/round.rs index 6ffae56c3a8..af1ce6c4676 100644 --- a/crates/celox-runtime/src/simulation/round.rs +++ b/crates/celox-runtime/src/simulation/round.rs @@ -175,19 +175,20 @@ impl SimulationState { /// Evaluate the triggered domains before an inactive region runs. Their /// nonblocking assignments stay in the working state until the NBA - /// region. + /// region. Returns whether a domain committed its blocking results. pub(super) fn evaluate_before_inactive( &mut self, executor: &mut E, current_time: u64, round: &mut Round, - ) -> Result<(), Halt> + ) -> Result where E: SimulationExecutor, { let marked = executor.backend().get_triggered_bits(); executor.backend_mut().clear_triggered_bits(); let mut evaluated = BitSet::new(); + let mut committed = false; let mut unsplit = Vec::new(); for id in marked.iter() { let info = self.model.event_info[id]; @@ -209,6 +210,7 @@ impl SimulationState { continue; } round.edge_approved.remove(id); + committed |= self.model.active_commits.contains(info.canonical_id); self.evaluate_deferred(executor, current_time, round, info)?; } // The edges are consumed: later rounds compare against the values @@ -223,7 +225,7 @@ impl SimulationState { round.scheduled_trigger_ids.insert(id); round.edge_approved.insert(id); } - Ok(()) + Ok(committed) } fn evaluate_deferred( diff --git a/crates/celox-test-suite/src/sv/cases/procedural.vtest b/crates/celox-test-suite/src/sv/cases/procedural.vtest index 0107c47f135..12890845ac2 100644 --- a/crates/celox-test-suite/src/sv/cases/procedural.vtest +++ b/crates/celox-test-suite/src/sv/cases/procedural.vtest @@ -46,6 +46,30 @@ (assert_eq shifted (trunc 8 (<< data count))) (assert_eq q data))) +(case mixed_blocking_and_nonblocking_writes_keep_their_regions + (source "mixed_writes.sv" #" + module Top(input logic clk, input logic [7:0] d, + output logic [7:0] q, output logic [7:0] x, output logic [7:0] r); + always @(posedge clk) begin + q <= d; + x = q; + q = 8'd2; + r = q; + end + endmodule + "#) + (top Top) + (modify (set d 7)) + (tick clk) + (assert_eq q 7 "the nonblocking update lands after the blocking one") + (assert_eq x 0 "a read after a nonblocking assignment sees the old value") + (assert_eq r 2) + (modify (set d 9)) + (tick clk) + (assert_eq q 9) + (assert_eq x 7) + (assert_eq r 2)) + (case constant_functions_size_parameters_and_ports (source "constant_functions.sv" #" module Child #(parameter int unsigned ENTRIES = 2, diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index e336bfe84e9..2e4c629acb6 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -395,6 +395,7 @@ pub(crate) struct NativeRuntimeSchema { pub(crate) watches: Vec>, pub(crate) wait_sites: Vec>, pub(crate) nba_sites: Vec>, + pub(crate) active_commits: Vec, } /// Pointer-free native compiler artifact which can be attached to the @@ -504,6 +505,7 @@ impl NativeProgramImage { watches: self.runtime_schema.watches.clone(), wait_sites: self.runtime_schema.wait_sites.clone(), nba_sites: self.runtime_schema.nba_sites.clone(), + active_commits: self.runtime_schema.active_commits.clone(), }, testbench: self.testbench.clone(), } @@ -2283,6 +2285,7 @@ fn compile_program( watches: sir.runtime().runtime_schema.watches.clone(), wait_sites: sir.runtime().runtime_schema.wait_sites.clone(), nba_sites: sir.runtime().runtime_schema.nba_sites.clone(), + active_commits: sir.runtime().runtime_schema.active_commits.clone(), }, layout: layout.clone(), native_memory_size, diff --git a/crates/celox/src/simulation/runtime_core_tests.rs b/crates/celox/src/simulation/runtime_core_tests.rs index 34ae5750e20..5a49f637753 100644 --- a/crates/celox/src/simulation/runtime_core_tests.rs +++ b/crates/celox/src/simulation/runtime_core_tests.rs @@ -2297,6 +2297,25 @@ mod sv_traces { /// divided clock, both edges of one clock, and the timing suite's cases /// that Celox runs. const DESIGNS: &[(&str, &str, &[&str], &[&str])] = &[ + ( + // A domain whose blocking result a process reads after `#0` + // commits it in the active region and its nonblocking update in + // the NBA region (#1470). + "sv_active_commits", + "module Top(input logic clk, output logic [7:0] q, output logic [7:0] observed, + output logic [7:0] derived_seen); + wire [7:0] derived = q + 8'd1; + always @(posedge clk) begin q <= q + 8'd7; q = 8'd2; end + initial forever begin + @(posedge clk); + #0; + observed = q; + derived_seen = derived; + end + endmodule", + &["clk"], + &["q", "observed", "derived_seen"], + ), ( "sv_buffered_clock", "module Top(input logic clk, output logic [31:0] up, output logic [31:0] down); diff --git a/crates/celox/src/simulation/snapshots/celox__simulation__runtime_core_tests__sv_traces__trace_sv_active_commits_default.snap b/crates/celox/src/simulation/snapshots/celox__simulation__runtime_core_tests__sv_traces__trace_sv_active_commits_default.snap new file mode 100644 index 00000000000..ece66b1e8a1 --- /dev/null +++ b/crates/celox/src/simulation/snapshots/celox__simulation__runtime_core_tests__sv_traces__trace_sv_active_commits_default.snap @@ -0,0 +1,76 @@ +--- +source: crates/celox/src/simulation/runtime_core_tests.rs +expression: "trace(Simulation::from_sv_sources(sources(), \"Top\").build().unwrap(), &ops,\nobserve)" +--- +modify [("clk", 0)] +run_until 0 + step -> Some(0): host_writes(0) process(0) comb finish_step(0) + time 0 finished false: q=0 observed=0 derived_seen=0 +modify [("clk", 37)] +run_until 2 + step -> Some(0): host_writes(1) process(0) comb stage(e0@0) eval_only(e0) comb process(0) comb apply(e0) fire(e0@0) comb finish_step(0) + time 2 finished false: q=7 observed=2 derived_seen=3 +modify [("clk", 74)] +run_until 4 + step -> Some(2): host_writes(1) comb finish_step(2) + time 4 finished false: q=7 observed=2 derived_seen=3 +modify [("clk", 111)] +run_until 6 + step -> Some(4): host_writes(1) process(0) comb stage(e0@4) eval_only(e0) comb process(0) comb apply(e0) fire(e0@4) comb finish_step(4) + time 6 finished false: q=14 observed=2 derived_seen=3 +modify [("clk", 148)] +run_until 8 + step -> Some(6): host_writes(1) comb finish_step(6) + time 8 finished false: q=14 observed=2 derived_seen=3 +modify [("clk", 185)] +run_until 10 + step -> Some(8): host_writes(1) process(0) comb stage(e0@8) eval_only(e0) comb process(0) comb apply(e0) fire(e0@8) comb finish_step(8) + time 10 finished false: q=21 observed=2 derived_seen=3 +modify [("clk", 222)] +run_until 12 + step -> Some(10): host_writes(1) comb finish_step(10) + time 12 finished false: q=21 observed=2 derived_seen=3 +modify [("clk", 1), ("clk", 0)] +run_until 14 + step -> Some(12): host_writes(2) process(0) comb process(0) comb finish_step(12) + time 14 finished false: q=21 observed=21 derived_seen=22 +schedule clk @15 = 1 +schedule clk @16 = 0 +schedule clk @17 = 1 +schedule clk @17 = 0 +schedule clk @18 = 1 +schedule clk @19 = 0 +run_until 20 + step -> Some(15): host_writes(0) process(0) comb stage(e0@15) eval_only(e0) comb process(0) comb apply(e0) fire(e0@15) comb finish_step(15) + step -> Some(16): host_writes(0) comb finish_step(16) + step -> Some(17): host_writes(0) process(0) comb stage(e0@17) eval_only(e0) comb process(0) comb apply(e0) fire(e0@17) comb finish_step(17) + step -> Some(18): host_writes(0) comb finish_step(18) + step -> Some(19): host_writes(0) comb finish_step(19) + time 20 finished false: q=35 observed=2 derived_seen=3 +clock clk period 4 delay 21 +run_until 40 + step -> Some(21): host_writes(0) process(0) comb stage(e0@21) eval_only(e0) comb process(0) comb apply(e0) fire(e0@21) comb finish_step(21) + step -> Some(23): host_writes(0) comb finish_step(23) + step -> Some(25): host_writes(0) process(0) comb stage(e0@25) eval_only(e0) comb process(0) comb apply(e0) fire(e0@25) comb finish_step(25) + step -> Some(27): host_writes(0) comb finish_step(27) + step -> Some(29): host_writes(0) process(0) comb stage(e0@29) eval_only(e0) comb process(0) comb apply(e0) fire(e0@29) comb finish_step(29) + step -> Some(31): host_writes(0) comb finish_step(31) + step -> Some(33): host_writes(0) process(0) comb stage(e0@33) eval_only(e0) comb process(0) comb apply(e0) fire(e0@33) comb finish_step(33) + step -> Some(35): host_writes(0) comb finish_step(35) + step -> Some(37): host_writes(0) process(0) comb stage(e0@37) eval_only(e0) comb process(0) comb apply(e0) fire(e0@37) comb finish_step(37) + step -> Some(39): host_writes(0) comb finish_step(39) + time 40 finished false: q=70 observed=2 derived_seen=3 +steps 12 + step -> Some(41): host_writes(0) process(0) comb stage(e0@41) eval_only(e0) comb process(0) comb apply(e0) fire(e0@41) comb finish_step(41) + step -> Some(43): host_writes(0) comb finish_step(43) + step -> Some(45): host_writes(0) process(0) comb stage(e0@45) eval_only(e0) comb process(0) comb apply(e0) fire(e0@45) comb finish_step(45) + step -> Some(47): host_writes(0) comb finish_step(47) + step -> Some(49): host_writes(0) process(0) comb stage(e0@49) eval_only(e0) comb process(0) comb apply(e0) fire(e0@49) comb finish_step(49) + step -> Some(51): host_writes(0) comb finish_step(51) + step -> Some(53): host_writes(0) process(0) comb stage(e0@53) eval_only(e0) comb process(0) comb apply(e0) fire(e0@53) comb finish_step(53) + step -> Some(55): host_writes(0) comb finish_step(55) + step -> Some(57): host_writes(0) process(0) comb stage(e0@57) eval_only(e0) comb process(0) comb apply(e0) fire(e0@57) comb finish_step(57) + step -> Some(59): host_writes(0) comb finish_step(59) + step -> Some(61): host_writes(0) process(0) comb stage(e0@61) eval_only(e0) comb process(0) comb apply(e0) fire(e0@61) comb finish_step(61) + step -> Some(63): host_writes(0) comb finish_step(63) + time 63 finished false: q=112 observed=2 derived_seen=3 diff --git a/crates/celox/src/simulation/snapshots/celox__simulation__runtime_core_tests__sv_traces__trace_sv_active_commits_interpreter.snap b/crates/celox/src/simulation/snapshots/celox__simulation__runtime_core_tests__sv_traces__trace_sv_active_commits_interpreter.snap new file mode 100644 index 00000000000..bcd65cd0db1 --- /dev/null +++ b/crates/celox/src/simulation/snapshots/celox__simulation__runtime_core_tests__sv_traces__trace_sv_active_commits_interpreter.snap @@ -0,0 +1,76 @@ +--- +source: crates/celox/src/simulation/runtime_core_tests.rs +expression: "trace(Simulation::new(Simulator::from_sv_sources(sources(),\n\"Top\").emit_triggers().build_interpreter().unwrap()), &ops, observe)" +--- +modify [("clk", 0)] +run_until 0 + step -> Some(0): host_writes(0) process(0) comb finish_step(0) + time 0 finished false: q=0 observed=0 derived_seen=0 +modify [("clk", 37)] +run_until 2 + step -> Some(0): host_writes(1) process(0) comb stage(e0@0) eval_only(e0) comb process(0) comb apply(e0) fire(e0@0) comb finish_step(0) + time 2 finished false: q=7 observed=2 derived_seen=3 +modify [("clk", 74)] +run_until 4 + step -> Some(2): host_writes(1) comb finish_step(2) + time 4 finished false: q=7 observed=2 derived_seen=3 +modify [("clk", 111)] +run_until 6 + step -> Some(4): host_writes(1) process(0) comb stage(e0@4) eval_only(e0) comb process(0) comb apply(e0) fire(e0@4) comb finish_step(4) + time 6 finished false: q=14 observed=2 derived_seen=3 +modify [("clk", 148)] +run_until 8 + step -> Some(6): host_writes(1) comb finish_step(6) + time 8 finished false: q=14 observed=2 derived_seen=3 +modify [("clk", 185)] +run_until 10 + step -> Some(8): host_writes(1) process(0) comb stage(e0@8) eval_only(e0) comb process(0) comb apply(e0) fire(e0@8) comb finish_step(8) + time 10 finished false: q=21 observed=2 derived_seen=3 +modify [("clk", 222)] +run_until 12 + step -> Some(10): host_writes(1) comb finish_step(10) + time 12 finished false: q=21 observed=2 derived_seen=3 +modify [("clk", 1), ("clk", 0)] +run_until 14 + step -> Some(12): host_writes(2) process(0) comb process(0) comb finish_step(12) + time 14 finished false: q=21 observed=21 derived_seen=22 +schedule clk @15 = 1 +schedule clk @16 = 0 +schedule clk @17 = 1 +schedule clk @17 = 0 +schedule clk @18 = 1 +schedule clk @19 = 0 +run_until 20 + step -> Some(15): host_writes(0) process(0) comb stage(e0@15) eval_only(e0) comb process(0) comb apply(e0) fire(e0@15) comb finish_step(15) + step -> Some(16): host_writes(0) comb finish_step(16) + step -> Some(17): host_writes(0) process(0) comb stage(e0@17) eval_only(e0) comb process(0) comb apply(e0) fire(e0@17) comb finish_step(17) + step -> Some(18): host_writes(0) comb finish_step(18) + step -> Some(19): host_writes(0) comb finish_step(19) + time 20 finished false: q=35 observed=2 derived_seen=3 +clock clk period 4 delay 21 +run_until 40 + step -> Some(21): host_writes(0) process(0) comb stage(e0@21) eval_only(e0) comb process(0) comb apply(e0) fire(e0@21) comb finish_step(21) + step -> Some(23): host_writes(0) comb finish_step(23) + step -> Some(25): host_writes(0) process(0) comb stage(e0@25) eval_only(e0) comb process(0) comb apply(e0) fire(e0@25) comb finish_step(25) + step -> Some(27): host_writes(0) comb finish_step(27) + step -> Some(29): host_writes(0) process(0) comb stage(e0@29) eval_only(e0) comb process(0) comb apply(e0) fire(e0@29) comb finish_step(29) + step -> Some(31): host_writes(0) comb finish_step(31) + step -> Some(33): host_writes(0) process(0) comb stage(e0@33) eval_only(e0) comb process(0) comb apply(e0) fire(e0@33) comb finish_step(33) + step -> Some(35): host_writes(0) comb finish_step(35) + step -> Some(37): host_writes(0) process(0) comb stage(e0@37) eval_only(e0) comb process(0) comb apply(e0) fire(e0@37) comb finish_step(37) + step -> Some(39): host_writes(0) comb finish_step(39) + time 40 finished false: q=70 observed=2 derived_seen=3 +steps 12 + step -> Some(41): host_writes(0) process(0) comb stage(e0@41) eval_only(e0) comb process(0) comb apply(e0) fire(e0@41) comb finish_step(41) + step -> Some(43): host_writes(0) comb finish_step(43) + step -> Some(45): host_writes(0) process(0) comb stage(e0@45) eval_only(e0) comb process(0) comb apply(e0) fire(e0@45) comb finish_step(45) + step -> Some(47): host_writes(0) comb finish_step(47) + step -> Some(49): host_writes(0) process(0) comb stage(e0@49) eval_only(e0) comb process(0) comb apply(e0) fire(e0@49) comb finish_step(49) + step -> Some(51): host_writes(0) comb finish_step(51) + step -> Some(53): host_writes(0) process(0) comb stage(e0@53) eval_only(e0) comb process(0) comb apply(e0) fire(e0@53) comb finish_step(53) + step -> Some(55): host_writes(0) comb finish_step(55) + step -> Some(57): host_writes(0) process(0) comb stage(e0@57) eval_only(e0) comb process(0) comb apply(e0) fire(e0@57) comb finish_step(57) + step -> Some(59): host_writes(0) comb finish_step(59) + step -> Some(61): host_writes(0) process(0) comb stage(e0@61) eval_only(e0) comb process(0) comb apply(e0) fire(e0@61) comb finish_step(61) + step -> Some(63): host_writes(0) comb finish_step(63) + time 63 finished false: q=112 observed=2 derived_seen=3 diff --git a/crates/celox/tests/frontends/systemverilog/procedural.rs b/crates/celox/tests/frontends/systemverilog/procedural.rs index 7dbc198f978..6dbb86aa139 100644 --- a/crates/celox/tests/frontends/systemverilog/procedural.rs +++ b/crates/celox/tests/frontends/systemverilog/procedural.rs @@ -19,6 +19,10 @@ sv_backends! { @case "procedural::always_ff_blocking_assignments_and_run_time_loops"; } + fn mixed_blocking_and_nonblocking_writes_keep_their_regions(sim) { + @case "procedural::mixed_blocking_and_nonblocking_writes_keep_their_regions"; + } + fn constant_functions_size_parameters_and_ports(sim) { @case "procedural::constant_functions_size_parameters_and_ports"; } diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index b6e5dfe0c0c..9421f957be7 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -8418,7 +8418,9 @@ fn reemits_run_time_loop_events_when_only_the_bound_changes() { #[test] fn commits_ff_output_actuals_whose_index_calls_a_function() { // `outer` writes `state[inner(k)]` from an always_ff select index; the - // write is committed with the process. + // write is committed with the process. `state` is cleared by a blocking + // assignment: a nonblocking clear would land after the call's write + // (IEEE 1800-2023 10.4) and hide it. let source = r#" module Top(input bit clk, input logic [1:0] k, output logic [3:0] st, output logic [3:0] bits); @@ -8431,7 +8433,7 @@ fn commits_ff_output_actuals_whose_index_calls_a_function() { endfunction logic [3:0] state; always_ff @(posedge clk) begin - state <= 4'd0; + state = 4'd0; bits[outer(state[inner(k)])] <= 1'b1; end assign st = state; diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index c328084f97b..1cb41dade0a 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -68,10 +68,8 @@ timed_cases! { fn run_until_drains_target_time_before_later_writes = "timing::run_until_drains_target_time_before_later_writes"; fn repeated_settles_do_not_advance_design_time = "timing::repeated_settles_do_not_advance_design_time"; fn run_to_finish_has_no_simulated_time_deadline = "timing::run_to_finish_has_no_simulated_time_deadline"; - #[ignore = "blocking stores of an edge-triggered always are committed with its nonblocking ones, not in the active region (#1470)"] fn blocking_ff_stores_are_visible_before_inactive_work = "timing::blocking_ff_stores_are_visible_before_inactive_work"; fn nonblocking_ff_stores_remain_pending_during_inactive_work = "timing::nonblocking_ff_stores_remain_pending_during_inactive_work"; - #[ignore = "blocking stores of an edge-triggered always are committed with its nonblocking ones, not in the active region (#1470)"] fn mixed_ff_stores_keep_their_active_and_nba_values = "timing::mixed_ff_stores_keep_their_active_and_nba_values"; fn printed_finish_notice_is_design_output = "timing::printed_finish_notice_is_design_output"; fn combinational_finish_ends_timed_execution = "timing::combinational_finish_ends_timed_execution"; diff --git a/crates/celox/tests/shared_jit_cache.rs b/crates/celox/tests/shared_jit_cache.rs index df1cf51d34d..04445164739 100644 --- a/crates/celox/tests/shared_jit_cache.rs +++ b/crates/celox/tests/shared_jit_cache.rs @@ -674,6 +674,34 @@ fn native_program_image_rejects_v3_before_decoding_changed_schema() { )); } +/// Version 14 added the domains that commit their blocking results with +/// their evaluation; a version 13 image lacks them and is rejected. +#[test] +fn native_program_image_rejects_v13_before_decoding_changed_schema() { + let sim = Simulator::builder(ADDER, "Top").build().unwrap(); + let mut encoded = sim + .shared_code() + .program_image() + .to_container_bytes() + .unwrap(); + let trailer_start = encoded.len() - NATIVE_IMAGE_TRAILER_SIZE; + encoded[trailer_start + NATIVE_IMAGE_VERSION_OFFSET + ..trailer_start + NATIVE_IMAGE_VERSION_OFFSET + 2] + .copy_from_slice(&13u16.to_le_bytes()); + + let Err(error) = celox::NativeProgramImage::discover_appended(&encoded) else { + panic!("a version 13 image must be rejected"); + }; + assert!( + matches!(error, NativeImageContainerError::UnsupportedVersion(13)), + "{error}" + ); + assert_eq!( + error.to_string(), + "native image container version 13 is unsupported" + ); +} + #[test] fn native_program_image_writes_an_executable_runtime_file() { let sim = Simulator::builder(ADDER, "Top").build().unwrap(); From 547ccf3e422d424a5368029d3378002af4c122da Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 18 Oct 2026 18:30:00 +0900 Subject: [PATCH 4/5] fix(sim): trigger the domains a blocking flip-flop commit gives an edge A domain that commits its blocking results before the inactive region changed event signals of other domains, directly or through combinational logic, but the new levels became the edge baseline without an edge. The reference loop now takes the levels before the commits, settles, marks the domains the committed changes trigger, and evaluates them in the same active region before resuming the inactive processes. Change-Id: Ifef70072f1fd3b703438669d1d0524d76e619a4c --- .../celox-runtime/src/simulation/process.rs | 9 ++- crates/celox-runtime/src/simulation/round.rs | 32 +++++++- .../src/sv/cases/timing.vtest | 20 +++++ .../src/simulation/runtime_core_tests.rs | 17 +++++ ..._trace_sv_active_commit_edges_default.snap | 76 +++++++++++++++++++ ...ce_sv_active_commit_edges_interpreter.snap | 76 +++++++++++++++++++ .../tests/frontends/systemverilog/timing.rs | 1 + 7 files changed, 225 insertions(+), 6 deletions(-) create mode 100644 crates/celox/src/simulation/snapshots/celox__simulation__runtime_core_tests__sv_traces__trace_sv_active_commit_edges_default.snap create mode 100644 crates/celox/src/simulation/snapshots/celox__simulation__runtime_core_tests__sv_traces__trace_sv_active_commit_edges_interpreter.snap diff --git a/crates/celox-runtime/src/simulation/process.rs b/crates/celox-runtime/src/simulation/process.rs index 8fe00cce48d..6ae53e48b4e 100644 --- a/crates/celox-runtime/src/simulation/process.rs +++ b/crates/celox-runtime/src/simulation/process.rs @@ -184,11 +184,12 @@ impl SimulationState { // before the inactive region's processes resume. if self.evaluate_before_inactive(executor, current_time, round)? { // Their blocking results are updates of the active region: - // continuous assignments follow them and the waits they wake - // run before the inactive region (IEEE 1800-2023 4.5). - executor.eval_comb()?; + // the waits they wake and the domains their edges trigger run + // before the inactive region (IEEE 1800-2023 4.5). self.observe_driven(executor.backend()); - if !self.process_state.ready.is_empty() { + if !self.process_state.ready.is_empty() + || !executor.backend().get_triggered_bits().is_empty() + { continue; } } diff --git a/crates/celox-runtime/src/simulation/round.rs b/crates/celox-runtime/src/simulation/round.rs index af1ce6c4676..ec667827171 100644 --- a/crates/celox-runtime/src/simulation/round.rs +++ b/crates/celox-runtime/src/simulation/round.rs @@ -175,7 +175,10 @@ impl SimulationState { /// Evaluate the triggered domains before an inactive region runs. Their /// nonblocking assignments stay in the working state until the NBA - /// region. Returns whether a domain committed its blocking results. + /// region. A domain that commits its blocking results does so now, in + /// the active region: combinational logic follows them and the domains + /// their edges trigger are marked. Returns whether a domain committed + /// its blocking results. pub(super) fn evaluate_before_inactive( &mut self, executor: &mut E, @@ -187,6 +190,10 @@ impl SimulationState { { let marked = executor.backend().get_triggered_bits(); executor.backend_mut().clear_triggered_bits(); + if !self.model.active_commits.is_empty() { + // The levels before any blocking result is committed. + self.event_values(executor.backend(), &mut round.before); + } let mut evaluated = BitSet::new(); let mut committed = false; let mut unsplit = Vec::new(); @@ -213,13 +220,34 @@ impl SimulationState { committed |= self.model.active_commits.contains(info.canonical_id); self.evaluate_deferred(executor, current_time, round, info)?; } + // Edges the committed blocking results give, directly or through + // combinational logic, are occurrences of this active region. + let mut occurred = Vec::new(); + if committed { + let pending = executor.backend().get_triggered_bits(); + executor.eval_comb()?; + // The settle's own trigger marks are replaced by the edges judged + // against the levels before the commits. + executor.backend_mut().clear_triggered_bits(); + self.record_transitions(executor.backend(), round); + let transitions = std::mem::take(&mut round.transitions); + round.begin_scan(self.model.domain_kinds.len()); + self.mark_occurrences(executor.backend_mut(), round, &transitions); + occurred.extend(executor.backend().get_triggered_bits().iter()); + executor.backend_mut().clear_triggered_bits(); + for id in pending.iter() { + executor.backend_mut().mark_triggered_bit(id); + } + round.transitions = transitions; + round.transitions.clear(); + } // The edges are consumed: later rounds compare against the values // they were evaluated at. self.synchronize_event_values(executor.backend()); round.begin_scan(self.model.domain_kinds.len()); round.scheduled_trigger_ids.make_empty(); round.counted_triggered.make_empty(); - for id in unsplit { + for id in unsplit.into_iter().chain(occurred) { // The edge stays approved: the new baseline no longer shows it. executor.backend_mut().mark_triggered_bit(id); round.scheduled_trigger_ids.insert(id); diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index a4a71ae644b..305f45fabc3 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -409,6 +409,26 @@ endmodule"#) (top Top) (run_until 1) (assert_eq observed 1) (assert_eq derived_seen 2) (assert_eq q 9)) +(case blocking_ff_clock_edges_trigger_their_domains_before_inactive_work + (source "blocking_clocks.sv" #" + module Top(output bit [7:0] cnt, cnt_gated, cnt_derived, seen); + bit clk, clk2, en = 1'b1, q = 1'b1; + wire gated = clk2 & en; + wire derived = ~q; + always #5 clk = ~clk; + always @(posedge clk) begin clk2 = ~clk2; q = ~q; end + always_ff @(posedge clk2) cnt <= cnt + 8'd1; + always_ff @(posedge gated) cnt_gated <= cnt_gated + 8'd1; + always_ff @(posedge derived) cnt_derived <= cnt_derived + 8'd1; + initial forever begin @(posedge clk); #0; seen = seen + 8'd1; end + endmodule"#) + (top Top) + (run_until 50) + (assert_eq seen 5) + (assert_eq cnt 3 "a blocking clock edge triggers its domain") + (assert_eq cnt_gated 3 "so does a clock computed from it") + (assert_eq cnt_derived 3 "and a falling one through an inverter")) + (case nonblocking_ff_stores_remain_pending_during_inactive_work (source "nonblocking.sv" #"module Top(output bit [7:0] q, observed, derived_seen); bit clk; wire [7:0] derived=q+1; diff --git a/crates/celox/src/simulation/runtime_core_tests.rs b/crates/celox/src/simulation/runtime_core_tests.rs index 5a49f637753..53ebd726cde 100644 --- a/crates/celox/src/simulation/runtime_core_tests.rs +++ b/crates/celox/src/simulation/runtime_core_tests.rs @@ -2316,6 +2316,23 @@ mod sv_traces { &["clk"], &["q", "observed", "derived_seen"], ), + ( + // A blocking store of a domain committed in the active region + // clocks other domains, directly and through combinational + // logic, before the inactive region. + "sv_active_commit_edges", + "module Top(input logic clk, output logic [7:0] cnt, output logic [7:0] cnt_gated, + output logic [7:0] seen); + logic clk2 = 1'b0, en = 1'b1; + wire gated = clk2 & en; + always @(posedge clk) clk2 = ~clk2; + always_ff @(posedge clk2) cnt <= cnt + 8'd1; + always_ff @(posedge gated) cnt_gated <= cnt_gated + 8'd1; + initial forever begin @(posedge clk); #0; seen = seen + 8'd1; end + endmodule", + &["clk"], + &["cnt", "cnt_gated", "seen"], + ), ( "sv_buffered_clock", "module Top(input logic clk, output logic [31:0] up, output logic [31:0] down); diff --git a/crates/celox/src/simulation/snapshots/celox__simulation__runtime_core_tests__sv_traces__trace_sv_active_commit_edges_default.snap b/crates/celox/src/simulation/snapshots/celox__simulation__runtime_core_tests__sv_traces__trace_sv_active_commit_edges_default.snap new file mode 100644 index 00000000000..175e27df84a --- /dev/null +++ b/crates/celox/src/simulation/snapshots/celox__simulation__runtime_core_tests__sv_traces__trace_sv_active_commit_edges_default.snap @@ -0,0 +1,76 @@ +--- +source: crates/celox/src/simulation/runtime_core_tests.rs +expression: "trace(Simulation::from_sv_sources(sources(), \"Top\").build().unwrap(), &ops,\nobserve)" +--- +modify [("clk", 0)] +run_until 0 + step -> Some(0): host_writes(0) process(0) comb finish_step(0) + time 0 finished false: cnt=0 cnt_gated=0 seen=0 +modify [("clk", 37)] +run_until 2 + step -> Some(0): host_writes(1) process(0) comb stage(e0@0) eval_only(e0) comb stage(e1@0) eval_only(e1) stage(e2@0) eval_only(e2) process(0) comb apply(e0) apply(e1) apply(e2) fire(e0@0) fire(e1@0) fire(e2@0) comb finish_step(0) + time 2 finished false: cnt=1 cnt_gated=1 seen=1 +modify [("clk", 74)] +run_until 4 + step -> Some(2): host_writes(1) comb finish_step(2) + time 4 finished false: cnt=1 cnt_gated=1 seen=1 +modify [("clk", 111)] +run_until 6 + step -> Some(4): host_writes(1) process(0) comb stage(e0@4) eval_only(e0) comb process(0) comb apply(e0) fire(e0@4) comb finish_step(4) + time 6 finished false: cnt=1 cnt_gated=1 seen=2 +modify [("clk", 148)] +run_until 8 + step -> Some(6): host_writes(1) comb finish_step(6) + time 8 finished false: cnt=1 cnt_gated=1 seen=2 +modify [("clk", 185)] +run_until 10 + step -> Some(8): host_writes(1) process(0) comb stage(e0@8) eval_only(e0) comb stage(e1@8) eval_only(e1) stage(e2@8) eval_only(e2) process(0) comb apply(e0) apply(e1) apply(e2) fire(e0@8) fire(e1@8) fire(e2@8) comb finish_step(8) + time 10 finished false: cnt=2 cnt_gated=2 seen=3 +modify [("clk", 222)] +run_until 12 + step -> Some(10): host_writes(1) comb finish_step(10) + time 12 finished false: cnt=2 cnt_gated=2 seen=3 +modify [("clk", 1), ("clk", 0)] +run_until 14 + step -> Some(12): host_writes(2) process(0) comb process(0) comb finish_step(12) + time 14 finished false: cnt=2 cnt_gated=2 seen=4 +schedule clk @15 = 1 +schedule clk @16 = 0 +schedule clk @17 = 1 +schedule clk @17 = 0 +schedule clk @18 = 1 +schedule clk @19 = 0 +run_until 20 + step -> Some(15): host_writes(0) process(0) comb stage(e0@15) eval_only(e0) comb process(0) comb apply(e0) fire(e0@15) comb finish_step(15) + step -> Some(16): host_writes(0) comb finish_step(16) + step -> Some(17): host_writes(0) process(0) comb stage(e0@17) eval_only(e0) comb stage(e1@17) eval_only(e1) stage(e2@17) eval_only(e2) process(0) comb apply(e0) apply(e1) apply(e2) fire(e0@17) fire(e1@17) fire(e2@17) comb finish_step(17) + step -> Some(18): host_writes(0) comb finish_step(18) + step -> Some(19): host_writes(0) comb finish_step(19) + time 20 finished false: cnt=3 cnt_gated=3 seen=6 +clock clk period 4 delay 21 +run_until 40 + step -> Some(21): host_writes(0) process(0) comb stage(e0@21) eval_only(e0) comb process(0) comb apply(e0) fire(e0@21) comb finish_step(21) + step -> Some(23): host_writes(0) comb finish_step(23) + step -> Some(25): host_writes(0) process(0) comb stage(e0@25) eval_only(e0) comb stage(e1@25) eval_only(e1) stage(e2@25) eval_only(e2) process(0) comb apply(e0) apply(e1) apply(e2) fire(e0@25) fire(e1@25) fire(e2@25) comb finish_step(25) + step -> Some(27): host_writes(0) comb finish_step(27) + step -> Some(29): host_writes(0) process(0) comb stage(e0@29) eval_only(e0) comb process(0) comb apply(e0) fire(e0@29) comb finish_step(29) + step -> Some(31): host_writes(0) comb finish_step(31) + step -> Some(33): host_writes(0) process(0) comb stage(e0@33) eval_only(e0) comb stage(e1@33) eval_only(e1) stage(e2@33) eval_only(e2) process(0) comb apply(e0) apply(e1) apply(e2) fire(e0@33) fire(e1@33) fire(e2@33) comb finish_step(33) + step -> Some(35): host_writes(0) comb finish_step(35) + step -> Some(37): host_writes(0) process(0) comb stage(e0@37) eval_only(e0) comb process(0) comb apply(e0) fire(e0@37) comb finish_step(37) + step -> Some(39): host_writes(0) comb finish_step(39) + time 40 finished false: cnt=5 cnt_gated=5 seen=11 +steps 12 + step -> Some(41): host_writes(0) process(0) comb stage(e0@41) eval_only(e0) comb stage(e1@41) eval_only(e1) stage(e2@41) eval_only(e2) process(0) comb apply(e0) apply(e1) apply(e2) fire(e0@41) fire(e1@41) fire(e2@41) comb finish_step(41) + step -> Some(43): host_writes(0) comb finish_step(43) + step -> Some(45): host_writes(0) process(0) comb stage(e0@45) eval_only(e0) comb process(0) comb apply(e0) fire(e0@45) comb finish_step(45) + step -> Some(47): host_writes(0) comb finish_step(47) + step -> Some(49): host_writes(0) process(0) comb stage(e0@49) eval_only(e0) comb stage(e1@49) eval_only(e1) stage(e2@49) eval_only(e2) process(0) comb apply(e0) apply(e1) apply(e2) fire(e0@49) fire(e1@49) fire(e2@49) comb finish_step(49) + step -> Some(51): host_writes(0) comb finish_step(51) + step -> Some(53): host_writes(0) process(0) comb stage(e0@53) eval_only(e0) comb process(0) comb apply(e0) fire(e0@53) comb finish_step(53) + step -> Some(55): host_writes(0) comb finish_step(55) + step -> Some(57): host_writes(0) process(0) comb stage(e0@57) eval_only(e0) comb stage(e1@57) eval_only(e1) stage(e2@57) eval_only(e2) process(0) comb apply(e0) apply(e1) apply(e2) fire(e0@57) fire(e1@57) fire(e2@57) comb finish_step(57) + step -> Some(59): host_writes(0) comb finish_step(59) + step -> Some(61): host_writes(0) process(0) comb stage(e0@61) eval_only(e0) comb process(0) comb apply(e0) fire(e0@61) comb finish_step(61) + step -> Some(63): host_writes(0) comb finish_step(63) + time 63 finished false: cnt=8 cnt_gated=8 seen=17 diff --git a/crates/celox/src/simulation/snapshots/celox__simulation__runtime_core_tests__sv_traces__trace_sv_active_commit_edges_interpreter.snap b/crates/celox/src/simulation/snapshots/celox__simulation__runtime_core_tests__sv_traces__trace_sv_active_commit_edges_interpreter.snap new file mode 100644 index 00000000000..ba0e908c9be --- /dev/null +++ b/crates/celox/src/simulation/snapshots/celox__simulation__runtime_core_tests__sv_traces__trace_sv_active_commit_edges_interpreter.snap @@ -0,0 +1,76 @@ +--- +source: crates/celox/src/simulation/runtime_core_tests.rs +expression: "trace(Simulation::new(Simulator::from_sv_sources(sources(),\n\"Top\").emit_triggers().build_interpreter().unwrap()), &ops, observe)" +--- +modify [("clk", 0)] +run_until 0 + step -> Some(0): host_writes(0) process(0) comb finish_step(0) + time 0 finished false: cnt=0 cnt_gated=0 seen=0 +modify [("clk", 37)] +run_until 2 + step -> Some(0): host_writes(1) process(0) comb stage(e0@0) eval_only(e0) comb stage(e1@0) eval_only(e1) stage(e2@0) eval_only(e2) process(0) comb apply(e0) apply(e1) apply(e2) fire(e0@0) fire(e1@0) fire(e2@0) comb finish_step(0) + time 2 finished false: cnt=1 cnt_gated=1 seen=1 +modify [("clk", 74)] +run_until 4 + step -> Some(2): host_writes(1) comb finish_step(2) + time 4 finished false: cnt=1 cnt_gated=1 seen=1 +modify [("clk", 111)] +run_until 6 + step -> Some(4): host_writes(1) process(0) comb stage(e0@4) eval_only(e0) comb process(0) comb apply(e0) fire(e0@4) comb finish_step(4) + time 6 finished false: cnt=1 cnt_gated=1 seen=2 +modify [("clk", 148)] +run_until 8 + step -> Some(6): host_writes(1) comb finish_step(6) + time 8 finished false: cnt=1 cnt_gated=1 seen=2 +modify [("clk", 185)] +run_until 10 + step -> Some(8): host_writes(1) process(0) comb stage(e0@8) eval_only(e0) comb stage(e1@8) eval_only(e1) stage(e2@8) eval_only(e2) process(0) comb apply(e0) apply(e1) apply(e2) fire(e0@8) fire(e1@8) fire(e2@8) comb finish_step(8) + time 10 finished false: cnt=2 cnt_gated=2 seen=3 +modify [("clk", 222)] +run_until 12 + step -> Some(10): host_writes(1) comb finish_step(10) + time 12 finished false: cnt=2 cnt_gated=2 seen=3 +modify [("clk", 1), ("clk", 0)] +run_until 14 + step -> Some(12): host_writes(2) process(0) comb process(0) comb finish_step(12) + time 14 finished false: cnt=2 cnt_gated=2 seen=4 +schedule clk @15 = 1 +schedule clk @16 = 0 +schedule clk @17 = 1 +schedule clk @17 = 0 +schedule clk @18 = 1 +schedule clk @19 = 0 +run_until 20 + step -> Some(15): host_writes(0) process(0) comb stage(e0@15) eval_only(e0) comb process(0) comb apply(e0) fire(e0@15) comb finish_step(15) + step -> Some(16): host_writes(0) comb finish_step(16) + step -> Some(17): host_writes(0) process(0) comb stage(e0@17) eval_only(e0) comb stage(e1@17) eval_only(e1) stage(e2@17) eval_only(e2) process(0) comb apply(e0) apply(e1) apply(e2) fire(e0@17) fire(e1@17) fire(e2@17) comb finish_step(17) + step -> Some(18): host_writes(0) comb finish_step(18) + step -> Some(19): host_writes(0) comb finish_step(19) + time 20 finished false: cnt=3 cnt_gated=3 seen=6 +clock clk period 4 delay 21 +run_until 40 + step -> Some(21): host_writes(0) process(0) comb stage(e0@21) eval_only(e0) comb process(0) comb apply(e0) fire(e0@21) comb finish_step(21) + step -> Some(23): host_writes(0) comb finish_step(23) + step -> Some(25): host_writes(0) process(0) comb stage(e0@25) eval_only(e0) comb stage(e1@25) eval_only(e1) stage(e2@25) eval_only(e2) process(0) comb apply(e0) apply(e1) apply(e2) fire(e0@25) fire(e1@25) fire(e2@25) comb finish_step(25) + step -> Some(27): host_writes(0) comb finish_step(27) + step -> Some(29): host_writes(0) process(0) comb stage(e0@29) eval_only(e0) comb process(0) comb apply(e0) fire(e0@29) comb finish_step(29) + step -> Some(31): host_writes(0) comb finish_step(31) + step -> Some(33): host_writes(0) process(0) comb stage(e0@33) eval_only(e0) comb stage(e1@33) eval_only(e1) stage(e2@33) eval_only(e2) process(0) comb apply(e0) apply(e1) apply(e2) fire(e0@33) fire(e1@33) fire(e2@33) comb finish_step(33) + step -> Some(35): host_writes(0) comb finish_step(35) + step -> Some(37): host_writes(0) process(0) comb stage(e0@37) eval_only(e0) comb process(0) comb apply(e0) fire(e0@37) comb finish_step(37) + step -> Some(39): host_writes(0) comb finish_step(39) + time 40 finished false: cnt=5 cnt_gated=5 seen=11 +steps 12 + step -> Some(41): host_writes(0) process(0) comb stage(e0@41) eval_only(e0) comb stage(e1@41) eval_only(e1) stage(e2@41) eval_only(e2) process(0) comb apply(e0) apply(e1) apply(e2) fire(e0@41) fire(e1@41) fire(e2@41) comb finish_step(41) + step -> Some(43): host_writes(0) comb finish_step(43) + step -> Some(45): host_writes(0) process(0) comb stage(e0@45) eval_only(e0) comb process(0) comb apply(e0) fire(e0@45) comb finish_step(45) + step -> Some(47): host_writes(0) comb finish_step(47) + step -> Some(49): host_writes(0) process(0) comb stage(e0@49) eval_only(e0) comb stage(e1@49) eval_only(e1) stage(e2@49) eval_only(e2) process(0) comb apply(e0) apply(e1) apply(e2) fire(e0@49) fire(e1@49) fire(e2@49) comb finish_step(49) + step -> Some(51): host_writes(0) comb finish_step(51) + step -> Some(53): host_writes(0) process(0) comb stage(e0@53) eval_only(e0) comb process(0) comb apply(e0) fire(e0@53) comb finish_step(53) + step -> Some(55): host_writes(0) comb finish_step(55) + step -> Some(57): host_writes(0) process(0) comb stage(e0@57) eval_only(e0) comb stage(e1@57) eval_only(e1) stage(e2@57) eval_only(e2) process(0) comb apply(e0) apply(e1) apply(e2) fire(e0@57) fire(e1@57) fire(e2@57) comb finish_step(57) + step -> Some(59): host_writes(0) comb finish_step(59) + step -> Some(61): host_writes(0) process(0) comb stage(e0@61) eval_only(e0) comb process(0) comb apply(e0) fire(e0@61) comb finish_step(61) + step -> Some(63): host_writes(0) comb finish_step(63) + time 63 finished false: cnt=8 cnt_gated=8 seen=17 diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 1cb41dade0a..8832b5aca5b 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -69,6 +69,7 @@ timed_cases! { fn repeated_settles_do_not_advance_design_time = "timing::repeated_settles_do_not_advance_design_time"; fn run_to_finish_has_no_simulated_time_deadline = "timing::run_to_finish_has_no_simulated_time_deadline"; fn blocking_ff_stores_are_visible_before_inactive_work = "timing::blocking_ff_stores_are_visible_before_inactive_work"; + fn blocking_ff_clock_edges_trigger_their_domains_before_inactive_work = "timing::blocking_ff_clock_edges_trigger_their_domains_before_inactive_work"; fn nonblocking_ff_stores_remain_pending_during_inactive_work = "timing::nonblocking_ff_stores_remain_pending_during_inactive_work"; fn mixed_ff_stores_keep_their_active_and_nba_values = "timing::mixed_ff_stores_keep_their_active_and_nba_values"; fn printed_finish_notice_is_design_output = "timing::printed_finish_notice_is_design_output"; From 85a97536ab347525239f3d4125f868ea032efcaa Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 18 Oct 2026 18:40:21 +0900 Subject: [PATCH 5/5] fix(js): return normally when bounded simulations stop Simulation.runUntil(endTime, { maxSteps }) treated the Rust bounded loop's false result as a timeout even when a design executed $stop. Return normally when an allowed step suspends the simulation, so callers can inspect isStopped() and resume it. Normalize fractional, negative and NaN budgets before the native call and the stop check so effective zero-step budgets still time out, including while a previous stop is pending. A resumed time slot can stop again or exhaust its budget before consuming pending host writes. Preserve dirty inputs after these interrupted resumptions so output reads still perform lazy combinational evaluation. Add TypeScript regressions for stop and resumption, normalized budgets, and pending input writes across repeated stops and budget exhaustion. Extend the Rust SystemVerilog $stop regression to verify bounded-loop results with actual stopped processes. Validation: - TypeScript Simulation unit tests (54 passed), package type checks, and Biome. - NAPI Simulation, timing-addon, cascaded-clock-addon, and e2e tests (168 passed). - Rust stop_suspends_the_simulation_until_it_continues regression. - cargo fmt and Clippy for the SystemVerilog integration test. - Reused the successful NAPI build and Rust checks from the prior revision; native sources are unchanged by this review fix. Fixes #1464 Change-Id: I3756bef676de6da4b8e9884f9025a72083dc21ae --- .../systemverilog/system_functions.rs | 20 ++++ packages/celox/src/simulation.test.ts | 105 ++++++++++++++++++ packages/celox/src/simulation.ts | 15 ++- 3 files changed, 136 insertions(+), 4 deletions(-) diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index 9db62d543e1..6ab72c2de2e 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -1337,6 +1337,26 @@ fn stop_suspends_the_simulation_until_it_continues() { assert_eq!(sim.time(), 10); assert_eq!(sim.get(count), 6u8.into()); assert_eq!(sim.get(other), 5u8.into()); + + // The bounded API returns false both at a new stop and when no step is + // allowed to resume it. Bindings distinguish these using the stop state + // and whether the budget allowed a step. + let mut sim = initial_simulation(source); + sim.modify(|io| io.set(rounds, 3u8)).unwrap(); + for expected in [1u8, 2, 4, 5] { + assert!(!sim.run_until_bounded(10, 1).unwrap()); + assert!(sim.is_stopped()); + assert_eq!(sim.time(), 0); + assert_eq!(sim.get(count), expected.into()); + assert!(!sim.run_until_bounded(10, 0).unwrap()); + assert!(sim.is_stopped()); + assert_eq!(sim.get(count), expected.into()); + } + assert!(sim.run_until_bounded(10, 1).unwrap()); + assert!(!sim.is_stopped()); + assert_eq!(sim.time(), 10); + assert_eq!(sim.get(count), 6u8.into()); + assert_eq!(sim.get(other), 5u8.into()); } /// The time step a `$stop` suspends continues where it stopped: an edge a diff --git a/packages/celox/src/simulation.test.ts b/packages/celox/src/simulation.test.ts index 9e0d355822b..e7b0072e175 100644 --- a/packages/celox/src/simulation.test.ts +++ b/packages/celox/src/simulation.test.ts @@ -389,6 +389,111 @@ describe("Simulation", () => { ); }); + test("runUntil with maxSteps: returns normally at $stop and can resume", () => { + const mock = createMockNative(); + let stopped = false; + mock.handle.isStopped = vi.fn(() => stopped); + vi.mocked(mock.handle.runUntilBounded!).mockImplementationOnce(() => { + mock.handle.step(); + stopped = true; + return false; + }); + const sim = Simulation.create(TopModule, { + __nativeCreate: mock.create, + }); + sim.dut.d = 42n; + + expect(() => sim.runUntil(25, { maxSteps: 1 })).not.toThrow(); + expect(sim.time()).toBe(5); + expect(sim.isStopped()).toBe(true); + expect(sim.dut.q).toBe(42n); + expect(mock.handle.evalComb).not.toHaveBeenCalled(); + + // No step was allowed to resume the stopped process, so this is + // still a budget exhaustion rather than a newly encountered stop. + expect(() => sim.runUntil(25, { maxSteps: 0 })).toThrow( + SimulationTimeoutError, + ); + expect(sim.isStopped()).toBe(true); + expect(sim.time()).toBe(5); + + vi.mocked(mock.handle.step).mockImplementationOnce(() => { + stopped = false; + return 5; + }); + sim.runUntil(25, { maxSteps: 5 }); + expect(sim.isStopped()).toBe(false); + expect(sim.time()).toBe(25); + }); + + test.each([0.5, -0.5, Number.NaN])( + "runUntil normalizes an effective zero budget while stopped (%s)", + (maxSteps) => { + const mock = createMockNative(); + mock.handle.isStopped = vi.fn(() => true); + vi.mocked(mock.handle.runUntilBounded!).mockReturnValue(false); + const sim = Simulation.create(TopModule, { + __nativeCreate: mock.create, + }); + sim.dut.d = 42n; + + expect(() => sim.runUntil(25, { maxSteps })).toThrow( + SimulationTimeoutError, + ); + expect(mock.handle.runUntilBounded).toHaveBeenCalledWith(25, 0); + expect(sim.isStopped()).toBe(true); + expect(sim.time()).toBe(0); + expect(sim.dut.q).toBe(42n); + expect(mock.handle.evalComb).toHaveBeenCalledOnce(); + }, + ); + + test("runUntil truncates a fractional positive budget before passing it to native code", () => { + const mock = createMockNative(); + const sim = Simulation.create(TopModule, { + __nativeCreate: mock.create, + }); + + sim.runUntil(25, { maxSteps: 5.9 }); + expect(mock.handle.runUntilBounded).toHaveBeenCalledWith(25, 5); + }); + + test.each([true, false])( + "runUntil preserves input writes when resuming a stopped slot (stops again: %s)", + (stopsAgain) => { + const mock = createMockNative(); + let stopped = true; + mock.handle.isStopped = vi.fn(() => stopped); + // Resuming the suspended slot can return before pending host + // writes are settled, both at another stop and at the step limit. + vi.mocked(mock.handle.runUntilBounded!).mockImplementationOnce(() => { + stopped = stopsAgain; + return false; + }); + const sim = Simulation.create(TopModule, { + __nativeCreate: mock.create, + }); + sim.dut.d = 42n; + + if (stopsAgain) { + expect(() => sim.runUntil(25, { maxSteps: 1 })).not.toThrow(); + } else { + expect(() => sim.runUntil(25, { maxSteps: 1 })).toThrow( + SimulationTimeoutError, + ); + } + expect(sim.time()).toBe(0); + expect(sim.isStopped()).toBe(stopsAgain); + expect(mock.handle.evalComb).not.toHaveBeenCalled(); + expect(sim.dut.q).toBe(42n); + expect(mock.handle.evalComb).toHaveBeenCalledOnce(); + // Reading twice must not evaluate twice or notify the scheduler again. + expect(sim.dut.q).toBe(42n); + expect(mock.handle.evalComb).toHaveBeenCalledOnce(); + expect(mock.handle.noteHostWrites).toHaveBeenCalledOnce(); + }, + ); + test("runUntil with maxSteps: timeout error has correct properties", () => { const mock = createMockNative(); const sim = Simulation.create(TopModule, { diff --git a/packages/celox/src/simulation.ts b/packages/celox/src/simulation.ts index 56fd3e998f1..49fbeb41a32 100644 --- a/packages/celox/src/simulation.ts +++ b/packages/celox/src/simulation.ts @@ -439,7 +439,8 @@ export class Simulation

> { * * When `maxSteps` is provided, the Rust run loop takes at most that many * steps and a `SimulationTimeoutError` is thrown if the budget is - * exhausted before reaching `endTime`. + * exhausted before reaching `endTime`. A design that executes `$stop` + * returns normally; use `isStopped()` to detect the suspension. */ runUntil(endTime: number, opts?: { maxSteps?: number }): void { this.ensureAlive(); @@ -451,7 +452,8 @@ export class Simulation

> { this._state.dirty = false; return; } - const max = opts.maxSteps; + // Normalize zero-step budgets before interpreting the native result. + const max = Math.max(0, Math.trunc(opts.maxSteps) || 0); if (!this._handle.runUntilBounded) { throw new Error("This simulation does not support bounded runs"); } @@ -463,9 +465,14 @@ export class Simulation

> { const next = this._handle.nextEventTime(); if (next == null || next > endTime) return; } + const wasStopped = this.isStopped(); if (!this._handle.runUntilBounded(endTime, max)) { - // A step took the pending inputs unless none was allowed. - if (max > 0) this._state.dirty = false; + if (max > 0) { + // A resumed slot can stop or exhaust the budget before pending + // host writes are consumed. Keep them eligible for lazy evaluation. + if (!wasStopped) this._state.dirty = false; + if (this.isStopped()) return; + } throw new SimulationTimeoutError( `runUntil: exceeded ${max} steps at time ${this._handle.time()} (target ${endTime})`, this._handle.time(),