From b78b0f51986ffbd6fa8ce5012af45dde3a136251 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 18 Oct 2026 07:34:41 +0900 Subject: [PATCH] feat(sv): support generate-block imports of types and subroutines that differ from the module's Closes #1206. A generate block that imports a type or subroutine under a name the module binds to another declaration was rejected, because types, constant functions and subroutine metadata were looked up module-wide by the plain name. This gives the generate scope its own view of those tables instead. - `Scope` and `Item` record the names the block's imports bind (`imports`, filled by `bind_import`). `BlockImports` keeps the ones an inner declaration has not hidden again, and derives from them: - the type aliases the block sees: a name the blocks declare or import hides the module's type of that name, and an imported `t` denotes `p::t`'s type; - the installed constant-function table, with `f` aliased to `p::f`, or hidden when the block's `f` is no constant function (a DPI-C import). Calls in the bodies of the functions it hides are renamed to the outer binding, so a module function still calls the `f` it was declared with. - The elaborator evaluates a block's declarations, conditions and nested blocks with that view, and resolves a generate condition's call to the qualified declaration ahead of a module function of the same name. - `Item::dimensions` carries the block's type aliases (casts, `$bits(t)`), next to the function, formal-name and shape aliases it already had. The signal, process, instance, function and subroutine collectors use the item's type aliases and install its constant functions. - The two "imports as another declaration than its module" rejections are removed. - `resolve_imports` also records a block import of the declaration the module sees when a block around it imports another declaration or declares the name, so the inner block no longer inherits the outer binding. This was already wrong for values since #1184. - As a result, a generate-local declaration such as `localparam T` now also hides a module typedef `T`, so `T n;` under it is rejected instead of taking the outer type (IEEE 1800-2023 23.9). Validation: - `cargo fmt --all -- --check` - `cargo clippy -p celox-sv-analyzer -p celox-frontend-sv -p celox --all-targets --features celox/systemverilog,celox/sv-dpi --no-deps` - `cargo test -p celox-sv-analyzer -p celox-frontend-sv` - `cargo test -p celox --features systemverilog,sv-dpi` (11465 passed, 0 failed) New regressions: `generate_block_imports_bind_their_own_subroutines`, `generate_block_imports_bind_their_own_types`, `nested_generate_block_imports_restore_the_module_binding` and `generate_block_declarations_hide_outer_types` in `sv_packages.rs`, and `generate_block_imports_bind_their_own_dpi_formals` and `generate_block_dpi_imports_hide_outer_constant_functions` in `sv_dpi.rs`. Every case also uses the name outside the block, so the block-local binding is taken rather than the module-wide alias for names only blocks use. Unrelated defects found while testing are filed as #1435, #1436, #1437, #1438 and #1461. Change-Id: Ic706ae8c0a61ae10d0a6e8afa53fc99b83d759d2 --- .../celox-sv-analyzer/src/ast/comb_process.rs | 1 + .../src/ast/const_functions.rs | 4 + .../celox-sv-analyzer/src/ast/declarations.rs | 3 +- .../celox-sv-analyzer/src/ast/ff_process.rs | 1 + crates/celox-sv-analyzer/src/ast/functions.rs | 6 +- crates/celox-sv-analyzer/src/ast/generate.rs | 161 ++++++- crates/celox-sv-analyzer/src/ast/imports.rs | 48 +- crates/celox-sv-analyzer/src/ast/instances.rs | 1 + .../celox-sv-analyzer/src/ast/procedural.rs | 10 +- .../celox-sv-analyzer/src/ast/validation.rs | 1 + crates/celox/tests/sv_dpi.rs | 57 +++ crates/celox/tests/sv_packages.rs | 413 +++++++++++++++++- 12 files changed, 648 insertions(+), 58 deletions(-) diff --git a/crates/celox-sv-analyzer/src/ast/comb_process.rs b/crates/celox-sv-analyzer/src/ast/comb_process.rs index 029cb3bd6a4..dd47a03bb69 100644 --- a/crates/celox-sv-analyzer/src/ast/comb_process.rs +++ b/crates/celox-sv-analyzer/src/ast/comb_process.rs @@ -38,6 +38,7 @@ pub(super) fn comb_processes_from_module_node( if !relevant { continue; } + let _constant_functions = item.enter(); let start = processes.len(); let (dimensions, literals) = views.get(item); comb_processes_from_module_or_generate_item( diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index 71898334e11..d418d39f8ba 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -170,6 +170,10 @@ impl ConstantFunctions { .retain(|name, _| keep(name)); } + pub(super) fn contains(&self, name: &str) -> bool { + self.functions.contains_key(name) || self.errors.by_name.contains_key(name) + } + /// Make the function `target` callable as `name` too. pub(super) fn alias(&mut self, name: &str, target: &str) { if let Some(function) = self.functions.get(target).cloned() { diff --git a/crates/celox-sv-analyzer/src/ast/declarations.rs b/crates/celox-sv-analyzer/src/ast/declarations.rs index bacb218b1c7..3207f979d8f 100644 --- a/crates/celox-sv-analyzer/src/ast/declarations.rs +++ b/crates/celox-sv-analyzer/src/ast/declarations.rs @@ -430,11 +430,12 @@ pub(super) fn signals_from_module_node( } ScopeItem::Package(_) => continue, }; + let _constant_functions = item.enter(); let start = signals.len(); signals_from_module_or_generate_item( node, syntax_tree, - type_aliases, + &item.type_aliases(type_aliases), &item.env, None, &mut signals, diff --git a/crates/celox-sv-analyzer/src/ast/ff_process.rs b/crates/celox-sv-analyzer/src/ast/ff_process.rs index 5c2fec12880..bfda9f3e1be 100644 --- a/crates/celox-sv-analyzer/src/ast/ff_process.rs +++ b/crates/celox-sv-analyzer/src/ast/ff_process.rs @@ -28,6 +28,7 @@ pub(super) fn ff_processes_from_module_node( ) { continue; } + let _constant_functions = item.enter(); let start = processes.len(); let (dimensions, literals) = views.get(item); ff_processes_from_module_or_generate_item( diff --git a/crates/celox-sv-analyzer/src/ast/functions.rs b/crates/celox-sv-analyzer/src/ast/functions.rs index aa8abe5b5b6..8911eb6a048 100644 --- a/crates/celox-sv-analyzer/src/ast/functions.rs +++ b/crates/celox-sv-analyzer/src/ast/functions.rs @@ -9,14 +9,16 @@ pub(super) fn functions_from_module_node( packed_dimensions: &PackedDimensions, ) -> Result, AnalyzerError> { let mut functions = HashMap::default(); - let type_aliases = + let module_type_aliases = type_aliases_from_module_node_with_env(node.clone(), syntax_tree, const_env)?; - let active = generate::items(node.clone(), syntax_tree, const_env, &type_aliases)?; + let active = generate::items(node.clone(), syntax_tree, const_env, &module_type_aliases)?; let mut views = generate::ScopeViews::new(packed_dimensions); for (item, child) in active .iter() .flat_map(|item| item.node.node().into_iter().map(move |child| (item, child))) { + let _constant_functions = item.enter(); + let type_aliases = item.type_aliases(&module_type_aliases); 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 1f451d23239..14e23e21a24 100644 --- a/crates/celox-sv-analyzer/src/ast/generate.rs +++ b/crates/celox-sv-analyzer/src/ast/generate.rs @@ -53,11 +53,111 @@ pub(super) struct Item<'a> { pub literals: SharedMap, parameter_dimensions: Arc, names: SharedMap, + imports: SharedMap, shadowed: Arc>, scope: String, } +/// The names the imports of the enclosing generate blocks bind to another +/// declaration than the module does (see `imports::resolve_imports`), unless +/// a declaration of an inner block hides them again. The module-wide tables +/// hold those declarations under their qualified names. +#[derive(Clone, Copy)] +struct BlockImports<'s> { + names: &'s HashMap, + imports: &'s HashMap, + /// The names the blocks declare or import. + shadowed: &'s HashSet, +} + +impl<'s> BlockImports<'s> { + fn bindings(self) -> impl Iterator { + self.imports + .iter() + .filter(move |(name, target)| self.names.get(*name) == Some(*target)) + } + + /// The type aliases visible here: a name the blocks declare or import + /// hides the module's type of that name, and an imported name denotes + /// the type of its declaration. + fn type_aliases<'m>( + self, + aliases: &'m HashMap, + ) -> Cow<'m, HashMap> { + let mut visible = Cow::Borrowed(aliases); + let hidden: Vec<&String> = if aliases.len() <= self.shadowed.len() { + aliases + .keys() + .filter(|name| self.shadowed.contains(*name)) + .collect() + } else { + self.shadowed + .iter() + .filter(|name| aliases.contains_key(*name)) + .collect() + }; + for name in hidden { + visible.to_mut().remove(name); + } + for (name, target) in self.bindings() { + if let Some(r#type) = aliases.get(target) { + visible.to_mut().insert(name.clone(), r#type.clone()); + } + } + visible + } + + /// Make each imported name call the constant function of its + /// declaration, until the guard is dropped; a name that imports no + /// constant function calls none. Calls in the bodies of the functions it + /// hides keep their definition-site meaning. + fn install_constant_functions(self) -> Option { + let installed = const_functions::installed(); + let rebound: Vec<_> = self + .bindings() + .filter(|(name, target)| installed.contains(name) || installed.contains(target)) + .collect(); + if rebound.is_empty() { + return None; + } + let hidden: HashMap = rebound + .iter() + .filter(|(name, _)| installed.contains(name)) + .map(|(name, _)| ((*name).clone(), format!("{OUTER_BINDING}{name}"))) + .collect(); + let rename = scope::Renamer { names: &hidden }; + let mut visible = + installed.renamed(&mut |name| rename.name(name), &mut |stmt| rename.stmt(stmt)); + for (name, target) in rebound { + visible.alias(name, target); + } + Some(const_functions::install(visible)) + } +} + impl Item<'_> { + fn block_imports(&self) -> BlockImports<'_> { + BlockImports { + names: &self.names, + imports: &self.imports, + shadowed: &self.shadowed, + } + } + + /// The type aliases this item sees, given the module's. + pub fn type_aliases<'m>( + &self, + aliases: &'m HashMap, + ) -> Cow<'m, HashMap> { + self.block_imports().type_aliases(aliases) + } + + /// Make the constant functions this item sees the installed ones, until + /// the guard is dropped. + pub fn enter(&self) -> Option { + self.block_imports().install_constant_functions() + } + pub fn common(&self) -> Option<&sv_parser::ModuleCommonItem> { match self.node { ScopeItem::Module(sv_parser::ModuleOrGenerateItem::ModuleItem(item)) => { @@ -140,6 +240,9 @@ impl Item<'_> { self.function_aliases(dimensions.function_return_types.clone()); } } + if let Cow::Owned(aliases) = self.type_aliases(&dimensions.type_aliases) { + local.type_aliases = aliases; + } let mut signedness = dimensions.expression_signedness.clone(); for name in self.shadowed.iter() { let protected = format!("{OUTER_BINDING}{name}"); @@ -340,12 +443,25 @@ struct Scope { parameters: Vec, parameter_dimensions: Arc, names: SharedMap, + imports: SharedMap, shadowed: Arc>, } +impl Scope { + fn block_imports(&self) -> BlockImports<'_> { + BlockImports { + names: &self.names, + imports: &self.imports, + shadowed: &self.shadowed, + } + } +} + struct Elaborator<'a, 'b> { tree: &'a SyntaxTree, - aliases: &'b HashMap, + module_aliases: &'b HashMap, + /// The type aliases of the scope being elaborated. + aliases: Cow<'b, HashMap>, remaining: usize, functions: HashMap, items: Vec>, @@ -397,7 +513,8 @@ fn items_with_literal_use<'a>( ) -> Result>, AnalyzerError> { let mut elaborator = Elaborator { tree, - aliases, + module_aliases: aliases, + aliases: Cow::Borrowed(aliases), remaining: MAX_GENERATE_LOOP_EXPANSION, functions: HashMap::default(), items: Vec::new(), @@ -541,7 +658,7 @@ impl<'a> Elaborator<'a, '_> { RefNode::ConstantExpression(expr), self.tree, &scope.env, - self.aliases, + &self.aliases, )? else { return Ok(None); @@ -565,6 +682,16 @@ impl<'a> Elaborator<'a, '_> { for arg in args { self.expand_constant_calls(arg, scope)?; } + // A block import binds the call to the qualified declaration, + // which the installed constant functions evaluate. + if let Callee::Subroutine(name) = callee + && let Some(target) = scope + .block_imports() + .bindings() + .find_map(|(imported, target)| (imported == name).then_some(target)) + { + *name = target.clone(); + } if let Callee::Subroutine(name) = callee && self.functions.contains_key(name) { @@ -908,6 +1035,7 @@ impl<'a> Elaborator<'a, '_> { literals: scope.literals.clone(), parameter_dimensions: scope.parameter_dimensions.clone(), names: scope.names.clone(), + imports: scope.imports.clone(), shadowed: scope.shadowed.clone(), scope: scope.path.clone(), }); @@ -1140,7 +1268,7 @@ impl<'a> Elaborator<'a, '_> { signals_from_module_or_generate_item( item, self.tree, - self.aliases, + &self.aliases, &scope.env, Some(&name), &mut signals, @@ -1200,7 +1328,7 @@ impl<'a> Elaborator<'a, '_> { &mut scope.parameters, true, &base, - self.aliases, + &self.aliases, &HashMap::default(), &mut environment, )?; @@ -1249,7 +1377,7 @@ impl<'a> Elaborator<'a, '_> { &mut scope.parameters, true, &scope.env, - self.aliases, + &self.aliases, &HashMap::default(), )?; let parameter = scope @@ -1327,6 +1455,22 @@ impl<'a> Elaborator<'a, '_> { bind_import(&mut scope, name, target); } } + // The declarations and nested blocks are elaborated with the types and + // constant functions those imports bind. + let _constant_functions = scope.block_imports().install_constant_functions(); + let aliases = scope.block_imports().type_aliases(self.module_aliases); + let outer = std::mem::replace(&mut self.aliases, aliases); + let elaborated = self.block_contents(children, scope, index); + self.aliases = outer; + elaborated + } + + fn block_contents( + &mut self, + children: Vec<&'a sv_parser::GenerateItem>, + mut scope: Scope, + index: Option<(&str, i128)>, + ) -> Result<(), AnalyzerError> { // Bind all declarations before lowering expressions, including forward references. let mut declared = HashSet::default(); if let Some((genvar, value)) = index { @@ -1352,7 +1496,7 @@ impl<'a> Elaborator<'a, '_> { signals_from_module_or_generate_item( item, self.tree, - self.aliases, + &self.aliases, &scope.env, None, &mut signals, @@ -1404,7 +1548,7 @@ impl<'a> Elaborator<'a, '_> { signals_from_module_or_generate_item( item, self.tree, - self.aliases, + &self.aliases, &scope.env, None, &mut signals, @@ -1450,6 +1594,7 @@ fn bind_import(scope: &mut Scope, name: &str, target: &str) { let imported = scope::imported(); Arc::make_mut(&mut scope.shadowed).insert(name.to_string()); scope.names.insert(name.to_string(), target.to_string()); + scope.imports.insert(name.to_string(), target.to_string()); // The constant value and type markers of the item, under the name. let names = |key: &str| -> Option { if key == target { diff --git a/crates/celox-sv-analyzer/src/ast/imports.rs b/crates/celox-sv-analyzer/src/ast/imports.rs index ce221725316..57b8a8a69ae 100644 --- a/crates/celox-sv-analyzer/src/ast/imports.rs +++ b/crates/celox-sv-analyzer/src/ast/imports.rs @@ -1271,9 +1271,9 @@ pub(super) fn resolve_imports( } // A name the generate blocks import is a name of the whole module when // nothing else gives it a meaning; otherwise each block that imports - // another declaration names it there. + // another declaration than the one visible around it names it there. let mut generate_imports: HashMap> = HashMap::default(); - for (name, uses) in scoped { + for (name, mut uses) in scoped { let outside = bindings .iter() .find(|binding| binding.name == name) @@ -1296,34 +1296,30 @@ pub(super) fn resolve_imports( }); continue; } - for (block, target) in uses { - if outside.as_ref() == Some(&target) { + uses.sort_unstable(); + uses.dedup(); + // A block around `block` that imports another declaration, or + // declares the name, hides the module's binding there. + let encloses = + |scope: &GenerateScope, block: usize| scope.start < block && scope.contains(block); + let hidden = |block: usize, target: &String| { + uses.iter().any(|(outer, other)| { + other != target + && all_scopes + .iter() + .any(|scope| scope.start == *outer && encloses(scope, block)) + }) || all_scopes + .iter() + .any(|scope| scope.declared.contains(&name) && encloses(scope, block)) + }; + for (block, target) in &uses { + if outside.as_ref() == Some(target) && !hidden(*block, target) { continue; } - // Types, and the formal names and shapes of subroutines, are - // looked up module-wide. - if symbols.type_aliases.contains_key(&target) { - return Err(AnalyzerError::Unsupported(format!( - "type `{name}` that a generate block imports as another declaration than \ - its module" - ))); - } - if symbols.subroutine_params.contains_key(&target) - || symbols.functions.contains_key(&target) - || symbols - .dpi_imports - .iter() - .any(|import| import.name() == target.as_str()) - { - return Err(AnalyzerError::Unsupported(format!( - "subroutine `{name}` that a generate block imports as another declaration \ - than its module" - ))); - } generate_imports - .entry(block) + .entry(*block) .or_default() - .insert(name.clone(), target); + .insert(name.clone(), target.clone()); } } symbols.generate_imports = generate_imports; diff --git a/crates/celox-sv-analyzer/src/ast/instances.rs b/crates/celox-sv-analyzer/src/ast/instances.rs index 143c9a56b82..aa2d08409df 100644 --- a/crates/celox-sv-analyzer/src/ast/instances.rs +++ b/crates/celox-sv-analyzer/src/ast/instances.rs @@ -20,6 +20,7 @@ pub(super) fn instances_from_module_node( if !matches!(node, sv_parser::ModuleOrGenerateItem::Module(_)) { continue; } + let _constant_functions = item.enter(); let start = instances.len(); let dimensions = views.dimensions(item); instances_from_module_or_generate_item( diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 5961e9ffe82..c51fd75dc29 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -1673,12 +1673,13 @@ pub(super) fn subroutine_argument_names( let Some(syntax) = syntax else { continue; }; + let _constant_functions = item.enter(); let params = subroutine_param_declarations( syntax.ports, syntax.items, tree, &item.env, - type_aliases, + &item.type_aliases(type_aliases), )?; let qualified = item.name(&syntax.name); let param_shapes: Vec = params @@ -1754,9 +1755,9 @@ pub(super) fn subroutines_with_symbolic_parameters( mut rejected: Option<&mut HashMap>, symbolic_parameters: &HashSet, ) -> Result, AnalyzerError> { - let type_aliases = packed_dimensions.type_aliases.clone(); + let module_type_aliases = &packed_dimensions.type_aliases; let mut subroutines = Vec::new(); - let active = generate::subroutine_items(node, tree, const_env, &type_aliases)?; + 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 { if item.is_parameter_declaration() { @@ -1796,6 +1797,8 @@ pub(super) fn subroutines_with_symbolic_parameters( ) }; + let _constant_functions = item.enter(); + let type_aliases = item.type_aliases(module_type_aliases); let name = syntax.name.clone(); let lowered = (|| -> Result { let params = subroutine_param_declarations( @@ -2000,6 +2003,7 @@ pub(super) fn initial_processes_from_module_node( if item.is_parameter_declaration() { continue; } + let _constant_functions = item.enter(); let mut assignments = Vec::new(); match item.node.declaration() { Some(sv_parser::PackageOrGenerateItemDeclaration::DataDeclaration(data)) => { diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index 7111b507008..10bdcdf8c7e 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -789,6 +789,7 @@ fn reject_silently_ignored_constructs_with_dimensions( let active = generate::items(node, syntax_tree, const_env, type_aliases)?; let mut views = generate::ScopeViews::new(indexed_dimensions); for item in &active { + let _constant_functions = item.enter(); let dimensions = views.dimensions(item); reject_silently_ignored_constructs_with_dimensions( item.node.node(), diff --git a/crates/celox/tests/sv_dpi.rs b/crates/celox/tests/sv_dpi.rs index ee6af3f67ef..f8c5bb8baf4 100644 --- a/crates/celox/tests/sv_dpi.rs +++ b/crates/celox/tests/sv_dpi.rs @@ -178,6 +178,35 @@ dpi_backends! { } } + // A generate block can import another declaration than its module + // (#1206): named arguments bind to the formals of the block's import. + fn generate_block_imports_bind_their_own_dpi_formals(sim) { + @build unsafe { + builder(r#" + package p; + import "DPI-C" digits = function int f(input int first, input int second); + endpackage + package q; + import "DPI-C" digits = function int f(input int second, input int first); + endpackage + module Top(input logic clk, input int a, b, output int block_result, module_result); + import q::*; + if (1) begin : g + import p::*; + always_ff @(posedge clk) block_result <= f(.first(a), .second(b)); + end + always_ff @(posedge clk) module_result <= f(.first(a), .second(b)); + endmodule + "#).dpi_function("digits", dpi_digits as *const ()) + }; + let clk = sim.event("clk"); + let (a, b) = (sim.signal("a"), sim.signal("b")); + sim.modify(|io| { io.set(a, 3u32); io.set(b, 4u32); }).unwrap(); + sim.tick(clk).unwrap(); + assert_eq!(sim.get(sim.signal("block_result")), BigUint::from(34u32)); + assert_eq!(sim.get(sim.signal("module_result")), BigUint::from(43u32)); + } + fn int_function_in_nonblocking_assignment(sim) { @build unsafe { builder(r#" @@ -580,6 +609,34 @@ fn imports_of_one_c_name_must_share_a_prototype() { ); } +/// A generate block that imports a DPI-C function hides a constant function of +/// the same name from the module, so a constant expression of the block +/// cannot call either (#1206). +#[test] +fn generate_block_dpi_imports_hide_outer_constant_functions() { + for outer in [ + "function automatic int f(int a); return 99; endfunction", + "import q::*;", + ] { + let source = format!( + r#"package p; import "DPI-C" function int f(input int a); endpackage + package q; function automatic int f(int a); return 99; endfunction endpackage + module Top(output int y); + {outer} + int a; + if (1) begin : g + import p::*; + localparam int Y = f(1); + assign a = Y; + end + assign y = a + f(0); + endmodule"# + ); + let error = build_error(&source); + assert!(error.contains("user constant function call"), "{error}"); + } +} + fn build_error(source: &str) -> String { match Simulator::from_sv_sources(vec![(source, Path::new("dpi.sv"))], "Top").build_cranelift() { Ok(_) => panic!("design unexpectedly compiled:\n{source}"), diff --git a/crates/celox/tests/sv_packages.rs b/crates/celox/tests/sv_packages.rs index 967d52e0574..4a0093a21ba 100644 --- a/crates/celox/tests/sv_packages.rs +++ b/crates/celox/tests/sv_packages.rs @@ -983,24 +983,6 @@ fn generate_block_imports_are_scoped_to_their_block() { ), 59 ); - // A subroutine the block imports as another one than its module is not - // supported: calls look up formal names and shapes module-wide. - let detail = Simulator::from_sv_sources( - vec![( - "package p; function automatic int f(int a); return a + 1; endfunction endpackage - package q; function automatic int f(int b); return b + 2; endfunction endpackage - module Top(output logic [7:0] y); import q::*; logic [7:0] a; - if (1) begin : g import p::*; assign a = f(4); end - assign y = a + f(0); - endmodule", - std::path::Path::new("packages.sv"), - )], - "Top", - ) - .build() - .expect_err("a block-local subroutine binding is unsupported") - .to_string(); - assert!(detail.contains("subroutine `f`"), "{detail}"); // A loop's genvar hides a wildcard import of its body. assert_eq!( output( @@ -1204,3 +1186,398 @@ fn generate_scopes_declare_loop_body_names_and_keep_inner_imports() { 3 ); } + +/// A generate block can import a type or subroutine that is another +/// declaration than the one its module sees under that name (#1206). +#[test] +fn generate_block_imports_bind_their_own_subroutines() { + // `f` takes its formals in another order in each package. + let functions = "package p; function automatic int f(int a, int b = 0); return a * 10 + b; endfunction + endpackage + package q; function automatic int f(int b, int a = 0); return b * 3 + a; endfunction + endpackage"; + let cases = [ + // Positional and named arguments, against the block's formals. + ( + "import q::*; logic [7:0] a; + if (1) begin : g import p::*; assign a = f(4); end + assign y = a + f(1);", + 43, + ), + ( + "import q::*; logic [7:0] a; + if (1) begin : g import p::*; assign a = f(.b(2), .a(1)); end + assign y = a + f(.a(1), .b(2));", + 19, + ), + ( + "import q::*; logic [7:0] a; + if (1) begin : g import p::*; always_comb a = f(.a(2)); end + assign y = a + f(0);", + 20, + ), + // Constant calls in declarations, selects, loop bounds and generate + // conditions of the block, and in the blocks inside it. + ( + "import q::*; logic [7:0] a; + if (1) begin : g import p::*; localparam int Y = f(.b(2), .a(1)); assign a = Y; end + assign y = a + f(1);", + 15, + ), + ( + "import q::*; logic [7:0] a; + if (1) begin : g import p::*; logic [f(1)-1:0] v; assign a = $bits(v); end + assign y = a + f(0);", + 10, + ), + ( + "import q::*; logic [7:0] a; + if (1) begin : g import p::*; int n = f(1); assign a = n; end + assign y = a + f(0);", + 10, + ), + ( + "import q::*; logic [15:0] w; logic [7:0] a; assign w = 16'h0780; + if (1) begin : g import p::*; assign a = w[f(1) - 3 +: 4]; end + assign y = a + f(0);", + 15, + ), + ( + "import q::*; logic [7:0] a; + if (1) begin : g import p::*; + always_comb begin a = 0; for (int i = 0; i < f(1); i++) a = a + 1; end + end + assign y = a + f(0);", + 10, + ), + ( + "import q::*; logic [7:0] a; + if (1) begin : g import p::*; + function automatic int k(logic [f(1)-1:0] v); return $bits(v); endfunction + assign a = k(0); + end + assign y = a + f(0);", + 10, + ), + ( + "import q::*; logic [7:0] a; + if (1) begin : g import p::*; + if (f(1) == 10) begin : h assign a = 1; end else begin : h assign a = 2; end + end + assign y = a + f(0);", + 1, + ), + ( + "import q::*; logic [7:0] a; + if (1) begin : g import p::*; + if (1) begin : h localparam int Y = f(1); assign a = Y + f(2); end + end + assign y = a + f(0);", + 30, + ), + ( + "import q::*; logic [7:0] a [2]; + for (genvar i = 0; i < 2; i++) begin : g import p::*; assign a[i] = f(i); end + assign y = a[0] + a[1] + f(0);", + 10, + ), + // The block's import comes before a function of the module. + ( + "function automatic int f(int a); return 99; endfunction logic [7:0] a; + if (1) begin : g import p::*; localparam int Y = f(1); assign a = Y; end + assign y = a + f(0);", + 109, + ), + ( + "function automatic int f(int a); return 99; endfunction logic [7:0] a; + if (1) begin : g import p::*; + if (f(1) == 10) begin : h assign a = 1; end else begin : h assign a = 2; end + end + assign y = a + f(0);", + 100, + ), + // A function of the module still calls the declaration it sees. + ( + "import q::*; function automatic int k(int v); return f(v); endfunction logic [7:0] a; + if (1) begin : g import p::*; localparam int Y = k(1); assign a = Y + k(2); end + assign y = a;", + 9, + ), + ( + "function automatic int f(int a); return 99; endfunction + function automatic int k(int v); return f(v); endfunction logic [7:0] a; + if (1) begin : g import p::*; localparam int Y = k(1); assign a = Y + f(1); end + assign y = a;", + 109, + ), + ]; + for (body, expected) in cases { + assert_eq!( + output(&format!( + "{functions} + module Top(output logic [7:0] y); {body} endmodule" + )), + expected, + "{body}" + ); + } + // Assignment-pattern arguments take the shape of the block's formal. + assert_eq!( + output( + "package p; function automatic int f(int v[2]); return v[0] * 10 + v[1]; endfunction + endpackage + package q; function automatic int f(int v[3]); return v[0] + v[1] + v[2]; endfunction + endpackage + module Top(output logic [7:0] y); import q::*; logic [7:0] a; + if (1) begin : g import p::*; assign a = f('{1, 2}); end + assign y = a + f('{1, 1, 1}); + endmodule" + ), + 15 + ); + assert_eq!( + output( + "package p; task automatic t(output int o, input int a); o = a + 1; endtask endpackage + package q; task automatic t(input int a, output int o); o = a + 2; endtask endpackage + module Top(output logic [7:0] y); import q::*; int a, b; + if (1) begin : g import p::*; always_comb t(a, 4); end + always_comb t(4, b); + assign y = a * 10 + b; + endmodule" + ), + 56 + ); +} + +/// A generate block can import a type that is another declaration than the +/// one its module sees under that name (#1206). +#[test] +fn generate_block_imports_bind_their_own_types() { + let types = "package p; typedef logic [3:0] t; endpackage + package q; typedef logic [7:0] t; endpackage"; + // The module's `m` is a `q::t`. + let cases = [ + ( + "if (1) begin : g import p::*; t n; assign n = '1; assign a = n; end", + 15, + ), + ( + "if (1) begin : g import p::*; t n; initial n = 8'hff; assign a = n; end", + 15, + ), + ( + "if (1) begin : g import p::*; t n = 8'hff; assign a = $bits(n); end", + 4, + ), + ( + "if (1) begin : g import p::*; t n = 8'hff; assign a = n; end", + 15, + ), + // Casts and type queries. + ( + "if (1) begin : g import p::*; assign a = t'(8'hff) + $bits(t); end", + 19, + ), + // Declarations and generate conditions of the block. + ( + "if (1) begin : g import p::*; localparam t Z = '1; localparam int W = $bits(t); + assign a = Z + W; end", + 19, + ), + ( + "if (1) begin : g import p::*; t n; localparam int W = $bits(n); assign a = W; end", + 4, + ), + ( + "if (1) begin : g import p::*; logic [$bits(t)-1:0] v; assign a = $bits(v); end", + 4, + ), + ( + "if (1) begin : g import p::*; + if ($bits(t) == 4) begin : h assign a = 1; end else begin : h assign a = 2; end + end", + 1, + ), + ( + "if (1) begin : g import p::*; t n; + if ($bits(n) == 4) begin : h assign a = 1; end else begin : h assign a = 2; end + end", + 1, + ), + // Subroutines of the block. + ( + "if (1) begin : g import p::*; + function automatic t inc(t v); return v + 1; endfunction + assign a = inc(8'h1f); + end", + 0, + ), + ( + "if (1) begin : g import p::*; + function automatic int w(t v [2]); return v[0] + v[1] + $bits(v); endfunction + assign a = w('{8'hff, 8'h01}); + end", + 24, + ), + ( + "if (1) begin : g import p::*; + task automatic k(output t o); o = 8'hff; endtask + always_comb k(a); + end", + 15, + ), + ]; + for (body, expected) in cases { + assert_eq!( + output(&format!( + "{types} + module Top(output logic [7:0] y); import q::*; logic [7:0] a; t m; + assign m = 8'hf0; {body} assign y = a + m - 8'hf0; + endmodule" + )), + expected, + "{body}" + ); + } + assert_eq!( + output( + "package p; typedef struct packed { logic [3:0] x; logic [3:0] z; } t; endpackage + package q; typedef struct packed { logic [7:0] x; } t; endpackage + module Top(output logic [7:0] y); import q::*; logic [7:0] a; t m; + if (1) begin : g import p::*; t n; assign n = t'{x: 4'h1, z: 4'h2}; assign a = n; + end + assign m = t'{x: 8'h30}; assign y = a + m.x; + endmodule" + ), + 0x42 + ); + // A block import of a value hides the module's type of that name. + let values = "package p; localparam int T = 3; endpackage + package q; typedef logic [7:0] T; endpackage"; + assert_eq!( + output(&format!( + "{values} + module Top(output logic [7:0] y); import q::*; T m; logic [7:0] a; + if (1) begin : g import p::*; assign a = T; end + assign m = 8'h10; assign y = a + m; + endmodule" + )), + 0x13 + ); + let result = Simulator::from_sv_sources( + vec![( + format!( + "{values} + module Top(output logic [7:0] y); import q::*; T m; logic [7:0] a; + if (1) begin : g import p::*; T n; assign n = 8'hff; assign a = n; end + assign m = 0; assign y = a + m; + endmodule" + ) + .as_str(), + std::path::Path::new("packages.sv"), + )], + "Top", + ) + .build(); + assert!(result.is_err(), "`T` is a parameter in block `g`"); +} + +/// A declaration of a generate block hides a type of that name around it, +/// whether the module declares or imports the type (IEEE 1800-2023 23.9). +#[test] +fn generate_block_declarations_hide_outer_types() { + let cases = [ + "package p; typedef logic [3:0] T; endpackage + package q; typedef logic [7:0] T; endpackage + module Top(output logic [7:0] y); import q::*; T m; logic [7:0] a; assign m = 0; + if (1) begin : g import p::*; T o; + if (1) begin : h localparam int T = 2; + if (1) begin : i T n; assign n = '1; assign a = n; end + end + end + assign y = a + m; + endmodule", + "module Top(output logic [7:0] y); typedef logic [7:0] T; logic [7:0] a; + if (1) begin : h localparam int T = 2; + if (1) begin : i T n; assign n = '1; assign a = n; end + end + assign y = a; + endmodule", + "module Top(output logic [7:0] y); typedef logic [7:0] T; logic [7:0] a; + if (1) begin : h logic T; T n; assign n = '1; assign a = n; end + assign y = a; + endmodule", + ]; + for source in cases { + let result = + Simulator::from_sv_sources(vec![(source, std::path::Path::new("packages.sv"))], "Top") + .build(); + assert!(result.is_err(), "`T` is not a type in the block:\n{source}"); + } +} + +/// An inner block that imports the declaration its module sees still hides +/// the binding of a block around it, by import or by declaration. +#[test] +fn nested_generate_block_imports_restore_the_module_binding() { + let packages = "package p; localparam int X = 3; typedef logic [3:0] t; + function automatic int f(int a); return a + 1; endfunction endpackage + package q; localparam int X = 5; typedef logic [7:0] t; + function automatic int f(int a); return a + 2; endfunction endpackage"; + let cases = [ + ( + "logic [7:0] a, c; + if (1) begin : g import p::*; assign c = X; + if (1) begin : h import q::*; assign a = X; end + end + assign y = a * 10 + c + X;", + 58, + ), + ( + "logic [7:0] a; t m; assign m = 0; + if (1) begin : g import p::*; t o; + if (1) begin : h import q::*; t n; assign n = '1; assign a = n; end + end + assign y = a + m;", + 255, + ), + ( + "logic [7:0] a, c; + if (1) begin : g import p::*; assign c = f(0); + if (1) begin : h import q::*; localparam int Y = f(0); assign a = Y + f(10); end + end + assign y = a + c * 10 + f(0);", + 26, + ), + // The binding alternates down a chain of blocks. + ( + "logic [7:0] a, b, c; + if (1) begin : g import p::*; assign c = X; + if (1) begin : h import q::*; + if (1) begin : i import p::*; assign b = X; end + assign a = X; + end + end + assign y = a * 10 + b + X + c * 0;", + 58, + ), + ( + "logic [7:0] a; + if (1) begin : g localparam int X = 9; + if (1) begin : h import q::X; assign a = X; end + end + assign y = a + X;", + 10, + ), + ]; + for (body, expected) in cases { + assert_eq!( + output(&format!( + "{packages} + module Top(output logic [7:0] y); import q::*; {body} endmodule" + )), + expected, + "{body}" + ); + } +}