diff --git a/conformance/sv-tests/README.md b/conformance/sv-tests/README.md index b1cb1cde9e6..a9a6d48c360 100644 --- a/conformance/sv-tests/README.md +++ b/conformance/sv-tests/README.md @@ -114,6 +114,23 @@ method call changes the original. Full official runs at the pinned revision report 1081 passing cases in 2state and 1092 in 4state, with no passing case regressing. +Classes of packages and of the compilation unit update 62 more rows: both +state modes of 31 chapter 18 cases that declare classes outside any module +change from fail to pass, as such sources now elaborate their compilation unit. +Seven declare no constraints: `18.4.1--rand-modifier`, +`18.12--randomization-of-scope-variables_0`, `18.13.1--urandom_0`, +`18.13.1--urandom_2`, `18.13.2--urandom_range_0` and +`18.15--manually-seeding-randomize_0` were each simulated with a module that +constructs the class and calls its methods or `randomize()`, and printed the +expected results; `18.4.2--randc-modifier` elaborates while `randomize()` of +its `randc` property is rejected. The other 24 pass by elaboration alone: +their constraint blocks are parsed but not checked, and `randomize()` of a +class with constraints is rejected. `18.5.8.1--foreach-iterative-constraints_0`, +`18.5.8.2--array-reduction-iterative-constraints_0` and +`18.6.3--behavior-of-randomization-methods_0` keep failing on their array and +static random properties. Full official runs at the pinned revision report 1112 +passing cases in 2state and 1123 in 4state, with no passing case regressing. + ## Running locally Use the locked development shell and install the pinned [`requirements.txt`](requirements.txt) in a Python environment. diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index 080686dec97..a6186810a34 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -413,24 +413,24 @@ chapter-18/18.11.1--in-line-constraint-checker_0.sv 2state fail chapter-18/18.11.1--in-line-constraint-checker_0.sv 4state fail chapter-18/18.11.1--in-line-constraint-checker_1.sv 2state fail chapter-18/18.11.1--in-line-constraint-checker_1.sv 4state fail -chapter-18/18.12--randomization-of-scope-variables_0.sv 2state fail -chapter-18/18.12--randomization-of-scope-variables_0.sv 4state fail +chapter-18/18.12--randomization-of-scope-variables_0.sv 2state pass +chapter-18/18.12--randomization-of-scope-variables_0.sv 4state pass chapter-18/18.12--randomization-of-scope-variables_1.sv 2state fail chapter-18/18.12--randomization-of-scope-variables_1.sv 4state fail chapter-18/18.12.1--adding-constraints-to-scope-variables_0.sv 2state fail chapter-18/18.12.1--adding-constraints-to-scope-variables_0.sv 4state fail chapter-18/18.12.1--adding-constraints-to-scope-variables_1.sv 2state fail chapter-18/18.12.1--adding-constraints-to-scope-variables_1.sv 4state fail -chapter-18/18.13.1--urandom_0.sv 2state fail -chapter-18/18.13.1--urandom_0.sv 4state fail +chapter-18/18.13.1--urandom_0.sv 2state pass +chapter-18/18.13.1--urandom_0.sv 4state pass chapter-18/18.13.1--urandom_1.sv 2state fail chapter-18/18.13.1--urandom_1.sv 4state fail -chapter-18/18.13.1--urandom_2.sv 2state fail -chapter-18/18.13.1--urandom_2.sv 4state fail +chapter-18/18.13.1--urandom_2.sv 2state pass +chapter-18/18.13.1--urandom_2.sv 4state pass chapter-18/18.13.1--urandom_3.sv 2state fail chapter-18/18.13.1--urandom_3.sv 4state fail -chapter-18/18.13.2--urandom_range_0.sv 2state fail -chapter-18/18.13.2--urandom_range_0.sv 4state fail +chapter-18/18.13.2--urandom_range_0.sv 2state pass +chapter-18/18.13.2--urandom_range_0.sv 4state pass chapter-18/18.13.2--urandom_range_1.sv 2state fail chapter-18/18.13.2--urandom_range_1.sv 4state fail chapter-18/18.13.2--urandom_range_2.sv 2state fail @@ -459,8 +459,8 @@ chapter-18/18.14.3--object-stability_0.sv 2state fail chapter-18/18.14.3--object-stability_0.sv 4state fail chapter-18/18.14.3--object-stability_1.sv 2state fail chapter-18/18.14.3--object-stability_1.sv 4state fail -chapter-18/18.15--manually-seeding-randomize_0.sv 2state fail -chapter-18/18.15--manually-seeding-randomize_0.sv 4state fail +chapter-18/18.15--manually-seeding-randomize_0.sv 2state pass +chapter-18/18.15--manually-seeding-randomize_0.sv 4state pass chapter-18/18.15--manually-seeding-randomize_1.sv 2state fail chapter-18/18.15--manually-seeding-randomize_1.sv 4state fail chapter-18/18.16--random-weighted-case-randcase_0.sv 2state fail @@ -499,12 +499,12 @@ chapter-18/18.17.6--aborting-productions-break-and-return_2_fail.sv 2state pass chapter-18/18.17.6--aborting-productions-break-and-return_2_fail.sv 4state pass chapter-18/18.17.7--value-passing-between-productions_0.sv 2state fail chapter-18/18.17.7--value-passing-between-productions_0.sv 4state fail -chapter-18/18.4.1--rand-modifier.sv 2state fail -chapter-18/18.4.1--rand-modifier.sv 4state fail -chapter-18/18.4.2--randc-modifier.sv 2state fail -chapter-18/18.4.2--randc-modifier.sv 4state fail -chapter-18/18.5--constraint-blocks_0.sv 2state fail -chapter-18/18.5--constraint-blocks_0.sv 4state fail +chapter-18/18.4.1--rand-modifier.sv 2state pass +chapter-18/18.4.1--rand-modifier.sv 4state pass +chapter-18/18.4.2--randc-modifier.sv 2state pass +chapter-18/18.4.2--randc-modifier.sv 4state pass +chapter-18/18.5--constraint-blocks_0.sv 2state pass +chapter-18/18.5--constraint-blocks_0.sv 4state pass chapter-18/18.5--constraint-blocks_1.sv 2state fail chapter-18/18.5--constraint-blocks_1.sv 4state fail chapter-18/18.5.1--explicit-external-constraint_0.sv 2state fail @@ -515,34 +515,34 @@ chapter-18/18.5.1--explicit-external-constraint_2.sv 2state fail chapter-18/18.5.1--explicit-external-constraint_2.sv 4state fail chapter-18/18.5.1--implicit-external-constraint_0.sv 2state fail chapter-18/18.5.1--implicit-external-constraint_0.sv 4state fail -chapter-18/18.5.1--implicit-external-constraint_1.sv 2state fail -chapter-18/18.5.1--implicit-external-constraint_1.sv 4state fail +chapter-18/18.5.1--implicit-external-constraint_1.sv 2state pass +chapter-18/18.5.1--implicit-external-constraint_1.sv 4state pass chapter-18/18.5.1--implicit-external-constraint_2.sv 2state fail chapter-18/18.5.1--implicit-external-constraint_2.sv 4state fail -chapter-18/18.5.10--variable-ordering_0.sv 2state fail -chapter-18/18.5.10--variable-ordering_0.sv 4state fail +chapter-18/18.5.10--variable-ordering_0.sv 2state pass +chapter-18/18.5.10--variable-ordering_0.sv 4state pass chapter-18/18.5.10--variable-ordering_1.sv 2state pass chapter-18/18.5.10--variable-ordering_1.sv 4state pass -chapter-18/18.5.11--static-constraint-blocks_0.sv 2state fail -chapter-18/18.5.11--static-constraint-blocks_0.sv 4state fail +chapter-18/18.5.11--static-constraint-blocks_0.sv 2state pass +chapter-18/18.5.11--static-constraint-blocks_0.sv 4state pass chapter-18/18.5.11--static-constraint-blocks_1.sv 2state fail chapter-18/18.5.11--static-constraint-blocks_1.sv 4state fail -chapter-18/18.5.12--functions-in-constraint_0.sv 2state fail -chapter-18/18.5.12--functions-in-constraint_0.sv 4state fail +chapter-18/18.5.12--functions-in-constraint_0.sv 2state pass +chapter-18/18.5.12--functions-in-constraint_0.sv 4state pass chapter-18/18.5.12--functions-in-constraint_1.sv 2state fail chapter-18/18.5.12--functions-in-constraint_1.sv 4state fail -chapter-18/18.5.13--constraint-guards_0.sv 2state fail -chapter-18/18.5.13--constraint-guards_0.sv 4state fail +chapter-18/18.5.13--constraint-guards_0.sv 2state pass +chapter-18/18.5.13--constraint-guards_0.sv 4state pass chapter-18/18.5.13--constraint-guards_1.sv 2state fail chapter-18/18.5.13--constraint-guards_1.sv 4state fail -chapter-18/18.5.14--soft-constraints_0.sv 2state fail -chapter-18/18.5.14--soft-constraints_0.sv 4state fail +chapter-18/18.5.14--soft-constraints_0.sv 2state pass +chapter-18/18.5.14--soft-constraints_0.sv 4state pass chapter-18/18.5.14--soft-constraints_1.sv 2state fail chapter-18/18.5.14--soft-constraints_1.sv 4state fail chapter-18/18.5.14--soft-constraints_2.sv 2state pass chapter-18/18.5.14--soft-constraints_2.sv 4state pass -chapter-18/18.5.14.1--soft-constraint-priorities_0.sv 2state fail -chapter-18/18.5.14.1--soft-constraint-priorities_0.sv 4state fail +chapter-18/18.5.14.1--soft-constraint-priorities_0.sv 2state pass +chapter-18/18.5.14.1--soft-constraint-priorities_0.sv 4state pass chapter-18/18.5.14.1--soft-constraint-priorities_1.sv 2state fail chapter-18/18.5.14.1--soft-constraint-priorities_1.sv 4state fail chapter-18/18.5.14.1--soft-constraint-priorities_2.sv 2state fail @@ -551,54 +551,54 @@ chapter-18/18.5.14.1--soft-constraint-priorities_3.sv 2state fail chapter-18/18.5.14.1--soft-constraint-priorities_3.sv 4state fail chapter-18/18.5.14.1--soft-constraint-priorities_4.sv 2state fail chapter-18/18.5.14.1--soft-constraint-priorities_4.sv 4state fail -chapter-18/18.5.14.2--discarding-soft-constraints_0.sv 2state fail -chapter-18/18.5.14.2--discarding-soft-constraints_0.sv 4state fail +chapter-18/18.5.14.2--discarding-soft-constraints_0.sv 2state pass +chapter-18/18.5.14.2--discarding-soft-constraints_0.sv 4state pass chapter-18/18.5.14.2--discarding-soft-constraints_1.sv 2state fail chapter-18/18.5.14.2--discarding-soft-constraints_1.sv 4state fail -chapter-18/18.5.14.2--discarding-soft-constraints_2.sv 2state fail -chapter-18/18.5.14.2--discarding-soft-constraints_2.sv 4state fail +chapter-18/18.5.14.2--discarding-soft-constraints_2.sv 2state pass +chapter-18/18.5.14.2--discarding-soft-constraints_2.sv 4state pass chapter-18/18.5.14.2--discarding-soft-constraints_3.sv 2state fail chapter-18/18.5.14.2--discarding-soft-constraints_3.sv 4state fail chapter-18/18.5.14.2--discarding-soft-constraints_5.sv 2state fail chapter-18/18.5.14.2--discarding-soft-constraints_5.sv 4state fail -chapter-18/18.5.2--constraint-inheritance_0.sv 2state fail -chapter-18/18.5.2--constraint-inheritance_0.sv 4state fail +chapter-18/18.5.2--constraint-inheritance_0.sv 2state pass +chapter-18/18.5.2--constraint-inheritance_0.sv 4state pass chapter-18/18.5.2--constraint-inheritance_1.sv 2state fail chapter-18/18.5.2--constraint-inheritance_1.sv 4state fail -chapter-18/18.5.2--pure-constraint_0.sv 2state fail -chapter-18/18.5.2--pure-constraint_0.sv 4state fail +chapter-18/18.5.2--pure-constraint_0.sv 2state pass +chapter-18/18.5.2--pure-constraint_0.sv 4state pass chapter-18/18.5.2--pure-constraint_1.sv 2state fail chapter-18/18.5.2--pure-constraint_1.sv 4state fail chapter-18/18.5.2--pure-constraint_2.sv 2state pass chapter-18/18.5.2--pure-constraint_2.sv 4state pass -chapter-18/18.5.2--pure-constraint_3.sv 2state fail -chapter-18/18.5.2--pure-constraint_3.sv 4state fail -chapter-18/18.5.3--set-membership_0.sv 2state fail -chapter-18/18.5.3--set-membership_0.sv 4state fail +chapter-18/18.5.2--pure-constraint_3.sv 2state pass +chapter-18/18.5.2--pure-constraint_3.sv 4state pass +chapter-18/18.5.3--set-membership_0.sv 2state pass +chapter-18/18.5.3--set-membership_0.sv 4state pass chapter-18/18.5.3--set-membership_1.sv 2state fail chapter-18/18.5.3--set-membership_1.sv 4state fail -chapter-18/18.5.4--distribution_0.sv 2state fail -chapter-18/18.5.4--distribution_0.sv 4state fail +chapter-18/18.5.4--distribution_0.sv 2state pass +chapter-18/18.5.4--distribution_0.sv 4state pass chapter-18/18.5.4--distribution_1.sv 2state fail chapter-18/18.5.4--distribution_1.sv 4state fail chapter-18/18.5.4--distribution_2.sv 2state pass chapter-18/18.5.4--distribution_2.sv 4state pass -chapter-18/18.5.5--uniqueness-constraints_0.sv 2state fail -chapter-18/18.5.5--uniqueness-constraints_0.sv 4state fail +chapter-18/18.5.5--uniqueness-constraints_0.sv 2state pass +chapter-18/18.5.5--uniqueness-constraints_0.sv 4state pass chapter-18/18.5.5--uniqueness-constraints_1.sv 2state fail chapter-18/18.5.5--uniqueness-constraints_1.sv 4state fail -chapter-18/18.5.6--implication_0.sv 2state fail -chapter-18/18.5.6--implication_0.sv 4state fail +chapter-18/18.5.6--implication_0.sv 2state pass +chapter-18/18.5.6--implication_0.sv 4state pass chapter-18/18.5.6--implication_1.sv 2state fail chapter-18/18.5.6--implication_1.sv 4state fail -chapter-18/18.5.7--if-else-constraints_0.sv 2state fail -chapter-18/18.5.7--if-else-constraints_0.sv 4state fail -chapter-18/18.5.7--if-else-constraints_1.sv 2state fail -chapter-18/18.5.7--if-else-constraints_1.sv 4state fail -chapter-18/18.5.7--if-else-constraints_2.sv 2state fail -chapter-18/18.5.7--if-else-constraints_2.sv 4state fail -chapter-18/18.5.7--if-else-constraints_3.sv 2state fail -chapter-18/18.5.7--if-else-constraints_3.sv 4state fail +chapter-18/18.5.7--if-else-constraints_0.sv 2state pass +chapter-18/18.5.7--if-else-constraints_0.sv 4state pass +chapter-18/18.5.7--if-else-constraints_1.sv 2state pass +chapter-18/18.5.7--if-else-constraints_1.sv 4state pass +chapter-18/18.5.7--if-else-constraints_2.sv 2state pass +chapter-18/18.5.7--if-else-constraints_2.sv 4state pass +chapter-18/18.5.7--if-else-constraints_3.sv 2state pass +chapter-18/18.5.7--if-else-constraints_3.sv 4state pass chapter-18/18.5.7--if-else-constraints_4.sv 2state fail chapter-18/18.5.7--if-else-constraints_4.sv 4state fail chapter-18/18.5.8.1--foreach-iterative-constraints_0.sv 2state fail @@ -609,18 +609,18 @@ chapter-18/18.5.8.2--array-reduction-iterative-constraints_0.sv 2state fail chapter-18/18.5.8.2--array-reduction-iterative-constraints_0.sv 4state fail chapter-18/18.5.8.2--array-reduction-iterative-constraints_1.sv 2state fail chapter-18/18.5.8.2--array-reduction-iterative-constraints_1.sv 4state fail -chapter-18/18.5.9--global-constraints_0.sv 2state fail -chapter-18/18.5.9--global-constraints_0.sv 4state fail +chapter-18/18.5.9--global-constraints_0.sv 2state pass +chapter-18/18.5.9--global-constraints_0.sv 4state pass chapter-18/18.5.9--global-constraints_1.sv 2state fail chapter-18/18.5.9--global-constraints_1.sv 4state fail chapter-18/18.6.1--randomize-method_0.sv 2state fail chapter-18/18.6.1--randomize-method_0.sv 4state fail -chapter-18/18.6.2--post-randomize_method_0.sv 2state fail -chapter-18/18.6.2--post-randomize_method_0.sv 4state fail +chapter-18/18.6.2--post-randomize_method_0.sv 2state pass +chapter-18/18.6.2--post-randomize_method_0.sv 4state pass chapter-18/18.6.2--post-randomize_method_1.sv 2state fail chapter-18/18.6.2--post-randomize_method_1.sv 4state fail -chapter-18/18.6.2--pre-randomize-method_0.sv 2state fail -chapter-18/18.6.2--pre-randomize-method_0.sv 4state fail +chapter-18/18.6.2--pre-randomize-method_0.sv 2state pass +chapter-18/18.6.2--pre-randomize-method_0.sv 4state pass chapter-18/18.6.2--pre-randomize-method_1.sv 2state fail chapter-18/18.6.2--pre-randomize-method_1.sv 4state fail chapter-18/18.6.3--behavior-of-randomization-methods_0.sv 2state fail diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 82d93b344f1..cb6cbe72434 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -1401,13 +1401,19 @@ impl Module { .collect(); // A package keeps its symbols for the scopes that use it. let symbols = (is_package || export_symbols).then(|| scope::ScopeSymbols { + classes: classes::scope_classes(syntax_tree, &const_env), declarations_only: imported.declarations_only, type_parameter_bindings: HashMap::default(), pattern_parameter_bindings: HashMap::default(), const_env: const_env.clone(), parameter_values: parameter_values.clone(), parameters: parameters.clone(), - type_aliases: type_aliases.clone(), + // A class of the scope is a type of it (IEEE 1800-2023 8.3). + type_aliases: type_aliases + .iter() + .map(|(name, ty)| (name.clone(), ty.clone())) + .chain(classes::scope_class_types(syntax_tree)) + .collect(), enum_constants: enum_constants.clone(), functions: functions.clone(), function_return_types: packed_dimensions.function_return_types.clone(), diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index 48585e85f64..10eecdbc2b6 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -76,8 +76,17 @@ pub(super) struct Method { pub name: String, /// The class that declares the method. pub owner: String, - /// The definition, or the prototype of a pure virtual method. + /// The definition, or the prototype of a pure virtual method, in the + /// source of the scope that declares the class. pub native: celox_sv_syntax::SubroutineId, + /// The names of its formals, which a class declared in another source + /// is called with. + pub formals: Vec>, + /// A function, not a task. + pub is_function: bool, + /// Its return type, resolved in the scope of the class: `None` for a + /// task, `void` or a constructor, and unknown when it cannot be bound. + pub result: Option>, pub qualifiers: celox_sv_syntax::ClassQualifiers, /// Declared `virtual` here or in a base: a call through a handle runs /// the override of the object's class (IEEE 1800-2023 8.20). @@ -141,7 +150,7 @@ impl Class { } /// Validate the supported unconstrained subset before binding a call. - pub fn check_randomize(&self, tree: &AnalysisContext<'_>) -> Converted<()> { + pub fn check_randomize(&self) -> Converted<()> { if self.has_constraints { return Err(unsupported("class randomize with constraints")); } @@ -162,9 +171,8 @@ impl Class { } for hook in ["pre_randomize", "post_randomize"] { if let Some(method) = self.method(hook) { - let native = tree.declarations().subroutine(method.native); - if native.kind != celox_sv_syntax::SubroutineKind::Function - || native.ports.as_ref().is_some_and(|ports| !ports.is_empty()) + if !method.is_function + || !method.formals.is_empty() || method.qualifiers.is_static || method.qualifiers.is_virtual { @@ -206,22 +214,11 @@ impl Class { /// is the order they are evaluated in. pub fn constructor_arguments( &self, - native: &celox_sv_syntax::Declarations, arguments: &[celox_sv_syntax::Argument], ) -> Converted<(Vec>, Vec)> { - let names = self.method("new").map_or_else(Vec::new, |method| { - native - .subroutine(method.native) - .ports - .iter() - .flatten() - .map(|port| { - port.name - .as_ref() - .map(|name| instances::normalize_identifier(&name.spelling)) - }) - .collect() - }); + let names = self + .method("new") + .map_or_else(Vec::new, |method| method.formals.clone()); let mut actuals = vec![None; names.len()]; let mut order = Vec::new(); let mut named = false; @@ -351,19 +348,117 @@ fn declaration<'a>( tree.declarations() .classes .iter() - .find(|class| instances::normalize_identifier(&class.name.spelling) == name) + .find(|class| declared_name(tree, class) == name) +} + +/// The name of class declaration `declaration`: qualified by the package +/// that declares it, or by `$unit` when it is declared in the compilation +/// unit outside any module, interface, program or package, so that each +/// names one class of the design (IEEE 1800-2023 3.12.1, 26.3). +pub(super) fn declared_name( + tree: &AnalysisContext<'_>, + declaration: &celox_sv_syntax::ClassDeclaration, +) -> String { + let name = instances::normalize_identifier(&declaration.name.spelling); + match enclosing_unit(tree.declarations(), declaration.tokens) { + Some(unit) if unit.kind == celox_sv_syntax::UnitKind::Package => format!( + "{}::{name}", + instances::normalize_identifier(&unit.name.spelling) + ), + Some(_) => name, + None => format!("{}::{name}", packages::UNIT), + } +} + +/// The class declarations of the current scope, not those of the scopes +/// nested in it. +pub(super) fn scope_declarations<'a>( + tree: &'a AnalysisContext<'_>, +) -> impl Iterator { + let native = tree.declarations(); + let scope = tree.root_unit().ok().map(|unit| unit.tokens); + native + .classes + .iter() + .filter(move |class| enclosing_unit(native, class.tokens).map(|unit| unit.tokens) == scope) +} + +/// The classes the current scope declares, as they have been laid out, for +/// the scopes that use it (see `scope::ScopeSymbols::classes`). +pub(super) fn scope_classes(tree: &AnalysisContext<'_>, env: &HashMap) -> Vec { + let laid_out = tree.state.classes.borrow(); + scope_declarations(tree) + .flat_map(|declaration| specializations_of(tree, declaration)) + .filter_map(|name| { + let mut class = Class::clone(laid_out.get(&name)?); + // The types are fixed in the scope that declares the class, + // whose names another scope does not see. + let (env, _) = specializations::scope(tree, &name, env, &HashMap::default()); + let resolve = |ty: &mut Type| { + if let Some(resolved) = type_parameters::resolve(&tree.state, ty.clone(), &env) { + *ty = resolved; + } + }; + for property in &mut class.properties { + resolve(&mut property.r#type); + } + for property in &mut class.statics { + resolve(&mut property.r#type); + } + Some(class) + }) + .collect() +} + +/// The classes the current scope declares as types of the scope, by the +/// names it declares them with. A parameterized class is a type only with +/// a specialization. +pub(super) fn scope_class_types(tree: &AnalysisContext<'_>) -> Vec<(String, Type)> { + scope_declarations(tree) + .filter(|declaration| declaration.parameter_ports.is_none()) + .map(|declaration| { + ( + instances::normalize_identifier(&declaration.name.spelling), + handle(&declared_name(tree, declaration)), + ) + }) + .collect() } -/// Whether a class named `name` is declared in the current scope or in the -/// compilation unit, where the scope sees it (IEEE 1800-2023 3.12.1). -pub(super) fn is_visible(tree: &AnalysisContext<'_>, name: &str) -> bool { +/// The class that the unqualified name `name` refers to where the current +/// scope sees it: one the scope declares, or else one the compilation unit +/// 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 { let native = tree.declarations(); let scope = tree.root_unit().ok().map(|unit| unit.tokens); - native.classes.iter().any(|class| { - instances::normalize_identifier(&class.name.spelling) == name && { - let unit = enclosing_unit(native, class.tokens).map(|unit| unit.tokens); - unit.is_none() || unit == scope + let mut unit_class = None; + for class in &native.classes { + if instances::normalize_identifier(&class.name.spelling) != name { + continue; + } + let enclosing = enclosing_unit(native, class.tokens).map(|unit| unit.tokens); + if enclosing == scope { + return Some(declared_name(tree, class)); } + if enclosing.is_none() { + 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()); + } + unit_class.or_else(|| { + let class = format!("{}::{name}", packages::UNIT); + imported + .classes + .iter() + .any(|known| known.name == class) + .then_some(class) }) } @@ -392,10 +487,7 @@ pub(super) fn is_interface(tree: &AnalysisContext<'_>, name: &str) -> bool { /// Whether `name` is a class declared with a parameter port list (IEEE /// 1800-2023 8.25). pub(super) fn is_parameterized(tree: &AnalysisContext<'_>, name: &str) -> bool { - tree.declarations().classes.iter().any(|class| { - class.parameter_ports.is_some() - && instances::normalize_identifier(&class.name.spelling) == name - }) + declaration(tree, name).is_some_and(|class| class.parameter_ports.is_some()) } /// The classes and interface classes that body item `item` declares: of a @@ -417,17 +509,17 @@ pub(super) fn item_classes( .filter(|class| { item.tokens.start <= class.tokens.start && class.tokens.end <= item.tokens.end }) - .flat_map(|class| specializations(tree, class)) + .flat_map(|class| specializations_of(tree, class)) .collect() } /// The specializations of class declaration `declaration`: the class itself /// when it has no parameter port list. -fn specializations( +pub(super) fn specializations_of( tree: &AnalysisContext<'_>, declaration: &celox_sv_syntax::ClassDeclaration, ) -> Vec { - let name = instances::normalize_identifier(&declaration.name.spelling); + let name = declared_name(tree, declaration); if declaration.parameter_ports.is_some() { specializations::of(tree, &name) } else { @@ -457,7 +549,7 @@ pub(super) fn declared_methods( return Ok((method.subroutine, method.qualifiers.is_static)); } let method_name = instances::normalize_identifier(&subroutine.name.spelling); - out_of_block_definition(tree, &declaration.name.spelling, &method_name) + out_of_block_definition(tree, declaration, &method_name) .map(|id| (id, method.qualifiers.is_static)) .ok_or_else(|| { unsupported(format!( @@ -505,8 +597,31 @@ pub(super) fn base_arguments<'a>( /// The handle type of class `name`, if it is a class. pub(super) fn handle_type(tree: &AnalysisContext<'_>, name: &str) -> Option { - declaration(tree, name)?; - Some(handle(name)) + (declaration(tree, name).is_some() || imported(tree, name).is_some()).then(|| handle(name)) +} + +/// Class `name` as the scope that declares it laid it out, when the current +/// scope uses that scope (see `scope::ScopeSymbols::classes`). +fn imported(tree: &AnalysisContext<'_>, name: &str) -> Option> { + scope::imported(&tree.state) + .classes + .iter() + .find(|class| class.name == name) + .map(|class| Rc::new(class.clone())) +} + +/// The classes whose objects the current scope may see: those it declares +/// and those of the scopes it uses. +pub(super) fn visible_classes(tree: &AnalysisContext<'_>) -> Vec { + let mut names = scope_declarations(tree) + .flat_map(|declaration| specializations_of(tree, declaration)) + .collect::>(); + for class in &scope::imported(&tree.state).classes { + if !names.contains(&class.name) { + names.push(class.name.clone()); + } + } + names } /// The handle type of class `name`. @@ -530,8 +645,21 @@ pub(super) fn class( if let Some(class) = tree.state.classes.borrow().get(name) { return Ok(class.clone()); } - let declaration = - declaration(tree, name).ok_or_else(|| unsupported(format!("class `{name}`")))?; + // A class of another scope is laid out in its own scope, where the + // names it uses are declared. + let declaration = declaration(tree, name).filter(|declaration| { + let native = tree.declarations(); + enclosing_unit(native, declaration.tokens).map(|unit| unit.tokens) + == tree.root_unit().ok().map(|unit| unit.tokens) + }); + let Some(declaration) = declaration else { + let class = imported(tree, name).ok_or_else(|| unsupported(format!("class `{name}`")))?; + tree.state + .classes + .borrow_mut() + .insert(name.to_owned(), class.clone()); + return Ok(class); + }; let (env, aliases) = specializations::scope(tree, name, env, aliases); let (env, aliases) = (&env, &aliases); let native = tree.declarations(); @@ -661,21 +789,24 @@ pub(super) fn class( let native_id = if method.qualifiers.is_pure { method.subroutine } else if subroutine.prototype { - out_of_block_definition(tree, &declaration.name.spelling, &method_name).ok_or_else( - || { - unsupported(format!( - "extern method `{name}::{method_name}` without a body" - )) - }, - )? + out_of_block_definition(tree, declaration, &method_name).ok_or_else(|| { + unsupported(format!( + "extern method `{name}::{method_name}` without a body" + )) + })? } else { method.subroutine }; methods.retain(|known| known.name != method_name); + let (formals, result) = signature(tree, native_id, env, aliases); methods.push(Method { name: method_name, owner: name.to_owned(), native: native_id, + formals, + is_function: native.subroutine(native_id).kind + == celox_sv_syntax::SubroutineKind::Function, + result, qualifiers: method.qualifiers, is_virtual, }); @@ -689,7 +820,7 @@ pub(super) fn class( class(tree, interface, env, aliases)? .methods .iter() - .map(|method| (method.name.clone(), method.native)), + .map(|method| (method.name.clone(), method.result.clone())), ); } for (method_name, prototype) in required { @@ -700,9 +831,12 @@ pub(super) fn class( "interface class method `{method_name}` implemented by a non-virtual method of a base class" ))); } - if return_type(tree, method.native, env, aliases)? - != return_type(tree, prototype, env, aliases)? - { + let (Some(implemented), Some(prototype)) = (&method.result, &prototype) else { + return Err(unsupported(format!( + "return type of interface class method `{method_name}`" + ))); + }; + if implemented != prototype { return Err(unsupported(format!( "method `{method_name}` of class `{name}` whose return type differs from its interface class" ))); @@ -728,7 +862,7 @@ pub(super) fn class( } let class = Rc::new(Class { name: name.to_owned(), - id: class_id(name), + id: class_id(tree, name), has_constraints: declaration.has_constraints || base.as_ref().is_some_and(|base| base.has_constraints), base: base.map(|base| base.name.clone()), @@ -761,7 +895,12 @@ fn interface_name( let name = type_binding::procedural_type(interface, native, tree, env, aliases)? .and_then(|ty| ty.class.clone()) .ok_or_else(|| unsupported("implemented interface class type"))?; - if !declaration(tree, &name).is_some_and(|declaration| declaration.interface) { + // An interface class of another scope is known by its layout. + let interface = match imported(tree, &name) { + Some(class) => class.is_interface, + None => declaration(tree, &name).is_some_and(|declaration| declaration.interface), + }; + if !interface { return Err(unsupported(format!( "`implements` of `{name}`, not an interface class" ))); @@ -829,17 +968,21 @@ fn interface_class( return_type(tree, method.subroutine, env, aliases)?; let method_name = instances::normalize_identifier(&subroutine.name.spelling); methods.retain(|known| known.name != method_name); + let (formals, result) = signature(tree, method.subroutine, env, aliases); methods.push(Method { name: method_name, owner: name.to_owned(), native: method.subroutine, + formals, + is_function: subroutine.kind == celox_sv_syntax::SubroutineKind::Function, + result, qualifiers: method.qualifiers, is_virtual: true, }); } let class = Rc::new(Class { name: name.to_owned(), - id: class_id(name), + id: class_id(tree, name), base: None, interfaces, is_abstract: true, @@ -881,6 +1024,31 @@ fn own_declarations( .collect() } +/// The formal names and the return type of method `id`, see [`Method`]. +fn signature( + tree: &AnalysisContext<'_>, + id: celox_sv_syntax::SubroutineId, + env: &HashMap, + aliases: &HashMap, +) -> (Vec>, Option>) { + let formals = tree + .declarations() + .subroutine(id) + .ports + .iter() + .flatten() + .map(|port| { + port.name + .as_ref() + .map(|name| instances::normalize_identifier(&name.spelling)) + }) + .collect(); + let result = return_type(tree, id, env, aliases) + .ok() + .map(|ty| ty.and_then(|ty| type_parameters::resolve(&tree.state, ty, env))); + (formals, result) +} + /// The return type of subroutine `id`, `None` for a task or `void`. fn return_type( tree: &AnalysisContext<'_>, @@ -895,20 +1063,23 @@ fn return_type( } } -/// The definition `function ... class::method` outside class `class`. +/// The definition `function ... class::method` outside class declaration +/// `declaration`, in the scope that declares the class (IEEE 1800-2023 8.24). fn out_of_block_definition( tree: &AnalysisContext<'_>, - class: &str, + declaration: &celox_sv_syntax::ClassDeclaration, method: &str, ) -> Option { let native = tree.declarations(); - let class = instances::normalize_identifier(class); + let class = instances::normalize_identifier(&declaration.name.spelling); + let scope = enclosing_unit(native, declaration.tokens).map(|unit| unit.tokens); native.subroutine_ids().find(|&id| { let subroutine = native.subroutine(id); !subroutine.prototype && instances::normalize_identifier(&subroutine.name.spelling) == method - && matches!(&subroutine.scope[..], [scope] - if instances::normalize_identifier(&scope.name.spelling) == class) + && matches!(&subroutine.scope[..], [name] + if instances::normalize_identifier(&name.name.spelling) == class) + && enclosing_unit(native, subroutine.tokens).map(|unit| unit.tokens) == scope }) } @@ -948,10 +1119,30 @@ fn field( /// A run-time identifier of class `name`: an FNV-1a hash, never 0, which /// `null` reads as. -fn class_id(name: &str) -> u32 { - let hash = name.bytes().fold(0x811c_9dc5u32, |hash, byte| { - (hash ^ u32::from(byte)).wrapping_mul(0x0100_0193) - }); +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) + }); hash.max(1) } @@ -966,17 +1157,14 @@ fn object_classes( ) -> Converted>> { let mut classes = Vec::new(); let mut ids = HashMap::default(); - let names = tree - .declarations() - .classes - .iter() - .filter(|declaration| !declaration.interface && !declaration.virtual_class) - .flat_map(|declaration| specializations(tree, declaration)); - for name in names { + for name in visible_classes(tree) { // A class that cannot be laid out has no objects. let Ok(class) = class(tree, &name, env, aliases) else { continue; }; + if class.is_abstract || class.is_interface { + continue; + } if !class.derives_from(tree, ancestor, env, aliases) { continue; } diff --git a/crates/celox-sv-analyzer/src/ast/classes/specializations.rs b/crates/celox-sv-analyzer/src/ast/classes/specializations.rs index ec90d03625f..8ea3ed49ee5 100644 --- a/crates/celox-sv-analyzer/src/ast/classes/specializations.rs +++ b/crates/celox-sv-analyzer/src/ast/classes/specializations.rs @@ -631,7 +631,7 @@ pub(in crate::ast) fn declare_scopes( for class in &native.classes { if super::enclosing_unit(native, class.tokens).map(|unit| unit.tokens) == scope { scopes.insert( - instances::normalize_identifier(&class.name.spelling), + super::declared_name(tree, class), (env.clone(), aliases.clone()), ); } @@ -664,11 +664,13 @@ fn type_argument( let name = instances::normalize_identifier(&name.spelling); match context.type_aliases.get(&name) { Some(ty) => Some(ty.clone()), - None if super::declaration(tree, &name).is_some() => { - let name = specialize(tree, &name, &[], context)?; - Some(super::handle(&name)) - } - None => None, + None => match super::resolve(tree, &name) { + Some(name) => { + let name = specialize(tree, &name, &[], context)?; + Some(super::handle(&name)) + } + None => None, + }, } } ExprKind::Parameterized { @@ -676,13 +678,13 @@ fn type_argument( arguments, } => match &native.expression(*expression).kind { ExprKind::Name(name) => { - let name = specialize( - tree, - &instances::normalize_identifier(&name.spelling), - arguments, - context, - )?; - Some(super::handle(&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, }, @@ -697,16 +699,20 @@ fn type_argument( let class = match &native.expression(*expression).kind { ExprKind::Name(scope) => { let scope = instances::normalize_identifier(&scope.spelling); - if super::is_visible(tree, &scope) { + if let Some(class) = super::resolve(tree, &scope) { // Inside the class, its name refers to the // specialization being declared (8.25). match context .type_aliases .get(&scope_key(&scope)) + .or_else(|| context.type_aliases.get(&scope_key(&class))) .and_then(|ty| ty.class.clone()) { - Some(class) => Some(class), - None => Some(specialize(tree, &scope, &[], context)?), + Some(specialization) => Some(specialization), + None if super::is_declared(tree, &class) => { + Some(specialize(tree, &class, &[], context)?) + } + None => Some(class), } } else { let qualified = scope::qualified_name(&tree.state, &scope, &member); @@ -721,17 +727,20 @@ fn type_argument( expression, arguments, } => match &native.expression(*expression).kind { - ExprKind::Name(scope) => Some(specialize( - tree, - &instances::normalize_identifier(&scope.spelling), - arguments, - context, - )?), + ExprKind::Name(scope) => { + match super::resolve( + tree, + &instances::normalize_identifier(&scope.spelling), + ) { + Some(class) => Some(specialize(tree, &class, arguments, context)?), + None => None, + } + } _ => None, }, _ => None, }; - class.and_then(|class| member_type(tree, &class, &member)) + class.and_then(|class: String| member_type(tree, &class, &member)) } _ => None, }; @@ -867,45 +876,48 @@ 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); - let Ok(unit) = tree.root_unit() else { - 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 }; + // The current scope: a module, interface, program or package, or the + // compilation unit outside them. + let unit = tree.root_unit().ok().map(|unit| unit.tokens); + let in_scope = |tokens: celox_sv_syntax::TokenRange| match unit { + Some(unit) => within(unit, tokens), + None => super::enclosing_unit(native, tokens).is_none(), + }; let classes = native .classes .iter() - .filter(|class| within(unit.tokens, class.tokens)) + .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 - .iter() - .map(|class| instances::normalize_identifier(&class.name.spelling)) - .collect::>(); - // 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 .iter() .map(|class| { ( - class.tokens, instances::normalize_identifier(&class.name.spelling), + super::declared_name(tree, class), ) }) + .collect::>(); + // 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 + .iter() + .map(|class| (class.tokens, super::declared_name(tree, class))) .collect::>(); for id in native.subroutine_ids() { let subroutine = native.subroutine(id); if let [scope] = subroutine.scope.as_slice() - && within(unit.tokens, subroutine.tokens) + && in_scope(subroutine.tokens) + && let Some(class) = names.get(&instances::normalize_identifier(&scope.name.spelling)) { - let class = instances::normalize_identifier(&scope.name.spelling); - if names.contains(&class) { - scopes.push((subroutine.tokens, class)); - } + scopes.push((subroutine.tokens, class.clone())); } } // The innermost class scope that contains `tokens`. @@ -924,16 +936,11 @@ pub(in crate::ast) fn collect(tree: &AnalysisContext<'_>, context: &PackedDimens )> = Vec::new(); for class in &classes { if class.parameter_ports.is_none() || class.interface { - references.push(( - None, - instances::normalize_identifier(&class.name.spelling), - &[], - class.tokens, - )); + references.push((None, super::declared_name(tree, class), &[], class.tokens)); } } for ty in &native.types { - if !within(unit.tokens, ty.tokens) { + if !in_scope(ty.tokens) { continue; } // A class, or the class scope of a type it declares, `C#(...)::T`. @@ -944,7 +951,7 @@ pub(in crate::ast) fn collect(tree: &AnalysisContext<'_>, context: &PackedDimens && (path.len() == 1 || segment.arguments.is_some()) { let name = instances::normalize_identifier(&segment.name.spelling); - if names.contains(&name) { + if let Some(name) = names.get(&name).cloned() { references.push(( enclosing(ty.tokens), name, @@ -955,7 +962,7 @@ pub(in crate::ast) fn collect(tree: &AnalysisContext<'_>, context: &PackedDimens } } for expression in &native.expressions { - if !within(unit.tokens, expression.tokens) { + if !in_scope(expression.tokens) { continue; } if let ExprKind::Parameterized { @@ -965,7 +972,7 @@ pub(in crate::ast) fn collect(tree: &AnalysisContext<'_>, context: &PackedDimens && let ExprKind::Name(name) = &native.expression(*scope).kind { let name = instances::normalize_identifier(&name.spelling); - if names.contains(&name) { + if let Some(name) = names.get(&name).cloned() { references.push(( enclosing(expression.tokens), name, @@ -996,7 +1003,7 @@ pub(in crate::ast) fn collect(tree: &AnalysisContext<'_>, context: &PackedDimens ), None => ((*context.const_env).clone(), context.type_aliases.clone()), }; - let name = instances::normalize_identifier(&class.name.spelling); + let name = super::declared_name(tree, class); if item.is_some_and(|item| items.iter().filter(|other| other.id == item.id).count() > 1) { tree.state .class_declarations_repeated @@ -1013,7 +1020,7 @@ pub(in crate::ast) fn collect(tree: &AnalysisContext<'_>, context: &PackedDimens native.body_items.iter().any(|item| { let contains = |id: &celox_sv_syntax::BodyItemId| within(native.body_item(*id).tokens, tokens); - within(unit.tokens, item.tokens) + in_scope(item.tokens) && match &item.kind { celox_sv_syntax::BodyItemKind::Conditional { then_body, diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs index 2d68af1269e..a546b1d4a84 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs @@ -551,22 +551,17 @@ fn class_signatures( ); Ok(()) } -/// Publish the signatures of the methods of every class in the source, of -/// each specialization of a parameterized class that the current module +/// Publish the signatures of the methods of every class the current scope +/// declares, of each specialization of a parameterized class that the scope /// names (IEEE 1800-2023 8.25). pub(in crate::ast) fn all_class_signatures( tree: &AnalysisContext<'_>, context: &mut PackedDimensions, ) { classes::specializations::collect(tree, context); - for class in &tree.declarations().classes { - let generic = name(&class.name); - let names = if class.parameter_ports.is_some() { - classes::specializations::of(tree, &generic) - } else { - vec![generic] - }; - for class_name in names { + // The classes of other scopes keep the signatures their scopes publish. + for class in classes::scope_declarations(tree) { + for class_name in classes::specializations_of(tree, class) { let _ = class_signatures(class, &class_name, tree, context); } } 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 3cd80786a50..fddf7e40f44 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -118,6 +118,36 @@ fn named_class( dimensions: &PackedDimensions, ) -> Converted> { let (name, arguments) = match &native.expression(ungroup(id, native)).kind { + // A class of a package, `p::C` (IEEE 1800-2023 26.3). + ExprKind::Member { + expression, + separator, + name, + } if separator == "::" => { + 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), + ); + // A typedef of the package may name a class or a specialization. + if let Some(aliased) = dimensions + .type_aliases + .get(&class) + .and_then(|ty| ty.class.clone()) + { + return Ok(Some(aliased)); + } + if classes::handle_type(tree, &class).is_some() { + return Ok(Some(class)); + } + // Inside its package, `p::C` is a name of the package itself, + // whose classes are declared under their qualified names. + return Ok(classes::resolve(tree, &class) + .filter(|class| classes::handle_type(tree, class).is_some())); + } ExprKind::Name(name) => (name, None), ExprKind::Parameterized { expression, @@ -138,14 +168,21 @@ fn named_class( && let Some(class) = dimensions .type_aliases .get(&classes::specializations::scope_key(&name)) + .or_else(|| { + // A class of a package is declared under its qualified name. + let class = classes::resolve(tree, &name)?; + dimensions + .type_aliases + .get(&classes::specializations::scope_key(&class)) + }) .or_else(|| dimensions.type_aliases.get(&name)) .and_then(|ty| ty.class.clone()) { return Ok(Some(class)); } - if !classes::is_visible(tree, &name) { + let Some(name) = classes::resolve(tree, &name) else { return Ok(None); - } + }; if !classes::is_parameterized(tree, &name) { if arguments.is_some_and(|arguments| !arguments.is_empty()) { return Err(unsupported(format!( @@ -468,7 +505,7 @@ pub(in crate::ast) fn method( )); } if method_name == "randomize" { - class.check_randomize(tree)?; + class.check_randomize()?; } return Ok(Some(( Class::subroutine_name(&class_name, &method_name), @@ -512,11 +549,7 @@ pub(in crate::ast) fn method( receiver => receiver, } }; - let formals = native - .subroutine(method.native) - .ports - .as_ref() - .map_or(0, Vec::len); + let formals = method.formals.len(); let subroutine = if method.is_virtual && !through_super && receiver != Receiver::Static { Class::dispatcher_name(&method.owner, &method.name) } else { @@ -711,7 +744,7 @@ pub(in crate::ast) fn constructor( ))); } let mut args = vec![Some(class.allocation())]; - let (actuals, order) = class.constructor_arguments(native, arguments)?; + let (actuals, order) = class.constructor_arguments(arguments)?; for actual in actuals { args.push( actual diff --git a/crates/celox-sv-analyzer/src/ast/imports.rs b/crates/celox-sv-analyzer/src/ast/imports.rs index 692c476ff37..d0279b3bd7e 100644 --- a/crates/celox-sv-analyzer/src/ast/imports.rs +++ b/crates/celox-sv-analyzer/src/ast/imports.rs @@ -228,6 +228,15 @@ pub(super) fn item_names(id: celox_sv_syntax::BodyItemId, tree: &SyntaxTree) -> add(&instance.name); } } + // The classes a class item declares (IEEE 1800-2023 8.3). + BodyItemKind::Unconverted { category, .. } if category == "class" => { + let tokens = native.body_item(id).tokens; + for class in &native.classes { + if tokens.start <= class.tokens.start && class.tokens.end <= tokens.end { + add(&class.name); + } + } + } _ => {} } for id in types { @@ -428,10 +437,7 @@ pub(super) fn unqualified_names(tree: &SyntaxTree) -> HashMap return HashMap::default(); }; let nested = nested_declarations(tree); - let Facts { - qualified_bases, - pattern_keys, - } = Facts::of(tree); + let Facts { pattern_keys, .. } = Facts::of(tree); let mut names: HashMap> = HashMap::default(); let mut add = |name: &str, offset| { let name = normalize_identifier(name); @@ -443,12 +449,14 @@ pub(super) fn unqualified_names(tree: &SyntaxTree) -> HashMap names.entry(name).or_default().push(offset); } }; + // The scope of `C::x` is a name too: it may be a class that a wildcard + // import makes visible (IEEE 1800-2023 8.23, 26.3), while a package name + // binds nothing. let spans = tree.spans(); for id in spans.expressions.within(&ranges) { let expression = native.expression(id); if let ExprKind::Name(name) = &expression.kind && !pattern_keys.contains(&expression.tokens.start) - && !qualified_bases.contains(&(expression.tokens.start, expression.tokens.end)) { add(&name.spelling, expression.tokens.start); } @@ -468,6 +476,15 @@ pub(super) fn unqualified_names(tree: &SyntaxTree) -> HashMap names } +/// The positions of the names that are the scope of `s::x`. +fn qualifier_offsets(tree: &SyntaxTree) -> HashSet { + Facts::of(tree) + .qualified_bases + .iter() + .map(|(start, _)| *start) + .collect() +} + /// Native generate scopes, keyed by their authored body owner. struct GenerateScope { parent: Option, @@ -916,6 +933,21 @@ pub(super) fn resolve_imports( // A qualified name names a declaration of the package, or one it // exports: `q::x` then denotes the declaration `x` denotes in `q` // (IEEE 1800-2023 26.6). + // `C::x` names a member of a class `C` that an import makes visible + // (IEEE 1800-2023 8.23, 26.3). + if packages.get(package_name).is_none() + && (imports + .explicit + .iter() + .any(|(_, item)| item == package_name) + || imports.wildcard.iter().any(|imported| { + packages + .get(imported) + .is_some_and(|imported| imported.provides(package_name).is_some()) + })) + { + continue; + } let package_symbols = package(package_name)?; if !package_symbols.declares(name) { let target = package_symbols.provides(name).ok_or_else(|| { @@ -1042,6 +1074,14 @@ pub(super) fn resolve_imports( } else { unqualified_names(tree) }; + // The scope of `p::x` that names a package refers to no item. + let qualifiers = qualifier_offsets(tree); + referenced.retain(|name, offsets| { + if packages.get(name).is_some() { + offsets.retain(|offset| !qualifiers.contains(offset)); + } + !offsets.is_empty() + }); // A reference in a generate block is looked up in that block and the // blocks around it first (IEEE 1800-2023 26.3): the references the // imports of a block bind, by name, with the block and the declaration. diff --git a/crates/celox-sv-analyzer/src/ast/packages.rs b/crates/celox-sv-analyzer/src/ast/packages.rs index c5b420aa162..c01fe29cae4 100644 --- a/crates/celox-sv-analyzer/src/ast/packages.rs +++ b/crates/celox-sv-analyzer/src/ast/packages.rs @@ -147,6 +147,17 @@ impl Packages { &self.warnings } + /// The first error that analyzing a compilation unit found. A unit is + /// otherwise analyzed only when a module uses one of its items, and a + /// design of compilation-unit items alone is checked through this. + pub fn compilation_unit_error(&self) -> Option<&AnalyzerError> { + let mut paths = self.units.keys().collect::>(); + paths.sort(); + paths + .into_iter() + .find_map(|path| self.units[path].scope.as_ref().err()) + } + pub fn is_empty(&self) -> bool { self.packages.is_empty() } @@ -252,6 +263,12 @@ impl Packages { continue; } let visibility = unit_visibility(tree)?; + // The classes of each compilation unit are its own, though those + // of two sources may share a name. + state.classes.borrow_mut().clear(); + state.class_specializations.borrow_mut().clear(); + state.class_declaration_scopes.borrow_mut().clear(); + state.class_declarations_repeated.borrow_mut().clear(); let scope = analyze_package(UNIT, tree, &packages, &state); if scope .as_ref() @@ -509,6 +526,17 @@ fn analyze_package_scope( .symbols .take() .expect("a package analysis keeps the package symbols"); + // The static properties of its classes are variables of the package, + // shared by every scope that uses them (IEEE 1800-2023 8.9). + for class in &symbols.classes { + variables.extend( + class + .statics + .iter() + .filter(|property| property.owner == class.name) + .map(|property| property.variable.clone()), + ); + } // The package's variables, and those it imports, are shared objects; // the other signals are constants, copied with their initializers. let (state, constants): (Vec<_>, Vec<_>) = std::mem::take(&mut symbols.signals) @@ -554,8 +582,10 @@ fn analyze_package_scope( .map(|declared| (declared.clone(), qualified(declared))) .collect(); let mut own_locals = HashSet::default(); + // The members of its classes are qualified by the classes already. + let prefix = format!("{name}::"); for local in symbols.local_names() { - if !imported_locals.contains(&local) { + if !imported_locals.contains(&local) && !local.starts_with(&prefix) { names.insert(local.clone(), qualified(&local)); own_locals.insert(local); } diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 6f69399da3c..8adc8f68e14 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -2003,9 +2003,87 @@ pub(super) fn subroutines_with_symbolic_parameters( } } } + // A class of the scope, or of another package, that overrides a virtual + // method of a class that another scope declares is reached through that + // method's dispatcher, which the declaring scope lowered for the classes + // it saw: the scope lowers the dispatcher again, over every class it + // sees, when the dispatcher misses one (IEEE 1800-2023 8.20). + let imported = scope::imported(&tree.state); + for class in &imported.classes { + for method in class.dispatched_methods() { + let name = classes::Class::dispatcher_name(&class.name, &method.name); + if subroutines.iter().any(|known| known.name == name) { + continue; + } + let Some(dispatcher) = imported.subroutines.iter().find(|known| known.name == name) + else { + continue; + }; + let targets = classes::dispatch_targets( + tree, + &class.name, + &method.name, + const_env, + module_type_aliases, + )?; + let covered = case_ids(&dispatcher.body); + if targets + .iter() + .all(|(_, ids)| ids.iter().all(|id| covered.contains(id))) + { + continue; + } + let mut dispatcher = dispatcher.clone(); + dispatcher.body = vec![dispatch_body( + &targets, + &dispatcher.params, + dispatcher.return_var.as_deref(), + )]; + subroutines.push(dispatcher); + } + // So does a `$cast` to a variable of the class (8.16). + let name = classes::Class::cast_name(&class.name); + if subroutines.iter().any(|known| known.name == name) { + continue; + } + let Some(cast) = imported.subroutines.iter().find(|known| known.name == name) else { + continue; + }; + let targets = classes::cast_targets(tree, &class.name, const_env, module_type_aliases)?; + let covered = case_ids(&cast.body); + if targets.iter().all(|id| covered.contains(id)) { + continue; + } + let mut cast = cast.clone(); + if let Some(Stmt::Case { items, .. }) = cast.body.first_mut() + && let Some(item) = items.first_mut() + { + item.labels = std::iter::once(0) + .chain(targets) + .map(|id| CaseLabel::Value(Expr::Literal(format!("32'd{id}")))) + .collect(); + subroutines.push(cast); + } + } Ok(subroutines) } +/// The class identifiers that the case on the class of an object in `body`, +/// the body of a dispatcher or a `$cast` helper, selects. +fn case_ids(body: &[Stmt]) -> HashSet { + let Some(Stmt::Case { items, .. }) = body.first() else { + return HashSet::default(); + }; + items + .iter() + .flat_map(|item| &item.labels) + .filter_map(|label| match label { + CaseLabel::Value(Expr::Literal(literal)) => literal.strip_prefix("32'd")?.parse().ok(), + _ => None, + }) + .collect() +} + /// Shared native subroutine lowering for execution and expression-form plans. /// Native ownership/control is identical in both consumers; typed headers remain /// borrowed operands until their independent type kernels are migrated. @@ -2030,7 +2108,13 @@ pub(super) fn lower_subroutine( class .methods .iter() - .any(|method| method.native == native_id && method.qualifiers.is_static) + // An inherited method of a class of another source may + // have the same identifier. + .any(|method| { + method.native == native_id + && method.owner == class.name + && method.qualifiers.is_static + }) }); let handle = class .map(|class| { @@ -2486,7 +2570,7 @@ impl BodyBuilder<'_, '_, '_> { )?; } let mut args = vec![Some(Expr::Ident(this.to_owned()))]; - let (actuals, order) = base.constructor_arguments(native, arguments)?; + let (actuals, order) = base.constructor_arguments(arguments)?; for actual in actuals { args.push( actual diff --git a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs index f92f50ec209..5e446a9caa9 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs @@ -26,7 +26,7 @@ pub(super) fn lower( }; let mut result = Vec::new(); for method in ["randomize", "srandom", "rand_mode"] { - if method == "randomize" && class.check_randomize(tree).is_err() { + if method == "randomize" && class.check_randomize().is_err() { continue; } let mut builder = @@ -183,18 +183,17 @@ pub(super) fn lower( // Object-wide rand_mode also covers the dynamic object's members. let mut items = Vec::new(); let aliases = item.type_aliases(&dimensions.type_aliases); - for declaration in &tree.declarations().classes { - if declaration.interface || declaration.virtual_class { - continue; - } - let name = instances::normalize_identifier(&declaration.name.spelling); + for name in classes::visible_classes(tree) { if name == class.name { continue; } let Ok(derived) = classes::class(tree, &name, &item.env, &aliases) else { continue; }; - if (method == "randomize" && derived.check_randomize(tree).is_err()) + if derived.is_abstract || derived.is_interface { + continue; + } + if (method == "randomize" && derived.check_randomize().is_err()) || !derived.derives_from(tree, &class.name, &item.env, &aliases) { continue; diff --git a/crates/celox-sv-analyzer/src/ast/scope.rs b/crates/celox-sv-analyzer/src/ast/scope.rs index 25d6b0c4026..2c1bd94a779 100644 --- a/crates/celox-sv-analyzer/src/ast/scope.rs +++ b/crates/celox-sv-analyzer/src/ast/scope.rs @@ -61,6 +61,10 @@ pub(super) struct ScopeSymbols { /// The names the imports of a generate block bind there to another /// declaration than outside it, by the native body identity of the block. pub generate_imports: HashMap>, + /// The classes the scope declares, laid out, by their qualified names + /// (IEEE 1800-2023 26.3): a scope that uses them may be analyzed from + /// another source, without their declarations. + pub classes: Vec, } #[derive(Default)] @@ -180,6 +184,11 @@ pub(super) fn split_marker(key: &str) -> Option<(&str, &str)> { impl ScopeSymbols { /// Add the symbols of `other` that this scope does not already have. pub fn extend(&mut self, other: &ScopeSymbols) { + for class in &other.classes { + if !self.classes.iter().any(|known| known.name == class.name) { + self.classes.push(class.clone()); + } + } for (name, value) in &other.const_env { self.const_env.entry(name.clone()).or_insert(*value); } @@ -420,6 +429,8 @@ impl ScopeSymbols { }) .collect(); ScopeSymbols { + // Classes have their qualified names already. + classes: self.classes.clone(), declarations_only: self.declarations_only, interface_instances: self.interface_instances.clone(), interface_types: self.interface_types.clone(), 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 fed2fc06737..d83a2fee5a8 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs @@ -88,6 +88,7 @@ fn bind_in_with_validation( let name = normalize_identifier(&part.name.spelling); if (part.arguments.is_some() || !context.type_aliases.contains_key(&name)) + && let Some(name) = super::super::classes::resolve(tree, &name) && super::super::classes::is_parameterized(tree, &name) { let name = super::super::classes::specializations::specialize( @@ -116,6 +117,32 @@ fn bind_in_with_validation( continue; } if path.iter().any(|part| part.arguments.is_some()) { + // A specialization is made where the class is + // declared, from its declaration. + let imported = scope::imported(&tree.state); + let class = match path.as_slice() { + [part] => imported + .aliases + .get(&normalize_identifier(&part.name.spelling)) + .cloned(), + [package, member] => Some(scope::qualified_name( + &tree.state, + &normalize_identifier(&package.name.spelling), + &normalize_identifier(&member.name.spelling), + )), + _ => None, + }; + if let Some(class) = class.filter(|class| { + imported + .classes + .iter() + .any(|known| known.name.starts_with(&format!("{class}#("))) + || imported.aliases.values().any(|known| known == class) + }) { + return Err(unsupported(format!( + "specialization of parameterized class `{class}` outside the scope that declares it" + ))); + } return Ok(None); } let name = match path.as_slice() { @@ -128,7 +155,18 @@ fn bind_in_with_validation( _ => return Ok(None), }; let Some(ty) = context.type_aliases.get(&name) else { - if let Some(class) = super::super::classes::handle_type(tree, &name) { + // Inside its package, `p::C` is a name of the + // package itself, whose classes are declared + // under their qualified names. + let class = match path.as_slice() { + [_] => super::super::classes::resolve(tree, &name), + _ => super::super::classes::handle_type(tree, &name) + .map(|_| name.clone()) + .or_else(|| super::super::classes::resolve(tree, &name)), + }; + if let Some(class) = class + .and_then(|class| super::super::classes::handle_type(tree, &class)) + { values.push(class); continue; } @@ -357,14 +395,21 @@ fn class_scope( && let Some(class) = context .type_aliases .get(&super::super::classes::specializations::scope_key(&name)) + .or_else(|| { + // A class of a package is declared under its qualified name. + let class = super::super::classes::resolve(tree, &name)?; + context + .type_aliases + .get(&super::super::classes::specializations::scope_key(&class)) + }) .or_else(|| context.type_aliases.get(&name)) .and_then(|ty| ty.class.clone()) { return Ok(Some(class)); } - if !super::super::classes::is_visible(tree, &name) { + let Some(name) = super::super::classes::resolve(tree, &name) else { return Ok(None); - } + }; if !super::super::classes::is_parameterized(tree, &name) { if scope .arguments diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 5b94c8dd3b8..cdf600a7e33 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -542,9 +542,9 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_icarus_unpacked_subroutine_ports` | compile | icarus | 2 | Icarus 13.0 reports that subroutine ports with unpacked dimensions are not yet supported. Verilator passes the valid case. | | `sv_icarus_classes` | compile | icarus | 5 | Icarus 13.0 does not support extern methods ("sorry: External methods are not yet supported") or string methods called on a class property ("Can't find task itoa in class Named") or comparisons of class handles ("SORRY: Compare class handles not implemented"), aborts on a failed assertion in dup_expr.cc while compiling objects_referring_to_objects, and crashes with a segmentation fault while compiling implicit_constructors_and_this. IEEE 1800-2023 8.4, 8.7, 8.8 and 8.24 define these constructs. Verilator passes all but the string-method case, see sv_verilator_class_property_string_methods. | | `sv_icarus_nested_class_members` | execute | icarus | 1 | Icarus 13.0 reads an empty string through a nested property path (kept.inner.text) after reporting "sorry: Nested member path not yet supported for class properties" for its assignment. IEEE 1800-2023 8.5 permits accessing a property of an object referred to by a property. Verilator passes the case. | -| `sv_icarus_class_scope_resolution` | compile | icarus | 1 | Icarus 13.0 rejects class scope resolution with a syntax error: reading a static property (Counter::created), calling a static method (Counter::next()) and assigning a static property (Counter::last = "set"). IEEE 1800-2023 8.9, 8.10 and 8.23 define these accesses. Verilator passes the case. | +| `sv_icarus_class_scope_resolution` | compile | icarus | 3 | Icarus 13.0 rejects class scope resolution with a syntax error: reading a static property (Counter::created), calling a static method (Counter::next()) and assigning a static property (Counter::last = "set"). IEEE 1800-2023 8.9, 8.10 and 8.23 define these accesses. Verilator passes both cases. | | `sv_icarus_virtual_dispatch` | execute | icarus | 1 | Icarus 13.0 binds a virtual function called through a base-class handle to the handle's class instead of the object's: the shared case prints area=0 for every shape, and the adapter-free source prints 1 1 1 3 where IEEE 1800-2023 8.20 requires 2 3 4 4. Verilator and Celox print 2 3 4 4 and pass the case. | -| `sv_icarus_abstract_and_interface_classes` | compile | icarus | 7 | Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors ("Invalid class item", "Invalid module item") and fails code generation without a diagnostic ("Code generation had 2 error(s)") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes all but two cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods. | +| `sv_icarus_abstract_and_interface_classes` | compile | icarus | 8 | Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors ("Invalid class item", "Invalid module item") and fails code generation without a diagnostic ("Code generation had 2 error(s)") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes all but two cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods. | | `sv_verilator_interface_class_casts` | execute | verilator | 1 | Verilator 5.052 returns 0 from $cast of a handle of one interface class to a variable of another interface class that the object's class also implements, so the case dereferences the unassigned null handle; the adapter-free source prints 0 1 where IEEE 1800-2023 8.16 and 8.26.5 require 1 1. Celox prints 1 1. Icarus rejects interface classes, see sv_icarus_abstract_and_interface_classes. | | `sv_verilator_extended_interface_class_methods` | compile | verilator | 1 | Verilator 5.052 does not find a method that an interface class inherits from an interface class it extends when the method is called through a handle of the extending class ("Class method 'sides' not found in class 'NamedShape'"). IEEE 1800-2023 8.26.3 makes the methods of the extended interface classes members of the extending one. Icarus rejects interface classes, see sv_icarus_abstract_and_interface_classes. | | `sv_icarus_cast` | execute | icarus | 1 | Icarus 13.0 does not implement $cast ("System task/function $cast() is not defined by any module"), which IEEE 1800-2023 6.24.2 and 8.16 define. Verilator passes the case. | diff --git a/crates/celox-test-suite/src/sv/cases/class.vtest b/crates/celox-test-suite/src/sv/cases/class.vtest index 3c91427cf9c..87511f25c91 100644 --- a/crates/celox-test-suite/src/sv/cases/class.vtest +++ b/crates/celox-test-suite/src/sv/cases/class.vtest @@ -1595,6 +1595,109 @@ endmodule "#) (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) +(case classes_of_packages + (source "class.sv" #" +package shapes; + parameter int SCALE = 10; + typedef bit [7:0] byte_t; + virtual class Shape; + byte_t id; + static int made; + function new(byte_t id); + this.id = id; + made++; + endfunction + pure virtual function int area(); + function int scaled(); + return area() * SCALE; + endfunction + endclass + class Square extends Shape; + int side; + function new(int side); + super.new(8'd1); + this.side = side; + endfunction + virtual function int area(); + return side * side; + endfunction + endclass + interface class Named; + pure virtual function int name_id(); + endclass + function automatic Shape make(int side); + Square square = new(side); + return square; + endfunction + function automatic int ask(Named named); + return named.name_id() + 100; + endfunction +endpackage +module Top(output bit done); + import shapes::Shape; + import shapes::Square; + class Rect extends shapes::Shape implements shapes::Named; + int w; + int h; + function new(int w, int h); + super.new(8'd2); + this.w = w; + this.h = h; + endfunction + virtual function int area(); + return w * h; + endfunction + virtual function int name_id(); + return 7; + endfunction + endclass + Shape shape; + Square square; + Rect rect; + initial begin + shape = shapes::make(3); + rect = new(2, 5); + $display("%0d %0d %0d %0d", shape.area(), shape.scaled(), shape.id, $cast(square, shape)); + shape = rect; + $display("%0d %0d %0d %0d", shape.area(), rect.scaled(), shapes::ask(rect), shapes::Shape::made); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "9 90 1 1\n10 100 107 2\n")) + +(case classes_of_the_compilation_unit + (source "class.sv" #" +class Counter; + static int total; + int n; + function void bump(); + n++; + total++; + endfunction +endclass +module Child(output int seen); + Counter counter; + initial begin + counter = new; + counter.bump(); + counter.bump(); + seen = counter.n; + end +endmodule +module Top(output bit done); + int seen; + Child child(.seen(seen)); + initial begin + #1 $display("%0d %0d", seen, Counter::total); + done = 1; + end +endmodule +"#) + (top Top) (run_until 1) (assert_eq done 1) + (expect_output "2 2\n")) + (case class_declarations_bind_in_their_scopes (source "class.sv" #" module Top(output bit done); @@ -1784,3 +1887,27 @@ endmodule "#) (top Top) (run_until 0) (assert_eq done 1) (expect_output "3\n")) + +(case package_classes_by_their_qualified_names + (source "class.sv" #" +package p; + class C; + int v = 5; + endclass + function automatic C make(); + p::C h; + h = p::C::new; + return h; + endfunction +endpackage +module Top(output bit done); + initial begin + p::C h; + h = p::make(); + $display("%0d", h.v); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "5\n")) diff --git a/crates/celox-test-suite/verification/sv/icarus/class.json b/crates/celox-test-suite/verification/sv/icarus/class.json index f24a9177a7f..693a8141fb0 100644 --- a/crates/celox-test-suite/verification/sv/icarus/class.json +++ b/crates/celox-test-suite/verification/sv/icarus/class.json @@ -138,6 +138,52 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes all but two cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_abstract_and_interface_classes", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes all but two cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods.", + "upstream": [] + }, + "name": "class::classes_of_packages", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 rejects class scope resolution with a syntax error: reading a static property (Counter::created), calling a static method (Counter::next()) and assigning a static property (Counter::last = \"set\"). IEEE 1800-2023 8.9, 8.10 and 8.23 define these accesses. Verilator passes both cases.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_class_scope_resolution", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects class scope resolution with a syntax error: reading a static property (Counter::created), calling a static method (Counter::next()) and assigning a static property (Counter::last = \"set\"). IEEE 1800-2023 8.9, 8.10 and 8.23 define these accesses. Verilator passes both cases.", + "upstream": [] + }, + "name": "class::classes_of_the_compilation_unit", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", @@ -401,6 +447,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "Icarus 13.0 rejects class scope resolution with a syntax error: reading a static property (Counter::created), calling a static method (Counter::next()) and assigning a static property (Counter::last = \"set\"). IEEE 1800-2023 8.9, 8.10 and 8.23 define these accesses. Verilator passes both cases.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_class_scope_resolution", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects class scope resolution with a syntax error: reading a static property (Counter::created), calling a static method (Counter::next()) and assigning a static property (Counter::last = \"set\"). IEEE 1800-2023 8.9, 8.10 and 8.23 define these accesses. Verilator passes both cases.", + "upstream": [] + }, + "name": "class::package_classes_by_their_qualified_names", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "Icarus 13.0 does not parse a parameter port list of a class (class Box #(int N = 4); is a syntax error), which IEEE 1800-2023 8.25 defines; each case declares a parameterized class. Verilator passes all but two cases, see sv_verilator_class_specialization_identity and sv_verilator_untyped_class_parameters.", @@ -886,7 +955,7 @@ }, { "category": "Types", - "detail": "Icarus 13.0 rejects class scope resolution with a syntax error: reading a static property (Counter::created), calling a static method (Counter::next()) and assigning a static property (Counter::last = \"set\"). IEEE 1800-2023 8.9, 8.10 and 8.23 define these accesses. Verilator passes the case.", + "detail": "Icarus 13.0 rejects class scope resolution with a syntax error: reading a static property (Counter::created), calling a static method (Counter::next()) and assigning a static property (Counter::last = \"set\"). IEEE 1800-2023 8.9, 8.10 and 8.23 define these accesses. Verilator passes both cases.", "expectation": "Simulation", "known_issue": { "category": "simulator_compile_limitation", @@ -897,7 +966,7 @@ "id": "sv_icarus_class_scope_resolution", "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", "phase": "compile", - "reason": "Icarus 13.0 rejects class scope resolution with a syntax error: reading a static property (Counter::created), calling a static method (Counter::next()) and assigning a static property (Counter::last = \"set\"). IEEE 1800-2023 8.9, 8.10 and 8.23 define these accesses. Verilator passes the case.", + "reason": "Icarus 13.0 rejects class scope resolution with a syntax error: reading a static property (Counter::created), calling a static method (Counter::next()) and assigning a static property (Counter::last = \"set\"). IEEE 1800-2023 8.9, 8.10 and 8.23 define these accesses. Verilator passes both cases.", "upstream": [] }, "name": "class::static_properties_and_methods", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index de6a717bc16..6c53e1025bc 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -1890,7 +1890,7 @@ "category": "simulator_compile_limitation", "phase": "compile", "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", - "reason": "Icarus 13.0 rejects class scope resolution with a syntax error: reading a static property (Counter::created), calling a static method (Counter::next()) and assigning a static property (Counter::last = \"set\"). IEEE 1800-2023 8.9, 8.10 and 8.23 define these accesses. Verilator passes the case.", + "reason": "Icarus 13.0 rejects class scope resolution with a syntax error: reading a static property (Counter::created), calling a static method (Counter::next()) and assigning a static property (Counter::last = \"set\"). IEEE 1800-2023 8.9, 8.10 and 8.23 define these accesses. Verilator passes both cases.", "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", @@ -1898,7 +1898,9 @@ ], "cases": { "icarus": [ - "class::static_properties_and_methods" + "class::static_properties_and_methods", + "class::classes_of_the_compilation_unit", + "class::package_classes_by_their_qualified_names" ] } }, @@ -1939,7 +1941,8 @@ "class::methods_called_through_interface_class_handles", "class::inherited_methods_of_extended_interface_classes", "class::casts_from_interface_class_handles", - "class::typedefs_of_interface_classes" + "class::typedefs_of_interface_classes", + "class::classes_of_packages" ] } }, diff --git a/crates/celox-test-suite/verification/sv/limitations/icarus.json b/crates/celox-test-suite/verification/sv/limitations/icarus.json index d544df46b33..facf02b146f 100644 --- a/crates/celox-test-suite/verification/sv/limitations/icarus.json +++ b/crates/celox-test-suite/verification/sv/limitations/icarus.json @@ -9,7 +9,7 @@ "unexpected_accept": 1, "mismatch": 17, "emission_error": 0, - "compile_error": 135, + "compile_error": 138, "runtime_error": 8, "unsupported": 0, "ignored": 0 @@ -1479,6 +1479,30 @@ "name": "class::shallow_copies", "phase": "compile", "status": "compile_error" + }, + { + "category": "Types", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:12: syntax error\n/source_0.sv:12: error: Invalid class item.\n/source_0.sv:27: syntax error\nI give up.\n", + "expectation": "Simulation", + "name": "class::classes_of_packages", + "phase": "compile", + "status": "compile_error" + }, + { + "category": "Types", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:23: syntax error\n/source_0.sv:23: error: Malformed statement\n", + "expectation": "Simulation", + "name": "class::classes_of_the_compilation_unit", + "phase": "compile", + "status": "compile_error" + }, + { + "category": "Types", + "detail": "Icarus build exit status: 8; see /build.log\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Malformed statement\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Malformed statement\n/testbench.sv:50: syntax error\n/testbench.sv:50: error: Syntax error in task/function port declaration.\n/testbench.sv:51: syntax error\n/testbench.sv:51: error: Malformed statement\n", + "expectation": "Simulation", + "name": "class::package_classes_by_their_qualified_names", + "phase": "compile", + "status": "compile_error" } ] } diff --git a/crates/celox-test-suite/verification/sv/verilator/class.json b/crates/celox-test-suite/verification/sv/verilator/class.json index 099e5862599..ceb08b51dc7 100644 --- a/crates/celox-test-suite/verification/sv/verilator/class.json +++ b/crates/celox-test-suite/verification/sv/verilator/class.json @@ -79,6 +79,28 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::classes_of_packages", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::classes_of_the_compilation_unit", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", @@ -234,6 +256,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::package_classes_by_their_qualified_names", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", diff --git a/crates/celox-test-suite/verification/sv/xezim/class.json b/crates/celox-test-suite/verification/sv/xezim/class.json index 60bd708fbb0..14fddbafbe4 100644 --- a/crates/celox-test-suite/verification/sv/xezim/class.json +++ b/crates/celox-test-suite/verification/sv/xezim/class.json @@ -35,7 +35,7 @@ }, { "category": "Types", - "detail": "class::class_declarations_bind_in_their_scopes at 1653:3: expect_output: expected [50, 53, 53, 32, 53, 32, 45, 51, 32, 51, 50, 10, 50, 48, 32, 51, 48, 32, 49, 32, 98, 99, 32, 48, 51, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 10], got [50, 53, 53, 32, 49, 32, 52, 50, 57, 52, 57, 54, 55, 50, 57, 51, 32, 51, 50, 10, 50, 48, 32, 51, 48, 32, 49, 32, 98, 99, 32, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 10]", + "detail": "class::class_declarations_bind_in_their_scopes at 1756:3: expect_output: expected [50, 53, 53, 32, 53, 32, 45, 51, 32, 51, 50, 10, 50, 48, 32, 51, 48, 32, 49, 32, 98, 99, 32, 48, 51, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 10], got [50, 53, 53, 32, 49, 32, 52, 50, 57, 52, 57, 54, 55, 50, 57, 51, 32, 51, 50, 10, 50, 48, 32, 51, 48, 32, 49, 32, 98, 99, 32, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 10]", "expectation": "Simulation", "name": "class::class_declarations_bind_in_their_scopes", "phase": "execute", @@ -66,6 +66,28 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::classes_of_packages", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::classes_of_the_compilation_unit", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "the simulation ended before the script did", @@ -79,7 +101,7 @@ }, { "category": "Types", - "detail": "class::derived_classes_keep_their_declaration_scopes at 1786:3: expect_output: expected [51, 10], got [49, 10]", + "detail": "class::derived_classes_keep_their_declaration_scopes at 1889:3: expect_output: expected [51, 10], got [49, 10]", "expectation": "Simulation", "name": "class::derived_classes_keep_their_declaration_scopes", "phase": "execute", @@ -211,7 +233,18 @@ }, { "category": "Types", - "detail": "class::parameter_defaults_bind_where_the_class_is_declared at 1675:3: expect_output: expected [49, 10], got [50, 10]", + "detail": "the simulation ended before the script did", + "expectation": "Simulation", + "name": "class::package_classes_by_their_qualified_names", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "class::parameter_defaults_bind_where_the_class_is_declared at 1778:3: expect_output: expected [49, 10], got [50, 10]", "expectation": "Simulation", "name": "class::parameter_defaults_bind_where_the_class_is_declared", "phase": "execute", @@ -365,7 +398,7 @@ }, { "category": "Types", - "detail": "class::specialization_keys_follow_the_bound_parameters at 1764:3: expect_output: expected [50, 32, 49, 32, 49, 10, 49, 32, 49, 10, 51, 46, 48, 32, 51, 46, 48, 10, 50, 10, 55, 10], got [50, 32, 49, 32, 48, 10, 48, 32, 49, 10, 48, 46, 48, 32, 48, 46, 48, 10, 50, 10, 55, 10]", + "detail": "class::specialization_keys_follow_the_bound_parameters at 1867:3: expect_output: expected [50, 32, 49, 32, 49, 10, 49, 32, 49, 10, 51, 46, 48, 32, 51, 46, 48, 10, 50, 10, 55, 10], got [50, 32, 49, 32, 48, 10, 48, 32, 49, 10, 48, 46, 48, 32, 48, 46, 48, 10, 50, 10, 55, 10]", "expectation": "Simulation", "name": "class::specialization_keys_follow_the_bound_parameters", "phase": "execute", diff --git a/crates/celox-test-suite/verification/xezim-review.json b/crates/celox-test-suite/verification/xezim-review.json index b691b53c3e4..6334a38ce38 100644 --- a/crates/celox-test-suite/verification/xezim-review.json +++ b/crates/celox-test-suite/verification/xezim-review.json @@ -3979,6 +3979,14 @@ "classification": "xezim_bug", "bug": "sv_class-X11", "note": "As top xezim prints the expected three lines. As non-top dut, `third = new Item::last` (shallow copy of the static handle, 8.12) leaves third null, so third.a is a fatal null dereference. Copying from a local handle (`tmp = Item::last; third = new tmp`) works, and Item::last itself reads non-null. Repro: work/review5/xezim/r/c9_static.sv (+ .wrap.sv)." + }, + { + "suite": "sv", + "name": "class::package_classes_by_their_qualified_names", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_rest-X2", + "note": "p::make() constructs with the typed constructor call `h = p::C::new`; xezim leaves the handle unusable (h == null is x), so h.v is a fatal null dereference and the run ends before the script (as top too). Replacing it with `h = new` prints the expected 5. Repro: work/review5/xezim/r/c4_typed.sv, work/review5/xezim/r/c4_new.sv." } ] } diff --git a/crates/celox/examples/sv_tests.rs b/crates/celox/examples/sv_tests.rs index dcc1b164b66..b87450b0b2f 100644 --- a/crates/celox/examples/sv_tests.rs +++ b/crates/celox/examples/sv_tests.rs @@ -182,6 +182,20 @@ fn run(options: &Options) -> Result<(), String> { .map(|(text, path)| celox_sv_analyzer::ParsedSource::parse(text, path)) .collect::, _>>() .map_err(|error| error.to_string())?; + // Sources of packages and compilation-unit items alone, such as + // classes, elaborate those scopes (IEEE 1800-2023 3.12.1). + if options.mode == Mode::Elaboration + && options.top.is_none() + && parsed.iter().all(|source| source.module_names().is_empty()) + { + let parsed = parsed.iter().collect::>(); + let packages = celox_sv_analyzer::ParsedSource::analyze_packages(&parsed) + .map_err(|error| error.to_string())?; + if let Some(error) = packages.compilation_unit_error() { + return Err(error.to_string()); + } + return Ok(()); + } let top = select_top(&parsed, options.top.as_deref())?; match options.mode { Mode::Preprocessing | Mode::Parsing => { diff --git a/crates/celox/tests/frontends/systemverilog/class.rs b/crates/celox/tests/frontends/systemverilog/class.rs index 140e242e112..90b5b974c1e 100644 --- a/crates/celox/tests/frontends/systemverilog/class.rs +++ b/crates/celox/tests/frontends/systemverilog/class.rs @@ -39,6 +39,9 @@ sv_backends! { fn class_specialization_keys_follow_the_bound_parameters(sim) { @case "class::specialization_keys_follow_the_bound_parameters"; } fn class_derived_classes_keep_their_declaration_scopes(sim) { @case "class::derived_classes_keep_their_declaration_scopes"; } fn class_shallow_copies(sim) { @case "class::shallow_copies"; } + fn class_classes_of_packages(sim) { @case "class::classes_of_packages"; } + fn class_package_classes_by_their_qualified_names(sim) { @case "class::package_classes_by_their_qualified_names"; } + fn class_classes_of_the_compilation_unit(sim) { @case "class::classes_of_the_compilation_unit"; } } sv_backends! { @@ -536,6 +539,74 @@ sv_backends! { } } +#[test] +fn classes_of_packages_in_other_sources_are_used_through_their_layouts() { + let package = "package shapes; + class Shape; + int id; + static int made; + function new(int id); this.id = id; made++; endfunction + virtual function int area(); return 0; endfunction + endclass + class Square extends Shape; + int side; + function new(int side); super.new(side + 1); this.side = side; endfunction + virtual function int area(); return side * side; endfunction + endclass + endpackage"; + let module = "module Top(output int area, output int id, output int made); + import shapes::*; + Shape shape; + initial begin + shape = Square::new(4); + area = shape.area(); + id = shape.id; + made = shapes::Shape::made; + end + endmodule"; + let mut sim = celox::Simulation::from_sv_sources( + vec![ + (package, Path::new("shapes.sv")), + (module, Path::new("top.sv")), + ], + "Top", + ) + .build() + .unwrap(); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("area")), 16u32.into()); + assert_eq!(sim.get(sim.signal("id")), 5u32.into()); + assert_eq!(sim.get(sim.signal("made")), 1u32.into()); +} + +#[test] +fn misused_classes_of_other_scopes_are_rejected() { + for (source, want) in [ + ( + "package p; class Box #(int N = 2); endclass endpackage + module Top; import p::*; Box #(3) box; endmodule", + "specialization of parameterized class `p::Box` outside the scope that declares it", + ), + // A package variable has one writing instance (#1146), static + // properties of package classes too. + ( + "package p; class C; static int n; function new(); n++; endfunction endclass endpackage + module W; p::C c; initial c = new; endmodule + module Top; W a(); W b(); endmodule", + "multiple drivers of package", + ), + ] { + 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(want), "{error}"); + } +} + #[test] fn a_class_of_another_module_does_not_hide_a_package() { let source = "package P; typedef bit [2:0] T; endpackage @@ -589,6 +660,88 @@ fn type_arguments_keep_their_dimensions_scopes_and_class_scoped_types() { assert!(error.to_string().contains("a handle of class"), "{error}"); } +#[test] +fn classes_of_packages_in_other_sources_keep_their_behaviour() { + let package = r#"package p; + class B; virtual function int f(); return 1; endfunction endclass + interface class I; pure virtual function int id(); endclass + class R; rand int x; int hooked; function void pre_randomize(); hooked = 5; endfunction endclass + class P #(int N = 1); + static function int f(); return P::N; endfunction + endclass + typedef P#(2) P2; + class Plain; function int v(); return 9; endfunction endclass + typedef Plain Alias; + interface class Getter #(type T = int); pure virtual function T get(); endclass +endpackage +package q; + class C; extern function int f(); endclass + function int C::f(); return 2; endfunction +endpackage +package r; + class C; extern function int f(); endclass + function int C::f(); return 3; endfunction +endpackage"#; + let module = r#"package w1; int p; endpackage +package w2; int p; endpackage +module Top(output int cast, output int over, output int iface, output int hooked, output int special, output int alias_v, output int qf, output int rf, output int got); + import w1::*; + import w2::*; + class D extends p::B; virtual function int f(); return 4; endfunction endclass + class M implements p::I; virtual function int id(); return 6; endfunction endclass + interface class Getter #(type T = int); pure virtual function T get(); endclass + class G implements Getter#(int); virtual function int get(); return 8; endfunction endclass + p::B b; + D d; + M m; + p::R rr; + p::Alias al; + q::C qc; + r::C rc; + G g; + initial begin + d = new; + m = new; + rr = new; + void'(rr.randomize()); + al = p::Alias::new; + qc = new; rc = new; g = new; + cast = $cast(b, d); + over = b.f(); + iface = m.id(); + hooked = rr.hooked; + special = p::P2::f(); + alias_v = al.v(); + qf = qc.f(); + rf = rc.f(); + got = g.get(); + end +endmodule"#; + let mut sim = celox::Simulation::from_sv_sources( + vec![ + (package, Path::new("packages.sv")), + (module, Path::new("top.sv")), + ], + "Top", + ) + .build() + .unwrap(); + sim.run_until(0).unwrap(); + for (signal, value) in [ + ("cast", 1u32), + ("over", 4), + ("iface", 6), + ("hooked", 5), + ("special", 2), + ("alias_v", 9), + ("qf", 2), + ("rf", 3), + ("got", 8), + ] { + assert_eq!(sim.get(sim.signal(signal)), value.into(), "{signal}"); + } +} + #[test] fn specializations_tell_types_apart_and_keep_their_bases() { let source = r#"module Top(output int packed_made, output int unpacked_made, output int width, output int base_n); @@ -625,6 +778,58 @@ endmodule"#; assert_eq!(sim.get(sim.signal("base_n")), 2u32.into()); } +#[test] +fn classes_keep_the_identity_and_signatures_of_their_scopes() { + let first = r#"`timescale 1ns/1ns +class C; bit [7:0] x; endclass +module A(output int a); + C c; + initial begin c = new; c.x = 300; a = c.x; end +endmodule"#; + let second = r#"`timescale 1ns/1ns +package p; + parameter int N = 8; + class B; virtual function int f(); return 1; endfunction static function bit [N-1:0] g(); return '1; endfunction endclass +endpackage +package q; + class D extends p::B; virtual function int f(); return 5; endfunction endclass +endpackage +class C; bit [15:0] x; endclass +module Top(output int narrow, output int wide, output int over, output int bits); + parameter int N = 16; + int a; + A ua(.a(a)); + C c; + p::B b; + q::D d; + initial begin + c = new; c.x = 300; d = new; b = d; + #1; + narrow = a; + wide = c.x; + over = b.f(); + bits = $bits(p::B::g()); + end +endmodule"#; + let mut sim = celox::Simulation::from_sv_sources( + vec![ + (first, Path::new("first.sv")), + (second, Path::new("second.sv")), + ], + "Top", + ) + .build() + .unwrap(); + sim.run_until(1).unwrap(); + // Each source's compilation-unit class `C` is its own (3.12.1). + assert_eq!(sim.get(sim.signal("narrow")), 44u32.into()); + assert_eq!(sim.get(sim.signal("wide")), 300u32.into()); + // A subclass of another package reaches its override. + assert_eq!(sim.get(sim.signal("over")), 5u32.into()); + // A package method keeps the width of its package's parameter. + assert_eq!(sim.get(sim.signal("bits")), 8u32.into()); +} + sv_backends! { fn class_randomization_enum_inheritance(sim) { @case "class::randomization_enum_inheritance"; } fn class_randomization_enum_alias(sim) { @case "class::randomization_enum_alias"; } @@ -635,6 +840,46 @@ sv_backends! { fn class_randomization_enum_fill_literals(sim) { @case "class::randomization_enum_fill_literals"; } } +// The methods and static properties a module class inherits from a class of +// a package in another source keep what they are there: a source-local +// method identifier does not make a method of the module static, and a +// static property keeps the width the package's constants give it. +#[test] +fn inherited_members_of_package_classes_keep_their_declarations() { + let package = r#"package p; + localparam int N = 8; + class B; + static bit [N-1:0] x; + static function int g(); return 1; endfunction + endclass +endpackage"#; + let module = r#"module Top(output int value, output int width); + localparam int N = 16; + class D extends p::B; + int y; + function int f(); y = 3; return y + $bits(x); endfunction + endclass + D d; + initial begin + d = new; + value = d.f(); + width = $bits(p::B::x); + end +endmodule"#; + let mut sim = celox::Simulation::from_sv_sources( + vec![ + (package, Path::new("packages.sv")), + (module, Path::new("top.sv")), + ], + "Top", + ) + .build() + .unwrap(); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("value")), 11u32.into()); + assert_eq!(sim.get(sim.signal("width")), 8u32.into()); +} + sv_backends! { fn class_randomization_cyclic_enum_alias(sim) { @case "class::randomization_cyclic_enum_alias"; } fn class_randomization_cyclic_domains(sim) { @case "class::randomization_cyclic_domains"; } diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 2a1006e78ec..3b3b3796d19 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -32,7 +32,7 @@ synthesis and is tested at the design level. | Selects | constant and run-time bit selects and indexed part-selects (`[i]`, `[i +: W]`, `[i -: W]`), in reads and writes, in either declaration direction | | Patterns | assignment patterns for packed structs, packed arrays and unpacked arrays (`'{a, b}`, `'{x: a, default: 0}`, `'{n{a}}`, `T'{...}`) | | Strings | `string` variables, function arguments and results: assignment of strings, string literals and casts (`string'(x)`), `==`, `!=` and ordering comparisons, concatenation and replication (with a run-time count), character reads and writes (`s[i]`), and the methods `len`, `getc`, `putc`, `toupper`, `tolower`, `compare`, `icompare`, `substr`, `atoi` / `atohex` / `atooct` / `atobin` and `itoa` / `hextoa` / `octtoa` / `bintoa`; `%s` and format-less display of string values. See [strings](#strings) | -| Classes | classes declared in a module: properties of 2-state integral types up to 64 bits, `string` and class handle types, with initializers; `new` with and without arguments, implicit and explicit constructors; methods (`function` and `task`, also `extern` with an out-of-block body) called through a handle or unqualified inside the class; `this`, `null`, handle assignment and comparison; inheritance of properties and methods, with base constructors called by `super.new(...)` or `extends Base(...)`; `super.` members; virtual methods, abstract (`virtual`) classes and pure virtual methods; classes that implement interface classes and method calls through interface class handles; `$cast` of class handles, as a function and as a task; static properties and methods; `C::` scope resolution of static members and `C::new`; arrays of handles; parameterized classes with value and type parameters, parameters read through a handle or `C#(...)::`, typedefs of classes and interface classes and `C::T`; named constructor arguments; shallow copies (`new h`). See [classes](#classes) | +| Classes | classes declared in a module, a package or the compilation unit: properties of 2-state integral types up to 64 bits, `string` and class handle types, with initializers; `new` with and without arguments, implicit and explicit constructors; methods (`function` and `task`, also `extern` with an out-of-block body) called through a handle or unqualified inside the class; `this`, `null`, handle assignment and comparison; inheritance of properties and methods, with base constructors called by `super.new(...)` or `extends Base(...)`; `super.` members; virtual methods, abstract (`virtual`) classes and pure virtual methods; classes that implement interface classes and method calls through interface class handles; `$cast` of class handles, as a function and as a task; static properties and methods; `C::` scope resolution of static members and `C::new`; arrays of handles; parameterized classes with value and type parameters, parameters read through a handle or `C#(...)::`, typedefs of classes and interface classes and `C::T`; named constructor arguments; shallow copies (`new h`). See [classes](#classes) | | Parameters | integral parameters and overrides preserving widths beyond 128 bits and X/Z values, and parameters of unpacked array or packed struct type given by an assignment pattern (constant tables), including unpacked-array pattern overrides | ### Processes and control flow @@ -187,7 +187,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, classes declared in packages, and properties that are 4-state, `real`, arrays or wider than 64 bits. Timed tasks with static local declarations, recursive calls and `ref` arguments 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, specializations of a parameterized class outside the package or compilation unit that declares it, a static property of a package or compilation-unit class that processes of two module instances write (see [packages](#packages)), and properties that are 4-state, `real`, arrays or wider than 64 bits. Timed tasks with static local declarations, recursive calls and `ref` arguments remain unsupported. - Behavioral and verification constructs: `final`, intra-assignment timing controls (`a = #1 b`), delayed continuous assignments ([#444](https://github.com/celox-sim/celox/issues/444)), named events and `->`, `fork` / `join`, `wait fork` / `disable fork`, concurrent assertions, `force` / `release`. @@ -342,6 +342,18 @@ different interface classes or specializations must declare its own scopes of a module name before it runs, binding an assignment inside a generate block once for each of its instances. +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 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, so their writers follow the rules of +package variables. 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. + 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 66f8b95f40b..da84f4d8c8d 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -29,7 +29,7 @@ outline: [2, 3] | 式 | `**` を含む算術、論理、シフト、比較、リダクション、連結・複製、`?:`、`inside`、`==?` / `!=?`、キャスト(`N'(x)`、`signed'(x)`、`T'(x)`)、`$signed` / `$unsigned` | | 選択 | 定数・実行時のビット選択と indexed part-select(`[i]`、`[i +: W]`、`[i -: W]`)。読み書きの両方、宣言の向きによらず | | パターン | packed 構造体・packed 配列・unpacked 配列の assignment pattern(`'{a, b}`、`'{x: a, default: 0}`、`'{n{a}}`、`T'{...}`) | -| クラス | モジュール内で宣言したクラス。64 ビット以下の 2 値整数型・`string`・クラスハンドル型のプロパティ(初期値つきも可)、引数あり・なしの `new`、暗黙と明示のコンストラクタ、ハンドル経由またはクラス内から修飾なしで呼ぶメソッド(`function` と `task`、本体をクラス外に書く `extern` も可)、`this`、`null`、ハンドルの代入と比較、プロパティとメソッドの継承(基底クラスのコンストラクタは `super.new(...)` か `extends Base(...)` で呼ぶ)、`super.` によるメンバ参照、virtual メソッド、抽象クラス(`virtual class`)と pure virtual メソッド、interface クラスを実装するクラスと interface クラスのハンドルを通したメソッド呼び出し、関数とタスクとしてのクラスハンドルの `$cast`、static プロパティとメソッド、static メンバと `C::new` の `C::` によるスコープ解決、ハンドルの配列、値パラメータと型パラメータを持つパラメータ付きクラス、ハンドルや `C#(...)::` を通したパラメータの参照、クラスと interface クラスの typedef と `C::T`、名前付きのコンストラクタ引数、浅いコピー(`new h`)。[クラス](#classes)を参照 | +| クラス | モジュール・package・コンパイル単位で宣言したクラス。64 ビット以下の 2 値整数型・`string`・クラスハンドル型のプロパティ(初期値つきも可)、引数あり・なしの `new`、暗黙と明示のコンストラクタ、ハンドル経由またはクラス内から修飾なしで呼ぶメソッド(`function` と `task`、本体をクラス外に書く `extern` も可)、`this`、`null`、ハンドルの代入と比較、プロパティとメソッドの継承(基底クラスのコンストラクタは `super.new(...)` か `extends Base(...)` で呼ぶ)、`super.` によるメンバ参照、virtual メソッド、抽象クラス(`virtual class`)と pure virtual メソッド、interface クラスを実装するクラスと interface クラスのハンドルを通したメソッド呼び出し、関数とタスクとしてのクラスハンドルの `$cast`、static プロパティとメソッド、static メンバと `C::new` の `C::` によるスコープ解決、ハンドルの配列、値パラメータと型パラメータを持つパラメータ付きクラス、ハンドルや `C#(...)::` を通したパラメータの参照、クラスと interface クラスの typedef と `C::T`、名前付きのコンストラクタ引数、浅いコピー(`new h`)。[クラス](#classes)を参照 | | 文字列 | `string` 型の変数、関数の引数と戻り値。文字列・文字列リテラル・キャスト(`string'(x)`)の代入、`==` / `!=` と大小比較、連結と複製(実行時の回数も可)、文字の読み書き(`s[i]`)、メソッド `len`、`getc`、`putc`、`toupper`、`tolower`、`compare`、`icompare`、`substr`、`atoi` / `atohex` / `atooct` / `atobin`、`itoa` / `hextoa` / `octtoa` / `bintoa`。`%s` と書式なしの表示。[文字列](#strings)を参照 | | パラメータ | 整数のパラメータ、128ビットを超える幅と X/Z を保持するパラメータ上書き、assignment pattern で与える unpacked 配列型・packed 構造体型のパラメータ(定数テーブル)と unpacked 配列のパターンによる上書き | @@ -163,7 +163,7 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 その構文を追跡する issue の番号が含まれます。専用の issue がない構文は、フロントエンドの ロードマップ [#88](https://github.com/celox-sim/celox/issues/88) を指します。 -- [対応範囲](#classes)外のクラスの機能:クラスハンドル以外の変数への `$cast`、クラス内で宣言した列挙定数、クラスパラメータの値としての列挙型・構造体型・共用体型と名前付きの 4 値・文字列定数、package 内で宣言したクラス、4 値・`real`・配列・64 ビットを超えるプロパティ。時間待ちを含む task の static ローカル宣言、再帰呼び出し、`ref` 引数。 +- [対応範囲](#classes)外のクラスの機能:クラスハンドル以外の変数への `$cast`、クラス内で宣言した列挙定数、クラスパラメータの値としての列挙型・構造体型・共用体型と名前付きの 4 値・文字列定数、宣言した package やコンパイル単位の外でのパラメータ付きクラスの特殊化、2 つのモジュールインスタンスのプロセスが書き込む package・コンパイル単位のクラスの static プロパティ、4 値・`real`・配列・64 ビットを超えるプロパティ。時間待ちを含む task の static ローカル宣言、再帰呼び出し、`ref` 引数。 - interface のポート、`inout` / `ref` / 式を使う modport、virtual interface など。 interface 自体と入れ子の interface は対応しています。型パラメータはインスタンスごとに解決し、modport ポート経由でも伝搬します。 再帰する特殊化と64段を超える入れ子は拒否します。細かな制約は[英語版の一覧](/guide/systemverilog-reference#interface-restrictions)を参照してください。 @@ -216,6 +216,8 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 パラメータ付きクラスでは、パラメータの値と型の組ごとに 1 つの特殊化があり、それぞれが独立したクラスとして static プロパティを持ちます(IEEE 1800-2023 8.25)。`C#(2, int)` と `C#(.T(int), .N(2))` は同じ特殊化で、`C#(2)` のハンドルは `C#(3)` の変数に代入できません。パラメータ値の割り当ては書いた場所で評価するので、モジュールのパラメータに依存してもかまいません。型としてのクラス名だけはクラスの中でもデフォルトの特殊化 `C#()` を表します。`::` の前に置いたクラス名は、クラスの中と extern メソッドの本体では宣言中の特殊化を指し、それ以外の場所では `C#()::` と書く必要があります(8.25.1)。interface クラスは継承する interface クラスのパラメータと typedef を引き継ぎ、異なる interface クラスや特殊化から同じ名前を引き継ぐ場合は自分で宣言し直す必要があります(8.26.6.2、8.26.6.3)。Celox はモジュールの型とスコープが参照する特殊化を実行前にすべて作り、generate ブロック内の割り当てはそのインスタンスごとに評価します。 +package やコンパイル単位で宣言したクラスは、宣言した場所で一度だけレイアウトを決めてメソッドを下ろします(IEEE 1800-2023 3.12.1、26.3)。モジュールは import や `p::C` で、コンパイル単位のクラスなら名前で、別のソースファイルからでも使えます。static プロパティは package の変数なので、書き込みは package 変数の規則に従います。モジュールのクラスはこれを継承して virtual メソッドをオーバーライドでき、そのモジュールのハンドルを通した呼び出しはモジュールのクラスのオーバーライドにも届きます。パラメータ付きクラスの特殊化はクラスを宣言した場所で作るので、そのスコープの外ではそこで名前を挙げた特殊化だけを使えます。package とコンパイル単位の要素だけのソースは、それらのスコープをエラボレーションします。 + チェックポイントはオブジェクトを保持します。状態ファイルは文字列を記録しますがオブジェクトは記録しないため、オブジェクトを持つ変数があると状態ファイルの保存は失敗します。 ### インスタンス配列の要素