From 73bcc1acf90661995616bb3c6c19cd108d9b6bba Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 18 Oct 2026 10:34:24 +0900 Subject: [PATCH] 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` と指定できます。