diff --git a/AGENTS.md b/AGENTS.md index 6a3103a84c7..0dfd5c54176 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -60,14 +60,21 @@ The second line keeps stacks on the `Depends-On:` chain that the merge queue orders, rather than GitHub-native stacks, which block GitHub's classic merge endpoint. +The rules below apply to Mergify-managed stacks. For ordinary pull requests, +including Renovate PRs, push fixes to the existing PR branch with `git push`. +Do not require converting an ordinary PR into a stack or asking for a workflow +exception. A request to push authorizes the appropriate push command for the +existing workflow. Prefer adding a fix commit to an ordinary PR over rewriting +its published history. + - One commit is one pull request. Its subject becomes the PR title and its body the PR description, so every commit subject must satisfy the PR title rules below, and its type must not exceed the release impact of the change. - Every commit must build and pass its checks on its own; put each fix in the commit that needs it rather than in a later commit. - Create a stack with `mergify stack new /` from an up-to-date - `master`. Publish with `mergify stack push`, never `git push`, and only when - pushing was requested. + `master`. Publish stacks with `mergify stack push` so their PRs and dependency + metadata stay synchronized, and only when pushing was requested. - Revise commits instead of adding fix-up commits: `git commit --amend` for the top commit; `mergify stack edit `, `fixup`, `squash`, `reword`, `move`, `reorder`, or `drop` for others. Never use `git rebase -i`. Before rewriting diff --git a/conformance/common-cells/README.md b/conformance/common-cells/README.md index e4105d2da11..eec535ddb97 100644 --- a/conformance/common-cells/README.md +++ b/conformance/common-cells/README.md @@ -1,6 +1,6 @@ # Upstream SystemVerilog testbench smoke test -Daily full CI runs the unmodified `cc_graycode_tb` from +Daily full CI runs the unmodified `cc_graycode_tb` and `cc_popcount_tb` from [PULP common_cells](https://github.com/pulp-platform/common_cells), pinned by [`revision`](revision). The same job runs on manual `ci.yml` dispatches and on develop's nightly full CI. It exercises the `celox run --project` CLI with the @@ -11,9 +11,15 @@ task, and immediate assertions. It checks binary/Gray round trips and changes in the Gray code population count. This is a small combinational design smoke test, not coverage of all common_cells modules or clocked testbenches. +The popcount TB covers widths 1, 5, 16, 32, 64, and 981 with unconstrained +scope randomization, explicit-unit `#5ns` delays, and immediate assertions +comparing the RTL with `$countones`. The randomizer supports arbitrary packed +widths; 981 is this upstream test's largest vector, not an implementation limit. + The gate first requires the original RTL/TB to exit successfully. It then forces -the Gray encoder output to zero in a separate RTL copy and requires exit code 1 -with an assertion diagnostic. Compilation errors, crashes and timeouts do not +the Gray encoder output to zero and disables popcount accumulation in separate +RTL copies, requiring exit code 1 with the corresponding assertion diagnostic +for each. Compilation errors, crashes and timeouts do not satisfy this negative control. Upstream files are never edited. Each execution has a two-minute wall timeout and the CLI's default scheduler step limit. @@ -29,7 +35,8 @@ node scripts/run-common-cells.mjs work/common-cells target/debug/celox work/comm ``` The output directory contains the generated `celox.toml`, negative-control -sources, both logs, and a `result.json` written only after both checks pass. +sources, the popcount manifests, four logs, and a `result.json` written only after all +four executions pass their positive or negative expectations. Use a fresh output directory for each run. CI retains this directory for 14 days, including on failure; failures feed the existing Full CI issue reporter. diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 7b440f50b12..bee7b6587b4 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -5497,6 +5497,7 @@ fn lower_bit_vector_function_slt( | SystemFunction::Urandom | SystemFunction::UrandomRange | SystemFunction::Fopen + | SystemFunction::ScopeRandomize | SystemFunction::Timeunit | SystemFunction::Timeprecision | SystemFunction::Isunbounded diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 64b54726a4a..6784552d67b 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -239,7 +239,9 @@ impl<'p, 'a> Ff<'p, 'a> { sv::ir::Callee::System(function) => { use sv::ir::SystemFunction; match function { - SystemFunction::Urandom | SystemFunction::UrandomRange => { + SystemFunction::ScopeRandomize + | SystemFunction::Urandom + | SystemFunction::UrandomRange => { self.urandom_state(); } SystemFunction::Random if args.is_empty() => { @@ -823,6 +825,30 @@ impl<'p, 'a> Ff<'p, 'a> { args, .. } => self.fopen(args)?, + Expr::Call { + callee: sv::ir::Callee::System(sv::ir::SystemFunction::ScopeRandomize), + args, + .. + } => { + for arg in args.iter().flatten() { + let Expr::Ident(name) = arg else { + return Err(unsupported("scope randomize variable")); + }; + let target = sv::ir::LValue::Ident(name.clone()); + let width = self.lvalue_width(&target)?; + let mut words = Vec::with_capacity(width.div_ceil(32)); + for offset in (0..width).step_by(32) { + words.push(Expr::Resize { + expr: Box::new(self.randomize_word()?), + width: (width - offset).min(32), + signed: false, + }); + } + words.reverse(); + self.assign(&target, &Expr::Concat(words))?; + } + Expr::Literal("32'sd1".into()) + } Expr::Call { callee: sv::ir::Callee::System(sv::ir::SystemFunction::Urandom), args, @@ -1283,6 +1309,44 @@ impl<'p, 'a> Ff<'p, 'a> { Ok(result) } + /// A bijective 32-bit output permutation of the process RNG. Mixing + /// high bits into low bits prevents the LCG's short low-bit periods from + /// freezing bits when a wide variable consumes an even number of words. + fn randomize_word(&mut self) -> Result { + use sv::ir::{BinaryOp, Expr}; + let mut word = self.urandom(None)?; + for (shift, multiplier) in [(16, 0x7feb352du32), (15, 0x846ca68bu32)] { + let mixed = Expr::Binary { + left: Box::new(word.clone()), + op: BinaryOp::BitXor, + right: Box::new(Expr::Binary { + left: Box::new(word), + op: BinaryOp::Shr, + right: Box::new(Expr::Literal(shift.to_string())), + }), + }; + word = self.hidden( + "randomize_mix", + &Expr::Binary { + left: Box::new(mixed), + op: BinaryOp::Mul, + right: Box::new(Expr::Literal(format!("32'd{multiplier}"))), + }, + false, + )?; + } + let mixed = Expr::Binary { + left: Box::new(word.clone()), + op: BinaryOp::BitXor, + right: Box::new(Expr::Binary { + left: Box::new(word), + op: BinaryOp::Shr, + right: Box::new(Expr::Literal("16".into())), + }), + }; + self.hidden("randomize_word", &mixed, false) + } + /// IEEE 1800-2023 18.13.2: a number of the `$urandom` stream between the /// two bounds, in either order, inclusive. fn urandom_range( diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 220496f725f..da42fe0cd09 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -1609,6 +1609,7 @@ impl Parameter { #[derive(Debug, Clone, PartialEq, Eq)] pub struct Port { + randomizable: bool, name: String, direction: PortDirection, r#type: Type, @@ -1618,6 +1619,7 @@ pub struct Port { #[derive(Debug, Clone, PartialEq, Eq)] pub struct Signal { + is_const: bool, name: String, r#type: Type, is_net: bool, @@ -1631,6 +1633,7 @@ impl Signal { name, r#type, is_net: false, + is_const: false, package_variable: None, } } @@ -1640,6 +1643,7 @@ impl Signal { name, r#type, is_net: true, + is_const: false, package_variable: None, } } @@ -1671,6 +1675,7 @@ impl Port { name, direction, r#type, + randomizable: !is_net, is_net, default: None, } @@ -1863,6 +1868,7 @@ pub enum PortDirection { #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Type { + is_enum: bool, kind: TypeKind, is_signed: bool, packed_ranges: Vec, @@ -1877,6 +1883,7 @@ pub struct Type { impl Type { fn implicit() -> Self { Self { + is_enum: false, kind: TypeKind::Implicit, is_signed: false, packed_ranges: Vec::new(), @@ -1889,6 +1896,7 @@ impl Type { fn new(kind: TypeKind) -> Self { Self { kind, + is_enum: false, is_signed: false, packed_ranges: Vec::new(), unpacked_ranges: Vec::new(), @@ -2567,6 +2575,7 @@ struct UnpackedDimension { #[derive(Debug, Clone, PartialEq, Eq)] struct VariableDimensions { + randomizable: bool, packed: Vec, unpacked: Vec, signed: bool, diff --git a/crates/celox-sv-analyzer/src/ast/declarations.rs b/crates/celox-sv-analyzer/src/ast/declarations.rs index b6d9aebd366..e983092529e 100644 --- a/crates/celox-sv-analyzer/src/ast/declarations.rs +++ b/crates/celox-sv-analyzer/src/ast/declarations.rs @@ -11,6 +11,7 @@ pub(super) fn ports_from_scope( let mut ports = Vec::new(); let mut inherited_direction = PortDirection::Unspecified; let mut inherited_type = Type::implicit(); + let mut inherited_variable = false; for native in port_owners::scope(selected, syntax_tree)? { let direction = native .direction @@ -69,15 +70,27 @@ pub(super) fn ports_from_scope( .ok_or_else(|| unsupported("nonconstant input port default")) }) .transpose()?; - ports.push( - Port::new( - native_port_name(native)?, - direction, - ty, - !explicit && !native.variable, - ) - .with_default(default), - ); + let variable = native.variable + || (direction == PortDirection::Output + && native.net_type.is_none() + && (native.data_type.is_some_and(|id| { + !matches!( + syntax_tree.declarations().data_type(id).kind, + celox_sv_syntax::DataTypeKind::Implicit + ) + }) || (native.direction.is_none() + && native.data_type.is_none() + && inherited_variable))); + inherited_variable = variable; + let mut port = Port::new( + native_port_name(native)?, + direction, + ty, + !explicit && !native.variable, + ) + .with_default(default); + port.randomizable = variable && direction != PortDirection::Input; + ports.push(port); } Ok(ports) } diff --git a/crates/celox-sv-analyzer/src/ast/dimensions.rs b/crates/celox-sv-analyzer/src/ast/dimensions.rs index f62510932aa..e9ac9ddfb74 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions.rs @@ -131,6 +131,7 @@ pub(super) fn packed_dimensions_from_ports_and_signals( dimensions.insert( port.name().to_string(), VariableDimensions { + randomizable: !port.r#type().is_enum && port.randomizable, packed: signal_packed_dimension_widths(port.r#type().packed_ranges()), unpacked: unpacked_dimension_widths(port.r#type().unpacked_ranges()), signed: port.r#type().is_signed(), @@ -144,6 +145,7 @@ pub(super) fn packed_dimensions_from_ports_and_signals( dimensions.insert( signal.name().to_string(), VariableDimensions { + randomizable: !signal.r#type().is_enum && !signal.is_net() && !signal.is_const, packed: signal_packed_dimension_widths(signal.r#type().packed_ranges()), unpacked: unpacked_dimension_widths(signal.r#type().unpacked_ranges()), signed: signal.r#type().is_signed(), @@ -326,6 +328,7 @@ fn extend_variable_dimensions_from_const_env( } let packed_ranges = ranges.split_off(unpacked); let ty = Type { + is_enum: false, kind: TypeKind::Logic, is_signed: variable_type_is_signed(const_env, name), packed_ranges, @@ -338,6 +341,7 @@ fn extend_variable_dimensions_from_const_env( }; let mut shape = procedural::dimensions_from_type(&ty); if let Some(existing) = context.get(name) { + shape.randomizable = existing.randomizable; shape.members = existing.members.clone(); shape.is_2state = existing.is_2state; shape.signed_element_depth = existing.signed_element_depth; @@ -505,6 +509,7 @@ pub(super) fn parameter_packed_dimensions(parameters: &[Parameter]) -> VariableP ( parameter.name.clone(), VariableDimensions { + randomizable: true, packed: function_packed_dimension_widths(¶meter.packed_ranges), unpacked: Vec::new(), signed: parameter.declared_signed.unwrap_or(false), 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 65c00b72f49..f3c11aabc6c 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -367,6 +367,62 @@ pub(in crate::ast) fn bind_value( expression, arguments: args, } => { + if matches!( + call_name(&tree.state, *expression, native).as_deref(), + Some("randomize" | "std::randomize") + ) { + if args + .iter() + .any(|arg| arg.name.is_some() || arg.value.is_none()) + { + return Err(unsupported( + "scope randomize requires positional variable identifiers", + )); + } + let actuals = + args.iter().filter_map(|arg| arg.value).collect::>(); + for &actual in &actuals { + let ExprKind::Name(name) = &native.expression(actual).kind else { + return Err(unsupported( + "scope randomize requires whole packed variable identifiers", + )); + }; + let name = instances::normalize_identifier(&name.spelling); + let shape = dimensions + .get(&name) + .ok_or_else(|| unsupported("scope randomize variable"))?; + if !shape.unpacked.is_empty() || !shape.randomizable { + return Err(unsupported( + "scope randomize requires a packed non-enum variable", + )); + } + if !expressions::query_actual_is_writable( + &Expr::Ident(name), + dimensions, + ) { + return Err(unsupported( + "scope randomize argument is not writable", + )); + } + } + jobs.push(Job::Finish( + Finish::Call { + name: "std::randomize".into(), + args: actuals.iter().copied().map(Some).collect(), + order: Vec::new(), + system: Some(SystemFunction::ScopeRandomize), + }, + actuals.len(), + scope.clone(), + )); + jobs.extend( + actuals + .into_iter() + .rev() + .map(|id| Job::Enter(id, None, scope.clone())), + ); + continue; + } let name = bound_callable_name(tree, *expression, native, dimensions)? .ok_or_else(|| unsupported("method or randomize call"))?; if name.starts_with('$') && !name.contains("::") { @@ -727,6 +783,7 @@ pub(in crate::ast) fn bind_value( | SystemFunction::ValuePlusargs | SystemFunction::Fopen | SystemFunction::UrandomRange + | SystemFunction::ScopeRandomize ) { for (position, arg) in operands.iter().enumerate() { if expr_static_width(&tree.state, arg, dimensions).is_none() diff --git a/crates/celox-sv-analyzer/src/ast/imports.rs b/crates/celox-sv-analyzer/src/ast/imports.rs index 3e80db98927..8b6b6f83e0c 100644 --- a/crates/celox-sv-analyzer/src/ast/imports.rs +++ b/crates/celox-sv-analyzer/src/ast/imports.rs @@ -116,6 +116,11 @@ impl ScopeImports { && let celox_sv_syntax::ExprKind::Name(package) = &native.expression(*base).kind { let package = normalize_identifier(&package.spelling); + // std::randomize is a built-in scope function, not a + // user-declared package dependency (IEEE 1800-2023 18.12). + if package == "std" && normalize_identifier(&name.spelling) == "randomize" { + continue; + } if !nested.iter().any(|(start, end, names)| { (*start..*end).contains(&expression.tokens.start) && names.contains(&package) }) { diff --git a/crates/celox-sv-analyzer/src/ast/interface_binding.rs b/crates/celox-sv-analyzer/src/ast/interface_binding.rs index 83c101df185..389ac475abf 100644 --- a/crates/celox-sv-analyzer/src/ast/interface_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/interface_binding.rs @@ -462,6 +462,7 @@ pub(super) fn analyze_module( name: port.name.clone(), r#type: port.r#type.clone(), is_net: port.is_net, + is_const: false, package_variable: None, }; module.symbols.as_mut().unwrap().signals.push(signal); diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs index 643d48c5e50..f778f37a118 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs @@ -56,6 +56,7 @@ fn member_dimensions(name: &str, r#type: &Type, dimensions: &PackedDimensions) - result.insert( name.to_string(), VariableDimensions { + randomizable: true, packed: function_packed_dimension_widths(&r#type.packed_ranges), unpacked: Vec::new(), signed: r#type.is_signed, diff --git a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs index 8270742c94e..a5097bab957 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs @@ -490,6 +490,7 @@ fn pattern_items( 0, count as i128 - 1, VariableDimensions { + randomizable: true, packed: Vec::new(), unpacked: Vec::new(), members: Vec::new(), diff --git a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs index fd82c4f5bac..4348cc7ed20 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs @@ -203,6 +203,7 @@ fn select<'a>( { let (left, right, count) = dimension_bounds(state, &dim.left, &dim.right, dims)?; let sub = Shape::Owned(Rc::new(VariableDimensions { + randomizable: true, packed: rest.to_vec(), unpacked: Vec::new(), signed: shape.signed_element_depth == Some(1), @@ -236,6 +237,7 @@ fn select<'a>( let width = shape_width(state, &shape, dims) .ok_or_else(|| unsupported("assignment pattern target width"))?; let bit = Shape::Owned(Rc::new(VariableDimensions { + randomizable: true, packed: Vec::new(), unpacked: Vec::new(), signed: false, diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 3d5af5962cc..ba171258fd8 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -68,6 +68,7 @@ pub(super) struct BodyBuilder<'s, 't, 'a> { /// The packed and unpacked shape of a declared type, as selects see it. pub(super) fn dimensions_from_type(r#type: &Type) -> VariableDimensions { VariableDimensions { + randomizable: !r#type.is_enum, packed: dimensions::signal_packed_dimension_widths(r#type.packed_ranges()), unpacked: unpacked_dimension_widths(r#type.unpacked_ranges()), signed: r#type.is_signed(), @@ -98,6 +99,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 { Type { + is_enum: false, kind: TypeKind::Bit, is_signed: true, packed_ranges: vec![PackedRange::new( @@ -651,6 +653,11 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { None => None, }; let name = self.declare(signal.name(), signal.r#type().clone()); + if signal.is_const { + let mut shape = self.dims.get(signal.name()).unwrap().clone(); + shape.randomizable = false; + self.dims.insert(signal.name().to_string(), shape); + } let automatic = match native.lifetime.as_deref() { Some("automatic") => true, Some("static") => false, @@ -746,6 +753,22 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { { let query_root = expression_binding::call_statement_root(root, discarded, self.tree.declarations())?; + if let celox_sv_syntax::ExprKind::Call { expression, .. } = + self.tree.declarations().expression(query_root).kind + && matches!( + expression_binding::native_name( + &self.tree.state, + expression, + self.tree.declarations() + ) + .as_deref(), + Some("randomize" | "std::randomize") + ) + { + let mut call = self.native_value(query_root)?; + self.rename_expr(&mut call); + return Ok(vec![Stmt::Eval(call)]); + } if timescales::is_query(query_root, self.tree.declarations()) { let value = timescales::query(query_root, self.tree)?; return Ok(vec![Stmt::Eval(Expr::Literal( diff --git a/crates/celox-sv-analyzer/src/ast/type_binding.rs b/crates/celox-sv-analyzer/src/ast/type_binding.rs index 1cf876d378f..7d58a46ff99 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding.rs @@ -82,7 +82,9 @@ pub(super) fn local_signals( base.clone(), constant_binding::bind_unpacked_ranges(&variable.dimensions, tree, &context)?, ); - signals.push(Signal::new(name, ty)); + let mut signal = Signal::new(name, ty); + signal.is_const = declaration.constant; + signals.push(signal); } Ok(signals) } diff --git a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs index 7c239591da1..e1bde36666e 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs @@ -77,6 +77,7 @@ pub(in crate::ast) fn bind_in( jobs.push(Job::Enter(*base)); } else { let mut ty = builtin_type("int", None).unwrap(); + ty.is_enum = true; ty.packed_ranges = ranges.into_iter().chain(ty.packed_ranges).collect(); values.push(ty); } @@ -147,6 +148,7 @@ pub(in crate::ast) fn bind_in( let mut outer = ranges; outer.extend(ty.packed_ranges); ty.packed_ranges = outer; + ty.is_enum = true; values.push(ty); } Job::Aggregate { diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 5ded0654667..684f08aad24 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -64,6 +64,8 @@ pub enum SystemFunction { ValuePlusargs, /// `$urandom` (18.13.1). Urandom, + /// Scope randomization of packed variables, without constraints (18.12). + ScopeRandomize, /// `$urandom_range` (18.13.2). UrandomRange, /// `$fopen` (21.3.1). @@ -86,7 +88,7 @@ impl SystemFunction { matches!(self, Self::Fopen | Self::TestPlusargs | Self::ValuePlusargs) } - /// The name, with its leading `$`. + /// The built-in name (`$` functions or `std::randomize`). pub const fn name(self) -> &'static str { match self { Self::Time => "$time", @@ -116,6 +118,7 @@ impl SystemFunction { Self::TestPlusargs => "$test$plusargs", Self::ValuePlusargs => "$value$plusargs", Self::Urandom => "$urandom", + Self::ScopeRandomize => "std::randomize", Self::UrandomRange => "$urandom_range", Self::Fopen => "$fopen", } @@ -154,6 +157,7 @@ impl SystemFunction { | Self::Urandom | Self::Fopen | Self::UrandomRange + | Self::ScopeRandomize ) } @@ -167,7 +171,8 @@ impl SystemFunction { /// Whether the call writes argument `position` back, as `$random(seed)` /// updates its seed variable. pub fn writes_argument(self, position: usize) -> bool { - (matches!(self, Self::Random | Self::DistUniform) && position == 0) + self == Self::ScopeRandomize + || (matches!(self, Self::Random | Self::DistUniform) && position == 0) || (self == Self::ValuePlusargs && position == 1) } @@ -181,7 +186,8 @@ impl SystemFunction { | Self::Timeprecision | Self::Clog2 | Self::Countbits - | Self::Countones => Some((32, true)), + | Self::Countones + | Self::ScopeRandomize => Some((32, true)), Self::Onehot | Self::Onehot0 | Self::Isunknown | Self::Isunbounded => Some((1, false)), Self::Random | Self::DistUniform | Self::TestPlusargs | Self::ValuePlusargs => { Some((32, true)) diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index 1473989e69c..f32421c9afb 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -6234,6 +6234,42 @@ fn unpacked_constant_function_bounds_survive_analysis_without_losing_the_contrac assert!(typecheck::eval_const_expr(range.right(), &HashMap::default()).is_none()); } +#[test] +fn scope_randomize_validates_variable_arguments() { + for call in [ + "randomize(value)", + "std::randomize(value)", + "std::randomize()", + ] { + let source = + format!("module Top; logic [2048:0] value; bit ok; initial ok = {call}; endmodule"); + analyze_source(&source, Path::new("randomize.sv")).unwrap(); + } + for (declaration, call) in [ + ("bit value;", "randomize(1)"), + ("bit value;", "randomize(value[0])"), + ("bit value;", "randomize({value})"), + ("bit value;", "randomize(.value(value))"), + ("bit value;", "randomize(value,)"), + ("localparam value = 1;", "randomize(value)"), + ("bit value[2];", "randomize(value)"), + ("wire value;", "randomize(value)"), + ("const bit value = 1;", "randomize(value)"), + ("enum bit [1:0] {A=0, B=3} value;", "randomize(value)"), + ( + "typedef enum bit [1:0] {A=0, B=3} E; E value;", + "std::randomize(value)", + ), + ("bit value;", "std::randomize(value) with {value == 1;}"), + ] { + let source = format!("module Top; {declaration} bit ok; initial ok = {call}; endmodule"); + assert!( + analyze_source(&source, Path::new("invalid_randomize.sv")).is_err(), + "accepted {source}" + ); + } +} + #[test] fn time_literal_delays_reject_scheduler_overflow() { let error = analyze_source( @@ -6258,3 +6294,22 @@ fn time_literal_delays_accept_numeric_separators() { assert_eq!(*ticks_per_unit, 1); assert!(matches!(amount, ir::Expr::Literal(value) if value == "64'd1000")); } + +#[test] +fn scope_randomize_respects_port_variable_kinds() { + for source in [ + "module Top(output logic [8:0] a, b); initial void'(std::randomize(a,b)); endmodule", + "module Top(output var bit a); initial void'(randomize(a)); endmodule", + ] { + analyze_source(source, Path::new("randomized_output.sv")).unwrap(); + } + for source in [ + "module Top(input var bit a); initial void'(randomize(a)); endmodule", + "module Top(output wire logic a); initial void'(randomize(a)); endmodule", + ] { + assert!( + analyze_source(source, Path::new("randomized_net.sv")).is_err(), + "accepted {source}" + ); + } +} diff --git a/crates/celox-test-suite/src/sv/cases/system_functions.vtest b/crates/celox-test-suite/src/sv/cases/system_functions.vtest index dff1230348c..961efccc184 100644 --- a/crates/celox-test-suite/src/sv/cases/system_functions.vtest +++ b/crates/celox-test-suite/src/sv/cases/system_functions.vtest @@ -2743,3 +2743,85 @@ endmodule (assert_eq ok 1) (assert_eq covered 1) (assert_eq width 32)) + +(case scope_randomize_fills_arbitrary_packed_widths + (source "scope_randomize.sv" #" + module Top(input bit clk, output bit passed, output bit [7:0] coverage); + int count = 0; + bit success; + logic [0:0] v1, ones1 = '0, zeros1 = '1; + logic [4:0] v5, ones5 = '0, zeros5 = '1; + logic [15:0] v16, ones16 = '0, zeros16 = '1; + logic [31:0] v32, ones32 = '0, zeros32 = '1; + logic [63:0] v64, ones64 = '0, zeros64 = '1; + logic [980:0] v981, ones981 = '0, zeros981 = '1; + logic [1023:0] v1024, ones1024 = '0, zeros1024 = '1; + logic [2050:0] v2051, ones2051 = '0, zeros2051 = '1; + always @(posedge clk) begin + success = std::randomize(v1, v5, v16, v32, v64, v981, v1024, v2051); + if (!success) $fatal(1, "scope randomization failed"); + if ($isunknown(v1)) $fatal(1, "unknown randomized bits"); + ones1 |= v1; zeros1 &= v1; + if ($isunknown(v5)) $fatal(1, "unknown randomized bits"); + ones5 |= v5; zeros5 &= v5; + if ($isunknown(v16)) $fatal(1, "unknown randomized bits"); + ones16 |= v16; zeros16 &= v16; + if ($isunknown(v32)) $fatal(1, "unknown randomized bits"); + ones32 |= v32; zeros32 &= v32; + if ($isunknown(v64)) $fatal(1, "unknown randomized bits"); + ones64 |= v64; zeros64 &= v64; + if ($isunknown(v981)) $fatal(1, "unknown randomized bits"); + ones981 |= v981; zeros981 &= v981; + if ($isunknown(v1024)) $fatal(1, "unknown randomized bits"); + ones1024 |= v1024; zeros1024 &= v1024; + if ($isunknown(v2051)) $fatal(1, "unknown randomized bits"); + ones2051 |= v2051; zeros2051 &= v2051; + count++; + if (count == 64) begin + coverage[0] = (&ones1) && !(|zeros1); + coverage[1] = (&ones5) && !(|zeros5); + coverage[2] = (&ones16) && !(|zeros16); + coverage[3] = (&ones32) && !(|zeros32); + coverage[4] = (&ones64) && !(|zeros64); + coverage[5] = (&ones981) && !(|zeros981); + coverage[6] = (&ones1024) && !(|zeros1024); + coverage[7] = (&ones2051) && !(|zeros2051); + passed = &coverage; + end + end + endmodule + "#) + (top Top) + (for draw (range 0 64) (tick clk)) + (assert_eq coverage 255 "coverage by width: 1,5,16,32,64,981,1024,2051") + (assert_eq passed 1 "every bit, including high bits and partial words, varied")) + +(case scope_randomize_obeys_control_flow_and_statement_order + (source "scope_randomize_order.sv" #" + module Top(output int status); + bit a = 0, b = 1; + bit ok; + function automatic bit draw; + bit local_value; + return std::randomize(local_value); + endfunction + initial begin + if (0 && randomize(a)) $fatal(1, "short circuit"); + if (1 || randomize(b)) status = 1; + if (a !== 0 || b !== 1) $fatal(1, "short circuited randomize wrote its argument"); + if ($bits(std::randomize(a)) != 32) $fatal(1, "randomize return width"); + ok = randomize(); + if (!ok || !draw()) $fatal(1, "empty or function call failed"); + void'(std::randomize(a, b)); + std::randomize(a); + randomize(b); + if ($isunknown({a, b})) $fatal(1, "unknown results"); + status = 2; + #1; + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (assert_eq status 2)) diff --git a/crates/celox-test-suite/verification/repros/sv_scope_randomize_icarus.json b/crates/celox-test-suite/verification/repros/sv_scope_randomize_icarus.json new file mode 100644 index 00000000000..a533600b07c --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_scope_randomize_icarus.json @@ -0,0 +1,31 @@ +{ + "schema_version": 3, + "suite": "sv", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "cases": [ + { + "name": "system_functions::scope_randomize_fills_arbitrary_packed_widths", + "category": "Functions", + "expectation": "Simulation", + "status": "compile_error", + "phase": "compile", + "detail": "source_0.sv:14: syntax error\nsource_0.sv:14: error: Malformed statement", + "stronger_than_sv": false, + "tags": [], + "tag_reasons": {} + }, + { + "name": "system_functions::scope_randomize_obeys_control_flow_and_statement_order", + "category": "Functions", + "expectation": "Simulation", + "status": "compile_error", + "phase": "compile", + "detail": "source_0.sv:7: syntax error\nsource_0.sv:7: error: Malformed statement\nsource_0.sv:13: syntax error\nsource_0.sv:13: error: Malformed statement\nsource_0.sv:13: error: Malformed conditional expression.\nsource_0.sv:16: syntax error\nsource_0.sv:16: error: Malformed statement\nsource_0.sv:17: syntax error\nsource_0.sv:17: error: Malformed statement", + "stronger_than_sv": false, + "tags": [], + "tag_reasons": {} + } + ], + "note": "Focused unexcluded compile failures of the two new scope randomize cases; native, Cranelift, Wasm and Verilator execute these cases." +} diff --git a/crates/celox-test-suite/verification/sv/icarus/system_functions.json b/crates/celox-test-suite/verification/sv/icarus/system_functions.json index a37381f1e66..341ab3ef479 100644 --- a/crates/celox-test-suite/verification/sv/icarus/system_functions.json +++ b/crates/celox-test-suite/verification/sv/icarus/system_functions.json @@ -1529,6 +1529,52 @@ "observed_version": "Icarus 13.0", "reason": "Icarus 13.0 terminates for an 8-bit $urandom seed variable with 'seed variable is less than 32 bits (8)'. IEEE 1800-2023 18.13.1 accepts any integral expression, converted to the int seed formal. A standalone signed/unsigned 8-bit seed probe compiles, then vvp exits with this width error; Verilator passes the same nonzero-seed extension checks." } + }, + { + "category": "Functions", + "detail": "Icarus 13.0 rejects std::randomize calls with syntax errors before executing the testbench. IEEE 1800-2023 18.12 defines scope randomization of variables without requiring a class. Verilator executes both the arbitrary-width and control-flow regressions successfully.", + "expectation": "Simulation", + "known_issue": { + "id": "sv_icarus_scope_randomize", + "category": "simulator_unsupported", + "phase": "compile", + "observed_version": "Icarus 13.0", + "reason": "Icarus 13.0 rejects std::randomize calls with syntax errors before executing the testbench. IEEE 1800-2023 18.12 defines scope randomization of variables without requiring a class. Verilator executes both the arbitrary-width and control-flow regressions successfully.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scope_randomize_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "name": "system_functions::scope_randomize_fills_arbitrary_packed_widths", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Icarus 13.0 rejects std::randomize calls with syntax errors before executing the testbench. IEEE 1800-2023 18.12 defines scope randomization of variables without requiring a class. Verilator executes both the arbitrary-width and control-flow regressions successfully.", + "expectation": "Simulation", + "known_issue": { + "id": "sv_icarus_scope_randomize", + "category": "simulator_unsupported", + "phase": "compile", + "observed_version": "Icarus 13.0", + "reason": "Icarus 13.0 rejects std::randomize calls with syntax errors before executing the testbench. IEEE 1800-2023 18.12 defines scope randomization of variables without requiring a class. Verilator executes both the arbitrary-width and control-flow regressions successfully.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scope_randomize_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "name": "system_functions::scope_randomize_obeys_control_flow_and_statement_order", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] } ] } diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 35d0da4feb3..41b86d38c16 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -1523,5 +1523,23 @@ "random_plusargs::dist_uniform_converts_wide_and_signed_seeds_to_int_formals" ] } + }, + { + "id": "sv_icarus_scope_randomize", + "category": "simulator_unsupported", + "phase": "compile", + "observed_version": "Icarus 13.0", + "reason": "Icarus 13.0 rejects std::randomize calls with syntax errors before executing the testbench. IEEE 1800-2023 18.12 defines scope randomization of variables without requiring a class. Verilator executes both the arbitrary-width and control-flow regressions successfully.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scope_randomize_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "system_functions::scope_randomize_fills_arbitrary_packed_widths", + "system_functions::scope_randomize_obeys_control_flow_and_statement_order" + ] + } } ] diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index 040afeae2ab..99295fba55a 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -156,7 +156,7 @@ fn run_sv(arguments: RunConfig) -> Result<(), String> { .map(|(text, path)| (text.as_str(), path.as_path())) .collect(); let builder = celox::Simulation::from_sv_sources(source_refs, &arguments.design.top) - .four_state(arguments.execution.four_state) + .four_state(arguments.design.four_state.unwrap_or(false)) .threads(arguments.execution.threads as usize) .opt_level(arguments.opt_level) .diagnostic_policy(arguments.design.diagnostics.clone()) @@ -403,7 +403,7 @@ fn compile_native_design(design: &Design) -> Result .map(|(text, path)| (text.as_str(), path.as_path())) .collect(); let builder = celox::Simulator::from_sv_sources(refs, &design.top) - .four_state(true) + .four_state(design.four_state.unwrap_or(false)) .diagnostic_policy(design.diagnostics.clone()) .signal_access(design.signal_access.clone()) .opt_level(design.opt_level.unwrap_or(celox::OptLevel::O1)); @@ -427,13 +427,14 @@ fn compile_native_design(design: &Design) -> Result { return Err("pass .sv/.v sources, or one .veryl project entry file".to_string()); } - let (image, warnings) = celox_vpi::driver::compile_native_image_with_parameters( + let (image, warnings) = celox_vpi::driver::compile_native_image_with_state( &design.sources[0], &design.top, design.diagnostics.clone(), design.opt_level.unwrap_or(celox::OptLevel::O1), design.signal_access.clone(), &design.parameters, + design.four_state.unwrap_or(false), )?; report_warnings(&warnings)?; Ok(image) diff --git a/crates/celox-vpi/src/bin/celox/project.rs b/crates/celox-vpi/src/bin/celox/project.rs index 4a46c0528be..f3082b12cb5 100644 --- a/crates/celox-vpi/src/bin/celox/project.rs +++ b/crates/celox-vpi/src/bin/celox/project.rs @@ -18,6 +18,12 @@ pub(super) struct DesignArgs { /// Override a compilation diagnostic: CODE=allow|warn|error (repeatable). #[arg(long = "diagnostic", value_name = "CODE=LEVEL")] diagnostics: Vec, + /// Use two-state simulation, resolving X/Z to zero. + #[arg(long, conflicts_with = "four_state")] + two_state: bool, + /// Use four-state simulation, overriding the project (default: two-state). + #[arg(long)] + four_state: bool, /// Optimization level: O0, O1, O2 (default: project setting or O2 for run, O1 for vpi build). #[arg(short = 'O', long, value_parser = super::parse_opt_level)] opt_level: Option, @@ -56,7 +62,7 @@ pub(super) struct DesignArgs { /// SystemVerilog macro, NAME or NAME=VALUE (repeatable; last value wins). #[arg(short = 'D', long = "define", value_name = "NAME[=VALUE]")] defines: Vec, - /// Override a numeric top parameter (repeatable; last value wins). + /// Override a top parameter with an integer or SV literal (repeatable; last value wins). #[arg( short = 'G', long = "parameter", @@ -95,6 +101,7 @@ struct Manifest { parameters: BTreeMap, top: Option, opt_level: Option, + four_state: Option, live_signals: Option>, force_signals: Option>, max_steps: Option, @@ -127,6 +134,7 @@ struct Target { parameters: BTreeMap, top: Option, opt_level: Option, + four_state: Option, live_signals: Option>, force_signals: Option>, max_steps: Option, @@ -140,8 +148,10 @@ pub(super) struct Design { pub include_dirs: Vec, pub defines: BTreeMap, pub parameters: BTreeMap, + sv_parameters: BTreeMap, pub top: String, pub opt_level: Option, + pub four_state: Option, pub signal_access: celox::SignalAccessOptions, pub max_steps: Option, } @@ -275,6 +285,7 @@ impl DesignArgs { design.signal_access.force_signals = config.force_signals.clone().unwrap_or_default(); design.max_steps = config.max_steps; + design.four_state = config.four_state; if let Some(target) = selected { design.extend_parameters(&target.parameters)?; design.diagnostics.0.extend(target.diagnostics.0.clone()); @@ -296,6 +307,7 @@ impl DesignArgs { design.signal_access.force_signals.clone_from(paths); } design.max_steps = target.max_steps.or(design.max_steps); + design.four_state = target.four_state.or(design.four_state); } design.opt_level = opt_level .map(|value| { @@ -322,6 +334,12 @@ impl DesignArgs { } })); design.opt_level = self.opt_level.or(design.opt_level); + if self.two_state { + design.four_state = Some(false); + } + if self.four_state { + design.four_state = Some(true); + } if self.no_live_signals { design.signal_access.live_signals.clear(); } else if !self.live_signals.is_empty() { @@ -359,7 +377,7 @@ impl DesignArgs { let (name, value) = parameter .split_once('=') .ok_or_else(|| format!("invalid parameter `{parameter}`: expected NAME=VALUE"))?; - design.set_parameter(name, parse_parameter_value(value)?)?; + design.set_parameter_text(name, value, false)?; } if let Some(top) = self.top { design.top = top; @@ -372,6 +390,9 @@ impl DesignArgs { if design.top.trim().is_empty() { return Err("provide --top MODULE or set top in celox.toml".to_string()); } + if !design.is_sv() && !design.sv_parameters.is_empty() { + return Err("SV parameter literals require .sv/.v sources".to_string()); + } if !design.is_sv() && (!design.include_dirs.is_empty() || !design.defines.is_empty()) { return Err( "include directories and defines require SystemVerilog sources".to_string(), @@ -381,12 +402,13 @@ impl DesignArgs { } } -/// TOML integers cover ordinary values; strings also permit radix prefixes -/// and the full unsigned 64-bit range supported by SimulatorBuilder::param. +/// Preserve ordinary integer settings while admitting signed SV literals and +/// textual parameters without losing their width or signedness. #[derive(Deserialize)] #[serde(untagged)] enum ParameterValue { Integer(u64), + Signed(i64), String(String), } @@ -424,6 +446,9 @@ impl Design { for (name, value) in &self.parameters { builder = builder.param(name, *value); } + for (name, literal) in &self.sv_parameters { + builder = builder.param_literal(name, literal); + } builder } @@ -432,16 +457,25 @@ impl Design { parameters: &BTreeMap, ) -> Result<(), String> { for (name, value) in parameters { - let value = match value { - ParameterValue::Integer(value) => *value, - ParameterValue::String(value) => parse_parameter_value(value)?, - }; - self.set_parameter(name, value)?; + match value { + ParameterValue::Integer(value) => self.set_parameter(name, *value)?, + ParameterValue::Signed(value) => { + self.set_parameter_text(name, &value.to_string(), false)? + } + ParameterValue::String(value) => self.set_parameter_text(name, value, true)?, + } } Ok(()) } fn set_parameter(&mut self, name: &str, value: u64) -> Result<(), String> { + Self::validate_parameter_name(name)?; + self.sv_parameters.remove(name); + self.parameters.insert(name.to_string(), value); + Ok(()) + } + + fn validate_parameter_name(name: &str) -> Result<(), String> { if name.is_empty() || !name.bytes().enumerate().all(|(index, byte)| { byte == b'_' @@ -451,10 +485,60 @@ impl Design { { return Err(format!("invalid top parameter name `{name}`")); } - self.parameters.insert(name.to_string(), value); Ok(()) } + fn set_parameter_text( + &mut self, + name: &str, + text: &str, + bare_string: bool, + ) -> Result<(), String> { + if let Ok(value) = parse_parameter_value(text) { + return self.set_parameter(name, value); + } + #[cfg(feature = "systemverilog")] + { + let literal = if celox_sv_analyzer::typecheck::parse_parameter_literal(text).is_some() { + text.to_string() + } else if bare_string { + // TOML strings are ordinary string values unless they spell a + // numeric literal. Encode bytes using SV's escape rules. + let mut quoted = String::from("\""); + for byte in text.bytes() { + match byte { + b'"' => quoted.push_str("\\\""), + b'\\' => quoted.push_str("\\\\"), + b'\n' => quoted.push_str("\\n"), + b'\t' => quoted.push_str("\\t"), + 32..=126 => quoted.push(char::from(byte)), + 0..=127 => quoted.push_str(&format!("\\{byte:03o}")), + _ => return Err(format!("non-ASCII string parameter `{name}`")), + } + } + quoted.push('"'); + quoted + } else { + return Err(format!( + "invalid parameter value `{text}`: expected an unsigned 64-bit integer or SV literal" + )); + }; + // Reuse the name validation and remove whichever representation a + // lower-precedence project or target setting used. + Self::validate_parameter_name(name)?; + self.parameters.remove(name); + self.sv_parameters.insert(name.to_string(), literal); + Ok(()) + } + #[cfg(not(feature = "systemverilog"))] + { + let _ = (name, bare_string); + Err(format!( + "invalid parameter value `{text}`: SV literals require the systemverilog feature" + )) + } + } + pub fn is_sv(&self) -> bool { !self.sources.is_empty() && self.sources.iter().all(|path| { diff --git a/crates/celox-vpi/src/bin/celox/runner.rs b/crates/celox-vpi/src/bin/celox/runner.rs index b3bc75ac7ae..802e60033c9 100644 --- a/crates/celox-vpi/src/bin/celox/runner.rs +++ b/crates/celox-vpi/src/bin/celox/runner.rs @@ -33,8 +33,6 @@ pub(super) struct ExecutionArgs { #[arg(long, value_enum, default_value = "native")] pub backend: Backend, #[arg(long)] - pub four_state: bool, - #[arg(long)] compile_only: bool, /// Write a pointer-free native image during compile-only mode. #[arg(long, value_name = "PATH")] @@ -197,7 +195,7 @@ pub(super) fn run( test: design.top.clone(), opt_level: design.opt_level.unwrap_or(OptLevel::O2), backend: cli.backend, - four_state: cli.four_state, + four_state: design.four_state.unwrap_or(false), compile_only: cli.compile_only, native_image_output: cli.native_image_output, native_image_input: cli.native_image_input, diff --git a/crates/celox-vpi/src/driver.rs b/crates/celox-vpi/src/driver.rs index 350ecd6912f..c7bd819169c 100644 --- a/crates/celox-vpi/src/driver.rs +++ b/crates/celox-vpi/src/driver.rs @@ -60,7 +60,10 @@ pub fn compile_native_image_with_diagnostics( policy, celox::OptLevel::O0, celox::SignalAccessOptions::default(), - true, + CompileMode { + legacy_force: true, + four_state: true, + }, &BTreeMap::new(), ) } @@ -85,16 +88,45 @@ pub fn compile_native_image_with_parameters( access: celox::SignalAccessOptions, parameters: &BTreeMap, ) -> Result<(NativeProgramImage, Vec), String> { - compile_native_image_configured(source, top, policy, level, access, false, parameters) + compile_native_image_with_state(source, top, policy, level, access, parameters, true) } -fn compile_native_image_configured( +/// Compile numeric parameters with an explicit four-state simulation mode. +pub fn compile_native_image_with_state( source: &Path, top: &str, policy: DiagnosticPolicy, level: celox::OptLevel, access: celox::SignalAccessOptions, + parameters: &BTreeMap, + four_state: bool, +) -> Result<(NativeProgramImage, Vec), String> { + compile_native_image_configured( + source, + top, + policy, + level, + access, + CompileMode { + legacy_force: false, + four_state, + }, + parameters, + ) +} + +struct CompileMode { legacy_force: bool, + four_state: bool, +} + +fn compile_native_image_configured( + source: &Path, + top: &str, + policy: DiagnosticPolicy, + level: celox::OptLevel, + access: celox::SignalAccessOptions, + mode: CompileMode, parameters: &BTreeMap, ) -> Result<(NativeProgramImage, Vec), String> { let compiled = if let Ok(metadata_path) = Metadata::search_from(source) { @@ -118,8 +150,8 @@ fn compile_native_image_configured( let builder = Simulator::from_sources(source_refs, top) .with_metadata(metadata) .diagnostic_policy(policy.clone()) - .four_state(true) - .native_force_support(legacy_force) + .four_state(mode.four_state) + .native_force_support(mode.legacy_force) .signal_access(access.clone()) .opt_level(level); parameters @@ -133,8 +165,8 @@ fn compile_native_image_configured( .map_err(|error| format!("failed to read {}: {error}", source.display()))?; let builder = Simulator::from_sources(vec![(contents.as_str(), source)], top) .diagnostic_policy(policy.clone()) - .four_state(true) - .native_force_support(legacy_force) + .four_state(mode.four_state) + .native_force_support(mode.legacy_force) .signal_access(access.clone()) .opt_level(level); parameters diff --git a/crates/celox-vpi/src/lib.rs b/crates/celox-vpi/src/lib.rs index 7b72d33a241..b35a0804a69 100644 --- a/crates/celox-vpi/src/lib.rs +++ b/crates/celox-vpi/src/lib.rs @@ -1312,10 +1312,12 @@ pub unsafe extern "C" fn vpi_put_value( } let signal_info = with_runtime(|runtime| { - runtime - .reflection() - .signal(id) - .map(|signal| (signal.signal.width, signal.signal.is_4state)) + runtime.reflection().signal(id).map(|signal| { + ( + signal.signal.width, + signal.signal.is_4state && runtime.four_state(), + ) + }) }) .flatten(); let Some((width, is_4state)) = signal_info else { diff --git a/crates/celox-vpi/tests/basic_vpi.rs b/crates/celox-vpi/tests/basic_vpi.rs index fe2ef1926b0..b0dd703a978 100644 --- a/crates/celox-vpi/tests/basic_vpi.rs +++ b/crates/celox-vpi/tests/basic_vpi.rs @@ -3088,3 +3088,69 @@ fn interface_members_are_navigable_after_native_image_round_trip() { } } } + +#[cfg(feature = "systemverilog")] +#[test] +fn two_state_image_converts_unknown_logic_deposits_and_forces() { + let _serial = lock_vpi(); + let source = "module Top(input logic[3:0] a,output logic[3:0] y); assign y=a; endmodule"; + let simulator = + Simulator::from_sv_sources(vec![(source, std::path::Path::new("two_state.sv"))], "Top") + .four_state(false) + .native_force_support(true) + .build() + .unwrap(); + let _session = install_runtime(trusted_instance( + simulator.shared_code().program_image().clone(), + )) + .unwrap(); + unsafe { + let a = vpi_handle_by_name(c"Top.a".as_ptr(), ptr::null_mut()); + let y = vpi_handle_by_name(c"Top.y".as_ptr(), ptr::null_mut()); + let mut word = VpiVecVal { aval: 15, bval: 10 }; + let input = VpiValue { + format: VPI_VECTOR_VAL, + value: VpiValueData { vector: &mut word }, + }; + let mut output = VpiValue { + format: VPI_VECTOR_VAL, + value: VpiValueData { integer: 0 }, + }; + assert_eq!(vpi_put_value(a, &input, ptr::null(), VPI_NO_DELAY), a); + vpi_get_value(y, &mut output); + assert_eq!((*output.value.vector).aval, 5); + assert_eq!((*output.value.vector).bval, 0); + let mut force_word = VpiVecVal { aval: 15, bval: 5 }; + let force_value = VpiValue { + format: VPI_VECTOR_VAL, + value: VpiValueData { + vector: &mut force_word, + }, + }; + assert_eq!( + vpi_put_value(a, &force_value, ptr::null(), VPI_FORCE_FLAG), + a + ); + vpi_get_value(y, &mut output); + assert_eq!((*output.value.vector).aval, 10); + assert_eq!((*output.value.vector).bval, 0); + let mut deposited_word = VpiVecVal { aval: 15, bval: 12 }; + let deposited_value = VpiValue { + format: VPI_VECTOR_VAL, + value: VpiValueData { + vector: &mut deposited_word, + }, + }; + assert_eq!( + vpi_put_value(a, &deposited_value, ptr::null(), VPI_NO_DELAY), + a + ); + assert_eq!(vpi_put_value(a, &input, ptr::null(), VPI_RELEASE_FLAG), a); + vpi_get_value(y, &mut output); + assert_eq!((*output.value.vector).aval, 3); + assert_eq!((*output.value.vector).bval, 0); + vpi_free_object(a); + vpi_free_object(y); + } + clear_runtime(); +} diff --git a/crates/celox-vpi/tests/project_cli.rs b/crates/celox-vpi/tests/project_cli.rs index bf043129c4f..06be274810f 100644 --- a/crates/celox-vpi/tests/project_cli.rs +++ b/crates/celox-vpi/tests/project_cli.rs @@ -583,18 +583,231 @@ fn top_parameters_reach_veryl_run_and_native_build() { fn invalid_parameter_assignments_are_rejected() { let root = tempfile::tempdir().unwrap(); for value in [ - "V", - "=1", - "x.y=1", - "V=", - "V=-1", - "V=1+2", - "V=18446744073709551616", - "V=0x", - "V=0b2", - "V=_1", + "V", "=1", "x.y=1", "V=", "V=--1", "V=1+2", "V=8'hG", "V=0x", "V=0b2", "V=_1", ] { let output = invoke(root.path(), &["run", "dut.sv", "--top", "Top", "-G", value]); rejected(&output, "parameter"); } } + +#[cfg(feature = "systemverilog")] +#[test] +fn sv_parameter_literals_preserve_types_across_project_target_and_cli() { + let root = tempfile::tempdir().unwrap(); + let source = r#" + module Top #(parameter VENDOR="GENERIC", parameter NEG=3, + parameter logic [64:0] WIDE=0, parameter logic [11:0] FILL=0, + parameter logic [3:0] UNKNOWN=0)(output logic matched); + assign matched=(VENDOR == "XILINX") && (NEG == -8) && (NEG < 0) + && ($bits(NEG) == 32) && ($bits(VENDOR) == 48) + && (WIDE == 65'h10000000000000001) && (FILL == 12'hfff) + && (UNKNOWN === 4'b10xz); + initial begin #1; assert(matched) else $fatal(1,"literal parameter types"); + $display("ok"); $finish; end + endmodule + "#; + fs::write(root.path().join("top.sv"), source).unwrap(); + fs::write( + root.path().join("celox.toml"), + r#" + sources=["top.sv"] + top="Top" + [parameters] + VENDOR="GENERIC" + NEG=3 + FILL=0 + [targets.literals.parameters] + VENDOR="XILINX" + NEG=-8 + WIDE="65'h10000000000000001" + FILL="'1" + UNKNOWN="4'b10xz" + "#, + ) + .unwrap(); + let output = invoke(root.path(), &["run", "--target", "literals"]); + success(&output); + assert_eq!(output.stdout, b"ok\n"); + let args = [ + "--target", + "literals", + "-GVENDOR=0", + "-GVENDOR=\"XILINX\"", + "-GNEG=8", + "-GNEG=-8", + "-GFILL=0", + "-GFILL='1", + ]; + let output = invoke(root.path(), &[&["run"][..], &args].concat()); + success(&output); + assert_eq!(output.stdout, b"ok\n"); + success(&invoke( + root.path(), + &[&["vpi", "build"][..], &args, &["-o", "sim"]].concat(), + )); + let bytes = fs::read(root.path().join("sim")).unwrap(); + let image = celox::NativeProgramImage::discover_appended(&bytes) + .unwrap() + .unwrap() + .image; + // Safety: the CLI compiled this test's source into the image above. + let instance = unsafe { celox::NativeProgramInstance::from_image(image) }.unwrap(); + let matched = instance.signal_ref("Top.matched").unwrap(); + assert_eq!( + celox::SimBackend::get_as::(instance.backend(), matched), + 1 + ); + assert_eq!( + fs::read_to_string(root.path().join("top.sv")).unwrap(), + source + ); +} + +#[cfg(feature = "systemverilog")] +#[test] +fn state_mode_merges_project_target_and_cli_for_run_and_native_build() { + let root = tempfile::tempdir().unwrap(); + fs::write( + root.path().join("top.sv"), + r#" + module Top(output logic[3:0] y); + logic[3:0] uninitialized; + assign y=uninitialized; + initial begin #1; $display("value=%b",y); $finish; end + endmodule + "#, + ) + .unwrap(); + fs::write( + root.path().join("celox.toml"), + "sources=['top.sv']\ntop='Top'\nfour_state=true\n[targets.two]\nfour_state=false\n", + ) + .unwrap(); + for (args, expected, is_four) in [ + (vec![], "value=xxxx\n", true), + (vec!["--two-state"], "value=0000\n", false), + (vec!["--target", "two"], "value=0000\n", false), + ( + vec!["--target", "two", "--four-state"], + "value=xxxx\n", + true, + ), + ] { + let run = invoke(root.path(), &[&["run"][..], &args].concat()); + success(&run); + assert_eq!(String::from_utf8(run.stdout).unwrap(), expected); + success(&invoke( + root.path(), + &[&["vpi", "build"][..], &args, &["-o", "sim"]].concat(), + )); + let bytes = fs::read(root.path().join("sim")).unwrap(); + let image = celox::NativeProgramImage::discover_appended(&bytes) + .unwrap() + .unwrap() + .image; + // Safety: the CLI compiled this test's source into this image. + let instance = unsafe { celox::NativeProgramInstance::from_image(image) }.unwrap(); + assert_eq!(instance.four_state(), is_four); + let (value, mask) = celox::SimBackend::get_four_state( + instance.backend(), + instance.signal_ref("Top.y").unwrap(), + ); + assert_eq!( + mask.to_u64_digits(), + if is_four { vec![15] } else { vec![] } + ); + if !is_four { + assert_eq!(value.to_u64_digits(), Vec::::new()); + } + } +} + +#[test] +fn sv_literal_parameters_are_rejected_for_veryl_in_both_commands() { + let root = tempfile::tempdir().unwrap(); + fs::write( + root.path().join("top.veryl"), + "module Top #(param W:u32=8) (y:output logic) { assign y=0; }", + ) + .unwrap(); + for prefix in [&["run"][..], &["vpi", "build"][..]] { + let output = invoke( + root.path(), + &[prefix, &["top.veryl", "--top", "Top", "-GW=-8"]].concat(), + ); + rejected(&output, "SV parameter literals require"); + } +} + +#[test] +fn veryl_native_images_preserve_the_selected_state_mode() { + for with_metadata in [false, true] { + let root = tempfile::tempdir().unwrap(); + fs::write( + root.path().join("top.veryl"), + "module Top (y:output logic<4>) { assign y=3; }", + ) + .unwrap(); + if with_metadata { + fs::write( + root.path().join("Veryl.toml"), + "[project]\nname='state_mode'\nversion='0.1.0'\n", + ) + .unwrap(); + } + for (flag, four_state) in [("--two-state", false), ("--four-state", true)] { + let output = invoke( + root.path(), + &[ + "vpi", + "build", + "top.veryl", + "--top", + "Top", + flag, + "-o", + "sim", + ], + ); + success(&output); + let bytes = fs::read(root.path().join("sim")).unwrap(); + let image = celox::NativeProgramImage::discover_appended(&bytes) + .unwrap() + .unwrap() + .image; + // Safety: the CLI compiled this test's source into this image. + let instance = unsafe { celox::NativeProgramInstance::from_image(image) }.unwrap(); + assert_eq!(instance.four_state(), four_state); + } + } +} + +#[cfg(feature = "systemverilog")] +#[test] +fn sv_cli_defaults_to_two_state_for_run_and_native_images() { + let root = tempfile::tempdir().unwrap(); + fs::write( + root.path().join("top.sv"), + r#"module Top(output logic[3:0] y); + logic[3:0] uninitialized; + assign y=uninitialized; + initial begin #1; $display("value=%b", y); $finish; end + endmodule"#, + ) + .unwrap(); + let run = invoke(root.path(), &["run", "top.sv", "--top", "Top"]); + success(&run); + assert_eq!(run.stdout, b"value=0000\n"); + success(&invoke( + root.path(), + &["vpi", "build", "top.sv", "--top", "Top", "-o", "sim"], + )); + let bytes = fs::read(root.path().join("sim")).unwrap(); + let image = celox::NativeProgramImage::discover_appended(&bytes) + .unwrap() + .unwrap() + .image; + // Safety: this test compiled the source into the image above. + let instance = unsafe { celox::NativeProgramInstance::from_image(image) }.unwrap(); + assert!(!instance.four_state()); +} diff --git a/crates/celox/src/backend/native/runtime_image.rs b/crates/celox/src/backend/native/runtime_image.rs index 271f4523a44..3e1bc73d563 100644 --- a/crates/celox/src/backend/native/runtime_image.rs +++ b/crates/celox/src/backend/native/runtime_image.rs @@ -108,6 +108,11 @@ impl NativeProgramInstance { self.shared.program_image().time_precision() } + /// Whether the attached image executes with four-state values. + pub fn four_state(&self) -> bool { + self.shared.program_image().four_state() + } + /// Elaborated hierarchy and signal metadata embedded by the compiler. pub fn reflection(&self) -> &DesignReflection { self.shared.program_image().reflection() diff --git a/crates/celox/src/parser.rs b/crates/celox/src/parser.rs index 1072ec8ad5f..36c5b0bc558 100644 --- a/crates/celox/src/parser.rs +++ b/crates/celox/src/parser.rs @@ -573,7 +573,7 @@ pub fn parse( pub fn parse_sv( sources: &[(&str, &std::path::Path)], top: &str, - parameter_overrides: &[(String, u64)], + parameter_overrides: &[(String, celox_frontend_sv::analyzer_ir::ConstExpr)], _config: &BuildConfig, ignored_loops: &[( (Vec<(String, usize)>, Vec), @@ -599,7 +599,7 @@ pub fn parse_sv( ) -> Result { let frontend_trace_options = trace_opts.frontend(diagnostics); let mut frontend_trace = celox_frontend_core::FrontendTrace::default(); - let scheduled = celox_frontend_sv::schedule_sources_with_force_signals( + let scheduled = celox_frontend_sv::schedule_sources_with_parameter_expressions( sources, top, parameter_overrides, diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 96414337517..89059ee1f19 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1081,6 +1081,7 @@ pub fn compile_sv_to_sir( &crate::DiagnosticPolicy::default(), crate::backend::memory_layout::MemoryLayoutMode::Packed, &[], + &[], ) } @@ -1110,7 +1111,24 @@ fn compile_sv_to_sir_with_layout_mode( diagnostic_policy: &crate::DiagnosticPolicy, layout_mode: crate::backend::memory_layout::MemoryLayoutMode, force_signals: &[String], + sv_param_literals: &[(String, String)], ) -> Result<(OptimizedSir, Vec), SimulatorError> { + let mut parameters = param_overrides + .iter() + .map(|(name, value)| { + ( + name.clone(), + celox_frontend_sv::analyzer_ir::ConstExpr::Literal(value.to_string()), + ) + }) + .collect::>(); + for (name, literal) in sv_param_literals { + let value = celox_frontend_sv::analyzer_typecheck::parse_parameter_literal(literal) + .ok_or_else(|| { + crate::CodegenError::message(format!("invalid SV parameter literal `{literal}`")) + })?; + parameters.push((name.clone(), value)); + } let metadata = metadata.unwrap_or_else(|| Metadata::create_default("prj").unwrap()); let mut build_config = BuildConfig::from(&metadata.build); if let Some(clock_type) = clock_type { @@ -1124,7 +1142,7 @@ fn compile_sv_to_sir_with_layout_mode( let sir = parser::parse_sv( sources, top, - param_overrides, + ¶meters, &build_config, ignored_loops, true_loops, @@ -1366,7 +1384,14 @@ fn compile_hdl_to_sir_with_layout_mode( allow_always_ff_function_effects: bool, file_dependencies: &celox_frontend_veryl::FileDependencyCollector, force_signals: &[String], + sv_param_literals: &[(String, String)], ) -> Result<(OptimizedSir, Vec), SimulatorError> { + if !sv_param_literals.is_empty() && (!sources.is_empty() || sv_sources.is_empty()) { + return Err(crate::CodegenError::message( + "parameter literals require pure SystemVerilog sources", + ) + .into()); + } if !force_signals.is_empty() && !sources.is_empty() { return Err(crate::CodegenError::message( "force_signals currently require pure SystemVerilog sources", @@ -1438,6 +1463,7 @@ fn compile_hdl_to_sir_with_layout_mode( diagnostic_policy, layout_mode, force_signals, + sv_param_literals, ), (false, false) => compile_mixed_to_sir_with_layout_mode( sources, @@ -1804,6 +1830,7 @@ mod host { clock_type: Option, reset_type: Option, param_overrides: Vec<(String, u64)>, + sv_param_literals: Vec<(String, String)>, live_signals: Vec<(Vec<(String, usize)>, Vec)>, injected_components: crate::InjectedComponents, frontend_artifact: Option, @@ -1885,10 +1912,22 @@ mod host { /// Override a top-level module parameter value. pub fn param(mut self, name: &str, value: u64) -> Self { + self.sv_param_literals.retain(|(key, _)| key != name); self.param_overrides.push((name.to_string(), value)); self } + /// Override a pure SV top parameter with a literal, such as `-8`, + /// `8'hff`, `'1`, or `"XILINX"`. The literal's width and signedness + /// are preserved. Invalid literals are reported when building. + pub fn param_literal(mut self, name: &str, literal: &str) -> Self { + self.param_overrides.retain(|(key, _)| key != name); + self.sv_param_literals.retain(|(key, _)| key != name); + self.sv_param_literals + .push((name.to_string(), literal.to_string())); + self + } + /// Make in-process component implementations available as `$comp::`. pub fn with_injected_components(mut self, components: crate::InjectedComponents) -> Self { self.injected_components = components; @@ -2332,6 +2371,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: None, @@ -2353,6 +2393,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: None, @@ -2375,6 +2416,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: None, @@ -2402,6 +2444,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: None, @@ -2428,6 +2471,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: Some(artifact), @@ -2455,6 +2499,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: Some(artifact), @@ -2509,7 +2554,13 @@ mod host { let phase_timing = self.options.diagnostics.phase_timing; let compile_start = phase_timing.then(crate::timing::now); let injected_manifests = self.injected_components.manifests(); - let compiled = if let Some(artifact) = &self.frontend_artifact { + let compiled = if !self.sv_param_literals.is_empty() && self.frontend_artifact.is_some() + { + Err(crate::CodegenError::message( + "parameter literals require pure SystemVerilog sources", + ) + .into()) + } else if let Some(artifact) = &self.frontend_artifact { if self.sources.is_empty() { compile_frontend_to_sir_with_layout_mode( artifact, @@ -2568,6 +2619,7 @@ mod host { self.options.allow_always_ff_function_effects, &self.file_dependencies, &self.options.signal_access.force_signals, + &self.sv_param_literals, ) }; let (program, mut warnings) = compiled @@ -3162,23 +3214,52 @@ mod host { layout_mode }; let injected_manifests = self.injected_components.manifests(); - let program_res = if let Some(artifact) = &self.frontend_artifact { - if self.sources.is_empty() { - compile_frontend_to_sir_with_layout_mode( - artifact, - &self.ignored_loops, - &self.true_loops, - self.options.four_state, - &self.options.trace, - Some(&mut trace), - &self.options.optimize_options, - &self.options.diagnostics, - layout_mode, + let program_res = + if !self.sv_param_literals.is_empty() && self.frontend_artifact.is_some() { + Err(crate::CodegenError::message( + "parameter literals require pure SystemVerilog sources", ) + .into()) + } else if let Some(artifact) = &self.frontend_artifact { + if self.sources.is_empty() { + compile_frontend_to_sir_with_layout_mode( + artifact, + &self.ignored_loops, + &self.true_loops, + self.options.four_state, + &self.options.trace, + Some(&mut trace), + &self.options.optimize_options, + &self.options.diagnostics, + layout_mode, + ) + } else { + compile_frontend_testbench_to_sir_with_layout_mode( + artifact, + &self.sources, + self.top, + &self.ignored_loops, + &self.true_loops, + self.options.four_state, + &self.options.trace, + Some(&mut trace), + self.metadata, + self.clock_type, + self.reset_type, + &self.options.optimize_options, + &self.options.diagnostics, + &self.options.diagnostic_policy, + &injected_manifests, + layout_mode, + !self.options.native_force_support, + self.options.allow_always_ff_function_effects, + &self.file_dependencies, + ) + } } else { - compile_frontend_testbench_to_sir_with_layout_mode( - artifact, + compile_hdl_to_sir_with_layout_mode( &self.sources, + &self.sv_sources, self.top, &self.ignored_loops, &self.true_loops, @@ -3188,6 +3269,7 @@ mod host { self.metadata, self.clock_type, self.reset_type, + &self.param_overrides, &self.options.optimize_options, &self.options.diagnostics, &self.options.diagnostic_policy, @@ -3196,33 +3278,10 @@ mod host { !self.options.native_force_support, self.options.allow_always_ff_function_effects, &self.file_dependencies, + &self.options.signal_access.force_signals, + &self.sv_param_literals, ) - } - } else { - compile_hdl_to_sir_with_layout_mode( - &self.sources, - &self.sv_sources, - self.top, - &self.ignored_loops, - &self.true_loops, - self.options.four_state, - &self.options.trace, - Some(&mut trace), - self.metadata, - self.clock_type, - self.reset_type, - &self.param_overrides, - &self.options.optimize_options, - &self.options.diagnostics, - &self.options.diagnostic_policy, - &injected_manifests, - layout_mode, - !self.options.native_force_support, - self.options.allow_always_ff_function_effects, - &self.file_dependencies, - &self.options.signal_access.force_signals, - ) - }; + }; let program_res = program_res .map_err(|error| error.apply_diagnostic_policy(&self.options.diagnostic_policy)); @@ -3336,6 +3395,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: None, @@ -3357,6 +3417,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: None, @@ -3380,6 +3441,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: Some(artifact), diff --git a/crates/celox/tests/frontends/systemverilog/hierarchy.rs b/crates/celox/tests/frontends/systemverilog/hierarchy.rs index 87930fcef09..f1baf76a403 100644 --- a/crates/celox/tests/frontends/systemverilog/hierarchy.rs +++ b/crates/celox/tests/frontends/systemverilog/hierarchy.rs @@ -362,3 +362,28 @@ fn rejects_feedback_through_the_same_bit_of_child_input() { "#, ); } + +sv_backends! { + fn literal_parameter_api_preserves_width_sign_and_unknowns(sim) { + @setup { + let source = r#" + module Top #(parameter TEXT="default", parameter NEG=0, + parameter logic [11:0] FILL=0, parameter logic [3:0] UNKNOWN=0, + parameter logic [64:0] WIDE=0, parameter FINAL=0)(output logic matched); + assign matched=(TEXT=="XILINX") && ($bits(TEXT)==48) + && (NEG==-8) && (NEG<0) && ($bits(NEG)==32) + && (FILL==12'hfff) && (UNKNOWN===4'b10xz) + && (WIDE==65'h10000000000000001) && (FINAL==7); + endmodule + "#; + } + @build Simulator::from_sv_sources(vec![(source, Path::new("parameter_api.sv"))], "Top") + .param_literal("TEXT", "\"XILINX\"") + .param("NEG", 3).param_literal("NEG", "-8") + .param_literal("FILL", "'1").param_literal("UNKNOWN", "4'b10xz") + .param_literal("WIDE", "65'h10000000000000001") + .param_literal("FINAL", "-1").param("FINAL", 7) + .four_state(true).opt_level(celox::OptLevel::O2); + assert_eq!(sim.get(sim.signal("matched")), BigUint::from(1u8)); + } +} diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index 4a0960a7a7c..ea78f60de55 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -160,6 +160,38 @@ sv_backends! { assert!(sim.drain_runtime_events().is_empty()); } + fn scope_randomize_fills_arbitrary_packed_widths(sim) { + @case "system_functions::scope_randomize_fills_arbitrary_packed_widths"; + } + + fn scope_randomize_obeys_control_flow_and_statement_order(sim) { + @case "system_functions::scope_randomize_obeys_control_flow_and_statement_order"; + } + + fn scope_randomize_preserves_four_state_storage_and_checkpoint(sim) { + @setup { let source = r#" + module Top(input bit clk, output logic signed [2048:0] value); + always @(posedge clk) void'(std::randomize(value)); + endmodule + "#; } + @build Simulator::from_sv_sources(vec![(source, Path::new("randomize_checkpoint.sv"))], "Top").four_state(true); + let clk = sim.event("clk"); + let value = sim.signal("value"); + let saved = sim.checkpoint().unwrap(); + sim.tick(clk).unwrap(); + let (first, mask) = sim.get_four_state(value); + assert_eq!(mask, 0u8.into()); + assert!(first.bits() > 2000, "upper words must receive random bits"); + sim.tick(clk).unwrap(); + let second = sim.get(value); + assert_ne!(first, second); + sim.restore(&saved).unwrap(); + sim.tick(clk).unwrap(); + assert_eq!(sim.get(value), first); + sim.tick(clk).unwrap(); + assert_eq!(sim.get(value), second); + } + fn urandom_extends_signed_seed_values(sim) { @case "system_functions::urandom_extends_signed_seed_values"; } @@ -3050,3 +3082,40 @@ sv_backends! { assert_eq!(warnings[0].1, source_line(&source, "$readmemh")); } } + +#[test] +fn scope_randomize_survives_all_optimization_levels() { + let source = r#" + module Top(input bit clk, output logic [980:0] value); + always @(posedge clk) void'(std::randomize(value)); + endmodule + "#; + for level in [ + celox::OptLevel::O0, + celox::OptLevel::O1, + celox::OptLevel::O2, + ] { + for four_state in [false, true] { + let mut sim = Simulator::from_sv_sources( + vec![(source, Path::new("randomize_optimization.sv"))], + "Top", + ) + .opt_level(level) + .four_state(four_state) + .build_native() + .unwrap(); + let value = sim.signal("value"); + let clk = sim.event("clk"); + let checkpoint = sim.checkpoint().unwrap(); + sim.tick(clk).unwrap(); + let first = sim.get(value); + assert!(first.bits() > 64, "{level:?} four_state={four_state}"); + if four_state { + assert_eq!(sim.get_four_state(value).1, 0u8.into()); + } + sim.restore(&checkpoint).unwrap(); + sim.tick(clk).unwrap(); + assert_eq!(sim.get(value), first, "{level:?} four_state={four_state}"); + } + } +} diff --git a/docs/guide/cocotb.md b/docs/guide/cocotb.md index a8e5e399c5e..196f4527c89 100644 --- a/docs/guide/cocotb.md +++ b/docs/guide/cocotb.md @@ -33,8 +33,9 @@ target/release/celox run test/Top.veryl --top Top ``` For SystemVerilog, pass `.sv` or `.v` sources in compilation order. The command -uses two-state simulation by default (`--four-state` enables X/Z tracking) and runs until `$finish` or no scheduled events -remain. For Veryl, pass one project entry file: Celox discovers `Veryl.toml` +uses two-state simulation by default and runs until `$finish` or no scheduled +events remain. Use `--four-state` or `four_state = true` in `celox.toml` to retain +X/Z values. For Veryl, pass one project entry file: Celox discovers `Veryl.toml` and collects the project's sources and dependencies. A standalone Veryl file also works. Both languages default to two-state simulation. Select the native testbench module with `--top`. Veryl uses the existing native testbench executor; a test may also complete by diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index a60253953f4..0d578221e67 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -61,6 +61,19 @@ until shared argument storage and its change notifications are supported. Event expressions have the same restrictions as waits written directly in a process. +### Scope randomization + +`randomize(a, b)` and `std::randomize(a, b)` support unconstrained whole packed +variables, including signed vectors and packed structures, at any supported +width. Each call fills every word with random zero/one bits and returns the +signed `int` success value `1`. An empty argument list succeeds without writing a +variable or advancing the random stream. Calls follow procedural statement order +and short-circuit evaluation, and use the calling process's persistent random +stream (IEEE 1800-2023 18.12). + +Constraints (`with`), class methods, enum variables, unpacked arrays, nets, +constants, selects and concatenation arguments are unsupported and rejected. + ### Time literal delays Standalone delay controls accept time literals such as `#5ns`, `#(2.75ns)` and diff --git a/docs/ja/guide/cocotb.md b/docs/ja/guide/cocotb.md index d0a26bd0fe6..0f37fae4f4b 100644 --- a/docs/ja/guide/cocotb.md +++ b/docs/ja/guide/cocotb.md @@ -30,8 +30,9 @@ target/release/celox run src/types.sv src/Dut.sv test/Top.sv --top Top target/release/celox run test/Top.veryl --top Top ``` -SVは`.sv`または`.v`をコンパイル順に指定します。既定では2値シミュレーションを使い(`--four-state`でX/Zを扱う4値に切り替え)、 +SVは`.sv`または`.v`をコンパイル順に指定します。既定では2値シミュレーションを使い、 `$finish`または実行待ちイベントがなくなるまで実行します。 +X/Zを保持する場合は`--four-state`または`celox.toml`の`four_state = true`を指定します。 Verylはプロジェクト内の1ファイルを指定すると、`Veryl.toml`から ソースと依存関係を収集します。単独のVerylファイルも使用でき、Verylも既定は2値です。 `--top`にはnative testbenchのモジュール名を指定します。 diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 131ffb7deb5..1423954aed7 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -56,6 +56,17 @@ package/`$unit` の static 引数を持つ時間待ち task と、static task 共有ストレージと変更通知に対応するまで拒否します。 イベント式の制約は、プロセスに直接記述するイベント待ちと同じです。 +### スコープ変数の乱数化 + +`randomize(a, b)` と `std::randomize(a, b)` は、制約なしで packed 変数全体を乱数化します。 +符号付きベクタと packed struct を含め、Celox が扱える幅で各ワードに0/1の乱数を設定し、 +成功値の1(signed `int`)を返します。引数なしの場合は変数や乱数列を変更せず成功します。 +プロセスごとの永続的な乱数列を使い、文の実行順序と短絡評価に従います +(IEEE 1800-2023 18.12)。 + +`with` 制約、class メソッド、enum 変数、unpacked 配列、net、定数、 +select・連結式の引数は未対応として拒否します。 + ### 時間リテラルによる遅延 遅延制御の時間リテラルは `#5ns`、`#(2.75ns)`、`#40ps` など、`fs` から `s` の6単位に diff --git a/package.json b/package.json index 44cc4b2a65c..1e8b06ee95e 100644 --- a/package.json +++ b/package.json @@ -21,12 +21,12 @@ }, "devDependencies": { "@biomejs/biome": "^2.4.5", - "@emnapi/core": "2.0.0-alpha.6", - "@emnapi/runtime": "2.0.0-alpha.6", + "@emnapi/core": "2.0.0-beta.1", + "@emnapi/runtime": "2.0.0-beta.1", "@napi-rs/wasm-runtime": "1.2.5", "@tybys/wasm-util": "^0.10.1", "chart.js": "^4.4.0", - "emnapi": "2.0.0-alpha.6", + "emnapi": "2.0.0-beta.1", "lefthook": "^2.1.2", "typedoc": "^0.28.0", "typedoc-plugin-markdown": "^4.4.0", diff --git a/patches/@napi-rs__wasm-runtime@1.2.5.patch b/patches/@napi-rs__wasm-runtime@1.2.5.patch new file mode 100644 index 00000000000..5e09846c82e --- /dev/null +++ b/patches/@napi-rs__wasm-runtime@1.2.5.patch @@ -0,0 +1,68 @@ +diff --git a/runtime.cjs b/runtime.cjs +index 3dc0d9776903bfc21a924f50ddff1def592062a8..b21ae20e5637e6593cf6b62d068ca42fef2cc43f 100644 +--- a/runtime.cjs ++++ b/runtime.cjs +@@ -3,23 +3,11 @@ const { + instantiateNapiModuleSync, + instantiateNapiModule, + } = require('@emnapi/core') +-// Single-threaded (non-shared-memory) WASI builds link an emnapi archive +-// without the C async-work and threadsafe-function implementations (they are +-// unconditional `napi_generic_failure` stubs without threads), so the +-// generated loaders provide the JavaScript implementations through these +-// plugins instead. Raw `instantiateNapiModule(Sync)` callers instantiating a +-// single-threaded napi-rs wasm must pass them too: +-// `plugins: [emnapiAsyncWorkPlugin, emnapiTSFNPlugin]` — without them +-// instantiation fails with a LinkError naming the missing import. Threaded +-// (shared-memory) builds link the C implementations and need no plugins; +-// this mirrors the upstream @emnapi/core v2 plugin split (v1 bundled these +-// implementations in the core runtime). The plugins are bundled into this +-// package so loading the runtime with @emnapi/core v1 does not resolve the +-// v2-only `@emnapi/core/plugins` package export. ++// Celox pins emnapi v2: use plugins matching its internal API. + const { +- emnapiAsyncWorkPlugin, +- emnapiTSFNPlugin, +-} = require('./dist/emnapi-plugins.cjs') ++ asyncWork: emnapiAsyncWorkPlugin, ++ tsfn: emnapiTSFNPlugin, ++} = require('@emnapi/core/plugins') + const { createContext, getDefaultContext } = require('@emnapi/runtime') + const { WASI } = require('@tybys/wasm-util') + +diff --git a/runtime.js b/runtime.js +index 7a727a04460d6fd507bcd5fe8c8bf4e13530ba04..5582340fc5ee937714efe4d05a5b4ac78fcaa8af 100644 +--- a/runtime.js ++++ b/runtime.js +@@ -2,27 +2,15 @@ import * as emnapiCore from '@emnapi/core' + import * as emnapiRuntime from '@emnapi/runtime' + + import { +- emnapiAsyncWorkPlugin, +- emnapiTSFNPlugin, +-} from './dist/emnapi-plugins.js' ++ asyncWork as emnapiAsyncWorkPlugin, ++ tsfn as emnapiTSFNPlugin, ++} from '@emnapi/core/plugins' + + const { instantiateNapiModuleSync, instantiateNapiModule, MessageHandler } = + emnapiCore + const { createContext, getDefaultContext } = emnapiRuntime + +-// Single-threaded (non-shared-memory) WASI builds link an emnapi archive +-// without the C async-work and threadsafe-function implementations (they are +-// unconditional `napi_generic_failure` stubs without threads), so the +-// generated loaders provide the JavaScript implementations through these +-// plugins instead. Raw `instantiateNapiModule(Sync)` callers instantiating a +-// single-threaded napi-rs wasm must pass them too: +-// `plugins: [emnapiAsyncWorkPlugin, emnapiTSFNPlugin]` — without them +-// instantiation fails with a LinkError naming the missing import. Threaded +-// (shared-memory) builds link the C implementations and need no plugins; +-// this mirrors the upstream @emnapi/core v2 plugin split (v1 bundled these +-// implementations in the core runtime). The plugins are bundled into this +-// package so loading the runtime with @emnapi/core v1 does not resolve the +-// v2-only `@emnapi/core/plugins` package export. ++// Celox pins emnapi v2: use plugins matching its internal API. + export { + MessageHandler, + createContext, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 52858b08e42..47c49683fab 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -166,9 +166,12 @@ overrides: '@celox-sim/celox': workspace:* '@celox-sim/celox-napi': workspace:* '@celox-sim/vite-plugin': workspace:* - '@emnapi/core': 2.0.0-alpha.6 - '@emnapi/runtime': 2.0.0-alpha.6 - emnapi: 2.0.0-alpha.6 + '@emnapi/core': 2.0.0-beta.1 + '@emnapi/runtime': 2.0.0-beta.1 + emnapi: 2.0.0-beta.1 + +patchedDependencies: + '@napi-rs/wasm-runtime@1.2.5': 55fd5d25b61174ba200fd92f6cb049e5d2baa68950bd8f903097f783c4f829ce importers: @@ -178,14 +181,14 @@ importers: specifier: ^2.4.5 version: 2.5.15 '@emnapi/core': - specifier: 2.0.0-alpha.6 - version: 2.0.0-alpha.6 + specifier: 2.0.0-beta.1 + version: 2.0.0-beta.1 '@emnapi/runtime': - specifier: 2.0.0-alpha.6 - version: 2.0.0-alpha.6 + specifier: 2.0.0-beta.1 + version: 2.0.0-beta.1 '@napi-rs/wasm-runtime': specifier: 1.2.5 - version: 1.2.5(@emnapi/core@2.0.0-alpha.6)(@emnapi/runtime@2.0.0-alpha.6) + version: 1.2.5(patch_hash=55fd5d25b61174ba200fd92f6cb049e5d2baa68950bd8f903097f783c4f829ce)(@emnapi/core@2.0.0-beta.1)(@emnapi/runtime@2.0.0-beta.1) '@tybys/wasm-util': specifier: ^0.10.1 version: 0.10.4 @@ -193,8 +196,8 @@ importers: specifier: ^4.4.0 version: 4.5.1 emnapi: - specifier: 2.0.0-alpha.6 - version: 2.0.0-alpha.6 + specifier: 2.0.0-beta.1 + version: 2.0.0-beta.1 lefthook: specifier: ^2.1.2 version: 2.2.2 @@ -221,7 +224,7 @@ importers: devDependencies: '@napi-rs/cli': specifier: 3.10.8 - version: 3.10.8(@emnapi/core@2.0.0-alpha.6)(@emnapi/runtime@2.0.0-alpha.6)(@types/node@25.9.9)(emnapi@2.0.0-alpha.6) + version: 3.10.8(@emnapi/core@2.0.0-beta.1)(@emnapi/runtime@2.0.0-beta.1)(@types/node@25.9.9)(emnapi@2.0.0-beta.1) packages/celox: dependencies: @@ -476,11 +479,11 @@ packages: search-insights: optional: true - '@emnapi/core@2.0.0-alpha.6': - resolution: {integrity: sha512-MNVvMV7WtEJMgqaWJMvCyupK7Oi8sZctUIgPRZTsiS3cVvefk8DXPflOU3MSBddtj/rrYHygpYgpHDgwXnI3+w==} + '@emnapi/core@2.0.0-beta.1': + resolution: {integrity: sha512-5E4gwO8qdhoubPxgbs8QvihDap+vjrx8oZUHimGulO2+O3smgEQGBY554Pr3MkoGy2PuvZgrzTzLatekbWWCLQ==} - '@emnapi/runtime@2.0.0-alpha.6': - resolution: {integrity: sha512-5ZR49ZsZ3cLvu5lkrVj6CMpHRgZjYz7XSlqK23GYYpyEqp749RVuIH0bEUKaGNghMh2pXRhIC3cnVrH28Y1j1Q==} + '@emnapi/runtime@2.0.0-beta.1': + resolution: {integrity: sha512-u//q85BwNEBaNK0K4PH/RL9UYgYnAoSAUpD/YtxHkAfcfRLvcpfasTUf+p9xnoQ6EKP74+Am3/zi2Kb00AzGYw==} '@emnapi/wasi-threads@2.2.0': resolution: {integrity: sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==} @@ -790,9 +793,9 @@ packages: engines: {node: ^20.17.0 || ^22.13.0 || >= 23.5.0} hasBin: true peerDependencies: - '@emnapi/core': 2.0.0-alpha.6 - '@emnapi/runtime': 2.0.0-alpha.6 - emnapi: 2.0.0-alpha.6 + '@emnapi/core': 2.0.0-beta.1 + '@emnapi/runtime': 2.0.0-beta.1 + emnapi: 2.0.0-beta.1 peerDependenciesMeta: '@emnapi/core': optional: true @@ -1057,8 +1060,8 @@ packages: resolution: {integrity: sha512-HshSvXzmBxNzqejd3k/KemgQ3hdREUYFRRrgxOZ+gPljDIsO2SDZrVZMd4Z/HsxudQbE62OVyVFE8z9BCurfjA==} engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0} peerDependencies: - '@emnapi/core': 2.0.0-alpha.6 - '@emnapi/runtime': 2.0.0-alpha.6 + '@emnapi/core': 2.0.0-beta.1 + '@emnapi/runtime': 2.0.0-beta.1 '@napi-rs/wasm-tools-android-arm-eabi@1.1.0': resolution: {integrity: sha512-p6J8PB59I8d/XItXB/go5JH6nKW+xIbpzaL43EBTV0hi7mrS/Z4gs+MsB04ZrlqZN29BdZV8fChRyasuXLhRaA==} @@ -1881,8 +1884,8 @@ packages: dompurify@3.4.15: resolution: {integrity: sha512-EUBjM+B+lkDE41iE82DDSCfkoPGfXx8IxFxPMjNzm/Uk4xDet77rTN9wqlxlVg71kK7XGuUMv6wUxJUwwv+Xyw==} - emnapi@2.0.0-alpha.6: - resolution: {integrity: sha512-+A54DE5YkbMVOa/0GDs3jhRmu2KnAFvOjEgAYuaPWdmF7A822PtB2znC23QbQ4l/qcC1ZFOrmvXVIuo9xWX2bg==} + emnapi@2.0.0-beta.1: + resolution: {integrity: sha512-8dyO4NxiqeCGy8DhqRjp675bsmOWs0Mz2LircSLB6sTfAza84u03/VX2S+imD9J1X6k2QJNpYrToi8gApHhafg==} peerDependencies: node-addon-api: '>= 6.1.0' peerDependenciesMeta: @@ -2774,12 +2777,12 @@ snapshots: transitivePeerDependencies: - '@algolia/client-search' - '@emnapi/core@2.0.0-alpha.6': + '@emnapi/core@2.0.0-beta.1': dependencies: '@emnapi/wasi-threads': 2.2.0 tslib: 2.8.1 - '@emnapi/runtime@2.0.0-alpha.6': + '@emnapi/runtime@2.0.0-beta.1': dependencies: tslib: 2.8.1 @@ -3007,7 +3010,7 @@ snapshots: '@kurkle/color@0.3.4': {} - '@napi-rs/cli@3.10.8(@emnapi/core@2.0.0-alpha.6)(@emnapi/runtime@2.0.0-alpha.6)(@types/node@25.9.9)(emnapi@2.0.0-alpha.6)': + '@napi-rs/cli@3.10.8(@emnapi/core@2.0.0-beta.1)(@emnapi/runtime@2.0.0-beta.1)(@types/node@25.9.9)(emnapi@2.0.0-beta.1)': dependencies: '@inquirer/prompts': 8.5.2(@types/node@25.9.9) '@napi-rs/cross-toolchain': 1.0.3 @@ -3022,9 +3025,9 @@ snapshots: typanion: 3.14.0 typescript: 6.0.3 optionalDependencies: - '@emnapi/core': 2.0.0-alpha.6 - '@emnapi/runtime': 2.0.0-alpha.6 - emnapi: 2.0.0-alpha.6 + '@emnapi/core': 2.0.0-beta.1 + '@emnapi/runtime': 2.0.0-beta.1 + emnapi: 2.0.0-beta.1 transitivePeerDependencies: - '@napi-rs/cross-toolchain-arm64-target-aarch64' - '@napi-rs/cross-toolchain-arm64-target-armv7' @@ -3088,9 +3091,9 @@ snapshots: '@napi-rs/lzma-wasm32-wasi@1.5.1': dependencies: - '@emnapi/core': 2.0.0-alpha.6 - '@emnapi/runtime': 2.0.0-alpha.6 - '@napi-rs/wasm-runtime': 1.2.5(@emnapi/core@2.0.0-alpha.6)(@emnapi/runtime@2.0.0-alpha.6) + '@emnapi/core': 2.0.0-beta.1 + '@emnapi/runtime': 2.0.0-beta.1 + '@napi-rs/wasm-runtime': 1.2.5(patch_hash=55fd5d25b61174ba200fd92f6cb049e5d2baa68950bd8f903097f783c4f829ce)(@emnapi/core@2.0.0-beta.1)(@emnapi/runtime@2.0.0-beta.1) optional: true '@napi-rs/lzma-win32-arm64-msvc@1.5.1': @@ -3160,9 +3163,9 @@ snapshots: '@napi-rs/tar-wasm32-wasi@1.1.1': dependencies: - '@emnapi/core': 2.0.0-alpha.6 - '@emnapi/runtime': 2.0.0-alpha.6 - '@napi-rs/wasm-runtime': 1.2.5(@emnapi/core@2.0.0-alpha.6)(@emnapi/runtime@2.0.0-alpha.6) + '@emnapi/core': 2.0.0-beta.1 + '@emnapi/runtime': 2.0.0-beta.1 + '@napi-rs/wasm-runtime': 1.2.5(patch_hash=55fd5d25b61174ba200fd92f6cb049e5d2baa68950bd8f903097f783c4f829ce)(@emnapi/core@2.0.0-beta.1)(@emnapi/runtime@2.0.0-beta.1) optional: true '@napi-rs/tar-win32-arm64-msvc@1.1.1': @@ -3193,10 +3196,10 @@ snapshots: '@napi-rs/tar-win32-ia32-msvc': 1.1.1 '@napi-rs/tar-win32-x64-msvc': 1.1.1 - '@napi-rs/wasm-runtime@1.2.5(@emnapi/core@2.0.0-alpha.6)(@emnapi/runtime@2.0.0-alpha.6)': + '@napi-rs/wasm-runtime@1.2.5(patch_hash=55fd5d25b61174ba200fd92f6cb049e5d2baa68950bd8f903097f783c4f829ce)(@emnapi/core@2.0.0-beta.1)(@emnapi/runtime@2.0.0-beta.1)': dependencies: - '@emnapi/core': 2.0.0-alpha.6 - '@emnapi/runtime': 2.0.0-alpha.6 + '@emnapi/core': 2.0.0-beta.1 + '@emnapi/runtime': 2.0.0-beta.1 '@tybys/wasm-util': 0.10.4 '@napi-rs/wasm-tools-android-arm-eabi@1.1.0': @@ -3228,9 +3231,9 @@ snapshots: '@napi-rs/wasm-tools-wasm32-wasi@1.1.0': dependencies: - '@emnapi/core': 2.0.0-alpha.6 - '@emnapi/runtime': 2.0.0-alpha.6 - '@napi-rs/wasm-runtime': 1.2.5(@emnapi/core@2.0.0-alpha.6)(@emnapi/runtime@2.0.0-alpha.6) + '@emnapi/core': 2.0.0-beta.1 + '@emnapi/runtime': 2.0.0-beta.1 + '@napi-rs/wasm-runtime': 1.2.5(patch_hash=55fd5d25b61174ba200fd92f6cb049e5d2baa68950bd8f903097f783c4f829ce)(@emnapi/core@2.0.0-beta.1)(@emnapi/runtime@2.0.0-beta.1) optional: true '@napi-rs/wasm-tools-win32-arm64-msvc@1.1.0': @@ -3850,7 +3853,7 @@ snapshots: optionalDependencies: '@types/trusted-types': 2.0.7 - emnapi@2.0.0-alpha.6: {} + emnapi@2.0.0-beta.1: {} emoji-regex-xs@1.0.0: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 9828b1a3469..a9c4b693c5e 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -5,9 +5,9 @@ overrides: "@celox-sim/celox": "workspace:*" "@celox-sim/celox-napi": "workspace:*" "@celox-sim/vite-plugin": "workspace:*" - "@emnapi/core": "2.0.0-alpha.6" - "@emnapi/runtime": "2.0.0-alpha.6" - emnapi: "2.0.0-alpha.6" + "@emnapi/core": "2.0.0-beta.1" + "@emnapi/runtime": "2.0.0-beta.1" + emnapi: "2.0.0-beta.1" allowBuilds: esbuild: true lefthook: true @@ -34,3 +34,8 @@ minimumReleaseAgeExclude: - "@rolldown/binding-win32-arm64-msvc@1.2.13" - "@rolldown/binding-openharmony-arm64@1.2.13" - "@rolldown/binding-linux-arm-gnueabihf@1.2.13" +patchedDependencies: + # 1.2.5 bundles alpha-era plugins that access napiModule; beta.1 uses + # addonModule internally. Load the pinned core's own plugins in both formats. + # Remove when wasm-runtime ships compatible plugins (regression: emnapi-compatibility.test.mjs). + '@napi-rs/wasm-runtime@1.2.5': patches/@napi-rs__wasm-runtime@1.2.5.patch diff --git a/scripts/emnapi-compatibility.test.mjs b/scripts/emnapi-compatibility.test.mjs new file mode 100644 index 00000000000..ee8b1617f15 --- /dev/null +++ b/scripts/emnapi-compatibility.test.mjs @@ -0,0 +1,27 @@ +import assert from "node:assert/strict"; +import { createRequire } from "node:module"; +import test from "node:test"; +import { createAddonModule } from "@emnapi/core"; + +const require = createRequire(import.meta.url); + +for (const format of ["import", "require"]) { + test(`emnapi plugins initialize with the installed core (${format})`, async () => { + const runtime = + format === "import" + ? await import("@napi-rs/wasm-runtime") + : require("@napi-rs/wasm-runtime"); + // Exercise plugin initialization without compiling a WASM addon. A stale + // bundled plugin fails here when emnapi changes its internal module API. + const addon = createAddonModule({ + context: runtime.createContext(), + plugins: [runtime.emnapiAsyncWorkPlugin, runtime.emnapiTSFNPlugin], + }); + assert.equal(typeof addon.initWorker, "function"); + assert.equal(typeof addon.imports.napi.napi_create_async_work, "function"); + assert.equal( + typeof addon.imports.napi.napi_create_threadsafe_function, + "function", + ); + }); +} diff --git a/scripts/run-common-cells.mjs b/scripts/run-common-cells.mjs index ca6bb5333f8..c6e4d3ca0cb 100644 --- a/scripts/run-common-cells.mjs +++ b/scripts/run-common-cells.mjs @@ -22,18 +22,19 @@ export function run({ source, celox, output }) { if (head.status !== 0 || head.stdout.trim() !== revision) { throw new Error(`Expected common_cells revision ${revision}; fetch the pinned checkout first`); } - const manifest = (files) => `sources = [${files.map((file) => JSON.stringify(file)).join(", ")}]\ntop = "cc_graycode_tb"\n`; + const manifest = (files, top = "cc_graycode_tb") => `sources = [${files.map((file) => JSON.stringify(file)).join(", ")}]\ntop = ${JSON.stringify(top)}\n`; const original = sources.map((file) => join(source, file)); const project = join(output, "celox.toml"); writeFileSync(project, manifest(original)); - const execute = (name, projectFile, negative = false) => { + const execute = (name, projectFile, negative = false, diagnostic = "assert failed") => { const result = spawnSync(celox, ["run", "--project", projectFile], { encoding: "utf8", timeout: 120_000, maxBuffer: 8 * 1024 * 1024, }); const log = `${result.stdout ?? ""}${result.stderr ?? ""}`; writeFileSync(join(output, `${name}.log`), log); if (result.error || result.signal || (negative - ? result.status !== 1 || !log.includes("assert failed") + ? result.status !== 1 || !log.includes(diagnostic) + || !log.includes("SystemVerilog testbench reported an assertion failure or $error") : result.status !== 0)) { throw new Error(`${name} failed (exit ${result.status}, signal ${result.signal}): ${result.error ?? log}`); } @@ -49,10 +50,25 @@ export function run({ source, celox, output }) { const negativeProject = join(output, "negative.toml"); writeFileSync(negativeProject, manifest([broken, ...original.slice(1)])); execute("graycode-negative", negativeProject, true); + const popcount = join(source, "src/cc_popcount.sv"); + const popcountTb = join(source, "test/cc_popcount_tb.sv"); + const popcountProject = join(output, "popcount.toml"); + writeFileSync(popcountProject, manifest([popcount, popcountTb], "cc_popcount_tb")); + execute("popcount", popcountProject); + + const popcountText = readFileSync(popcount, "utf8"); + const increment = "popcount_o += data_i[i];"; + if (popcountText.split(increment).length !== 2) throw new Error("Cannot locate the pinned popcount accumulation"); + const brokenPopcount = join(output, "negative_popcount.sv"); + writeFileSync(brokenPopcount, popcountText.replace(increment, "popcount_o += 0;")); + const negativePopcountProject = join(output, "popcount-negative.toml"); + writeFileSync(negativePopcountProject, manifest([brokenPopcount, popcountTb], "cc_popcount_tb")); + execute("popcount-negative", negativePopcountProject, true, "Popcount of"); writeFileSync(join(output, "result.json"), `${JSON.stringify({ revision, top: "cc_graycode_tb", positive: "passed", negative: "assertion failure detected", + testbenches: ["cc_graycode_tb", "cc_popcount_tb"], }, null, 2)}\n`); - console.log(`common_cells ${revision}: upstream Gray code TB passed; broken RTL rejected`); + console.log(`common_cells ${revision}: upstream Gray code and popcount TBs passed; both broken RTL copies rejected`); } if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { diff --git a/scripts/run-common-cells.test.mjs b/scripts/run-common-cells.test.mjs index 35948733316..6614de22602 100644 --- a/scripts/run-common-cells.test.mjs +++ b/scripts/run-common-cells.test.mjs @@ -18,20 +18,28 @@ test("upstream gate rejects wrong revisions, broken positives, and false negativ writeFileSync(join(source, "src/cc_binary_to_gray.sv"), original); writeFileSync(join(source, "src/cc_gray_to_binary.sv"), ""); writeFileSync(join(source, "test/cc_graycode_tb.sv"), ""); + const popcountOriginal = "popcount_o += data_i[i];"; + writeFileSync(join(source, "src/cc_popcount.sv"), popcountOriginal); + writeFileSync(join(source, "test/cc_popcount_tb.sv"), ""); writeFileSync(join(bin, "git"), `#!/usr/bin/env node\nconsole.log(process.env.TEST_REVISION || ${JSON.stringify(revision)});\n`); const celox = join(bin, "celox"); writeFileSync(celox, `#!/usr/bin/env node const negative = process.argv.at(-1).endsWith("negative.toml"); const mode = process.env.TEST_MODE; +const popcount = process.argv.at(-1).endsWith("popcount.toml") || process.argv.at(-1).endsWith("popcount-negative.toml"); +if (popcount && mode === "popcount-positive-failure" && !negative) process.exit(1); +if (popcount && mode === "popcount-false-pass" && negative) process.exit(0); if (!negative) process.exit(mode === "positive-failure" ? 1 : 0); if (mode === "false-pass") process.exit(0); if (mode === "compile-error") { console.error("compilation failed"); process.exit(1); } +if (mode === "quoted-compile-error") { console.error("compilation failed: source contains assert failed / Popcount of"); process.exit(1); } if (mode === "crash") { process.kill(process.pid, "SIGTERM"); } -console.error("assert failed"); process.exit(1); +console.error(popcount ? "Popcount of 1 was 0 but should be 1" : "assert failed"); +console.error("SystemVerilog testbench reported an assertion failure or $error"); process.exit(1); `); chmodSync(join(bin, "git"), 0o755); chmodSync(celox, 0o755); - for (const mode of ["success", "positive-failure", "false-pass", "compile-error", "crash", "wrong-revision"]) { + for (const mode of ["success", "positive-failure", "false-pass", "compile-error", "quoted-compile-error", "crash", "wrong-revision", "popcount-positive-failure", "popcount-false-pass"]) { const output = join(root, mode); const result = spawnSync(process.execPath, [resolve("scripts/run-common-cells.mjs"), source, celox, output], { encoding: "utf8", @@ -40,11 +48,15 @@ console.error("assert failed"); process.exit(1); }); assert.equal(result.status, mode === "success" ? 0 : 1, `${mode}: ${result.stderr}`); if (mode === "success") { - assert.equal(JSON.parse(readFileSync(join(output, "result.json"))).positive, "passed"); + const report = JSON.parse(readFileSync(join(output, "result.json"))); + assert.equal(report.positive, "passed"); + assert.deepEqual(report.testbenches, ["cc_graycode_tb", "cc_popcount_tb"]); + assert.match(readFileSync(join(output, "popcount-negative.log"), "utf8"), /Popcount of/); assert.match(readFileSync(join(output, "graycode-negative.log"), "utf8"), /assert failed/); } } assert.equal(readFileSync(join(source, "src/cc_binary_to_gray.sv"), "utf8"), original); + assert.equal(readFileSync(join(source, "src/cc_popcount.sv"), "utf8"), popcountOriginal); } finally { rmSync(root, { recursive: true, force: true }); }