From 3dd8e2a82a33612b7163e2dc61c7715856fd10bb Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 28 Oct 2026 20:13:19 +0900 Subject: [PATCH] feat(sv): specialize package classes from importing scopes Allow modules, packages and compilation-unit classes to request package-class specializations that the declaring package never names. This enables the UVM registry pattern `typedef Registry#(User) type_id`, including calls through `type_id::create()` that construct the supplied compilation-unit class. Bind explicit actuals in the requesting scope and defaults, inherited member types/constants and method bodies in their declaration scopes. Reuse one canonical specialization and package state across importing scopes, preserving nominal type identity, equivalent defaults, constructor defaults, static class handles and distinct per-file compilation-unit classes. Discover signatures before binding executable bodies with the supplied classes' metadata. Keep module-local class actuals unsupported until their identity can distinguish module instances. This change is independent of built-in process control and virtual-interface support. It does not remove the existing restriction on nonconstant package declaration initializers. Add nine portable shared cases and API regressions for native images and serialized checkpoints. Retain all 19 observed external-simulator failures with unchanged expectations, exact diagnostics, standard review and six standalone probes. xezim validation uses pinned source d491f948/core a25655a4 with a regenerated dependency lock in an isolated Nix package; no simulator or repository lock sources are changed. Validation: - All five backends: 50 foreign-specialization tests passed; class/package and concurrent-assertion regressions: 539 passed after syncing master. Package regressions: 70 passed after syncing master. Earlier full SV run: 6250 passed, 20 ignored. - Analyzer/frontend unit tests on master e7ec496251: 896 passed, 3 ignored. - NAPI/JS: 435 tests, playground 132 tests, and plugin/watch integration passed. - Affected-crate Clippy, formatting and retained-report/gate checks passed. - Nine external cases: Verilator 5 pass/4 retained failures, Icarus 9 retained failures, xezim 3 pass/6 retained failures. Standalone Celox probes pass in both two-state and four-state modes. After syncing master 8c8119247e (with #2322 and #2421): a scope without classes of its own discovers queries as before, since it has no class signatures to bind once; resolution keeps the built-in `process` fallback and its type spelling. Analyzer/frontend units: 886 passed, 3 ignored; full SV: 6,421 passed, 20 skipped; retained-report and gate tests pass. Retained Verilator/xezim diagnostics of the foreign cases follow their new case lines. Review follow-ups: a request supplies only the caller's qualified routines (the methods of the classes its actual type arguments name), not its own unqualified functions; an unresolved name in a package class body binding to an importing module's function also happens without importing-scope specializations and is tracked in #2447. A compilation-unit typedef is named with its source file, as compilation-unit classes are, so the same enum typedef in two files gives two specializations; a Celox-only multi-file test covers it, since IEEE 1800-2023 3.12.1 also allows one compilation unit for all files (Verilator rejects the duplicate typedef). Analyzer/frontend 886, full SV 6,422 passed. Second review round: a handle chain such as `a.next.next...` resolves each receiver once for both the instance and the static property, instead of doubling the walk per field; and a request binds against the template its owner package declares, not a same-named class of another package in that source (`class::foreign_generic_template_of_the_named_package`: Verilator and xezim pass, Icarus rejects the class). Analyzer/frontend 887, full SV 6,427 passed. Change-Id: I94cfcf52749ba3ad9d7e7d893e795c86bc146939 --- crates/celox-frontend-sv/src/lowering.rs | 3 +- crates/celox-sv-analyzer/src/ast.rs | 48 ++ crates/celox-sv-analyzer/src/ast/classes.rs | 78 +-- .../src/ast/classes/foreign.rs | 514 ++++++++++++++++++ .../src/ast/classes/specializations.rs | 351 +++++++++--- .../src/ast/dimensions/discovery.rs | 21 +- .../src/ast/expression_binding.rs | 6 +- .../src/ast/expression_binding/direct.rs | 5 + .../src/ast/expression_binding/objects.rs | 96 +++- crates/celox-sv-analyzer/src/ast/packages.rs | 54 +- .../src/ast/type_binding/binding.rs | 56 +- crates/celox-sv-analyzer/src/ast/types.rs | 9 +- crates/celox-sv-analyzer/src/parsed.rs | 19 +- crates/celox-sv-analyzer/src/source_tree.rs | 5 + crates/celox-sv-analyzer/src/tests.rs | 110 ++++ crates/celox-test-suite/LIMITATIONS.md | 38 ++ .../celox-test-suite/src/sv/cases/class.vtest | 325 +++++++++++ .../celox-test-suite/src/sv/verification.rs | 27 +- .../tests/retained_reports.rs | 52 ++ .../repros/sv_foreign_generic.json | 171 ++++++ .../repros/sv_foreign_generic_constructor.sv | 26 + .../repros/sv_foreign_generic_defaults.sv | 35 ++ .../repros/sv_foreign_generic_factory.sv | 42 ++ .../repros/sv_foreign_generic_inheritance.sv | 29 + .../repros/sv_foreign_generic_nominal.sv | 13 + .../repros/sv_foreign_generic_package_type.sv | 27 + .../verification/sv/icarus/class.json | 110 ++++ .../verification/sv/verilator/class.json | 99 ++++ .../verification/sv/xezim/class.json | 99 ++++ .../verification/xezim-review.json | 64 +++ .../tests/frontends/systemverilog/class.rs | 201 ++++++- docs/guide/systemverilog-reference.md | 21 +- docs/ja/guide/systemverilog-reference.md | 6 +- scripts/check-external-suite-report.test.mjs | 14 + 34 files changed, 2605 insertions(+), 169 deletions(-) create mode 100644 crates/celox-sv-analyzer/src/ast/classes/foreign.rs create mode 100644 crates/celox-test-suite/verification/repros/sv_foreign_generic.json create mode 100644 crates/celox-test-suite/verification/repros/sv_foreign_generic_constructor.sv create mode 100644 crates/celox-test-suite/verification/repros/sv_foreign_generic_defaults.sv create mode 100644 crates/celox-test-suite/verification/repros/sv_foreign_generic_factory.sv create mode 100644 crates/celox-test-suite/verification/repros/sv_foreign_generic_inheritance.sv create mode 100644 crates/celox-test-suite/verification/repros/sv_foreign_generic_nominal.sv create mode 100644 crates/celox-test-suite/verification/repros/sv_foreign_generic_package_type.sv diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 3d2e810cfc2..3c612ac960b 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -936,7 +936,8 @@ fn lower_package_states( ff_parts: bool, warnings: &mut Vec, ) -> Result, sv::AnalyzerError> { - let mut states = packages.state_modules().collect::>(); + let states = packages.specialized_state_modules(); + let mut states = states.iter().collect::>(); states.sort_by(|left, right| left.name().cmp(right.name())); states .into_iter() diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index e6b88f385ae..eda915e84b5 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -21,6 +21,10 @@ use crate::source_tree::SourceTree as SyntaxTree; #[derive(Default)] pub(super) struct AnalysisState { pub(crate) const_functions: const_functions::State, + foreign: std::rc::Rc, + foreign_arguments: RefCell>, + foreign_names: RefCell>, + foreign_error: RefCell>, scope: scope::State, interfaces: interface_ast::State, dimensions: dimensions::State, @@ -93,6 +97,7 @@ impl<'a> AnalysisContext<'a> { syntax_tree, state: std::rc::Rc::new(AnalysisState { next_call_site: packages.call_sites.clone(), + foreign: packages.foreign.clone(), ..AnalysisState::default() }), parameter_overrides: Cow::Owned(HashMap::default()), @@ -696,6 +701,49 @@ impl Module { imported: Arc, export_symbols: bool, header_ports: Option<&port_owners::Selection<'_>>, + ) -> Result { + let registry = syntax_tree.state.foreign.clone(); + for _ in 0..1024 { + let revision = registry.revision(); + let mut symbols = (*imported).clone(); + registry.extend(syntax_tree, &mut symbols); + let declarations_only = symbols.declarations_only; + let result = Self::from_selected_scope_once( + syntax_tree, + override_module_name, + parameter_overrides, + interfaces, + Arc::new(symbols), + export_symbols || registry.has_templates(), + header_ports, + ); + if let Ok(module) = &result + && !declarations_only + && let Some(symbols) = &module.symbols + { + registry.finish(syntax_tree, symbols)?; + } + if registry.revision() == revision { + return result; + } + syntax_tree.state.classes.borrow_mut().clear(); + syntax_tree.state.class_specializations.borrow_mut().clear(); + syntax_tree.state.foreign_error.borrow_mut().take(); + syntax_tree.state.foreign_names.borrow_mut().clear(); + } + Err(unsupported( + "foreign class specialization discovery did not converge", + )) + } + + fn from_selected_scope_once( + syntax_tree: &AnalysisContext<'_>, + override_module_name: &str, + parameter_overrides: &HashMap, + interfaces: &InterfaceLookup<'_>, + imported: Arc, + export_symbols: bool, + header_ports: Option<&port_owners::Selection<'_>>, ) -> Result { // The scope makes its class specializations until its class methods // have signatures. diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index 2b4716c8a28..415e4f13829 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -13,6 +13,7 @@ use super::*; use crate::system_functions::{HandleProperty, ObjectField, ObjectOp}; pub(super) mod constraints; +pub(super) mod foreign; pub(super) mod specializations; /// Bit width of a handle, see `celox_design::HANDLE_WIDTH`. @@ -371,7 +372,12 @@ pub(super) fn declared_name( instances::normalize_identifier(&unit.name.spelling) ), Some(_) => name, - None => format!("{}::{name}", packages::UNIT), + None => { + use std::hash::{Hash, Hasher}; + let mut hasher = fxhash::FxHasher::default(); + tree.compilation_path().hash(&mut hasher); + format!("{}::{name}@{:016x}", packages::UNIT, hasher.finish()) + } } } @@ -435,9 +441,15 @@ pub(super) fn scope_class_types(tree: &AnalysisContext<'_>) -> Vec<(String, Type /// declares (IEEE 1800-2023 3.12.1). Classes of packages are seen through /// imports, as types. pub(super) fn resolve(tree: &AnalysisContext<'_>, name: &str) -> Option { + if tree.state.foreign.contains(name) { + return Some(name.to_owned()); + } let native = tree.declarations(); let scope = tree.root_unit().ok().map(|unit| unit.tokens); let mut unit_class = None; + let package_scope = tree + .root_unit() + .is_ok_and(|unit| unit.kind == celox_sv_syntax::UnitKind::Package); for class in &native.classes { if instances::normalize_identifier(&class.name.spelling) != name { continue; @@ -446,25 +458,35 @@ pub(super) fn resolve(tree: &AnalysisContext<'_>, name: &str) -> Option if enclosing == scope { return Some(declared_name(tree, class)); } - if enclosing.is_none() { + if enclosing.is_none() && !package_scope { unit_class = Some(declared_name(tree, class)); } } // A class an import makes visible (IEEE 1800-2023 26.3). let imported = scope::imported(&tree.state); - if let Some(class) = imported.aliases.get(name) - && imported.classes.iter().any(|known| &known.name == class) - { - return Some(class.clone()); + if let Some(alias) = imported.aliases.get(name) { + let class = imported + .type_aliases + .get(alias) + .and_then(Type::class) + .unwrap_or(alias); + if imported.classes.iter().any(|known| known.name == class) + || tree.state.foreign.contains(class) + { + return Some(class.to_owned()); + } } unit_class .or_else(|| { - let class = format!("{}::{name}", packages::UNIT); + if package_scope { + return None; + } + let alias = format!("{}::{name}", packages::UNIT); imported - .classes - .iter() - .any(|known| known.name == class) - .then_some(class) + .type_aliases + .get(&alias) + .and_then(Type::class) + .map(str::to_owned) }) .or_else(|| (name == "process").then(|| super::processes::CLASS.to_owned())) } @@ -495,6 +517,7 @@ pub(super) fn is_interface(tree: &AnalysisContext<'_>, name: &str) -> bool { /// 1800-2023 8.25). pub(super) fn is_parameterized(tree: &AnalysisContext<'_>, name: &str) -> bool { declaration(tree, name).is_some_and(|class| class.parameter_ports.is_some()) + || tree.state.foreign.contains(name) } /// The classes and interface classes that body item `item` declares: of a @@ -912,7 +935,7 @@ pub(super) fn class( } let class = Rc::new(Class { name: name.to_owned(), - id: class_id(tree, name), + id: class_id(name), constraints, has_constraints: declaration.has_constraints || base.as_ref().is_some_and(|base| base.has_constraints), @@ -1033,7 +1056,7 @@ fn interface_class( } let class = Rc::new(Class { name: name.to_owned(), - id: class_id(tree, name), + id: class_id(name), base: None, interfaces, is_abstract: true, @@ -1176,30 +1199,11 @@ fn field( /// A run-time identifier of class `name`: an FNV-1a hash, never 0, which /// `null` reads as. -fn class_id(tree: &AnalysisContext<'_>, name: &str) -> u32 { - // Classes of the compilation units of two sources may share a name; the - // path of the source tells them apart (IEEE 1800-2023 3.12.1). - let source = name - .starts_with(&format!("{}::", packages::UNIT)) - .then(|| { - let native = tree.declarations(); - native.tokens.first().map(|token| { - native - .sources - .file(token.origin.spelling.file) - .path - .display() - .to_string() - }) - }) - .flatten() - .unwrap_or_default(); - let hash = name - .bytes() - .chain(source.bytes()) - .fold(0x811c_9dc5u32, |hash, byte| { - (hash ^ u32::from(byte)).wrapping_mul(0x0100_0193) - }); +fn class_id(name: &str) -> u32 { + // Compilation-unit declaration names already contain their source identity. + let hash = name.bytes().fold(0x811c_9dc5u32, |hash, byte| { + (hash ^ u32::from(byte)).wrapping_mul(0x0100_0193) + }); hash.max(1) } diff --git a/crates/celox-sv-analyzer/src/ast/classes/foreign.rs b/crates/celox-sv-analyzer/src/ast/classes/foreign.rs new file mode 100644 index 00000000000..2438014ab36 --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/classes/foreign.rs @@ -0,0 +1,514 @@ +//! Package class templates instantiated by scopes that use the package. +use super::*; +use crate::ast::scope::ScopeSymbols; +use specializations::BoundArguments; +use std::cell::{Cell, RefCell}; + +#[derive(Debug)] +struct Owner { + tree: Rc, + imports: ScopeSymbols, + calls: Rc>, + timescales: Arc, +} + +#[derive(Clone, Debug)] +struct Request { + generic: String, + arguments: BoundArguments, + name: Option, +} + +/// Bound declarations inherited from a class, excluding its enclosing package. +#[derive(Clone, Debug, Default)] +pub(in crate::ast) struct DeclarationScope { + pub env: HashMap>, + pub types: HashMap, + pub literals: HashMap, +} + +impl DeclarationScope { + pub fn apply(&self, env: &mut HashMap, types: &mut HashMap) { + for (name, value) in &self.env { + match value { + Some(value) => { + env.insert(name.clone(), *value); + } + None => { + env.remove(name); + } + } + } + types.extend(self.types.clone()); + } +} + +#[derive(Debug, Default)] +pub(in crate::ast) struct Registry { + owners: RefCell>>, + templates: RefCell>, + requests: RefCell>>, + prepared: RefCell>, + complete: RefCell>, + argument_symbols: RefCell, + active: RefCell>, + states: RefCell>, + revision: Cell, + generics: RefCell>, + declarations: RefCell>>, +} + +impl Registry { + pub fn revision(&self) -> u64 { + self.revision.get() + } + pub fn has_templates(&self) -> bool { + !self.templates.borrow().is_empty() + } + pub fn generic(&self, name: &str) -> Option { + self.generics.borrow().get(name).cloned() + } + pub fn parameter(&self, name: &str, parameter: &str) -> Option { + self.declarations + .borrow() + .get(name)? + .literals + .get(parameter) + .cloned() + } + pub fn declarations(&self, name: &str) -> Option> { + self.declarations.borrow().get(name).cloned() + } + pub fn member_type(&self, name: &str, member: &str) -> Option { + self.prepared + .borrow() + .values() + .find_map(|symbols| symbols.class_member_types.get(name)?.get(member).cloned()) + } + pub fn names(&self) -> Vec { + self.templates.borrow().keys().cloned().collect() + } + pub fn contains(&self, name: &str) -> bool { + self.templates.borrow().contains_key(name) + } + pub fn register( + &self, + name: &str, + tree: &SyntaxTree, + imports: &ScopeSymbols, + calls: Rc>, + timescales: Arc, + ) { + if self.owners.borrow().contains_key(name) { + return; + } + let scope = tree.root_unit().ok().map(|unit| unit.tokens); + for declaration in &tree.declarations().classes { + if declaration.parameter_ports.is_some() + && enclosing_unit(tree.declarations(), declaration.tokens).map(|unit| unit.tokens) + == scope + { + self.templates.borrow_mut().insert( + format!( + "{}::{}", + name, + instances::normalize_identifier(&declaration.name.spelling) + ), + name.to_owned(), + ); + } + } + self.owners.borrow_mut().insert( + name.into(), + Rc::new(Owner { + tree: Rc::new(tree.clone()), + imports: imports.clone(), + calls, + timescales, + }), + ); + } + pub fn extend(&self, tree: &AnalysisContext<'_>, symbols: &mut ScopeSymbols) { + let local_classes = scope_declarations(tree) + .map(|class| declared_name(tree, class)) + .collect::>(); + for (owner, extra) in self.prepared.borrow().iter() { + if self.active.borrow().contains(owner) { + continue; + } + // An owner may import a caller's static field while binding T's + // methods. Returning those symbols to the caller must not redeclare + // storage that the caller's own class declarations already supply. + let local_storage = extra + .signals + .iter() + .chain(&extra.state_signals) + .filter(|signal| { + local_classes.iter().any(|class| { + signal.name().strip_prefix(class).is_some_and(|suffix| { + suffix.starts_with("::") || suffix.starts_with("#(") + }) + }) + }) + .map(|signal| signal.name().to_owned()) + .collect::>(); + let declarations_only = symbols.declarations_only; + if local_storage.is_empty() { + symbols.extend(extra); + } else { + symbols.extend(&extra.clone().without(&local_storage)); + } + symbols.declarations_only = declarations_only; + } + } + pub fn states(&self) -> HashMap { + self.states.borrow().clone() + } + + pub fn request( + self: &Rc, + tree: &AnalysisContext<'_>, + generic: &str, + arguments: &[celox_sv_syntax::Argument], + context: &PackedDimensions, + ) -> Converted> { + let Some(owner_name) = self.templates.borrow().get(generic).cloned() else { + return Ok(None); + }; + let owner = self.owners.borrow()[&owner_name].clone(); + let native = owner.tree.declarations(); + // The source can declare classes of the same name in other scopes; + // the template is the one the owner package declares, as `register` + // found it. + let scope = owner.tree.root_unit().ok().map(|unit| unit.tokens); + let declaration = native + .classes + .iter() + .find(|class| { + enclosing_unit(native, class.tokens).map(|unit| unit.tokens) == scope + && format!( + "{}::{}", + owner_name, + instances::normalize_identifier(&class.name.spelling) + ) == generic + }) + .ok_or_else(|| unsupported(format!("class template `{generic}`")))?; + let Some(arguments) = specializations::bind_arguments( + tree, + generic, + declaration, + native, + arguments, + context, + )? + else { + return Ok(None); + }; + // Module-local class names do not yet carry instance identity. They + // cannot safely key a design-wide package specialization (8.25). + fn module_class<'a>(tree: &AnalysisContext<'_>, ty: &'a Type) -> Option<&'a str> { + ty.class() + .filter(|class| { + !class.contains("::") + || super::declaration(tree, class).is_some_and(|declaration| { + enclosing_unit(tree.declarations(), declaration.tokens) + .is_some_and(|unit| unit.kind != celox_sv_syntax::UnitKind::Package) + }) + }) + .or_else(|| { + let container = ty.container.as_ref()?; + module_class(tree, &container.element).or_else(|| { + container + .key + .as_ref() + .and_then(|key| module_class(tree, key)) + }) + }) + } + if let Some(class) = arguments + .types + .values() + .find_map(|ty| module_class(tree, ty)) + { + return Err(unsupported(format!( + "module-local class `{class}` as a package class type argument" + ))); + } + let index = { + let mut requests = self.requests.borrow_mut(); + let requests = requests.entry(owner_name.clone()).or_default(); + match requests + .iter() + .position(|r| r.generic == generic && r.arguments == arguments) + { + Some(index) => index, + None => { + if requests.len() >= 1024 { + return Err(unsupported("more than 1024 foreign class specializations")); + } + requests.push(Request { + generic: generic.into(), + arguments, + name: None, + }); + self.complete.borrow_mut().remove(&owner_name); + requests.len() - 1 + } + } + }; + if self.requests.borrow()[&owner_name][index].name.is_none() { + self.build(&owner_name, None)?; + } + Ok(self.requests.borrow()[&owner_name][index].name.clone()) + } + + fn build(self: &Rc, name: &str, caller: Option<&ScopeSymbols>) -> Converted<()> { + if self.active.borrow().len() >= 16 { + return Err(unsupported("foreign class scopes nested more than 16 deep")); + } + if !self.active.borrow_mut().insert(name.into()) { + return Ok(()); + } + let result = self.build_inner(name, caller); + self.active.borrow_mut().remove(name); + result + } + fn build_inner(self: &Rc, name: &str, caller: Option<&ScopeSymbols>) -> Converted<()> { + let owner = self.owners.borrow()[name].clone(); + let requests = self.requests.borrow()[name].clone(); + let state = Rc::new(AnalysisState { + foreign: self.clone(), + next_call_site: owner.calls.clone(), + foreign_arguments: RefCell::new( + requests + .iter() + .map(|r| (r.generic.clone(), r.arguments.clone())) + .collect(), + ), + ..Default::default() + }); + let context = AnalysisContext { + syntax_tree: &owner.tree, + state: state.clone(), + parameter_overrides: Cow::Owned(HashMap::default()), + }; + let _timescales = + timescales::install_for_tree(&state.timescales, owner.timescales.clone(), &owner.tree)?; + let _package = scope::enter_package(&state, name); + let mut imports = owner.imports.clone(); + if let Some(caller) = caller { + // Preserve the owner's existing bindings when caller metadata also + // contains imported classes or routines from that package. + imports.extend(&ScopeSymbols { + classes: caller.classes.clone(), + class_member_types: caller.class_member_types.clone(), + state_signals: caller + .state_signals + .iter() + .filter(|signal| { + !signal.name().starts_with(&format!("{name}::")) + && signal + .package_variable + .as_ref() + .is_none_or(|(owner, _)| owner != name) + }) + .cloned() + .collect(), + // Only qualified routines, the methods of classes the actual + // type arguments name: a body of the package resolves an + // unqualified call in its own scope, not the caller's (26.3). + subroutine_params: qualified(&caller.subroutine_params), + subroutine_shapes: qualified(&caller.subroutine_shapes), + subroutines: caller + .subroutines + .iter() + .filter(|subroutine| subroutine.name.contains("::")) + .cloned() + .collect(), + function_return_types: qualified(&caller.function_return_types), + ..Default::default() + }); + } else { + imports.declarations_only = true; + } + let self_qualified = imports::ScopeImports::from_scope(&context)? + .qualified + .iter() + .any(|(package, _)| package == name); + let mut package = packages::analyze_package_with_symbols( + name, + &context, + imports.clone(), + HashMap::default(), + None, + )?; + if self_qualified { + drop(_package); + // Class statics already have qualified names. Unlike ordinary + // package variables, their new declarations would collide with + // the first pass's imported storage. + let statics = package + .symbols + .classes + .iter() + .flat_map(|class| class.statics.iter()) + .filter(|property| property.owner.starts_with(&format!("{name}::"))) + .map(|property| property.variable.clone()) + .collect(); + let own_items = package.symbols.clone().without(&statics); + package = packages::analyze_package_with_symbols( + name, + &context, + imports, + HashMap::default(), + Some(&own_items), + )?; + } + if let Some(error) = state.foreign_error.borrow_mut().take() { + return Err(error); + } + let mut symbols = package.symbols; + symbols.aliases.clear(); + symbols.declarations_only = false; + for request in self.requests.borrow_mut().get_mut(name).unwrap() { + if let Some((_, _, bound)) = + state + .foreign_names + .borrow() + .iter() + .find(|(generic, arguments, _)| { + generic == &request.generic && arguments == &request.arguments + }) + { + request.name = Some(bound.clone()); + } + } + for (class, specialization) in state.class_specializations.borrow().iter() { + self.generics + .borrow_mut() + .insert(class.clone(), specialization.generic.clone()); + } + let declarations = + specializations::export_declarations(&context, &symbols.class_member_types); + self.declarations.borrow_mut().extend(declarations); + self.prepared.borrow_mut().insert(name.into(), symbols); + if caller.is_some() { + self.complete.borrow_mut().insert(name.into()); + if let Some(module) = package.state_module { + self.states.borrow_mut().insert(name.into(), module); + } + } + self.revision.set(self.revision.get() + 1); + Ok(()) + } + pub fn finish( + self: &Rc, + tree: &AnalysisContext<'_>, + caller: &ScopeSymbols, + ) -> Converted<()> { + let declarations = specializations::export_declarations(tree, &caller.class_member_types); + self.declarations.borrow_mut().extend(declarations); + let package_owner = match tree.root_unit() { + Ok(unit) if unit.kind == celox_sv_syntax::UnitKind::Package => { + Some(instances::normalize_identifier(&unit.name.spelling)) + } + Err(_) => Some(packages::UNIT.to_owned()), + _ => None, + }; + { + let mut known = self.argument_symbols.borrow_mut(); + known + .class_member_types + .extend(caller.class_member_types.clone()); + let variables = caller + .classes + .iter() + .flat_map(|class| { + class + .statics + .iter() + .map(|property| property.variable.as_str()) + }) + .collect::>(); + for signal in caller + .signals + .iter() + .chain(&caller.state_signals) + .filter(|signal| variables.contains(signal.name())) + { + if !known + .state_signals + .iter() + .any(|old| old.name == signal.name) + { + let mut signal = signal.clone(); + if signal.package_variable.is_none() + && let Some(owner) = &package_owner + { + signal.package_variable = Some((owner.clone(), signal.name().into())); + } + known.state_signals.push(signal); + } + } + + for class in &caller.classes { + if !known.classes.iter().any(|old| old.name == class.name) { + known.classes.push(class.clone()); + } + } + known + .subroutine_params + .extend(caller.subroutine_params.clone()); + known + .subroutine_shapes + .extend(caller.subroutine_shapes.clone()); + for subroutine in &caller.subroutines { + if !known + .subroutines + .iter() + .any(|old| old.name == subroutine.name) + { + known.subroutines.push(subroutine.clone()); + } + } + known + .function_return_types + .extend(caller.function_return_types.clone()); + } + let caller = self.argument_symbols.borrow().clone(); + let names = self + .requests + .borrow() + .keys() + .filter(|name| { + !self.complete.borrow().contains(*name) && !self.active.borrow().contains(*name) + }) + .cloned() + .collect::>(); + for name in names { + self.build(&name, Some(&caller))?; + } + Ok(()) + } +} + +pub(in crate::ast) fn is_foreign(tree: &AnalysisContext<'_>, generic: &str) -> bool { + let registry = &tree.state.foreign; + let Some(owner) = registry.templates.borrow().get(generic).cloned() else { + return false; + }; + tree.root_unit() + .ok() + .map(|unit| instances::normalize_identifier(&unit.name.spelling)) + .as_deref() + != Some(owner.as_str()) +} + +/// The entries of `table` with qualified names, `scope::name`. +fn qualified(table: &HashMap) -> HashMap { + table + .iter() + .filter(|(name, _)| name.contains("::")) + .map(|(name, value)| (name.clone(), value.clone())) + .collect() +} diff --git a/crates/celox-sv-analyzer/src/ast/classes/specializations.rs b/crates/celox-sv-analyzer/src/ast/classes/specializations.rs index cc439b434e5..db7cf8f1a84 100644 --- a/crates/celox-sv-analyzer/src/ast/classes/specializations.rs +++ b/crates/celox-sv-analyzer/src/ast/classes/specializations.rs @@ -132,7 +132,12 @@ pub(in crate::ast) fn lookup(tree: &AnalysisContext<'_>, name: &str) -> Option, name: &str) -> String { lookup(tree, name).map_or_else( - || name.to_owned(), + || { + tree.state + .foreign + .generic(name) + .unwrap_or_else(|| name.to_owned()) + }, |specialization| specialization.generic.clone(), ) } @@ -173,6 +178,13 @@ pub(in crate::ast) fn shared_scope( let mut aliases = aliases.clone(); let own = generic(tree, name); for specialization in lineage(tree, name) { + for base in &specialization.bases { + if lookup(tree, base).is_none() + && let Some(scope) = tree.state.foreign.declarations(base) + { + scope.apply(&mut env, &mut aliases); + } + } if !specialization.env.is_empty() || !specialization.hidden.is_empty() { env.extend(specialization.env.clone()); for key in &specialization.hidden { @@ -197,10 +209,13 @@ fn inherit( env: &mut HashMap, aliases: &mut HashMap, ) { - if lookup(tree, name).is_none() - && let Some(members) = scope::imported(&tree.state).class_member_types.get(name) - { - aliases.extend(members.clone()); + if lookup(tree, name).is_none() { + if let Some(scope) = tree.state.foreign.declarations(name) { + scope.apply(env, aliases); + } + if let Some(members) = scope::imported(&tree.state).class_member_types.get(name) { + aliases.extend(members.clone()); + } } for specialization in lineage(tree, name) { for (key, value) in &specialization.declared_env { @@ -233,6 +248,14 @@ pub(in crate::ast) fn body_scope( let mut literals = literals.clone(); let own = generic(tree, name); for specialization in lineage(tree, name) { + for base in &specialization.bases { + if lookup(tree, base).is_none() + && let Some(scope) = tree.state.foreign.declarations(base) + { + scope.apply(&mut dimensions.const_env, &mut dimensions.type_aliases); + literals.extend(scope.literals.clone()); + } + } dimensions.const_env.extend(specialization.env.clone()); for key in &specialization.hidden { dimensions.const_env.remove(key); @@ -254,7 +277,55 @@ pub(in crate::ast) fn parameter( lineage(tree, name) .iter() .rev() - .find_map(|specialization| specialization.literals.get(parameter).cloned()) + .find_map(|specialization| { + specialization.literals.get(parameter).cloned().or_else(|| { + specialization + .bases + .iter() + .filter(|base| lookup(tree, base).is_none()) + .find_map(|base| tree.state.foreign.parameter(base, parameter)) + }) + }) + .or_else(|| tree.state.foreign.parameter(name, parameter)) +} + +pub(in crate::ast) fn export_declarations( + tree: &AnalysisContext<'_>, + members: &HashMap>, +) -> HashMap> { + // Only compilation-unit and package declarations have a design-wide name. + if tree + .root_unit() + .is_ok_and(|unit| unit.kind != celox_sv_syntax::UnitKind::Package) + { + return HashMap::default(); + } + let own = super::scope_declarations(tree) + .map(|class| super::declared_name(tree, class)) + .collect::>(); + tree.state + .class_specializations + .borrow() + .iter() + .filter(|(_, specialization)| own.contains(&specialization.generic)) + .map(|(name, _)| { + let mut scope = super::foreign::DeclarationScope::default(); + for specialization in lineage(tree, name) { + for base in &specialization.bases { + if lookup(tree, base).is_none() + && let Some(parent) = tree.state.foreign.declarations(base) + { + scope.env.extend(parent.env.clone()); + scope.literals.extend(parent.literals.clone()); + } + } + scope.env.extend(specialization.declared_env.clone()); + scope.literals.extend(specialization.literals.clone()); + } + scope.types = members.get(name).cloned().unwrap_or_default(); + (name.clone(), Rc::new(scope)) + }) + .collect() } /// The type parameter or typedef `member` of class `name`, declared in it @@ -284,6 +355,7 @@ pub(in crate::ast) fn member_type( .get(member) .cloned() }) + .or_else(|| tree.state.foreign.member_type(name, member)) } /// Only types declared by a class and its bases cross the scope boundary. @@ -375,6 +447,18 @@ fn bind_specialization( } depth.set(depth.get() + 1); let _nesting = Nesting(depth); + if super::foreign::is_foreign(tree, generic) { + return Ok( + match tree + .state + .foreign + .request(tree, generic, arguments, context)? + { + Some(name) => Binding::Ready(name), + None => Binding::Deferred(unsupported("class type parameter value")), + }, + ); + } // Parameter binding and body construction have large temporary values. // Keep those phases off the stack while resolving an inherited class. let pending = match prepare(tree, generic, arguments, context)? { @@ -404,29 +488,37 @@ enum Preparation { Pending(Box), } -// These boundaries keep the recursive inheritance frame small in debug and -// optimized builds alike; the specialization limit must produce a diagnostic -// before the host thread runs out of stack. -#[inline(never)] -fn prepare( +#[derive(Clone, Debug, Default)] +pub(in crate::ast) struct BoundArguments { + pub values: HashMap, + pub types: HashMap, +} + +// Ordinary type equality ignores nominal declaration identity; specialization +// matching must distinguish separately declared enum and aggregate types (8.25). +impl PartialEq for BoundArguments { + fn eq(&self, other: &Self) -> bool { + self.values == other.values + && self.types.len() == other.types.len() + && self.types.iter().all(|(name, ty)| { + other + .types + .get(name) + .is_some_and(|other| spelling(ty) == spelling(other)) + }) + } +} + +impl Eq for BoundArguments {} + +pub(in crate::ast) fn bind_arguments( tree: &AnalysisContext<'_>, generic: &str, + declaration: &celox_sv_syntax::ClassDeclaration, + native: &celox_sv_syntax::Declarations, arguments: &[Argument], context: &PackedDimensions, -) -> Converted { - let native = tree.declarations(); - let declaration = super::declaration(tree, generic) - .ok_or_else(|| unsupported(format!("class `{generic}`")))?; - if tree - .state - .class_declarations_repeated - .borrow() - .contains(generic) - { - return Err(unsupported(format!( - "class `{generic}` declared in a loop generate block" - ))); - } +) -> Converted> { // The parameters an assignment may set: those of the parameter port // list that are not local, in order. let ports = declaration @@ -479,9 +571,7 @@ fn prepare( types.insert(name, ty); } None => { - return Ok(Preparation::Deferred(unsupported( - "class type parameter value", - ))); + return Ok(None); } }, ParameterKind::Value { .. } => { @@ -489,6 +579,50 @@ fn prepare( } } } + Ok(Some(BoundArguments { values, types })) +} + +// These boundaries keep the recursive inheritance frame small in debug and +// optimized builds alike; the specialization limit must produce a diagnostic +// before the host thread runs out of stack. +#[inline(never)] +fn prepare( + tree: &AnalysisContext<'_>, + generic: &str, + arguments: &[Argument], + context: &PackedDimensions, +) -> Converted { + let native = tree.declarations(); + let declaration = super::declaration(tree, generic) + .ok_or_else(|| unsupported(format!("class `{generic}`")))?; + if tree + .state + .class_declarations_repeated + .borrow() + .contains(generic) + { + return Err(unsupported(format!( + "class `{generic}` declared in a loop generate block" + ))); + } + let Some(arguments) = bind_arguments(tree, generic, declaration, native, arguments, context)? + else { + return Ok(Preparation::Deferred(unsupported( + "class type parameter value", + ))); + }; + prepare_bound(tree, generic, arguments, context) +} + +fn prepare_bound( + tree: &AnalysisContext<'_>, + generic: &str, + arguments: BoundArguments, + context: &PackedDimensions, +) -> Converted { + let declaration = super::declaration(tree, generic) + .ok_or_else(|| unsupported(format!("class `{generic}`")))?; + let BoundArguments { values, types } = arguments; // The declarations of the class are bound in the scope that declares it, // the actuals in the scope that names the specialization. let (mut env, mut aliases) = declaration_scope(tree, generic).unwrap_or_else(|| { @@ -873,21 +1007,10 @@ fn type_argument( }, } } - ExprKind::Parameterized { - expression, - arguments, - } => match &native.expression(*expression).kind { - ExprKind::Name(name) => { - match super::resolve(tree, &instances::normalize_identifier(&name.spelling)) { - Some(name) => { - let name = specialize(tree, &name, arguments, context)?; - Some(super::handle(&name)) - } - None => None, - } - } - _ => None, - }, + ExprKind::Parameterized { .. } => { + expression_binding::named_class(tree, id, native, context)? + .map(|name| super::handle(&name)) + } // A type of a class, `C::T` or `C#(...)::T`, or of a package // (IEEE 1800-2023 8.23, 26.3). ExprKind::Member { @@ -926,21 +1049,9 @@ fn type_argument( ); } } - ExprKind::Parameterized { - expression, - arguments, - } => match &native.expression(*expression).kind { - ExprKind::Name(scope) => { - match super::resolve( - tree, - &instances::normalize_identifier(&scope.spelling), - ) { - Some(class) => Some(specialize(tree, &class, arguments, context)?), - None => None, - } - } - _ => None, - }, + ExprKind::Parameterized { .. } => { + expression_binding::named_class(tree, *expression, native, context)? + } _ => None, }; class.and_then(|class: String| member_type(tree, &class, &member)) @@ -1023,18 +1134,28 @@ fn value_argument( /// A spelling of type `ty` that tells it apart from other types, for the /// name of a specialization. fn spelling(ty: &Type) -> String { - let mut spelled = match (ty.class(), ty.kind()) { - (Some(class), _) => class.to_owned(), - (None, TypeKind::Real) => "real".to_owned(), - (None, TypeKind::Shortreal) => "shortreal".to_owned(), - (None, TypeKind::String) => "string".to_owned(), - (None, TypeKind::Object) => "object".to_owned(), - (None, TypeKind::Process) => "process".to_owned(), - (None, TypeKind::Bit) => "bit".to_owned(), - // `reg` is `logic` (6.11.2). - (None, TypeKind::Logic | TypeKind::Implicit | TypeKind::Reg) => "logic".to_owned(), + let mut spelled = if let Some(container) = &ty.container { + format!( + "container({:?},{},{})", + container.layout, + spelling(&container.element), + container.key.as_ref().map(spelling).unwrap_or_default() + ) + } else { + match (ty.class(), ty.kind()) { + (Some(class), _) => class.to_owned(), + (None, TypeKind::Real) => "real".to_owned(), + (None, TypeKind::Shortreal) => "shortreal".to_owned(), + (None, TypeKind::String) => "string".to_owned(), + (None, TypeKind::Object) => "object".to_owned(), + (None, TypeKind::Process) => "process".to_owned(), + (None, TypeKind::Bit) => "bit".to_owned(), + // `reg` is `logic` (6.11.2). + (None, TypeKind::Logic | TypeKind::Implicit | TypeKind::Reg) => "logic".to_owned(), + } }; - let integral = ty.class().is_none() + let integral = ty.container.is_none() + && ty.class().is_none() && !matches!( ty.kind(), TypeKind::Real @@ -1089,6 +1210,42 @@ fn spelling(ty: &Type) -> String { /// new specialization appears. pub(in crate::ast) fn collect(tree: &AnalysisContext<'_>, context: &PackedDimensions) { tree.state.class_specializations_frozen.set(false); + for (generic, arguments) in tree.state.foreign_arguments.borrow().clone() { + let pending = match prepare_bound(tree, &generic, arguments.clone(), context) { + Ok(Preparation::Pending(pending)) => pending, + Ok(Preparation::Existing(name)) => { + tree.state + .foreign_names + .borrow_mut() + .push((generic, arguments, name)); + continue; + } + Ok(Preparation::Deferred(error)) | Err(error) => { + *tree.state.foreign_error.borrow_mut() = Some(error); + return; + } + }; + tree.state + .class_specializations_building + .borrow_mut() + .push(pending.name.clone()); + let _building = Building(&tree.state.class_specializations_building); + let result = (|| { + let bases = bind_bases(tree, &generic, &pending.env, &pending.aliases)?; + finish_specialization(tree, &generic, pending, bases) + })(); + match result { + Ok(name) => tree + .state + .foreign_names + .borrow_mut() + .push((generic, arguments, name)), + Err(error) => { + *tree.state.foreign_error.borrow_mut() = Some(error); + return; + } + } + } let native = tree.declarations(); let within = |outer: celox_sv_syntax::TokenRange, inner: celox_sv_syntax::TokenRange| { outer.start <= inner.start && inner.end <= outer.end @@ -1105,11 +1262,8 @@ pub(in crate::ast) fn collect(tree: &AnalysisContext<'_>, context: &PackedDimens .iter() .filter(|class| super::enclosing_unit(native, class.tokens).map(|unit| unit.tokens) == unit) .collect::>(); - if classes.is_empty() { - return; - } // The classes of the scope by the names its declarations use. - let names = classes + let mut names = classes .iter() .map(|class| { ( @@ -1118,6 +1272,14 @@ pub(in crate::ast) fn collect(tree: &AnalysisContext<'_>, context: &PackedDimens ) }) .collect::>(); + for name in tree.state.foreign.names() { + names.entry(name.clone()).or_insert(name); + } + for (alias, name) in &scope::imported(&tree.state).aliases { + if tree.state.foreign.contains(name) { + names.entry(alias.clone()).or_insert(name.clone()); + } + } // The class scopes: each class declaration, and each out-of-block // method definition, which is in the scope of its class (8.24). let mut scopes = classes @@ -1174,6 +1336,29 @@ pub(in crate::ast) fn collect(tree: &AnalysisContext<'_>, context: &PackedDimens } } } + for ty in &native.types { + if !in_scope(ty.tokens) { + continue; + } + if let celox_sv_syntax::DataTypeKind::Named(path) = &ty.kind + && let [package, member] = path.as_slice() + && member.arguments.is_some() + { + let name = format!( + "{}::{}", + instances::normalize_identifier(&package.name.spelling), + instances::normalize_identifier(&member.name.spelling) + ); + if tree.state.foreign.contains(&name) { + references.push(( + enclosing(ty.tokens), + name, + member.arguments.as_deref().unwrap(), + ty.tokens, + )); + } + } + } for expression in &native.expressions { if !in_scope(expression.tokens) { continue; @@ -1182,9 +1367,25 @@ pub(in crate::ast) fn collect(tree: &AnalysisContext<'_>, context: &PackedDimens expression: scope, arguments, } = &expression.kind - && let ExprKind::Name(name) = &native.expression(*scope).kind { - let name = instances::normalize_identifier(&name.spelling); + let name = match &native.expression(*scope).kind { + ExprKind::Name(name) => instances::normalize_identifier(&name.spelling), + ExprKind::Member { + expression, + separator, + name, + } if separator == "::" => { + let ExprKind::Name(package) = &native.expression(*expression).kind else { + continue; + }; + format!( + "{}::{}", + instances::normalize_identifier(&package.spelling), + instances::normalize_identifier(&name.spelling) + ) + } + _ => continue, + }; if let Some(name) = names.get(&name).cloned() { references.push(( enclosing(expression.tokens), diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs index 4e1da8f54a4..375705ca604 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs @@ -993,14 +993,19 @@ pub(in crate::ast) fn query_operand_dimensions_id( // A class's signatures are bound in the scope that declares it, from // that scope's declarations alone, once for all of its queries. let base = context.clone(); - let classes = scope_class_signatures(tree, &frames[0], &key, &base)?; - settle( - &frames, - tree, - &key, - &mut context, - Classes::Published(&classes), - )?; + // Without classes of its own, the scope has no signatures to bind once. + if classes::scope_declarations(tree).next().is_none() { + settle(&frames, tree, &key, &mut context, Classes::Bind)?; + } else { + let classes = scope_class_signatures(tree, &frames[0], &key, &base)?; + settle( + &frames, + tree, + &key, + &mut context, + Classes::Published(&classes), + )?; + } overlay(&mut context, input); if let Some(id) = owners.subroutine { let subroutine = native.subroutine(id); diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding.rs b/crates/celox-sv-analyzer/src/ast/expression_binding.rs index 0f30decf9ce..7eafd04faf6 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding.rs @@ -19,9 +19,9 @@ pub(super) use objects::{ Cast as ObjectCast, Receiver as ObjectReceiver, cast as object_cast, check_access as check_member_access, check_assignment as check_handle_assignment, constraint_mode_call as object_constraint_mode_call, constructor as object_constructor, - method as object_method, native_class as object_native_class, property as object_property, - rand_mode_call as object_rand_mode_call, receiver as object_receiver, - static_property as object_static_property, this as object_this, + method as object_method, named_class, native_class as object_native_class, + property as object_property, rand_mode_call as object_rand_mode_call, + receiver as object_receiver, static_property as object_static_property, this as object_this, }; pub(super) use strings::{ call as string_call, method as string_method, native_string, to_string as string_operand, diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index bbf0009b7b8..d4e7d3694b2 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -68,6 +68,11 @@ pub(super) fn bound_callable_name( if let Some(name) = callable_name(&tree.state, id, native) { return Ok(Some(name)); } + if let Some((name, _, objects::Receiver::Static)) = + objects::method(tree, id, native, dimensions)? + { + return Ok(Some(name)); + } let ExprKind::Member { expression, separator, diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs index 8366951d85e..b55d1eb7f42 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -74,6 +74,31 @@ pub(in crate::ast) fn native_class( return super_class(tree, dimensions); } } + // The receiver of `h.p` is resolved once for both kinds of property, so + // a chain `a.b.c` takes one walk. + if let ExprKind::Member { + expression: receiver, + separator, + name, + } = &expression.kind + && separator == "." + { + let owner = native_class(tree, *receiver, native, dimensions)?; + let member = instances::normalize_identifier(&name.spelling); + let receiver = (!is_super(*receiver, native)).then_some(*receiver); + if let Some((property, _)) = + property_in(tree, dimensions, &owner, &member, receiver).ok()? + { + return property.r#type.class().map(str::to_owned); + } + return class(tree, dimensions, &owner) + .ok()? + .static_property(&member) + .and_then(|property| property.r#type.class().map(str::to_owned)); + } + if let Some(class) = static_property_class(tree, id, native, dimensions).ok()? { + return Some(class); + } let (property, _) = property(tree, id, native, dimensions).ok()??; property.r#type.class().map(str::to_owned) } @@ -136,7 +161,7 @@ fn is_super(id: ExprId, native: &Declarations) -> bool { /// The class that native expression `id` names, as the scope of `C::name`: /// a class, or the specialization that a parameter value assignment or the /// defaults of a parameterized class make (IEEE 1800-2023 8.25.1). -fn named_class( +pub(in crate::ast) fn named_class( tree: &AnalysisContext<'_>, id: ExprId, native: &Declarations, @@ -152,11 +177,20 @@ fn named_class( let ExprKind::Name(package) = &native.expression(*expression).kind else { return Ok(None); }; - let class = scope::qualified_name( - &tree.state, - &instances::normalize_identifier(&package.spelling), - &instances::normalize_identifier(&name.spelling), - ); + let scope_name = instances::normalize_identifier(&package.spelling); + let member_name = instances::normalize_identifier(&name.spelling); + if let Some(scope_class) = dimensions + .type_aliases + .get(&scope_name) + .and_then(|ty| ty.class().map(str::to_owned)) + .or_else(|| classes::resolve(tree, &scope_name)) + && let Some(ty) = + classes::specializations::member_type(tree, &scope_class, &member_name) + && let Some(class) = ty.class() + { + return Ok(Some(class.to_owned())); + } + let class = scope::qualified_name(&tree.state, &scope_name, &member_name); // A typedef of the package may name a class or a specialization. if let Some(aliased) = dimensions .type_aliases @@ -173,17 +207,36 @@ fn named_class( return Ok(classes::resolve(tree, &class) .filter(|class| classes::handle_type(tree, class).is_some())); } - ExprKind::Name(name) => (name, None), + ExprKind::Name(name) => (instances::normalize_identifier(&name.spelling), None), ExprKind::Parameterized { expression, arguments, } => match &native.expression(*expression).kind { - ExprKind::Name(name) => (name, Some(&arguments[..])), + ExprKind::Name(name) => ( + instances::normalize_identifier(&name.spelling), + Some(&arguments[..]), + ), + ExprKind::Member { + expression, + separator, + name, + } if separator == "::" => { + let ExprKind::Name(package) = &native.expression(*expression).kind else { + return Ok(None); + }; + ( + format!( + "{}::{}", + instances::normalize_identifier(&package.spelling), + instances::normalize_identifier(&name.spelling) + ), + Some(&arguments[..]), + ) + } _ => return Ok(None), }, _ => return Ok(None), }; - let name = instances::normalize_identifier(&name.spelling); if dimensions.get(&name).is_some() { return Ok(None); } @@ -363,13 +416,30 @@ pub(in crate::ast) fn property( } _ => return Ok(None), }; + property_in( + tree, + dimensions, + &class_name, + &instances::normalize_identifier(&name.spelling), + receiver, + ) +} + +/// The instance property `name` of class `class_name`, read through +/// `receiver` as [`property`] returns it. +fn property_in( + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, + class_name: &str, + name: &str, + receiver: Option, +) -> Converted)>> { if class_name == super::super::processes::CLASS { return Ok(None); } - let class = class(tree, dimensions, &class_name)?; - let name = instances::normalize_identifier(&name.spelling); - let Some(property) = class.property(&name) else { - if let Some(property) = class.static_property(&name) { + let class = class(tree, dimensions, class_name)?; + let Some(property) = class.property(name) else { + if let Some(property) = class.static_property(name) { check_access( tree, dimensions, diff --git a/crates/celox-sv-analyzer/src/ast/packages.rs b/crates/celox-sv-analyzer/src/ast/packages.rs index c01fe29cae4..1ae22f62700 100644 --- a/crates/celox-sv-analyzer/src/ast/packages.rs +++ b/crates/celox-sv-analyzer/src/ast/packages.rs @@ -1,11 +1,13 @@ //! Packages (IEEE 1800-2023 26) and compilation units (3.12.1). //! -//! A package is analyzed once, after the packages it depends on, with the +//! A package is analyzed after the packages it depends on, with the //! collectors that analyze a module: its declarations form a scope of their //! own. Its symbols are exported under their qualified names `p::x`, with the //! references among them bound to those names (see the `scope` module). A //! module or package that uses packages starts from their symbols, and from -//! an alias for each name its imports bind (see the `imports` module). +//! an alias for each name its imports bind (see the `imports` module). Importing +//! scopes can request additional class specializations; their declarations and +//! bodies are bound in the retained package scope (see `classes::foreign`). //! //! Each source file is a compilation unit of its own. Its declarations //! outside any module or package form the compilation-unit scope `$unit`, @@ -21,6 +23,7 @@ use super::*; /// The analyzed packages of a design. #[derive(Debug, Clone, Default)] pub struct Packages { + pub(super) foreign: std::rc::Rc, /// Source-call identities shared with modules importing these package bodies. pub(super) call_sites: std::rc::Rc>, pub(crate) interface_plan: Arc, @@ -91,7 +94,7 @@ pub(super) struct Package { pub symbols: ScopeSymbols, /// The package as a module, when it has variables: the module the /// package's one instance holds them in. - state_module: Option, + pub(super) state_module: Option, } impl Package { @@ -183,6 +186,28 @@ impl Packages { .filter_map(|package| package.state_module.as_ref()) } + /// Package state after specialization requests made by importing scopes. + pub fn specialized_state_modules(&self) -> Vec { + let specialized = self.foreign.states(); + // Different compilation units may each have a state module named + // `$unit`; preserve every one rather than indexing them by name. + let mut states = self + .state_modules() + .filter(|module| !specialized.contains_key(module.name())) + .cloned() + .collect::>(); + states.extend(specialized.into_values()); + states.sort_by(|left, right| { + left.name().cmp(right.name()).then_with(|| { + left.signals() + .first() + .map(|signal| signal.name()) + .cmp(&right.signals().first().map(|signal| signal.name())) + }) + }); + states + } + pub(super) fn get(&self, name: &str) -> Option<&Package> { self.packages.get(name).map(|package| &**package) } @@ -338,6 +363,7 @@ impl Packages { } if declarations.is_empty() { return Ok(Self { + foreign: state.foreign.clone(), timescales, ..Self::default() }); @@ -364,6 +390,7 @@ impl Packages { // Package bodies can query selected hierarchy roots while they are // collected, before any module is analyzed. let mut packages = Self { + foreign: state.foreign.clone(), timescales, ..Self::default() }; @@ -497,9 +524,28 @@ fn analyze_package_scope( own_items: Option<&ScopeSymbols>, ) -> Result { let imports::ResolvedImports { - symbols: mut imported, + symbols: imported, exports, } = imports::resolve_imports(tree, packages, None)?; + if own_items.is_none() && name != UNIT { + tree.state.foreign.register( + name, + tree.syntax_tree, + &imported, + tree.state.next_call_site.clone(), + packages.timescales.clone(), + ); + } + analyze_package_with_symbols(name, tree, imported, exports, own_items) +} + +pub(super) fn analyze_package_with_symbols( + name: &str, + tree: &AnalysisContext<'_>, + mut imported: ScopeSymbols, + exports: HashMap, + own_items: Option<&ScopeSymbols>, +) -> Result { if let Some(own_items) = own_items { imported.extend(own_items); } diff --git a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs index 9cfab268185..4ed4a4ae94c 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs @@ -146,6 +146,26 @@ fn bind_in_mode( continue; } } + if let [package, class, member] = path.as_slice() { + let name = scope::qualified_name( + &tree.state, + &normalize_identifier(&package.name.spelling), + &normalize_identifier(&class.name.spelling), + ); + if let Some(class) = + class_scope_named(class, tree, context, mode, name)? + { + let member = normalize_identifier(&member.name.spelling); + let ty = super::super::classes::specializations::member_type( + tree, &class, &member, + ) + .ok_or_else(|| { + unsupported(format!("type `{member}` of class `{class}`")) + })?; + values.push(types::enclose_aliased_packed_type(ty, ranges)); + continue; + } + } // A type that a class declares, `C::T` (IEEE 1800-2023 // 8.23, 8.25.1). if let [scope, member] = path.as_slice() @@ -177,6 +197,25 @@ fn bind_in_mode( )), _ => None, }; + if let Some(class) = class + .as_ref() + .filter(|class| tree.state.foreign.contains(class)) + { + let arguments = path + .last() + .and_then(|part| part.arguments.as_deref()) + .unwrap_or_default(); + let Some(name) = + mode.specialize(tree, class, arguments, context)? + else { + return Ok(None); + }; + values.push(types::enclose_aliased_packed_type( + super::super::classes::handle(&name), + ranges, + )); + continue; + } if let Some(class) = class.filter(|class| { imported .classes @@ -436,7 +475,22 @@ fn class_scope( context: &PackedDimensions, mode: BindingMode, ) -> Converted> { - let name = normalize_identifier(&scope.name.spelling); + class_scope_named( + scope, + tree, + context, + mode, + normalize_identifier(&scope.name.spelling), + ) +} + +fn class_scope_named( + scope: &celox_sv_syntax::TypeSegment, + tree: &AnalysisContext<'_>, + context: &PackedDimensions, + mode: BindingMode, + name: String, +) -> Converted> { if scope.arguments.is_none() && let Some(class) = context .type_aliases diff --git a/crates/celox-sv-analyzer/src/ast/types.rs b/crates/celox-sv-analyzer/src/ast/types.rs index 95e10b03d5f..4f50075f515 100644 --- a/crates/celox-sv-analyzer/src/ast/types.rs +++ b/crates/celox-sv-analyzer/src/ast/types.rs @@ -196,7 +196,14 @@ fn declaration_name( "{}::{name}", instances::normalize_identifier(&unit.name.spelling) ), - None => format!("{}::{name}", packages::UNIT), + // Each source file's compilation unit is a scope of its own, as for + // its classes (IEEE 1800-2023 3.12.1). + None => { + use std::hash::{Hash, Hasher}; + let mut hasher = fxhash::FxHasher::default(); + tree.compilation_path().hash(&mut hasher); + format!("{}::{name}@{:016x}", packages::UNIT, hasher.finish()) + } } } diff --git a/crates/celox-sv-analyzer/src/parsed.rs b/crates/celox-sv-analyzer/src/parsed.rs index 6fff884e774..dca10dceeb5 100644 --- a/crates/celox-sv-analyzer/src/parsed.rs +++ b/crates/celox-sv-analyzer/src/parsed.rs @@ -344,6 +344,23 @@ impl ParsedSource { module_name: &str, overrides: &HashMap, packages: &Packages, + ) -> Result { + self.analyze_module_declarations_with_interfaces( + module_name, + overrides, + &ModuleInterfaces::default(), + packages, + ) + } + + /// Inspect declaration shapes with interfaces of modules in other sources. + /// This retains the metadata-only contract of `analyze_module_declarations`. + pub fn analyze_module_declarations_with_interfaces( + &self, + module_name: &str, + overrides: &HashMap, + interfaces: &ModuleInterfaces, + packages: &Packages, ) -> Result { self.validate_module_namespace(module_name, packages)?; let overrides = overrides @@ -362,7 +379,7 @@ impl ParsedSource { patterns: &[], hierarchical: &[], }, - &ModuleInterfaces::default(), + interfaces, packages, )?; analyze::analyze_source(source) diff --git a/crates/celox-sv-analyzer/src/source_tree.rs b/crates/celox-sv-analyzer/src/source_tree.rs index a4a8acbf6d1..51351ee34e3 100644 --- a/crates/celox-sv-analyzer/src/source_tree.rs +++ b/crates/celox-sv-analyzer/src/source_tree.rs @@ -36,9 +36,13 @@ impl std::ops::DerefMut for Shared { pub(crate) struct SourceTree { declarations: Shared, scope: scopes::View, + compilation_path: std::sync::Arc, } impl SourceTree { + pub(crate) fn compilation_path(&self) -> &Path { + &self.compilation_path + } pub(crate) fn scope_handle(&self) -> ScopeHandle { self.scope.handle } @@ -167,6 +171,7 @@ pub(crate) fn parse_source(code: &str, path: &Path) -> Result Option { let packages = celox_sv_analyzer::ParsedSource::analyze_packages(&sources.iter().collect::>()) .ok()?; + let mut interfaces = celox_sv_analyzer::ModuleInterfaces::default(); + for source in &sources { + interfaces.extend(source.module_interfaces().clone()); + } let mut modules: Vec = Vec::new(); for source in &sources { for name in source.module_names() { @@ -72,9 +76,14 @@ fn analyzed_info(design: &Design) -> Option { Default::default() }; let result = if design.timed { - source.analyze_module_declarations(name, &overrides, &packages) + source.analyze_module_declarations_with_interfaces( + name, + &overrides, + &interfaces, + &packages, + ) } else { - source.analyze_module(name, &overrides, &[], &[], &Default::default(), &packages) + source.analyze_module(name, &overrides, &[], &[], &interfaces, &packages) }; if let Ok(ir) = result { modules.extend(ir.modules().iter().cloned()); @@ -205,3 +214,17 @@ pub fn suite() -> Suite { pub fn run(tool: Tool) -> Result<()> { crate::verification::run(tool, &suite(), &SvFrontend) } + +#[cfg(test)] +mod tests { + #[test] + fn foreign_generic_multisource_case_has_declaration_metadata() { + let case = crate::sv::case("class::foreign_generic_multiple_user_classes").unwrap(); + let info = super::design_info(&case.design()) + .expect("cross-file instances retain their module contracts"); + assert_eq!( + info.outputs, + ["first", "second", "first_count", "second_count"] + ); + } +} diff --git a/crates/celox-test-suite/tests/retained_reports.rs b/crates/celox-test-suite/tests/retained_reports.rs index 2a1f937dece..5745534940c 100644 --- a/crates/celox-test-suite/tests/retained_reports.rs +++ b/crates/celox-test-suite/tests/retained_reports.rs @@ -520,6 +520,58 @@ fn systemverilog_retained_reports_explain_exclusions_and_executed_failures() { "compile", "Overriding the default variable lifetime is not yet supported", ), + ("verilator", "class::foreign_generic_constructor_lexical_scope") => { + ("compile_error", "compile", "FuncRef without fvar") + } + ( + "verilator", + "class::foreign_generic_declaration_scope_and_equivalent_defaults", + ) => ( + "mismatch", + "execute", + "assert_eq checks: expected 0x7f, got 0x5f", + ), + ("verilator", "class::foreign_generic_inherited_constants") => ( + "mismatch", + "execute", + "assert_eq checks: expected 0x1f, got 0x0", + ), + ("verilator", "class::foreign_generic_nominal_and_nested_types") => ( + "compile_error", + "compile", + "Unsupported: Multiple '::' package/class reference", + ), + ("icarus", "class::foreign_generic_constructor_lexical_scope") => { + ("compile_error", "compile", "source_0.sv:5: syntax error") + } + ( + "icarus", + "class::foreign_generic_declaration_scope_and_equivalent_defaults", + ) => ("compile_error", "compile", "source_0.sv:5: syntax error"), + ("icarus", "class::foreign_generic_inherited_constants") => { + ("compile_error", "compile", "source_0.sv:3: syntax error") + } + ("icarus", "class::foreign_generic_multiple_user_classes") => { + ("compile_error", "compile", "source_0.sv:3: syntax error") + } + ("icarus", "class::foreign_generic_nominal_and_nested_types") => { + ("compile_error", "compile", "source_0.sv:3: syntax error") + } + ("icarus", "class::foreign_generic_package_type_static_storage") => { + ("compile_error", "compile", "source_0.sv:10: syntax error") + } + ("icarus", "class::foreign_generic_template_of_the_named_package") => { + ("compile_error", "compile", "source_0.sv:3: syntax error") + } + ("icarus", "class::foreign_generic_static_handle_identity") => { + ("compile_error", "compile", "source_0.sv:11: syntax error") + } + ("icarus", "class::foreign_generic_static_state_across_modules") => { + ("compile_error", "compile", "source_0.sv:3: syntax error") + } + ("icarus", "class::foreign_generic_unit_type_constructor") => { + ("compile_error", "compile", "source_0.sv:3: syntax error") + } _ => panic!("unreviewed failure: {tool} {name}: {status}"), }; assert_eq!(status, expected_status, "{name}"); diff --git a/crates/celox-test-suite/verification/repros/sv_foreign_generic.json b/crates/celox-test-suite/verification/repros/sv_foreign_generic.json new file mode 100644 index 00000000000..bc7e72b28ad --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_foreign_generic.json @@ -0,0 +1,171 @@ +{ + "description": "Adapter-free probes for foreign package-class specialization. Outputs are observed directly, independently of shared-suite assertions. The shared reports retain their own exact failures; these smaller probes may expose a different subset of the same behavior.", + "tools": { + "celox": { + "base_revision": "a037246f79080d37487d12de591e90e9e3923711", + "build": "Working tree implementation of foreign generic package-class specialization." + }, + "verilator": { + "version": "Verilator 5.052 2026-09-05 rev v5.052" + }, + "xezim": { + "version": "xezim version 0.11.3", + "source_revision": "d491f9480123895e064ee4b37173a9d0f5d7383b", + "core_revision": "a25655a4f46dd47f6e9f4612729a725129e6187a", + "dependency_lock_sha256": "00a9cffdf344ecd66f4d7045ac41a8a944357a04a0c18658238bb16678d5cb90", + "build": "Exact repository-pinned upstream sources, built using the existing Nix recipe in an isolated validation package with a regenerated dependency lock. The repository's Nix package lock referenced core 48820a89 instead of the upstream manifest core a25655a4 and could not build. Neither simulator source nor repository lock files were changed. The binary reports git unknown; revision attribution comes from its Nix source inputs." + } + }, + "probes": [ + { + "source": "sv_foreign_generic_defaults.sv", + "source_sha256": "e29342c0a7712141ef8618d29bf061e0fea72fb58fc798b9e58cac39db3b5331", + "top": "Top", + "standard": "IEEE 1800-2023 8.25, 8.26.3", + "expected_output": "OBS checks=127 widths=9,9,5 counts=2,2,1", + "observations": { + "celox_2state": { + "status": "passed", + "output": "OBS checks=127 widths=9,9,5 counts=2,2,1" + }, + "celox_4state": { + "status": "passed", + "output": "OBS checks=127 widths=9,9,5 counts=2,2,1" + }, + "xezim": { + "status": "mismatch", + "output": "OBS checks=111 widths=9,9,5 counts=2,2,1" + }, + "verilator": { + "status": "mismatch", + "output": "OBS checks=95 widths=9,9,5 counts=1,1,1" + } + } + }, + { + "source": "sv_foreign_generic_nominal.sv", + "source_sha256": "73037e360fe34363b1cecac02239aef1570944e715552787f5f8f0a037f61b83", + "top": "Top", + "standard": "IEEE 1800-2023 6.22.1, 8.25", + "expected_output": "OBS nominal=1,2,1", + "observations": { + "celox_2state": { + "status": "passed", + "output": "OBS nominal=1,2,1" + }, + "celox_4state": { + "status": "passed", + "output": "OBS nominal=1,2,1" + }, + "xezim": { + "status": "mismatch", + "output": "OBS nominal=1,1,1" + }, + "verilator": { + "status": "passed", + "output": "OBS nominal=1,2,1" + } + } + }, + { + "source": "sv_foreign_generic_factory.sv", + "source_sha256": "e91831a82ae3f52105cba4097aed133652ae7f344318fb280435bbaf6c861257", + "top": "Observe", + "standard": "IEEE 1800-2023 8.23, 8.25", + "expected_output": "OBS factories=42,73 counts=1,1", + "observations": { + "celox_2state": { + "status": "passed", + "output": "OBS factories=42,73 counts=1,1" + }, + "celox_4state": { + "status": "passed", + "output": "OBS factories=42,73 counts=1,1" + }, + "xezim": { + "status": "mismatch", + "output": "OBS factories=42,42 counts=X,X" + }, + "verilator": { + "status": "passed", + "output": "OBS factories=42,73 counts=1,1" + } + } + }, + { + "source": "sv_foreign_generic_inheritance.sv", + "source_sha256": "4f26b9f8acb55a482ad9928cdecb83a1f9c1668e6217e52f12c21979480d4486", + "top": "Observe", + "standard": "IEEE 1800-2023 8.13, 8.18, 8.25", + "expected_output": "OBS inheritance=31", + "observations": { + "celox_2state": { + "status": "passed", + "output": "OBS inheritance=31" + }, + "celox_4state": { + "status": "passed", + "output": "OBS inheritance=31" + }, + "xezim": { + "status": "mismatch", + "output": "OBS inheritance=23" + }, + "verilator": { + "status": "mismatch", + "output": "OBS inheritance=0" + } + } + }, + { + "source": "sv_foreign_generic_constructor.sv", + "source_sha256": "5c288a86d6e55860ff72c3c5b643d1d46b7321cbe3081ea1f147624615ee3300", + "top": "Observe", + "standard": "IEEE 1800-2023 13.5.3", + "expected_output": "OBS constructor=23,1", + "observations": { + "celox_2state": { + "status": "passed", + "output": "OBS constructor=23,1" + }, + "celox_4state": { + "status": "passed", + "output": "OBS constructor=23,1" + }, + "xezim": { + "status": "mismatch", + "output": "OBS constructor=20,1" + }, + "verilator": { + "status": "compile_error", + "detail": "%Error: Internal Error: crates/celox-test-suite/verification/repros/sv_foreign_generic_constructor.sv:14:11: ../V3Task.cpp:2179: FuncRef without fvar" + } + } + }, + { + "source": "sv_foreign_generic_package_type.sv", + "source_sha256": "8546299af23d61397c759e9f069000f1185c7560d2150de27d9c28b514324e85", + "top": "Observe", + "standard": "IEEE 1800-2023 8.23, 8.25", + "expected_output": "OBS package_type=42,7,1", + "observations": { + "celox_2state": { + "status": "passed", + "output": "OBS package_type=42,7,1" + }, + "celox_4state": { + "status": "passed", + "output": "OBS package_type=42,7,1" + }, + "xezim": { + "status": "mismatch", + "output": "OBS package_type=X,7,1" + }, + "verilator": { + "status": "passed", + "output": "OBS package_type=42,7,1" + } + } + } + ] +} diff --git a/crates/celox-test-suite/verification/repros/sv_foreign_generic_constructor.sv b/crates/celox-test-suite/verification/repros/sv_foreign_generic_constructor.sv new file mode 100644 index 00000000000..179f7c433ca --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_foreign_generic_constructor.sv @@ -0,0 +1,26 @@ + +package p; + int source_value=96; + function automatic int initial_value(); return source_value+3; endfunction + class Factory #(type T); + static int count=0; + static function T create(); T result; result=new(); count++; return result; endfunction + endclass +endpackage +int value=20; +function automatic int initial_value(); return value+3; endfunction +class User; + int value; + function new(int n=initial_value()); value=n; endfunction +endclass +module Top(output int result, count); + User object; + initial begin + object=p::Factory#(User)::create(); result=object.value; count=p::Factory#(User)::count; + end +endmodule +module Observe; + wire [31:0] result, count; + Top dut(result, count); + initial begin #1; $display("OBS constructor=%0d,%0d", result, count); $finish; end +endmodule diff --git a/crates/celox-test-suite/verification/repros/sv_foreign_generic_defaults.sv b/crates/celox-test-suite/verification/repros/sv_foreign_generic_defaults.sv new file mode 100644 index 00000000000..63e9510ce5b --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_foreign_generic_defaults.sv @@ -0,0 +1,35 @@ + +package p; + parameter int W=5; + typedef bit [W-1:0] word_t; + class Box #(int N=W, type T=word_t); + static int count=0; + T value; + function new(); count++; endfunction + static function int width(); return $bits(T); endfunction + static function int number(); return N; endfunction + static function int from_pkg(); int W; W=77; return p::W; endfunction + endclass +endpackage +module Top(output int checks); + parameter int W=9; + typedef bit [W-1:0] word_t; + typedef p::Box#(.T(word_t)) Wide; + typedef p::Box#(.T(word_t),.N(5)) Same; + typedef Wide::T word_again; + Wide a; Same b; p::Box#() c; + initial begin + a=new(); b=new(); c=new(); + checks=(Wide::number()==5); + checks+=(Wide::width()==9)*2; + checks+=(p::Box#()::width()==5)*4; + checks+=(Wide::N==5)*8; + checks+=($bits(word_again)==9)*16; + checks+=(Wide::count==2 && Same::count==2 && p::Box#()::count==1)*32; + checks+=(Wide::from_pkg()==5)*64; + end +initial begin #1; + $display("OBS checks=%0d widths=%0d,%0d,%0d counts=%0d,%0d,%0d", checks, Wide::width(), Same::width(), p::Box#()::width(), Wide::count, Same::count, p::Box#()::count); + $finish; +end +endmodule \ No newline at end of file diff --git a/crates/celox-test-suite/verification/repros/sv_foreign_generic_factory.sv b/crates/celox-test-suite/verification/repros/sv_foreign_generic_factory.sv new file mode 100644 index 00000000000..7bf564c3842 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_foreign_generic_factory.sv @@ -0,0 +1,42 @@ + +package p; + class Registry #(type T); + static int count=0; + static function T create(); T object; object=new(); count++; return object; endfunction + endclass +endpackage + +import p::*; +class FirstUser; + int value; + function new(); value=42; endfunction + typedef Registry#(FirstUser) type_id; +endclass +module First(output int result, count); + FirstUser object; + initial begin object=FirstUser::type_id::create(); result=object.value; count=FirstUser::type_id::count; end +endmodule + +import p::*; +class SecondUser; + int padding; + int value; + function new(); padding=99; value=73; endfunction + typedef Registry#(SecondUser) type_id; +endclass +module Second(output int result, count); + SecondUser object; + initial begin object=SecondUser::type_id::create(); result=object.value; count=SecondUser::type_id::count; end +endmodule + +module Top(output int first, second, first_count, second_count); + First a(first, first_count); Second b(second, second_count); +endmodule +module Observe; + wire [31:0] first, second, first_count, second_count; + Top dut(first,second,first_count,second_count); + initial begin #1; + $display("OBS factories=%0d,%0d counts=%0d,%0d", first,second,first_count,second_count); + $finish; + end +endmodule diff --git a/crates/celox-test-suite/verification/repros/sv_foreign_generic_inheritance.sv b/crates/celox-test-suite/verification/repros/sv_foreign_generic_inheritance.sv new file mode 100644 index 00000000000..4246eea19b8 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_foreign_generic_inheritance.sv @@ -0,0 +1,29 @@ + +package p; + class Base #(int N=3, type T=bit[N-1:0]); + localparam int LOCAL=N+1; + parameter string LABEL="base"; + typedef T item_t; + endclass +endpackage +package q; + import p::*; + parameter int N=99, LOCAL=23; + parameter string LABEL="package_q"; + class Child #(int M=5) extends Base#(M); + bit[LOCAL-1:0] field; + function int checks(); + return (N==5) + (LOCAL==6)*2 + ($bits(item_t)==5)*4 + + ($bits(field)==6)*8 + (LABEL=="base")*16; + endfunction + endclass +endpackage +module Top(output int checks); + q::Child#(5) child; + initial begin child=new(); checks=child.checks(); end +endmodule +module Observe; + wire [31:0] checks; + Top dut(checks); + initial begin #1; $display("OBS inheritance=%0d", checks); $finish; end +endmodule diff --git a/crates/celox-test-suite/verification/repros/sv_foreign_generic_nominal.sv b/crates/celox-test-suite/verification/repros/sv_foreign_generic_nominal.sv new file mode 100644 index 00000000000..36eb7bddf84 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_foreign_generic_nominal.sv @@ -0,0 +1,13 @@ +package p; + class Counter #(type T); static int count=0; static function int tick(); count++; return count; endfunction endclass +endpackage +module Top; + typedef enum bit [1:0] {A0=0,A1=1} A; + typedef A Alias; + typedef enum bit [1:0] {B0=0,B1=1} B; + int a,b,c; + initial begin + a=p::Counter#(A)::tick(); b=p::Counter#(Alias)::tick(); c=p::Counter#(B)::tick(); + $display("OBS nominal=%0d,%0d,%0d",a,b,c); $finish; + end +endmodule diff --git a/crates/celox-test-suite/verification/repros/sv_foreign_generic_package_type.sv b/crates/celox-test-suite/verification/repros/sv_foreign_generic_package_type.sv new file mode 100644 index 00000000000..fc356b720e9 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_foreign_generic_package_type.sv @@ -0,0 +1,27 @@ + +package p; + class Item; + static int tag=7; + int value; + function new(); value=42; endfunction + endclass +endpackage +package q; + class Factory #(type T); + static int count=0; + static function T create(); T result; result=new(); count++; return result; endfunction + static function int type_tag(); return T::tag; endfunction + endclass +endpackage +module Top(output int result, tag, count); + p::Item object; + initial begin + object=q::Factory#(p::Item)::create(); result=object.value; + tag=q::Factory#(p::Item)::type_tag(); count=q::Factory#(p::Item)::count; + end +endmodule +module Observe; + wire [31:0] result, tag, count; + Top dut(result, tag, count); + initial begin #1; $display("OBS package_type=%0d,%0d,%0d", result, tag, count); $finish; end +endmodule diff --git a/crates/celox-test-suite/verification/sv/icarus/class.json b/crates/celox-test-suite/verification/sv/icarus/class.json index 5b45280df28..2577b2077b5 100644 --- a/crates/celox-test-suite/verification/sv/icarus/class.json +++ b/crates/celox-test-suite/verification/sv/icarus/class.json @@ -732,6 +732,116 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:5: syntax error\nI give up.\n", + "expectation": "Simulation", + "name": "class::foreign_generic_constructor_lexical_scope", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:5: syntax error\nI give up.\n", + "expectation": "Simulation", + "name": "class::foreign_generic_declaration_scope_and_equivalent_defaults", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: syntax error\nI give up.\n", + "expectation": "Simulation", + "name": "class::foreign_generic_inherited_constants", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: syntax error\nI give up.\n", + "expectation": "Simulation", + "name": "class::foreign_generic_multiple_user_classes", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: syntax error\nI give up.\n", + "expectation": "Simulation", + "name": "class::foreign_generic_nominal_and_nested_types", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:10: syntax error\nI give up.\n", + "expectation": "Simulation", + "name": "class::foreign_generic_package_type_static_storage", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:11: syntax error\nI give up.\n", + "expectation": "Simulation", + "name": "class::foreign_generic_static_handle_identity", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: syntax error\nI give up.\n", + "expectation": "Simulation", + "name": "class::foreign_generic_static_state_across_modules", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: syntax error\nI give up.\n", + "expectation": "Simulation", + "name": "class::foreign_generic_template_of_the_named_package", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: syntax error\nI give up.\n", + "expectation": "Simulation", + "name": "class::foreign_generic_unit_type_constructor", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "Icarus build exit status: 134; see /build.log\n/source_0.sv:3: syntax error\n/source_0.sv:3: error: Invalid module item.\n/source_0.sv:5: syntax error\n/source_0.sv:5: error: I give up on this function definition.\n/source_0.sv:8: syntax error\n/source_0.sv:9: error: Invalid module item.\n/source_0.sv:13: syntax error\n/source_0.sv:13: error: Syntax error in typedef clause.\n/source_0.sv:15: sorry: Overriding the default variable lifetime is not yet supported.\n/source_0.sv:15: syntax error\n/source_0.sv:15: error: Malformed statement\n/source_0.sv:16: sorry: Overriding the default variable lifetime is not yet supported.\n/source_0.sv:16: syntax error\n/source_0.sv:16: error: Invalid module item.\n/source_0.sv:17: syntax error\n/source_0.sv:17: error: Invalid module item.\n/source_0.sv:11: assert: pform.cc:1727: failed assertion lexical_scope == pform_cur_generate\nAborted (core dumped)\n", diff --git a/crates/celox-test-suite/verification/sv/verilator/class.json b/crates/celox-test-suite/verification/sv/verilator/class.json index 42f2fc7c4d9..f6b88859ab7 100644 --- a/crates/celox-test-suite/verification/sv/verilator/class.json +++ b/crates/celox-test-suite/verification/sv/verilator/class.json @@ -304,6 +304,105 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "Verilator build exit status: 1; see /build.log\n%Error: Internal Error: /source_0.sv:14:11: ../V3Task.cpp:2179: FuncRef without fvar\n : ... note: In instance 'celox_suite_tb'\n 14 | function new(int n=initial_value()); value=n; endfunction\n | ^~~\n ... See the manual at https://verilator.org/verilator_doc.html?v=5.052 for more assistance.\n", + "expectation": "Simulation", + "name": "class::foreign_generic_constructor_lexical_scope", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "class::foreign_generic_declaration_scope_and_equivalent_defaults at 2974:26: assert_eq checks: expected 0x7f, got 0x5f", + "expectation": "Simulation", + "name": "class::foreign_generic_declaration_scope_and_equivalent_defaults", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "class::foreign_generic_inherited_constants at 3080:26: assert_eq checks: expected 0x1f, got 0x0", + "expectation": "Simulation", + "name": "class::foreign_generic_inherited_constants", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::foreign_generic_multiple_user_classes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Verilator build exit status: 1; see /build.log\n%Error-UNSUPPORTED: /source_0.sv:15:13: Unsupported: Multiple '::' package/class reference\n 15 | typedef p::Wrap#(byte)::T element_t;\n | ^~~~\n ... For error description see https://verilator.org/warn/UNSUPPORTED?v=5.052\n%Error: /source_0.sv:15:26: Can't find typedef/interface: 'T'\n 15 | typedef p::Wrap#(byte)::T element_t;\n | ^\n ... See the manual at https://verilator.org/verilator_doc.html?v=5.052 for more assistance.\n%Error: Exiting due to 2 error(s)\n", + "expectation": "Simulation", + "name": "class::foreign_generic_nominal_and_nested_types", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::foreign_generic_package_type_static_storage", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::foreign_generic_static_handle_identity", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::foreign_generic_static_state_across_modules", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::foreign_generic_unit_type_constructor", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "class::generate_scope_enum_type_arguments at 2759:27: assert_eq sum: expected 0x4bc, got 0x8ae", diff --git a/crates/celox-test-suite/verification/sv/xezim/class.json b/crates/celox-test-suite/verification/sv/xezim/class.json index 6ad38174bf9..763f1d8f898 100644 --- a/crates/celox-test-suite/verification/sv/xezim/class.json +++ b/crates/celox-test-suite/verification/sv/xezim/class.json @@ -132,6 +132,105 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "class::foreign_generic_constructor_lexical_scope at 3106:26: assert_eq result: expected 0x17, got 0x14", + "expectation": "Simulation", + "name": "class::foreign_generic_constructor_lexical_scope", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "class::foreign_generic_declaration_scope_and_equivalent_defaults at 2974:26: assert_eq checks: expected 0x7f, got 0x6d", + "expectation": "Simulation", + "name": "class::foreign_generic_declaration_scope_and_equivalent_defaults", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "class::foreign_generic_inherited_constants at 3080:26: assert_eq checks: expected 0x1f, got 0x17", + "expectation": "Simulation", + "name": "class::foreign_generic_inherited_constants", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "class::foreign_generic_multiple_user_classes at 3014:23: assert_eq second: expected 0x49, got 0x2a", + "expectation": "Simulation", + "name": "class::foreign_generic_multiple_user_classes", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "class::foreign_generic_nominal_and_nested_types at 3051:26: assert_eq checks: expected 0x7ff, got 0x1", + "expectation": "Simulation", + "name": "class::foreign_generic_nominal_and_nested_types", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "class::foreign_generic_package_type_static_storage reads result with unknown bits in a two-state run", + "expectation": "Simulation", + "name": "class::foreign_generic_package_type_static_storage", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::foreign_generic_static_handle_identity", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::foreign_generic_static_state_across_modules", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::foreign_generic_unit_type_constructor", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "class::generate_scope_enum_type_arguments at 2759:27: assert_eq sum: expected 0x4bc, got 0x8ae", diff --git a/crates/celox-test-suite/verification/xezim-review.json b/crates/celox-test-suite/verification/xezim-review.json index fb459cb7395..9d9c88284b5 100644 --- a/crates/celox-test-suite/verification/xezim-review.json +++ b/crates/celox-test-suite/verification/xezim-review.json @@ -738,6 +738,22 @@ "sv_ref_subarray_element": { "title": "A ref formal bound to a subarray element neither reads nor writes that element", "standard": "IEEE 1800-2023 13.5.2, 7.4.6" + }, + "sv_class_foreign_factory_constructor": { + "title": "A package factory reached through distinct caller-class type_id typedefs constructs the first caller type for both", + "standard": "IEEE 1800-2023 8.23, 8.25" + }, + "sv_class_foreign_inherited_field_width": { + "title": "A derived class in another package sizes a field incorrectly when its bound uses an inherited local parameter", + "standard": "IEEE 1800-2023 8.13, 8.25" + }, + "sv_class_foreign_constructor_default": { + "title": "A factory's call of a supplied class constructor loses the result of its call-valued default argument", + "standard": "IEEE 1800-2023 8.25, 13.5.3" + }, + "sv_class_foreign_package_constructor": { + "title": "Constructing a package-class type argument through a generic in another package leaves initialized instance fields unknown", + "standard": "IEEE 1800-2023 8.7, 8.25" } }, "cases": [ @@ -4459,6 +4475,54 @@ "classification": "xezim_bug", "bug": "sv_ref_copy_semantics", "note": "The same concurrent task activations as references::ref_elements_of_concurrent_task_activations with the input argument first: ref formals bound to different array elements do not update them as references (q=18340 instead of 13570, which 13.5.2 gives with 11, 22, 33, 40). The adapter-free Top/Wrapped probe in verification/repros/ref_arguments.json shows the copy semantics in the installed xezim 0.11.3 build; this is not current-pin validation." + }, + { + "suite": "sv", + "name": "class::foreign_generic_declaration_scope_and_equivalent_defaults", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_class-X2", + "note": "The explicit T argument is the importing module's 9-bit word_t; Wide::T must retain that width. The shared checksum is 109 instead of 127. The standalone reports 111 with the member-type width check still false. Verilator separately gives Wide/Same/default counts 1,1,1 instead of 2,2,1, despite matching N/T actuals. See verification/repros/sv_foreign_generic.json for sources, observations and exact installed-build provenance." + }, + { + "suite": "sv", + "name": "class::foreign_generic_nominal_and_nested_types", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_class-X6", + "note": "The typedef Alias names the same enum type as A, so Counter#(Alias) and Counter#(A) must share their count. A standalone assigns consecutive tick results and prints 1,1,1 for A/Alias/B instead of 1,2,1. The shared case additionally distinguishes enum/struct declarations and queue element types. See verification/repros/sv_foreign_generic.json." + }, + { + "suite": "sv", + "name": "class::foreign_generic_multiple_user_classes", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_class_foreign_factory_constructor", + "note": "FirstUser and SecondUser have distinct names and layouts, so the source is valid with either compilation-unit model. Both factories construct a FirstUser-valued object: the second result is 42 instead of 73. A single-file standalone reproduces factories=42,42 instead of 42,73. This is independent of the separate-file compilation-unit policy. See verification/repros/sv_foreign_generic.json." + }, + { + "suite": "sv", + "name": "class::foreign_generic_inherited_constants", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_class_foreign_inherited_field_width", + "note": "Base#(5) gives LOCAL=6 and item_t a width of 5. The derived field bound LOCAL must use the inherited value, despite q::LOCAL=23. The shared and standalone checksums are 23 instead of 31, specifically missing the bit for $bits(field)==6. Verilator reports 0 for the same checksum. See verification/repros/sv_foreign_generic.json." + }, + { + "suite": "sv", + "name": "class::foreign_generic_constructor_lexical_scope", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_class_foreign_constructor_default", + "note": "User::new has n=initial_value() in compilation-unit scope; that function reads value=20 and returns 23. The package's same-named function returns 99. The constructor result is 20 instead of 23. IEEE 13.5.3 binds and evaluates the default in the subroutine declaration scope. Verilator raises an internal FuncRef-without-fvar error. See verification/repros/sv_foreign_generic.json." + }, + { + "suite": "sv", + "name": "class::foreign_generic_package_type_static_storage", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_class_foreign_package_constructor", + "note": "q::Factory#(p::Item)::create() calls Item::new(), which must assign value=42. The result contains unknown bits; a standalone prints X,7,1 for result/tag/count instead of 42,7,1. The static tag and factory counter are explicitly initialized. See verification/repros/sv_foreign_generic.json." } ] } diff --git a/crates/celox/tests/frontends/systemverilog/class.rs b/crates/celox/tests/frontends/systemverilog/class.rs index d17b3770a43..36f6c077633 100644 --- a/crates/celox/tests/frontends/systemverilog/class.rs +++ b/crates/celox/tests/frontends/systemverilog/class.rs @@ -733,19 +733,53 @@ fn classes_of_packages_in_other_sources_are_used_through_their_layouts() { } #[test] -fn specializations_of_classes_of_other_scopes_are_rejected() { - let source = "package p; class Box #(int N = 2); endclass endpackage - module Top; import p::*; Box #(3) box; endmodule"; - let Err(error) = - celox::Simulation::from_sv_sources(vec![(source, Path::new("class.sv"))], "Top").build() - else { - panic!("`{source}` is rejected"); - }; - let error = error.to_string(); - assert!( - error.contains("outside the scope that declares it"), - "{error}" - ); +fn compilation_unit_types_of_separate_files_specialize_package_classes_separately() { + // Celox makes each source file a compilation unit of its own (IEEE + // 1800-2023 3.12.1 lets a tool choose this), so the same typedef in two + // files names two types and two specializations of `p::Counter`. + let package = "`timescale 1ns/1ns + package p; + class Counter #(type T = int); + static int count; + function new(); count++; endfunction + endclass + endpackage"; + let a = "`timescale 1ns/1ns + typedef enum {A0, A1} E; + module A(output int n); + initial begin + automatic p::Counter#(E) c = new(); + #1 n = p::Counter#(E)::count; + end + endmodule"; + let b = "`timescale 1ns/1ns + typedef enum {B0, B1} E; + module B(output int n); + initial begin + automatic p::Counter#(E) c = new(); + automatic p::Counter#(E) d = new(); + #1 n = p::Counter#(E)::count; + end + endmodule"; + let top = "`timescale 1ns/1ns + module Top(output int a, output int b); + A ua(.n(a)); + B ub(.n(b)); + endmodule"; + let mut sim = celox::Simulation::from_sv_sources( + vec![ + (package, Path::new("package.sv")), + (a, Path::new("a.sv")), + (b, Path::new("b.sv")), + (top, Path::new("top.sv")), + ], + "Top", + ) + .build() + .unwrap(); + sim.run_until(1).unwrap(); + assert_eq!(sim.get(sim.signal("a")), 1u32.into()); + assert_eq!(sim.get(sim.signal("b")), 2u32.into()); } #[test] @@ -1167,3 +1201,144 @@ sv_backends! { sv_backends! { fn constraint_mode_base_dispatch(sim) { @case "class::constraint_mode_base_dispatch"; } } + +sv_backends! { + fn class_foreign_generic_static_state_across_modules(sim) { @case "class::foreign_generic_static_state_across_modules"; } + fn class_foreign_generic_unit_type_constructor(sim) { @case "class::foreign_generic_unit_type_constructor"; } + fn class_foreign_generic_static_handle_identity(sim) { @case "class::foreign_generic_static_handle_identity"; } +} + +sv_backends! { + fn class_foreign_generic_declaration_scope_and_equivalent_defaults(sim) { @case "class::foreign_generic_declaration_scope_and_equivalent_defaults"; } +} + +sv_backends! { + fn class_foreign_generic_multiple_user_classes(sim) { @case "class::foreign_generic_multiple_user_classes"; } +} + +sv_backends! { + fn class_foreign_generic_nominal_and_nested_types(sim) { @case "class::foreign_generic_nominal_and_nested_types"; } +} + +#[test] +fn foreign_generic_native_images_and_checkpoints_preserve_shared_handles() { + let source = r#"`timescale 1ps/1ps + package p; + class Slot #(type T); + static T saved; + static function void put(T object); saved=object; endfunction + endclass + endpackage + class Item; + int value; + function new(); value=7; endfunction + endclass + module Writer; + Item object; + initial begin + object=new(); p::Slot#(Item)::put(object); + #10; object.value=21; + #10; object.value++; + end + endmodule + module Reader(output int value); + initial begin + #15; value=p::Slot#(Item)::saved.value; + #10; value=p::Slot#(Item)::saved.value; + end + endmodule + module Top(output int value); + Writer writer(); Reader reader(value); + endmodule + "#; + for four_state in [false, true] { + let builder = || { + celox::Simulation::from_sv_sources( + vec![(source, Path::new("foreign_checkpoint.sv"))], + "Top", + ) + .four_state(four_state) + }; + let mut interpreted = builder().build_interpreter().unwrap(); + interpreted.run_until(30).unwrap(); + assert_eq!( + interpreted.get(interpreted.signal("value")), + BigUint::from(22u8) + ); + let image = builder().compile_native().unwrap().into_program_image(); + let image = + celox::NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()) + .unwrap(); + let mut sim = celox::Simulation::from_sv_sources(Vec::new(), "Top") + .build_native_from_image(image) + .unwrap(); + sim.run_until(15).unwrap(); + let value = sim.signal("value"); + assert_eq!(sim.get(value), BigUint::from(21u8)); + let bytes = sim.checkpoint().unwrap().to_bytes().unwrap(); + // SAFETY: bytes were created by this simulator. + let checkpoint = unsafe { sim.checkpoint_from_bytes(&bytes) }.unwrap(); + sim.run_until(30).unwrap(); + assert_eq!(sim.get(value), BigUint::from(22u8)); + sim.restore(&checkpoint).unwrap(); + sim.run_until(30).unwrap(); + assert_eq!(sim.get(value), BigUint::from(22u8)); + } +} + +// This API chooses one compilation unit per source file (3.12.1). +sv_backends! { + fn foreign_generic_distinct_unit_classes(sim) { + @setup { let sources = vec![ + (r#" +package p; + class Registry #(type T); + static int count=0; + static function T create(); T object; object=new(); count++; return object; endfunction + endclass +endpackage"#, Path::new("registry.sv")), + (r#" +import p::*; +class User; + int value; + function new(); value=42; endfunction + typedef Registry#(User) type_id; +endclass +module First(output int result, count); + User object; + initial begin object=User::type_id::create(); result=object.value; count=User::type_id::count; end +endmodule"#, Path::new("first.sv")), + (r#" +import p::*; +class User; + int padding; + int value; + function new(); padding=99; value=73; endfunction + typedef Registry#(User) type_id; +endclass +module Second(output int result, count); + User object; + initial begin object=User::type_id::create(); result=object.value; count=User::type_id::count; end +endmodule"#, Path::new("second.sv")), + (r#" +module Top(output int first, second, first_count, second_count); + First a(first, first_count); Second b(second, second_count); +endmodule"#, Path::new("top.sv")), + ]; } + @build celox::Simulation::from_sv_sources(sources, "Top"); + sim.run_until(0).unwrap(); + for (name, expected) in [("first", 42u32), ("second", 73), ("first_count", 1), ("second_count", 1)] { + assert_eq!(sim.get(sim.signal(name)), BigUint::from(expected), "{name}"); + } + } +} + +sv_backends! { + fn class_foreign_generic_inherited_constants(sim) { @case "class::foreign_generic_inherited_constants"; } +} + +sv_backends! { + fn class_foreign_generic_constructor_lexical_scope(sim) { @case "class::foreign_generic_constructor_lexical_scope"; } + fn class_foreign_generic_package_type_static_storage(sim) { @case "class::foreign_generic_package_type_static_storage"; } + fn class_foreign_generic_template_of_the_named_package(sim) { @case "class::foreign_generic_template_of_the_named_package"; } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 4bb6f1f82b0..652243aeca5 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -331,7 +331,7 @@ Celox reports an `Unsupported` error naming the construct instead of ignoring it. The error carries the number of the issue that tracks the construct; constructs without a dedicated issue point to the frontend roadmap, [#88](https://github.com/celox-sim/celox/issues/88). -- Class features beyond those [listed](#classes): `$cast` to a variable that is not a class handle, enumeration constants declared in a class, enumeration, struct and union types and named four-state or string constants as class parameter values, specializations of a parameterized class outside the package or compilation unit that declares it, properties that are `real`, arrays or wider than 64 bits, and randomization or constraints over 4-state properties. Timed tasks with static local declarations and recursive calls remain unsupported. +- Class features beyond those [listed](#classes): `$cast` to a variable that is not a class handle, enumeration constants declared in a class, enumeration, struct and union types and named four-state or string constants as class parameter values, module-local classes as type arguments to package-class specializations, properties that are `real`, arrays or wider than 64 bits, and randomization or constraints over 4-state properties. Timed tasks with static local declarations and recursive calls remain unsupported. - Behavioral and verification constructs: intra-assignment timing controls (`a = #1 b`), delayed continuous assignments ([#444](https://github.com/celox-sim/celox/issues/444)), named events and `->`, `wait fork` / `disable fork`, temporal concurrent assertions beyond the Boolean subset below, `force` / `release`. @@ -595,23 +595,30 @@ anonymous enumeration, struct or union type is rejected as a type argument. Package typedefs of specializations, such as `typedef C#(word_t) word_c` with `word_t` bounded by a package parameter, use the package's constants. -A class declared in a package or the compilation unit is laid out and its -methods are lowered where it is declared, once (IEEE 1800-2023 3.12.1, 26.3): +A class declared in a package or the compilation unit has its layout and +method bodies bound in its declaration scope (IEEE 1800-2023 3.12.1, 26.3): a module uses it through an import, as `p::C`, or by its name when the compilation unit declares it, also from another source file. Its static properties are variables of the package, shared by every module that uses the class. A module class may extend it and override its virtual methods; calls of those methods through handles in the module then also reach -the overrides of the module's classes. A specialization of a parameterized class -is made where the class is declared, so outside that scope only the -specializations it names can be used. Sources of packages and compilation-unit -items alone elaborate those scopes. +the overrides of the module's classes. A package's parameterized class can also +be specialized by an importing module, package, or compilation-unit class, +including with a compilation-unit class as a type argument. Explicit arguments +are bound in the caller's scope; defaults and class bodies retain the package's +declaration scope. Matching specializations share their type and static storage +throughout the design (8.25). Module-local classes cannot yet be used as these +type arguments: their identity must distinguish module instances. Sources of +packages and compilation-unit items alone elaborate those scopes. Member typedefs and type parameters of a concrete package-class specialization remain available through imported aliases such as `Small::element_t`, including inheritance and package re-exports. Their dimensions are fixed in the declaring specialization; parameters of the importing module cannot change them. A module or another package can inherit those bound member types (6.18, 8.13, 8.23). +Inherited value parameters and localparams, including strings, also retain their +base specialization's bindings when the derived package declares names that +shadow them (8.13, 8.25). Checkpoints keep objects. State files record strings but not objects, so saving a state file fails while any variable holds an object. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 31f649466a9..5a43e9094bc 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -210,7 +210,7 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 その構文を追跡する issue の番号が含まれます。専用の issue がない構文は、フロントエンドの ロードマップ [#88](https://github.com/celox-sim/celox/issues/88) を指します。 -- [対応範囲](#classes)外のクラスの機能:クラスハンドル以外の変数への `$cast`、クラス内で宣言した列挙定数、クラスパラメータの値としての列挙型・構造体型・共用体型と名前付きの 4 値・文字列定数、宣言した package やコンパイル単位の外でのパラメータ付きクラスの特殊化、4 値・`real`・配列・64 ビットを超えるプロパティ。時間待ちを含む task の static ローカル宣言、再帰呼び出し。 +- [対応範囲](#classes)外のクラスの機能:クラスハンドル以外の変数への `$cast`、クラス内で宣言した列挙定数、クラスパラメータの値としての列挙型・構造体型・共用体型と名前付きの 4 値・文字列定数、package のクラスをモジュール内クラス型で特殊化する機能、4 値・`real`・配列・64 ビットを超えるプロパティ。時間待ちを含む task の static ローカル宣言、再帰呼び出し。 - `inout` / `ref` / 式を使う modport、virtual interface など。 ANSI ヘッダーのポートは、クロック入力やパラメータ依存の幅も含めて modport 経由で渡せます。 interface 自体と入れ子の interface は対応しています。型パラメータはインスタンスごとに解決し、modport ポート経由でも伝搬します。 @@ -267,9 +267,9 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 型パラメータの値には、typedef で名前を付けた列挙型・構造体・共用体も使えます。宣言ごとに別の型なので、同じ構造でも別の特殊化になり、その typedef(`typedef A B`)は `A` と同じ特殊化になります(6.18、6.19、6.22.1)。generate ブロックの typedef はブロックのインスタンスごと(ループでは繰り返しごと)に別の型を宣言し(27.4)、package の typedef はどこで import しても同じ型です。名前のない列挙型・構造体・共用体は型パラメータの値にできません。`typedef C#(word_t) word_c` のように package の parameter で幅が決まる型を package 内の typedef で特殊化に渡すと、その package の定数で確定します。 -package やコンパイル単位で宣言したクラスは、宣言した場所で一度だけレイアウトを決めてメソッドを下ろします(IEEE 1800-2023 3.12.1、26.3)。モジュールは import や `p::C` で、コンパイル単位のクラスなら名前で、別のソースファイルからでも使えます。static プロパティは package の変数で、クラスを使うすべてのモジュールが共有します。モジュールのクラスはこれを継承して virtual メソッドをオーバーライドでき、そのモジュールのハンドルを通した呼び出しはモジュールのクラスのオーバーライドにも届きます。パラメータ付きクラスの特殊化はクラスを宣言した場所で作るので、そのスコープの外ではそこで名前を挙げた特殊化だけを使えます。package とコンパイル単位の要素だけのソースは、それらのスコープをエラボレーションします。 +package やコンパイル単位で宣言したクラスは、宣言スコープでレイアウトとメソッド本体を束縛します(IEEE 1800-2023 3.12.1、26.3)。モジュールは import や `p::C` で、コンパイル単位のクラスなら名前で、別のソースファイルからでも使えます。static プロパティは package の変数で、クラスを使うすべてのモジュールが共有します。モジュールのクラスはこれを継承して virtual メソッドをオーバーライドでき、そのモジュールのハンドルを通した呼び出しはモジュールのクラスのオーバーライドにも届きます。package のパラメータ付きクラスは、利用するモジュール、package、コンパイル単位のクラスからも特殊化できます。型引数にはコンパイル単位のクラスも渡せます。明示した実引数は呼び出し側で評価し、既定値とクラス本体は宣言元の package で束縛します。同じ特殊化はプログラム全体で型と static ストレージを共有します(8.25)。モジュール内のクラスを型引数にする場合は、インスタンスごとの型の同一性への対応が必要なため、現在は拒否します。package とコンパイル単位の要素だけのソースは、それらのスコープをエラボレーションします。 -package 内で具体化したクラスの typedef と型パラメータは、`Small::element_t` のように import した別名を通して参照できます。継承した型と package の再 export にも対応します。型の次元は宣言元の特殊化で確定するため、利用するモジュールの同名パラメータでは変化しません。別のモジュールや package のクラスも、これらの確定したメンバー型を継承できます(6.18、8.13、8.23)。 +package 内で具体化したクラスの typedef と型パラメータは、`Small::element_t` のように import した別名を通して参照できます。継承した型と package の再 export にも対応します。型の次元は宣言元の特殊化で確定するため、利用するモジュールの同名パラメータでは変化しません。別のモジュールや package のクラスも、これらの確定したメンバー型を継承できます(6.18、8.13、8.23)。値パラメータや localparam の文字列も基底の特殊化の値を継承し、派生側の package に同名の定数があっても変わりません(8.13、8.25)。 チェックポイントはオブジェクトを保持します。状態ファイルは文字列を記録しますがオブジェクトは記録しないため、オブジェクトを持つ変数があると状態ファイルの保存は失敗します。 diff --git a/scripts/check-external-suite-report.test.mjs b/scripts/check-external-suite-report.test.mjs index 94d6f0673a4..5b5b8ae9552 100644 --- a/scripts/check-external-suite-report.test.mjs +++ b/scripts/check-external-suite-report.test.mjs @@ -285,6 +285,16 @@ test("every retained baseline accepts only its existing failures", () => { result.accepted_failures, tool === "icarus" ? [ + "class::foreign_generic_constructor_lexical_scope", + "class::foreign_generic_declaration_scope_and_equivalent_defaults", + "class::foreign_generic_inherited_constants", + "class::foreign_generic_multiple_user_classes", + "class::foreign_generic_nominal_and_nested_types", + "class::foreign_generic_package_type_static_storage", + "class::foreign_generic_static_handle_identity", + "class::foreign_generic_static_state_across_modules", + "class::foreign_generic_template_of_the_named_package", + "class::foreign_generic_unit_type_constructor", "class::generate_scope_enum_type_arguments", "class::imported_member_type_dimensions", "class::imported_member_type_inheritance", @@ -368,6 +378,10 @@ test("every retained baseline accepts only its existing failures", () => { "unions::soft_wide_four_state", ] : [ + "class::foreign_generic_constructor_lexical_scope", + "class::foreign_generic_declaration_scope_and_equivalent_defaults", + "class::foreign_generic_inherited_constants", + "class::foreign_generic_nominal_and_nested_types", "class::generate_scope_enum_type_arguments", "fork::compound_event_activations_outlive_parent", "fork_control::process_ancestor_kill_preserves_caller_rng",