diff --git a/conformance/sv-tests/README.md b/conformance/sv-tests/README.md index 1c96cdab5ea..b1cb1cde9e6 100644 --- a/conformance/sv-tests/README.md +++ b/conformance/sv-tests/README.md @@ -107,6 +107,13 @@ stays a passing negative case because `par_cls::b` outside the class is rejected. `8.5--properties_enum` keeps failing because enumeration constants declared in a class are not supported. +Shallow copies update two more rows: both state modes for `8.12--shallow_copy` +change from fail to pass. The case was simulated and its displayed values +checked: the property of the copy keeps the value it was copied with after the +method call changes the original. Full official runs at the pinned revision +report 1081 passing cases in 2state and 1092 in 4state, with no passing case +regressing. + ## Running locally Use the locked development shell and install the pinned [`requirements.txt`](requirements.txt) in a Python environment. diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index bf5592271d7..080686dec97 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1469,8 +1469,8 @@ 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.12--shallow_copy.sv 2state pass +chapter-8/8.12--shallow_copy.sv 4state pass 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 diff --git a/crates/celox-frontend-sv/src/lowering/ff/objects.rs b/crates/celox-frontend-sv/src/lowering/ff/objects.rs index 9f2026bb1c5..4b83614aa47 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/objects.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/objects.rs @@ -115,13 +115,17 @@ impl Ff<'_, '_> { let object = self.handle(&args[0])?; self.heap_call(ops::OBJECT_CLASS, &[object]) } + ObjectOp::Copy => { + let object = self.handle(&args[0])?; + self.heap_call(ops::OBJECT_COPY, &[object]) + } }; let (width, signed) = op.result_type(); let value = self.b.alloc_bit(width, signed); self.b.emit(SIRInstruction::Slice(value, result, 0, width)); let (temp, name) = self.m.temp("object", width, signed, false); let kind = match op { - ObjectOp::New { .. } => Some(celox_design::ValueKind::ObjRef), + ObjectOp::New { .. } | ObjectOp::Copy => Some(celox_design::ValueKind::ObjRef), ObjectOp::Load(field) => field.handle.map(|handle| match handle { HandleProperty::String => celox_design::ValueKind::StrRef, HandleProperty::Object => celox_design::ValueKind::ObjRef, diff --git a/crates/celox-heap/src/objects.rs b/crates/celox-heap/src/objects.rs index bace65434d6..2683ca747b9 100644 --- a/crates/celox-heap/src/objects.rs +++ b/crates/celox-heap/src/objects.rs @@ -196,6 +196,18 @@ impl Heap { true } + /// A new object of the class of `object` with a copy of its properties: + /// the handles it holds are copied, not the objects they refer to (IEEE + /// 1800-2023 8.12). Copying `null` is a fault and gives `null`. + pub fn copy_object(&mut self, object: Handle) -> Handle { + let Some(copy) = self.object_mut(object).map(|object| object.clone()) else { + return NULL; + }; + let handle = self.new_object(copy.class, 0); + self.objects.insert(handle, copy); + handle + } + /// Declare that the property of `object` at byte `offset` holds a handle /// of `kind`. pub fn declare_handle(&mut self, object: Handle, offset: u32, kind: HandleKind) { @@ -297,6 +309,28 @@ mod tests { assert_eq!(heap.class_of(NULL), 0); } + #[test] + fn copies_are_shallow() { + let mut heap = Heap::new(); + let inner = heap.new_object(2, 4); + let original = heap.new_object(1, 8); + heap.declare_handle(original, 0, HandleKind::Object); + heap.store(original, 0, 4, inner.into()); + heap.store(original, 4, 4, 9); + let copy = heap.copy_object(original); + assert_ne!(copy, original); + assert_eq!(heap.class_of(copy), 1); + assert_eq!(heap.load(copy, 0, 4), u64::from(inner)); + heap.store(copy, 4, 4, 5); + assert_eq!(heap.load(original, 4, 4), 9); + // The copy keeps what its handle properties refer to alive. + heap.collect([Root::object(copy)]); + assert!(heap.contains_object(inner)); + assert!(!heap.contains_object(original)); + assert_eq!(heap.copy_object(NULL), NULL); + assert_eq!(heap.take_fault(), Some(Fault::NullDereference)); + } + #[test] fn collection_follows_handle_properties() { let mut heap = Heap::new(); diff --git a/crates/celox-heap/src/ops.rs b/crates/celox-heap/src/ops.rs index d0485579576..1b725feabc3 100644 --- a/crates/celox-heap/src/ops.rs +++ b/crates/celox-heap/src/ops.rs @@ -81,6 +81,8 @@ pub const OBJECT_MODE_SELECT: u64 = 60; pub const OBJECT_MODE_SELECTED: u64 = 61; /// Draw a randc domain index; parameter is the property offset, b its domain size. pub const OBJECT_RANDOM_CYCLIC: u64 = 62; +/// `copy(object)`: a new object with a copy of the properties of `object`. +pub const OBJECT_COPY: u64 = 63; /// The opcode word of `op` with parameter `parameter`. pub const fn encode(op: u64, parameter: u64) -> u64 { @@ -222,6 +224,7 @@ impl Heap { OBJECT_MODE_SELECTED => { u64::from(self.selected_random_mode(a as Handle, parameter as u32)) } + OBJECT_COPY => self.copy_object(a as Handle).into(), other => panic!("unknown heap operation {other}"), } } 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 1d4cfbf810c..3cd80786a50 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -233,6 +233,35 @@ pub(in crate::ast) fn static_property( Ok(Some(property.variable.clone())) } +/// The class of the handle that the static property native expression `id` +/// names holds, `h.p` or `C::p`. +fn static_property_class( + 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)) + .and_then(|property| property.r#type.class().map(str::to_owned))) +} + /// The property that native expression `id` names, `h.p` or an unqualified /// `p` inside a method of its class, with the receiver: the expression of /// the handle, or `None` for the enclosing method's `this`. @@ -611,6 +640,29 @@ pub(in crate::ast) fn constructor( dimensions: &PackedDimensions, class_name: &str, ) -> Converted> { + // `new h` copies the properties of the object of `h` into a new object + // of its class; handles are copied, not the objects they refer to (IEEE + // 1800-2023 8.12). + if let ExprKind::Copy(source) = &native.expression(ungroup(id, native)).kind { + let source_class = match native_class(tree, *source, native, dimensions) { + Some(class) => Some(class), + None => static_property_class(tree, *source, native, dimensions)?, + }; + let Some(source_class) = source_class else { + return Err(unsupported( + "shallow copy of a value that is not a class handle", + )); + }; + if !derives_from(tree, dimensions, &source_class, class_name)? { + return Err(AnalyzerError::IncompatibleClassHandle { + context: "shallow copy".to_owned(), + actual: source_class, + target: class_name.to_owned(), + }); + } + let handle = bind_value(*source, native, tree, dimensions, None)?; + return Ok(Some(classes::object_call(ObjectOp::Copy, vec![handle]))); + } let (callee, arguments): (ExprId, &[celox_sv_syntax::Argument]) = match &native.expression(ungroup(id, native)).kind { ExprKind::Call { diff --git a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs index 6572ebce485..5fb76eddd95 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs @@ -370,6 +370,9 @@ pub(in crate::ast) fn validate( push(&mut jobs, *value); } } + ExprKind::Copy(_) => { + return Err(unsupported("shallow copy in skipped operand")); + } ExprKind::Parameterized { .. } => { return Err(unsupported("parameterized value in skipped operand")); } diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index e496c9871eb..6b3b0ef51fb 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -810,6 +810,9 @@ pub enum ObjectOp { ModePop, ModeSelect(u32, bool), ModeSelected(u32), + /// A new object of the class of the object in the argument, with a copy + /// of its properties (IEEE 1800-2023 8.12). + Copy, } impl ObjectOp { @@ -826,7 +829,7 @@ impl ObjectOp { | Self::ModeSelected(_) => (32, false), Self::ModeGet(..) => (32, true), Self::Load(field) => (field.width as usize, field.signed), - Self::New { .. } | Self::ClassOf | Self::Store(_) => (32, false), + Self::New { .. } | Self::ClassOf | Self::Store(_) | Self::Copy => (32, false), } } } @@ -848,6 +851,7 @@ impl fmt::Display for ObjectOp { Self::ModePop => "restore random modes", Self::ModeSelect(..) => "select random property", Self::ModeSelected(_) => "selected random property query", + Self::Copy => "shallow copy", }) } } diff --git a/crates/celox-sv-syntax/src/nodes.rs b/crates/celox-sv-syntax/src/nodes.rs index de6c52aceb9..d77bc1ad138 100644 --- a/crates/celox-sv-syntax/src/nodes.rs +++ b/crates/celox-sv-syntax/src/nodes.rs @@ -77,6 +77,8 @@ pub enum ExprKind { member: Name, value: Option, }, + /// `new h`: a shallow copy of the object of handle `h` (8.12). + Copy(ExprId), Member { expression: ExprId, separator: String, diff --git a/crates/celox-sv-syntax/src/parser/expressions.rs b/crates/celox-sv-syntax/src/parser/expressions.rs index 5c0dce906c0..5951612029d 100644 --- a/crates/celox-sv-syntax/src/parser/expressions.rs +++ b/crates/celox-sv-syntax/src/parser/expressions.rs @@ -50,6 +50,10 @@ pub(super) enum Job { minimum: u8, member: Name, }, + Copy { + start: usize, + minimum: u8, + }, GroupTypical { start: usize, minimum: u8, @@ -312,6 +316,7 @@ impl Parser<'_> { pending.push(*expression); } ExprKind::Group(value) + | ExprKind::Copy(value) | ExprKind::Member { expression: value, .. } => pending.push(*value), @@ -582,6 +587,22 @@ impl Parser<'_> { jobs.push(Job::Expression(0)); } } + // `new h` copies the object of `h`; `new` followed + // by `(`, or by nothing, constructs one (8.7, 8.12). + "new" + if self.indices.get(self.at + 1).is_some_and(|&index| { + let token = &self.tokens[index]; + matches!( + token.kind, + TokenKind::Identifier | TokenKind::EscapedIdentifier + ) && (!self.reserved_identifier(token) + || matches!(token.text.as_str(), "this" | "super")) + }) => + { + self.at += 1; + jobs.push(Job::Copy { start, minimum }); + jobs.push(Job::Expression(0)); + } "(" => { self.at += 1; jobs.push(Job::Group { start, minimum }); @@ -924,6 +945,10 @@ impl Parser<'_> { ExprKind::Tagged { member, value }, )?; } + Job::Copy { start, minimum } => { + let value = values.pop().unwrap().expression(); + self.tail(&mut jobs, start, minimum, ExprKind::Copy(value))?; + } Job::GroupTypical { start, minimum, diff --git a/crates/celox-sv-syntax/src/parser/procedures.rs b/crates/celox-sv-syntax/src/parser/procedures.rs index bd513df2ce0..0623ccca86b 100644 --- a/crates/celox-sv-syntax/src/parser/procedures.rs +++ b/crates/celox-sv-syntax/src/parser/procedures.rs @@ -888,7 +888,9 @@ impl Parser<'_> { }, ); } else if !matches!(self.peek(), ";" | "," | "") { - self.expression(0)?; + // A shallow copy of an object (8.12). + let value = self.expression(0)?; + return self.node(start, ExprKind::Copy(value)); } // The declaration retains its explicit Unconverted semantic owner. // This range validates allocation grammar without introducing execution. diff --git a/crates/celox-sv-syntax/src/parser/tests.rs b/crates/celox-sv-syntax/src/parser/tests.rs index cab7fc78510..50f8e782993 100644 --- a/crates/celox-sv-syntax/src/parser/tests.rs +++ b/crates/celox-sv-syntax/src/parser/tests.rs @@ -2902,6 +2902,27 @@ fn class_declarations_record_names_bases_properties_and_method_qualifiers() { } } +#[test] +fn shallow_copies_are_expressions_of_their_own() { + let syntax = parse( + "module M; class C; endclass C a, b; initial begin b = new a; end C c = new a; C d = new; endmodule", + ); + let copies = syntax + .expressions + .iter() + .filter_map(|expression| match expression.kind { + ExprKind::Copy(source) => Some(source), + _ => None, + }) + .collect::>(); + assert_eq!(copies.len(), 2); + for source in copies { + assert!( + matches!(&syntax.expression(source).kind, ExprKind::Name(name) if name.value() == "a") + ); + } +} + #[test] fn class_random_qualifiers_and_constraints_are_preserved() { let syntax = parse( diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index eed64275137..5b94c8dd3b8 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -551,6 +551,7 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_verilator_class_specialization_identity` | execute | verilator | 1 | Verilator 5.052 makes a separate specialization of a parameterized class for each way a parameter value assignment is written, so Box#(2, int)::made and Box#(.N(2), .T(int))::made read 0 after an object of Box#(.T(int), .N(2)) was constructed; the adapter-free source prints 0 1 0 where IEEE 1800-2023 8.25 requires 1 1 1, as the three assignments give the same values. Celox prints 1 1 1. Icarus rejects parameterized classes, see sv_icarus_parameterized_classes. | | `sv_verilator_untyped_class_parameters` | execute | verilator | 1 | Verilator 5.052 gives a class parameter declared without a type the 32-bit type of its default even when a specialization assigns it a sized value, so $bits(V) of Sized#(8'h1) is 32; the adapter-free source prints 32 32 where IEEE 1800-2023 6.20.2 requires 8 32, as the parameter takes the type of its final value after overrides. Celox prints 8 32. Icarus rejects parameterized classes, see sv_icarus_parameterized_classes. | | `sv_icarus_parameterized_classes` | compile | icarus | 13 | Icarus 13.0 does not parse a parameter port list of a class (class Box #(int N = 4); is a syntax error), which IEEE 1800-2023 8.25 defines; each case declares a parameterized class. Verilator passes all but two cases, see sv_verilator_class_specialization_identity and sv_verilator_untyped_class_parameters. | +| `sv_icarus_shallow_copies` | compile | icarus | 1 | Icarus 13.0 does not parse a shallow copy (second = new first; is a syntax error, "Malformed statement"), which IEEE 1800-2023 8.12 defines; the case also compares class handles, which Icarus does not implement, see sv_icarus_classes. 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 b1305205dd0..3c91427cf9c 100644 --- a/crates/celox-test-suite/src/sv/cases/class.vtest +++ b/crates/celox-test-suite/src/sv/cases/class.vtest @@ -1046,6 +1046,55 @@ endmodule (top Top) (run_until 0) (assert_eq done 1) (expect_output "8 32\n")) +(case shallow_copies + (source "class.sv" #" +module Top(output bit done); + class Inner; + int v; + endclass + class Base; + int b = 1; + endclass + class Item extends Base; + int a; + string s; + Inner inner; + static int made; + static Item last; + function new(); + inner = new; + made++; + endfunction + endclass + Item first; + Item second; + Item third; + Base base; + Base copy; + initial begin + first = new; + first.a = 12; + first.b = 7; + first.s = "hi"; + first.inner.v = 3; + second = new first; + first.a = 13; + first.s = "bye"; + first.inner.v = 4; + $display("%0d %0d %s %0d %0d %0d", second.a, second.b, second.s, second.inner.v, Item::made, first == second); + base = second; + copy = new base; + $display("%0d %0d %0d %0d", copy.b, $cast(third, copy), third.a, third == second); + Item::last = second; + third = new Item::last; + $display("%0d %0d %0d", third.a, third == second, Item::made); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "12 7 hi 4 1 0\n7 1 12 0\n12 0 1\n")) + (case unconstrained_randomize (source "randomize.sv" #" module Top(output bit done, output int errors); diff --git a/crates/celox-test-suite/verification/sv/icarus/class.json b/crates/celox-test-suite/verification/sv/icarus/class.json index c2a5199d3ff..f24a9177a7f 100644 --- a/crates/celox-test-suite/verification/sv/icarus/class.json +++ b/crates/celox-test-suite/verification/sv/icarus/class.json @@ -700,6 +700,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "Icarus 13.0 does not parse a shallow copy (second = new first; is a syntax error, \"Malformed statement\"), which IEEE 1800-2023 8.12 defines; the case also compares class handles, which Icarus does not implement, see sv_icarus_classes. 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_shallow_copies", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not parse a shallow copy (second = new first; is a syntax error, \"Malformed statement\"), which IEEE 1800-2023 8.12 defines; the case also compares class handles, which Icarus does not implement, see sv_icarus_classes. Verilator passes the case.", + "upstream": [] + }, + "name": "class::shallow_copies", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "Icarus 13.0 does not parse a parameter port list of a class (class Box #(int N = 4); is a syntax error), which IEEE 1800-2023 8.25 defines; each case declares a parameterized class. Verilator passes all but two cases, see sv_verilator_class_specialization_identity and sv_verilator_untyped_class_parameters.", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 73e0edf3216..de6a717bc16 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2060,6 +2060,23 @@ ] } }, + { + "id": "sv_icarus_shallow_copies", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 does not parse a shallow copy (second = new first; is a syntax error, \"Malformed statement\"), which IEEE 1800-2023 8.12 defines; the case also compares class handles, which Icarus does not implement, see sv_icarus_classes. Verilator passes the case.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "class::shallow_copies" + ] + } + }, { "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 daf824e03a2..d544df46b33 100644 --- a/crates/celox-test-suite/verification/sv/limitations/icarus.json +++ b/crates/celox-test-suite/verification/sv/limitations/icarus.json @@ -9,7 +9,7 @@ "unexpected_accept": 1, "mismatch": 17, "emission_error": 0, - "compile_error": 134, + "compile_error": 135, "runtime_error": 8, "unsupported": 0, "ignored": 0 @@ -1471,6 +1471,14 @@ "name": "class::derived_classes_keep_their_declaration_scopes", "phase": "compile", "status": "compile_error" + }, + { + "category": "Types", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:34: syntax error\n/source_0.sv:34: error: Malformed statement\n", + "expectation": "Simulation", + "name": "class::shallow_copies", + "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 7dc91416ad5..099e5862599 100644 --- a/crates/celox-test-suite/verification/sv/verilator/class.json +++ b/crates/celox-test-suite/verification/sv/verilator/class.json @@ -437,6 +437,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::shallow_copies", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", diff --git a/crates/celox-test-suite/verification/sv/xezim/class.json b/crates/celox-test-suite/verification/sv/xezim/class.json index 64919583719..60bd708fbb0 100644 --- a/crates/celox-test-suite/verification/sv/xezim/class.json +++ b/crates/celox-test-suite/verification/sv/xezim/class.json @@ -35,7 +35,7 @@ }, { "category": "Types", - "detail": "class::class_declarations_bind_in_their_scopes at 1604:3: expect_output: expected [50, 53, 53, 32, 53, 32, 45, 51, 32, 51, 50, 10, 50, 48, 32, 51, 48, 32, 49, 32, 98, 99, 32, 48, 51, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 10], got [50, 53, 53, 32, 49, 32, 52, 50, 57, 52, 57, 54, 55, 50, 57, 51, 32, 51, 50, 10, 50, 48, 32, 51, 48, 32, 49, 32, 98, 99, 32, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 10]", + "detail": "class::class_declarations_bind_in_their_scopes at 1653:3: expect_output: expected [50, 53, 53, 32, 53, 32, 45, 51, 32, 51, 50, 10, 50, 48, 32, 51, 48, 32, 49, 32, 98, 99, 32, 48, 51, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 10], got [50, 53, 53, 32, 49, 32, 52, 50, 57, 52, 57, 54, 55, 50, 57, 51, 32, 51, 50, 10, 50, 48, 32, 51, 48, 32, 49, 32, 98, 99, 32, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 10]", "expectation": "Simulation", "name": "class::class_declarations_bind_in_their_scopes", "phase": "execute", @@ -79,7 +79,7 @@ }, { "category": "Types", - "detail": "class::derived_classes_keep_their_declaration_scopes at 1737:3: expect_output: expected [51, 10], got [49, 10]", + "detail": "class::derived_classes_keep_their_declaration_scopes at 1786:3: expect_output: expected [51, 10], got [49, 10]", "expectation": "Simulation", "name": "class::derived_classes_keep_their_declaration_scopes", "phase": "execute", @@ -211,7 +211,7 @@ }, { "category": "Types", - "detail": "class::parameter_defaults_bind_where_the_class_is_declared at 1626:3: expect_output: expected [49, 10], got [50, 10]", + "detail": "class::parameter_defaults_bind_where_the_class_is_declared at 1675:3: expect_output: expected [49, 10], got [50, 10]", "expectation": "Simulation", "name": "class::parameter_defaults_bind_where_the_class_is_declared", "phase": "execute", @@ -222,7 +222,7 @@ }, { "category": "Types", - "detail": "class::randomization_cyclic_controls at 1515:46: assert_eq errors: expected 0x0, got 0x1", + "detail": "class::randomization_cyclic_controls at 1564:46: assert_eq errors: expected 0x0, got 0x1", "expectation": "Simulation", "name": "class::randomization_cyclic_controls", "phase": "execute", @@ -233,7 +233,7 @@ }, { "category": "Types", - "detail": "class::randomization_cyclic_domains at 1462:46: assert_eq errors: expected 0x0, got 0x300", + "detail": "class::randomization_cyclic_domains at 1511:46: assert_eq errors: expected 0x0, got 0x300", "expectation": "Simulation", "name": "class::randomization_cyclic_domains", "phase": "execute", @@ -244,7 +244,7 @@ }, { "category": "Types", - "detail": "class::randomization_cyclic_enum_alias at 1547:46: assert_eq errors: expected 0x0, got 0x30", + "detail": "class::randomization_cyclic_enum_alias at 1596:46: assert_eq errors: expected 0x0, got 0x30", "expectation": "Simulation", "name": "class::randomization_cyclic_enum_alias", "phase": "execute", @@ -255,7 +255,7 @@ }, { "category": "Types", - "detail": "class::randomization_enum_alias at 1372:46: assert_eq errors: expected 0x0, got 0x81", + "detail": "class::randomization_enum_alias at 1421:46: assert_eq errors: expected 0x0, got 0x81", "expectation": "Simulation", "name": "class::randomization_enum_alias", "phase": "execute", @@ -266,7 +266,7 @@ }, { "category": "Types", - "detail": "class::randomization_enum_domain at 1313:46: assert_eq errors: expected 0x0, got 0x1e5", + "detail": "class::randomization_enum_domain at 1362:46: assert_eq errors: expected 0x0, got 0x1e5", "expectation": "Simulation", "name": "class::randomization_enum_domain", "phase": "execute", @@ -277,7 +277,7 @@ }, { "category": "Types", - "detail": "class::randomization_enum_fill_literals at 1403:46: assert_eq errors: expected 0x0, got 0x18", + "detail": "class::randomization_enum_fill_literals at 1452:46: assert_eq errors: expected 0x0, got 0x18", "expectation": "Simulation", "name": "class::randomization_enum_fill_literals", "phase": "execute", @@ -288,7 +288,7 @@ }, { "category": "Types", - "detail": "class::randomization_enum_inheritance at 1344:46: assert_eq errors: expected 0x0, got 0xff", + "detail": "class::randomization_enum_inheritance at 1393:46: assert_eq errors: expected 0x0, got 0xff", "expectation": "Simulation", "name": "class::randomization_enum_inheritance", "phase": "execute", @@ -299,7 +299,7 @@ }, { "category": "Types", - "detail": "class::randomization_inheritance at 1169:46: assert_eq errors: expected 0x0, got 0x1", + "detail": "class::randomization_inheritance at 1218:46: assert_eq errors: expected 0x0, got 0x1", "expectation": "Simulation", "name": "class::randomization_inheritance", "phase": "execute", @@ -310,7 +310,7 @@ }, { "category": "Types", - "detail": "class::randomization_mode_bit_argument at 1265:46: assert_eq errors: expected 0x0, got 0x3", + "detail": "class::randomization_mode_bit_argument at 1314:46: assert_eq errors: expected 0x0, got 0x3", "expectation": "Simulation", "name": "class::randomization_mode_bit_argument", "phase": "execute", @@ -321,7 +321,7 @@ }, { "category": "Types", - "detail": "class::randomization_modes_and_selection at 1216:46: assert_eq errors: expected 0x0, got 0x1414", + "detail": "class::randomization_modes_and_selection at 1265:46: assert_eq errors: expected 0x0, got 0x1414", "expectation": "Simulation", "name": "class::randomization_modes_and_selection", "phase": "execute", @@ -332,7 +332,7 @@ }, { "category": "Types", - "detail": "class::randomization_pre_hook_controls_modes at 1242:46: assert_eq errors: expected 0x0, got 0x2", + "detail": "class::randomization_pre_hook_controls_modes at 1291:46: assert_eq errors: expected 0x0, got 0x2", "expectation": "Simulation", "name": "class::randomization_pre_hook_controls_modes", "phase": "execute", @@ -354,7 +354,18 @@ }, { "category": "Types", - "detail": "class::specialization_keys_follow_the_bound_parameters at 1715:3: expect_output: expected [50, 32, 49, 32, 49, 10, 49, 32, 49, 10, 51, 46, 48, 32, 51, 46, 48, 10, 50, 10, 55, 10], got [50, 32, 49, 32, 48, 10, 48, 32, 49, 10, 48, 46, 48, 32, 48, 46, 48, 10, 50, 10, 55, 10]", + "detail": "the simulation ended before the script did", + "expectation": "Simulation", + "name": "class::shallow_copies", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "class::specialization_keys_follow_the_bound_parameters at 1764:3: expect_output: expected [50, 32, 49, 32, 49, 10, 49, 32, 49, 10, 51, 46, 48, 32, 51, 46, 48, 10, 50, 10, 55, 10], got [50, 32, 49, 32, 48, 10, 48, 32, 49, 10, 48, 46, 48, 32, 48, 46, 48, 10, 50, 10, 55, 10]", "expectation": "Simulation", "name": "class::specialization_keys_follow_the_bound_parameters", "phase": "execute", diff --git a/crates/celox-test-suite/verification/xezim-review.json b/crates/celox-test-suite/verification/xezim-review.json index 8f5cbf55fd1..b691b53c3e4 100644 --- a/crates/celox-test-suite/verification/xezim-review.json +++ b/crates/celox-test-suite/verification/xezim-review.json @@ -646,6 +646,10 @@ "sv_class-X4": { "title": "A typedef inside a class declared in a generate block does not see the generate block's localparams (`typedef bit [K-1:0] T` uses the module-level K, or none)", "standard": "IEEE 1800-2023 23.9, 27.5" + }, + "sv_class-X11": { + "title": "In a non-top module, a shallow copy of a class-scoped static handle (`h = new C::last`) leaves h null", + "standard": "IEEE 1800-2023 8.12, 8.23, 8.9" } }, "cases": [ @@ -3967,6 +3971,14 @@ "classification": "xezim_bug", "bug": "sv_class-X4", "note": "Derived is declared in generate block g, whose localparam K = 3 hides the module's K = 2; `typedef bit [K-1:0] T` must use K = 3 (23.9: names resolve from the declaration scope upward), so $bits = 3. xezim prints 1 (as top and non-top); in a reduction with another class it uses the module K (2). It does not depend on `extends`: a plain class in g behaves the same, while a static function in the same class returns K = 3. Repro: work/review5/xezim/r/c3c.sv, work/review5/xezim/r/c3_genscope.sv." + }, + { + "suite": "sv", + "name": "class::shallow_copies", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_class-X11", + "note": "As top xezim prints the expected three lines. As non-top dut, `third = new Item::last` (shallow copy of the static handle, 8.12) leaves third null, so third.a is a fatal null dereference. Copying from a local handle (`tmp = Item::last; third = new tmp`) works, and Item::last itself reads non-null. Repro: work/review5/xezim/r/c9_static.sv (+ .wrap.sv)." } ] } diff --git a/crates/celox/tests/frontends/systemverilog/class.rs b/crates/celox/tests/frontends/systemverilog/class.rs index 4f4a156f218..140e242e112 100644 --- a/crates/celox/tests/frontends/systemverilog/class.rs +++ b/crates/celox/tests/frontends/systemverilog/class.rs @@ -38,6 +38,7 @@ sv_backends! { fn class_parameter_defaults_bind_where_the_class_is_declared(sim) { @case "class::parameter_defaults_bind_where_the_class_is_declared"; } fn class_specialization_keys_follow_the_bound_parameters(sim) { @case "class::specialization_keys_follow_the_bound_parameters"; } fn class_derived_classes_keep_their_declaration_scopes(sim) { @case "class::derived_classes_keep_their_declaration_scopes"; } + fn class_shallow_copies(sim) { @case "class::shallow_copies"; } } sv_backends! { @@ -91,6 +92,25 @@ sv_backends! { assert!(error.contains("null object handle"), "{error}"); } + fn shallow_copies_of_null_are_runtime_errors(sim) { + @setup { + let source = r#"module Top(output bit done); + class C; + int x; + endclass + C a; + C b; + initial begin + b = new a; + done = 1; + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("null.sv"))], "Top"); + let error = sim.run_until(0).unwrap_err().to_string(); + assert!(error.contains("null object handle"), "{error}"); + } + fn virtual_calls_through_null_are_runtime_errors(sim) { @setup { let source = r#"module Top(output int value, output bit done); @@ -217,6 +237,8 @@ fn incompatible_class_handle_assignments_are_rejected() { ("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`"]), + ("d = new b;", ["handle of class `B`", "class `D`"]), + ("u = new d;", ["handle of class `D`", "class `U`"]), ("$cast(d.next, b);", ["`$cast` to a class property", ""]), ] { let source = format!( diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 72105e17cca..2a1006e78ec 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -32,7 +32,7 @@ synthesis and is tested at the design level. | Selects | constant and run-time bit selects and indexed part-selects (`[i]`, `[i +: W]`, `[i -: W]`), in reads and writes, in either declaration direction | | Patterns | assignment patterns for packed structs, packed arrays and unpacked arrays (`'{a, b}`, `'{x: a, default: 0}`, `'{n{a}}`, `T'{...}`) | | Strings | `string` variables, function arguments and results: assignment of strings, string literals and casts (`string'(x)`), `==`, `!=` and ordering comparisons, concatenation and replication (with a run-time count), character reads and writes (`s[i]`), and the methods `len`, `getc`, `putc`, `toupper`, `tolower`, `compare`, `icompare`, `substr`, `atoi` / `atohex` / `atooct` / `atobin` and `itoa` / `hextoa` / `octtoa` / `bintoa`; `%s` and format-less display of string values. See [strings](#strings) | -| Classes | classes declared in a module: properties of 2-state integral types up to 64 bits, `string` and class handle types, with initializers; `new` with and without arguments, implicit and explicit constructors; methods (`function` and `task`, also `extern` with an out-of-block body) called through a handle or unqualified inside the class; `this`, `null`, handle assignment and comparison; inheritance of properties and methods, with base constructors called by `super.new(...)` or `extends Base(...)`; `super.` members; virtual methods, abstract (`virtual`) classes and pure virtual methods; classes that implement interface classes and method calls through interface class handles; `$cast` of class handles, as a function and as a task; static properties and methods; `C::` scope resolution of static members and `C::new`; arrays of handles; parameterized classes with value and type parameters, parameters read through a handle or `C#(...)::`, typedefs of classes and interface classes and `C::T`; named constructor arguments. 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; parameterized classes with value and type parameters, parameters read through a handle or `C#(...)::`, typedefs of classes and interface classes and `C::T`; named constructor arguments; shallow copies (`new h`). See [classes](#classes) | | Parameters | integral parameters and overrides preserving widths beyond 128 bits and X/Z values, and parameters of unpacked array or packed struct type given by an assignment pattern (constant tables), including unpacked-array pattern overrides | ### Processes and control flow @@ -187,7 +187,7 @@ Celox reports an `Unsupported` error naming the construct instead of ignoring it. The error carries the number of the issue that tracks the construct; constructs without a dedicated issue point to the frontend roadmap, [#88](https://github.com/celox-sim/celox/issues/88). -- Class features beyond those [listed](#classes): `$cast` to a variable that is not a class handle, enumeration constants declared in a class, enumeration, struct and union types and named four-state or string constants as class parameter values, classes declared in packages, 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, enumeration constants declared in a class, enumeration, struct and union types and named four-state or string constants as class parameter values, classes declared in packages, and properties that are 4-state, `real`, arrays or wider than 64 bits. Timed tasks with static local declarations, recursive calls and `ref` arguments remain unsupported. - 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`. @@ -322,7 +322,10 @@ 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. +the class, so each instance of the module has its own. `new h` creates an +object of the class of the object `h` refers to with a copy of its properties, +without running a constructor; a property holding a handle is copied, so both +objects refer to the same object (8.12). Copying `null` is a runtime error. Each set of parameter values and types of a parameterized class is a specialization, a class of its own with its own static properties (IEEE diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 282d29ac1bc..66f8b95f40b 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -29,7 +29,7 @@ outline: [2, 3] | 式 | `**` を含む算術、論理、シフト、比較、リダクション、連結・複製、`?:`、`inside`、`==?` / `!=?`、キャスト(`N'(x)`、`signed'(x)`、`T'(x)`)、`$signed` / `$unsigned` | | 選択 | 定数・実行時のビット選択と indexed part-select(`[i]`、`[i +: W]`、`[i -: W]`)。読み書きの両方、宣言の向きによらず | | パターン | packed 構造体・packed 配列・unpacked 配列の assignment pattern(`'{a, b}`、`'{x: a, default: 0}`、`'{n{a}}`、`T'{...}`) | -| クラス | モジュール内で宣言したクラス。64 ビット以下の 2 値整数型・`string`・クラスハンドル型のプロパティ(初期値つきも可)、引数あり・なしの `new`、暗黙と明示のコンストラクタ、ハンドル経由またはクラス内から修飾なしで呼ぶメソッド(`function` と `task`、本体をクラス外に書く `extern` も可)、`this`、`null`、ハンドルの代入と比較、プロパティとメソッドの継承(基底クラスのコンストラクタは `super.new(...)` か `extends Base(...)` で呼ぶ)、`super.` によるメンバ参照、virtual メソッド、抽象クラス(`virtual class`)と pure virtual メソッド、interface クラスを実装するクラスと interface クラスのハンドルを通したメソッド呼び出し、関数とタスクとしてのクラスハンドルの `$cast`、static プロパティとメソッド、static メンバと `C::new` の `C::` によるスコープ解決、ハンドルの配列、値パラメータと型パラメータを持つパラメータ付きクラス、ハンドルや `C#(...)::` を通したパラメータの参照、クラスと interface クラスの typedef と `C::T`、名前付きのコンストラクタ引数。[クラス](#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::` によるスコープ解決、ハンドルの配列、値パラメータと型パラメータを持つパラメータ付きクラス、ハンドルや `C#(...)::` を通したパラメータの参照、クラスと interface クラスの typedef と `C::T`、名前付きのコンストラクタ引数、浅いコピー(`new h`)。[クラス](#classes)を参照 | | 文字列 | `string` 型の変数、関数の引数と戻り値。文字列・文字列リテラル・キャスト(`string'(x)`)の代入、`==` / `!=` と大小比較、連結と複製(実行時の回数も可)、文字の読み書き(`s[i]`)、メソッド `len`、`getc`、`putc`、`toupper`、`tolower`、`compare`、`icompare`、`substr`、`atoi` / `atohex` / `atooct` / `atobin`、`itoa` / `hextoa` / `octtoa` / `bintoa`。`%s` と書式なしの表示。[文字列](#strings)を参照 | | パラメータ | 整数のパラメータ、128ビットを超える幅と X/Z を保持するパラメータ上書き、assignment pattern で与える unpacked 配列型・packed 構造体型のパラメータ(定数テーブル)と unpacked 配列のパターンによる上書き | @@ -163,7 +163,7 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 その構文を追跡する issue の番号が含まれます。専用の issue がない構文は、フロントエンドの ロードマップ [#88](https://github.com/celox-sim/celox/issues/88) を指します。 -- [対応範囲](#classes)外のクラスの機能:クラスハンドル以外の変数への `$cast`、クラス内で宣言した列挙定数、クラスパラメータの値としての列挙型・構造体型・共用体型と名前付きの 4 値・文字列定数、package 内で宣言したクラス、浅いコピー(`new h`)、4 値・`real`・配列・64 ビットを超えるプロパティ。時間待ちを含む task の static ローカル宣言、再帰呼び出し、`ref` 引数。 +- [対応範囲](#classes)外のクラスの機能:クラスハンドル以外の変数への `$cast`、クラス内で宣言した列挙定数、クラスパラメータの値としての列挙型・構造体型・共用体型と名前付きの 4 値・文字列定数、package 内で宣言したクラス、4 値・`real`・配列・64 ビットを超えるプロパティ。時間待ちを含む task の static ローカル宣言、再帰呼び出し、`ref` 引数。 - interface のポート、`inout` / `ref` / 式を使う modport、virtual interface など。 interface 自体と入れ子の interface は対応しています。型パラメータはインスタンスごとに解決し、modport ポート経由でも伝搬します。 再帰する特殊化と64段を超える入れ子は拒否します。細かな制約は[英語版の一覧](/guide/systemverilog-reference#interface-restrictions)を参照してください。 @@ -212,7 +212,7 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 ハンドルは、そのクラス・基底クラス・実装する 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 つずつあります。 +コンストラクタは、まず `super.new(...)` または `extends` 節の引数で基底クラスのコンストラクタを呼び、次に自クラスが宣言するプロパティの初期値を設定し、最後に本体を実行します(IEEE 1800-2023 8.17)。static プロパティはクラスを宣言したモジュールの変数なので、モジュールのインスタンスごとに 1 つずつあります。`new h` は、`h` が参照するオブジェクトと同じクラスのオブジェクトを、プロパティをコピーして作ります。コンストラクタは実行せず、ハンドルを持つプロパティはハンドルだけをコピーするので、両方のオブジェクトが同じオブジェクトを参照します(8.12)。`null` のコピーは実行時エラーです。 パラメータ付きクラスでは、パラメータの値と型の組ごとに 1 つの特殊化があり、それぞれが独立したクラスとして static プロパティを持ちます(IEEE 1800-2023 8.25)。`C#(2, int)` と `C#(.T(int), .N(2))` は同じ特殊化で、`C#(2)` のハンドルは `C#(3)` の変数に代入できません。パラメータ値の割り当ては書いた場所で評価するので、モジュールのパラメータに依存してもかまいません。型としてのクラス名だけはクラスの中でもデフォルトの特殊化 `C#()` を表します。`::` の前に置いたクラス名は、クラスの中と extern メソッドの本体では宣言中の特殊化を指し、それ以外の場所では `C#()::` と書く必要があります(8.25.1)。interface クラスは継承する interface クラスのパラメータと typedef を引き継ぎ、異なる interface クラスや特殊化から同じ名前を引き継ぐ場合は自分で宣言し直す必要があります(8.26.6.2、8.26.6.3)。Celox はモジュールの型とスコープが参照する特殊化を実行前にすべて作り、generate ブロック内の割り当てはそのインスタンスごとに評価します。