From b78b0f51986ffbd6fa8ce5012af45dde3a136251 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 18 Oct 2026 07:34:41 +0900 Subject: [PATCH 1/2] 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}" + ); + } +} From 73bcc1acf90661995616bb3c6c19cd108d9b6bba Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 18 Oct 2026 10:34:24 +0900 Subject: [PATCH 2/2] fix(sv)!: name Veryl declarations by their emitted SV names In a mixed design, SV referred to Veryl modules and interfaces by their Veryl source names, while the Veryl emitter names them `_` (or `` with `omit_project_prefix`). SV written against the emitted code did not link, and SV written for Celox did not build with other tools. SV now sees Veryl declarations only by their emitted names: declaration contracts, interface bindings and foreign roots use them, and the hierarchy linker maps each emitted name back to its Veryl body instead of matching names, so an SV module and an emitted Veryl name no longer shadow each other. An SV module named like an emitted Veryl module is reported as a duplicate. A Veryl top is still selected by its Veryl name, and instances keep Veryl module names. Validation: - cargo test -p celox -p celox-frontend-veryl --features celox/systemverilog --lib --test systemverilog - cargo clippy -p celox -p celox-frontend-veryl --all-targets --features celox/systemverilog --no-deps - cargo fmt --all -- --check - New mixed tests cover a custom project prefix, omit_project_prefix, rejection of source names, and emitted-name collisions BREAKING CHANGE: SV sources in a mixed design must instantiate Veryl modules and interfaces by their emitted names, such as `prj_Child`, instead of `Child`. parse_ir_with_external_hierarchy_and_native_modules takes a map from external module names to Veryl module names instead of a name set. Change-Id: Ib464695577c60ea747f010607b3bebf6671b2805 --- crates/celox-frontend-veryl/src/artifact.rs | 13 +- crates/celox-frontend-veryl/src/hierarchy.rs | 21 ++- crates/celox/src/parser.rs | 51 +++++-- crates/celox/src/simulator/builder.rs | 6 +- crates/celox/src/simulator/mixed.rs | 99 +++++++++---- .../tests/frontends/systemverilog/mixed.rs | 140 ++++++++++++++---- docs/guide/systemverilog.md | 10 +- docs/ja/guide/systemverilog.md | 6 +- 8 files changed, 257 insertions(+), 89 deletions(-) diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index 1c01f52e657..597abeb4e3d 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -83,6 +83,8 @@ pub fn external_signatures( ExternalModule { sim_module, port_order, + // Veryl children link through the IR; only SV children are + // left for the SV frontend to resolve by name. unresolved_instances: module .declarations .iter() @@ -90,12 +92,13 @@ pub fn external_signatures( let veryl_analyzer::ir::Declaration::Inst(instance) = declaration else { return None; }; - let name = match instance.component.as_ref() { - Component::Module(module) => module.name, - Component::SystemVerilog(module) => module.name, - Component::Interface(_) => return None, + let Component::SystemVerilog(module) = instance.component.as_ref() else { + return None; }; - Some(veryl_parser::resource_table::get_str_value(name).unwrap_or_default()) + Some( + veryl_parser::resource_table::get_str_value(module.name) + .unwrap_or_default(), + ) }) .collect(), }, diff --git a/crates/celox-frontend-veryl/src/hierarchy.rs b/crates/celox-frontend-veryl/src/hierarchy.rs index b8da652c4e1..694584c8271 100644 --- a/crates/celox-frontend-veryl/src/hierarchy.rs +++ b/crates/celox-frontend-veryl/src/hierarchy.rs @@ -48,13 +48,15 @@ pub fn parse_ir_with_external_hierarchy<'a>( } /// Link the explicitly identified Veryl exports without matching SV namesakes. +/// `native_modules` maps each external module name that stands for a Veryl +/// body to the name of that body in `ir`. pub fn parse_ir_with_external_hierarchy_and_native_modules<'a>( ir: &'a veryl_analyzer::ir::Ir, loop_provenance: &LoopProvenance, external: &'a ExternalHierarchy, config: &BuildConfig, top: &StrId, - native_modules: &HashSet, + native_modules: &HashMap, ) -> Result, ParserError> { parse_external_hierarchy( ir, @@ -72,7 +74,7 @@ fn parse_external_hierarchy<'a>( external: &'a ExternalHierarchy, config: &BuildConfig, top: &StrId, - native_modules: Option<&HashSet>, + native_modules: Option<&HashMap>, ) -> Result, ParserError> { // Token-to-scope resolution uses process-global analyzer state and is not // safe while independent compilations run on other test threads. Snapshot @@ -116,7 +118,7 @@ fn parse_external_hierarchy<'a>( let top_name = resource_table::get_str_value(*top).unwrap_or_default(); let root_ir = name_to_ir.get(top).copied(); let external_root = external.roots.get(&top_name).copied().filter(|_| { - root_ir.is_none() || native_modules.is_none_or(|names| names.contains(&top_name)) + root_ir.is_none() || native_modules.is_none_or(|names| names.contains_key(&top_name)) }); if root_ir.is_none() && external_root.is_none() { return Err(ParserError::TopNotFound { name: top_name }); @@ -172,11 +174,18 @@ fn parse_external_hierarchy<'a>( binding.package = external_ids[&binding.package]; } module_names.insert(global_id, external_module.sim_module.name.clone()); - let native_name = resource_table::insert_str(&external_module.sim_module.name); - if let Some(&native_module) = name_to_ir.get(&native_name) - && native_modules.is_none_or(|names| names.contains(&external_module.sim_module.name)) + let native_name = match native_modules { + Some(names) => names.get(&external_module.sim_module.name).copied(), + None => Some(resource_table::insert_str(&external_module.sim_module.name)), + }; + if let Some(native_name) = native_name + && let Some(&native_module) = name_to_ir.get(&native_name) && !module_ir.contains_key(&global_id) { + module_names.insert( + global_id, + resource_table::get_str_value(native_name).unwrap_or_default(), + ); module_ir.insert(global_id, native_module); signature_to_id.insert(native_module.signature.clone(), global_id); worklist.push((global_id, native_module)); diff --git a/crates/celox/src/parser.rs b/crates/celox/src/parser.rs index 4a4c4eda6de..493a8d0ead4 100644 --- a/crates/celox/src/parser.rs +++ b/crates/celox/src/parser.rs @@ -662,6 +662,7 @@ pub fn parse_mixed( requests: &[celox_frontend_sv::SvModuleRequest], sv_interfaces: &[celox_frontend_sv::InterfaceSignature], used_names: &mut fxhash::FxHashSet, + names: crate::simulator::mixed::EmittedNames, config: &BuildConfig, ignored_loops: &[( (Vec<(String, usize)>, Vec), @@ -699,8 +700,23 @@ pub fn parse_mixed( external_roots.insert(top_name.clone()); } let mut foreign = celox_frontend_veryl::external_signatures(ir, config)?; - let authored = celox_frontend_sv::module_interfaces(sv_sources).map_err(sv_analysis_error)?; - foreign.roots.retain(|name, _| !authored.contains_key(name)); + // SV instantiates a Veryl module by its emitted name. The linker binds + // that name back to the Veryl body; an SV module declaring the same name + // is a duplicate the SV analyzer reports. + let mut native_modules = crate::HashMap::default(); + let mut roots = std::mem::take(&mut foreign.roots); + for component in &ir.components { + let veryl_analyzer::ir::Component::Module(module) = component else { + continue; + }; + let Some(id) = roots.remove(&module.name.to_string()) else { + continue; + }; + let emitted = names.module(module); + foreign.modules.get_mut(&id).unwrap().sim_module.name = emitted.clone(); + foreign.roots.insert(emitted.clone(), id); + native_modules.insert(emitted, module.name); + } let sv_top_parameters = (!native_top).then_some((top_name.as_str(), top_parameters)); let base = ir.clone(); let mut specializations = Vec::new(); @@ -743,8 +759,19 @@ pub fn parse_mixed( )); } let mut prepare = || -> Result<_, ParserError> { + let native = native_modules.get(name).ok_or_else(|| { + ParserError::illegal_context( + "foreign module specialization", + format!("`{name}` is not a Veryl module"), + None, + ) + })?; let module = crate::simulator::mixed::specialize_foreign_module( - &base, context, name, parameters, used_names, + &base, + context, + &native.to_string(), + parameters, + used_names, )?; let mut specialized = veryl_analyzer::ir::Ir { components: vec![veryl_analyzer::ir::Component::Module(module)], @@ -767,6 +794,7 @@ pub fn parse_mixed( &joint_sources, context, used_names, + names, )?; let exported = celox_frontend_veryl::external_signatures(&specialized, config)?; let signature = exported.modules.values().next().cloned().ok_or_else(|| { @@ -818,17 +846,12 @@ pub fn parse_mixed( .map(|source| (source, std::path::PathBuf::from(""))), ); }; - ir.components.extend(specializations); - let mut native_modules = foreign.roots.keys().cloned().collect::>(); - native_modules.extend(ir.components.iter().filter_map(|component| { - if let veryl_analyzer::ir::Component::Module(module) = component - && !authored.contains_key(&module.name.to_string()) - { - Some(module.name.to_string()) - } else { - None + for component in &specializations { + if let veryl_analyzer::ir::Component::Module(module) = component { + native_modules.insert(module.name.to_string(), module.name); } - })); + } + ir.components.extend(specializations); parse_with_external_hierarchy( top, ir, @@ -856,7 +879,7 @@ pub fn parse_with_external_hierarchy( ir: &veryl_analyzer::ir::Ir, loop_provenance: &loop_provenance::LoopProvenance, external: &celox_frontend_core::symbolic::artifact::ExternalHierarchy, - native_modules: Option<&HashSet>, + native_modules: Option<&crate::HashMap>, config: &BuildConfig, ignored_loops: &[( (Vec<(String, usize)>, Vec), diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index ba64dbdfa88..80b636b6991 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -497,7 +497,8 @@ fn analyze( { if let Some(sv_sources) = sv_sources { (|| { - let mut used_names = super::mixed::component_names(sv_sources)?; + let names = super::mixed::EmittedNames::new(&metadata); + let mut used_names = super::mixed::component_names(sv_sources, names)?; let behavior_sources = super::mixed::attach_sv_interface_behavior( &mut ir, &sv_interface_signatures, @@ -515,12 +516,14 @@ fn analyze( &joint_sources, &mut context, &mut used_names, + names, )?; let declarations = super::mixed::sv_declaration_contracts( &ir, &mut context, &joint_sources, &requests, + names, )?; parser::parse_mixed( &top, @@ -536,6 +539,7 @@ fn analyze( &requests, &sv_interface_signatures, &mut used_names, + names, &build_config, ignored_loops, true_loops, diff --git a/crates/celox/src/simulator/mixed.rs b/crates/celox/src/simulator/mixed.rs index ab2592c6331..d63f2c522b5 100644 --- a/crates/celox/src/simulator/mixed.rs +++ b/crates/celox/src/simulator/mixed.rs @@ -19,17 +19,54 @@ fn fresh_name(prefix: &str, used: &mut fxhash::FxHashSet, next: &mut usi } } +/// SystemVerilog sees Veryl declarations by the names the Veryl emitter gives +/// them, so SV written against the emitted code links unchanged. +#[derive(Clone, Copy)] +pub(crate) struct EmittedNames { + project: veryl_parser::resource_table::StrId, + omit_project_prefix: bool, +} + +impl EmittedNames { + pub(crate) fn new(metadata: &veryl_metadata::Metadata) -> Self { + Self { + project: veryl_parser::resource_table::insert_str(&metadata.project.name), + omit_project_prefix: metadata.build.omit_project_prefix, + } + } + + /// The emitted name of a top-level declaration. SV declarations seen + /// through `$sv` keep their own names. + pub(crate) fn symbol(&self, symbol: &veryl_analyzer::symbol::Symbol) -> String { + let name = symbol.token.text.to_string(); + let Some(&project) = symbol.namespace.paths.first() else { + return name; + }; + let project_text = project.to_string(); + if project_text == "$sv" || (self.omit_project_prefix && project == self.project) { + return name; + } + format!("{project_text}_{name}").replace("$std_", "__std_") + } + + pub(crate) fn module(&self, module: &veryl_analyzer::ir::Module) -> String { + veryl_analyzer::symbol_table::get(module.signature.symbol) + .map(|symbol| self.symbol(&symbol)) + .unwrap_or_else(|| module.name.to_string()) + } +} + pub(super) fn component_names( sources: &[(&str, &std::path::Path)], + names: EmittedNames, ) -> Result, ParserError> { - let mut names = + let mut used = celox_frontend_sv::component_names(sources).map_err(crate::parser::sv_analysis_error)?; - names.extend( - veryl_analyzer::symbol_table::get_all() - .iter() - .map(|symbol| symbol.token.text.to_string()), - ); - Ok(names) + for symbol in veryl_analyzer::symbol_table::get_all() { + used.insert(symbol.token.text.to_string()); + used.insert(names.symbol(&symbol)); + } + Ok(used) } pub(super) fn referenced_sv_components<'a>( @@ -942,6 +979,7 @@ pub(super) fn sv_declaration_contracts( context: &mut veryl_analyzer::Context, sources: &[(&str, &std::path::Path)], requests: &[celox_frontend_sv::SvModuleRequest], + names: EmittedNames, ) -> Result { use veryl_analyzer::{ ir::{Component, Signature, TypeKind, VarKind}, @@ -962,18 +1000,12 @@ pub(super) fn sv_declaration_contracts( })); for component in &ir.components { if let Component::Module(module) = component - && referenced.contains(&module.name.to_string()) - && !authored.contains_key(&module.name.to_string()) + && referenced.contains(&names.module(module)) { for (ty, _) in module.port_types.values() { if let TypeKind::Modport(signature, _) = &ty.kind { - needed_interfaces.insert( - symbol_table::get(signature.symbol) - .unwrap() - .token - .text - .to_string(), - ); + needed_interfaces + .insert(names.symbol(&symbol_table::get(signature.symbol).unwrap())); } } } @@ -987,7 +1019,8 @@ pub(super) fn sv_declaration_contracts( if symbol.namespace.to_string() == "$sv" || property.is_proto { continue; } - if !needed_interfaces.contains(&symbol.token.text.to_string()) { + let name = names.symbol(symbol); + if !needed_interfaces.contains(&name) { continue; } let signature = Signature::new(symbol.id); @@ -1003,7 +1036,7 @@ pub(super) fn sv_declaration_contracts( continue; }; let parameters = sv_parameters(&property.parameters, &interface.variables, context)?; - source.push_str(&format!("interface {}{parameters};\n", symbol.token.text)); + source.push_str(&format!("interface {name}{parameters};\n")); let mut variables = interface.variables.values().collect::>(); variables.sort_by_key(|variable| variable.id); for variable in variables { @@ -1055,9 +1088,10 @@ pub(super) fn sv_declaration_contracts( let Component::Module(module) = component else { continue; }; - if !referenced.contains(&module.name.to_string()) - || authored.contains_key(&module.name.to_string()) - { + let emitted = names.module(module); + // An authored SV module of the same name is a duplicate definition; + // the SV analyzer reports it when the foreign roots are linked. + if !referenced.contains(&emitted) || authored.contains_key(&emitted) { continue; } if module @@ -1067,9 +1101,10 @@ pub(super) fn sv_declaration_contracts( { continue; } - let Some(symbol) = symbols.iter().find(|symbol| { - symbol.token.text == module.name && matches!(symbol.kind, SymbolKind::Module(_)) - }) else { + let Some(symbol) = symbols + .iter() + .find(|symbol| symbol.id == module.signature.symbol) + else { continue; }; let SymbolKind::Module(property) = &symbol.kind else { @@ -1086,7 +1121,7 @@ pub(super) fn sv_declaration_contracts( let interface = symbol_table::get(signature.symbol).unwrap(); ports.push(format!( "{}.{modport} {name}{}", - interface.token.text, + names.symbol(&interface), sv_array(ty) )); } else if let Some(id) = module.ports.get(&path) { @@ -1106,8 +1141,7 @@ pub(super) fn sv_declaration_contracts( } let parameters = sv_parameters(&property.parameters, &module.variables, context)?; source.push_str(&format!( - "module {}{parameters}({}); endmodule\n", - module.name, + "module {emitted}{parameters}({}); endmodule\n", ports.join(", ") )); } @@ -1339,6 +1373,7 @@ pub(crate) fn specialize_sv_instances( sources: &[(&str, &std::path::Path)], context: &mut veryl_analyzer::Context, used_names: &mut fxhash::FxHashSet, + names: EmittedNames, ) -> Result, ParserError> { use veryl_analyzer::{ir::*, symbol::SymbolKind, symbol_table}; use veryl_parser::resource_table; @@ -1374,6 +1409,7 @@ pub(crate) fn specialize_sv_instances( requests: &mut Vec, used_names: &mut fxhash::FxHashSet, next_alias: &mut usize, + names: EmittedNames, ) -> Result<(), ParserError> { let mut evaluation = veryl_analyzer::Context::default(); evaluation.inherit(context); @@ -1398,7 +1434,9 @@ pub(crate) fn specialize_sv_instances( continue; }; if let Component::Module(child) = std::sync::Arc::make_mut(&mut instance.component) { - walk(child, interfaces, context, requests, used_names, next_alias)?; + walk( + child, interfaces, context, requests, used_names, next_alias, names, + )?; continue; } let Component::SystemVerilog(component) = instance.component.as_ref() else { @@ -1513,7 +1551,7 @@ pub(crate) fn specialize_sv_instances( }; signature.normalize(); let symbol = symbol_table::get(signature.symbol).unwrap(); - bindings.push((formal.clone(), symbol.token.text.to_string())); + bindings.push((formal.clone(), names.symbol(&symbol))); for (name, value) in &signature.parameters { let ValueVariant::Numeric(value) = value else { return Err(unsupported("foreign interface type parameter")); @@ -1552,6 +1590,7 @@ pub(crate) fn specialize_sv_instances( &mut requests, used_names, &mut next_alias, + names, )?; } } @@ -1940,7 +1979,7 @@ mod tests { let mut sibling = child.clone(); sibling.name = resource_table::insert_str("__sv_logic_bus_0"); module.declarations.push(Declaration::Inst(sibling)); - let mut names = component_names(&sources).unwrap(); + let mut names = component_names(&sources, EmittedNames::new(&metadata)).unwrap(); let generated = attach_sv_interface_behavior(&mut ir, &signatures, &mut context, &mut names).unwrap(); assert_eq!(generated.len(), 1); diff --git a/crates/celox/tests/frontends/systemverilog/mixed.rs b/crates/celox/tests/frontends/systemverilog/mixed.rs index 1aa8d1bb4b0..fa62b1055ba 100644 --- a/crates/celox/tests/frontends/systemverilog/mixed.rs +++ b/crates/celox/tests/frontends/systemverilog/mixed.rs @@ -15,7 +15,7 @@ sv_backends! { fn reserves_authored_interface_names_for_generated_modules(sim) { @setup { let veryl = "module Child #(param K: u32 = 1)(a: input logic<8>, y: output logic<8>) { inst bus: $sv::Bus; assign bus.req = a; assign y = bus.rsp + K; }"; - let sv = "interface __celox_sv_interface_0; logic x; endinterface interface __celox_foreign_Child_0; logic x; endinterface interface Bus; logic [7:0] req, rsp; assign rsp = req + 1; endinterface module Top(input logic [7:0] a, output logic [7:0] y); Child #(.K(3)) child(a,y); endmodule"; + let sv = "interface __celox_sv_interface_0; logic x; endinterface interface __celox_foreign_Child_0; logic x; endinterface interface Bus; logic [7:0] req, rsp; assign rsp = req + 1; endinterface module Top(input logic [7:0] a, output logic [7:0] y); prj_Child #(.K(3)) child(a,y); endmodule"; } @build Simulator::from_mixed_sources(vec![(veryl, Path::new("child.veryl"))], vec![(sv, Path::new("top.sv"))], "Top"); let a = sim.signal("a"); @@ -49,7 +49,7 @@ sv_backends! { fn resolves_veryl_interface_parameter_types_after_prior_overrides(sim) { @setup { let veryl = "interface Bus #(param W: u32 = 8, param V: logic = 4) { var req: logic; var rsp: logic; modport slave { req: input, rsp: output, } } module Child(bus: modport Bus::slave) { assign bus.rsp = bus.req; }"; - let sv = "module Top(input logic [259:0] a, output logic [259:0] y); Bus #(.V(16'd260), .W(16)) bus(); assign bus.req = a; Child child(.bus(bus)); assign y = bus.rsp; endmodule"; + let sv = "module Top(input logic [259:0] a, output logic [259:0] y); prj_Bus #(.V(16'd260), .W(16)) bus(); assign bus.req = a; prj_Child child(.bus(bus)); assign y = bus.rsp; endmodule"; } @build Simulator::from_mixed_sources(vec![(veryl, Path::new("bus.veryl"))], vec![(sv, Path::new("top.sv"))], "Top"); let a = sim.signal("a"); @@ -81,7 +81,7 @@ sv_backends! { } module Child(bus: modport Bus::slave) { assign bus.rsp = bus.req + 1; } "#; - let sv = "module Top(input logic [31:0] a, output logic [31:0] y); Bus #(.W(16)) bus(); assign bus.req = a; Child child(.bus(bus)); assign y = bus.rsp; endmodule"; + let sv = "module Top(input logic [31:0] a, output logic [31:0] y); prj_Bus #(.W(16)) bus(); assign bus.req = a; prj_Child child(.bus(bus)); assign y = bus.rsp; endmodule"; } @build Simulator::from_mixed_sources( vec![(veryl, Path::new("bus.veryl"))], vec![(sv, Path::new("top.sv"))], "Top", @@ -108,7 +108,7 @@ sv_backends! { let sv = r#" module Top(output logic [255:0] y, negative); localparam logic [127:0] HIGH = 128'h8000_0000_0000_0000_0000_0000_0000_0001; - Child #(.K(HIGH), .S(-128'sd1)) child(.y(y), .negative(negative)); + prj_Child #(.K(HIGH), .S(-128'sd1)) child(.y(y), .negative(negative)); endmodule "#; } @@ -183,7 +183,7 @@ sv_backends! { let sv = r#" module Top(input logic [7:0] a, output logic [7:0] y); timeunit 1ns; timeprecision 1ps; - Child child(.a(a), .y(y)); + prj_Child child(.a(a), .y(y)); endmodule "#; } @@ -266,7 +266,7 @@ sv_backends! { assign y = a + 42; endmodule module Top(input logic [7:0] a, output logic [7:0] specialized, authored); - Child #(.K(5)) child(.a(a), .y(specialized)); + prj_Child #(.K(5)) child(.a(a), .y(specialized)); __celox_foreign_Child_0 other(.a(a), .y(authored)); endmodule "#; @@ -302,8 +302,8 @@ sv_backends! { assign y = a + W; endmodule module Top(input logic [15:0] a, output logic [15:0] y, output logic [7:0] narrow); - Mid #(.W(16)) wide(.a(a), .y(y)); - Mid normal(.a(a[7:0]), .y(narrow)); + prj_Mid #(.W(16)) wide(.a(a), .y(y)); + prj_Mid normal(.a(a[7:0]), .y(narrow)); endmodule "#; } @@ -325,8 +325,8 @@ sv_backends! { assign rsp = req + W; endinterface module Top(input logic [15:0] a, output logic [15:0] y, output logic [7:0] narrow); - Mid #(.W(16)) wide(.a(a), .y(y)); - Mid normal(.a(a[7:0]), .y(narrow)); + prj_Mid #(.W(16)) wide(.a(a), .y(y)); + prj_Mid normal(.a(a[7:0]), .y(narrow)); endmodule "#; } @@ -356,8 +356,8 @@ sv_backends! { let sv = r#" module Leaf(interface bus); assign bus.rsp = bus.req + bus.W; endmodule module Top(input logic [15:0] a, output logic [15:0] y, output logic [7:0] narrow); - Mid #(.W(16)) wide(.a(a), .y(y)); - Mid normal(.a(a[7:0]), .y(narrow)); + prj_Mid #(.W(16)) wide(.a(a), .y(y)); + prj_Mid normal(.a(a[7:0]), .y(narrow)); endmodule "#; } @@ -382,14 +382,14 @@ sv_backends! { "#; let sv = r#" module Hop #(parameter W = 8)(input logic [W-1:0] a, output logic [W-1:0] y); - Final #(.W(W)) child(.a(a), .y(y)); + prj_Final #(.W(W)) child(.a(a), .y(y)); endmodule module Leaf #(parameter W = 8)(input logic [W-1:0] a, output logic [W-1:0] y); assign y = a + W; endmodule module Top(input logic [31:0] a, output logic [31:0] y, output logic [15:0] narrow); - Mid #(.W(32)) wide(.a(a), .y(y)); - Mid #(.W(16)) other(.a(a[15:0]), .y(narrow)); + prj_Mid #(.W(32)) wide(.a(a), .y(y)); + prj_Mid #(.W(16)) other(.a(a[15:0]), .y(narrow)); endmodule "#; } @@ -438,7 +438,7 @@ sv_backends! { "#; let sv = r#" module Top(output logic [127:0] negative, output logic [95:0] positive); - Child #(.NEG(-128'sd1), .HIGH(96'h1_0000_0000_0000_0001)) child(.negative(negative), .positive(positive)); + prj_Child #(.NEG(-128'sd1), .HIGH(96'h1_0000_0000_0000_0001)) child(.negative(negative), .positive(positive)); endmodule "#; } @@ -495,7 +495,7 @@ sv_backends! { module Child #(param W: u32 = 8, param N: u32 = W * 2, param C: u32 = Defaults::increment()) (a: input logic, y: output logic) { assign y = a + C; } "#; - let sv = "module Top(input logic [31:0] a, output logic [31:0] y); Child #(.W(16)) child(.a(a), .y(y)); endmodule"; + let sv = "module Top(input logic [31:0] a, output logic [31:0] y); prj_Child #(.W(16)) child(.a(a), .y(y)); endmodule"; } @build Simulator::from_mixed_sources( vec![(veryl, Path::new("child.veryl"))], vec![(sv, Path::new("top.sv"))], "Top", @@ -516,9 +516,9 @@ sv_backends! { "#; let sv = r#" module Top(input logic [31:0] a, output logic [31:0] y); - Bus #(.W(16)) bus(); + prj_Bus #(.W(16)) bus(); assign bus.req = a; - Child child(.bus(bus)); + prj_Child child(.bus(bus)); assign y = bus.rsp; endmodule "#; @@ -573,7 +573,7 @@ sv_backends! { fn overrides_parameters_of_a_systemverilog_top_in_a_mixed_design(sim) { @setup { let veryl = "module Child (a: input logic<16>, y: output logic<16>) { assign y = a + 1; }"; - let sv = "module Top #(parameter W = 8)(input logic [W-1:0] a, output logic [W-1:0] y); Child child(.a(a), .y(y)); endmodule"; + let sv = "module Top #(parameter W = 8)(input logic [W-1:0] a, output logic [W-1:0] y); prj_Child child(.a(a), .y(y)); endmodule"; } @build Simulator::from_mixed_sources( vec![(veryl, Path::new("child.veryl"))], @@ -668,7 +668,7 @@ sv_backends! { "#; let sv = r#" module Top(input logic [15:0] a, output logic [15:0] y); - Child #(.W(16)) child(.a(a), .y(y)); + prj_Child #(.W(16)) child(.a(a), .y(y)); endmodule "#; } @@ -696,7 +696,7 @@ sv_backends! { module Top(input logic [15:0] a, output logic [15:0] y); Bus #(.W(16)) bus(); assign bus.req = a; - Child child(.bus(bus)); + prj_Child child(.bus(bus)); assign y = bus.rsp; endmodule "#; @@ -777,9 +777,9 @@ sv_backends! { "#; let sv = r#" module Top(input logic [7:0] a, output logic [7:0] y); - Bus bus(); + prj_Bus bus(); assign bus.req = a; - Child child(.bus(bus)); + prj_Child child(.bus(bus)); assign y = bus.rsp; endmodule "#; @@ -808,7 +808,7 @@ sv_backends! { assign y = bus.rsp; } "#; - let sv = "module Slave(Bus.slave bus); assign bus.rsp = bus.req + 8'd1; endmodule"; + let sv = "module Slave(prj_Bus.slave bus); assign bus.rsp = bus.req + 8'd1; endmodule"; } @build Simulator::from_mixed_sources( vec![(veryl, Path::new("bus.veryl"))], @@ -834,7 +834,7 @@ sv_backends! { module Top(input logic [7:0] a, output logic [7:0] y); Bus bus(); assign bus.req = a; - Child child(.bus(bus)); + prj_Child child(.bus(bus)); assign y = bus.rsp; endmodule "#; @@ -888,7 +888,7 @@ sv_backends! { "#; let sv = r#" module Top(input logic [7:0] a, output logic [7:0] y); - VerylChild child(.y(y), .a(a)); + prj_VerylChild child(.y(y), .a(a)); endmodule module SvLeaf(input logic [7:0] a, output logic [7:0] y); assign y = a ^ 8'h55; @@ -1168,7 +1168,7 @@ sv_backends! { #[test] fn bounds_recursive_alternating_parameter_specializations() { let veryl = "module Mid #(param W: u32 = 0) { inst child: $sv::Hop #(W: W + 1); }"; - let sv = "module Hop #(parameter W = 0); Mid #(.W(W)) child(); endmodule module Top; Mid #(.W(1)) child(); endmodule"; + let sv = "module Hop #(parameter W = 0); prj_Mid #(.W(W)) child(); endmodule module Top; prj_Mid #(.W(1)) child(); endmodule"; let error = Simulator::from_mixed_sources( vec![(veryl, Path::new("mid.veryl"))], vec![(sv, Path::new("top.sv"))], @@ -1200,7 +1200,7 @@ fn rejects_missing_children_of_a_systemverilog_top_in_a_mixed_design() { #[test] fn rejects_cycles_that_cross_language_boundaries() { let veryl = "module Child { inst parent: $sv::Top; }"; - let sv = "module Top; Child child(); endmodule"; + let sv = "module Top; prj_Child child(); endmodule"; let error = Simulator::from_mixed_sources( vec![(veryl, Path::new("child.veryl"))], vec![(sv, Path::new("top.sv"))], @@ -1214,6 +1214,88 @@ fn rejects_cycles_that_cross_language_boundaries() { ); } +fn metadata(project: &str, omit_project_prefix: bool) -> veryl_metadata::Metadata { + let mut metadata = veryl_metadata::Metadata::create_default(project).unwrap(); + metadata.build.omit_project_prefix = omit_project_prefix; + metadata +} + +#[test] +fn names_veryl_declarations_by_their_emitted_project_prefix() { + let veryl = r#" + interface Bus { var req: logic<8>; var rsp: logic<8>; modport slave { req: input, rsp: output, } } + module Child (bus: modport Bus::slave) { assign bus.rsp = bus.req + 8'd1; } + "#; + let sv = "module Top(input logic [7:0] a, output logic [7:0] y); mylib_Bus bus(); assign bus.req = a; mylib_Child child(.bus(bus)); assign y = bus.rsp; endmodule"; + let mut sim = Simulator::from_mixed_sources( + vec![(veryl, Path::new("child.veryl"))], + vec![(sv, Path::new("top.sv"))], + "Top", + ) + .with_metadata(metadata("mylib", false)) + .build_cranelift() + .unwrap(); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 41u8)).unwrap(); + assert_eq!(sim.get(sim.signal("y")), 42u8.into()); +} + +#[test] +fn names_veryl_declarations_without_an_omitted_project_prefix() { + let veryl = "module Child (a: input logic<8>, y: output logic<8>) { assign y = a + 1; }"; + let sv = "module Top(input logic [7:0] a, output logic [7:0] y); Child child(.a(a), .y(y)); endmodule"; + let mut sim = Simulator::from_mixed_sources( + vec![(veryl, Path::new("child.veryl"))], + vec![(sv, Path::new("top.sv"))], + "Top", + ) + .with_metadata(metadata("prj", true)) + .build_cranelift() + .unwrap(); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 41u8)).unwrap(); + assert_eq!(sim.get(sim.signal("y")), 42u8.into()); +} + +#[test] +fn rejects_veryl_source_names_that_differ_from_emitted_names() { + let veryl = "module Child (a: input logic<8>, y: output logic<8>) { assign y = a + 1; }"; + let sv = "module Top(input logic [7:0] a, output logic [7:0] y); Child child(.a(a), .y(y)); endmodule"; + let error = Simulator::from_mixed_sources( + vec![(veryl, Path::new("child.veryl"))], + vec![(sv, Path::new("top.sv"))], + "Top", + ) + .build_cranelift() + .unwrap_err(); + assert!( + error + .to_string() + .contains("External module `Child` was not supplied"), + "{error}" + ); +} + +#[test] +fn rejects_sv_modules_named_like_an_emitted_veryl_module() { + let veryl = "module Top (a: input logic<8>, y: output logic<8>) { inst child: $sv::Child (a, y); } module Child (a: input logic<8>, y: output logic<8>) { assign y = a + 1; }"; + let sv = "module Child(input logic [7:0] a, output logic [7:0] y); assign y = a; endmodule"; + let error = Simulator::from_mixed_sources( + vec![(veryl, Path::new("top.veryl"))], + vec![(sv, Path::new("child.sv"))], + "Top", + ) + .with_metadata(metadata("prj", true)) + .build_cranelift() + .unwrap_err(); + assert!( + error + .to_string() + .contains("Duplicate module declaration: Child"), + "{error}" + ); +} + // These assert the intended simulation results, so implementing the missing // bridge behavior only requires removing the ignore attributes. mod pending_interface_functions { diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index 963940f0c26..4ecaef57c65 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -32,9 +32,13 @@ let mut sim = Simulator::from_sv_sources( ``` `Simulator::from_mixed_sources` combines both source lists in one simulation. -Veryl instantiates an SV module with `$sv::Module`; SV instantiates a Veryl -module by its name. A Veryl module and an SV module may share a name; -`$sv::Module` selects the SV definition. Numeric module parameters are resolved by the owning +Veryl instantiates an SV module with `$sv::Module`. SV refers to a Veryl module +or interface by the name the Veryl emitter gives it, as SV written against the +emitted code does: `prj_Module` for module `Module` of project `prj`, or +`Module` when `omit_project_prefix` is set in `Veryl.toml`. Without a +`Veryl.toml` the project is named `prj`. An SV module whose name equals the +emitted name of a Veryl module is a duplicate definition. A Veryl top is named +by its Veryl name. Numeric module parameters are resolved by the owning frontend, including parameters of Veryl children instantiated from SV. Interfaces and `input` / `output` modports may cross the boundary in either diff --git a/docs/ja/guide/systemverilog.md b/docs/ja/guide/systemverilog.md index 52d84f87476..022c50c3cfe 100644 --- a/docs/ja/guide/systemverilog.md +++ b/docs/ja/guide/systemverilog.md @@ -31,7 +31,11 @@ let mut sim = Simulator::from_sv_sources( `Simulator::from_mixed_sources` は両言語のソースを組み合わせます。トップはどちらの言語でもよく、 階層は Veryl → SV → Veryl のように言語境界を複数回跨げます。Veryl では `$sv::Module`、 -SV では Veryl のモジュール名でインスタンス化します。数値パラメータは、それぞれの frontend が解決します。 +SV からは Veryl のモジュールや interface を Veryl の emitter が出力する名前で参照します。 +出力された SV に対して書いた SV コードがそのまま使えます。プロジェクト `prj` のモジュール `Module` は +`prj_Module`、`Veryl.toml` で `omit_project_prefix` を設定した場合は `Module` です。 +`Veryl.toml` がない場合のプロジェクト名は `prj` です。Veryl モジュールの出力名と同名の SV モジュールは +重複定義になります。Veryl のトップは Veryl の名前で指定します。数値パラメータは、それぞれの frontend が解決します。 interface と `input` / `output` modport のメンバー接続も双方向に対応します。SV の interface は Veryl で `inst bus: $sv::Bus;`、ポートで `bus: modport $sv::Bus::slave` と指定できます。