From 462d189a32789bbf644148548c37aa153a2b0c04 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 22 Oct 2026 23:47:38 +0900 Subject: [PATCH 1/2] feat(sv)!: support interface class handles and $cast of class handles A variable of an interface class type holds a handle of an object whose class implements it; a method called through it runs the implementation of the object's class, including methods the interface class inherits from the interface classes it extends (IEEE 1800-2023 8.26). Each method of an interface class gets a dispatcher like a virtual method's. A handle may only be assigned to a variable of its class, a base class or an interface class it implements; any other assignment to a variable, a property or from `C::new` is rejected (8.16, 8.26.5). `$cast` to a class handle calls a subroutine generated for the destination class: it assigns a source that is `null` or whose object's class derives from or implements the class and returns 1, and otherwise returns 0, leaving the destination unchanged. Called as a task, a failing cast reports an error. A cast between classes that are not cast compatible fails without a call (8.16). Interface classes are now lowered; one whose methods use its own typedefs or type parameters is left without subroutines and rejected only where its handles are used. sv-tests: 8.26.5--cast_between_interface_classes now passes in both state modes (543 / 545). Verilator's failing interface-to-interface casts and inherited interface methods, and Icarus's missing $cast and interface classes, are recorded as limitations. BREAKING CHANGE: `AnalyzerError` has an `IncompatibleClassHandle` variant, and assignments of incompatible class handles that were accepted are now rejected. Change-Id: I1edcc030c35a6bec183c76b567cff49e1319a7e5 --- conformance/sv-tests/README.md | 11 + conformance/sv-tests/expected.tsv | 4 +- crates/celox-sv-analyzer/src/ast/classes.rs | 197 ++++++++++++++---- .../src/ast/dimensions/discovery.rs | 29 ++- .../src/ast/expression_binding.rs | 17 +- .../src/ast/expression_binding/direct.rs | 25 ++- .../src/ast/expression_binding/objects.rs | 109 +++++++++- .../celox-sv-analyzer/src/ast/procedural.rs | 183 +++++++++++++++- crates/celox-sv-analyzer/src/lib.rs | 11 + crates/celox-test-suite/LIMITATIONS.md | 5 +- .../celox-test-suite/src/sv/cases/class.vtest | 185 ++++++++++++++++ .../repros/interface_class_casts.sv | 28 +++ .../interface_class_casts_verilator.json | 40 ++++ .../verification/sv/icarus/class.json | 104 ++++++++- .../verification/sv/limitations.json | 59 +++++- .../verification/sv/limitations/icarus.json | 36 +++- .../sv/limitations/verilator.json | 20 +- .../verification/sv/verilator/class.json | 69 ++++++ .../tests/frontends/systemverilog/class.rs | 35 ++++ docs/guide/systemverilog-reference.md | 16 +- docs/ja/guide/systemverilog-reference.md | 8 +- 21 files changed, 1106 insertions(+), 85 deletions(-) create mode 100644 crates/celox-test-suite/verification/repros/interface_class_casts.sv create mode 100644 crates/celox-test-suite/verification/repros/interface_class_casts_verilator.json diff --git a/conformance/sv-tests/README.md b/conformance/sv-tests/README.md index a0c9b0c88e3..d1cba2b74f9 100644 --- a/conformance/sv-tests/README.md +++ b/conformance/sv-tests/README.md @@ -187,6 +187,17 @@ passing negative case: its return types conflict, which is rejected. Calls through interface class handles, `$cast`, parameterized classes and shallow copies stay unsupported. +Interface class handles and `$cast` of class handles update two more rows: both +state modes for `8.26.5--cast_between_interface_classes` change from fail to +pass. The case was simulated with calls added after the cast, which reached the +object through both interface class handles. Full official runs at the pinned +revision report 544 passing cases in 2state and 546 in 4state, with no passing +case regressing: an interface class whose methods use its own typedefs or type +parameters, as in `8.26.3--type_access_extends` and +`8.26.6.2--parameter_type_conflict`, is still elaborated without being lowered. +`6.24.2--cast_fn`, `6.24.2--cast_task` and `8.16--cast_func` keep failing +because they cast to integral and enum variables. + The report contains each case’s state mode, verdict, selected execution mode, tags, tool return code and path to the official log. The output directory retains both the official log and runner diagnostics for each case and state mode. diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index df6b904eb10..6e2efb757e4 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1523,8 +1523,8 @@ chapter-8/8.26.4--illegal_forward_def_implements.sv 2state pass chapter-8/8.26.4--illegal_forward_def_implements.sv 4state pass chapter-8/8.26.4--illegal_implements_parameter.sv 2state pass chapter-8/8.26.4--illegal_implements_parameter.sv 4state pass -chapter-8/8.26.5--cast_between_interface_classes.sv 2state fail -chapter-8/8.26.5--cast_between_interface_classes.sv 4state fail +chapter-8/8.26.5--cast_between_interface_classes.sv 2state pass +chapter-8/8.26.5--cast_between_interface_classes.sv 4state pass chapter-8/8.26.5--implemented_class_handle.sv 2state pass chapter-8/8.26.5--implemented_class_handle.sv 4state pass chapter-8/8.26.5--invalid_interface_instantiation.sv 2state pass diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index 55eff2a48e9..aea08638043 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -69,8 +69,15 @@ pub(super) struct Class { /// Identifies the class at run time; stable across modules and runs. pub id: u32, pub base: Option, - /// A `virtual class`, which cannot be constructed (IEEE 1800-2023 8.21). + /// The interface classes the class implements, or the interface class + /// extends (IEEE 1800-2023 8.26). + pub interfaces: Vec, + /// A `virtual class` or an interface class, which cannot be constructed + /// (IEEE 1800-2023 8.21, 8.26). pub is_abstract: bool, + /// An interface class: it has no properties and its methods are pure + /// virtual (IEEE 1800-2023 8.26). + pub is_interface: bool, /// Properties of the class and its bases, bases first. pub properties: Vec, /// How many of `properties` the bases declare. @@ -138,7 +145,9 @@ impl Class { .filter(|method| method.owner == self.name && method.is_virtual) } - /// Whether the class is `ancestor` or derives from it. + /// Whether the class is `ancestor`, derives from it or implements it, + /// so that a handle of the class may be assigned to a variable of + /// `ancestor` (IEEE 1800-2023 8.16, 8.26.5). pub fn derives_from( &self, tree: &AnalysisContext<'_>, @@ -146,18 +155,28 @@ impl Class { env: &HashMap, aliases: &HashMap, ) -> bool { - let mut class = Some(self.name.clone()); - while let Some(name) = class { + let mut pending = vec![self.name.clone()]; + let mut seen = HashSet::default(); + while let Some(name) = pending.pop() { if name == ancestor { return true; } - class = self::class(tree, &name, env, aliases) - .ok() - .and_then(|class| class.base.clone()); + if !seen.insert(name.clone()) { + continue; + } + if let Ok(class) = self::class(tree, &name, env, aliases) { + pending.extend(class.base.iter().chain(&class.interfaces).cloned()); + } } false } + /// The subroutine that `$cast` to a variable of `class` calls (IEEE + /// 1800-2023 8.16). + pub fn cast_name(class: &str) -> String { + format!("{class}::$cast") + } + /// An allocation of an uninitialized object of the class. pub fn allocation(&self) -> Expr { let handles = self @@ -192,8 +211,12 @@ fn declaration<'a>( .find(|class| instances::normalize_identifier(&class.name.spelling) == name) } -/// The classes that body item `item` declares, except interface classes, -/// which have no implementation (IEEE 1800-2023 8.26). +/// Whether `name` is an interface class (IEEE 1800-2023 8.26). +pub(super) fn is_interface(tree: &AnalysisContext<'_>, name: &str) -> bool { + declaration(tree, name).is_some_and(|declaration| declaration.interface) +} + +/// The classes and interface classes that body item `item` declares. pub(super) fn item_classes( item: celox_sv_syntax::BodyItemId, tree: &AnalysisContext<'_>, @@ -208,9 +231,7 @@ pub(super) fn item_classes( .classes .iter() .filter(|class| { - !class.interface - && item.tokens.start <= class.tokens.start - && class.tokens.end <= item.tokens.end + item.tokens.start <= class.tokens.start && class.tokens.end <= item.tokens.end }) .map(|class| instances::normalize_identifier(&class.name.spelling)) .collect() @@ -308,10 +329,15 @@ pub(super) fn class( } let declaration = declaration(tree, name).ok_or_else(|| unsupported(format!("class `{name}`")))?; + let native = tree.declarations(); + let interfaces = declaration + .interfaces + .iter() + .map(|&interface| interface_name(tree, interface, env, aliases)) + .collect::>>()?; if declaration.interface { - return Err(unsupported("interface class")); + return interface_class(tree, name, declaration, interfaces, env, aliases); } - let native = tree.declarations(); let base = match &declaration.base { None => None, Some(base) => { @@ -406,8 +432,13 @@ pub(super) fn class( // implements it with the same return type (8.26.2, 8.26.6.1). An // abstract class may instead re-declare it pure (8.26.7). let mut required = Vec::new(); - for &interface in &declaration.interfaces { - interface_methods(tree, interface, env, aliases, &mut required)?; + for interface in &interfaces { + required.extend( + class(tree, interface, env, aliases)? + .methods + .iter() + .map(|method| (method.name.clone(), method.native)), + ); } for (method_name, prototype) in required { match methods.iter_mut().find(|method| method.name == method_name) { @@ -447,7 +478,9 @@ pub(super) fn class( name: name.to_owned(), id: class_id(name), base: base.map(|base| base.name.clone()), + interfaces, is_abstract: declaration.virtual_class, + is_interface: false, properties, base_properties, statics, @@ -461,32 +494,84 @@ pub(super) fn class( Ok(class) } -/// The methods that interface class type `interface` declares or inherits, -/// with their prototypes, appended to `methods` (IEEE 1800-2023 8.26). A -/// name that several interface classes declare appears once for each. -fn interface_methods( +/// The interface class that type `interface` of an `implements` or an +/// interface class's `extends` list names (IEEE 1800-2023 8.26). +fn interface_name( tree: &AnalysisContext<'_>, interface: celox_sv_syntax::TypeId, env: &HashMap, aliases: &HashMap, - methods: &mut Vec<(String, celox_sv_syntax::SubroutineId)>, -) -> Converted<()> { +) -> Converted { let native = tree.declarations(); let name = type_binding::procedural_type(interface, native, tree, env, aliases)? .and_then(|ty| ty.class.clone()) .ok_or_else(|| unsupported("implemented interface class type"))?; - let declaration = declaration(tree, &name) - .filter(|declaration| declaration.interface) - .ok_or_else(|| unsupported(format!("`implements` of `{name}`, not an interface class")))?; - for method in &declaration.methods { - let method_name = - instances::normalize_identifier(&native.subroutine(method.subroutine).name.spelling); - methods.push((method_name, method.subroutine)); + if !declaration(tree, &name).is_some_and(|declaration| declaration.interface) { + return Err(unsupported(format!( + "`implements` of `{name}`, not an interface class" + ))); + } + Ok(name) +} + +/// Interface class `name`, whose methods are the pure virtual methods it +/// declares and those of the interface classes it extends (IEEE 1800-2023 +/// 8.26). A handle of it refers to an object of a class implementing it. +fn interface_class( + tree: &AnalysisContext<'_>, + name: &str, + declaration: &celox_sv_syntax::ClassDeclaration, + interfaces: Vec, + env: &HashMap, + aliases: &HashMap, +) -> Converted> { + let native = tree.declarations(); + let mut methods: Vec = Vec::new(); + for interface in &interfaces { + for method in &class(tree, interface, env, aliases)?.methods { + methods.retain(|known| known.name != method.name); + methods.push(method.clone()); + } } - for &base in &declaration.interfaces { - interface_methods(tree, base, env, aliases, methods)?; + for method in &declaration.methods { + let subroutine = native.subroutine(method.subroutine); + // A method whose types cannot be resolved, such as one using a + // type parameter or a typedef of the interface class, leaves the + // interface class without a layout; it is lowered only when used. + type_binding::subroutine_formals( + subroutine, + tree, + &PackedDimensions::new(HashMap::default(), env, aliases), + )?; + return_type(tree, method.subroutine, env, aliases)?; + let method_name = instances::normalize_identifier(&subroutine.name.spelling); + methods.retain(|known| known.name != method_name); + methods.push(Method { + name: method_name, + owner: name.to_owned(), + native: method.subroutine, + qualifiers: method.qualifiers, + is_virtual: true, + }); } - Ok(()) + let class = Rc::new(Class { + name: name.to_owned(), + id: class_id(name), + base: None, + interfaces, + is_abstract: true, + is_interface: true, + properties: Vec::new(), + base_properties: 0, + statics: Vec::new(), + methods, + size: 1, + }); + tree.state + .classes + .borrow_mut() + .insert(name.to_owned(), class.clone()); + Ok(class) } /// The return type of subroutine `id`, `None` for a task or `void`. @@ -562,17 +647,16 @@ fn class_id(name: &str) -> u32 { hash.max(1) } -/// The overrides that dispatcher `Class::dispatcher_name(owner, method)` -/// calls: each implementation of the method with the classes, deriving from -/// `owner` and not abstract, whose objects run it. -pub(super) fn dispatch_targets( +/// The classes whose objects a handle of class `ancestor` may refer to: +/// those deriving from it or implementing it that are not abstract (IEEE +/// 1800-2023 8.16), laid out. +fn object_classes( tree: &AnalysisContext<'_>, - owner: &str, - method: &str, + ancestor: &str, env: &HashMap, aliases: &HashMap, -) -> Converted)>> { - let mut targets: Vec<(String, Vec)> = Vec::new(); +) -> Converted>> { + let mut classes = Vec::new(); let mut ids = HashMap::default(); for declaration in &tree.declarations().classes { if declaration.interface || declaration.virtual_class { @@ -583,7 +667,7 @@ pub(super) fn dispatch_targets( let Ok(class) = class(tree, &name, env, aliases) else { continue; }; - if !class.derives_from(tree, owner, env, aliases) { + if !class.derives_from(tree, ancestor, env, aliases) { continue; } if let Some(other) = ids.insert(class.id, name.clone()) { @@ -591,6 +675,23 @@ pub(super) fn dispatch_targets( "classes `{other}` and `{name}` with the same run-time identifier" ))); } + classes.push(class); + } + Ok(classes) +} + +/// The overrides that dispatcher `Class::dispatcher_name(owner, method)` +/// calls: each implementation of the method with the classes, deriving from +/// or implementing `owner` and not abstract, whose objects run it. +pub(super) fn dispatch_targets( + tree: &AnalysisContext<'_>, + owner: &str, + method: &str, + env: &HashMap, + aliases: &HashMap, +) -> Converted)>> { + let mut targets: Vec<(String, Vec)> = Vec::new(); + for class in object_classes(tree, owner, env, aliases)? { let Some(implementation) = class.method(method) else { continue; }; @@ -603,6 +704,20 @@ pub(super) fn dispatch_targets( Ok(targets) } +/// The run-time identifiers of the classes whose objects `$cast` may assign +/// to a variable of class `name` (IEEE 1800-2023 8.16). +pub(super) fn cast_targets( + tree: &AnalysisContext<'_>, + name: &str, + env: &HashMap, + aliases: &HashMap, +) -> Converted> { + Ok(object_classes(tree, name, env, aliases)? + .iter() + .map(|class| class.id) + .collect()) +} + /// A call of object operation `op`. pub(super) fn object_call(op: ObjectOp, args: Vec) -> Expr { Expr::Call { diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs index d15c8400ea1..e822be405e2 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs @@ -457,15 +457,36 @@ fn class_signatures( context, ); } - if !constructor { + if !constructor && !class.interface { publish_signature( classes::Class::subroutine_name(&class_name, "new"), vec![this], - Some(Some(handle)), + Some(Some(handle.clone())), tree, context, ); } + // `$cast` to a variable of the class (8.16). + let formal = |name: &str, direction| { + ( + FunctionArgumentMetadata { + name: name.into(), + direction, + has_default: false, + }, + handle.clone(), + ) + }; + publish_signature( + classes::Class::cast_name(&class_name), + vec![ + formal(procedural::CAST_DESTINATION, ParamDirection::Inout), + formal(procedural::CAST_SOURCE, ParamDirection::Input), + ], + Some(Some(procedural::int_type())), + tree, + context, + ); Ok(()) } /// Publish the signatures of the methods of every class in the source. @@ -474,9 +495,7 @@ pub(in crate::ast) fn all_class_signatures( context: &mut PackedDimensions, ) { for class in &tree.declarations().classes { - if !class.interface { - let _ = class_signatures(class, tree, context); - } + let _ = class_signatures(class, tree, context); } } fn publish_signature( diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding.rs b/crates/celox-sv-analyzer/src/ast/expression_binding.rs index 065187f34ae..0e3c5c64a85 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding.rs @@ -15,8 +15,10 @@ pub(super) use direct::{ }; pub(super) use lvalues::{net_lvalue, variable_lvalue}; pub(super) use objects::{ - Receiver as ObjectReceiver, constructor as object_constructor, method as object_method, - property as object_property, receiver as object_receiver, this as object_this, + Cast as ObjectCast, Receiver as ObjectReceiver, cast as object_cast, + check_assignment as check_handle_assignment, constructor as object_constructor, + method as object_method, property as object_property, receiver as object_receiver, + this as object_this, }; pub(super) use strings::{ call as string_call, method as string_method, native_string, to_string as string_operand, @@ -56,10 +58,13 @@ pub(super) fn expression( .and_then(|shape| shape.class.as_deref()), LValue::Select { .. } => None, }; - if let Some(class) = class - && let Some(call) = objects::constructor(tree, root, native, dimensions, class)? - { - return Ok(call); + if let Some(class) = class { + if let Some(call) = objects::constructor(tree, root, native, dimensions, class)? { + return Ok(call); + } + objects::check_assignment(tree, root, native, dimensions, class, || { + "assignment".to_owned() + })?; } let value = bind_value(root, native, tree, dimensions, shape)?; // A string literal or integral value assigned to a string becomes its diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index ebc5adcd21b..353394f99bd 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -527,7 +527,30 @@ pub(in crate::ast) fn bind_value( } let name = bound_callable_name(tree, *expression, native, dimensions)? .ok_or_else(|| unsupported("method or randomize call"))?; - if name.starts_with('$') && !name.contains("::") { + let cast = match name.as_str() { + "$cast" => objects::cast(tree, args, native, dimensions)?, + _ => None, + }; + if let Some(cast) = cast { + let objects::Cast::Call { + name, + destination, + source, + } = cast + else { + values.push(Expr::Literal("0".into())); + continue; + }; + ( + Finish::Call { + name, + args: vec![Some(destination), Some(source)], + order: Vec::new(), + system: None, + }, + vec![(destination, None), (source, None)], + ) + } else if name.starts_with('$') && !name.contains("::") { let presence = args .iter() .map(|arg| { diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs index 7665af7a0b4..41b00e548c0 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -321,6 +321,104 @@ pub(in crate::ast) fn method( Ok(Some((subroutine, formals, receiver))) } +/// Check that the handle native expression `id` evaluates to may be +/// assigned to a variable of class `target`: its class derives from or +/// implements `target`, or it is `null` or of a class not known before +/// binding (IEEE 1800-2023 8.16, 8.26.5). +pub(in crate::ast) fn check_assignment( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, + target: &str, + context: impl FnOnce() -> String, +) -> Converted<()> { + let Some(source) = native_class(tree, id, native, dimensions) else { + return Ok(()); + }; + if derives_from(tree, dimensions, &source, target)? { + return Ok(()); + } + Err(AnalyzerError::IncompatibleClassHandle { + context: context(), + actual: source, + target: target.to_owned(), + }) +} + +/// Whether class `class_name` derives from or implements `ancestor`. +fn derives_from( + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, + class_name: &str, + ancestor: &str, +) -> Converted { + Ok(class(tree, dimensions, class_name)?.derives_from( + tree, + ancestor, + &dimensions.const_env, + &dimensions.type_aliases, + )) +} + +/// A `$cast(destination, source)` whose destination is a class handle +/// (IEEE 1800-2023 8.16). +pub(in crate::ast) enum Cast { + /// A call of the destination class's [`Class::cast_name`] subroutine + /// with the destination and the source. + Call { + name: String, + destination: ExprId, + source: ExprId, + }, + /// The source's class is neither assignment nor cast compatible with + /// the destination's, so the cast fails whatever the source's value. + Fails, +} + +/// The `$cast` with `arguments` when its destination is a variable or an +/// array element of a class handle type. +pub(in crate::ast) fn cast( + tree: &AnalysisContext<'_>, + arguments: &[celox_sv_syntax::Argument], + native: &Declarations, + dimensions: &PackedDimensions, +) -> Converted> { + let [destination, source] = arguments else { + return Ok(None); + }; + let (Some(destination), Some(source), None, None) = ( + destination.value, + source.value, + &destination.name, + &source.name, + ) else { + return Ok(None); + }; + let Some(target) = native_class(tree, destination, native, dimensions) else { + return Ok(None); + }; + if property(tree, destination, native, dimensions)?.is_some() { + return Err(unsupported("`$cast` to a class property")); + } + class(tree, dimensions, &target)?; + // The source's class may be a base of the destination's, or an interface + // class, whose object the call checks; any other class's cannot be + // assigned (8.16). + if let Some(source_class) = native_class(tree, source, native, dimensions) + && !derives_from(tree, dimensions, &source_class, &target)? + && !derives_from(tree, dimensions, &target, &source_class)? + && !class(tree, dimensions, &source_class)?.is_interface + { + return Ok(Some(Cast::Fails)); + } + Ok(Some(Cast::Call { + name: Class::cast_name(&target), + destination, + source, + })) +} + /// The receiver of an unqualified method call inside a method. pub(in crate::ast) fn this() -> Expr { Expr::Ident(THIS.into()) @@ -354,7 +452,16 @@ pub(in crate::ast) fn constructor( name, } if separator == "::" && name.spelling == "new" => { match named_class(tree, *expression, native, dimensions) { - Some(class) => class, + Some(class) => { + if !derives_from(tree, dimensions, &class, class_name)? { + return Err(AnalyzerError::IncompatibleClassHandle { + context: format!("`{class}::new`"), + actual: class, + target: class_name.to_owned(), + }); + } + class + } None => return Ok(None), } } diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 6d1661eb256..7fb788f706d 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -111,7 +111,7 @@ pub(super) fn scoped_type(mut r#type: Type, const_env: &HashMap) - } /// The `int` type of a loop variable declared by `foreach`. -fn int_type() -> Type { +pub(super) fn int_type() -> Type { Type { is_enum: false, kind: TypeKind::Bit, @@ -629,7 +629,17 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { self.tree, right, native, &self.dims, class, )? { Some(call) => call, - None => bind(right)?, + None => { + expression_binding::check_handle_assignment( + self.tree, + right, + native, + &self.dims, + class, + || format!("assignment to property `{}`", property.name), + )?; + bind(right)? + } } } _ if op == "=" => bind(right)?, @@ -1177,6 +1187,31 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { .collect::>(); let args = (!arguments.iter().any(|arg| arg.name.is_some())).then_some(presence); let name = name.spelling.as_str(); + // `$cast` as a task reports a run-time error when the cast fails + // (IEEE 1800-2023 6.24.2). + if name == "$cast" + && !discarded + && let Some(cast) = + expression_binding::object_cast(self.tree, arguments, declarations, &self.dims)? + { + let error = Stmt::SystemTask { + task: SystemTask::Severity(system_functions::Severity::Error), + site: source_span(declarations.expression(root).tokens, self.tree), + args: vec![SystemTaskArg::Str( + "$cast of a class handle to an incompatible class".into(), + )], + }; + if let expression_binding::ObjectCast::Fails = cast { + return Ok(vec![error]); + } + let mut succeeded = self.native_value(root)?; + self.rename_expr(&mut succeeded); + return Ok(vec![Stmt::If { + condition: succeeded, + then_body: Vec::new(), + else_body: vec![error], + }]); + } let task = match system_functions::check_call( name, args.as_deref(), @@ -1556,7 +1591,8 @@ pub(super) fn subroutine_argument_names( .collect::>(); // A class that cannot be laid out reports why where it is // lowered. - if let Ok(layout) = classes::class(tree, &class, &item.env, &aliases) { + let layout = classes::class(tree, &class, &item.env, &aliases).ok(); + if let Some(layout) = &layout { methods.extend(layout.dispatched_methods().map(|method| { ( classes::Class::dispatcher_name(&class, &method.name), @@ -1591,15 +1627,23 @@ pub(super) fn subroutine_argument_names( params.into_iter().map(|(name, ..)| name).collect(), ); } - if !constructor { + let handle = dimensions_from_type(&scoped_type(handle, &item.env)); + if !constructor && !layout.is_some_and(|layout| layout.is_interface) { let qualified = item.name(&classes::Class::subroutine_name(&class, "new")); directions.insert(qualified.clone(), vec![ParamDirection::Input]); - shapes.insert( - qualified.clone(), - vec![dimensions_from_type(&scoped_type(handle, &item.env))], - ); + shapes.insert(qualified.clone(), vec![handle.clone()]); names.insert(qualified, vec![classes::THIS.to_owned()]); } + let qualified = item.name(&classes::Class::cast_name(&class)); + directions.insert( + qualified.clone(), + vec![ParamDirection::Inout, ParamDirection::Input], + ); + shapes.insert(qualified.clone(), vec![handle.clone(), handle]); + names.insert( + qualified, + vec![CAST_DESTINATION.to_owned(), CAST_SOURCE.to_owned()], + ); } } Ok((names, shapes, directions)) @@ -2295,7 +2339,13 @@ fn lower_class( state: &mut BodyState<'_>, item: &generate::Item, ) -> Converted> { - let class = classes::class(tree, name, declaration_env, type_aliases)?; + let class = match classes::class(tree, name, declaration_env, type_aliases) { + Ok(class) => class, + // An interface class that cannot be laid out has no subroutines; a + // use of its handles reports why (IEEE 1800-2023 8.26). + Err(_) if classes::is_interface(tree, name) => return Ok(Vec::new()), + Err(error) => return Err(error), + }; let mut subroutines = Vec::new(); let mut constructor = false; for (id, _) in classes::declared_methods(tree, name)? { @@ -2330,7 +2380,7 @@ fn lower_class( Some(&targets), )?); } - if !constructor { + if !constructor && !class.is_interface { let handle = classes::handle_type(tree, name) .ok_or_else(|| unsupported(format!("class `{name}`")))?; let ir_type = crate::ir::Type::from_ast( @@ -2385,9 +2435,122 @@ fn lower_class( } subroutines.push(subroutine); } + subroutines.push(lower_cast( + name, + tree, + declaration_env, + type_aliases, + item_dimensions, + state, + item, + )?); Ok(subroutines) } +/// The formals of [`classes::Class::cast_name`]. +pub(super) const CAST_DESTINATION: &str = "destination"; +pub(super) const CAST_SOURCE: &str = "source"; + +/// The subroutine `$cast` to a variable of class `name` calls: it assigns +/// the source handle to the destination and returns 1 when the source is +/// `null` or its object's class derives from or implements the class, and +/// otherwise returns 0 (IEEE 1800-2023 8.16). +#[allow(clippy::too_many_arguments)] +fn lower_cast( + name: &str, + tree: &AnalysisContext<'_>, + declaration_env: &HashMap, + type_aliases: &HashMap, + item_dimensions: &PackedDimensions, + state: &mut BodyState<'_>, + item: &generate::Item, +) -> Converted { + let environment = const_functions::Environment { + constants: &*item.env, + functions: &tree.state.const_functions, + }; + let handle = + classes::handle_type(tree, name).ok_or_else(|| unsupported(format!("class `{name}`")))?; + let ir_handle = + crate::ir::Type::from_ast(scoped_type(handle.clone(), declaration_env), &environment); + let ir_int = crate::ir::Type::from_ast(int_type(), &environment); + let mut labels = vec![0]; + labels.extend(classes::cast_targets( + tree, + name, + declaration_env, + type_aliases, + )?); + let mut builder = BodyBuilder::new( + tree, + item_dimensions, + state, + system_functions::Body::Subroutine, + ); + builder.automatic = true; + let first_local = builder.state.locals.len(); + builder.push_scope(); + let destination = builder.declare(CAST_DESTINATION, handle.clone()); + let source = builder.declare(CAST_SOURCE, handle); + let result = builder.declare("$cast", int_type()); + builder.pop_scope(); + let assign = |lhs: &str, rhs: Expr| Stmt::Assign { + lhs: LValue::Ident(lhs.to_owned()), + rhs, + nonblocking: false, + }; + let mut subroutine = Subroutine { + name: item.name(&classes::Class::cast_name(name)), + is_task: false, + automatic_locals: builder.state.locals[first_local..] + .iter() + .map(|local| local.name.clone()) + .collect(), + persistent_locals: Vec::new(), + return_type: Some(ir_int), + params: vec![ + SubroutineParam { + name: destination.clone(), + source_name: CAST_DESTINATION.to_owned(), + direction: ParamDirection::Inout, + r#type: ir_handle.clone(), + default: None, + }, + SubroutineParam { + name: source.clone(), + source_name: CAST_SOURCE.to_owned(), + direction: ParamDirection::Input, + r#type: ir_handle, + default: None, + }, + ], + return_var: Some(result.clone()), + body: vec![Stmt::Case { + kind: CaseKind::Exact, + selector: classes::object_call( + system_functions::ObjectOp::ClassOf, + vec![Expr::Ident(source.clone())], + ), + items: vec![CaseItemBase { + labels: labels + .iter() + .map(|id| CaseLabel::Value(Expr::Literal(format!("32'd{id}")))) + .collect(), + body: vec![ + assign(&destination, Expr::Ident(source)), + assign(&result, Expr::Literal("1".into())), + ], + }], + default: Some(vec![assign(&result, Expr::Literal("0".into()))]), + }], + sensitivity_body: Vec::new(), + }; + for stmt in &mut subroutine.body { + qualify_stmt(item, stmt); + } + Ok(subroutine) +} + /// Qualify the module-scope names of a statement for its generate scope. pub(super) fn qualify_stmt(item: &generate::Item, stmt: &mut Stmt) { stmt.visit_mut( diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index 2725f991aff..6cb234e623f 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -147,6 +147,17 @@ pub enum AnalyzerError { actual: typecheck::UnpackedArrayType, target: typecheck::UnpackedArrayType, }, + /// A handle of class `actual` assigned to a variable of class `target` + /// that `actual` neither derives from nor implements; only `$cast` may + /// assign it (IEEE 1800-2023 8.16, 8.26.5). + #[error( + "{context}: a handle of class `{actual}` is not assignment compatible with class `{target}`" + )] + IncompatibleClassHandle { + context: String, + actual: String, + target: String, + }, } impl miette::Diagnostic for AnalyzerError {} diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 287bdccd714..5bf57e9bf84 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -494,7 +494,10 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_icarus_nested_class_members` | execute | icarus | 1 | Icarus 13.0 reads an empty string through a nested property path (kept.inner.text) after reporting "sorry: Nested member path not yet supported for class properties" for its assignment. IEEE 1800-2023 8.5 permits accessing a property of an object referred to by a property. Verilator passes the case. | | `sv_icarus_class_scope_resolution` | compile | icarus | 1 | Icarus 13.0 rejects class scope resolution with a syntax error: reading a static property (Counter::created), calling a static method (Counter::next()) and assigning a static property (Counter::last = "set"). IEEE 1800-2023 8.9, 8.10 and 8.23 define these accesses. Verilator passes the case. | | `sv_icarus_virtual_dispatch` | execute | icarus | 1 | Icarus 13.0 binds a virtual function called through a base-class handle to the handle's class instead of the object's: the shared case prints area=0 for every shape, and the adapter-free source prints 1 1 1 3 where IEEE 1800-2023 8.20 requires 2 3 4 4. Verilator and Celox print 2 3 4 4 and pass the case. | -| `sv_icarus_abstract_and_interface_classes` | compile | icarus | 3 | Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors ("Invalid class item", "Invalid module item") and fails code generation without a diagnostic ("Code generation had 2 error(s)") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes all three cases. | +| `sv_icarus_abstract_and_interface_classes` | compile | icarus | 6 | Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors ("Invalid class item", "Invalid module item") and fails code generation without a diagnostic ("Code generation had 2 error(s)") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others. | +| `sv_verilator_interface_class_casts` | execute | verilator | 1 | Verilator 5.052 returns 0 from $cast of a handle of one interface class to a variable of another interface class that the object's class also implements, so the case dereferences the unassigned null handle; the adapter-free source prints 0 1 where IEEE 1800-2023 8.16 and 8.26.5 require 1 1. Celox prints 1 1. Icarus rejects interface classes, see sv_icarus_abstract_and_interface_classes. | +| `sv_verilator_extended_interface_class_methods` | compile | verilator | 1 | Verilator 5.052 does not find a method that an interface class inherits from an interface class it extends when the method is called through a handle of the extending class ("Class method 'sides' not found in class 'NamedShape'"). IEEE 1800-2023 8.26.3 makes the methods of the extended interface classes members of the extending one. Icarus rejects interface classes, see sv_icarus_abstract_and_interface_classes. | +| `sv_icarus_cast` | execute | icarus | 1 | Icarus 13.0 does not implement $cast ("System task/function $cast() is not defined by any module"), which IEEE 1800-2023 6.24.2 and 8.16 define. Verilator passes the case. | | `sv_verilator_class_property_string_methods` | compile | verilator | 1 | Verilator 5.052 stops with an internal error ("AstNode is not of expected type, but instead has type 'MEMBERSEL'") on a string method called on a class property, n.name.itoa(42), which IEEE 1800-2023 6.16 and 8.5 permit. Icarus rejects the case too, see sv_icarus_classes. | | `sv_icarus_unpacked_array_patterns` | compile | icarus | 1 | Icarus 13.0 reports that an assignment pattern with unpacked array items assigned to a multidimensional unpacked array is not yet supported ("Procedural assignment of array or array slice"), so the run cannot count it as a language rejection. The design is invalid (IEEE 1800-2023 7.6, 10.8). | | `sv_icarus_display_field_width` | execute | icarus | 1 | Icarus 13.0 zero-pads a value wider than an explicit field width of %h or %o to the argument's full width (%3h of 32'h1234 prints 00001234); IEEE 1800-2023 21.2.1.2 expands the field to the value without leading zeros (1234). Verilator agrees with the expected value. | diff --git a/crates/celox-test-suite/src/sv/cases/class.vtest b/crates/celox-test-suite/src/sv/cases/class.vtest index c7470fd436a..9aec1add777 100644 --- a/crates/celox-test-suite/src/sv/cases/class.vtest +++ b/crates/celox-test-suite/src/sv/cases/class.vtest @@ -526,3 +526,188 @@ endmodule "#) (top Top) (run_until 0) (assert_eq done 1) (expect_output "3 6\n100 200\n")) + +(case methods_called_through_interface_class_handles + (source "class.sv" #" +module Top(output bit done); + interface class Shape; + pure virtual function int area(int scale); + endclass + interface class Named; + pure virtual function int id(); + endclass + interface class Polygon extends Shape; + pure virtual function int sides(); + endclass + class Rectangle; + int w = 2; + virtual function int area(int scale); + return w * scale; + endfunction + endclass + class Square extends Rectangle implements Polygon, Named; + virtual function int area(int scale); + return w * w * scale; + endfunction + virtual function int sides(); + return 4; + endfunction + virtual function int id(); + return 7; + endfunction + endclass + class Label implements Named; + virtual function int id(); + return 9; + endfunction + endclass + Square square; + Label label; + Shape shape; + Named names[2]; + Polygon polygon; + initial begin + square = new; + label = new; + shape = square; + polygon = square; + names[0] = square; + names[1] = label; + $display("%0d %0d", shape.area(3), polygon.sides()); + $display("%0d %0d", names[0].id(), names[1].id()); + shape = polygon; + $display("%0d %0d", shape.area(1), shape == null); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "12 4\n7 9\n4 0\n")) + +(case inherited_methods_of_extended_interface_classes + (source "class.sv" #" +module Top(output bit done); + interface class Named; + pure virtual function int id(); + endclass + interface class Shape; + pure virtual function int sides(); + endclass + interface class NamedShape extends Named, Shape; + pure virtual function int area(); + endclass + class Triangle implements NamedShape; + virtual function int id(); + return 3; + endfunction + virtual function int sides(); + return 3; + endfunction + virtual function int area(); + return 6; + endfunction + endclass + Triangle triangle; + NamedShape shape; + initial begin + triangle = new; + shape = triangle; + $display("%0d %0d %0d", shape.id(), shape.sides(), shape.area()); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "3 3 6\n")) + +(case casts_of_class_handles + (source "class.sv" #" +module Top(output bit done); + class Animal; + virtual function int legs(); + return 0; + endfunction + endclass + class Dog extends Animal; + virtual function int legs(); + return 4; + endfunction + endclass + class Puppy extends Dog; + endclass + class Rock; + endclass + Animal animal; + Dog dog; + Rock rock; + int ok; + initial begin + animal = Puppy::new; + ok = $cast(dog, animal); + $display("%0d %0d", ok, dog.legs()); + animal = new; + ok = $cast(dog, animal); + $display("%0d %0d", ok, dog.legs()); + animal = null; + ok = $cast(dog, animal); + $display("%0d %0d", ok, dog == null); + dog = new; + ok = $cast(animal, dog); + $display("%0d %0d", ok, animal.legs()); + if (!$cast(rock, dog)) + $display("rock"); + ok = $cast(dog, null); + $display("%0d %0d", ok, dog == null); + animal = Dog::new; + $cast(dog, animal); + $display("%0d", dog.legs()); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "1 4\n0 4\n1 1\n1 4\nrock\n1 1\n4\n")) + +(case casts_from_interface_class_handles + (source "class.sv" #" +module Top(output bit done); + interface class Named; + pure virtual function int id(); + endclass + interface class Sized; + pure virtual function int size(); + endclass + class Box implements Named, Sized; + virtual function int id(); + return 1; + endfunction + virtual function int size(); + return 8; + endfunction + endclass + class Tag implements Named; + virtual function int id(); + return 2; + endfunction + endclass + Box box; + Named named; + Sized sized; + int ok; + initial begin + box = new; + named = box; + ok = $cast(sized, named); + $display("%0d %0d", ok, sized.size()); + box = null; + ok = $cast(box, named); + $display("%0d %0d", ok, box.id()); + named = Tag::new; + ok = $cast(sized, named); + $display("%0d %0d", ok, sized.size()); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "1 8\n1 1\n0 8\n")) diff --git a/crates/celox-test-suite/verification/repros/interface_class_casts.sv b/crates/celox-test-suite/verification/repros/interface_class_casts.sv new file mode 100644 index 00000000000..61a6772c27f --- /dev/null +++ b/crates/celox-test-suite/verification/repros/interface_class_casts.sv @@ -0,0 +1,28 @@ +// $cast from a handle of an interface class assigns the object when its class +// is assignment compatible with the destination (IEEE 1800-2023 8.16, 8.26.5). +// Expected output: 1 1. +module Top; + interface class Named; + pure virtual function int id(); + endclass + interface class Sized; + pure virtual function int size(); + endclass + class Box implements Named, Sized; + virtual function int id(); + return 1; + endfunction + virtual function int size(); + return 8; + endfunction + endclass + Box box; + Box back; + Named named; + Sized sized; + initial begin + box = new; + named = box; + $display("%0d %0d", $cast(sized, named), $cast(back, named)); + end +endmodule diff --git a/crates/celox-test-suite/verification/repros/interface_class_casts_verilator.json b/crates/celox-test-suite/verification/repros/interface_class_casts_verilator.json new file mode 100644 index 00000000000..917d747e16b --- /dev/null +++ b/crates/celox-test-suite/verification/repros/interface_class_casts_verilator.json @@ -0,0 +1,40 @@ +{ + "schema_version": 3, + "suite_version": "0.11.0", + "tool": "verilator", + "version": "Verilator 5.052 2026-09-05 rev v5.052", + "cases": [ + { + "category": "Types", + "detail": "native testbench failed: exit status: 1; see runtime.log and protocol.log\n", + "expectation": "Simulation", + "name": "class::casts_from_interface_class_handles", + "phase": "execute", + "status": "runtime_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "counts": { + "passed": 0, + "mismatch": 0, + "compile_error": 0, + "emission_error": 0, + "ignored": 0, + "rejected": 0, + "runtime_error": 1, + "unexpected_accept": 0, + "unsupported": 0 + }, + "include_ignored": true, + "exclude_stronger_than_sv": false, + "standard": "IEEE 1800-2023 8.16 and 8.26.5: $cast from a handle of an interface class succeeds when the object it refers to is assignment compatible with the destination, including a variable of another interface class that the object's class implements.", + "adapter_free": { + "source": "verification/repros/interface_class_casts.sv", + "verilator_command": "verilator --binary --timing -Wno-fatal --top-module Top --Mdir interface_class_casts.sv", + "verilator_version": "Verilator 5.052 2026-09-05 rev v5.052", + "verilator_output": "0 1", + "expected_output": "1 1" + } +} diff --git a/crates/celox-test-suite/verification/sv/icarus/class.json b/crates/celox-test-suite/verification/sv/icarus/class.json index 2c488fd85ce..7d66640caf0 100644 --- a/crates/celox-test-suite/verification/sv/icarus/class.json +++ b/crates/celox-test-suite/verification/sv/icarus/class.json @@ -2,7 +2,7 @@ "cases": [ { "category": "Types", - "detail": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes all three cases.", + "detail": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others.", "expectation": "Simulation", "known_issue": { "category": "simulator_compile_limitation", @@ -13,7 +13,7 @@ "id": "sv_icarus_abstract_and_interface_classes", "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", "phase": "compile", - "reason": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes all three cases.", + "reason": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others.", "upstream": [] }, "name": "class::abstract_classes_and_pure_virtual_methods", @@ -25,7 +25,7 @@ }, { "category": "Types", - "detail": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes all three cases.", + "detail": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others.", "expectation": "Simulation", "known_issue": { "category": "simulator_compile_limitation", @@ -36,7 +36,53 @@ "id": "sv_icarus_abstract_and_interface_classes", "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", "phase": "compile", - "reason": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes all three cases.", + "reason": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others.", + "upstream": [] + }, + "name": "class::casts_from_interface_class_handles", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 does not implement $cast (\"System task/function $cast() is not defined by any module\"), which IEEE 1800-2023 6.24.2 and 8.16 define. Verilator passes the case.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_cast", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "execute", + "reason": "Icarus 13.0 does not implement $cast (\"System task/function $cast() is not defined by any module\"), which IEEE 1800-2023 6.24.2 and 8.16 define. Verilator passes the case.", + "upstream": [] + }, + "name": "class::casts_of_class_handles", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_abstract_and_interface_classes", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others.", "upstream": [] }, "name": "class::classes_implementing_interface_classes", @@ -114,6 +160,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_abstract_and_interface_classes", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others.", + "upstream": [] + }, + "name": "class::inherited_methods_of_extended_interface_classes", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "Icarus 13.0 does not support extern methods (\"sorry: External methods are not yet supported\") or string methods called on a class property (\"Can't find task itoa in class Named\") or comparisons of class handles (\"SORRY: Compare class handles not implemented\"), aborts on a failed assertion in dup_expr.cc while compiling objects_referring_to_objects, and crashes with a segmentation fault while compiling implicit_constructors_and_this. IEEE 1800-2023 8.4, 8.7, 8.8 and 8.24 define these constructs. Verilator passes all but the string-method case, see sv_verilator_class_property_string_methods.", @@ -139,7 +208,30 @@ }, { "category": "Types", - "detail": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes all three cases.", + "detail": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_abstract_and_interface_classes", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others.", + "upstream": [] + }, + "name": "class::methods_called_through_interface_class_handles", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others.", "expectation": "Simulation", "known_issue": { "category": "simulator_compile_limitation", @@ -150,7 +242,7 @@ "id": "sv_icarus_abstract_and_interface_classes", "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", "phase": "compile", - "reason": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes all three cases.", + "reason": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others.", "upstream": [] }, "name": "class::methods_of_handle_array_elements", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index cd5e9eb793d..6373c0fafc4 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -1904,7 +1904,7 @@ "category": "simulator_compile_limitation", "phase": "compile", "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", - "reason": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes all three cases.", + "reason": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes the first three cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods for the others.", "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", @@ -1914,7 +1914,62 @@ "icarus": [ "class::abstract_classes_and_pure_virtual_methods", "class::methods_of_handle_array_elements", - "class::classes_implementing_interface_classes" + "class::classes_implementing_interface_classes", + "class::methods_called_through_interface_class_handles", + "class::inherited_methods_of_extended_interface_classes", + "class::casts_from_interface_class_handles" + ] + } + }, + { + "id": "sv_verilator_interface_class_casts", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Verilator 5.052 returns 0 from $cast of a handle of one interface class to a variable of another interface class that the object's class also implements, so the case dereferences the unassigned null handle; the adapter-free source prints 0 1 where IEEE 1800-2023 8.16 and 8.26.5 require 1 1. Celox prints 1 1. Icarus rejects interface classes, see sv_icarus_abstract_and_interface_classes.", + "upstream": [], + "evidence": [ + "verification/repros/interface_class_casts_verilator.json", + "verification/repros/interface_class_casts.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "class::casts_from_interface_class_handles" + ] + } + }, + { + "id": "sv_verilator_extended_interface_class_methods", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Verilator 5.052 does not find a method that an interface class inherits from an interface class it extends when the method is called through a handle of the extending class (\"Class method 'sides' not found in class 'NamedShape'\"). IEEE 1800-2023 8.26.3 makes the methods of the extended interface classes members of the extending one. Icarus rejects interface classes, see sv_icarus_abstract_and_interface_classes.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "class::inherited_methods_of_extended_interface_classes" + ] + } + }, + { + "id": "sv_icarus_cast", + "category": "simulator_compile_limitation", + "phase": "execute", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 does not implement $cast (\"System task/function $cast() is not defined by any module\"), which IEEE 1800-2023 6.24.2 and 8.16 define. Verilator passes the case.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "class::casts_of_class_handles" ] } }, diff --git a/crates/celox-test-suite/verification/sv/limitations/icarus.json b/crates/celox-test-suite/verification/sv/limitations/icarus.json index bcde8372c4e..52658fffaa6 100644 --- a/crates/celox-test-suite/verification/sv/limitations/icarus.json +++ b/crates/celox-test-suite/verification/sv/limitations/icarus.json @@ -9,8 +9,8 @@ "unexpected_accept": 1, "mismatch": 16, "emission_error": 0, - "compile_error": 116, - "runtime_error": 7, + "compile_error": 119, + "runtime_error": 8, "unsupported": 0, "ignored": 0 }, @@ -1311,6 +1311,38 @@ "name": "class::classes_implementing_interface_classes", "phase": "compile", "status": "compile_error" + }, + { + "category": "Types", + "detail": "Icarus build exit status: 32; see /build.log\n/source_0.sv:3: syntax error\n/source_0.sv:3: error: Invalid module item.\n/source_0.sv:4: syntax error\n/source_0.sv:4: error: Invalid module item.\n/source_0.sv:5: syntax error\n/source_0.sv:6: error: Invalid module item.\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Invalid module item.\n/source_0.sv:8: syntax error\n/source_0.sv:9: error: Invalid module item.\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Invalid module item.\n/source_0.sv:11: syntax error\n/source_0.sv:11: error: Invalid module item.\n/source_0.sv:12: syntax error\n/source_0.sv:13: error: Invalid module item.\n/source_0.sv:14: syntax error\n/source_0.sv:14: error: Invalid module item.\n/source_0.sv:15: syntax error\n/source_0.sv:17: error: Invalid module item.\n/source_0.sv:18: syntax error\n/source_0.sv:18: error: Invalid module item.\n/source_0.sv:19: syntax error\n/source_0.sv:19: error: Invalid module item.\n/source_0.sv:20: syntax error\n/source_0.sv:22: error: Invalid module item.\n/source_0.sv:23: syntax error\n/source_0.sv:23: error: Invalid module instantiation\n/source_0.sv:24: syntax error\n/source_0.sv:24: error: Invalid module instantiation\n/source_0.sv:34: syntax error\n/source_0.sv:34: error: Malformed statement\n", + "expectation": "Simulation", + "name": "class::casts_from_interface_class_handles", + "phase": "compile", + "status": "compile_error" + }, + { + "category": "Types", + "detail": "native testbench failed: exit status: 7; see runtime.log and protocol.log\n/source_0.sv:23: Error: System task/function $cast() is not defined by any module.\n/source_0.sv:26: Error: System task/function $cast() is not defined by any module.\n/source_0.sv:29: Error: System task/function $cast() is not defined by any module.\n/source_0.sv:32: Error: System task/function $cast() is not defined by any module.\n/source_0.sv:34: Error: System task/function $cast() is not defined by any module.\n/source_0.sv:36: Error: System task/function $cast() is not defined by any module.\n/source_0.sv:39: Error: System task/function $cast() is not defined by any module.\n", + "expectation": "Simulation", + "name": "class::casts_of_class_handles", + "phase": "execute", + "status": "runtime_error" + }, + { + "category": "Types", + "detail": "Icarus build exit status: 30; see /build.log\n/source_0.sv:3: syntax error\n/source_0.sv:3: error: Invalid module item.\n/source_0.sv:4: syntax error\n/source_0.sv:4: error: Invalid module item.\n/source_0.sv:5: syntax error\n/source_0.sv:6: error: Invalid module item.\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Invalid module item.\n/source_0.sv:8: syntax error\n/source_0.sv:9: error: Invalid module item.\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Invalid module item.\n/source_0.sv:11: syntax error\n/source_0.sv:12: error: Invalid module item.\n/source_0.sv:13: syntax error\n/source_0.sv:13: error: Invalid module item.\n/source_0.sv:14: syntax error\n/source_0.sv:14: error: Invalid module item.\n/source_0.sv:15: syntax error\n/source_0.sv:16: error: Invalid module item.\n/source_0.sv:17: syntax error\n/source_0.sv:17: error: Invalid module item.\n/source_0.sv:18: syntax error\n/source_0.sv:19: error: Invalid module item.\n/source_0.sv:20: syntax error\n/source_0.sv:20: error: Invalid module item.\n/source_0.sv:21: syntax error\n/source_0.sv:23: error: Invalid module item.\n/source_0.sv:24: syntax error\n/source_0.sv:24: error: Invalid module instantiation\n", + "expectation": "Simulation", + "name": "class::inherited_methods_of_extended_interface_classes", + "phase": "compile", + "status": "compile_error" + }, + { + "category": "Types", + "detail": "Icarus build exit status: 46; see /build.log\n/source_0.sv:3: syntax error\n/source_0.sv:3: error: Invalid module item.\n/source_0.sv:4: syntax error\n/source_0.sv:4: error: Invalid module item.\n/source_0.sv:5: syntax error\n/source_0.sv:6: error: Invalid module item.\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Invalid module item.\n/source_0.sv:8: syntax error\n/source_0.sv:9: error: Invalid module item.\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Invalid module item.\n/source_0.sv:11: syntax error\n/source_0.sv:12: error: Invalid module item.\n/source_0.sv:14: syntax error\n/source_0.sv:14: error: Invalid module item.\n/source_0.sv:15: syntax error\n/source_0.sv:15: error: Invalid module item.\n/source_0.sv:16: syntax error\n/source_0.sv:18: error: Invalid module item.\n/source_0.sv:19: syntax error\n/source_0.sv:19: error: Invalid module item.\n/source_0.sv:20: syntax error\n/source_0.sv:20: error: Invalid module item.\n/source_0.sv:21: syntax error\n/source_0.sv:22: error: Invalid module item.\n/source_0.sv:23: syntax error\n/source_0.sv:23: error: Invalid module item.\n/source_0.sv:24: syntax error\n/source_0.sv:25: error: Invalid module item.\n/source_0.sv:26: syntax error\n/source_0.sv:26: error: Invalid module item.\n/source_0.sv:27: syntax error\n/source_0.sv:29: error: Invalid module item.\n/source_0.sv:30: syntax error\n/source_0.sv:30: error: Invalid module item.\n/source_0.sv:31: syntax error\n/source_0.sv:31: error: Invalid module item.\n/source_0.sv:32: syntax error\n/source_0.sv:34: error: Invalid module item.\n/source_0.sv:35: syntax error\n/source_0.sv:35: error: Invalid module instantiation\n/source_0.sv:36: syntax error\n/source_0.sv:36: error: Invalid module instantiation\n/source_0.sv:38: syntax error\n/source_0.sv:38: error: Invalid module instantiation\n", + "expectation": "Simulation", + "name": "class::methods_called_through_interface_class_handles", + "phase": "compile", + "status": "compile_error" } ] } diff --git a/crates/celox-test-suite/verification/sv/limitations/verilator.json b/crates/celox-test-suite/verification/sv/limitations/verilator.json index 7dde73b816f..fe8238160f7 100644 --- a/crates/celox-test-suite/verification/sv/limitations/verilator.json +++ b/crates/celox-test-suite/verification/sv/limitations/verilator.json @@ -9,8 +9,8 @@ "unexpected_accept": 0, "mismatch": 21, "emission_error": 0, - "compile_error": 17, - "runtime_error": 1, + "compile_error": 18, + "runtime_error": 2, "unsupported": 0, "ignored": 0 }, @@ -410,6 +410,22 @@ "name": "class::string_methods_on_properties", "phase": "compile", "status": "compile_error" + }, + { + "category": "Types", + "detail": "native testbench failed: exit status: 1; see runtime.log and protocol.log\n", + "expectation": "Simulation", + "name": "class::casts_from_interface_class_handles", + "phase": "execute", + "status": "runtime_error" + }, + { + "category": "Types", + "detail": "Verilator build exit status: 1; see /build.log\n%Error: /source_0.sv:28:51: Class method 'sides' not found in class 'NamedShape'\n : ... note: In instance 'celox_suite_tb.dut'\n 28 | $display(\"%0d %0d %0d\", shape.id(), shape.sides(), shape.area());\n | ^~~~~\n ... See the manual at https://verilator.org/verilator_doc.html?v=5.052 for more assistance.\n%Error: Exiting due to 1 error(s)\n", + "expectation": "Simulation", + "name": "class::inherited_methods_of_extended_interface_classes", + "phase": "compile", + "status": "compile_error" } ] } diff --git a/crates/celox-test-suite/verification/sv/verilator/class.json b/crates/celox-test-suite/verification/sv/verilator/class.json index 736c8fff273..50899178c71 100644 --- a/crates/celox-test-suite/verification/sv/verilator/class.json +++ b/crates/celox-test-suite/verification/sv/verilator/class.json @@ -11,6 +11,41 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "Verilator 5.052 returns 0 from $cast of a handle of one interface class to a variable of another interface class that the object's class also implements, so the case dereferences the unassigned null handle; the adapter-free source prints 0 1 where IEEE 1800-2023 8.16 and 8.26.5 require 1 1. Celox prints 1 1. Icarus rejects interface classes, see sv_icarus_abstract_and_interface_classes.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/interface_class_casts_verilator.json", + "verification/repros/interface_class_casts.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_interface_class_casts", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "execute", + "reason": "Verilator 5.052 returns 0 from $cast of a handle of one interface class to a variable of another interface class that the object's class also implements, so the case dereferences the unassigned null handle; the adapter-free source prints 0 1 where IEEE 1800-2023 8.16 and 8.26.5 require 1 1. Celox prints 1 1. Icarus rejects interface classes, see sv_icarus_abstract_and_interface_classes.", + "upstream": [] + }, + "name": "class::casts_from_interface_class_handles", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::casts_of_class_handles", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", @@ -66,6 +101,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "Verilator 5.052 does not find a method that an interface class inherits from an interface class it extends when the method is called through a handle of the extending class (\"Class method 'sides' not found in class 'NamedShape'\"). IEEE 1800-2023 8.26.3 makes the methods of the extended interface classes members of the extending one. Icarus rejects interface classes, see sv_icarus_abstract_and_interface_classes.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_extended_interface_class_methods", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Verilator 5.052 does not find a method that an interface class inherits from an interface class it extends when the method is called through a handle of the extending class (\"Class method 'sides' not found in class 'NamedShape'\"). IEEE 1800-2023 8.26.3 makes the methods of the extended interface classes members of the extending one. Icarus rejects interface classes, see sv_icarus_abstract_and_interface_classes.", + "upstream": [] + }, + "name": "class::inherited_methods_of_extended_interface_classes", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", @@ -77,6 +135,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::methods_called_through_interface_class_handles", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", diff --git a/crates/celox/tests/frontends/systemverilog/class.rs b/crates/celox/tests/frontends/systemverilog/class.rs index a70bfda6206..d3ce2c4cdcb 100644 --- a/crates/celox/tests/frontends/systemverilog/class.rs +++ b/crates/celox/tests/frontends/systemverilog/class.rs @@ -20,6 +20,10 @@ sv_backends! { fn class_abstract_classes_and_pure_virtual_methods(sim) { @case "class::abstract_classes_and_pure_virtual_methods"; } fn class_methods_of_handle_array_elements(sim) { @case "class::methods_of_handle_array_elements"; } fn class_classes_implementing_interface_classes(sim) { @case "class::classes_implementing_interface_classes"; } + fn class_methods_called_through_interface_class_handles(sim) { @case "class::methods_called_through_interface_class_handles"; } + fn class_inherited_methods_of_extended_interface_classes(sim) { @case "class::inherited_methods_of_extended_interface_classes"; } + fn class_casts_of_class_handles(sim) { @case "class::casts_of_class_handles"; } + fn class_casts_from_interface_class_handles(sim) { @case "class::casts_from_interface_class_handles"; } } sv_backends! { @@ -158,3 +162,34 @@ fn misplaced_super_new_static_misuse_and_unimplemented_methods_are_rejected() { assert!(error.contains(want), "{error}"); } } + +#[test] +fn incompatible_class_handle_assignments_are_rejected() { + for (statement, want) in [ + ("d = b;", ["handle of class `B`", "class `D`"]), + ("d = u;", ["handle of class `U`", "class `D`"]), + ("i = b;", ["handle of class `B`", "class `I`"]), + ("b = U::new;", ["handle of class `U`", "class `B`"]), + ("d.next = b;", ["handle of class `B`", "class `D`"]), + ("$cast(d.next, b);", ["`$cast` to a class property", ""]), + ] { + let source = format!( + "module Top; + interface class I; endclass + class B; endclass + class D extends B implements I; D next; endclass + class U; endclass + B b; D d; U u; I i; + initial begin d = new; {statement} end + endmodule" + ); + let Err(error) = + Simulator::from_sv_sources(vec![(source.as_str(), Path::new("class.sv"))], "Top") + .build_cranelift() + else { + panic!("`{statement}` is rejected"); + }; + let error = error.to_string(); + assert!(want.iter().all(|want| error.contains(want)), "{error}"); + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index d3358f3d560..a5944c2c5db 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -30,7 +30,7 @@ synthesis and is tested at the design level. | Selects | constant and run-time bit selects and indexed part-selects (`[i]`, `[i +: W]`, `[i -: W]`), in reads and writes, in either declaration direction | | Patterns | assignment patterns for packed structs, packed arrays and unpacked arrays (`'{a, b}`, `'{x: a, default: 0}`, `'{n{a}}`, `T'{...}`) | | Strings | `string` variables, function arguments and results: assignment of strings, string literals and casts (`string'(x)`), `==`, `!=` and ordering comparisons, concatenation and replication (with a run-time count), character reads and writes (`s[i]`), and the methods `len`, `getc`, `putc`, `toupper`, `tolower`, `compare`, `icompare`, `substr`, `atoi` / `atohex` / `atooct` / `atobin` and `itoa` / `hextoa` / `octtoa` / `bintoa`; `%s` and format-less display of string values. See [strings](#strings) | -| Classes | classes declared in a module: properties of 2-state integral types up to 64 bits, `string` and class handle types, with initializers; `new` with and without arguments, implicit and explicit constructors; methods (`function` and `task`, also `extern` with an out-of-block body) called through a handle or unqualified inside the class; `this`, `null`, handle assignment and comparison; inheritance of properties and methods, with base constructors called by `super.new(...)` or `extends Base(...)`; `super.` members; virtual methods, abstract (`virtual`) classes and pure virtual methods; classes that implement interface classes; static properties and methods; `C::` scope resolution of static members and `C::new`; arrays of handles. See [classes](#classes) | +| Classes | classes declared in a module: properties of 2-state integral types up to 64 bits, `string` and class handle types, with initializers; `new` with and without arguments, implicit and explicit constructors; methods (`function` and `task`, also `extern` with an out-of-block body) called through a handle or unqualified inside the class; `this`, `null`, handle assignment and comparison; inheritance of properties and methods, with base constructors called by `super.new(...)` or `extends Base(...)`; `super.` members; virtual methods, abstract (`virtual`) classes and pure virtual methods; classes that implement interface classes and method calls through interface class handles; `$cast` of class handles, as a function and as a task; static properties and methods; `C::` scope resolution of static members and `C::new`; arrays of handles. See [classes](#classes) | | Parameters | integral parameters and overrides preserving widths beyond 128 bits and X/Z values, and parameters of unpacked array or packed struct type given by an assignment pattern (constant tables), including unpacked-array pattern overrides | ### Processes and control flow @@ -128,7 +128,7 @@ Celox reports an `Unsupported` error naming the construct instead of ignoring it. The error carries the number of the issue that tracks the construct; constructs without a dedicated issue point to the frontend roadmap, [#88](https://github.com/celox-sim/celox/issues/88). -- Class features beyond those [listed](#classes): method calls through an interface class handle, `$cast`, classes declared in packages, parameterized classes, named constructor arguments, shallow copies (`new h`), and properties that are 4-state, `real`, arrays or wider than 64 bits. Timed tasks with static local declarations, recursive calls and `ref` arguments remain unsupported. +- Class features beyond those [listed](#classes): `$cast` to a variable that is not a class handle, typedefs and parameters of interface classes, classes declared in packages, parameterized classes, named constructor arguments, shallow copies (`new h`), and properties that are 4-state, `real`, arrays or wider than 64 bits. Timed tasks with static local declarations, recursive calls and `ref` arguments remain unsupported. - Behavioral and verification constructs: `final`, intra-assignment timing controls (`a = #1 b`), delayed continuous assignments ([#444](https://github.com/celox-sim/celox/issues/444)), named events and `->`, `fork` / `join`, `wait fork` / `disable fork`, concurrent assertions, `force` / `release`. @@ -236,7 +236,17 @@ into the runtime. Reading or writing a property or calling a method through `null` is a runtime error. Constructing an abstract class and a class that leaves a pure virtual method unimplemented are rejected (8.21). A class that implements an interface class implements each of its methods with the same -return type, or, if it is abstract, re-declares it pure (8.26). +return type, or, if it is abstract, re-declares it pure (8.26). A method called +through a handle of an interface class runs the implementation of the object's +class. + +A handle may be assigned to a variable of its class, of a base class or of an +interface class it implements; any other assignment of a handle is an error +(IEEE 1800-2023 8.16, 8.26.5). `$cast(dest, source)` assigns a handle whose +object's class derives from or implements the class of `dest`, or `null`, and +returns 1; otherwise it leaves `dest` unchanged and returns 0, or, called as a +task, reports an error. A `$cast` between classes neither of which derives from +the other, unless the source is an interface class, always fails (8.16). A constructor calls the constructor of the base class first, with the arguments of `super.new(...)` or of the `extends` clause, then runs the diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 7667500252d..64a81f84068 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -28,7 +28,7 @@ outline: [2, 3] | 式 | `**` を含む算術、論理、シフト、比較、リダクション、連結・複製、`?:`、`inside`、`==?` / `!=?`、キャスト(`N'(x)`、`signed'(x)`、`T'(x)`)、`$signed` / `$unsigned` | | 選択 | 定数・実行時のビット選択と indexed part-select(`[i]`、`[i +: W]`、`[i -: W]`)。読み書きの両方、宣言の向きによらず | | パターン | packed 構造体・packed 配列・unpacked 配列の assignment pattern(`'{a, b}`、`'{x: a, default: 0}`、`'{n{a}}`、`T'{...}`) | -| クラス | モジュール内で宣言したクラス。64 ビット以下の 2 値整数型・`string`・クラスハンドル型のプロパティ(初期値つきも可)、引数あり・なしの `new`、暗黙と明示のコンストラクタ、ハンドル経由またはクラス内から修飾なしで呼ぶメソッド(`function` と `task`、本体をクラス外に書く `extern` も可)、`this`、`null`、ハンドルの代入と比較、プロパティとメソッドの継承(基底クラスのコンストラクタは `super.new(...)` か `extends Base(...)` で呼ぶ)、`super.` によるメンバ参照、virtual メソッド、抽象クラス(`virtual class`)と pure virtual メソッド、interface クラスを実装するクラス、static プロパティとメソッド、static メンバと `C::new` の `C::` によるスコープ解決、ハンドルの配列。[クラス](#classes)を参照 | +| クラス | モジュール内で宣言したクラス。64 ビット以下の 2 値整数型・`string`・クラスハンドル型のプロパティ(初期値つきも可)、引数あり・なしの `new`、暗黙と明示のコンストラクタ、ハンドル経由またはクラス内から修飾なしで呼ぶメソッド(`function` と `task`、本体をクラス外に書く `extern` も可)、`this`、`null`、ハンドルの代入と比較、プロパティとメソッドの継承(基底クラスのコンストラクタは `super.new(...)` か `extends Base(...)` で呼ぶ)、`super.` によるメンバ参照、virtual メソッド、抽象クラス(`virtual class`)と pure virtual メソッド、interface クラスを実装するクラスと interface クラスのハンドルを通したメソッド呼び出し、関数とタスクとしてのクラスハンドルの `$cast`、static プロパティとメソッド、static メンバと `C::new` の `C::` によるスコープ解決、ハンドルの配列。[クラス](#classes)を参照 | | 文字列 | `string` 型の変数、関数の引数と戻り値。文字列・文字列リテラル・キャスト(`string'(x)`)の代入、`==` / `!=` と大小比較、連結と複製(実行時の回数も可)、文字の読み書き(`s[i]`)、メソッド `len`、`getc`、`putc`、`toupper`、`tolower`、`compare`、`icompare`、`substr`、`atoi` / `atohex` / `atooct` / `atobin`、`itoa` / `hextoa` / `octtoa` / `bintoa`。`%s` と書式なしの表示。[文字列](#strings)を参照 | | パラメータ | 整数のパラメータ、128ビットを超える幅と X/Z を保持するパラメータ上書き、assignment pattern で与える unpacked 配列型・packed 構造体型のパラメータ(定数テーブル)と unpacked 配列のパターンによる上書き | @@ -118,7 +118,7 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 その構文を追跡する issue の番号が含まれます。専用の issue がない構文は、フロントエンドの ロードマップ [#88](https://github.com/celox-sim/celox/issues/88) を指します。 -- [対応範囲](#classes)外のクラスの機能:interface クラスのハンドルを通したメソッド呼び出し、`$cast`、package 内で宣言したクラス、パラメータ付きクラス、名前付きのコンストラクタ引数、浅いコピー(`new h`)、4 値・`real`・配列・64 ビットを超えるプロパティ。時間待ちを含む task の static ローカル宣言、再帰呼び出し、`ref` 引数。 +- [対応範囲](#classes)外のクラスの機能:クラスハンドル以外の変数への `$cast`、interface クラスの typedef とパラメータ、package 内で宣言したクラス、パラメータ付きクラス、名前付きのコンストラクタ引数、浅いコピー(`new h`)、4 値・`real`・配列・64 ビットを超えるプロパティ。時間待ちを含む task の static ローカル宣言、再帰呼び出し、`ref` 引数。 - interface のポート、`inout` / `ref` / 式を使う modport、virtual interface など。 interface 自体と入れ子の interface は対応しています。型パラメータはインスタンスごとに解決し、modport ポート経由でも伝搬します。 再帰する特殊化と64段を超える入れ子は拒否します。細かな制約は[英語版の一覧](/guide/systemverilog-reference#interface-restrictions)を参照してください。 @@ -167,7 +167,9 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 ### クラス {#classes} -クラス型の変数はシミュレータのヒープ上のオブジェクトへのハンドルを持ち、コンストラクタを呼ぶまでは `null` です。文字列と同じく、ハンドルのコピーと比較は 32 ビット整数と同じコストで、プロパティの読み書きとオブジェクトの生成だけがランタイムを呼び出します。どの変数・オブジェクトからも参照されないオブジェクトは、タイムスロットの間と各 `tick` の後に回収されます。メソッドは呼び出したオブジェクトを受け取るので function でも task でもよく、呼び出しは変数のクラスのメソッドに結び付きます(IEEE 1800-2023 8.6)。virtual メソッドの呼び出しは、代わりにオブジェクトのクラスの override を実行します。ただし `super.m(...)` は基底クラスの実装を実行します(8.15、8.20)。override はオブジェクトのクラスで選ぶので、ランタイムの呼び出しが 1 回増えます。`null` を通したプロパティの読み書きやメソッド呼び出しは実行時エラーです。抽象クラスの生成と、pure virtual メソッドを実装しないクラスはエラーになります(8.21)。interface クラスを実装するクラスは、そのメソッドをすべて同じ戻り値型で実装するか、抽象クラスなら pure として宣言し直します(8.26)。 +クラス型の変数はシミュレータのヒープ上のオブジェクトへのハンドルを持ち、コンストラクタを呼ぶまでは `null` です。文字列と同じく、ハンドルのコピーと比較は 32 ビット整数と同じコストで、プロパティの読み書きとオブジェクトの生成だけがランタイムを呼び出します。どの変数・オブジェクトからも参照されないオブジェクトは、タイムスロットの間と各 `tick` の後に回収されます。メソッドは呼び出したオブジェクトを受け取るので function でも task でもよく、呼び出しは変数のクラスのメソッドに結び付きます(IEEE 1800-2023 8.6)。virtual メソッドの呼び出しは、代わりにオブジェクトのクラスの override を実行します。ただし `super.m(...)` は基底クラスの実装を実行します(8.15、8.20)。override はオブジェクトのクラスで選ぶので、ランタイムの呼び出しが 1 回増えます。`null` を通したプロパティの読み書きやメソッド呼び出しは実行時エラーです。抽象クラスの生成と、pure virtual メソッドを実装しないクラスはエラーになります(8.21)。interface クラスを実装するクラスは、そのメソッドをすべて同じ戻り値型で実装するか、抽象クラスなら pure として宣言し直します(8.26)。interface クラスのハンドルを通して呼んだメソッドは、オブジェクトのクラスの実装を実行します。 + +ハンドルは、そのクラス・基底クラス・実装する interface クラスの変数に代入でき、それ以外のハンドルの代入はエラーです(IEEE 1800-2023 8.16、8.26.5)。`$cast(dest, source)` は、オブジェクトのクラスが `dest` のクラスを継承または実装するハンドルか `null` を代入して 1 を返します。それ以外では `dest` を変えずに 0 を返し、タスクとして呼んだ場合はエラーを報告します。どちらも他方を継承しないクラスどうしの `$cast` は、ソースが interface クラスでない限り常に失敗します(8.16)。 コンストラクタは、まず `super.new(...)` または `extends` 節の引数で基底クラスのコンストラクタを呼び、次に自クラスが宣言するプロパティの初期値を設定し、最後に本体を実行します(IEEE 1800-2023 8.17)。static プロパティはクラスを宣言したモジュールの変数なので、モジュールのインスタンスごとに 1 つずつあります。 From 3ade32a4c902da277229329f7a65d5ab0f94d577 Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 23 Oct 2026 06:48:54 +0900 Subject: [PATCH 2/2] feat(sim)!: make a tick one clock period and run every clock generator `Simulator::tick` was the event's active edge only, with the signal left unchanged, so domains of the opposite edge and clocks derived from it never ran on a tick. A tick is now one clock period of the event's signal, the SystemVerilog `s <= A; #H; s <= I; #L;`: the active edge, then the inactive edge, running every domain sensitive to either and leaving the signal at its inactive level. A signal already at the active level takes no active edge. `tick_events` makes the edges of several events together, the N-API and WASM ticks follow the same definition, and `Simulator::cycle`, which did this already, is removed. `$tb::clock_gen` instances in Veryl testbenches now run from time 0 whether or not a process waits on them, as the generated SystemVerilog does. Before, a clock advanced only while some process was in its `next()`. `next(n)` runs n periods of the clock. The new execution semantics guide describes the host API as a whole. BREAKING CHANGE: `Simulator::tick` and `tick_events` also take the inactive edge, so domains of the opposite edge now run and the event's signal ends at its inactive level. A negative-edge clock that starts at 0 takes no edge on its first tick. `Simulator::cycle` is removed; use `Simulator::tick`. Every `$tb::clock_gen` in a Veryl testbench runs all the time, so counters on clocks other than the one being waited on keep counting. Change-Id: I90587af4533d71983b1b43a06fde072de10446a8 --- crates/celox-frontend-veryl/src/schedule.rs | 5 + crates/celox-frontend-veryl/src/testbench.rs | 18 +- crates/celox-napi/src/lib.rs | 38 ++- crates/celox-runtime/src/derived_tick.rs | 12 +- crates/celox-runtime/src/edge.rs | 52 ++++ crates/celox-runtime/src/lib.rs | 2 +- crates/celox-runtime/src/testbench.rs | 17 +- crates/celox-testbench/src/lib.rs | 35 +++ crates/celox/benches/overhead.rs | 17 -- crates/celox/src/lib.rs | 2 +- crates/celox/src/simulation.rs | 30 +-- crates/celox/src/simulator.rs | 229 +++++++++++------- crates/celox/src/testbench.rs | 103 +++++--- crates/celox/tests/both_clock_edges.rs | 5 +- crates/celox/tests/clock_gen_semantics.rs | 149 ++++++++++++ crates/celox/tests/component_method.rs | 4 +- crates/celox/tests/derived_register_clock.rs | 8 +- crates/celox/tests/edge_api.rs | 29 +-- .../celox/tests/four_state_explicit_edges.rs | 6 +- .../systemverilog/review_regressions.rs | 5 + crates/celox/tests/native_testbench.rs | 10 +- crates/celox/tests/tick_semantics.rs | 220 +++++++++++++++++ docs/.vitepress/config.mts | 5 + docs/guide/execution-semantics.md | 107 ++++++++ docs/guide/writing-tests.md | 21 +- docs/internals/cascade-limitations.md | 36 ++- docs/ja/guide/execution-semantics.md | 108 +++++++++ docs/ja/guide/writing-tests.md | 2 +- .../celox/src/simulator-edges-addon.test.ts | 7 +- packages/celox/src/simulator.ts | 14 +- packages/celox/src/wasm-bridge.ts | 4 +- packages/celox/src/wasm-edges.test.ts | 14 +- packages/celox/src/wasm-edges.ts | 29 +-- .../playground/src/playground-simulator.ts | 7 +- .../playground/test/playground-dts.test.ts | 2 +- .../test/playground-simulator-wasm.test.ts | 20 +- 36 files changed, 1080 insertions(+), 292 deletions(-) create mode 100644 crates/celox/tests/clock_gen_semantics.rs create mode 100644 crates/celox/tests/tick_semantics.rs create mode 100644 docs/guide/execution-semantics.md create mode 100644 docs/ja/guide/execution-semantics.md diff --git a/crates/celox-frontend-veryl/src/schedule.rs b/crates/celox-frontend-veryl/src/schedule.rs index 0fdb7d44517..1e731abac03 100644 --- a/crates/celox-frontend-veryl/src/schedule.rs +++ b/crates/celox-frontend-veryl/src/schedule.rs @@ -238,6 +238,8 @@ pub fn schedule_symbolic_rtl( }) } +/// The period of every `$tb::clock_gen` instance of `module`. +/// /// Veryl 0.22 keeps clock configuration on instance symbols, but only copies it /// into ClockNext IR. Recover it while the analyzer symbols are still available, /// using the specialization's overrides rather than a parameter's default. @@ -262,11 +264,14 @@ fn configured_clock_periods( let SymbolKind::Instance(instance) = &symbol.found.kind else { continue; }; + // A clock variable declared by an instance is a `$tb::clock_gen`; + // without a `period` it has the default period. let Some((_, target)) = instance .parameter_connects .iter() .find(|(name, _)| name.text.to_string() == "period") else { + periods.insert(symbol.found.token.text, 2); continue; }; let context = context.get_or_insert_with(|| { diff --git a/crates/celox-frontend-veryl/src/testbench.rs b/crates/celox-frontend-veryl/src/testbench.rs index 3f90788ba56..3ed5e6c4d11 100644 --- a/crates/celox-frontend-veryl/src/testbench.rs +++ b/crates/celox-frontend-veryl/src/testbench.rs @@ -6,7 +6,7 @@ use celox_testbench::{ AssertMessage as GenericAssertMessage, ClockCount as GenericClockCount, ExprBytecode, ExprOpcode as TbOpcode, LoopBound as GenericLoopBound, SemanticArgument, SemanticComponentBinding, SemanticSignal, SemanticStatement, SourceLocation, StateLocation, - TestbenchOperator as Op, TestbenchProgram, TestbenchSelection, + TestbenchClock, TestbenchOperator as Op, TestbenchProgram, TestbenchSelection, TestbenchStatement as GenericTestbenchStatement, TestbenchTarget, }; use fxhash::{FxHashMap as HashMap, FxHashSet}; @@ -2568,6 +2568,17 @@ impl<'a> SemanticTestbenchBuilder<'a> { } } + /// The `$tb::clock_gen` instances of this source's module. + fn clock_generators(&self) -> impl Iterator> + '_ { + self.testbench_source + .clock_periods + .iter() + .filter_map(|(&name, &period)| { + let (event, _) = self.named_variable(name)?; + Some(TestbenchClock { event, period }) + }) + } + fn named_variable(&self, name: StrId) -> Option<(StateAddr, &VariableInfo)> { let instance = self.testbench_source.base_instance(self.lookup); let module = self.lookup.instance_module.get(&instance)?; @@ -3852,6 +3863,7 @@ pub fn compile_semantic_testbench( .sum(); let mut site_end = runtime_event_site_count.saturating_sub(total_sites); let mut processes = Vec::new(); + let mut clocks = Vec::new(); for source in sources { let initial_stmts = source.initial_statements.as_ref().unwrap(); validate_testbench_statements(initial_stmts, lookup, source, &mut FxHashSet::default())?; @@ -3859,12 +3871,16 @@ pub fn compile_semantic_testbench( let mut builder = SemanticTestbenchBuilder::new(lookup, source, site_end); builder.prepared_readmem = super::readmem::prepare_testbench_memories(lookup, source)?; builder.build_event_map(initial_stmts); + clocks.extend(builder.clock_generators()); processes.extend(builder.convert(initial_stmts)); } + clocks.sort_unstable_by_key(|clock: &TestbenchClock| clock.event); + clocks.dedup_by_key(|clock| clock.event); let builder = SemanticTestbenchBuilder::new(lookup, source, runtime_event_site_count); let component_bindings = builder.convert_component_bindings()?; Ok(Some( TestbenchProgram::from_processes(processes) + .with_clocks(clocks) .with_private_variables(private_variables) .with_random_seed_option(random_seed) .with_components(source.components.clone()) diff --git a/crates/celox-napi/src/lib.rs b/crates/celox-napi/src/lib.rs index ddc686da9fd..af000d0e460 100644 --- a/crates/celox-napi/src/lib.rs +++ b/crates/celox-napi/src/lib.rs @@ -918,36 +918,46 @@ enum HandleDerivedTicks { #[cfg(not(target_arch = "wasm32"))] impl HandleBackend { - /// Tick an event as `Simulator::tick` does: settle, run its domain, - /// settle, and run the derived clock domains the tick reaches. + /// Tick an event as `Simulator::tick` does: a pulse of its signal to + /// the active level, running every domain sensitive to its edges. fn tick( &mut self, event_id: usize, derived: &HandleDerivedTicks, + event_edges: &celox::EventEdges, scratch: &mut celox::DerivedTickScratch, ) -> std::result::Result<(), celox::RuntimeErrorCode> { fn tick_with( backend: &mut B, event_id: usize, plans: &celox::DerivedTickPlans, + event_edges: &celox::EventEdges, scratch: &mut celox::DerivedTickScratch, ) -> std::result::Result<(), celox::RuntimeErrorCode> { let event = backend.id_to_event_slice()[event_id]; - match plans.get(event_id) { - Some(Some(plan)) => plan.tick(&mut celox::BackendExecutor(backend), scratch, true), - _ => { - backend.eval_comb()?; - backend.eval_apply_ff_at(event)?; - backend.eval_comb() - } + let plan = plans.get(event_id).and_then(Option::as_ref); + match celox::run_tick( + &mut celox::BackendExecutor(backend), + plan, + event_edges[event_id], + scratch, + event, + true, + celox::set_level, + ) { + Ok(()) => Ok(()), + // A bare backend reports no `$finish` or `$stop`; what ran + // settles here. + Err(celox::Halt::Finish | celox::Halt::Stop) => backend.eval_comb(), + Err(celox::Halt::Error(error)) => Err(error), } } match (self, derived) { (Self::Default(backend), HandleDerivedTicks::Default(plans)) => { - tick_with(backend, event_id, plans, scratch) + tick_with(backend, event_id, plans, event_edges, scratch) } (Self::Tiered(backend), HandleDerivedTicks::Tiered(plans)) => { - tick_with(backend.as_mut(), event_id, plans, scratch) + tick_with(backend.as_mut(), event_id, plans, event_edges, scratch) } _ => unreachable!("derived tick plans belong to the handle's backend"), } @@ -1544,6 +1554,7 @@ impl NativeSimulatorHandle { b.tick( event_id as usize, &self.derived_ticks, + &self.event_edges, &mut self.derived_scratch, ) .map_err(|e| napi_runtime_error(&runtime_errors, e)) @@ -1620,6 +1631,7 @@ impl NativeSimulatorHandle { b.tick( event_id as usize, &self.derived_ticks, + &self.event_edges, &mut self.derived_scratch, ) .map_err(|e| napi_runtime_error(&runtime_errors, e))?; @@ -3958,9 +3970,13 @@ mod tests { #[test] fn native_handle_dumps_consume_activity_until_memory_is_exposed() { + // A tick writes `clk` as well as `q`. The wide inputs keep those two + // trace groups below half of the design, where a dump scans every + // signal. let source = "module Top ( clk: input clock, q: output logic<64>, a: input logic<512>, b: input logic<512>, c: input logic<512>, + d: input logic<512>, e: input logic<512>, ) { always_ff (clk) { q += 1; } }"; let dir = tempfile::tempdir().unwrap(); // Warm the uninstrumented cache first. A traced build must not reuse it. diff --git a/crates/celox-runtime/src/derived_tick.rs b/crates/celox-runtime/src/derived_tick.rs index 19b35c1d783..c619d1f0298 100644 --- a/crates/celox-runtime/src/derived_tick.rs +++ b/crates/celox-runtime/src/derived_tick.rs @@ -1,7 +1,7 @@ -//! Derived clock domains of an event-based tick. +//! Derived clock domains of an event-based edge. //! -//! A tick is one active edge of an event. Clocks derived from the event run -//! with the rules of the timed scheduler: +//! A plan runs the domains one edge of an event reaches. Clocks derived from +//! the event run with the rules of the timed scheduler: //! //! - A clock computed combinationally from the event's signal, such as //! `clk & enable`, changes at the same instant as the event. Its edge is @@ -17,9 +17,9 @@ //! commit raises while the clock is high is a further edge. Each domain //! fires at most once per phase. //! -//! A tick is the event's active edge only and does not change the event's -//! signal. Domains that react to the signal's opposite edge, such as one -//! clocked by `~clk` or by a falling `clk & en`, do not run on a tick. +//! A plan's [`DerivedTickPlan::tick`] is the event's active edge with its +//! signal left as it is; the edge APIs move the signal around it, and a +//! `Simulator::tick` takes the active edge and then the inactive one. //! //! What an event can reach is computed when the simulator is built //! ([`celox_design::EventTopology::derived_events`] and diff --git a/crates/celox-runtime/src/edge.rs b/crates/celox-runtime/src/edge.rs index 3d404e53dfe..1b971593394 100644 --- a/crates/celox-runtime/src/edge.rs +++ b/crates/celox-runtime/src/edge.rs @@ -42,6 +42,14 @@ impl Edge { Edge::Falling => 0, } } + + /// The other transition. + pub fn opposite(self) -> Edge { + match self { + Edge::Rising => Edge::Falling, + Edge::Falling => Edge::Rising, + } + } } /// What an edge needs to know about one event. @@ -346,3 +354,47 @@ where moved_only(comb_read) }) } + +/// One tick of `event`: a clock period of its signal, defined as the +/// SystemVerilog statements +/// +/// ```systemverilog +/// s <= A; #H; +/// s <= I; #L; +/// ``` +/// +/// where `A` and `I` are the event's active and inactive levels: the active +/// edge, then the inactive edge, each running every domain sensitive to it. +/// Combinational logic is settled afterwards. `dirty` says whether it has +/// pending changes; `write` moves the signal. +#[allow(clippy::too_many_arguments)] +pub fn run_tick( + executor: &mut X, + plan: Option<&DerivedTickPlan>, + info: EventEdge, + scratch: &mut DerivedTickScratch, + event: E, + dirty: bool, + mut write: impl FnMut(&mut X::Backend, SignalRef, u8), +) -> Result<(), Halt> +where + X: TickExecutor, + X::Backend: SimBackend, + E: EventHandle, +{ + let active = info.active_edge(); + let mut dirty = dirty; + for edge in [active, active.opposite()] { + dirty = match run_edge( + executor, plan, info, scratch, event, edge, dirty, &mut write, + )? { + EdgeOutcome::Unchanged | EdgeOutcome::Stored => dirty, + EdgeOutcome::Moved => true, + EdgeOutcome::Settled => false, + }; + } + if dirty { + executor.eval_comb()?; + } + Ok(()) +} diff --git a/crates/celox-runtime/src/lib.rs b/crates/celox-runtime/src/lib.rs index f0c637d01e0..ecffa23e4b5 100644 --- a/crates/celox-runtime/src/lib.rs +++ b/crates/celox-runtime/src/lib.rs @@ -25,7 +25,7 @@ pub use derived_tick::{ }; pub use edge::{ Edge, EdgeOutcome, EventEdge, EventEdges, SignalWrite, build_event_edges, move_signal, - run_edge, run_edges, set_level, + run_edge, run_edges, run_tick, set_level, }; pub use error::{SimulatorErrorCode, comb_fatal_code, comb_fatal_site}; pub use event_buffer::RuntimeEventBuffer; diff --git a/crates/celox-runtime/src/testbench.rs b/crates/celox-runtime/src/testbench.rs index 92a8753bc0e..620a9f9049b 100644 --- a/crates/celox-runtime/src/testbench.rs +++ b/crates/celox-runtime/src/testbench.rs @@ -3,8 +3,9 @@ use celox_testbench::{ AssertMessage as GenericAssertMessage, ClockCount as GenericClockCount, CompiledExpr, ExecutableArgument, ExecutableAssertMessage, ExecutableClockCount, ExecutableLoopBound, ExecutableStatement, ExecutableTestbench, ExprBytecode, LoopBound as GenericLoopBound, - SemanticArgument, SemanticComponentBinding, SemanticStatement, StateLocation, TestbenchProgram, - TestbenchSelection, TestbenchStatement as GenericTestbenchStatement, TestbenchTarget, + SemanticArgument, SemanticComponentBinding, SemanticStatement, StateLocation, TestbenchClock, + TestbenchProgram, TestbenchSelection, TestbenchStatement as GenericTestbenchStatement, + TestbenchTarget, }; use crate::{SignalRef, backend::SimBackend}; @@ -389,6 +390,17 @@ pub fn bind_testbench_program( } } let random_seed = program.configured_random_seed(); + // A clock generator without an event drives no domain. + let clocks = program + .clocks() + .iter() + .filter_map(|clock| { + Some(TestbenchClock { + event: backend.resolve_event_opt(&clock.event)?, + period: clock.period, + }) + }) + .collect(); let components = program.components().to_vec(); let component_libraries = program.component_libraries().to_vec(); let component_file_base = program.component_file_base().map(ToOwned::to_owned); @@ -410,6 +422,7 @@ pub fn bind_testbench_program( .collect(); Some( ExecutableTestbench::from_processes(processes, random_seed) + .with_clocks(clocks) .with_private_signals(private_signals) .with_component_runtime( components, diff --git a/crates/celox-testbench/src/lib.rs b/crates/celox-testbench/src/lib.rs index 24217b7e149..b5f5a840fa3 100644 --- a/crates/celox-testbench/src/lib.rs +++ b/crates/celox-testbench/src/lib.rs @@ -271,10 +271,21 @@ pub type SemanticStatement = TestbenchStatement< pub type SemanticComponentBinding = ComponentBinding, ExprBytecode>>; +/// A `$tb::clock_gen` instance: a clock that runs from time 0, rising at +/// multiples of `period` and falling `ceil(period / 2)` after each rise, +/// whether or not a process waits on it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct TestbenchClock { + pub event: Event, + /// At least two. + pub period: u64, +} + #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct TestbenchProgram { statements: Vec>, process_lengths: Vec, + clocks: Vec>, private_variables: Vec, random_seed: Option, components: Vec, @@ -288,6 +299,7 @@ impl Default for TestbenchProgram { Self { statements: Vec::new(), process_lengths: Vec::new(), + clocks: Vec::new(), private_variables: Vec::new(), random_seed: None, components: Vec::new(), @@ -302,6 +314,7 @@ impl TestbenchProgram { pub fn new(statements: Vec>) -> Self { Self { process_lengths: vec![statements.len()], + clocks: Vec::new(), private_variables: Vec::new(), statements, random_seed: None, @@ -320,6 +333,16 @@ impl TestbenchProgram { program } + /// The clock generators of the testbench. + pub fn with_clocks(mut self, clocks: Vec>) -> Self { + self.clocks = clocks; + self + } + + pub fn clocks(&self) -> &[TestbenchClock] { + &self.clocks + } + /// Temporaries whose values belong to each independently suspended process. pub fn with_private_variables(mut self, variables: Vec) -> Self { self.private_variables = variables; @@ -578,6 +601,7 @@ pub type ExecutableComponentBinding = ComponentBinding { statements: Vec>, process_lengths: Vec, + clocks: Vec>, private_signals: Vec, random_seed: Option, components: Vec, @@ -597,6 +621,7 @@ impl ExecutableTestbench { ) -> Self { Self { process_lengths: vec![statements.len()], + clocks: Vec::new(), private_signals: Vec::new(), statements, random_seed, @@ -633,6 +658,16 @@ impl ExecutableTestbench { program } + /// The clock generators of the testbench. + pub fn with_clocks(mut self, clocks: Vec>) -> Self { + self.clocks = clocks; + self + } + + pub fn clocks(&self) -> &[TestbenchClock] { + &self.clocks + } + pub fn with_private_signals(mut self, signals: Vec) -> Self { self.private_signals = signals; self diff --git a/crates/celox/benches/overhead.rs b/crates/celox/benches/overhead.rs index 9bafc8fe723..0f6de57f77c 100644 --- a/crates/celox/benches/overhead.rs +++ b/crates/celox/benches/overhead.rs @@ -46,16 +46,6 @@ fn benchmark_simulation_overhead(c: &mut Criterion) { } }) }); - - // Explicit edges of the same clock: one cycle is a domain-running - // rising edge and a falling edge that only moves the signal. - c.bench_function("simulator_cycle_x10000", |b| { - b.iter(|| { - for _ in 0..10000 { - sim.cycle(clk).unwrap(); - } - }) - }); } // Benchmark 1b/1c: Simulator::tick with a derived clock domain: a gated @@ -93,13 +83,6 @@ fn benchmark_simulation_overhead(c: &mut Criterion) { } }) }); - c.bench_function(&format!("simulator_cycle_{name}{suffix}_x10000"), |b| { - b.iter(|| { - for _ in 0..10000 { - sim.cycle(clk).unwrap(); - } - }) - }); } } diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index e16d6ae2eb7..5f4e4a92a38 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -119,7 +119,7 @@ mod host_api { pub use celox_runtime::{ BackendExecutor, DerivedTickPlan, DerivedTickPlans, DerivedTickScratch, Edge, EdgeOutcome, EventEdge, EventEdges, Halt, SignalWrite, VcdSignalDesc, VcdStatistics, VcdWriter, - move_signal, run_edge, run_edges, set_level, + move_signal, run_edge, run_edges, run_tick, set_level, }; pub struct IOContext<'a, B: SimBackend = DefaultBackend> { diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 8eea263c394..30acc066cc3 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -1122,10 +1122,10 @@ mod process_tests { /// enable from before the edge (here a register of `clk`'s own domain) /// and its domain reads the state from before `clk`'s domain commits; an /// edge raising `en` raises the gate after the commit, a further edge - /// that reads the committed state. `~clk` rises when `clk` falls, which - /// the timed steps drive and a tick, the active edge only, does not. Timed steps and - /// event-based ticks agree on every backend, in both state modes; the - /// four-state ticks judge the gate by settling the design. + /// that reads the committed state. `~clk` rises when `clk` falls. Timed + /// steps and event-based ticks, one clock period each, agree on every + /// backend, in both state modes; the four-state ticks judge the gate by + /// settling the design. #[test] fn gated_clocks_share_their_source_edge_on_every_backend() { const CODE: &str = "module Top (clk: input '_ clock, rst: input '_ reset_async_low, @@ -1209,22 +1209,12 @@ mod process_tests { .iter() .map(|&enable| { sim.modify(|io| io.set(en_in, enable)).unwrap(); - let clk_before = sim.get_four_state(sim.signal("clk")); sim.tick(clk).unwrap(); - let mut observed = observe(&mut sim); - assert_eq!( - sim.get_four_state(sim.signal("clk")), - clk_before, - "a tick leaves clk as it was" - ); - // A tick is not a falling edge of `clk`: `~clk` stays put. - observed[3] = 0; - observed + observe(&mut sim) }) .collect() } let want = expected(); - let want_ticked: Vec<_> = want.iter().map(|&[a, b, c, _]| [a, b, c, 0]).collect(); for four_state in [false, true] { let build = || { crate::Simulator::builder(CODE, "Top") @@ -1240,7 +1230,7 @@ mod process_tests { ); assert_eq!( ticked(build().build_interpreter().unwrap()), - want_ticked, + want, "{}", context("interp tick") ); @@ -1252,7 +1242,7 @@ mod process_tests { ); assert_eq!( ticked(build().build_cranelift().unwrap()), - want_ticked, + want, "{}", context("cranelift tick") ); @@ -1264,7 +1254,7 @@ mod process_tests { ); assert_eq!( ticked(build().build_wasm().unwrap()), - want_ticked, + want, "{}", context("wasm tick") ); @@ -1276,7 +1266,7 @@ mod process_tests { ); assert_eq!( ticked(build().build_tiered().unwrap()), - want_ticked, + want, "{}", context("tiered tick") ); @@ -1293,7 +1283,7 @@ mod process_tests { ); assert_eq!( ticked(build().build_native().unwrap()), - want_ticked, + want, "{}", context("native tick") ); diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index da45194afbd..524a7281730 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -1699,28 +1699,71 @@ mod host { .map_err(|e| self.decorate_runtime_error(e)) } - /// Manually triggers a clock or event to process sequential logic. + /// One clock period of an event's signal: its active edge, then its + /// inactive edge. /// - /// A tick is one active edge of the event. Clock domains derived from - /// it run as in the timed [`crate::Simulation`]: a clock computed - /// combinationally from the event's signal, such as `clk & enable`, - /// is judged from the state before the edge and its domain evaluates - /// together with the event's own; domains clocked from state the - /// tick changes, such as a register bit, a divider or a gate whose - /// enable the commit raises, run after the commit, transitively. + /// A tick is defined as the SystemVerilog statements /// - /// Only the active edge is ticked, and the event's signal is left - /// unchanged. Domains that react to the opposite edge of the event's - /// signal, such as one clocked by `~clk` or by a falling `clk & en`, - /// do not run; drive the signal's levels with the timed - /// [`crate::Simulation`] for them. + /// ```systemverilog + /// s <= A; #H; + /// s <= I; #L; + /// ``` + /// + /// on the event's signal `s`, where `A` is its active level (1 for a + /// positive-edge clock or an active-high reset, 0 otherwise) and `I` + /// the inactive one, with host operations taking place between + /// periods. Every domain sensitive to either edge runs, including + /// domains of the opposite edge and clocks derived from the signal, + /// and the signal ends at the inactive level. A signal already at the + /// active level takes no active edge. See the execution semantics + /// guide for the host API as a whole. pub fn tick(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { - let result = self.tick_unit(event); + if self.frozen { + return Ok(()); + } + let info = self.event_edges[event.id()]; + let active = info.active_edge(); + let inactive = active.opposite(); + let plain = !matches!(self.derived_ticks.get(event.id()), Some(Some(_))); + if !(plain && self.host_watch.is_empty() && !info.can_fire(inactive)) { + self.active_edge(event)?; + return self.inactive_edge(event); + } + // Everything is read before the domain runs: right after its + // kernel, loads of host tables can wait behind the kernel's + // stores (4 KiB aliasing), which made a period cost almost two + // domain runs. The inactive edge runs nothing and only stores. + let observers = !self.program.runtime_schema.comb_observers.is_empty(); + let moved = celox_runtime::move_signal( + &mut self.backend, + &info, + active, + celox_runtime::set_level, + ); + if let Some(old) = moved { + if info.comb_read { + self.dirty = true; + } + if info.fires(old, active) { + self.fire(event)?; + } + } + self.backend.set(info.signal, inactive.level()); + if info.comb_read || observers { + self.dirty = true; + } + Ok(()) + } + + /// Run the event's domain as its active edge does, with the signal + /// left as it is: the unit of the edge APIs. + fn fire(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + let result = self.fire_unit(event); self.heap_safepoint(); result.and(self.take_heap_fault()) } - fn tick_unit(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + fn fire_unit(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { if let Some(Some(_)) = self.derived_ticks.get(event.id()) { return self.tick_derived(event); } @@ -1787,7 +1830,7 @@ mod host { // store the level without reading it first. A load of // the signal right after the previous edge's kernel can // wait behind the kernel's stores (4 KiB aliasing), - // which made a cycle cost almost two ticks. + // which made a period cost almost two domain runs. self.backend.set(info.signal, edge.level()); if info.comb_read || !self.program.runtime_schema.comb_observers.is_empty() { self.dirty = true; @@ -1795,7 +1838,7 @@ mod host { return Ok(()); } // No derived domains: move the signal, then run the event's - // domain exactly as `tick` does. + // domain. let write = watched_write(&mut self.host_watch); let Some(old) = celox_runtime::move_signal(&mut self.backend, &info, edge, write) else { @@ -1805,7 +1848,7 @@ mod host { self.dirty = true; } if info.fires(old, edge) { - return self.tick(event); + return self.fire(event); } if !self.program.runtime_schema.comb_observers.is_empty() { self.dirty = true; @@ -1875,49 +1918,6 @@ mod host { self.edge(event, edge) } - /// One clock cycle: [`Self::active_edge`], then - /// [`Self::inactive_edge`]. - pub fn cycle(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { - if self.frozen { - return Ok(()); - } - let info = self.event_edges[event.id()]; - let active = info.active_edge(); - let inactive = match active { - celox_runtime::Edge::Rising => celox_runtime::Edge::Falling, - celox_runtime::Edge::Falling => celox_runtime::Edge::Rising, - }; - let plain = !matches!(self.derived_ticks.get(event.id()), Some(Some(_))); - if !(plain && self.host_watch.is_empty() && !info.can_fire(inactive)) { - self.active_edge(event)?; - return self.inactive_edge(event); - } - // Everything is read before the domain runs: right after its - // kernel, loads of host tables can wait behind the kernel's - // stores (4 KiB aliasing), which made a cycle cost almost two - // ticks. The inactive edge runs nothing and only stores. - let observers = !self.program.runtime_schema.comb_observers.is_empty(); - let moved = celox_runtime::move_signal( - &mut self.backend, - &info, - active, - celox_runtime::set_level, - ); - if let Some(old) = moved { - if info.comb_read { - self.dirty = true; - } - if info.fires(old, active) { - self.tick(event)?; - } - } - self.backend.set(info.signal, inactive.level()); - if info.comb_read || observers { - self.dirty = true; - } - Ok(()) - } - /// Move several event signals at one instant, as coincident edges: /// every domain sensitive to one of them evaluates against the state /// before the edges, then all of them commit, then the rounds of @@ -1955,8 +1955,8 @@ mod host { std::sync::Arc::clone(&self.derived_ticks) } - /// [`Self::tick`] of an event whose ticks can trigger derived domains, - /// kept out of line so that the plain tick stays small. + /// The domain run of an event whose edges can trigger derived + /// domains, kept out of line so that the plain run stays small. #[inline(never)] fn tick_derived(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { let plans = std::sync::Arc::clone(&self.derived_ticks); @@ -2014,23 +2014,80 @@ mod host { result } - /// Advance several events as one coincident edge. + /// Tick several events at once: [`Self::tick`] with the edges of all + /// their signals made together, /// - /// Every triggered domain samples the state settled before the edge, - /// then all of them update, then combinational logic settles once. - /// This is the behaviour of clocks that share an edge in hardware, - /// such as a divided clock and its source, which sequential - /// [`Self::tick`] calls cannot express: each of them would settle - /// the design between the domains. Events of the same domain are - /// applied once. A single event behaves like [`Self::tick`]. + /// ```systemverilog + /// s1 <= A1; ... sk <= Ak; #H; + /// s1 <= I1; ... sk <= Ik; #L; + /// ``` /// - /// Derived domains of the ticked events run as in [`Self::tick`]: - /// gated clocks with the ticked domains, state-derived ones after - /// all of them commit. + /// so every domain triggered by the coincident active edges samples + /// the state settled before them, then all of them update. This is + /// the behaviour of clocks that share an edge in hardware, such as a + /// divided clock and its source, which sequential [`Self::tick`] + /// calls cannot express: each of them would settle the design + /// between the domains. Events of the same domain are applied once. + /// A single event behaves like [`Self::tick`]. pub fn tick_events(&mut self, events: &[B::Event]) -> Result<(), RuntimeErrorCode> { - let result = self.tick_events_unit(events); + if self.frozen { + return Ok(()); + } + if let [event] = events { + return self.tick(*event); + } + let only_active_edges = self.host_watch.is_empty() + && events.iter().all(|event| { + let info = self.event_edges[event.id()]; + !matches!(self.derived_ticks.get(event.id()), Some(Some(_))) + && !info.can_fire(info.active_edge().opposite()) + }); + if !only_active_edges { + let moves = |edge: fn(celox_runtime::EventEdge) -> celox_runtime::Edge| { + events + .iter() + .map(|&event| (event, edge(self.event_edges[event.id()]))) + .collect::>() + }; + let active = moves(|info| info.active_edge()); + let inactive = moves(|info| info.active_edge().opposite()); + self.edges(&active)?; + return self.edges(&inactive); + } + // The inactive edges run nothing and only store. + let mut fired = Vec::with_capacity(events.len()); + for &event in events { + let info = self.event_edges[event.id()]; + let active = info.active_edge(); + if let Some(old) = celox_runtime::move_signal( + &mut self.backend, + &info, + active, + celox_runtime::set_level, + ) { + if info.comb_read { + self.dirty = true; + } + if info.fires(old, active) { + fired.push(event); + } + } + } + let result = self.tick_events_unit(&fired); self.heap_safepoint(); - result.and(self.take_heap_fault()) + result.and(self.take_heap_fault())?; + for &event in events { + let info = self.event_edges[event.id()]; + self.backend + .set(info.signal, info.active_edge().opposite().level()); + if info.comb_read { + self.dirty = true; + } + } + if !self.program.runtime_schema.comb_observers.is_empty() { + self.dirty = true; + } + Ok(()) } fn tick_events_unit(&mut self, events: &[B::Event]) -> Result<(), RuntimeErrorCode> { @@ -2073,11 +2130,11 @@ mod host { match domains.as_slice() { [] => { for event in unsplit { - self.tick(event)?; + self.fire(event)?; } return Ok(()); } - [(event, _, _)] => return self.tick(*event), + [(event, _, _)] => return self.fire(*event), _ => {} } let timing_enabled = self.diagnostics.tick_timing_every.is_some(); @@ -2122,7 +2179,7 @@ mod host { || matches!(self.derived_ticks.get(event.id()), Some(Some(_))) { // Derived domains need the settled state to see their edges. - return self.tick(event); + return self.fire(event); } if self.dirty { self.eval_comb_apply_ff_at_checked(event)?; @@ -2133,6 +2190,16 @@ mod host { Ok(()) } + /// Whether a period of `event`'s signal, a rise and a fall, runs only + /// the event's own domain, once: no domain reacts to the other edge + /// and no clock derives from the signal. + pub(crate) fn period_runs_only_own_domain(&self, event: B::Event) -> bool { + let info = self.event_edges[event.id()]; + !matches!(self.derived_ticks.get(event.id()), Some(Some(_))) + && !info.can_fire(info.active_edge().opposite()) + && self.host_watch.is_empty() + } + /// Advance a run of identical deferred-comb ticks. Native code may keep /// the loop inside the generated function, but must return after publishing /// a runtime event so host-side observation remains tick-accurate. @@ -2786,7 +2853,7 @@ mod host { sim.frozen = true; sim.posedge(clk).unwrap(); sim.edges(&[(clk, celox_runtime::Edge::Rising)]).unwrap(); - sim.cycle(clk).unwrap(); + sim.tick(clk).unwrap(); let clk_signal = sim.signal("clk"); assert_eq!(sim.get(clk_signal), BigUint::from(0u8)); assert_eq!(sim.get(count), BigUint::from(1u8)); @@ -2844,7 +2911,7 @@ mod host { // logic stale only when it reads `clk`. sim.negedge(clk).unwrap(); assert_eq!(sim.dirty, comb_read, "{seen}"); - sim.cycle(clk).unwrap(); + sim.tick(clk).unwrap(); assert_eq!(sim.dirty, comb_read, "{seen}"); let seen_signal = sim.signal("seen"); let expected = if comb_read { 0u8 } else { 1 }; diff --git a/crates/celox/src/testbench.rs b/crates/celox/src/testbench.rs index 037d4ad61ac..f1239aa8884 100644 --- a/crates/celox/src/testbench.rs +++ b/crates/celox/src/testbench.rs @@ -1685,29 +1685,42 @@ struct ProcessClock { // Clock generators start low even when the design uses four-state storage. // Otherwise X's nonzero payload can make the first scheduled 1 look like a // steady high to the edge detector, losing the first clock/reset cycle. +// Returns the clock events, declared generators first. fn initialize_process_clocks( sim: &mut Simulator, - statements: &[TestbenchStatement], -) { - for statement in statements { - match statement { - GenericTestbenchStatement::ClockNext { clock_event, .. } - | GenericTestbenchStatement::ResetAssert { clock_event, .. } => { - let signal = sim.backend.resolve_signal(&clock_event.addr()); - sim_set_u64(sim, signal, 0); - } - GenericTestbenchStatement::If { - then_block, - else_block, - .. - } => { - initialize_process_clocks(sim, then_block); - initialize_process_clocks(sim, else_block); - } - GenericTestbenchStatement::For { body, .. } => initialize_process_clocks(sim, body), - _ => {} + testbench: &CompiledTestbench, +) -> Vec { + fn referenced(statements: &[TestbenchStatement], clocks: &mut Vec) { + for statement in statements { + match statement { + GenericTestbenchStatement::ClockNext { clock_event, .. } + | GenericTestbenchStatement::ResetAssert { clock_event, .. } => { + clocks.push(*clock_event); + } + GenericTestbenchStatement::If { + then_block, + else_block, + .. + } => { + referenced::(then_block, clocks); + referenced::(else_block, clocks); + } + GenericTestbenchStatement::For { body, .. } => referenced::(body, clocks), + _ => {} + } + } + } + let mut clocks: Vec<_> = testbench.clocks().iter().map(|clock| clock.event).collect(); + referenced::(testbench.statements(), &mut clocks); + let mut unique: Vec = Vec::with_capacity(clocks.len()); + for event in clocks { + if unique.iter().all(|known| known.id() != event.id()) { + let signal = sim.backend.resolve_signal(&event.addr()); + sim_set_u64(sim, signal, 0); + unique.push(event); } } + unique } fn exec_testbench( @@ -1719,7 +1732,10 @@ fn exec_testbench( .processes() .filter(|block| !block.is_empty()) .collect(); - if blocks.len() <= 1 { + let clocks = initialize_process_clocks(sim, testbench); + // One process on one clock spends time only in that clock's periods, so + // stepping them in place is the whole schedule. + if blocks.is_empty() || (blocks.len() == 1 && clocks.len() <= 1) { return exec_detailed(sim, testbench.statements(), ctx); } // Suspended processes keep their temporaries outside state memory, so @@ -1736,7 +1752,6 @@ fn exec_processes( ctx: &mut DetailedExecContext, blocks: &[&[TestbenchStatement]], ) -> ExecResult { - initialize_process_clocks(sim, testbench.statements()); // The compiler's function slots are shared by inline call sites. Keep // only these temporaries private; design variables remain shared between // initial processes and all RTL. Capture masks as well as payloads. @@ -1755,7 +1770,18 @@ fn exec_processes( .zip(&waits) .map(|(block, wait)| Some(exec_process(&sim, &ctx, wait, &reset_edges, block))) .collect(); - let mut clocks: Vec> = Vec::new(); + // Every clock generator runs from time 0, whether or not a process + // waits on it. + let mut clocks: Vec> = testbench + .clocks() + .iter() + .map(|clock| ProcessClock { + event: clock.event, + period: clock.period.max(2), + next_edge: 0, + falling_edge: None, + }) + .collect(); // Capture the baseline before runnable processes drive reset. Reset // assertions are signal writes AND events at this timestamp, even if // their clock's next edge is still in the future. Rebasing after the @@ -1868,16 +1894,9 @@ fn exec_processes( } } } - let active = |event: B::Event| { - waits.iter().any(|wait| { - wait.borrow() - .as_ref() - .is_some_and(|wait| wait.remaining != 0 && wait.clock.id() == event.id()) - }) - }; let fired: Vec<_> = clocks .iter() - .filter(|clock| !draining && !stopped && clock.next_edge == now && active(clock.event)) + .filter(|clock| !draining && !stopped && clock.next_edge == now) .map(|clock| clock.event) .collect(); { @@ -1938,7 +1957,7 @@ fn exec_processes( } let next_edge = clocks .iter() - .filter(|clock| !ctx.borrow().at_tick_limit() && active(clock.event)) + .filter(|_| !ctx.borrow().at_tick_limit()) .map(|clock| clock.next_edge) .min(); let next_falling = clocks.iter().filter_map(|clock| clock.falling_edge).min(); @@ -2078,7 +2097,7 @@ fn exec_one_detailed( let (completed, result) = if sim.components.has_scheduled_components() { (1, tick_component_clock(sim, *clock_event, ctx.current_time)) } else { - let (completed, result) = sim.tick_deferred_comb_many(*clock_event, batch); + let (completed, result) = clock_periods(sim, *clock_event, batch); (completed, result.map_err(|error| error.to_string())) }; if completed == 0 || completed > batch { @@ -2146,7 +2165,7 @@ fn exec_one_detailed( ), ) } else { - let (completed, result) = sim.tick_deferred_comb_many(*clock_event, batch); + let (completed, result) = clock_periods(sim, *clock_event, batch); (completed, result.map_err(|error| error.to_string())) }; if completed == 0 || completed > batch { @@ -2397,6 +2416,24 @@ fn exec_one_detailed( } } +/// Run up to `count` periods of a testbench clock generator's signal, each a +/// rise followed by a fall, and return how many ran. A run that the event's +/// own domain alone reacts to fires that domain once per period with the +/// signal left low, which is all a period does then. +fn clock_periods( + sim: &mut Simulator, + event: B::Event, + count: u64, +) -> (u64, Result<(), crate::RuntimeErrorCode>) { + if sim.period_runs_only_own_domain(event) { + return sim.tick_deferred_comb_many(event, count); + } + let result = sim + .edge(event, celox_runtime::Edge::Rising) + .and_then(|()| sim.edge(event, celox_runtime::Edge::Falling)); + (1, result) +} + fn tick_component_reset( sim: &mut Simulator, reset_event: Option, diff --git a/crates/celox/tests/both_clock_edges.rs b/crates/celox/tests/both_clock_edges.rs index f662b5924fd..727892aea59 100644 --- a/crates/celox/tests/both_clock_edges.rs +++ b/crates/celox/tests/both_clock_edges.rs @@ -7,9 +7,8 @@ //! 9.4.2 defines, evaluating against the state before the edge (4.4.2, //! 10.4.2), and that the copy is invisible. //! -//! Event-based `Simulator` tests with explicit edges belong here too, once the -//! `Simulator` can drive a falling edge: a `tick` is the rising edge only and -//! does not run falling-edge domains. +//! The event-based `Simulator`, whose `tick` is a clock period, is covered by +//! `tick_semantics.rs`. #![cfg(feature = "systemverilog")] diff --git a/crates/celox/tests/clock_gen_semantics.rs b/crates/celox/tests/clock_gen_semantics.rs new file mode 100644 index 00000000000..4a8b0312081 --- /dev/null +++ b/crates/celox/tests/clock_gen_semantics.rs @@ -0,0 +1,149 @@ +//! `$tb::clock_gen` and `clk.next(n)` behave as the SystemVerilog the +//! execution semantics guide defines them by: every clock generator runs from +//! time 0, rising through a nonblocking assignment at multiples of its period +//! and falling half a period later, and `clk.next(n)` resumes a period after +//! the `n`-th rising edge it waits for. +//! +//! The expected values come from running that SystemVerilog under Icarus +//! Verilog 13.0 and Verilator 5.052, which agree: +//! +//! ```systemverilog +//! bit clk = 0, clk2 = 0; +//! initial forever begin clk <= 1; #2 clk <= 0; #2; end +//! initial forever begin clk2 <= 1; #3 clk2 <= 0; #3; end +//! task automatic clk_next(int unsigned k); +//! if (k != 0) begin repeat (k) @(posedge clk); #4; end +//! endtask +//! ``` + +use celox::Simulator; +use celox::TestResult; +use celox::testbench::{compile_initial_testbench, run_compiled_testbench_to_finish}; + +const COUNTERS: &str = r#" +module Cnt ( + i_clk: input clock , + i_x : input logic<8> , + o_p : output logic<8> , + o_q : output logic<8> , +) { + var p: logic<8>; + var q: logic<8>; + always_ff (i_clk) { + p = p + 8'd1; + q = i_x + 8'd1; + } + assign o_p = p; + assign o_q = q; +} + +module NegCnt ( + i_clk: input clock_negedge, + o_n : output logic<8> , +) { + var n: logic<8>; + always_ff (i_clk) { + n = n + 8'd1; + } + assign o_n = n; +} +"#; + +fn run(top: &str) -> TestResult { + let code = format!("{COUNTERS}\n{top}"); + let mut sim = Simulator::builder(&code, "Top").build().unwrap(); + let tb = compile_initial_testbench(&sim).unwrap(); + run_compiled_testbench_to_finish(&mut sim, &tb) +} + +/// One process on one clock: the falling edge runs negative-edge domains, +/// and a write between two waits reaches the next rising edge. +#[test] +fn one_process_takes_both_edges_of_each_period() { + let result = run(r#" +#[test(Top)] +module Top { + inst clk: $tb::clock_gen #(period: 4); + var x: logic<8>; + var p: logic<8>; + var q: logic<8>; + var n: logic<8>; + inst a: Cnt (i_clk: clk, i_x: x, o_p: p, o_q: q); + inst an: NegCnt (i_clk: clk, o_n: n); + initial { + x = 8'd5; + clk.next(1); + $assert(p == 8'd1 && q == 8'd6 && n == 8'd1 && clk == 1'b0, "t=4: p=%d q=%d n=%d clk=%b", p, q, n, clk); + x = 8'd7; + clk.next(2); + $assert(p == 8'd3 && q == 8'd8 && n == 8'd3 && clk == 1'b0, "t=12: p=%d q=%d n=%d clk=%b", p, q, n, clk); + clk.next(0); + $assert(p == 8'd3 && n == 8'd3, "next(0) waits for nothing: p=%d n=%d", p, n); + $finish(); + } +} +"#); + assert_eq!(result, TestResult::Pass); +} + +/// The same with a second process: concurrency changes nothing. +#[test] +fn a_second_process_changes_nothing() { + let result = run(r#" +#[test(Top)] +module Top { + inst clk: $tb::clock_gen #(period: 4); + var x: logic<8>; + var p: logic<8>; + var q: logic<8>; + var n: logic<8>; + inst a: Cnt (i_clk: clk, i_x: x, o_p: p, o_q: q); + inst an: NegCnt (i_clk: clk, o_n: n); + initial { + x = 8'd5; + clk.next(1); + $assert(p == 8'd1 && q == 8'd6 && n == 8'd1 && clk == 1'b0, "t=4: p=%d q=%d n=%d clk=%b", p, q, n, clk); + x = 8'd7; + clk.next(2); + $assert(p == 8'd3 && q == 8'd8 && n == 8'd3 && clk == 1'b0, "t=12: p=%d q=%d n=%d clk=%b", p, q, n, clk); + $finish(); + } + initial { + clk.next(1); + } +} +"#); + assert_eq!(result, TestResult::Pass); +} + +/// A clock no process waits on still runs: `clk2` rises at 0, 6 and 12, +/// and the process resuming at 12 runs before that edge. +#[test] +fn clocks_run_whether_or_not_a_process_waits() { + let result = run(r#" +#[test(Top)] +module Top { + inst clk: $tb::clock_gen #(period: 4); + inst clk2: $tb::clock_gen #(period: 6); + var x: logic<8>; + var y: logic<8>; + var p: logic<8>; + var q: logic<8>; + var p2: logic<8>; + var q2: logic<8>; + inst a: Cnt (i_clk: clk, i_x: x, o_p: p, o_q: q); + inst b: Cnt (i_clk: clk2, i_x: y, o_p: p2, o_q: q2); + initial { + x = 8'd5; + y = 8'd9; + clk.next(1); + $assert(p == 8'd1 && q == 8'd6 && p2 == 8'd1 && q2 == 8'd10, "t=4: p=%d q=%d p2=%d q2=%d", p, q, p2, q2); + x = 8'd7; + clk.next(2); + $assert(p == 8'd3 && q == 8'd8 && p2 == 8'd2 && q2 == 8'd10, "t=12: p=%d q=%d p2=%d q2=%d", p, q, p2, q2); + $finish(); + } +} +"#); + assert_eq!(result, TestResult::Pass); +} diff --git a/crates/celox/tests/component_method.rs b/crates/celox/tests/component_method.rs index f42f5b940ec..fb120b0d587 100644 --- a/crates/celox/tests/component_method.rs +++ b/crates/celox/tests/component_method.rs @@ -3016,7 +3016,9 @@ fn child_initial_resolves_its_component_method_instance() { var d: logic<8>; var q: logic<8>; inst component: $comp::celox_clocked #(STEP: 0) (clk, d, q); - initial { component.drive(8'h5a); $assert(q == 8'h5a); } + // `clk` runs whether or not a process waits on it, and its edges + // load `d` into `q`. + initial { component.drive(8'h5a); $assert(q == 8'h5a); d = 8'h5a; } } #[test(t)] module t { inst clk: $tb::clock_gen; diff --git a/crates/celox/tests/derived_register_clock.rs b/crates/celox/tests/derived_register_clock.rs index b7cf39ab08a..ff3d100695d 100644 --- a/crates/celox/tests/derived_register_clock.rs +++ b/crates/celox/tests/derived_register_clock.rs @@ -389,8 +389,8 @@ module Top ( } /// `~clk` rises when `clk` falls: the timed simulation, which drives both -/// levels of `clk`, runs its domain once per cycle, while a tick is the -/// active edge of `clk` only and does not run it. +/// levels of `clk`, runs its domain once per cycle, and so does a tick, one +/// period of `clk`. #[test] fn an_inverted_clock_runs_on_the_falling_edge_only() { let code = r#" @@ -425,9 +425,9 @@ module Top ( let mut sim = Simulator::builder(code, "Top").build().unwrap(); let (clk, rst, cnt2) = (sim.event("clk"), sim.signal("rst"), sim.signal("cnt2")); sim.modify(|io| io.set(rst, 1u8)).unwrap(); - for _ in 0..4 { + for cycle in 0..4u64 { sim.tick(clk).unwrap(); - assert_eq!(sim.get(cnt2), 0u8.into(), "a tick is not a falling edge"); + assert_eq!(sim.get(cnt2), (cycle + 1).into(), "tick {cycle}"); } } diff --git a/crates/celox/tests/edge_api.rs b/crates/celox/tests/edge_api.rs index 20ee1eca805..995f0d22ac0 100644 --- a/crates/celox/tests/edge_api.rs +++ b/crates/celox/tests/edge_api.rs @@ -1,12 +1,11 @@ //! Explicit edges: `posedge`, `negedge`, `active_edge`, `inactive_edge`, -//! `cycle` and coincident `edges`, on every backend. +//! `tick` and coincident `edges`, on every backend. use celox::{ClockType, Edge, SimBackend, Simulation, Simulator, SimulatorBuilder}; /// A simulator under test, independent of its backend. trait Probe { fn edge(&mut self, event: &str, edge: Edge); - fn cycle(&mut self, event: &str); fn active_edge(&mut self, event: &str); fn inactive_edge(&mut self, event: &str); fn tick(&mut self, event: &str); @@ -20,10 +19,6 @@ impl Probe for Simulator { let event = self.event(event); Simulator::edge(self, event, edge).unwrap(); } - fn cycle(&mut self, event: &str) { - let event = self.event(event); - Simulator::cycle(self, event).unwrap(); - } fn active_edge(&mut self, event: &str) { let event = self.event(event); Simulator::active_edge(self, event).unwrap(); @@ -134,12 +129,12 @@ fn edges_run_the_domains_of_their_direction() { sim.edge("clk", Edge::Falling); assert_eq!(counters(sim), [1, 1, 1], "{backend}: negedge"); sim.set("en", 0); - sim.cycle("clk"); + sim.tick("clk"); assert_eq!(counters(sim), [2, 2, 1], "{backend}: closed gate"); - // A tick is the active edge only and leaves the clock low. + sim.set("en", 1); sim.tick("clk"); - assert_eq!(counters(sim), [3, 2, 1], "{backend}: tick"); - assert_eq!(sim.get("clk"), 0, "{backend}: tick leaves clk"); + assert_eq!(counters(sim), [3, 3, 2], "{backend}: tick"); + assert_eq!(sim.get("clk"), 0, "{backend}: tick leaves clk low"); } } @@ -169,20 +164,20 @@ module Top (clk: input clock, rst: input reset_async_low, q: output logic<8>) { assert_eq!(sim.get("q"), 1, "{backend}: {clock_type:?} inactive"); sim.edge("clk", active); assert_eq!(sim.get("q"), 2, "{backend}: {clock_type:?} explicit"); - sim.cycle("clk"); + // A clock at its active level takes no active edge. + sim.tick("clk"); assert_eq!(sim.get("q"), 2, "{backend}: {clock_type:?} stays active"); - sim.edge("clk", inactive); - sim.cycle("clk"); - assert_eq!(sim.get("q"), 3, "{backend}: {clock_type:?} cycle"); + sim.tick("clk"); + assert_eq!(sim.get("q"), 3, "{backend}: {clock_type:?} tick"); } } } -/// `cycle` runs a clock cycle exactly as the timed simulation's two steps +/// `tick` runs a clock period exactly as the timed simulation's two steps /// do: gated clocks with pre-edge sampling, a gate the commit raises, `~clk` /// and a register divider of a divider. #[test] -fn a_cycle_matches_the_timed_simulation() { +fn a_tick_matches_the_timed_simulation() { const CODE: &str = r#" module Top ( clk: input '_ clock, @@ -238,7 +233,7 @@ module Top ( .iter() .map(|&enable| { sim.set("en_in", enable); - sim.cycle("clk"); + sim.tick("clk"); sim.get("observed") }) .collect(); diff --git a/crates/celox/tests/four_state_explicit_edges.rs b/crates/celox/tests/four_state_explicit_edges.rs index 7bb97553b85..3e873745114 100644 --- a/crates/celox/tests/four_state_explicit_edges.rs +++ b/crates/celox/tests/four_state_explicit_edges.rs @@ -70,8 +70,8 @@ fn check(mut sim: Simulator, backend: &str) { set(&mut sim, "clkn", X); edge(&mut sim, "clkn", Edge::Rising); assert_eq!(counts(&mut sim), [1, 1, 0, 0], "{backend}: inactive from x"); - sim.cycle(sim.event("clkp")).unwrap(); - assert_eq!(counts(&mut sim), [2, 1, 0, 0], "{backend}: cycle after x"); + sim.tick(sim.event("clkp")).unwrap(); + assert_eq!(counts(&mut sim), [2, 1, 0, 0], "{backend}: tick after x"); // A gated clock: `x & 1` -> `1 & 1` rises; `x & x` -> `1 & x` stays x. set(&mut sim, "en", ONE); @@ -103,7 +103,7 @@ fn check(mut sim: Simulator, backend: &str) { edge(&mut sim, "clkd", Edge::Rising); assert_eq!(counts(&mut sim)[3], 2, "{backend}: register x -> 1"); set(&mut sim, "d", ZERO); - sim.cycle(sim.event("clkd")).unwrap(); + sim.tick(sim.event("clkd")).unwrap(); assert_eq!(counts(&mut sim)[3], 2, "{backend}: register 1 -> 0"); // Coincident edges from x judge the gated clock from x too. diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index 1db1f427c34..9684113cba3 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -2048,16 +2048,21 @@ fn uses_the_first_always_ff_event_as_a_negedge_clock() { .build_cranelift() .unwrap(); let clk = sim.event("clk"); + let clk_signal = sim.signal("clk"); let rst = sim.signal("rst"); let d = sim.signal("d"); let q = sim.signal("q"); + // A tick from the active level takes no active edge, so the clock idles + // high. sim.modify(|io| { + io.set(clk_signal, 1u8); io.set(rst, 0u8); io.set(d, 1u8); }) .unwrap(); sim.tick(clk).unwrap(); assert_eq!(sim.get(q), 1u8.into()); + assert_eq!(sim.get(clk_signal), 1u8.into()); } #[test] diff --git a/crates/celox/tests/native_testbench.rs b/crates/celox/tests/native_testbench.rs index 7e09ff73e3d..a5df2eb8ac1 100644 --- a/crates/celox/tests/native_testbench.rs +++ b/crates/celox/tests/native_testbench.rs @@ -2290,15 +2290,17 @@ fn test_dual_clock() { clk_a, rst_a, clk_b, rst_b, cnt_a, cnt_b, ); + // Both clocks run throughout. `cnt_a` counts the 3 periods of + // `rst_b`'s assertion, then both count every period. initial { rst_a.assert(); rst_b.assert(); clk_a.next (10); - $assert (cnt_a == 32'd10); - $assert (cnt_b == 32'd0); + $assert (cnt_a == 32'd13); + $assert (cnt_b == 32'd10); clk_b.next (5); - $assert (cnt_a == 32'd10); - $assert (cnt_b == 32'd5); + $assert (cnt_a == 32'd18); + $assert (cnt_b == 32'd15); $finish (); } } diff --git a/crates/celox/tests/tick_semantics.rs b/crates/celox/tests/tick_semantics.rs new file mode 100644 index 00000000000..78ebf514fac --- /dev/null +++ b/crates/celox/tests/tick_semantics.rs @@ -0,0 +1,220 @@ +//! The event-based `Simulator` API behaves as the SystemVerilog the execution +//! semantics guide defines it by. Each host operation is rewritten into those +//! statements of an `initial` process, which the timed `Simulation` runs, and +//! both must observe the same values after every operation: +//! +//! - `set(x, v)` is `x = v;`, +//! - `edge(e, lvl)` is `s <= lvl;`, +//! - `tick(e)` is `s <= A; #H; s <= I; #L;`, +//! - `tick_events(e1..ek)` makes the moves of all their signals together, +//! +//! where `s` is the event's signal, `A` its active level and `I` its inactive +//! one. + +#![cfg(feature = "systemverilog")] + +use std::path::Path; + +use celox::{Edge, Simulation, Simulator}; + +const DUT: &str = r#" +`timescale 1ns/1ns +module Dut ( + input logic clk, + input logic clk2, + input logic en, + input logic rst_n, + output logic [7:0] p, + output logic [7:0] n, + output logic [7:0] g, + output logic [7:0] ng, + output logic [7:0] r, + output logic [7:0] c2, + output logic [7:0] s, + output logic lvl +); + logic gclk; + assign gclk = clk & en; + always_ff @(posedge clk) p <= p + 8'd1; + always_ff @(negedge clk) n <= n + 8'd1; + always_ff @(posedge gclk) g <= g + 8'd1; + always_ff @(negedge gclk) ng <= ng + 8'd1; + always_ff @(posedge clk or negedge rst_n) + if (!rst_n) r <= 8'd0; + else r <= r + 8'd1; + always_ff @(posedge clk2) c2 <= c2 + 8'd1; + always_ff @(posedge clk) s <= c2; + assign lvl = clk; +endmodule +"#; + +const OUTPUTS: [&str; 8] = ["p", "n", "g", "ng", "r", "c2", "s", "lvl"]; + +/// Event signals with their active levels. +const EVENTS: [(&str, u8); 3] = [("clk", 1), ("clk2", 1), ("rst_n", 0)]; + +#[derive(Clone, Copy, Debug)] +enum Op { + Set(&'static str, u8), + Edge(&'static str, u8), + Tick(&'static [&'static str]), +} + +fn active(name: &str) -> u8 { + EVENTS.iter().find(|(event, _)| *event == name).unwrap().1 +} + +/// The statements `op` stands for, with the half periods of a tick at 1. +fn statements(op: Op) -> String { + match op { + Op::Set(name, value) => format!("{name} = {value};"), + Op::Edge(name, level) => format!("{name} <= {level};"), + Op::Tick(names) => { + let moves = |level: fn(u8) -> u8| { + names + .iter() + .map(|name| format!("{name} <= {}; ", level(active(name)))) + .collect::() + }; + format!("{}#1; {}#1;", moves(|a| a), moves(|a| 1 - a)) + } + } +} + +/// The values of `OUTPUTS` after each operation, from the timed simulation of +/// the operations' statements. Operation `k` starts at time `4k + 1`. +fn reference(ops: &[Op]) -> Vec> { + let mut body = String::new(); + for (k, &op) in ops.iter().enumerate() { + body += &format!(" #({} - $time) {}\n", 4 * k + 1, statements(op)); + } + let top = format!( + r#" +`timescale 1ns/1ns +module Top; + logic clk, clk2, en, rst_n; + wire [7:0] p, n, g, ng, r, c2, s; + wire lvl; + Dut u ( + .clk, .clk2, .en, .rst_n, .p, .n, .g, .ng, .r, .c2, .s, .lvl + ); + initial begin +{body} end +endmodule +"# + ); + let mut sim = Simulation::from_sv_sources( + vec![(DUT, Path::new("dut.sv")), (&top, Path::new("top.sv"))], + "Top", + ) + .four_state(false) + .build() + .unwrap(); + (0..ops.len()) + .map(|k| { + sim.run_until(4 * k as u64 + 4).unwrap(); + OUTPUTS + .iter() + .map(|name| { + let signal = sim.signal(name); + sim.get(signal).try_into().unwrap() + }) + .collect() + }) + .collect() +} + +fn hosted(ops: &[Op]) -> Vec> { + let mut sim = Simulator::from_sv_sources(vec![(DUT, Path::new("dut.sv"))], "Dut") + .four_state(false) + .build() + .unwrap(); + ops.iter() + .map(|&op| { + match op { + Op::Set(name, value) => { + let signal = sim.signal(name); + sim.set(signal, value); + } + Op::Edge(name, level) => { + let event = sim.event(name); + let edge = if level == 1 { + Edge::Rising + } else { + Edge::Falling + }; + sim.edge(event, edge).unwrap(); + } + Op::Tick([name]) => { + let event = sim.event(name); + sim.tick(event).unwrap(); + } + Op::Tick(names) => { + let events: Vec<_> = names.iter().map(|name| sim.event(name)).collect(); + sim.tick_events(&events).unwrap(); + } + } + OUTPUTS + .iter() + .map(|name| { + let signal = sim.signal(name); + sim.get(signal).try_into().unwrap() + }) + .collect() + }) + .collect() +} + +fn check(ops: &[Op]) { + let expected = reference(ops); + let actual = hosted(ops); + for (k, (expected, actual)) in expected.iter().zip(&actual).enumerate() { + assert_eq!( + actual, expected, + "after {:?} (operation {k}), outputs {OUTPUTS:?}", + ops[k] + ); + } +} + +/// A tick runs the domains of both edges of its signal and of a clock gated +/// from it, and leaves the signal at its inactive level. +#[test] +fn a_tick_is_a_clock_period() { + check(&[ + Op::Edge("rst_n", 1), + Op::Set("en", 1), + Op::Tick(&["clk"]), + Op::Tick(&["clk"]), + Op::Set("en", 0), + Op::Tick(&["clk"]), + ]); +} + +/// A signal already at its active level takes no active edge: a tick of an +/// active-low reset that starts low only releases it. +#[test] +fn a_tick_from_the_active_level_takes_only_the_inactive_edge() { + check(&[ + Op::Tick(&["rst_n"]), + Op::Tick(&["clk"]), + Op::Edge("rst_n", 0), + Op::Tick(&["clk"]), + Op::Edge("rst_n", 1), + Op::Edge("clk", 1), + Op::Tick(&["clk"]), + Op::Tick(&["clk"]), + ]); +} + +/// Coincident ticks sample each other's values from before the edge. +#[test] +fn ticks_of_several_events_are_coincident() { + check(&[ + Op::Edge("rst_n", 1), + Op::Tick(&["clk2"]), + Op::Tick(&["clk", "clk2"]), + Op::Tick(&["clk", "clk2"]), + Op::Tick(&["clk"]), + ]); +} diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts index 26e70805d77..b58ca97ce20 100644 --- a/docs/.vitepress/config.mts +++ b/docs/.vitepress/config.mts @@ -66,6 +66,10 @@ export default defineConfig({ text: "テストの書き方", link: "/ja/guide/writing-tests", }, + { + text: "実行の意味論", + link: "/ja/guide/execution-semantics", + }, { text: "celox CLIとcocotb", link: "/ja/guide/cocotb", @@ -185,6 +189,7 @@ export default defineConfig({ text: "Testbenches", items: [ { text: "Writing Tests", link: "/guide/writing-tests" }, + { text: "Execution Semantics", link: "/guide/execution-semantics" }, { text: "Celox CLI and cocotb", link: "/guide/cocotb" }, { text: "4-State Simulation", link: "/guide/four-state" }, { text: "Parameter Overrides", link: "/guide/parameter-overrides" }, diff --git a/docs/guide/execution-semantics.md b/docs/guide/execution-semantics.md new file mode 100644 index 00000000000..5bd364cfb7e --- /dev/null +++ b/docs/guide/execution-semantics.md @@ -0,0 +1,107 @@ +# Execution Semantics + +The clock-driving operations of Celox are defined by SystemVerilog: each one +is equivalent to a fixed piece of SystemVerilog, and running that code on an +IEEE 1800 simulator observes the same values as Celox does. This page gives +that code for the event-based `Simulator` API and for the `$tb::clock_gen` +component of Veryl native testbenches. + +In the code below, `s` is the signal of an event (a clock or reset port), +`A` its active level and `I` its inactive one. `A` is 1 for a positive-edge +clock and an active-high reset, and 0 for a negative-edge clock and an +active-low reset. For Veryl's abstract `clock` type it follows the build's +clock type. + +## The `Simulator` API + +A sequence of host calls is the `initial` process of a wrapper module that +instantiates the design and drives its inputs, with each call replaced by: + +| Call | SystemVerilog | +|---|---| +| `set(x, v)`, `sim.dut.x = v` | `x = v; #1;` | +| `edge(e, Rising)`, `posedge(e)` | `s <= 1; #1;` | +| `edge(e, Falling)`, `negedge(e)` | `s <= 0; #1;` | +| `active_edge(e)` / `inactive_edge(e)` | `s <= A; #1;` / `s <= I; #1;` | +| `edges([(e1, l1), …])` | `s1 <= l1; …; #1;` | +| `tick(e)` | `s <= A; #H; s <= I; #L;` | +| `tick(e, n)` | `tick(e)` `n` times | +| `tick_events([e1, …, ek])` | `s1 <= A1; …; sk <= Ak; #H; s1 <= I1; …; sk <= Ik; #L;` | + +A read (`get`, `sim.dut.x`) returns the value at the point between two calls, +when the previous call's events have all settled. + +A `Simulator` has no simulation time: it rejects designs with delays, so the +lengths of the delays above are not observable. They only order the calls: +every call starts after the previous one has settled. + +Some consequences: + +- A tick is one clock period. Every domain sensitive to either edge runs: + the event's own domain on the active edge, domains of the opposite edge + (`@(negedge clk)`, a register clocked by `~clk`), and clocks computed from + the signal, such as `clk & en`, on whichever edge they see. The signal ends + at its inactive level. +- A signal already at its active level takes no active edge, as + `s <= A` changes nothing. A tick of a two-state active-low reset that starts + at 0 only releases it; assert a reset with `negedge(rst)` or + `active_edge(rst)`. +- Domains triggered by one edge sample the state from before it and update + together, as nonblocking assignments do. Coincident ticks of several clocks + (`tick_events`) sample each other's values from before their shared edge. +- In a four-state design an unknown level counts as either level: `x` to 1 is + a rising edge and `x` to 0 a falling one (IEEE 1800-2023 Table 9-2). + +`set` and writes through `sim.dut` must not move an event signal or a clock +computed from one: Celox runs domains only for the edge calls above. Drive +those signals with `edge`, `tick` and their variants. + +## Veryl native testbenches + +The initial blocks of a Veryl testbench are SystemVerilog `initial` +processes, and `$finish()` is `$finish`. + +### `$tb::clock_gen` + +`inst clk: $tb::clock_gen #(period: P);` is a clock generator that runs from +time 0, whether or not a process waits on it. `P` defaults to 2 and is at +least 2; with `H = ceil(P / 2)` and `L = floor(P / 2)`: + +```systemverilog +bit clk = 1'b0; +initial forever begin + clk <= 1'b1; #H; + clk <= 1'b0; #L; +end +``` + +### `clk.next(n)` + +```systemverilog +task automatic clk_next(int unsigned n); + if (n != 0) begin + repeat (n) @(posedge clk); + #P; + end +endtask +``` + +`clk.next()` is `clk.next(1)`. + +- The process resumes a period after the `n`-th rising edge it waits for, + just before the next one. It then observes the state after both edges of + that period: the clock is low, and negative-edge domains have run. +- The clock rises through a nonblocking assignment, after the processes that + resume at the same time have run. What a process writes between two + `next` calls is therefore sampled by the rising edge that follows, without + a race. +- Several initial processes, and several clocks of different periods, need no + further rule: they are concurrent SystemVerilog processes. A clock nobody + waits on keeps running and clocking its domains. + +A testbench statement that reads the design, such as `$assert` or an `if` +condition, sees combinational logic settled after the process's own writes. +SystemVerilog leaves such a read racy within one time step; Celox resolves it +this way. + +`rst.assert` of `$tb::reset_gen` is not defined by this page yet. diff --git a/docs/guide/writing-tests.md b/docs/guide/writing-tests.md index ea59203ad16..d82a68852e3 100644 --- a/docs/guide/writing-tests.md +++ b/docs/guide/writing-tests.md @@ -52,11 +52,12 @@ module Reg ( - `Simulator.create(Module)` creates a simulator instance from a Veryl module definition. - Signal values are read and written via `sim.dut.`. -- `sim.tick()` advances the simulation by one clock cycle. - Clock domains derived from that clock run in the same tick when their clock - rises: a gated `clk & en` together with `clk`'s own domain, a - register-driven divider after it. A tick is the clock's active edge only: - domains clocked by its opposite edge, such as `~clk`, do not run. +- `sim.tick()` advances the simulation by one clock period: the clock's + active edge, then its inactive edge. Every domain sensitive to either edge + runs, including clocks derived from it, such as a gated `clk & en`, a + register-driven divider or `~clk`. See + [Execution Semantics](./execution-semantics.md) for the SystemVerilog a + tick is equivalent to. - `sim.dispose()` frees the native resources. ::: tip Combinational logic @@ -65,9 +66,8 @@ For purely combinational modules (`always_comb` only), `tick()` is not required. ### Clock edges -`tick()` stands for a clock's active edge and leaves the clock signal alone. -When a design also reacts to the other edge, for example a register on `~clk` -or on a falling `clk & en`, drive the edges themselves: +`tick()` drives a whole clock period. To stop between the two edges, or to +drive a reset, move the signals edge by edge: ```typescript const clk = sim.event("clk"); @@ -76,7 +76,6 @@ sim.posedge(clk); // clk = 1: domains sensitive to its rising edge run sim.negedge(clk); // clk = 0: domains sensitive to its falling edge run sim.activeEdge(clk); // the clock's own edge: rising for a posedge clock sim.inactiveEdge(clk); // the opposite edge -sim.cycle(clk); // activeEdge(), then inactiveEdge() // Several clocks at one instant: every domain samples the state before them. sim.edges([ @@ -95,8 +94,8 @@ Veryl's abstract `clock` type, `activeEdge()` follows the build's clock type (`clockType: "negedge"` makes it the falling edge). Reset ports work the same way: `negedge(rst)` asserts an active-low asynchronous reset. -`cycle()` gives the same results as two timed steps of the clock, a rising -and a falling one. +`tick()` is `activeEdge()` followed by `inactiveEdge()`, and gives the same +results as two timed steps of the clock, a rising and a falling one. ## Time-Based Simulation diff --git a/docs/internals/cascade-limitations.md b/docs/internals/cascade-limitations.md index af32fc922d7..1c1913960f9 100644 --- a/docs/internals/cascade-limitations.md +++ b/docs/internals/cascade-limitations.md @@ -99,26 +99,22 @@ optimization and does not change the ordering model above. ## Event-based ticks -`Simulator::tick` applies the same rules to one active edge of an event. -Gated clocks of the event are judged from the state before the edge and -evaluate with the ticked domain; after the commit, the rounds above run the -domains whose clocks are computed from state and the gated clocks the commit -moves. `Simulator::tick_events` does -the same for coincident events, and the native testbench's `clock.next()` and -the N-API `tick` use the same mechanism. - -A tick is the event's active edge only, without simulation time, and does not -change the event's signal. Domains that react to the signal's opposite edge, -such as one clocked by `~clk` or by a falling edge of `clk & en`, do not run on -a tick; the timed `Simulation`, which drives both levels of a clock, runs them. - -`Simulator::posedge`, `negedge`, `active_edge`, `inactive_edge`, `cycle` and the -coincident `edges` move the signal instead and apply the same rules to the -transition they make, as a timed step does: the event's own domain runs on its -active edge, gated clocks of either polarity are judged at the transition, and -the signal stays at its new level. `cycle` is equivalent to the two timed -steps of one clock period. The N-API handles and the WASM bridge of the -TypeScript package use the same plans. +`Simulator::posedge`, `negedge`, `active_edge`, `inactive_edge` and the +coincident `edges` apply the same rules to the transition of an event signal +they make, as a timed step does: the event's own domain runs on its active +edge, gated clocks of either polarity are judged at the transition, and the +signal stays at its new level. Gated clocks are judged from the state before +the edge and evaluate with the event's own domain; after the commit, the +rounds above run the domains whose clocks are computed from state and the +gated clocks the commit moves. + +`Simulator::tick` is one clock period, the active edge followed by the +inactive edge, and is equivalent to the two timed steps of that period; +`Simulator::tick_events` does the same for coincident events, and the +native testbench's `clock.next()` takes the same two edges. The +[execution semantics](../guide/execution-semantics.md) define them by +SystemVerilog. The N-API handles and the WASM bridge of the TypeScript +package use the same plans. Which derived domains an event can reach is computed once when the design is built, together with a small program for each gate where its combinational diff --git a/docs/ja/guide/execution-semantics.md b/docs/ja/guide/execution-semantics.md new file mode 100644 index 00000000000..7feddbd5c51 --- /dev/null +++ b/docs/ja/guide/execution-semantics.md @@ -0,0 +1,108 @@ +# 実行の意味論 + +Celox のクロックを駆動する操作は SystemVerilog で定義されています。各操作は +決まった SystemVerilog のコードと等価で、そのコードを IEEE 1800 準拠の +シミュレータで実行すると Celox と同じ値が観測されます。このページでは、 +イベントベースの `Simulator` API と、Veryl ネイティブテストベンチの +`$tb::clock_gen` コンポーネントについて、そのコードを示します。 + +以下のコードで、`s` はイベント(クロックまたはリセットのポート)の信号、 +`A` はそのアクティブレベル、`I` は非アクティブレベルです。`A` は +立ち上がりエッジのクロックと active-high リセットで 1、立ち下がりエッジの +クロックと active-low リセットで 0 です。Veryl の抽象 `clock` 型では、 +ビルドのクロック種別に従います。 + +## `Simulator` API + +ホストの呼び出し列は、設計をインスタンス化して入力を駆動するラッパー +モジュールの `initial` プロセスであり、各呼び出しは次のコードに置き換わります。 + +| 呼び出し | SystemVerilog | +|---|---| +| `set(x, v)`、`sim.dut.x = v` | `x = v; #1;` | +| `edge(e, Rising)`、`posedge(e)` | `s <= 1; #1;` | +| `edge(e, Falling)`、`negedge(e)` | `s <= 0; #1;` | +| `active_edge(e)` / `inactive_edge(e)` | `s <= A; #1;` / `s <= I; #1;` | +| `edges([(e1, l1), …])` | `s1 <= l1; …; #1;` | +| `tick(e)` | `s <= A; #H; s <= I; #L;` | +| `tick(e, n)` | `tick(e)` を `n` 回 | +| `tick_events([e1, …, ek])` | `s1 <= A1; …; sk <= Ak; #H; s1 <= I1; …; sk <= Ik; #L;` | + +読み出し(`get`、`sim.dut.x`)は、呼び出しと呼び出しの間、直前の呼び出しの +イベントがすべて落ち着いた時点の値を返します。 + +`Simulator` にはシミュレーション時刻がありません。遅延を含む設計は +受け付けないので、上の遅延の長さは観測できません。遅延は呼び出しを +順序付けるだけで、各呼び出しは直前の呼び出しが落ち着いてから始まります。 + +ここから次のことが従います。 + +- tick はクロック 1 周期です。どちらかのエッジに反応するドメインはすべて + 実行されます。イベント自身のドメインはアクティブエッジで、逆エッジの + ドメイン(`@(negedge clk)`、`~clk` をクロックとするレジスタ)や + `clk & en` のように信号から計算されるクロックは、それぞれが見るエッジで + 実行されます。信号は非アクティブレベルで終わります。 +- すでにアクティブレベルにある信号では、`s <= A` は何も変えないので + アクティブエッジは起きません。2 値で 0 から始まる active-low リセットを + tick すると、解除されるだけです。リセットをアサートするには + `negedge(rst)` か `active_edge(rst)` を使います。 +- 1 つのエッジで起動されたドメインは、ノンブロッキング代入と同じく、 + エッジ前の状態をサンプルしてからまとめて更新します。複数クロックの + 同時 tick(`tick_events`)では、共有エッジの前の値を互いにサンプルします。 +- 4 値の設計では、不定レベルはどちらのレベルとしても扱われます。`x` から + 1 は立ち上がりエッジ、`x` から 0 は立ち下がりエッジです + (IEEE 1800-2023 Table 9-2)。 + +`set` や `sim.dut` 経由の書き込みで、イベント信号や、それから計算される +クロックを動かしてはいけません。Celox がドメインを実行するのは上の +エッジ操作だけです。これらの信号は `edge` や `tick` とその派生で駆動して +ください。 + +## Veryl ネイティブテストベンチ + +Veryl テストベンチの initial ブロックは SystemVerilog の `initial` +プロセスで、`$finish()` は `$finish` です。 + +### `$tb::clock_gen` + +`inst clk: $tb::clock_gen #(period: P);` は、待つプロセスがあるかどうかに +かかわらず時刻 0 から動くクロック生成器です。`P` の既定値は 2 で、最小値も +2 です。`H = ceil(P / 2)`、`L = floor(P / 2)` として: + +```systemverilog +bit clk = 1'b0; +initial forever begin + clk <= 1'b1; #H; + clk <= 1'b0; #L; +end +``` + +### `clk.next(n)` + +```systemverilog +task automatic clk_next(int unsigned n); + if (n != 0) begin + repeat (n) @(posedge clk); + #P; + end +endtask +``` + +`clk.next()` は `clk.next(1)` です。 + +- プロセスは、待っていた `n` 回目の立ち上がりエッジから 1 周期後、次の + 立ち上がりの直前に再開します。そのため、その周期の両エッジの後の状態を + 観測します。クロックは Low で、立ち下がりエッジのドメインは実行済みです。 +- クロックはノンブロッキング代入で立ち上がり、同じ時刻に再開した + プロセスの実行後に立ち上がります。そのため、2 つの `next` の間で + プロセスが書き込んだ値は、競合なく次の立ち上がりエッジでサンプルされます。 +- 複数の initial プロセスや周期の異なる複数のクロックに、追加の規則は + ありません。これらは並行する SystemVerilog のプロセスです。誰も待って + いないクロックも動き続け、そのドメインを駆動します。 + +`$assert` や `if` の条件のように設計を読むテストベンチの文は、プロセス +自身の書き込みの後に組み合わせ回路が落ち着いた値を見ます。 +SystemVerilog では同じ時間ステップ内のこのような読み出しは競合になりますが、 +Celox はこのように解決します。 + +`$tb::reset_gen` の `rst.assert` は、まだこのページでは定義していません。 diff --git a/docs/ja/guide/writing-tests.md b/docs/ja/guide/writing-tests.md index 23152ebf14b..19b1c132a27 100644 --- a/docs/ja/guide/writing-tests.md +++ b/docs/ja/guide/writing-tests.md @@ -52,7 +52,7 @@ module Reg ( - `Simulator.create(Module)` は Veryl モジュール定義からシミュレータインスタンスを作成します。 - シグナル値は `sim.dut.<ポート名>` で読み書きします。 -- `sim.tick()` でシミュレーションを 1 クロックサイクル進めます。 +- `sim.tick()` でシミュレーションを 1 クロック周期進めます。クロックのアクティブエッジ、続いて非アクティブエッジで、どちらかに反応するドメインはすべて実行されます。tick と等価な SystemVerilog は[実行の意味論](./execution-semantics.md)を参照してください。 - `sim.dispose()` でネイティブリソースを解放します。 ::: tip 組み合わせ回路の場合 diff --git a/packages/celox/src/simulator-edges-addon.test.ts b/packages/celox/src/simulator-edges-addon.test.ts index 070265934d8..1b313a565c6 100644 --- a/packages/celox/src/simulator-edges-addon.test.ts +++ b/packages/celox/src/simulator-edges-addon.test.ts @@ -66,10 +66,11 @@ describe("explicit clock edges", () => { sim.negedge(clk); expect(counters()).toEqual([1n, 1n, 1n]); sim.dut.en = 0n; - sim.cycle(clk); + sim.tick(clk); expect(counters()).toEqual([2n, 2n, 1n]); + sim.dut.en = 1n; sim.tick(clk); - expect(counters()).toEqual([3n, 2n, 1n]); + expect(counters()).toEqual([3n, 3n, 2n]); } finally { sim.dispose(); } @@ -159,7 +160,7 @@ module Top ( reset(sim); const observed = enables.map((enable) => { sim.dut.en_in = enable; - sim.cycle(clk); + sim.tick(clk); return [sim.dut.a_out, sim.dut.b_out, sim.dut.d_out]; }); expect(observed).toEqual(expected); diff --git a/packages/celox/src/simulator.ts b/packages/celox/src/simulator.ts index d174b5f54df..73f761011e5 100644 --- a/packages/celox/src/simulator.ts +++ b/packages/celox/src/simulator.ts @@ -449,7 +449,13 @@ export class Simulator

> { } /** - * Trigger a clock edge. + * Run clock periods of an event's signal. + * + * One tick is the event's active edge, then its inactive edge: every + * domain sensitive to either runs, including domains of the opposite edge + * and clocks derived from the signal, and the signal ends at its inactive + * level. See the execution semantics guide for the SystemVerilog this is + * equivalent to. * * A single numeric argument is the tick count for the default event. When a * second argument is not `undefined`, a numeric first argument is treated as @@ -555,12 +561,6 @@ export class Simulator

> { this.edges([[id, this.activeIsRising(id) ? "negedge" : "posedge"]]); } - /** One clock cycle: `activeEdge()`, then `inactiveEdge()`. */ - cycle(event?: EventHandle | number): void { - this.activeEdge(event); - this.inactiveEdge(event); - } - /** * Move several event signals at one instant. Every domain sensitive to * one of the edges evaluates against the state before them, then all of diff --git a/packages/celox/src/wasm-bridge.ts b/packages/celox/src/wasm-bridge.ts index b5810fcaca4..f3d5aeb6182 100644 --- a/packages/celox/src/wasm-bridge.ts +++ b/packages/celox/src/wasm-bridge.ts @@ -263,7 +263,7 @@ export function createWasmSimulatorBridge( ); const handle: NativeSimulatorHandle = { tick(eventId: number): void { - if (edges?.hasDerived(eventId)) { + if (edges) { edges.tick(eventId); return; } @@ -345,7 +345,7 @@ export async function createWasmSimulatorBridgeAsync( ); const handle: NativeSimulatorHandle = { tick(eventId: number): void { - if (edges?.hasDerived(eventId)) { + if (edges) { edges.tick(eventId); return; } diff --git a/packages/celox/src/wasm-edges.test.ts b/packages/celox/src/wasm-edges.test.ts index e82a48d3c38..8968c0daf7c 100644 --- a/packages/celox/src/wasm-edges.test.ts +++ b/packages/celox/src/wasm-edges.test.ts @@ -143,28 +143,28 @@ test("the WASM bridge ticks and moves clocks as the native simulator does", () = sharedMemory[EN] = 1; handle.evalComb(); - // A tick is the active edge only: the gate passes it, `~clk` does not - // rise, and `clk` stays low. + // A tick is a clock period: the gate passes its rising edge, `~clk` + // rises on its falling edge, and `clk` ends low. handle.tick(0); - expect(counters()).toEqual([1, 1, 0]); + expect(counters()).toEqual([1, 1, 1]); expect(sharedMemory[CLK]).toBe(0); expect(handle.activeEdgeIsRising?.(0)).toBe(true); expect(handle.edges?.([0], [true])).toBe(true); - expect(counters()).toEqual([2, 2, 0]); + expect(counters()).toEqual([2, 2, 1]); expect(sharedMemory[CLK]).toBe(1); // Already high: no edge. handle.edges?.([0], [true]); - expect(counters()).toEqual([2, 2, 0]); - handle.edges?.([0], [false]); expect(counters()).toEqual([2, 2, 1]); + handle.edges?.([0], [false]); + expect(counters()).toEqual([2, 2, 2]); // A closed gate passes no edge. sharedMemory[EN] = 0; handle.evalComb(); handle.edges?.([0], [true]); handle.edges?.([0], [false]); - expect(counters()).toEqual([3, 2, 2]); + expect(counters()).toEqual([3, 2, 3]); }); test("a bridge without edge plans keeps the plain tick", () => { diff --git a/packages/celox/src/wasm-edges.ts b/packages/celox/src/wasm-edges.ts index 9e4c1cc966a..6a088098cda 100644 --- a/packages/celox/src/wasm-edges.ts +++ b/packages/celox/src/wasm-edges.ts @@ -13,8 +13,8 @@ * - After the commit, every domain whose clock then moved to its active edge * runs, in rounds, until no further edge appears: domains clocked from * state, and gates the commit moved. - * - `tick` is the event's active edge without moving its signal. An edge - * moves the signal and leaves it at its new level. + * - An edge moves the signal and leaves it at its new level. `tick` is a + * clock period: the active edge, then the inactive edge. * * Gates are judged by settling the design with the signal at each level. * @@ -180,31 +180,22 @@ export class WasmEdgeRunner { return this.plan(eventId)?.edge !== "negedge"; } - /** The event's active edge without moving its signal, as `tick`. */ + /** A clock period of the event's signal, as `tick`. */ tick(eventId: number): void { const name = this.name(eventId); const plan = this.plan(eventId); - if (!plan || !this.hasDerived(eventId)) { + if (!plan) { this.evalComb(); this.kernels(name)?.evalApply(); this.evalComb(); return; } - const active = plan.edge === "negedge" ? 0 : 1; - const levers: Lever[] = - plan.gated.length > 0 - ? [{ signal: plan.signal, from: active ^ 1, to: active }] - : []; - this.run( - [name], - plan.domains, - plan.gated.map((g) => [g, 0]), - levers, - { - settle: true, - persist: false, - }, - ); + const rising = plan.edge !== "negedge"; + let settled = this.edges([eventId], [rising]); + settled = this.edges([eventId], [!rising], !settled); + if (!settled) { + this.evalComb(); + } } /** diff --git a/packages/playground/src/playground-simulator.ts b/packages/playground/src/playground-simulator.ts index 1fd89e7e534..30f42e11848 100644 --- a/packages/playground/src/playground-simulator.ts +++ b/packages/playground/src/playground-simulator.ts @@ -106,7 +106,7 @@ class PlaygroundInstance { if (this.dirty) this.evalComb(); } - /** The event's active edge without moving its signal, as `tick`. */ + /** A clock period of the event's signal, as `tick`. */ tickOne(eventId: number): void { this.runner.tick(eventId); this.dirty = false; @@ -269,11 +269,6 @@ export function createPlaygroundSimulator( const id = resolveEventId(event); sim.edges([[id, design.activeIsRising(id) ? "negedge" : "posedge"]]); }, - /** One clock cycle: `activeEdge()`, then `inactiveEdge()`. */ - cycle(event?: PlaygroundEvent) { - sim.activeEdge(event); - sim.inactiveEdge(event); - }, event(name: string): PlaygroundEventHandle { return { name, id: design.resolveEvent(name) }; }, diff --git a/packages/playground/test/playground-dts.test.ts b/packages/playground/test/playground-dts.test.ts index 87ea9c8ce94..a70e9f7b1f4 100644 --- a/packages/playground/test/playground-dts.test.ts +++ b/packages/playground/test/playground-dts.test.ts @@ -45,7 +45,7 @@ describe("celox declarations for Monaco", () => { "negedge(", "activeEdge(", "inactiveEdge(", - "cycle(", + "tick(", "edges(", ]) { expect(simulator?.content).toContain(method); diff --git a/packages/playground/test/playground-simulator-wasm.test.ts b/packages/playground/test/playground-simulator-wasm.test.ts index 985912eb06a..a0817dce6a8 100644 --- a/packages/playground/test/playground-simulator-wasm.test.ts +++ b/packages/playground/test/playground-simulator-wasm.test.ts @@ -95,20 +95,20 @@ describe.skipIf(!isWasm)("playground runtime (WASM)", () => { expect(counts()).toEqual([1, 0, 1, 1]); sim.negedge(clk); expect(counts()).toEqual([1, 1, 1, 1]); - sim.cycle(clk); + // A tick is a clock period: both edges of the clock. + sim.tick(clk); expect(counts()).toEqual([2, 2, 2, 1]); - // A tick is the active edge without moving the clock. sim.tick(clk); - expect(counts()).toEqual([3, 2, 3, 2]); + expect(counts()).toEqual([3, 3, 3, 2]); sim.dut.en = 0n; - sim.cycle(clk); - expect(counts()).toEqual([4, 3, 3, 2]); + sim.tick(clk); + expect(counts()).toEqual([4, 4, 3, 2]); // The clock is already at its inactive level: no edge. sim.inactiveEdge(clk); - expect(counts()).toEqual([4, 3, 3, 2]); + expect(counts()).toEqual([4, 4, 3, 2]); sim.activeEdge(); sim.edges([[clk, "negedge"]]); - expect(counts()).toEqual([5, 4, 3, 3]); + expect(counts()).toEqual([5, 5, 3, 3]); expect(() => sim.edges([[clk, "sideways" as "posedge"]])).toThrow( RangeError, ); @@ -118,8 +118,8 @@ describe.skipIf(!isWasm)("playground runtime (WASM)", () => { const sim = createPlaygroundSimulator(compile(LEVER, "Lever")); const clk = sim.event("clk"); sim.dut.en = 1n; - sim.cycle(clk); - sim.cycle(clk); + sim.tick(clk); + sim.tick(clk); expect(sim.dut.count).toBe(2n); sim.tick(clk); expect(sim.dut.count).toBe(3n); @@ -129,7 +129,7 @@ describe.skipIf(!isWasm)("playground runtime (WASM)", () => { const sim = Simulator.fromSource(LEVER, "Lever"); const clk = sim.event("clk"); sim.dut.en = 1n; - sim.cycle(clk); + sim.tick(clk); sim.tick(clk); expect(sim.dut.count).toBe(2n); sim.dispose();