From 462d189a32789bbf644148548c37aa153a2b0c04 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 22 Oct 2026 23:47:38 +0900 Subject: [PATCH] feat(sv)!: support interface class handles and $cast of class handles A variable of an interface class type holds a handle of an object whose class implements it; a method called through it runs the implementation of the object's class, including methods the interface class inherits from the interface classes it extends (IEEE 1800-2023 8.26). Each method of an interface class gets a dispatcher like a virtual method's. A handle may only be assigned to a variable of its class, a base class or an interface class it implements; any other assignment to a variable, a property or from `C::new` is rejected (8.16, 8.26.5). `$cast` to a class handle calls a subroutine generated for the destination class: it assigns a source that is `null` or whose object's class derives from or implements the class and returns 1, and otherwise returns 0, leaving the destination unchanged. Called as a task, a failing cast reports an error. A cast between classes that are not cast compatible fails without a call (8.16). Interface classes are now lowered; one whose methods use its own typedefs or type parameters is left without subroutines and rejected only where its handles are used. sv-tests: 8.26.5--cast_between_interface_classes now passes in both state modes (543 / 545). Verilator's failing interface-to-interface casts and inherited interface methods, and Icarus's missing $cast and interface classes, are recorded as limitations. BREAKING CHANGE: `AnalyzerError` has an `IncompatibleClassHandle` variant, and assignments of incompatible class handles that were accepted are now rejected. Change-Id: I1edcc030c35a6bec183c76b567cff49e1319a7e5 --- conformance/sv-tests/README.md | 11 + conformance/sv-tests/expected.tsv | 4 +- crates/celox-sv-analyzer/src/ast/classes.rs | 197 ++++++++++++++---- .../src/ast/dimensions/discovery.rs | 29 ++- .../src/ast/expression_binding.rs | 17 +- .../src/ast/expression_binding/direct.rs | 25 ++- .../src/ast/expression_binding/objects.rs | 109 +++++++++- .../celox-sv-analyzer/src/ast/procedural.rs | 183 +++++++++++++++- crates/celox-sv-analyzer/src/lib.rs | 11 + crates/celox-test-suite/LIMITATIONS.md | 5 +- .../celox-test-suite/src/sv/cases/class.vtest | 185 ++++++++++++++++ .../repros/interface_class_casts.sv | 28 +++ .../interface_class_casts_verilator.json | 40 ++++ .../verification/sv/icarus/class.json | 104 ++++++++- .../verification/sv/limitations.json | 59 +++++- .../verification/sv/limitations/icarus.json | 36 +++- .../sv/limitations/verilator.json | 20 +- .../verification/sv/verilator/class.json | 69 ++++++ .../tests/frontends/systemverilog/class.rs | 35 ++++ docs/guide/systemverilog-reference.md | 16 +- docs/ja/guide/systemverilog-reference.md | 8 +- 21 files changed, 1106 insertions(+), 85 deletions(-) create mode 100644 crates/celox-test-suite/verification/repros/interface_class_casts.sv create mode 100644 crates/celox-test-suite/verification/repros/interface_class_casts_verilator.json diff --git a/conformance/sv-tests/README.md b/conformance/sv-tests/README.md index a0c9b0c88e3..d1cba2b74f9 100644 --- a/conformance/sv-tests/README.md +++ b/conformance/sv-tests/README.md @@ -187,6 +187,17 @@ passing negative case: its return types conflict, which is rejected. Calls through interface class handles, `$cast`, parameterized classes and shallow copies stay unsupported. +Interface class handles and `$cast` of class handles update two more rows: both +state modes for `8.26.5--cast_between_interface_classes` change from fail to +pass. The case was simulated with calls added after the cast, which reached the +object through both interface class handles. Full official runs at the pinned +revision report 544 passing cases in 2state and 546 in 4state, with no passing +case regressing: an interface class whose methods use its own typedefs or type +parameters, as in `8.26.3--type_access_extends` and +`8.26.6.2--parameter_type_conflict`, is still elaborated without being lowered. +`6.24.2--cast_fn`, `6.24.2--cast_task` and `8.16--cast_func` keep failing +because they cast to integral and enum variables. + The report contains each case’s state mode, verdict, selected execution mode, tags, tool return code and path to the official log. The output directory retains both the official log and runner diagnostics for each case and state mode. diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index df6b904eb10..6e2efb757e4 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1523,8 +1523,8 @@ chapter-8/8.26.4--illegal_forward_def_implements.sv 2state pass chapter-8/8.26.4--illegal_forward_def_implements.sv 4state pass chapter-8/8.26.4--illegal_implements_parameter.sv 2state pass chapter-8/8.26.4--illegal_implements_parameter.sv 4state pass -chapter-8/8.26.5--cast_between_interface_classes.sv 2state fail -chapter-8/8.26.5--cast_between_interface_classes.sv 4state fail +chapter-8/8.26.5--cast_between_interface_classes.sv 2state pass +chapter-8/8.26.5--cast_between_interface_classes.sv 4state pass chapter-8/8.26.5--implemented_class_handle.sv 2state pass chapter-8/8.26.5--implemented_class_handle.sv 4state pass chapter-8/8.26.5--invalid_interface_instantiation.sv 2state pass diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index 55eff2a48e9..aea08638043 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -69,8 +69,15 @@ pub(super) struct Class { /// Identifies the class at run time; stable across modules and runs. pub id: u32, pub base: Option, - /// A `virtual class`, which cannot be constructed (IEEE 1800-2023 8.21). + /// The interface classes the class implements, or the interface class + /// extends (IEEE 1800-2023 8.26). + pub interfaces: Vec, + /// A `virtual class` or an interface class, which cannot be constructed + /// (IEEE 1800-2023 8.21, 8.26). pub is_abstract: bool, + /// An interface class: it has no properties and its methods are pure + /// virtual (IEEE 1800-2023 8.26). + pub is_interface: bool, /// Properties of the class and its bases, bases first. pub properties: Vec, /// How many of `properties` the bases declare. @@ -138,7 +145,9 @@ impl Class { .filter(|method| method.owner == self.name && method.is_virtual) } - /// Whether the class is `ancestor` or derives from it. + /// Whether the class is `ancestor`, derives from it or implements it, + /// so that a handle of the class may be assigned to a variable of + /// `ancestor` (IEEE 1800-2023 8.16, 8.26.5). pub fn derives_from( &self, tree: &AnalysisContext<'_>, @@ -146,18 +155,28 @@ impl Class { env: &HashMap, aliases: &HashMap, ) -> bool { - let mut class = Some(self.name.clone()); - while let Some(name) = class { + let mut pending = vec![self.name.clone()]; + let mut seen = HashSet::default(); + while let Some(name) = pending.pop() { if name == ancestor { return true; } - class = self::class(tree, &name, env, aliases) - .ok() - .and_then(|class| class.base.clone()); + if !seen.insert(name.clone()) { + continue; + } + if let Ok(class) = self::class(tree, &name, env, aliases) { + pending.extend(class.base.iter().chain(&class.interfaces).cloned()); + } } false } + /// The subroutine that `$cast` to a variable of `class` calls (IEEE + /// 1800-2023 8.16). + pub fn cast_name(class: &str) -> String { + format!("{class}::$cast") + } + /// An allocation of an uninitialized object of the class. pub fn allocation(&self) -> Expr { let handles = self @@ -192,8 +211,12 @@ fn declaration<'a>( .find(|class| instances::normalize_identifier(&class.name.spelling) == name) } -/// The classes that body item `item` declares, except interface classes, -/// which have no implementation (IEEE 1800-2023 8.26). +/// Whether `name` is an interface class (IEEE 1800-2023 8.26). +pub(super) fn is_interface(tree: &AnalysisContext<'_>, name: &str) -> bool { + declaration(tree, name).is_some_and(|declaration| declaration.interface) +} + +/// The classes and interface classes that body item `item` declares. pub(super) fn item_classes( item: celox_sv_syntax::BodyItemId, tree: &AnalysisContext<'_>, @@ -208,9 +231,7 @@ pub(super) fn item_classes( .classes .iter() .filter(|class| { - !class.interface - && item.tokens.start <= class.tokens.start - && class.tokens.end <= item.tokens.end + item.tokens.start <= class.tokens.start && class.tokens.end <= item.tokens.end }) .map(|class| instances::normalize_identifier(&class.name.spelling)) .collect() @@ -308,10 +329,15 @@ pub(super) fn class( } let declaration = declaration(tree, name).ok_or_else(|| unsupported(format!("class `{name}`")))?; + let native = tree.declarations(); + let interfaces = declaration + .interfaces + .iter() + .map(|&interface| interface_name(tree, interface, env, aliases)) + .collect::>>()?; if declaration.interface { - return Err(unsupported("interface class")); + return interface_class(tree, name, declaration, interfaces, env, aliases); } - let native = tree.declarations(); let base = match &declaration.base { None => None, Some(base) => { @@ -406,8 +432,13 @@ pub(super) fn class( // implements it with the same return type (8.26.2, 8.26.6.1). An // abstract class may instead re-declare it pure (8.26.7). let mut required = Vec::new(); - for &interface in &declaration.interfaces { - interface_methods(tree, interface, env, aliases, &mut required)?; + for interface in &interfaces { + required.extend( + class(tree, interface, env, aliases)? + .methods + .iter() + .map(|method| (method.name.clone(), method.native)), + ); } for (method_name, prototype) in required { match methods.iter_mut().find(|method| method.name == method_name) { @@ -447,7 +478,9 @@ pub(super) fn class( name: name.to_owned(), id: class_id(name), base: base.map(|base| base.name.clone()), + interfaces, is_abstract: declaration.virtual_class, + is_interface: false, properties, base_properties, statics, @@ -461,32 +494,84 @@ pub(super) fn class( Ok(class) } -/// The methods that interface class type `interface` declares or inherits, -/// with their prototypes, appended to `methods` (IEEE 1800-2023 8.26). A -/// name that several interface classes declare appears once for each. -fn interface_methods( +/// The interface class that type `interface` of an `implements` or an +/// interface class's `extends` list names (IEEE 1800-2023 8.26). +fn interface_name( tree: &AnalysisContext<'_>, interface: celox_sv_syntax::TypeId, env: &HashMap, aliases: &HashMap, - methods: &mut Vec<(String, celox_sv_syntax::SubroutineId)>, -) -> Converted<()> { +) -> Converted { let native = tree.declarations(); 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"))?; - let declaration = declaration(tree, &name) - .filter(|declaration| declaration.interface) - .ok_or_else(|| unsupported(format!("`implements` of `{name}`, not an interface class")))?; - for method in &declaration.methods { - let method_name = - instances::normalize_identifier(&native.subroutine(method.subroutine).name.spelling); - methods.push((method_name, method.subroutine)); + if !declaration(tree, &name).is_some_and(|declaration| declaration.interface) { + return Err(unsupported(format!( + "`implements` of `{name}`, not an interface class" + ))); + } + Ok(name) +} + +/// Interface class `name`, whose methods are the pure virtual methods it +/// declares and those of the interface classes it extends (IEEE 1800-2023 +/// 8.26). A handle of it refers to an object of a class implementing it. +fn interface_class( + tree: &AnalysisContext<'_>, + name: &str, + declaration: &celox_sv_syntax::ClassDeclaration, + interfaces: Vec, + env: &HashMap, + aliases: &HashMap, +) -> Converted> { + let native = tree.declarations(); + let mut methods: Vec = Vec::new(); + for interface in &interfaces { + for method in &class(tree, interface, env, aliases)?.methods { + methods.retain(|known| known.name != method.name); + methods.push(method.clone()); + } } - for &base in &declaration.interfaces { - interface_methods(tree, base, env, aliases, methods)?; + for method in &declaration.methods { + let subroutine = native.subroutine(method.subroutine); + // A method whose types cannot be resolved, such as one using a + // type parameter or a typedef of the interface class, leaves the + // interface class without a layout; it is lowered only when used. + type_binding::subroutine_formals( + subroutine, + tree, + &PackedDimensions::new(HashMap::default(), env, aliases), + )?; + return_type(tree, method.subroutine, env, aliases)?; + let method_name = instances::normalize_identifier(&subroutine.name.spelling); + methods.retain(|known| known.name != method_name); + methods.push(Method { + name: method_name, + owner: name.to_owned(), + native: method.subroutine, + qualifiers: method.qualifiers, + is_virtual: true, + }); } - Ok(()) + let class = Rc::new(Class { + name: name.to_owned(), + id: class_id(name), + base: None, + interfaces, + is_abstract: true, + is_interface: true, + properties: Vec::new(), + base_properties: 0, + statics: Vec::new(), + methods, + size: 1, + }); + tree.state + .classes + .borrow_mut() + .insert(name.to_owned(), class.clone()); + Ok(class) } /// The return type of subroutine `id`, `None` for a task or `void`. @@ -562,17 +647,16 @@ fn class_id(name: &str) -> u32 { hash.max(1) } -/// The overrides that dispatcher `Class::dispatcher_name(owner, method)` -/// calls: each implementation of the method with the classes, deriving from -/// `owner` and not abstract, whose objects run it. -pub(super) fn dispatch_targets( +/// The classes whose objects a handle of class `ancestor` may refer to: +/// those deriving from it or implementing it that are not abstract (IEEE +/// 1800-2023 8.16), laid out. +fn object_classes( tree: &AnalysisContext<'_>, - owner: &str, - method: &str, + ancestor: &str, env: &HashMap, aliases: &HashMap, -) -> Converted)>> { - let mut targets: Vec<(String, Vec)> = Vec::new(); +) -> Converted>> { + let mut classes = Vec::new(); let mut ids = HashMap::default(); for declaration in &tree.declarations().classes { if declaration.interface || declaration.virtual_class { @@ -583,7 +667,7 @@ pub(super) fn dispatch_targets( let Ok(class) = class(tree, &name, env, aliases) else { continue; }; - if !class.derives_from(tree, owner, env, aliases) { + if !class.derives_from(tree, ancestor, env, aliases) { continue; } if let Some(other) = ids.insert(class.id, name.clone()) { @@ -591,6 +675,23 @@ pub(super) fn dispatch_targets( "classes `{other}` and `{name}` with the same run-time identifier" ))); } + classes.push(class); + } + Ok(classes) +} + +/// The overrides that dispatcher `Class::dispatcher_name(owner, method)` +/// calls: each implementation of the method with the classes, deriving from +/// or implementing `owner` and not abstract, whose objects run it. +pub(super) fn dispatch_targets( + tree: &AnalysisContext<'_>, + owner: &str, + method: &str, + env: &HashMap, + aliases: &HashMap, +) -> Converted)>> { + let mut targets: Vec<(String, Vec)> = Vec::new(); + for class in object_classes(tree, owner, env, aliases)? { let Some(implementation) = class.method(method) else { continue; }; @@ -603,6 +704,20 @@ pub(super) fn dispatch_targets( Ok(targets) } +/// The run-time identifiers of the classes whose objects `$cast` may assign +/// to a variable of class `name` (IEEE 1800-2023 8.16). +pub(super) fn cast_targets( + tree: &AnalysisContext<'_>, + name: &str, + env: &HashMap, + aliases: &HashMap, +) -> Converted> { + Ok(object_classes(tree, name, env, aliases)? + .iter() + .map(|class| class.id) + .collect()) +} + /// A call of object operation `op`. pub(super) fn object_call(op: ObjectOp, args: Vec) -> Expr { Expr::Call { diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs index d15c8400ea1..e822be405e2 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs @@ -457,15 +457,36 @@ fn class_signatures( context, ); } - if !constructor { + if !constructor && !class.interface { publish_signature( classes::Class::subroutine_name(&class_name, "new"), vec![this], - Some(Some(handle)), + Some(Some(handle.clone())), tree, context, ); } + // `$cast` to a variable of the class (8.16). + let formal = |name: &str, direction| { + ( + FunctionArgumentMetadata { + name: name.into(), + direction, + has_default: false, + }, + handle.clone(), + ) + }; + publish_signature( + classes::Class::cast_name(&class_name), + vec![ + formal(procedural::CAST_DESTINATION, ParamDirection::Inout), + formal(procedural::CAST_SOURCE, ParamDirection::Input), + ], + Some(Some(procedural::int_type())), + tree, + context, + ); Ok(()) } /// Publish the signatures of the methods of every class in the source. @@ -474,9 +495,7 @@ pub(in crate::ast) fn all_class_signatures( context: &mut PackedDimensions, ) { for class in &tree.declarations().classes { - if !class.interface { - let _ = class_signatures(class, tree, context); - } + let _ = class_signatures(class, tree, context); } } fn publish_signature( diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding.rs b/crates/celox-sv-analyzer/src/ast/expression_binding.rs index 065187f34ae..0e3c5c64a85 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding.rs @@ -15,8 +15,10 @@ pub(super) use direct::{ }; pub(super) use lvalues::{net_lvalue, variable_lvalue}; pub(super) use objects::{ - Receiver as ObjectReceiver, constructor as object_constructor, method as object_method, - property as object_property, receiver as object_receiver, this as object_this, + Cast as ObjectCast, Receiver as ObjectReceiver, cast as object_cast, + check_assignment as check_handle_assignment, constructor as object_constructor, + method as object_method, property as object_property, receiver as object_receiver, + this as object_this, }; pub(super) use strings::{ call as string_call, method as string_method, native_string, to_string as string_operand, @@ -56,10 +58,13 @@ pub(super) fn expression( .and_then(|shape| shape.class.as_deref()), LValue::Select { .. } => None, }; - if let Some(class) = class - && let Some(call) = objects::constructor(tree, root, native, dimensions, class)? - { - return Ok(call); + if let Some(class) = class { + if let Some(call) = objects::constructor(tree, root, native, dimensions, class)? { + return Ok(call); + } + objects::check_assignment(tree, root, native, dimensions, class, || { + "assignment".to_owned() + })?; } let value = bind_value(root, native, tree, dimensions, shape)?; // A string literal or integral value assigned to a string becomes its diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index ebc5adcd21b..353394f99bd 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -527,7 +527,30 @@ pub(in crate::ast) fn bind_value( } let name = bound_callable_name(tree, *expression, native, dimensions)? .ok_or_else(|| unsupported("method or randomize call"))?; - if name.starts_with('$') && !name.contains("::") { + let cast = match name.as_str() { + "$cast" => objects::cast(tree, args, native, dimensions)?, + _ => None, + }; + if let Some(cast) = cast { + let objects::Cast::Call { + name, + destination, + source, + } = cast + else { + values.push(Expr::Literal("0".into())); + continue; + }; + ( + Finish::Call { + name, + args: vec![Some(destination), Some(source)], + order: Vec::new(), + system: None, + }, + vec![(destination, None), (source, None)], + ) + } else if name.starts_with('$') && !name.contains("::") { let presence = args .iter() .map(|arg| { 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 7665af7a0b4..41b00e548c0 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -321,6 +321,104 @@ pub(in crate::ast) fn method( Ok(Some((subroutine, formals, receiver))) } +/// Check that the handle native expression `id` evaluates to may be +/// assigned to a variable of class `target`: its class derives from or +/// implements `target`, or it is `null` or of a class not known before +/// binding (IEEE 1800-2023 8.16, 8.26.5). +pub(in crate::ast) fn check_assignment( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, + target: &str, + context: impl FnOnce() -> String, +) -> Converted<()> { + let Some(source) = native_class(tree, id, native, dimensions) else { + return Ok(()); + }; + if derives_from(tree, dimensions, &source, target)? { + return Ok(()); + } + Err(AnalyzerError::IncompatibleClassHandle { + context: context(), + actual: source, + target: target.to_owned(), + }) +} + +/// Whether class `class_name` derives from or implements `ancestor`. +fn derives_from( + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, + class_name: &str, + ancestor: &str, +) -> Converted { + Ok(class(tree, dimensions, class_name)?.derives_from( + tree, + ancestor, + &dimensions.const_env, + &dimensions.type_aliases, + )) +} + +/// A `$cast(destination, source)` whose destination is a class handle +/// (IEEE 1800-2023 8.16). +pub(in crate::ast) enum Cast { + /// A call of the destination class's [`Class::cast_name`] subroutine + /// with the destination and the source. + Call { + name: String, + destination: ExprId, + source: ExprId, + }, + /// The source's class is neither assignment nor cast compatible with + /// the destination's, so the cast fails whatever the source's value. + Fails, +} + +/// The `$cast` with `arguments` when its destination is a variable or an +/// array element of a class handle type. +pub(in crate::ast) fn cast( + tree: &AnalysisContext<'_>, + arguments: &[celox_sv_syntax::Argument], + native: &Declarations, + dimensions: &PackedDimensions, +) -> Converted> { + let [destination, source] = arguments else { + return Ok(None); + }; + let (Some(destination), Some(source), None, None) = ( + destination.value, + source.value, + &destination.name, + &source.name, + ) else { + return Ok(None); + }; + let Some(target) = native_class(tree, destination, native, dimensions) else { + return Ok(None); + }; + if property(tree, destination, native, dimensions)?.is_some() { + return Err(unsupported("`$cast` to a class property")); + } + class(tree, dimensions, &target)?; + // The source's class may be a base of the destination's, or an interface + // class, whose object the call checks; any other class's cannot be + // assigned (8.16). + if let Some(source_class) = native_class(tree, source, native, dimensions) + && !derives_from(tree, dimensions, &source_class, &target)? + && !derives_from(tree, dimensions, &target, &source_class)? + && !class(tree, dimensions, &source_class)?.is_interface + { + return Ok(Some(Cast::Fails)); + } + Ok(Some(Cast::Call { + name: Class::cast_name(&target), + destination, + source, + })) +} + /// The receiver of an unqualified method call inside a method. pub(in crate::ast) fn this() -> Expr { Expr::Ident(THIS.into()) @@ -354,7 +452,16 @@ pub(in crate::ast) fn constructor( name, } if separator == "::" && name.spelling == "new" => { match named_class(tree, *expression, native, dimensions) { - Some(class) => class, + Some(class) => { + if !derives_from(tree, dimensions, &class, class_name)? { + return Err(AnalyzerError::IncompatibleClassHandle { + context: format!("`{class}::new`"), + actual: class, + target: class_name.to_owned(), + }); + } + class + } None => return Ok(None), } } diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 6d1661eb256..7fb788f706d 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -111,7 +111,7 @@ pub(super) fn scoped_type(mut r#type: Type, const_env: &HashMap) - } /// The `int` type of a loop variable declared by `foreach`. -fn int_type() -> Type { +pub(super) fn int_type() -> Type { Type { is_enum: false, kind: TypeKind::Bit, @@ -629,7 +629,17 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { self.tree, right, native, &self.dims, class, )? { Some(call) => call, - None => bind(right)?, + None => { + expression_binding::check_handle_assignment( + self.tree, + right, + native, + &self.dims, + class, + || format!("assignment to property `{}`", property.name), + )?; + bind(right)? + } } } _ if op == "=" => bind(right)?, @@ -1177,6 +1187,31 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { .collect::>(); let args = (!arguments.iter().any(|arg| arg.name.is_some())).then_some(presence); let name = name.spelling.as_str(); + // `$cast` as a task reports a run-time error when the cast fails + // (IEEE 1800-2023 6.24.2). + if name == "$cast" + && !discarded + && let Some(cast) = + expression_binding::object_cast(self.tree, arguments, declarations, &self.dims)? + { + let error = Stmt::SystemTask { + task: SystemTask::Severity(system_functions::Severity::Error), + site: source_span(declarations.expression(root).tokens, self.tree), + args: vec![SystemTaskArg::Str( + "$cast of a class handle to an incompatible class".into(), + )], + }; + if let expression_binding::ObjectCast::Fails = cast { + return Ok(vec![error]); + } + let mut succeeded = self.native_value(root)?; + self.rename_expr(&mut succeeded); + return Ok(vec![Stmt::If { + condition: succeeded, + then_body: Vec::new(), + else_body: vec![error], + }]); + } let task = match system_functions::check_call( name, args.as_deref(), @@ -1556,7 +1591,8 @@ pub(super) fn subroutine_argument_names( .collect::>(); // A class that cannot be laid out reports why where it is // lowered. - if let Ok(layout) = classes::class(tree, &class, &item.env, &aliases) { + let layout = classes::class(tree, &class, &item.env, &aliases).ok(); + if let Some(layout) = &layout { methods.extend(layout.dispatched_methods().map(|method| { ( classes::Class::dispatcher_name(&class, &method.name), @@ -1591,15 +1627,23 @@ pub(super) fn subroutine_argument_names( params.into_iter().map(|(name, ..)| name).collect(), ); } - if !constructor { + let handle = dimensions_from_type(&scoped_type(handle, &item.env)); + if !constructor && !layout.is_some_and(|layout| layout.is_interface) { let qualified = item.name(&classes::Class::subroutine_name(&class, "new")); directions.insert(qualified.clone(), vec![ParamDirection::Input]); - shapes.insert( - qualified.clone(), - vec![dimensions_from_type(&scoped_type(handle, &item.env))], - ); + shapes.insert(qualified.clone(), vec![handle.clone()]); names.insert(qualified, vec![classes::THIS.to_owned()]); } + let qualified = item.name(&classes::Class::cast_name(&class)); + directions.insert( + qualified.clone(), + vec![ParamDirection::Inout, ParamDirection::Input], + ); + shapes.insert(qualified.clone(), vec![handle.clone(), handle]); + names.insert( + qualified, + vec![CAST_DESTINATION.to_owned(), CAST_SOURCE.to_owned()], + ); } } Ok((names, shapes, directions)) @@ -2295,7 +2339,13 @@ fn lower_class( state: &mut BodyState<'_>, item: &generate::Item, ) -> Converted> { - let class = classes::class(tree, name, declaration_env, type_aliases)?; + let class = match classes::class(tree, name, declaration_env, type_aliases) { + Ok(class) => class, + // An interface class that cannot be laid out has no subroutines; a + // use of its handles reports why (IEEE 1800-2023 8.26). + Err(_) if classes::is_interface(tree, name) => return Ok(Vec::new()), + Err(error) => return Err(error), + }; let mut subroutines = Vec::new(); let mut constructor = false; for (id, _) in classes::declared_methods(tree, name)? { @@ -2330,7 +2380,7 @@ fn lower_class( Some(&targets), )?); } - if !constructor { + if !constructor && !class.is_interface { let handle = classes::handle_type(tree, name) .ok_or_else(|| unsupported(format!("class `{name}`")))?; let ir_type = crate::ir::Type::from_ast( @@ -2385,9 +2435,122 @@ fn lower_class( } subroutines.push(subroutine); } + subroutines.push(lower_cast( + name, + tree, + declaration_env, + type_aliases, + item_dimensions, + state, + item, + )?); Ok(subroutines) } +/// The formals of [`classes::Class::cast_name`]. +pub(super) const CAST_DESTINATION: &str = "destination"; +pub(super) const CAST_SOURCE: &str = "source"; + +/// The subroutine `$cast` to a variable of class `name` calls: it assigns +/// the source handle to the destination and returns 1 when the source is +/// `null` or its object's class derives from or implements the class, and +/// otherwise returns 0 (IEEE 1800-2023 8.16). +#[allow(clippy::too_many_arguments)] +fn lower_cast( + name: &str, + tree: &AnalysisContext<'_>, + declaration_env: &HashMap, + type_aliases: &HashMap, + item_dimensions: &PackedDimensions, + state: &mut BodyState<'_>, + item: &generate::Item, +) -> Converted { + let environment = const_functions::Environment { + constants: &*item.env, + functions: &tree.state.const_functions, + }; + let handle = + classes::handle_type(tree, name).ok_or_else(|| unsupported(format!("class `{name}`")))?; + let ir_handle = + crate::ir::Type::from_ast(scoped_type(handle.clone(), declaration_env), &environment); + let ir_int = crate::ir::Type::from_ast(int_type(), &environment); + let mut labels = vec![0]; + labels.extend(classes::cast_targets( + tree, + name, + declaration_env, + type_aliases, + )?); + let mut builder = BodyBuilder::new( + tree, + item_dimensions, + state, + system_functions::Body::Subroutine, + ); + builder.automatic = true; + let first_local = builder.state.locals.len(); + builder.push_scope(); + let destination = builder.declare(CAST_DESTINATION, handle.clone()); + let source = builder.declare(CAST_SOURCE, handle); + let result = builder.declare("$cast", int_type()); + builder.pop_scope(); + let assign = |lhs: &str, rhs: Expr| Stmt::Assign { + lhs: LValue::Ident(lhs.to_owned()), + rhs, + nonblocking: false, + }; + let mut subroutine = Subroutine { + name: item.name(&classes::Class::cast_name(name)), + is_task: false, + automatic_locals: builder.state.locals[first_local..] + .iter() + .map(|local| local.name.clone()) + .collect(), + persistent_locals: Vec::new(), + return_type: Some(ir_int), + params: vec![ + SubroutineParam { + name: destination.clone(), + source_name: CAST_DESTINATION.to_owned(), + direction: ParamDirection::Inout, + r#type: ir_handle.clone(), + default: None, + }, + SubroutineParam { + name: source.clone(), + source_name: CAST_SOURCE.to_owned(), + direction: ParamDirection::Input, + r#type: ir_handle, + default: None, + }, + ], + return_var: Some(result.clone()), + body: vec![Stmt::Case { + kind: CaseKind::Exact, + selector: classes::object_call( + system_functions::ObjectOp::ClassOf, + vec![Expr::Ident(source.clone())], + ), + items: vec![CaseItemBase { + labels: labels + .iter() + .map(|id| CaseLabel::Value(Expr::Literal(format!("32'd{id}")))) + .collect(), + body: vec![ + assign(&destination, Expr::Ident(source)), + assign(&result, Expr::Literal("1".into())), + ], + }], + default: Some(vec![assign(&result, Expr::Literal("0".into()))]), + }], + sensitivity_body: Vec::new(), + }; + for stmt in &mut subroutine.body { + qualify_stmt(item, stmt); + } + Ok(subroutine) +} + /// Qualify the module-scope names of a statement for its generate scope. pub(super) fn qualify_stmt(item: &generate::Item, stmt: &mut Stmt) { stmt.visit_mut( diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index 2725f991aff..6cb234e623f 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -147,6 +147,17 @@ pub enum AnalyzerError { actual: typecheck::UnpackedArrayType, target: typecheck::UnpackedArrayType, }, + /// A handle of class `actual` assigned to a variable of class `target` + /// that `actual` neither derives from nor implements; only `$cast` may + /// assign it (IEEE 1800-2023 8.16, 8.26.5). + #[error( + "{context}: a handle of class `{actual}` is not assignment compatible with class `{target}`" + )] + IncompatibleClassHandle { + context: String, + actual: String, + target: String, + }, } impl miette::Diagnostic for AnalyzerError {} diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 287bdccd714..5bf57e9bf84 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -494,7 +494,10 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `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_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 | 3 | 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 three cases. | +| `sv_icarus_abstract_and_interface_classes` | compile | icarus | 6 | 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 the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others. | +| `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. | | `sv_verilator_class_property_string_methods` | compile | verilator | 1 | Verilator 5.052 stops with an internal error ("AstNode is not of expected type, but instead has type 'MEMBERSEL'") on a string method called on a class property, n.name.itoa(42), which IEEE 1800-2023 6.16 and 8.5 permit. Icarus rejects the case too, see sv_icarus_classes. | | `sv_icarus_unpacked_array_patterns` | compile | icarus | 1 | Icarus 13.0 reports that an assignment pattern with unpacked array items assigned to a multidimensional unpacked array is not yet supported ("Procedural assignment of array or array slice"), so the run cannot count it as a language rejection. The design is invalid (IEEE 1800-2023 7.6, 10.8). | | `sv_icarus_display_field_width` | execute | icarus | 1 | Icarus 13.0 zero-pads a value wider than an explicit field width of %h or %o to the argument's full width (%3h of 32'h1234 prints 00001234); IEEE 1800-2023 21.2.1.2 expands the field to the value without leading zeros (1234). Verilator agrees with the expected value. | diff --git a/crates/celox-test-suite/src/sv/cases/class.vtest b/crates/celox-test-suite/src/sv/cases/class.vtest index c7470fd436a..9aec1add777 100644 --- a/crates/celox-test-suite/src/sv/cases/class.vtest +++ b/crates/celox-test-suite/src/sv/cases/class.vtest @@ -526,3 +526,188 @@ endmodule "#) (top Top) (run_until 0) (assert_eq done 1) (expect_output "3 6\n100 200\n")) + +(case methods_called_through_interface_class_handles + (source "class.sv" #" +module Top(output bit done); + interface class Shape; + pure virtual function int area(int scale); + endclass + interface class Named; + pure virtual function int id(); + endclass + interface class Polygon extends Shape; + pure virtual function int sides(); + endclass + class Rectangle; + int w = 2; + virtual function int area(int scale); + return w * scale; + endfunction + endclass + class Square extends Rectangle implements Polygon, Named; + virtual function int area(int scale); + return w * w * scale; + endfunction + virtual function int sides(); + return 4; + endfunction + virtual function int id(); + return 7; + endfunction + endclass + class Label implements Named; + virtual function int id(); + return 9; + endfunction + endclass + Square square; + Label label; + Shape shape; + Named names[2]; + Polygon polygon; + initial begin + square = new; + label = new; + shape = square; + polygon = square; + names[0] = square; + names[1] = label; + $display("%0d %0d", shape.area(3), polygon.sides()); + $display("%0d %0d", names[0].id(), names[1].id()); + shape = polygon; + $display("%0d %0d", shape.area(1), shape == null); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "12 4\n7 9\n4 0\n")) + +(case inherited_methods_of_extended_interface_classes + (source "class.sv" #" +module Top(output bit done); + interface class Named; + pure virtual function int id(); + endclass + interface class Shape; + pure virtual function int sides(); + endclass + interface class NamedShape extends Named, Shape; + pure virtual function int area(); + endclass + class Triangle implements NamedShape; + virtual function int id(); + return 3; + endfunction + virtual function int sides(); + return 3; + endfunction + virtual function int area(); + return 6; + endfunction + endclass + Triangle triangle; + NamedShape shape; + initial begin + triangle = new; + shape = triangle; + $display("%0d %0d %0d", shape.id(), shape.sides(), shape.area()); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "3 3 6\n")) + +(case casts_of_class_handles + (source "class.sv" #" +module Top(output bit done); + class Animal; + virtual function int legs(); + return 0; + endfunction + endclass + class Dog extends Animal; + virtual function int legs(); + return 4; + endfunction + endclass + class Puppy extends Dog; + endclass + class Rock; + endclass + Animal animal; + Dog dog; + Rock rock; + int ok; + initial begin + animal = Puppy::new; + ok = $cast(dog, animal); + $display("%0d %0d", ok, dog.legs()); + animal = new; + ok = $cast(dog, animal); + $display("%0d %0d", ok, dog.legs()); + animal = null; + ok = $cast(dog, animal); + $display("%0d %0d", ok, dog == null); + dog = new; + ok = $cast(animal, dog); + $display("%0d %0d", ok, animal.legs()); + if (!$cast(rock, dog)) + $display("rock"); + ok = $cast(dog, null); + $display("%0d %0d", ok, dog == null); + animal = Dog::new; + $cast(dog, animal); + $display("%0d", dog.legs()); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "1 4\n0 4\n1 1\n1 4\nrock\n1 1\n4\n")) + +(case casts_from_interface_class_handles + (source "class.sv" #" +module Top(output bit done); + interface class Named; + pure virtual function int id(); + endclass + interface class Sized; + pure virtual function int size(); + endclass + class Box implements Named, Sized; + virtual function int id(); + return 1; + endfunction + virtual function int size(); + return 8; + endfunction + endclass + class Tag implements Named; + virtual function int id(); + return 2; + endfunction + endclass + Box box; + Named named; + Sized sized; + int ok; + initial begin + box = new; + named = box; + ok = $cast(sized, named); + $display("%0d %0d", ok, sized.size()); + box = null; + ok = $cast(box, named); + $display("%0d %0d", ok, box.id()); + named = Tag::new; + ok = $cast(sized, named); + $display("%0d %0d", ok, sized.size()); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "1 8\n1 1\n0 8\n")) diff --git a/crates/celox-test-suite/verification/repros/interface_class_casts.sv b/crates/celox-test-suite/verification/repros/interface_class_casts.sv new file mode 100644 index 00000000000..61a6772c27f --- /dev/null +++ b/crates/celox-test-suite/verification/repros/interface_class_casts.sv @@ -0,0 +1,28 @@ +// $cast from a handle of an interface class assigns the object when its class +// is assignment compatible with the destination (IEEE 1800-2023 8.16, 8.26.5). +// Expected output: 1 1. +module Top; + interface class Named; + pure virtual function int id(); + endclass + interface class Sized; + pure virtual function int size(); + endclass + class Box implements Named, Sized; + virtual function int id(); + return 1; + endfunction + virtual function int size(); + return 8; + endfunction + endclass + Box box; + Box back; + Named named; + Sized sized; + initial begin + box = new; + named = box; + $display("%0d %0d", $cast(sized, named), $cast(back, named)); + end +endmodule diff --git a/crates/celox-test-suite/verification/repros/interface_class_casts_verilator.json b/crates/celox-test-suite/verification/repros/interface_class_casts_verilator.json new file mode 100644 index 00000000000..917d747e16b --- /dev/null +++ b/crates/celox-test-suite/verification/repros/interface_class_casts_verilator.json @@ -0,0 +1,40 @@ +{ + "schema_version": 3, + "suite_version": "0.11.0", + "tool": "verilator", + "version": "Verilator 5.052 2026-09-05 rev v5.052", + "cases": [ + { + "category": "Types", + "detail": "native testbench failed: exit status: 1; see runtime.log and protocol.log\n", + "expectation": "Simulation", + "name": "class::casts_from_interface_class_handles", + "phase": "execute", + "status": "runtime_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "counts": { + "passed": 0, + "mismatch": 0, + "compile_error": 0, + "emission_error": 0, + "ignored": 0, + "rejected": 0, + "runtime_error": 1, + "unexpected_accept": 0, + "unsupported": 0 + }, + "include_ignored": true, + "exclude_stronger_than_sv": false, + "standard": "IEEE 1800-2023 8.16 and 8.26.5: $cast from a handle of an interface class succeeds when the object it refers to is assignment compatible with the destination, including a variable of another interface class that the object's class implements.", + "adapter_free": { + "source": "verification/repros/interface_class_casts.sv", + "verilator_command": "verilator --binary --timing -Wno-fatal --top-module Top --Mdir interface_class_casts.sv", + "verilator_version": "Verilator 5.052 2026-09-05 rev v5.052", + "verilator_output": "0 1", + "expected_output": "1 1" + } +} diff --git a/crates/celox-test-suite/verification/sv/icarus/class.json b/crates/celox-test-suite/verification/sv/icarus/class.json index 2c488fd85ce..7d66640caf0 100644 --- a/crates/celox-test-suite/verification/sv/icarus/class.json +++ b/crates/celox-test-suite/verification/sv/icarus/class.json @@ -2,7 +2,7 @@ "cases": [ { "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 three cases.", + "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 the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others.", "expectation": "Simulation", "known_issue": { "category": "simulator_compile_limitation", @@ -13,7 +13,7 @@ "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 three cases.", + "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 the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others.", "upstream": [] }, "name": "class::abstract_classes_and_pure_virtual_methods", @@ -25,7 +25,7 @@ }, { "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 three cases.", + "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 the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others.", "expectation": "Simulation", "known_issue": { "category": "simulator_compile_limitation", @@ -36,7 +36,53 @@ "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 three cases.", + "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 the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others.", + "upstream": [] + }, + "name": "class::casts_from_interface_class_handles", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "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.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_cast", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "execute", + "reason": "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.", + "upstream": [] + }, + "name": "class::casts_of_class_handles", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "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 the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others.", + "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 the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others.", "upstream": [] }, "name": "class::classes_implementing_interface_classes", @@ -114,6 +160,29 @@ "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 the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others.", + "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 the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others.", + "upstream": [] + }, + "name": "class::inherited_methods_of_extended_interface_classes", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "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.", @@ -139,7 +208,30 @@ }, { "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 three cases.", + "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 the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others.", + "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 the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others.", + "upstream": [] + }, + "name": "class::methods_called_through_interface_class_handles", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "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 the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others.", "expectation": "Simulation", "known_issue": { "category": "simulator_compile_limitation", @@ -150,7 +242,7 @@ "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 three cases.", + "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 the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others.", "upstream": [] }, "name": "class::methods_of_handle_array_elements", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index cd5e9eb793d..6373c0fafc4 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -1904,7 +1904,7 @@ "category": "simulator_compile_limitation", "phase": "compile", "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", - "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 three cases.", + "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 the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others.", "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", @@ -1914,7 +1914,62 @@ "icarus": [ "class::abstract_classes_and_pure_virtual_methods", "class::methods_of_handle_array_elements", - "class::classes_implementing_interface_classes" + "class::classes_implementing_interface_classes", + "class::methods_called_through_interface_class_handles", + "class::inherited_methods_of_extended_interface_classes", + "class::casts_from_interface_class_handles" + ] + } + }, + { + "id": "sv_verilator_interface_class_casts", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "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.", + "upstream": [], + "evidence": [ + "verification/repros/interface_class_casts_verilator.json", + "verification/repros/interface_class_casts.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "class::casts_from_interface_class_handles" + ] + } + }, + { + "id": "sv_verilator_extended_interface_class_methods", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "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.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "class::inherited_methods_of_extended_interface_classes" + ] + } + }, + { + "id": "sv_icarus_cast", + "category": "simulator_compile_limitation", + "phase": "execute", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "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.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "class::casts_of_class_handles" ] } }, diff --git a/crates/celox-test-suite/verification/sv/limitations/icarus.json b/crates/celox-test-suite/verification/sv/limitations/icarus.json index bcde8372c4e..52658fffaa6 100644 --- a/crates/celox-test-suite/verification/sv/limitations/icarus.json +++ b/crates/celox-test-suite/verification/sv/limitations/icarus.json @@ -9,8 +9,8 @@ "unexpected_accept": 1, "mismatch": 16, "emission_error": 0, - "compile_error": 116, - "runtime_error": 7, + "compile_error": 119, + "runtime_error": 8, "unsupported": 0, "ignored": 0 }, @@ -1311,6 +1311,38 @@ "name": "class::classes_implementing_interface_classes", "phase": "compile", "status": "compile_error" + }, + { + "category": "Types", + "detail": "Icarus build exit status: 32; see /build.log\n/source_0.sv:3: syntax error\n/source_0.sv:3: error: Invalid module item.\n/source_0.sv:4: syntax error\n/source_0.sv:4: error: Invalid module item.\n/source_0.sv:5: syntax error\n/source_0.sv:6: error: Invalid module item.\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Invalid module item.\n/source_0.sv:8: syntax error\n/source_0.sv:9: error: Invalid module item.\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Invalid module item.\n/source_0.sv:11: syntax error\n/source_0.sv:11: error: Invalid module item.\n/source_0.sv:12: syntax error\n/source_0.sv:13: error: Invalid module item.\n/source_0.sv:14: syntax error\n/source_0.sv:14: error: Invalid module item.\n/source_0.sv:15: syntax error\n/source_0.sv:17: error: Invalid module item.\n/source_0.sv:18: syntax error\n/source_0.sv:18: error: Invalid module item.\n/source_0.sv:19: syntax error\n/source_0.sv:19: error: Invalid module item.\n/source_0.sv:20: syntax error\n/source_0.sv:22: error: Invalid module item.\n/source_0.sv:23: syntax error\n/source_0.sv:23: error: Invalid module instantiation\n/source_0.sv:24: syntax error\n/source_0.sv:24: error: Invalid module instantiation\n/source_0.sv:34: syntax error\n/source_0.sv:34: error: Malformed statement\n", + "expectation": "Simulation", + "name": "class::casts_from_interface_class_handles", + "phase": "compile", + "status": "compile_error" + }, + { + "category": "Types", + "detail": "native testbench failed: exit status: 7; see runtime.log and protocol.log\n/source_0.sv:23: Error: System task/function $cast() is not defined by any module.\n/source_0.sv:26: Error: System task/function $cast() is not defined by any module.\n/source_0.sv:29: Error: System task/function $cast() is not defined by any module.\n/source_0.sv:32: Error: System task/function $cast() is not defined by any module.\n/source_0.sv:34: Error: System task/function $cast() is not defined by any module.\n/source_0.sv:36: Error: System task/function $cast() is not defined by any module.\n/source_0.sv:39: Error: System task/function $cast() is not defined by any module.\n", + "expectation": "Simulation", + "name": "class::casts_of_class_handles", + "phase": "execute", + "status": "runtime_error" + }, + { + "category": "Types", + "detail": "Icarus build exit status: 30; see /build.log\n/source_0.sv:3: syntax error\n/source_0.sv:3: error: Invalid module item.\n/source_0.sv:4: syntax error\n/source_0.sv:4: error: Invalid module item.\n/source_0.sv:5: syntax error\n/source_0.sv:6: error: Invalid module item.\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Invalid module item.\n/source_0.sv:8: syntax error\n/source_0.sv:9: error: Invalid module item.\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Invalid module item.\n/source_0.sv:11: syntax error\n/source_0.sv:12: error: Invalid module item.\n/source_0.sv:13: syntax error\n/source_0.sv:13: error: Invalid module item.\n/source_0.sv:14: syntax error\n/source_0.sv:14: error: Invalid module item.\n/source_0.sv:15: syntax error\n/source_0.sv:16: error: Invalid module item.\n/source_0.sv:17: syntax error\n/source_0.sv:17: error: Invalid module item.\n/source_0.sv:18: syntax error\n/source_0.sv:19: error: Invalid module item.\n/source_0.sv:20: syntax error\n/source_0.sv:20: error: Invalid module item.\n/source_0.sv:21: syntax error\n/source_0.sv:23: error: Invalid module item.\n/source_0.sv:24: syntax error\n/source_0.sv:24: error: Invalid module instantiation\n", + "expectation": "Simulation", + "name": "class::inherited_methods_of_extended_interface_classes", + "phase": "compile", + "status": "compile_error" + }, + { + "category": "Types", + "detail": "Icarus build exit status: 46; see /build.log\n/source_0.sv:3: syntax error\n/source_0.sv:3: error: Invalid module item.\n/source_0.sv:4: syntax error\n/source_0.sv:4: error: Invalid module item.\n/source_0.sv:5: syntax error\n/source_0.sv:6: error: Invalid module item.\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Invalid module item.\n/source_0.sv:8: syntax error\n/source_0.sv:9: error: Invalid module item.\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Invalid module item.\n/source_0.sv:11: syntax error\n/source_0.sv:12: error: Invalid module item.\n/source_0.sv:14: syntax error\n/source_0.sv:14: error: Invalid module item.\n/source_0.sv:15: syntax error\n/source_0.sv:15: error: Invalid module item.\n/source_0.sv:16: syntax error\n/source_0.sv:18: error: Invalid module item.\n/source_0.sv:19: syntax error\n/source_0.sv:19: error: Invalid module item.\n/source_0.sv:20: syntax error\n/source_0.sv:20: error: Invalid module item.\n/source_0.sv:21: syntax error\n/source_0.sv:22: error: Invalid module item.\n/source_0.sv:23: syntax error\n/source_0.sv:23: error: Invalid module item.\n/source_0.sv:24: syntax error\n/source_0.sv:25: error: Invalid module item.\n/source_0.sv:26: syntax error\n/source_0.sv:26: error: Invalid module item.\n/source_0.sv:27: syntax error\n/source_0.sv:29: error: Invalid module item.\n/source_0.sv:30: syntax error\n/source_0.sv:30: error: Invalid module item.\n/source_0.sv:31: syntax error\n/source_0.sv:31: error: Invalid module item.\n/source_0.sv:32: syntax error\n/source_0.sv:34: error: Invalid module item.\n/source_0.sv:35: syntax error\n/source_0.sv:35: error: Invalid module instantiation\n/source_0.sv:36: syntax error\n/source_0.sv:36: error: Invalid module instantiation\n/source_0.sv:38: syntax error\n/source_0.sv:38: error: Invalid module instantiation\n", + "expectation": "Simulation", + "name": "class::methods_called_through_interface_class_handles", + "phase": "compile", + "status": "compile_error" } ] } diff --git a/crates/celox-test-suite/verification/sv/limitations/verilator.json b/crates/celox-test-suite/verification/sv/limitations/verilator.json index 7dde73b816f..fe8238160f7 100644 --- a/crates/celox-test-suite/verification/sv/limitations/verilator.json +++ b/crates/celox-test-suite/verification/sv/limitations/verilator.json @@ -9,8 +9,8 @@ "unexpected_accept": 0, "mismatch": 21, "emission_error": 0, - "compile_error": 17, - "runtime_error": 1, + "compile_error": 18, + "runtime_error": 2, "unsupported": 0, "ignored": 0 }, @@ -410,6 +410,22 @@ "name": "class::string_methods_on_properties", "phase": "compile", "status": "compile_error" + }, + { + "category": "Types", + "detail": "native testbench failed: exit status: 1; see runtime.log and protocol.log\n", + "expectation": "Simulation", + "name": "class::casts_from_interface_class_handles", + "phase": "execute", + "status": "runtime_error" + }, + { + "category": "Types", + "detail": "Verilator build exit status: 1; see /build.log\n%Error: /source_0.sv:28:51: Class method 'sides' not found in class 'NamedShape'\n : ... note: In instance 'celox_suite_tb.dut'\n 28 | $display(\"%0d %0d %0d\", shape.id(), shape.sides(), shape.area());\n | ^~~~~\n ... See the manual at https://verilator.org/verilator_doc.html?v=5.052 for more assistance.\n%Error: Exiting due to 1 error(s)\n", + "expectation": "Simulation", + "name": "class::inherited_methods_of_extended_interface_classes", + "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 736c8fff273..50899178c71 100644 --- a/crates/celox-test-suite/verification/sv/verilator/class.json +++ b/crates/celox-test-suite/verification/sv/verilator/class.json @@ -11,6 +11,41 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "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.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/interface_class_casts_verilator.json", + "verification/repros/interface_class_casts.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_interface_class_casts", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "execute", + "reason": "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.", + "upstream": [] + }, + "name": "class::casts_from_interface_class_handles", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::casts_of_class_handles", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", @@ -66,6 +101,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "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.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_extended_interface_class_methods", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "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.", + "upstream": [] + }, + "name": "class::inherited_methods_of_extended_interface_classes", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", @@ -77,6 +135,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::methods_called_through_interface_class_handles", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", diff --git a/crates/celox/tests/frontends/systemverilog/class.rs b/crates/celox/tests/frontends/systemverilog/class.rs index a70bfda6206..d3ce2c4cdcb 100644 --- a/crates/celox/tests/frontends/systemverilog/class.rs +++ b/crates/celox/tests/frontends/systemverilog/class.rs @@ -20,6 +20,10 @@ sv_backends! { fn class_abstract_classes_and_pure_virtual_methods(sim) { @case "class::abstract_classes_and_pure_virtual_methods"; } fn class_methods_of_handle_array_elements(sim) { @case "class::methods_of_handle_array_elements"; } fn class_classes_implementing_interface_classes(sim) { @case "class::classes_implementing_interface_classes"; } + fn class_methods_called_through_interface_class_handles(sim) { @case "class::methods_called_through_interface_class_handles"; } + fn class_inherited_methods_of_extended_interface_classes(sim) { @case "class::inherited_methods_of_extended_interface_classes"; } + fn class_casts_of_class_handles(sim) { @case "class::casts_of_class_handles"; } + fn class_casts_from_interface_class_handles(sim) { @case "class::casts_from_interface_class_handles"; } } sv_backends! { @@ -158,3 +162,34 @@ fn misplaced_super_new_static_misuse_and_unimplemented_methods_are_rejected() { assert!(error.contains(want), "{error}"); } } + +#[test] +fn incompatible_class_handle_assignments_are_rejected() { + for (statement, want) in [ + ("d = b;", ["handle of class `B`", "class `D`"]), + ("d = u;", ["handle of class `U`", "class `D`"]), + ("i = b;", ["handle of class `B`", "class `I`"]), + ("b = U::new;", ["handle of class `U`", "class `B`"]), + ("d.next = b;", ["handle of class `B`", "class `D`"]), + ("$cast(d.next, b);", ["`$cast` to a class property", ""]), + ] { + let source = format!( + "module Top; + interface class I; endclass + class B; endclass + class D extends B implements I; D next; endclass + class U; endclass + B b; D d; U u; I i; + initial begin d = new; {statement} end + endmodule" + ); + let Err(error) = + Simulator::from_sv_sources(vec![(source.as_str(), Path::new("class.sv"))], "Top") + .build_cranelift() + else { + panic!("`{statement}` is rejected"); + }; + let error = error.to_string(); + assert!(want.iter().all(|want| error.contains(want)), "{error}"); + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index d3358f3d560..a5944c2c5db 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -30,7 +30,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; static properties and methods; `C::` scope resolution of static members and `C::new`; arrays of handles. See [classes](#classes) | +| 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. 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 @@ -128,7 +128,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): method calls through an interface class handle, `$cast`, classes declared in packages, parameterized classes, named constructor arguments, shallow copies (`new h`), 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, typedefs and parameters of interface classes, classes declared in packages, parameterized classes, named constructor arguments, shallow copies (`new h`), 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`. @@ -236,7 +236,17 @@ into the runtime. Reading or writing a property or calling a method through `null` is a runtime error. Constructing an abstract class and a class that leaves a pure virtual method unimplemented are rejected (8.21). A class that implements an interface class implements each of its methods with the same -return type, or, if it is abstract, re-declares it pure (8.26). +return type, or, if it is abstract, re-declares it pure (8.26). A method called +through a handle of an interface class runs the implementation of the object's +class. + +A handle may be assigned to a variable of its class, of a base class or of an +interface class it implements; any other assignment of a handle is an error +(IEEE 1800-2023 8.16, 8.26.5). `$cast(dest, source)` assigns a handle whose +object's class derives from or implements the class of `dest`, or `null`, and +returns 1; otherwise it leaves `dest` unchanged and returns 0, or, called as a +task, reports an error. A `$cast` between classes neither of which derives from +the other, unless the source is an interface class, always fails (8.16). A constructor calls the constructor of the base class first, with the arguments of `super.new(...)` or of the `extends` clause, then runs the diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 7667500252d..64a81f84068 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -28,7 +28,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 クラスを実装するクラス、static プロパティとメソッド、static メンバと `C::new` の `C::` によるスコープ解決、ハンドルの配列。[クラス](#classes)を参照 | +| クラス | モジュール内で宣言したクラス。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::` によるスコープ解決、ハンドルの配列。[クラス](#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 配列のパターンによる上書き | @@ -118,7 +118,7 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 その構文を追跡する issue の番号が含まれます。専用の issue がない構文は、フロントエンドの ロードマップ [#88](https://github.com/celox-sim/celox/issues/88) を指します。 -- [対応範囲](#classes)外のクラスの機能:interface クラスのハンドルを通したメソッド呼び出し、`$cast`、package 内で宣言したクラス、パラメータ付きクラス、名前付きのコンストラクタ引数、浅いコピー(`new h`)、4 値・`real`・配列・64 ビットを超えるプロパティ。時間待ちを含む task の static ローカル宣言、再帰呼び出し、`ref` 引数。 +- [対応範囲](#classes)外のクラスの機能:クラスハンドル以外の変数への `$cast`、interface クラスの typedef とパラメータ、package 内で宣言したクラス、パラメータ付きクラス、名前付きのコンストラクタ引数、浅いコピー(`new h`)、4 値・`real`・配列・64 ビットを超えるプロパティ。時間待ちを含む task の static ローカル宣言、再帰呼び出し、`ref` 引数。 - interface のポート、`inout` / `ref` / 式を使う modport、virtual interface など。 interface 自体と入れ子の interface は対応しています。型パラメータはインスタンスごとに解決し、modport ポート経由でも伝搬します。 再帰する特殊化と64段を超える入れ子は拒否します。細かな制約は[英語版の一覧](/guide/systemverilog-reference#interface-restrictions)を参照してください。 @@ -167,7 +167,9 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 ### クラス {#classes} -クラス型の変数はシミュレータのヒープ上のオブジェクトへのハンドルを持ち、コンストラクタを呼ぶまでは `null` です。文字列と同じく、ハンドルのコピーと比較は 32 ビット整数と同じコストで、プロパティの読み書きとオブジェクトの生成だけがランタイムを呼び出します。どの変数・オブジェクトからも参照されないオブジェクトは、タイムスロットの間と各 `tick` の後に回収されます。メソッドは呼び出したオブジェクトを受け取るので function でも task でもよく、呼び出しは変数のクラスのメソッドに結び付きます(IEEE 1800-2023 8.6)。virtual メソッドの呼び出しは、代わりにオブジェクトのクラスの override を実行します。ただし `super.m(...)` は基底クラスの実装を実行します(8.15、8.20)。override はオブジェクトのクラスで選ぶので、ランタイムの呼び出しが 1 回増えます。`null` を通したプロパティの読み書きやメソッド呼び出しは実行時エラーです。抽象クラスの生成と、pure virtual メソッドを実装しないクラスはエラーになります(8.21)。interface クラスを実装するクラスは、そのメソッドをすべて同じ戻り値型で実装するか、抽象クラスなら pure として宣言し直します(8.26)。 +クラス型の変数はシミュレータのヒープ上のオブジェクトへのハンドルを持ち、コンストラクタを呼ぶまでは `null` です。文字列と同じく、ハンドルのコピーと比較は 32 ビット整数と同じコストで、プロパティの読み書きとオブジェクトの生成だけがランタイムを呼び出します。どの変数・オブジェクトからも参照されないオブジェクトは、タイムスロットの間と各 `tick` の後に回収されます。メソッドは呼び出したオブジェクトを受け取るので function でも task でもよく、呼び出しは変数のクラスのメソッドに結び付きます(IEEE 1800-2023 8.6)。virtual メソッドの呼び出しは、代わりにオブジェクトのクラスの override を実行します。ただし `super.m(...)` は基底クラスの実装を実行します(8.15、8.20)。override はオブジェクトのクラスで選ぶので、ランタイムの呼び出しが 1 回増えます。`null` を通したプロパティの読み書きやメソッド呼び出しは実行時エラーです。抽象クラスの生成と、pure virtual メソッドを実装しないクラスはエラーになります(8.21)。interface クラスを実装するクラスは、そのメソッドをすべて同じ戻り値型で実装するか、抽象クラスなら pure として宣言し直します(8.26)。interface クラスのハンドルを通して呼んだメソッドは、オブジェクトのクラスの実装を実行します。 + +ハンドルは、そのクラス・基底クラス・実装する interface クラスの変数に代入でき、それ以外のハンドルの代入はエラーです(IEEE 1800-2023 8.16、8.26.5)。`$cast(dest, source)` は、オブジェクトのクラスが `dest` のクラスを継承または実装するハンドルか `null` を代入して 1 を返します。それ以外では `dest` を変えずに 0 を返し、タスクとして呼んだ場合はエラーを報告します。どちらも他方を継承しないクラスどうしの `$cast` は、ソースが interface クラスでない限り常に失敗します(8.16)。 コンストラクタは、まず `super.new(...)` または `extends` 節の引数で基底クラスのコンストラクタを呼び、次に自クラスが宣言するプロパティの初期値を設定し、最後に本体を実行します(IEEE 1800-2023 8.17)。static プロパティはクラスを宣言したモジュールの変数なので、モジュールのインスタンスごとに 1 つずつあります。