Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions conformance/sv-tests/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions conformance/sv-tests/expected.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion crates/celox-frontend-sv/src/lowering/ff/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
34 changes: 34 additions & 0 deletions crates/celox-heap/src/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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();
Expand Down
3 changes: 3 additions & 0 deletions crates/celox-heap/src/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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}"),
}
}
Expand Down
52 changes: 52 additions & 0 deletions crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Option<String>> {
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`.
Expand Down Expand Up @@ -611,6 +640,29 @@ pub(in crate::ast) fn constructor(
dimensions: &PackedDimensions,
class_name: &str,
) -> Converted<Option<Expr>> {
// `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 {
Comment on lines +643 to +646

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Lower copy nodes in non-assignment expression contexts

A Copy node is lowered only when constructor is called for the complete right-hand side of an assignment, declaration initializer, or property initializer. In other valid contextual positions such as take(new h), return new h, or a conditional branch, normal bind_value traversal reaches the new node and rejects it as an unsupported primary expression, even when the formal, return, or enclosing assignment type supplies the required class. Handle ExprKind::Copy wherever a class-valued expression is bound, rather than only at top-level assignment sites.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tracked in #1891 (shallow copies of class-valued expressions, in any context and of null): these forms are rejected with a diagnostic today, not lowered wrongly.

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 {
Expand Down
3 changes: 3 additions & 0 deletions crates/celox-sv-analyzer/src/ast/parameters/skipped.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
}
Expand Down
6 changes: 5 additions & 1 deletion crates/celox-sv-analyzer/src/system_functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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),
}
}
}
Expand All @@ -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",
})
}
}
Expand Down
2 changes: 2 additions & 0 deletions crates/celox-sv-syntax/src/nodes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ pub enum ExprKind {
member: Name,
value: Option<ExprId>,
},
/// `new h`: a shallow copy of the object of handle `h` (8.12).
Copy(ExprId),
Member {
expression: ExprId,
separator: String,
Expand Down
25 changes: 25 additions & 0 deletions crates/celox-sv-syntax/src/parser/expressions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ pub(super) enum Job {
minimum: u8,
member: Name,
},
Copy {
start: usize,
minimum: u8,
},
GroupTypical {
start: usize,
minimum: u8,
Expand Down Expand Up @@ -312,6 +316,7 @@ impl Parser<'_> {
pending.push(*expression);
}
ExprKind::Group(value)
| ExprKind::Copy(value)
| ExprKind::Member {
expression: value, ..
} => pending.push(*value),
Expand Down Expand Up @@ -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"))
Comment on lines +597 to +599

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Accept null as a shallow-copy operand

The lookahead recognizes a shallow copy only when the token after new is a non-reserved identifier, this, or super, so an assignment such as C dst; initial dst = new null; does not produce ExprKind::Copy and fails during parsing instead of reaching the null-copy runtime fault implemented by this change. null is an expression operand of the new expression form, so it needs to be recognized here and typed from the destination context.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tracked in #1891 (shallow copies of class-valued expressions, in any context and of null): these forms are rejected with a diagnostic today, not lowered wrongly.

}) =>
{
self.at += 1;
jobs.push(Job::Copy { start, minimum });
jobs.push(Job::Expression(0));
}
"(" => {
self.at += 1;
jobs.push(Job::Group { start, minimum });
Expand Down Expand Up @@ -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,
Expand Down
4 changes: 3 additions & 1 deletion crates/celox-sv-syntax/src/parser/procedures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
21 changes: 21 additions & 0 deletions crates/celox-sv-syntax/src/parser/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Vec<_>>();
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(
Expand Down
1 change: 1 addition & 0 deletions crates/celox-test-suite/LIMITATIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
49 changes: 49 additions & 0 deletions crates/celox-test-suite/src/sv/cases/class.vtest
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading
Loading