From 535f07bbdcde0fac8a831e34ab0d777a452db91f Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 22:06:58 +0900 Subject: [PATCH] feat(sv): support static class members, super and base constructors Classes may now extend a class that has a constructor, call members of their base through `super`, and declare static properties and methods (IEEE 1800-2023 8.9, 8.10, 8.15, 8.17, 8.23). - A `new` expression allocates the object and passes it to the constructor `C::new(this, args)`, which only initializes it: it calls the base constructor with the arguments of a leading `super.new(...)` or of `extends Base(...)`, runs the initializers of the properties its class declares, then its body. Constructors are no longer inherited, so a class without one gets an implicit constructor that calls its base. - `super.m()` and `super.p` reach the members of the base through `this`. `C::new` creates an object of class `C`. - A static property is a variable of the module that declares the class, initialized like other module variables, so each module instance has its own. `h.p`, `C::p` and unqualified names inside methods refer to it. A static method takes no `this` and may be called through a handle, as `C::m()` or unqualified inside the class; a static method that uses a non-static member is rejected. - `C::name` with a class `C` is no longer looked up as a package item. - `++` and `--` work on properties. sv-tests: 8.7-constructor_super, 8.8-typed_constructor, 8.9-static_properties, 8.10-static_methods, 8.13-inheritance, 8.14-override_member, 8.15-super, 8.17-constructor_const_arg and 8.23-scope_resolution now pass in both state modes (509 / 511). Icarus 13.0 cannot parse class scope resolution; its failure on the new static-member case is recorded as a reviewed limitation. Change-Id: I15a7dd1a41d0358f92163d3683ed46b3caa06f7a --- conformance/sv-tests/README.md | 15 +- conformance/sv-tests/expected.tsv | 36 +- crates/celox-sv-analyzer/src/ast.rs | 3 + crates/celox-sv-analyzer/src/ast/classes.rs | 144 +++++++- .../celox-sv-analyzer/src/ast/declarations.rs | 5 + .../src/ast/dimensions/discovery.rs | 32 +- .../src/ast/expression_binding.rs | 4 +- .../src/ast/expression_binding/direct.rs | 60 ++-- .../src/ast/expression_binding/objects.rs | 275 ++++++++++----- crates/celox-sv-analyzer/src/ast/imports.rs | 8 + .../celox-sv-analyzer/src/ast/procedural.rs | 315 +++++++++++++----- crates/celox-test-suite/LIMITATIONS.md | 1 + .../celox-test-suite/src/sv/cases/class.vtest | 83 +++++ .../verification/sv/icarus/class.json | 34 ++ .../verification/sv/limitations.json | 17 + .../verification/sv/limitations/icarus.json | 10 +- .../verification/sv/verilator/class.json | 22 ++ .../tests/frontends/systemverilog/class.rs | 30 ++ docs/guide/systemverilog-reference.md | 10 +- docs/ja/guide/systemverilog-reference.md | 6 +- 20 files changed, 865 insertions(+), 245 deletions(-) diff --git a/conformance/sv-tests/README.md b/conformance/sv-tests/README.md index 96c8486ebd1..731745d973d 100644 --- a/conformance/sv-tests/README.md +++ b/conformance/sv-tests/README.md @@ -158,8 +158,19 @@ cases in 2state and 526 in 4state. No passing case regresses: classes that are declared but never constructed, interface classes and pure virtual methods are not lowered. `8.7--constructor` keeps failing because it initializes an implicitly static procedural variable without the `static` keyword, which IEEE -1800-2023 6.21 requires. Inheritance with constructors, `super`, static members, -virtual dispatch and parameterized classes stay unsupported. +1800-2023 6.21 requires; `8.7--constructor_param` fails for the same reason. + +Base constructors, `super`, static members and `C::` scope resolution update +eighteen more rows: both state modes for `8.7--constructor_super`, +`8.8--typed_constructor`, `8.9--static_properties`, `8.10--static_methods`, +`8.13--inheritance`, `8.14--override_member`, `8.15--super`, +`8.17--constructor_const_arg` and `8.23--scope_resolution` change from fail to +pass. Each was simulated and its displayed values checked, including the base +method that a base-class handle calls in `8.14--override_member`. Full official +runs at the pinned revision report 534 passing cases in 2state and 536 in +4state, with no passing case regressing. Virtual dispatch, abstract and +interface classes, classes in packages, parameterized classes and shallow copies +stay unsupported. 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 diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index 0631e5f6113..c63919786c8 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1461,26 +1461,26 @@ chapter-7/unions/tagged/packed.sv 2state fail chapter-7/unions/tagged/packed.sv 4state fail chapter-7/unions/unpacked/basic.sv 2state fail chapter-7/unions/unpacked/basic.sv 4state fail -chapter-8/8.10--static_methods.sv 2state fail -chapter-8/8.10--static_methods.sv 4state fail +chapter-8/8.10--static_methods.sv 2state pass +chapter-8/8.10--static_methods.sv 4state pass chapter-8/8.11--this.sv 2state pass chapter-8/8.11--this.sv 4state pass chapter-8/8.12--assignment.sv 2state pass chapter-8/8.12--assignment.sv 4state pass chapter-8/8.12--shallow_copy.sv 2state fail chapter-8/8.12--shallow_copy.sv 4state fail -chapter-8/8.13--inheritance.sv 2state fail -chapter-8/8.13--inheritance.sv 4state fail -chapter-8/8.14--override_member.sv 2state fail -chapter-8/8.14--override_member.sv 4state fail +chapter-8/8.13--inheritance.sv 2state pass +chapter-8/8.13--inheritance.sv 4state pass +chapter-8/8.14--override_member.sv 2state pass +chapter-8/8.14--override_member.sv 4state pass chapter-8/8.15--super-default-new.sv 2state fail chapter-8/8.15--super-default-new.sv 4state fail -chapter-8/8.15--super.sv 2state fail -chapter-8/8.15--super.sv 4state fail +chapter-8/8.15--super.sv 2state pass +chapter-8/8.15--super.sv 4state pass chapter-8/8.16--cast_func.sv 2state fail chapter-8/8.16--cast_func.sv 4state fail -chapter-8/8.17--constructor_const_arg.sv 2state fail -chapter-8/8.17--constructor_const_arg.sv 4state fail +chapter-8/8.17--constructor_const_arg.sv 2state pass +chapter-8/8.17--constructor_const_arg.sv 4state pass chapter-8/8.18--var_local.sv 2state pass chapter-8/8.18--var_local.sv 4state pass chapter-8/8.18--var_protected.sv 2state pass @@ -1497,8 +1497,8 @@ chapter-8/8.21--abstract_class_inst.sv 2state pass chapter-8/8.21--abstract_class_inst.sv 4state pass chapter-8/8.22--dynamic_method_lookup.sv 2state fail chapter-8/8.22--dynamic_method_lookup.sv 4state fail -chapter-8/8.23--scope_resolution.sv 2state fail -chapter-8/8.23--scope_resolution.sv 4state fail +chapter-8/8.23--scope_resolution.sv 2state pass +chapter-8/8.23--scope_resolution.sv 4state pass chapter-8/8.24--out_of_block_methods.sv 2state pass chapter-8/8.24--out_of_block_methods.sv 4state pass chapter-8/8.25--parametrized_class_extend.sv 2state fail @@ -1559,14 +1559,14 @@ chapter-8/8.7--constructor.sv 2state fail chapter-8/8.7--constructor.sv 4state fail chapter-8/8.7--constructor_param.sv 2state fail chapter-8/8.7--constructor_param.sv 4state fail -chapter-8/8.7--constructor_super.sv 2state fail -chapter-8/8.7--constructor_super.sv 4state fail -chapter-8/8.8--typed_constructor.sv 2state fail -chapter-8/8.8--typed_constructor.sv 4state fail +chapter-8/8.7--constructor_super.sv 2state pass +chapter-8/8.7--constructor_super.sv 4state pass +chapter-8/8.8--typed_constructor.sv 2state pass +chapter-8/8.8--typed_constructor.sv 4state pass chapter-8/8.8--typed_constructor_param.sv 2state fail chapter-8/8.8--typed_constructor_param.sv 4state fail -chapter-8/8.9--static_properties.sv 2state fail -chapter-8/8.9--static_properties.sv 4state fail +chapter-8/8.9--static_properties.sv 2state pass +chapter-8/8.9--static_properties.sv 4state pass chapter-9/9.2.1--initial.sv 2state pass chapter-9/9.2.1--initial.sv 4state pass chapter-9/9.2.2.1--always.sv 2state pass diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 0f5545a9def..6ab988df73b 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -2734,6 +2734,8 @@ struct PackedDimensions { /// assignment patterns passed as arguments. subroutine_param_shapes: Arc>>, subroutine_param_names: Arc>>, + /// The class whose method is being bound. + class_scope: Option, } impl PackedDimensions { @@ -2756,6 +2758,7 @@ impl PackedDimensions { type_query: false, subroutine_param_shapes: Arc::default(), subroutine_param_names: Arc::default(), + class_scope: None, } } } diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index 9b3aefc0111..c4d9aafde87 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -28,6 +28,19 @@ pub(super) struct Property { pub initializer: Option, } +/// A static property of a class: one variable of the module that declares +/// the class, shared by all of its objects (IEEE 1800-2023 8.9). +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct StaticProperty { + pub name: String, + /// The class that declares the property. + pub owner: String, + pub r#type: Type, + /// The name of the variable that holds the property. + pub variable: String, + pub initializer: Option, +} + /// A method of a class. #[derive(Debug, Clone, PartialEq, Eq)] pub(super) struct Method { @@ -47,6 +60,10 @@ pub(super) struct Class { pub base: Option, /// Properties of the class and its bases, bases first. pub properties: Vec, + /// How many of `properties` the bases declare. + pub base_properties: usize, + /// Static properties of the class and its bases. + pub statics: Vec, /// Methods visible in the class, overrides replacing inherited ones. pub methods: Vec, /// Bytes of an object. @@ -63,14 +80,58 @@ impl Class { .find(|property| property.name == name) } + pub fn static_property(&self, name: &str) -> Option<&StaticProperty> { + self.statics.iter().find(|property| property.name == name) + } + pub fn method(&self, name: &str) -> Option<&Method> { self.methods.iter().find(|method| method.name == name) } - /// The subroutine name of `method` of `owner`. + /// The properties the class itself declares. + pub fn own_properties(&self) -> &[Property] { + &self.properties[self.base_properties..] + } + + /// The number of formals of the constructor, which takes the handle of + /// the object it initializes before them. + pub fn constructor_formals(&self, native: &celox_sv_syntax::Declarations) -> usize { + self.method("new").map_or(0, |method| { + native + .subroutine(method.native) + .ports + .as_ref() + .map_or(0, Vec::len) + }) + } + + /// The subroutine name of `method` of `owner`, and the variable name of + /// its static property `method`. pub fn subroutine_name(owner: &str, method: &str) -> String { format!("{owner}::{method}") } + + /// An allocation of an uninitialized object of the class. + pub fn allocation(&self) -> Expr { + let handles = self + .properties + .iter() + .filter_map(|property| { + property + .field + .handle + .map(|handle| (property.field.offset, handle)) + }) + .collect(); + object_call( + ObjectOp::New { + class: self.id, + size: self.size, + handles, + }, + Vec::new(), + ) + } } /// The declaration of class `name`, if one exists. @@ -110,11 +171,12 @@ pub(super) fn item_classes( /// The methods that class `name` implements, with their definitions: the /// method itself or, for an `extern` method, its out-of-block definition. -/// A pure virtual method has none (IEEE 1800-2023 8.21). +/// A pure virtual method has none (IEEE 1800-2023 8.21). Each comes with +/// whether it is static. pub(super) fn declared_methods( tree: &AnalysisContext<'_>, name: &str, -) -> Converted> { +) -> Converted> { let Some(declaration) = declaration(tree, name) else { return Ok(Vec::new()); }; @@ -126,18 +188,55 @@ pub(super) fn declared_methods( .map(|method| { let subroutine = native.subroutine(method.subroutine); if !subroutine.prototype { - return Ok(method.subroutine); + return Ok((method.subroutine, method.qualifiers.is_static)); } let method_name = instances::normalize_identifier(&subroutine.name.spelling); - out_of_block_definition(tree, name, &method_name).ok_or_else(|| { - unsupported(format!( - "extern method `{name}::{method_name}` without a body" - )) - }) + out_of_block_definition(tree, name, &method_name) + .map(|id| (id, method.qualifiers.is_static)) + .ok_or_else(|| { + unsupported(format!( + "extern method `{name}::{method_name}` without a body" + )) + }) }) .collect() } +/// The static properties that the classes of body item `item` declare, +/// which are variables of the module (IEEE 1800-2023 8.9). A class that +/// cannot be laid out declares none here; its uses report why. +pub(super) fn item_statics( + item: celox_sv_syntax::BodyItemId, + tree: &AnalysisContext<'_>, + env: &HashMap, + aliases: &HashMap, +) -> Vec { + item_classes(item, tree) + .into_iter() + .filter_map(|name| { + let class = class(tree, &name, env, aliases).ok()?; + Some( + class + .statics + .iter() + .filter(|property| property.owner == name) + .cloned() + .collect::>(), + ) + }) + .flatten() + .collect() +} + +/// The arguments that the `extends` clause of class `name` passes to the +/// constructor of its base (IEEE 1800-2023 8.17). +pub(super) fn base_arguments<'a>( + tree: &'a AnalysisContext<'_>, + name: &str, +) -> Option<&'a [celox_sv_syntax::Argument]> { + declaration(tree, name)?.base.as_ref()?.arguments.as_deref() +} + /// The handle type of class `name`, if it is a class. pub(super) fn handle_type(tree: &AnalysisContext<'_>, name: &str) -> Option { declaration(tree, name)?; @@ -179,11 +278,13 @@ pub(super) fn class( .as_ref() .map(|base| base.properties.clone()) .unwrap_or_default(); + let base_properties = properties.len(); + let mut statics = base + .as_ref() + .map(|base| base.statics.clone()) + .unwrap_or_default(); let mut size = base.as_ref().map_or(0, |base| base.size); for property in &declaration.properties { - if property.qualifiers.is_static { - return Err(unsupported("static class property")); - } let ty = type_binding::procedural_type( property.declaration.data_type, native, @@ -196,7 +297,19 @@ pub(super) fn class( if !variable.dimensions.is_empty() { return Err(unsupported("class property with unpacked dimensions")); } - let name = instances::normalize_identifier(&variable.name.spelling); + let property_name = instances::normalize_identifier(&variable.name.spelling); + if property.qualifiers.is_static { + statics.retain(|known| known.name != property_name); + statics.push(StaticProperty { + variable: Class::subroutine_name(name, &property_name), + name: property_name, + owner: name.to_owned(), + r#type: ty.clone(), + initializer: variable.value, + }); + continue; + } + let name = property_name; let field = field(&tree.state, &ty, env, size)?; size = field.offset + field.bytes(); properties.push(Property { @@ -207,10 +320,13 @@ pub(super) fn class( }); } } + // A constructor is not inherited: a class without one has an implicit + // constructor (IEEE 1800-2023 8.7). let mut methods = base .as_ref() .map(|base| base.methods.clone()) .unwrap_or_default(); + methods.retain(|method| method.name != "new"); for method in &declaration.methods { let subroutine = native.subroutine(method.subroutine); let method_name = instances::normalize_identifier(&subroutine.name.spelling); @@ -241,6 +357,8 @@ pub(super) fn class( id: class_id(name), base: base.map(|base| base.name.clone()), properties, + base_properties, + statics, methods, size: size.max(1), }); diff --git a/crates/celox-sv-analyzer/src/ast/declarations.rs b/crates/celox-sv-analyzer/src/ast/declarations.rs index 6c4af50f31b..aa2cb256ead 100644 --- a/crates/celox-sv-analyzer/src/ast/declarations.rs +++ b/crates/celox-sv-analyzer/src/ast/declarations.rs @@ -375,6 +375,11 @@ pub(super) fn signals_from_body_item( } values } + BodyItemKind::Unconverted { .. } => classes::item_statics(id, tree, env, aliases) + .into_iter() + .filter(|property| selected_name.is_none_or(|selected| selected == property.variable)) + .map(|property| Signal::new(property.variable, property.r#type)) + .collect(), _ => Vec::new(), }; substitute_signal_local_constants(&mut declared, env); diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs index ce1ddd82ae2..775b26fc042 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs @@ -405,10 +405,10 @@ fn return_type( } Ok(Some(ty)) } -/// The methods of `class` as subroutines `class::method`: a method takes -/// the handle `this` before its formals, and the constructor, declared or -/// implicit, returns the handle of the object it creates (IEEE 1800-2023 -/// 8.6, 8.7). +/// The methods of `class` as subroutines `class::method`: a method that is +/// not static takes the handle `this` before its formals, and the +/// constructor, declared or implicit, returns `this` once it has +/// initialized it (IEEE 1800-2023 8.6, 8.7, 8.10). fn class_signatures( class: &celox_sv_syntax::ClassDeclaration, tree: &AnalysisContext<'_>, @@ -418,25 +418,25 @@ fn class_signatures( let Some(handle) = classes::handle_type(tree, &class_name) else { return Ok(()); }; + let this = ( + FunctionArgumentMetadata { + name: classes::THIS.into(), + direction: ParamDirection::Input, + has_default: false, + }, + handle.clone(), + ); let mut constructor = false; for method in &class.methods { let subroutine = tree.declarations().subroutine(method.subroutine); let mut formals = formal_types(subroutine, tree, context)?; + if !method.qualifiers.is_static { + formals.insert(0, this.clone()); + } let result = if subroutine.kind == SubroutineKind::Constructor { constructor = true; Some(Some(handle.clone())) } else { - formals.insert( - 0, - ( - FunctionArgumentMetadata { - name: classes::THIS.into(), - direction: ParamDirection::Input, - has_default: false, - }, - handle.clone(), - ), - ); return_type(subroutine, tree, context)? }; publish_signature( @@ -450,7 +450,7 @@ fn class_signatures( if !constructor { publish_signature( classes::Class::subroutine_name(&class_name, "new"), - Vec::new(), + vec![this], Some(Some(handle)), tree, context, diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding.rs b/crates/celox-sv-analyzer/src/ast/expression_binding.rs index 54768b99b7d..79354194004 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding.rs @@ -15,8 +15,8 @@ pub(super) use direct::{ }; pub(super) use lvalues::{net_lvalue, variable_lvalue}; pub(super) use objects::{ - constructor as object_constructor, method as object_method, property as object_property, - receiver as object_receiver, this as object_this, + Receiver as ObjectReceiver, 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, 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 a93b9505792..ebc5adcd21b 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -233,16 +233,13 @@ enum Finish { /// A string operation on the bound children, see [`strings`]. StringCall(StringOp), /// A read of property `property` of the object handle child. - ObjectLoad { - class: String, - property: String, - }, + ObjectLoad(crate::ast::classes::Property), /// A call of method subroutine `name` with `formals` formals; the first - /// child is the receiver unless `this` passes the enclosing method's own. + /// child is the object handle when `receiver` is one. MethodCall { name: String, formals: usize, - this: bool, + receiver: objects::Receiver, }, } @@ -419,8 +416,10 @@ pub(in crate::ast) fn bind_value( if args.len() > formals || args.iter().any(|arg| arg.name.is_some()) { return Err(unsupported(format!("arguments of method `{name}`"))); } - let mut children: Vec<_> = - receiver.into_iter().map(|id| (id, None)).collect(); + let mut children = Vec::new(); + if let objects::Receiver::Handle(handle) = receiver { + children.push((handle, None)); + } for arg in args { let Some(value) = arg.value else { return Err(unsupported(format!( @@ -433,7 +432,7 @@ pub(in crate::ast) fn bind_value( Finish::MethodCall { name, formals, - this: receiver.is_none(), + receiver, }, children, ) @@ -712,22 +711,20 @@ pub(in crate::ast) fn bind_value( vec![(*expression, None), (index, None)], ) } - ExprKind::Member { - expression, - separator, - name, - } if separator == "." - && objects::native_class(tree, *expression, native, dimensions) - .is_some() => + ExprKind::Member { .. } + if objects::property(tree, id, native, dimensions)?.is_some() => { - ( - Finish::ObjectLoad { - class: objects::native_class(tree, *expression, native, dimensions) - .expect("checked by the guard"), - property: instances::normalize_identifier(&name.spelling), - }, - vec![(*expression, None)], - ) + let (property, receiver) = objects::property(tree, id, native, dimensions)? + .expect("checked by the guard"); + match receiver { + Some(receiver) => { + (Finish::ObjectLoad(property), vec![(receiver, None)]) + } + None => { + values.push(objects::load(&property, objects::this())); + continue; + } + } } ExprKind::Member { .. } | ExprKind::Select { .. } => { values.push(selected_value(id, native, tree, dimensions)?); @@ -893,22 +890,23 @@ pub(in crate::ast) fn bind_value( Finish::StringCall(op) => { strings::call(op, strings::operands(op, operands, dimensions)) } - Finish::ObjectLoad { class, property } => { + Finish::ObjectLoad(property) => { let handle = operands.pop().ok_or_else(disagreement)?; - objects::load(tree, dimensions, &class, &property, handle)? + objects::load(&property, handle) } Finish::MethodCall { name, formals, - this, + receiver, } => { let mut args: Vec> = Vec::with_capacity(formals + 1); - if this { + if receiver == objects::Receiver::This { args.push(Some(objects::this())); } + let handles = usize::from(receiver != objects::Receiver::Static); args.extend(operands.into_iter().map(Some)); // Omitted trailing arguments take their defaults. - args.resize(formals + 1, None); + args.resize(formals + handles, None); Expr::Call { callee: Callee::Subroutine(name), args, @@ -1213,6 +1211,10 @@ fn path( tree: &AnalysisContext<'_>, dimensions: &PackedDimensions, ) -> Converted<(Vec, Option)> { + // A static class property is a variable of the module. + if let Some(variable) = objects::static_property(tree, root, native, dimensions)? { + return Ok((vec![variable], None)); + } let mut parts = Vec::new(); let mut qualified = None; loop { 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 109c10d885e..5a23baf7cb6 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -28,10 +28,14 @@ pub(in crate::ast) fn native_class( native: &Declarations, dimensions: &PackedDimensions, ) -> Option { - if let ExprKind::Name(name) = &native.expression(ungroup(id, native)).kind - && let Some(ty) = dimensions.get(&instances::normalize_identifier(&name.spelling)) - { - return ty.class.clone(); + if let ExprKind::Name(name) = &native.expression(ungroup(id, native)).kind { + let name = instances::normalize_identifier(&name.spelling); + if let Some(ty) = dimensions.get(&name) { + return ty.class.clone(); + } + if name == "super" { + return super_class(tree, dimensions); + } } let (property, _) = property(tree, id, native, dimensions).ok()??; property.r#type.class().map(str::to_owned) @@ -40,7 +44,68 @@ pub(in crate::ast) fn native_class( /// The class whose method is being bound, whose properties and methods /// unqualified names may refer to. pub(in crate::ast) fn scope_class(dimensions: &PackedDimensions) -> Option { - dimensions.get(THIS).and_then(|ty| ty.class.clone()) + dimensions.class_scope.clone() +} + +/// The base of the scope class, which `super` refers to inside a method that +/// has an object (IEEE 1800-2023 8.15). +fn super_class(tree: &AnalysisContext<'_>, dimensions: &PackedDimensions) -> Option { + dimensions.get(THIS)?; + class(tree, dimensions, &scope_class(dimensions)?) + .ok()? + .base + .clone() +} + +/// Whether native expression `id` is `super`, which passes the enclosing +/// method's `this`. +fn is_super(id: ExprId, native: &Declarations) -> bool { + matches!(&native.expression(ungroup(id, native)).kind, + ExprKind::Name(name) if name.spelling == "super") +} + +/// The class that native expression `id` names, as the scope of `C::name`. +fn named_class( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, +) -> Option { + let ExprKind::Name(name) = &native.expression(ungroup(id, native)).kind else { + return None; + }; + let name = instances::normalize_identifier(&name.spelling); + (dimensions.get(&name).is_none() && classes::handle_type(tree, &name).is_some()).then_some(name) +} + +/// The variable of the static property that native expression `id` names: +/// `h.p` or `C::p` (IEEE 1800-2023 8.9, 8.23). An unqualified name inside a +/// method of the class is renamed to it where the method's scope begins. +pub(in crate::ast) fn static_property( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, +) -> Converted> { + let ExprKind::Member { + expression, + separator, + name, + } = &native.expression(ungroup(id, native)).kind + else { + return Ok(None); + }; + let class_name = match separator.as_str() { + "." => native_class(tree, *expression, native, dimensions), + "::" => named_class(tree, *expression, native, dimensions), + _ => None, + }; + let Some(class_name) = class_name else { + return Ok(None); + }; + Ok(class(tree, dimensions, &class_name)? + .static_property(&instances::normalize_identifier(&name.spelling)) + .map(|property| property.variable.clone())) } /// The property that native expression `id` names, `h.p` or an unqualified @@ -58,7 +123,11 @@ pub(in crate::ast) fn property( separator, name, } if separator == "." => match native_class(tree, *expression, native, dimensions) { - Some(class) => (class, name, Some(*expression)), + Some(class) => ( + class, + name, + (!is_super(*expression, native)).then_some(*expression), + ), None => return Ok(None), }, ExprKind::Name(name) => { @@ -76,9 +145,16 @@ pub(in crate::ast) fn property( _ => return Ok(None), }; let class = class(tree, dimensions, &class_name)?; - Ok(class - .property(&instances::normalize_identifier(&name.spelling)) - .map(|property| (property.clone(), receiver))) + let Some(property) = class.property(&instances::normalize_identifier(&name.spelling)) else { + return Ok(None); + }; + if receiver.is_none() && dimensions.get(THIS).is_none() { + return Err(unsupported(format!( + "non-static property `{}` in a static method", + property.name + ))); + } + Ok(Some((property.clone(), receiver))) } /// The handle of the object that `receiver` of [`property`] refers to. @@ -94,22 +170,9 @@ pub(in crate::ast) fn receiver( } } -/// A read of property `property` of the object `handle` of class `class`. -pub(in crate::ast) fn load( - tree: &AnalysisContext<'_>, - dimensions: &PackedDimensions, - class_name: &str, - property: &str, - handle: Expr, -) -> Converted { - let class = class(tree, dimensions, class_name)?; - let property = class - .property(property) - .ok_or_else(|| unsupported(format!("property `{property}` of class `{class_name}`")))?; - Ok(classes::object_call( - ObjectOp::Load(property.field), - vec![handle], - )) +/// A read of property `property` of the object `handle`. +pub(in crate::ast) fn load(property: &classes::Property, handle: Expr) -> Expr { + classes::object_call(ObjectOp::Load(property.field), vec![handle]) } /// The unqualified name `name` inside a method of the scope class, when it @@ -126,60 +189,104 @@ pub(in crate::ast) fn unqualified_property( return Ok(None); }; let class = class(tree, dimensions, &class_name)?; - Ok(class.property(name).map(|property| { - classes::object_call( - ObjectOp::Load(property.field), - vec![Expr::Ident(THIS.into())], - ) - })) + let Some(property) = class.property(name) else { + return Ok(None); + }; + if dimensions.get(THIS).is_none() { + return Err(unsupported(format!( + "non-static property `{name}` in a static method" + ))); + } + Ok(Some(load(property, this()))) +} + +/// The object a method is called on. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(in crate::ast) enum Receiver { + /// The object of a handle expression. + Handle(ExprId), + /// The object of the enclosing method. + This, + /// None: a static method (IEEE 1800-2023 8.10). + Static, } /// The method that native callee expression `id` names: through a handle -/// (`h.m`), `this.m`, or unqualified inside a method. Returns the method's -/// subroutine, its number of formals, and the receiver to pass as `this`, -/// `None` for the enclosing method's own `this`. +/// (`h.m`), `this.m`, `super.m`, `C::m`, or unqualified inside a method. +/// Returns the method's subroutine, its number of formals, and the object +/// it is called on. pub(in crate::ast) fn method( tree: &AnalysisContext<'_>, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, -) -> Converted)>> { +) -> Converted> { let (class_name, method_name, receiver) = match &native.expression(ungroup(id, native)).kind { ExprKind::Member { expression, separator, name, } if separator == "." => match native_class(tree, *expression, native, dimensions) { - Some(class) => (class, name, Some(*expression)), + Some(class) if is_super(*expression, native) => (class, name, Receiver::This), + Some(class) => (class, name, Receiver::Handle(*expression)), None => return Ok(None), }, - ExprKind::Name(name) if dimensions.get(THIS).is_some() => { + ExprKind::Member { + expression, + separator, + name, + } if separator == "::" => match named_class(tree, *expression, native, dimensions) { + Some(class) => (class, name, Receiver::Static), + None => return Ok(None), + }, + ExprKind::Name(name) => { let normalized = instances::normalize_identifier(&name.spelling); if dimensions.get(&normalized).is_some() { return Ok(None); } match scope_class(dimensions) { - Some(class) => (class, name, None), + Some(class) => (class, name, Receiver::This), None => return Ok(None), } } _ => return Ok(None), }; let class = class(tree, dimensions, &class_name)?; - let Some(method) = class.method(&instances::normalize_identifier(&method_name.spelling)) else { + let method_name = instances::normalize_identifier(&method_name.spelling); + if method_name == "new" { + return match receiver { + // `C::new` is a constructor call, see [`constructor`]. + Receiver::Static => Ok(None), + _ => Err(unsupported( + "`super.new` that is not the first statement of a constructor", + )), + }; + } + let Some(method) = class.method(&method_name) else { return Ok(None); }; - if method.qualifiers.is_static || method.qualifiers.is_virtual { - return Err(unsupported(format!( - "{} method `{}`", - if method.qualifiers.is_static { - "static" - } else { - "virtual" - }, - method.name - ))); + if method.qualifiers.is_virtual { + return Err(unsupported(format!("virtual method `{}`", method.name))); } + let receiver = if method.qualifiers.is_static { + Receiver::Static + } else { + match receiver { + Receiver::This if dimensions.get(THIS).is_none() => { + return Err(unsupported(format!( + "non-static method `{}` called from a static method", + method.name + ))); + } + Receiver::Static => { + return Err(unsupported(format!( + "non-static method `{}` called through its class scope", + method.name + ))); + } + receiver => receiver, + } + }; let formals = native .subroutine(method.native) .ports @@ -197,8 +304,11 @@ pub(in crate::ast) fn this() -> Expr { Expr::Ident(THIS.into()) } -/// The constructor call that `new` or `new(args)` in native expression -/// `id` makes for an object of class `class_name`, if `id` is one. +/// The constructor call that native expression `id` makes when it is `new`, +/// `new(args)`, `C::new` or `C::new(args)`, the plain forms creating an +/// object of class `class_name` (IEEE 1800-2023 8.7, 8.8). The call +/// allocates the object and passes it to the constructor, which initializes +/// it and returns it. pub(in crate::ast) fn constructor( tree: &AnalysisContext<'_>, id: ExprId, @@ -206,48 +316,51 @@ pub(in crate::ast) fn constructor( dimensions: &PackedDimensions, class_name: &str, ) -> Converted> { - let arguments: &[celox_sv_syntax::Argument] = match &native.expression(ungroup(id, native)).kind - { - ExprKind::Name(name) if name.spelling == "new" => &[], - ExprKind::Call { + let (callee, arguments): (ExprId, &[celox_sv_syntax::Argument]) = + match &native.expression(ungroup(id, native)).kind { + ExprKind::Call { + expression, + arguments, + } => (*expression, arguments), + _ => (id, &[]), + }; + let class_name = match &native.expression(ungroup(callee, native)).kind { + ExprKind::Name(name) if name.spelling == "new" => class_name.to_owned(), + ExprKind::Member { expression, - arguments, - } if matches!(&native.expression(ungroup(*expression, native)).kind, - ExprKind::Name(name) if name.spelling == "new") => - { - arguments + separator, + name, + } if separator == "::" && name.spelling == "new" => { + match named_class(tree, *expression, native, dimensions) { + Some(class) => class, + None => return Ok(None), + } } _ => return Ok(None), }; - let class = class(tree, dimensions, class_name)?; - let formals = class.method("new").map_or(0, |method| { - native - .subroutine(method.native) - .ports - .as_ref() - .map_or(0, Vec::len) - }); - let mut args = arguments - .iter() - .map(|argument| { - if argument.name.is_some() { - return Err(unsupported("named constructor argument")); - } + let class = class(tree, dimensions, &class_name)?; + let formals = class.constructor_formals(native); + let mut args = vec![Some(class.allocation())]; + for argument in arguments { + if argument.name.is_some() { + return Err(unsupported("named constructor argument")); + } + args.push( argument .value .map(|value| bind_value(value, native, tree, dimensions, None)) - .transpose() - }) - .collect::, _>>()?; - if args.len() > formals { + .transpose()?, + ); + } + if args.len() > formals + 1 { return Err(unsupported(format!( "constructor of class `{class_name}` with {} arguments", - args.len() + args.len() - 1 ))); } - args.resize(formals, None); + args.resize(formals + 1, None); Ok(Some(Expr::Call { - callee: Callee::Subroutine(Class::subroutine_name(class_name, "new")), + callee: Callee::Subroutine(Class::subroutine_name(&class_name, "new")), args, arg_order: Vec::new(), })) diff --git a/crates/celox-sv-analyzer/src/ast/imports.rs b/crates/celox-sv-analyzer/src/ast/imports.rs index 8b6b6f83e0c..9e7c4882027 100644 --- a/crates/celox-sv-analyzer/src/ast/imports.rs +++ b/crates/celox-sv-analyzer/src/ast/imports.rs @@ -121,6 +121,14 @@ impl ScopeImports { if package == "std" && normalize_identifier(&name.spelling) == "randomize" { continue; } + // `C::name` names a member of class `C` (IEEE 1800-2023 8.23). + if native + .classes + .iter() + .any(|class| normalize_identifier(&class.name.spelling) == package) + { + continue; + } if !nested.iter().any(|(start, end, names)| { (*start..*end).contains(&expression.tokens.start) && names.contains(&package) }) { diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index d58ec3ad6f7..0f1ff9d0e7c 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -265,7 +265,10 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { /// Hide the module-scope names that the properties of `class` shadow /// inside its methods (IEEE 1800-2023 8.5), until the scope ends. + /// A static property's name is renamed to the module variable that holds + /// it (IEEE 1800-2023 8.9). fn enter_class_scope(&mut self, class: &classes::Class) { + self.dims.class_scope = Some(class.name.clone()); for property in &class.properties { let entry = self.take_binding(&property.name, None, 0); self.scopes @@ -274,6 +277,25 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { .entries .push(entry); } + for property in &class.statics { + let entry = self.take_binding( + &property.name, + Some(property.variable.clone()), + property.r#type.packed_ranges.len(), + ); + self.dims.insert( + property.name.clone(), + dimensions_from_type(&property.r#type), + ); + self.dims + .expression_signedness + .insert(property.name.clone(), property.r#type.is_signed()); + self.scopes + .last_mut() + .expect("a body always has a scope") + .entries + .push(entry); + } } fn lookup(&self, source: &str) -> Option<&str> { @@ -619,6 +641,18 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { } value = expression_binding::string_operand(value, &self.dims); } + self.property_store(&property, handle, op, value).map(Some) + } + + /// `h.p op value`: a store of `value` into property `property` of the + /// object `handle`, combined with its old value by a compound `op`. + fn property_store( + &self, + property: &classes::Property, + handle: Expr, + op: &str, + mut value: Expr, + ) -> Result { if op != "=" { let operator = match op.strip_suffix('=') { Some("+") => BinaryOp::Add, @@ -648,7 +682,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { vec![handle, value], ); self.rename_expr(&mut store); - Ok(Some(Stmt::Eval(store))) + Ok(Stmt::Eval(store)) } /// A call of a class method as a statement, `h.m(args)`, `h.m`, or an @@ -674,14 +708,19 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { else { return Ok(None); }; - let receiver = match receiver { - Some(receiver) => { - expression_binding::value(receiver, native, self.tree, &self.dims)? + let mut args = match receiver { + expression_binding::ObjectReceiver::Handle(receiver) => vec![Some( + expression_binding::value(receiver, native, self.tree, &self.dims)?, + )], + expression_binding::ObjectReceiver::This => { + vec![Some(expression_binding::object_this())] } - None => expression_binding::object_this(), + expression_binding::ObjectReceiver::Static => Vec::new(), }; - let mut args = vec![Some(receiver)]; - args.resize(formals + 1, None); + args.resize( + formals + usize::from(receiver != expression_binding::ObjectReceiver::Static), + None, + ); Expr::Call { callee: Callee::Subroutine(name), args, @@ -770,6 +809,17 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { "--" => "-=", _ => return Err(unsupported("increment or decrement operator")), }; + let native = self.tree.declarations(); + if let Some((property, receiver)) = + expression_binding::object_property(self.tree, *expression, native, &self.dims)? + { + if property.field.handle.is_some() { + return Err(unsupported(format!("operator `{operator}` on a handle"))); + } + let handle = + expression_binding::object_receiver(self.tree, receiver, native, &self.dims)?; + return self.property_store(&property, handle, op, Expr::Literal("1".into())); + } let (written, lhs) = self.native_lvalue(*expression)?; let mut rhs = assignment_op_expr( &self.tree.state, @@ -1485,21 +1535,18 @@ pub(super) fn subroutine_argument_names( let handle = classes::handle_type(tree, &class) .ok_or_else(|| unsupported(format!("class `{class}`")))?; let mut constructor = false; - for native_id in classes::declared_methods(tree, &class)? { + let this = ( + classes::THIS.to_owned(), + ParamDirection::Input, + handle.clone(), + None, + ); + for (native_id, is_static) in classes::declared_methods(tree, &class)? { let native = tree.declarations().subroutine(native_id); let mut params = subroutine_param_declarations(native, tree, &item.env, &aliases)?; - if native.kind == celox_sv_syntax::SubroutineKind::Constructor { - constructor = true; - } else { - params.insert( - 0, - ( - classes::THIS.to_owned(), - ParamDirection::Input, - handle.clone(), - None, - ), - ); + constructor |= native.kind == celox_sv_syntax::SubroutineKind::Constructor; + if !is_static { + params.insert(0, this.clone()); } let qualified = item.name(&classes::Class::subroutine_name( &class, @@ -1525,9 +1572,12 @@ pub(super) fn subroutine_argument_names( } if !constructor { let qualified = item.name(&classes::Class::subroutine_name(&class, "new")); - directions.insert(qualified.clone(), Vec::new()); - shapes.insert(qualified.clone(), Vec::new()); - names.insert(qualified, Vec::new()); + directions.insert(qualified.clone(), vec![ParamDirection::Input]); + shapes.insert( + qualified.clone(), + vec![dimensions_from_type(&scoped_type(handle, &item.env))], + ); + names.insert(qualified, vec![classes::THIS.to_owned()]); } } } @@ -1701,6 +1751,12 @@ pub(super) fn lower_subroutine( let native = tree.declarations().subroutine(native_id); let name = instances::normalize_identifier(&native.name.spelling); let constructor = native.kind == celox_sv_syntax::SubroutineKind::Constructor; + let is_static = class.is_some_and(|class| { + class + .methods + .iter() + .any(|method| method.native == native_id && method.qualifiers.is_static) + }); let handle = class .map(|class| { classes::handle_type(tree, &class.name) @@ -1779,9 +1835,9 @@ pub(super) fn lower_subroutine( .collect::, _>>()?; let mut lowered_params = Vec::new(); let mut formal_types = HashMap::default(); - // A method receives the handle of its object first, and a constructor - // returns the handle of the object it creates. - let this = handle.clone().filter(|_| !constructor).map(|handle| { + // A method that is not static receives the handle of its object first, + // and a constructor returns the handle of the object it initializes. + let this = handle.clone().filter(|_| !is_static).map(|handle| { ( classes::THIS.to_owned(), ParamDirection::Input, @@ -1811,21 +1867,42 @@ pub(super) fn lower_subroutine( default, }); } - let return_var = return_type.as_ref().map(|r#type| { - builder.declare( - if constructor { classes::THIS } else { &name }, - r#type.clone(), - ) - }); + let return_var = return_type + .as_ref() + .map(|r#type| builder.declare(&name, r#type.clone())); if let (Some(name), Some(ty)) = (&return_var, &return_type) { formal_types.insert(name.clone(), scoped_type(ty.clone(), declaration_env)); } let parameter_locals_end = builder.state.locals.len(); - let mut body = match (class, &return_var) { - (Some(class), Some(this)) if constructor => builder.constructor_prologue(class, this)?, - _ => Vec::new(), - }; - body.extend(builder.native_body(&native.items, &native.authored_statements)?); + let mut items = native.items.clone(); + let mut prologue = Vec::new(); + if let (Some(class), Some(result), Some(this)) = (class, &return_var, lowered_params.first()) + && constructor + { + // An explicit `super.new` call is made before the property + // initializers, with the base call the prologue makes. + let arguments = match ( + super_new(tree.declarations(), &items), + classes::base_arguments(tree, &class.name), + ) { + (Some(_), Some(_)) => { + return Err(unsupported( + "`super.new` in a class whose `extends` passes constructor arguments", + )); + } + (Some(_), None) if class.base.is_none() => { + return Err(unsupported("`super.new` in a class without a base")); + } + (Some((index, arguments)), None) => { + items.remove(index); + arguments + } + (None, arguments) => arguments.unwrap_or_default(), + }; + prologue = builder.constructor_prologue(class, &this.name, result, arguments)?; + } + let mut body = prologue; + body.extend(builder.native_body(&items, &native.authored_statements)?); builder.pop_scope(); let static_types: HashMap = builder .state @@ -1978,35 +2055,103 @@ pub(super) fn lower_subroutine( Ok(subroutine) } +/// The `super.new(args)` call that starts constructor body `items`, as its +/// index in `items` and its arguments (IEEE 1800-2023 8.15, 8.17). +fn super_new<'a>( + native: &'a celox_sv_syntax::Declarations, + items: &[celox_sv_syntax::StatementId], +) -> Option<(usize, &'a [celox_sv_syntax::Argument])> { + use celox_sv_syntax::{ExprKind, StatementKind}; + let (index, statement) = items.iter().enumerate().find(|(_, id)| { + !matches!( + native.statement(**id).kind, + StatementKind::Declaration(_) | StatementKind::Empty + ) + })?; + let StatementKind::Expression(root) = native.statement(*statement).kind else { + return None; + }; + let root = expression_binding::ungroup(root, native); + let (callee, arguments) = match &native.expression(root).kind { + ExprKind::Call { + expression, + arguments, + } => (*expression, arguments.as_slice()), + _ => (root, &[][..]), + }; + let ExprKind::Member { + expression, + separator, + name, + } = &native.expression(callee).kind + else { + return None; + }; + (separator == "." + && name.spelling == "new" + && matches!(&native.expression(*expression).kind, + ExprKind::Name(name) if name.spelling == "super")) + .then_some((index, arguments)) +} + impl BodyBuilder<'_, '_, '_> { - /// The statements a constructor of `class` runs before its body: create - /// the object into `this` and initialize the properties that have - /// initializers (IEEE 1800-2023 8.7, 8.8). - fn constructor_prologue(&mut self, class: &classes::Class, this: &str) -> Converted> { + /// The statements a constructor of `class` runs before its body, on the + /// object `this` its caller allocated: return `this` as `result`, call + /// the constructor of the base with `arguments`, and initialize the + /// properties the class declares (IEEE 1800-2023 8.7, 8.8, 8.17). + fn constructor_prologue( + &mut self, + class: &classes::Class, + this: &str, + result: &str, + arguments: &[celox_sv_syntax::Argument], + ) -> Converted> { let native = self.tree.declarations(); - let handles = class - .properties - .iter() - .filter_map(|property| { - property - .field - .handle - .map(|handle| (property.field.offset, handle)) - }) - .collect(); let mut body = vec![Stmt::Assign { - lhs: LValue::Ident(this.to_owned()), - rhs: classes::object_call( - system_functions::ObjectOp::New { - class: class.id, - size: class.size, - handles, - }, - Vec::new(), - ), + lhs: LValue::Ident(result.to_owned()), + rhs: Expr::Ident(this.to_owned()), nonblocking: false, }]; - for property in &class.properties { + if let Some(base) = &class.base { + let base = classes::class( + self.tree, + base, + &self.dims.const_env, + &self.dims.type_aliases, + )?; + let formals = base.constructor_formals(native); + if arguments.len() > formals { + return Err(unsupported(format!( + "constructor of class `{}` with {} arguments", + base.name, + arguments.len() + ))); + } + let mut args = vec![Some(Expr::Ident(this.to_owned()))]; + for argument in arguments { + if argument.name.is_some() { + return Err(unsupported("named constructor argument")); + } + args.push( + argument + .value + .map(|value| { + let mut value = + expression_binding::value(value, native, self.tree, &self.dims)?; + self.rename_expr(&mut value); + Ok::<_, AnalyzerError>(value) + }) + .transpose()?, + ); + } + args.resize(formals + 1, None); + body.push(Stmt::Call { + name: classes::Class::subroutine_name(&base.name, "new"), + args, + arg_order: Vec::new(), + }); + } + for property in class.own_properties() { let Some(initializer) = property.initializer else { continue; }; @@ -2057,16 +2202,9 @@ fn lower_class( item: &generate::Item, ) -> Converted> { let class = classes::class(tree, name, declaration_env, type_aliases)?; - if let Some(base) = &class.base - && classes::class(tree, base, declaration_env, type_aliases)? - .method("new") - .is_some() - { - return Err(unsupported("class extending a class with a constructor")); - } let mut subroutines = Vec::new(); let mut constructor = false; - for id in classes::declared_methods(tree, name)? { + for (id, _) in classes::declared_methods(tree, name)? { constructor |= tree.declarations().subroutine(id).kind == celox_sv_syntax::SubroutineKind::Constructor; subroutines.push(lower_subroutine( @@ -2084,6 +2222,13 @@ fn lower_class( if !constructor { let handle = classes::handle_type(tree, name) .ok_or_else(|| unsupported(format!("class `{name}`")))?; + let ir_type = crate::ir::Type::from_ast( + scoped_type(handle.clone(), declaration_env), + &const_functions::Environment { + constants: &*item.env, + functions: &tree.state.const_functions, + }, + ); let mut builder = BodyBuilder::new( tree, item_dimensions, @@ -2095,7 +2240,13 @@ fn lower_class( builder.push_scope(); builder.enter_class_scope(&class); let this = builder.declare(classes::THIS, handle.clone()); - let body = builder.constructor_prologue(&class, &this)?; + let result = builder.declare("new", handle); + let body = builder.constructor_prologue( + &class, + &this, + &result, + classes::base_arguments(tree, name).unwrap_or_default(), + )?; builder.pop_scope(); let mut subroutine = Subroutine { name: item.name(&classes::Class::subroutine_name(name, "new")), @@ -2105,15 +2256,15 @@ fn lower_class( .map(|local| local.name.clone()) .collect(), persistent_locals: Vec::new(), - return_type: Some(crate::ir::Type::from_ast( - scoped_type(handle, declaration_env), - &const_functions::Environment { - constants: &*item.env, - functions: &tree.state.const_functions, - }, - )), - params: Vec::new(), - return_var: Some(this), + return_type: Some(ir_type.clone()), + params: vec![SubroutineParam { + name: this, + source_name: classes::THIS.to_owned(), + direction: ParamDirection::Input, + r#type: ir_type, + default: None, + }], + return_var: Some(result), body, sensitivity_body: Vec::new(), }; @@ -2208,6 +2359,12 @@ pub(super) fn initial_processes_from_scope( } } } + // Static class properties are initialized like variables. + for property in classes::item_statics(item.id, tree, &item.env, &type_aliases) { + if let Some(value) = property.initializer { + assignments.push((property.variable, value)); + } + } if !assignments.is_empty() { let (item_dimensions, literals) = views.get(item); let mut body = Vec::new(); diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index ebc1d9d5ed4..5f9554fe29c 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -492,6 +492,7 @@ 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_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 e0a62bceba1..98c2d18e311 100644 --- a/crates/celox-test-suite/src/sv/cases/class.vtest +++ b/crates/celox-test-suite/src/sv/cases/class.vtest @@ -229,3 +229,86 @@ module Top(output int result, output bit same, output bit done); endmodule "#) (top Top) (run_until 0) (assert_eq done 1) (assert_eq same 1) (assert_eq result 6281)) + +(case static_properties_and_methods + (source "class.sv" #" +module Top(output bit done); + class Counter; + static int created = 0; + static string last = "none"; + int id; + function new(); + created++; + id = created; + endfunction + static function int next(int by = 1); + created += by; + return created; + endfunction + function int peek(); + return created * 10 + id; + endfunction + endclass + Counter a, b; + initial begin + a = new; + b = new; + $display("created=%0d a=%0d b=%0d", Counter::created, a.id, b.id); + a.created = 7; + $display("b.created=%0d peek=%0d", b.created, b.peek()); + $display("next=%0d next=%0d", Counter::next(), a.next(3)); + Counter::last = "set"; + $display("last=%s", b.last); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "created=2 a=1 b=2\nb.created=7 peek=72\nnext=8 next=11\nlast=set\n")) + +(case constructors_chain_to_base + (source "class.sv" #" +module Top(output bit done); + class Base; + int a = 1; + int b; + function new(int b = 2); + this.b = b + a; + endfunction + function int sum(); + return a + b; + endfunction + endclass + class Derived extends Base; + int c = a * 100; + function new(int c0); + super.new(c0 * 2); + c += c0; + endfunction + function int sum(); + return super.sum() * 1000 + c + super.b; + endfunction + endclass + class Fixed extends Base(40); + endclass + class Default extends Base; + int d = b; + endclass + Derived d; + Base b; + Fixed f; + Default e; + initial begin + d = new(3); + b = d; + $display("a=%0d b=%0d c=%0d", d.a, d.b, d.c); + $display("derived=%0d base=%0d", d.sum(), b.sum()); + f = new; + e = Default::new; + $display("fixed=%0d default=%0d", f.b, e.d); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "a=1 b=7 c=103\nderived=8110 base=8\nfixed=41 default=3\n")) diff --git a/crates/celox-test-suite/verification/sv/icarus/class.json b/crates/celox-test-suite/verification/sv/icarus/class.json index 3d6ebc71698..02c99aaf1a5 100644 --- a/crates/celox-test-suite/verification/sv/icarus/class.json +++ b/crates/celox-test-suite/verification/sv/icarus/class.json @@ -1,5 +1,16 @@ { "cases": [ + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::constructors_chain_to_base", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", @@ -137,6 +148,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 the case.", + "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 the case.", + "upstream": [] + }, + "name": "class::static_properties_and_methods", + "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.", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 42048791a99..f2c69d158b0 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -1864,6 +1864,23 @@ ] } }, + { + "id": "sv_icarus_class_scope_resolution", + "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.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "class::static_properties_and_methods" + ] + } + }, { "id": "sv_verilator_class_property_string_methods", "category": "simulator_compile_limitation", diff --git a/crates/celox-test-suite/verification/sv/limitations/icarus.json b/crates/celox-test-suite/verification/sv/limitations/icarus.json index d976c61d989..2d569e682de 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": 15, "emission_error": 0, - "compile_error": 112, + "compile_error": 113, "runtime_error": 7, "unsupported": 0, "ignored": 0 @@ -1271,6 +1271,14 @@ "name": "class::inherited_properties_and_methods", "phase": "compile", "status": "compile_error" + }, + { + "category": "Types", + "detail": "Icarus build exit status: 6; see /build.log\n/source_0.sv:23: syntax error\n/source_0.sv:23: error: Malformed statement\n/source_0.sv:26: syntax error\n/source_0.sv:26: error: Malformed statement\n/source_0.sv:27: syntax error\n/source_0.sv:27: Syntax in assignment statement l-value.\n", + "expectation": "Simulation", + "name": "class::static_properties_and_methods", + "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 ddf65590565..72774285008 100644 --- a/crates/celox-test-suite/verification/sv/verilator/class.json +++ b/crates/celox-test-suite/verification/sv/verilator/class.json @@ -1,5 +1,16 @@ { "cases": [ + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::constructors_chain_to_base", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", @@ -77,6 +88,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::static_properties_and_methods", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "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.", diff --git a/crates/celox/tests/frontends/systemverilog/class.rs b/crates/celox/tests/frontends/systemverilog/class.rs index 6b821e0d979..4d2e3a2f413 100644 --- a/crates/celox/tests/frontends/systemverilog/class.rs +++ b/crates/celox/tests/frontends/systemverilog/class.rs @@ -14,6 +14,8 @@ sv_backends! { fn class_string_methods_on_properties(sim) { @case "class::string_methods_on_properties"; } fn class_derived_properties_hide_base_properties(sim) { @case "class::derived_properties_hide_base_properties"; } fn class_inherited_properties_and_methods(sim) { @case "class::inherited_properties_and_methods"; } + fn class_static_properties_and_methods(sim) { @case "class::static_properties_and_methods"; } + fn class_constructors_chain_to_base(sim) { @case "class::constructors_chain_to_base"; } } sv_backends! { @@ -87,3 +89,31 @@ fn four_state_properties_are_rejected() { let error = error.to_string(); assert!(error.contains("4-state class property"), "{error}"); } + +#[test] +fn misplaced_super_new_and_static_misuse_are_rejected() { + for (body, want) in [ + ( + "class B; endclass class C extends B; int x; function new(); x = 1; super.new(); endfunction endclass", + "`super.new` that is not the first statement", + ), + ( + "class C; int x; static function int f(); return x; endfunction endclass", + "non-static property `x` in a static method", + ), + ( + "class C; function int g(); return 1; endfunction static function int f(); return g(); endfunction endclass", + "non-static method `g` called from a static method", + ), + ] { + let source = format!("module Top; {body} C c; initial c = new; endmodule"); + let Err(error) = + Simulator::from_sv_sources(vec![(source.as_str(), Path::new("class.sv"))], "Top") + .build_cranelift() + else { + panic!("`{body}` is rejected"); + }; + let error = error.to_string(); + assert!(error.contains(want), "{error}"); + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 7a776ac9a3c..6bf041d4ce4 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 non-virtual methods from a base class without a constructor. 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 non-virtual methods, with base constructors called by `super.new(...)` or `extends Base(...)`; `super.` members; static properties and methods; `C::` scope resolution of static members and `C::new`. 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): constructors of base classes and `super`, virtual method calls, static properties and methods, `C::` scope resolution, parameterized classes, 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): virtual method calls, abstract and 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`. @@ -232,6 +232,12 @@ calls are bound to the method of the variable's class (IEEE 1800-2023 8.6). Reading or writing a property or calling a method through `null` is a runtime error. +A constructor calls the constructor of the base class first, with the +arguments of `super.new(...)` or of the `extends` clause, then runs the +initializers of the properties its class declares, then its body (IEEE +1800-2023 8.17). A static property is a variable of the module that declares +the class, so each instance of the module has its own. + 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 7bce8fc86df..b67333b1c30 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`、ハンドルの代入と比較、コンストラクタのない基底クラスからのプロパティと非 virtual メソッドの継承。[クラス](#classes)を参照 | +| クラス | モジュール内で宣言したクラス。64 ビット以下の 2 値整数型・`string`・クラスハンドル型のプロパティ(初期値つきも可)、引数あり・なしの `new`、暗黙と明示のコンストラクタ、ハンドル経由またはクラス内から修飾なしで呼ぶメソッド(`function` と `task`、本体をクラス外に書く `extern` も可)、`this`、`null`、ハンドルの代入と比較、プロパティと非 virtual メソッドの継承(基底クラスのコンストラクタは `super.new(...)` か `extends Base(...)` で呼ぶ)、`super.` によるメンバ参照、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)外のクラスの機能:基底クラスのコンストラクタと `super`、virtual メソッドの呼び出し、static プロパティとメソッド、`C::` によるスコープ解決、パラメータ付きクラス、浅いコピー(`new h`)、4 値・`real`・配列・64 ビットを超えるプロパティ。時間待ちを含む task の static ローカル宣言、再帰呼び出し、`ref` 引数。 +- [対応範囲](#classes)外のクラスの機能:virtual メソッドの呼び出し、抽象クラスと interface クラス、package 内で宣言したクラス、パラメータ付きクラス、名前付きのコンストラクタ引数、浅いコピー(`new h`)、4 値・`real`・配列・64 ビットを超えるプロパティ。時間待ちを含む task の static ローカル宣言、再帰呼び出し、`ref` 引数。 - interface のポート、`inout` / `ref` / 式を使う modport、virtual interface など。 interface 自体と入れ子の interface は対応しています。型パラメータはインスタンスごとに解決し、modport ポート経由でも伝搬します。 再帰する特殊化と64段を超える入れ子は拒否します。細かな制約は[英語版の一覧](/guide/systemverilog-reference#interface-restrictions)を参照してください。 @@ -169,6 +169,8 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 クラス型の変数はシミュレータのヒープ上のオブジェクトへのハンドルを持ち、コンストラクタを呼ぶまでは `null` です。文字列と同じく、ハンドルのコピーと比較は 32 ビット整数と同じコストで、プロパティの読み書きとオブジェクトの生成だけがランタイムを呼び出します。どの変数・オブジェクトからも参照されないオブジェクトは、タイムスロットの間と各 `tick` の後に回収されます。メソッドは呼び出したオブジェクトを受け取るので function でも task でもよく、呼び出しは変数のクラスのメソッドに結び付きます(IEEE 1800-2023 8.6)。`null` を通したプロパティの読み書きやメソッド呼び出しは実行時エラーです。 +コンストラクタは、まず `super.new(...)` または `extends` 節の引数で基底クラスのコンストラクタを呼び、次に自クラスが宣言するプロパティの初期値を設定し、最後に本体を実行します(IEEE 1800-2023 8.17)。static プロパティはクラスを宣言したモジュールの変数なので、モジュールのインスタンスごとに 1 つずつあります。 + チェックポイントはオブジェクトを保持します。状態ファイルは文字列を記録しますがオブジェクトは記録しないため、オブジェクトを持つ変数があると状態ファイルの保存は失敗します。 ### インスタンス配列の要素