From 728b37de1105d3a419a51a4376026517cd38dfc7 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 26 Oct 2026 05:13:48 +0900 Subject: [PATCH 1/2] fix(sv): validate enum initializer declarations Reject sized enum literals whose width differs from the base, X/Z values without an explicit four-state base, and implicit successors of X/Z values as required by IEEE 1800-2023 6.19. Preserve masks across references to preceding members and allow expressions that resolve to known values. Defer typedef validation until enum constants and dependent aliases resolve. Keep inline declarations checked when their types are bound. Leave ranged member expansion to the existing unsupported path instead of guessing values. Update the three affected sv-tests cases in both state modes. Validation: all analyzer tests (811 passed, 3 existing ignored), 2 doctests, combined analyzer tests (814 passed, 3 ignored), all-target Clippy and fmt. Full release-driver sv-tests validation runs in CI as requested. Change-Id: I71ba3443f34b307ef6a424decec09ef01881948d --- conformance/sv-tests/expected.tsv | 12 +- .../celox-sv-analyzer/src/ast/parameters.rs | 19 ++- .../celox-sv-analyzer/src/ast/type_binding.rs | 2 +- .../src/ast/type_binding/binding.rs | 155 ++++++++++++++++++ crates/celox-sv-analyzer/src/tests.rs | 72 ++++++++ .../systemverilog/review_regressions.rs | 19 ++- 6 files changed, 264 insertions(+), 15 deletions(-) diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index b4e64f909ce..3560aabeea7 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1153,14 +1153,14 @@ chapter-6/6.18--typedef.sv 2state pass chapter-6/6.18--typedef.sv 4state pass chapter-6/6.19--enum_anon.sv 2state pass chapter-6/6.19--enum_anon.sv 4state pass -chapter-6/6.19--enum_value_inv.sv 2state fail -chapter-6/6.19--enum_value_inv.sv 4state fail +chapter-6/6.19--enum_value_inv.sv 2state pass +chapter-6/6.19--enum_value_inv.sv 4state pass chapter-6/6.19--enum_xx.sv 2state pass chapter-6/6.19--enum_xx.sv 4state pass -chapter-6/6.19--enum_xx_inv.sv 2state fail -chapter-6/6.19--enum_xx_inv.sv 4state fail -chapter-6/6.19--enum_xx_inv_order.sv 2state fail -chapter-6/6.19--enum_xx_inv_order.sv 4state fail +chapter-6/6.19--enum_xx_inv.sv 2state pass +chapter-6/6.19--enum_xx_inv.sv 4state pass +chapter-6/6.19--enum_xx_inv_order.sv 2state pass +chapter-6/6.19--enum_xx_inv_order.sv 4state pass chapter-6/6.19.1--enum_typedef.sv 2state pass chapter-6/6.19.1--enum_typedef.sv 4state pass chapter-6/6.19.2--enum_sequence.sv 2state pass diff --git a/crates/celox-sv-analyzer/src/ast/parameters.rs b/crates/celox-sv-analyzer/src/ast/parameters.rs index d27f1403a84..250465ada6c 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters.rs @@ -1046,20 +1046,25 @@ pub(super) fn enum_member_constants_from_items( let DataTypeKind::Enum { base, items } = &native.data_type(id).kind else { unreachable!(); }; - let member_type = match base { + let member_base = match base { Some(id) => type_binding::enum_constant_base( *id, syntax_tree, &eval_env, &resolved_type_aliases, - )? - .and_then(|ty| expr_type_from_type(&syntax_tree.state, &ty, &eval_env)), - None => Some(ExprType { - width: 32, - signed: true, - }), + )?, + None => type_binding::builtin_type("int", None), } .ok_or_else(|| unsupported("enum base type"))?; + type_binding::binding::validate_enum_initializers( + id, + native, + syntax_tree, + &PackedDimensions::new(HashMap::default(), &eval_env, &resolved_type_aliases), + &member_base, + )?; + let member_type = expr_type_from_type(&syntax_tree.state, &member_base, &eval_env) + .ok_or_else(|| unsupported("enum base type"))?; let mut next_enum_value = 0i128; for new in items { let name = instances::normalize_identifier(&new.name.spelling); diff --git a/crates/celox-sv-analyzer/src/ast/type_binding.rs b/crates/celox-sv-analyzer/src/ast/type_binding.rs index 419dad7b2bd..5d2ecd8d7ef 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding.rs @@ -250,7 +250,7 @@ pub(super) fn alias_base_type( return Ok(None); } let context = PackedDimensions::new(HashMap::default(), env, aliases); - binding::bind_in(id, native, tree, &context) + binding::bind_alias_in(id, native, tree, &context) } /// Builtin integral identity/width without syntax or aggregate layout. 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 6d152b61b19..9f0fe4aa2be 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs @@ -15,6 +15,27 @@ pub(in crate::ast) fn bind_in( native: &celox_sv_syntax::Declarations, tree: &AnalysisContext<'_>, context: &PackedDimensions, +) -> Converted> { + bind_in_with_validation(root, native, tree, context, true) +} + +/// Typedef discovery precedes enum constant resolution, so dependent aliases +/// may still have provisional widths. Validate them when collecting members. +pub(in crate::ast) fn bind_alias_in( + root: TypeId, + native: &celox_sv_syntax::Declarations, + tree: &AnalysisContext<'_>, + context: &PackedDimensions, +) -> Converted> { + bind_in_with_validation(root, native, tree, context, false) +} + +fn bind_in_with_validation( + root: TypeId, + native: &celox_sv_syntax::Declarations, + tree: &AnalysisContext<'_>, + context: &PackedDimensions, + validate_enums: bool, ) -> Converted> { enum Job { Enter(TypeId), @@ -88,6 +109,9 @@ pub(in crate::ast) fn bind_in( } else { let mut ty = builtin_type("int", None).unwrap(); ty.is_enum = true; + if validate_enums { + validate_enum_initializers(id, native, tree, context, &ty)?; + } ty.enum_values = enum_values(id, native, tree, context, &ty); ty.packed_ranges = ranges.into_iter().chain(ty.packed_ranges).collect(); values.push(ty); @@ -182,6 +206,9 @@ pub(in crate::ast) fn bind_in( let Some(mut ty) = values.pop() else { return Err(unsupported("enum base type")); }; + if validate_enums { + validate_enum_initializers(id, native, tree, context, &ty)?; + } let mut outer = ranges; outer.extend(ty.packed_ranges); ty.packed_ranges = outer; @@ -317,6 +344,134 @@ pub(in crate::ast) fn expression_type( Ok(dimensions::bound_bits_type(&tree.state, &value, &query)) } +/// IEEE 1800-2023 6.19 imposes declaration rules even when no enum member +/// is used. Keep these checks separate from best-effort randomization metadata. +pub(in crate::ast) fn validate_enum_initializers( + id: TypeId, + native: &celox_sv_syntax::Declarations, + tree: &AnalysisContext<'_>, + context: &PackedDimensions, + ty: &Type, +) -> Converted<()> { + let DataTypeKind::Enum { base, items } = &native.data_type(id).kind else { + return Ok(()); + }; + let Some(shape) = casts::expr_type_from_type(&tree.state, ty, &context.const_env) else { + return Ok(()); + }; + let mut env = context.const_env.clone(); + let mut unknown_literals = HashMap::default(); + let mut previous_unknown = false; + let mut next = Some(0i128); + for item in items { + let name = normalize_identifier(&item.name.spelling); + let Some(value) = item.value else { + if previous_unknown { + return Err(unsupported(format!( + "enum member `{name}` cannot implicitly increment an X/Z value" + ))); + } + if !item.dimensions.is_empty() { + next = None; + continue; + } + if let Some(value) = next { + env.insert(name.clone(), value); + dimensions::insert_parameter_type_markers(&mut env, &name, shape); + next = value.checked_add(1); + } + continue; + }; + // Check authored syntax, not a folded expression: a parameter, cast, + // or arithmetic expression is not a sized literal constant. + let mut literal_id = value; + while let ExprKind::Group(inner) = native.expression(literal_id).kind { + literal_id = inner; + } + if let ExprKind::Literal(text) = &native.expression(literal_id).kind + && let Some((size, _)) = text.split_once('\'') + && !size.is_empty() + && let Ok(width) = size.replace('_', "").parse::() + && width != shape.width + { + return Err(unsupported(format!( + "enum member `{name}` sized literal width {width} differs from base width {}", + shape.width + ))); + } + // During signature discovery some constants are still unresolved. + // Leave their resolution to the ordinary constant-binding pass. + let expr = constant_binding::expression(value, native, tree, &env, &context.type_aliases) + .ok() + .flatten() + .and_then(|expr| { + expr_to_const( + &tree.state, + constants::substitute_expr_constants_with_parameter_literals( + &tree.state, + const_expr_to_expr(expr), + &env, + &unknown_literals, + ), + ) + }); + let expr = expr.map(|expr| match expr { + ConstExpr::Literal(text) => ConstExpr::Literal( + resize_unbased_fill_literal_for_cast(&text, shape.width, shape.signed) + .unwrap_or(text), + ), + expr => expr, + }); + let literal = expr.as_ref().and_then(|expr| { + typecheck::eval_const_integral_literal_with_lookup( + &expr.clone().into(), + &env, + &|name| { + dimensions::parameter_type_from_const_env(&env, name) + .map(|ty| (ty.width, ty.signed)) + }, + ) + }); + previous_unknown = literal + .as_ref() + .is_some_and(|value| value.mask != Default::default()); + if previous_unknown && (base.is_none() || ty.kind == TypeKind::Bit) { + return Err(unsupported(format!( + "enum member `{name}` X/Z value requires an explicit four-state base type" + ))); + } + if !item.dimensions.is_empty() { + next = None; + continue; + } + if previous_unknown { + // Preserve masks when a later enumerator refers to this member. + // Numeric constant environments cannot represent X/Z values. + unknown_literals.insert( + name.clone(), + Expr::Literal(resize_integral_literal_for_cast( + literal.unwrap(), + shape.width, + shape.signed, + )), + ); + env.remove(&name); + } + next = expr + .as_ref() + .and_then(|expr| eval_ast_const_expr(&tree.state, expr, &env)) + .map(|value| { + parameters::coerce_const_parameter_value(value, shape.width, shape.signed) + }); + if let Some(value) = next { + env.insert(name.clone(), value); + dimensions::insert_parameter_type_markers(&mut env, &name, shape); + next = value.checked_add(1); + } + } + Ok(()) +} + /// Domain metadata is best-effort during signature discovery. Only a caller /// requesting randomization requires a resolved domain; unused types must not /// start reporting new errors merely because this metadata is collected. diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index 5c6a2c29d8c..c9385650f3d 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -6959,3 +6959,75 @@ fn class_visibility_checks_constructors() { } } } + +#[test] +fn rejects_invalid_enum_declaration_initializers() { + for (declaration, diagnostic) in [ + ( + "enum logic [2:0] { Global = 4'h2, Local = 4'h3 } value;", + "sized literal width 4 differs from base width 3", + ), + ( + "typedef enum logic [2:0] { A = 2'b01 } E;", + "sized literal width 2 differs from base width 3", + ), + ( + "enum bit [1:0] { a=0, b=2'bxx, c=1 } value;", + "X/Z value requires an explicit four-state base type", + ), + ( + "enum { a='z } value;", + "X/Z value requires an explicit four-state base type", + ), + ( + "typedef bit [1:0] B; enum B { a=2'b0z } value;", + "X/Z value requires an explicit four-state base type", + ), + ( + "enum integer { a=0, b={32{1'bx}}, c } value;", + "cannot implicitly increment an X/Z value", + ), + ( + "enum logic [1:0] { a='z, b } value;", + "cannot implicitly increment an X/Z value", + ), + ( + "enum logic [1:0] { a=2'bxx, b=a, c } value;", + "cannot implicitly increment an X/Z value", + ), + ( + "enum logic [1:0] { a='x, b=a | 2'b00, c } value;", + "cannot implicitly increment an X/Z value", + ), + ] { + let source = format!("module Top; {declaration} endmodule"); + let error = + analyze_source(&source, Path::new("invalid_enum_initializers.sv")).expect_err(&source); + assert!(error.to_string().contains(diagnostic), "{source}: {error}"); + } +} + +#[test] +fn preserves_legal_enum_declaration_initializers() { + for declaration in [ + "enum logic [2:0] { A=3'h2, B=3'h3 } value;", + "enum bit [3:0] { bronze='h3, silver, gold='h5 } value;", + "enum logic [3:0] { A='1 } value;", + "enum integer { a=0, b={32{1'bx}}, c=1, d } value;", + "enum logic [1:0] { a=2'bxx, b=2'bzz, c=0 } value;", + "enum bit [1:0] { a=(2'bxx & 2'b00), b } value;", + "enum logic [1:0] { a=2'bxx, b=2'b01, c } value;", + "enum logic [1:0] { a=2'bxx, b=a & 2'b00, c } value;", + "localparam P=4'h2; enum logic [2:0] { A=P, B=4'h1+1 } value;", + "enum logic [2:0] { A=3'(4'h2) } value;", + "enum logic [2:0] { A=3'h2 } value [2];", + "typedef enum int { W=3 } E; typedef logic [W'(2):0] B; enum B { A=3'b101 } value;", + "localparam W=3; enum logic [W-1:0] { A=3'b101 } value;", + "enum logic [2:0] { A=3'h2 } [1:0] value;", + "typedef enum logic signed [1:0] { A=2'b10, B } E;", + ] { + let source = format!("module Top; {declaration} endmodule"); + analyze_source(&source, Path::new("valid_enum_initializers.sv")) + .unwrap_or_else(|error| panic!("{source}: {error}")); + } +} diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index 92ffc36ceb1..5ad82945518 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -4185,7 +4185,7 @@ fn rejects_enum_initializers_that_do_not_fit_the_base_type() { let error = cranelift_build_error( r#" module Top(output logic [1:0] y); - typedef enum logic [1:0] { A = 3'd4 } E; + typedef enum logic [1:0] { A = 4 } E; assign y = A; endmodule "#, @@ -4196,6 +4196,23 @@ fn rejects_enum_initializers_that_do_not_fit_the_base_type() { ); } +#[test] +fn rejects_enum_literals_with_mismatched_explicit_widths() { + let error = cranelift_build_error( + r#" + module Top(output logic [1:0] y); + typedef enum logic [1:0] { A = 3'd1 } E; + assign y = A; + endmodule + "#, + ); + // The value fits, but an explicitly sized literal must match the enum base. + assert!( + error.contains("enum member `A` sized literal width 3 differs from base width 2"), + "unexpected error: {error}" + ); +} + #[test] fn preserves_masked_parameter_guards_before_latch_detection() { let source = r#" From 5cc033c38444c32a927fcf7c24bc906a401be5f8 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 26 Oct 2026 05:14:04 +0900 Subject: [PATCH 2/2] fix(sv)!: read heap strings in formatted scans $sscanf read string handles as packed bytes, so a string source such as "1234" failed to populate its integer destination. Carry ValueKind in host request operands and use it for both GC roots and host string resolution. Support string expressions for the source and for $sscanf/$fscanf formats while retaining packed input behavior (IEEE 1800-2023 21.3.4.3). Add shared regressions for discarded returns, temporary strings, dynamic formats and empty input. Update the affected sv-tests case in both modes. Version the native image container at 38 and reject old images before postcard decoding; test both new scan cases through native-image roundtrips. Validation: 30 shared scan backend tests, 8 API tests, 2 metadata tests, 5 configurations of the final temporary-string case, native-image roundtrip and old-version rejection, Clippy and fmt. Verilator and Icarus each pass the string-source case. The dynamic-format case is a documented external limitation: Verilator rejects it and Icarus crashes even with a variable-only format. Keep it enabled for Celox and retain the observed external evidence. Full release-driver sv-tests validation runs in CI as requested. BREAKING CHANGE: HostRequestValue requires value_kind in Rust struct literals. Native program images from container version 37 and earlier must be rebuilt. Change-Id: I982978c1d365c983441526595dd3cb454cae718a --- conformance/sv-tests/expected.tsv | 4 +- crates/celox-design/src/lib.rs | 6 +++ crates/celox-frontend-sv/src/lowering/ff.rs | 5 ++ .../src/lowering/ff/file_io.rs | 3 ++ .../src/lowering/ff/fread.rs | 2 + .../celox-frontend-sv/src/lowering/ff/scan.rs | 26 ++++++++-- crates/celox-test-suite/LIMITATIONS.md | 11 +++++ .../celox-test-suite/src/sv/cases/scan.vtest | 49 +++++++++++++++++++ .../verification/sv/icarus.json | 1 + .../verification/sv/icarus/scan.json | 27 ++++++++++ .../verification/sv/limitations.json | 34 +++++++++++++ .../scan-string-format-icarus.json | 12 +++++ .../scan-string-format-verilator.json | 10 ++++ .../verification/sv/verilator.json | 1 + .../verification/sv/verilator/scan.json | 27 ++++++++++ crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/simulator/host/scan.rs | 46 ++++++++++++----- .../tests/frontends/systemverilog/scan.rs | 13 +++++ crates/celox/tests/shared_jit_cache.rs | 19 +++++++ crates/celox/tests/sv_scan.rs | 7 +-- 20 files changed, 285 insertions(+), 20 deletions(-) create mode 100644 crates/celox-test-suite/verification/sv/icarus/scan.json create mode 100644 crates/celox-test-suite/verification/sv/limitations/scan-string-format-icarus.json create mode 100644 crates/celox-test-suite/verification/sv/limitations/scan-string-format-verilator.json create mode 100644 crates/celox-test-suite/verification/sv/verilator/scan.json diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index 3560aabeea7..fd3c5c5909b 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -807,8 +807,8 @@ chapter-21/21.3--fwrite-boh.sv 2state fail chapter-21/21.3--fwrite-boh.sv 4state fail chapter-21/21.3--fwrite.sv 2state fail chapter-21/21.3--fwrite.sv 4state fail -chapter-21/21.3--sscanf.sv 2state fail -chapter-21/21.3--sscanf.sv 4state fail +chapter-21/21.3--sscanf.sv 2state pass +chapter-21/21.3--sscanf.sv 4state pass chapter-21/21.3--ungetc.sv 2state fail chapter-21/21.3--ungetc.sv 4state fail chapter-21/21.4--readmemb.sv 2state pass diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 8e81e66f936..7294c286a4e 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -536,6 +536,9 @@ pub struct HostRequestValue { pub width: usize, pub signed: bool, pub is_string: bool, + /// The payload representation, independent of display formatting. + #[serde(default)] + pub value_kind: ValueKind, #[serde(default)] pub float_precision: Option, } @@ -543,6 +546,7 @@ pub struct HostRequestValue { impl HostRequestValue { pub fn map(&self, map: &mut impl FnMut(A) -> B) -> HostRequestValue { HostRequestValue { + value_kind: self.value_kind, id: map(self.id), width: self.width, signed: self.signed, @@ -2032,6 +2036,7 @@ mod tests { #[test] fn host_request_mapping_relocates_operands_and_results() { let value = |id| HostRequestValue { + value_kind: ValueKind::StrRef, id, width: 17, signed: true, @@ -2051,6 +2056,7 @@ mod tests { assert_eq!(relocated.process, 2); assert_eq!(relocated.args[0].width, 17); assert!(relocated.results[0].signed); + assert_eq!(relocated.args[0].value_kind, ValueKind::StrRef); assert_eq!(relocated.strings, site.strings); } diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 3dc8a09386f..f4729eccf3e 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -1524,6 +1524,7 @@ impl<'p, 'a> Ff<'p, 'a> { let (id, _) = self.m.temp("vcd_argument", width, signed, is_4state); self.store(id, SIROffset::Static(0), width, reg); values.push(HostRequestValue { + value_kind: celox_design::ValueKind::Bits, float_precision: None, id, width, @@ -2221,6 +2222,7 @@ impl<'p, 'a> Ff<'p, 'a> { let (seed_id, seed_result) = self.host_hidden("distribution_seed", &formal, 32, true, true)?; let value = |id| HostRequestValue { + value_kind: celox_design::ValueKind::Bits, float_precision: None, id, width: 32, @@ -2288,6 +2290,7 @@ impl<'p, 'a> Ff<'p, 'a> { let mut results = Vec::new(); let (ret_id, ret_name) = self.m.temp("plusargs_result", 32, true, false); results.push(HostRequestValue { + value_kind: celox_design::ValueKind::Bits, float_precision: None, id: ret_id, width: 32, @@ -2306,6 +2309,7 @@ impl<'p, 'a> Ff<'p, 'a> { .ok_or_else(|| unsupported("integral plusargs destination"))?; let (id, result) = self.host_hidden("plusargs_value", &captured, width, false, true)?; results.push(HostRequestValue { + value_kind: celox_design::ValueKind::Bits, float_precision: None, id, width, @@ -2326,6 +2330,7 @@ impl<'p, 'a> Ff<'p, 'a> { kind: HostRequestKind::Plusargs, operation: u32::from(value_query), args: vec![HostRequestValue { + value_kind: celox_design::ValueKind::Bits, float_precision: None, id: query_id, width, diff --git a/crates/celox-frontend-sv/src/lowering/ff/file_io.rs b/crates/celox-frontend-sv/src/lowering/ff/file_io.rs index 5cfba9fda9b..a5a98d1fa45 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/file_io.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/file_io.rs @@ -37,6 +37,7 @@ impl Ff<'_, '_> { let (id, _) = self.m.temp("file_arg", width, signed, four_state); self.store(id, SIROffset::Static(0), width, reg); Ok(HostRequestValue { + value_kind: celox_design::ValueKind::Bits, id, width, signed, @@ -101,6 +102,7 @@ impl Ff<'_, '_> { 0, values, vec![HostRequestValue { + value_kind: celox_design::ValueKind::Bits, id, width: 32, signed: false, @@ -151,6 +153,7 @@ impl Ff<'_, '_> { operation, values, vec![HostRequestValue { + value_kind: celox_design::ValueKind::Bits, float_precision: None, id, width: 32, diff --git a/crates/celox-frontend-sv/src/lowering/ff/fread.rs b/crates/celox-frontend-sv/src/lowering/ff/fread.rs index 876a884d5ae..1307e26f568 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/fread.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/fread.rs @@ -61,6 +61,7 @@ impl Ff<'_, '_> { values, vec![ HostRequestValue { + value_kind: celox_design::ValueKind::Bits, float_precision: None, id: result_id, width: 32, @@ -68,6 +69,7 @@ impl Ff<'_, '_> { is_string: false, }, HostRequestValue { + value_kind: celox_design::ValueKind::Bits, float_precision: None, id: data_id, width, diff --git a/crates/celox-frontend-sv/src/lowering/ff/scan.rs b/crates/celox-frontend-sv/src/lowering/ff/scan.rs index dc5629469f8..bbef896b24d 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/scan.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/scan.rs @@ -1,5 +1,5 @@ use super::*; -use celox_design::{HostRequestKind, HostRequestSite, HostRequestValue}; +use celox_design::{HostRequestKind, HostRequestSite, HostRequestValue, ValueKind}; impl Ff<'_, '_> { pub(super) fn scan_function( @@ -24,7 +24,7 @@ impl Ff<'_, '_> { .m .comparison_width(&argument, &argument) .ok_or_else(|| { - unsupported("scan source/format must be a packed integral or literal string") + unsupported("scan source/format must be a packed integral or string") })?; // File descriptors are 32-bit packed values (21.3.1), even when // the actual expression has a wider integral type. @@ -33,8 +33,26 @@ impl Ff<'_, '_> { } else { width }; - let (id, _) = self.host_hidden("scan_input", &argument, width, false, true)?; + let value_kind = if self.m.expr_is_string(&argument) { + ValueKind::StrRef + } else { + ValueKind::Bits + }; + let (id, _) = self.host_hidden( + "scan_input", + &argument, + width, + false, + value_kind == ValueKind::Bits, + )?; + // Keep captured strings rooted across the host-request suspension. + self.m + .variables + .get_mut(&id) + .expect("scan input") + .value_kind = value_kind; inputs.push(HostRequestValue { + value_kind, float_precision: None, id, width, @@ -44,6 +62,7 @@ impl Ff<'_, '_> { } let (result_id, result_name) = self.m.temp("scan_count", 32, true, false); let mut results = vec![HostRequestValue { + value_kind: ValueKind::Bits, float_precision: None, id: result_id, width: 32, @@ -70,6 +89,7 @@ impl Ff<'_, '_> { let (id, name) = self.m.temp("scan_value", width, false, precision.is_none()); self.m.variables.get_mut(&id).expect("scan temporary").float = precision; results.push(HostRequestValue { + value_kind: ValueKind::Bits, float_precision: precision, id, width, diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 65deec8647c..93daa8b7347 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -345,6 +345,17 @@ records the native-runner result; the case stays enabled on all Celox backends. ## SystemVerilog suite +Verilator 5.052 rejects a string variable or string method expression as the +`$sscanf` format, requiring a literal instead. IEEE 1800-2023 21.3.4.3 permits +string expressions here. Only `scan::sscanf_string_format_expression` is +excluded for Verilator; string sources with literal formats remain enabled. +The [direct lint observation](verification/sv/limitations/scan-string-format-verilator.json) +retains the diagnostic against the unchanged shared source. Icarus 13.0 +compiles the dynamic-format case but crashes in `vvp`; a reduced source using +only a format variable also crashes. This same case is excluded for Icarus, +with the [runtime observation and reduced source](verification/sv/limitations/scan-string-format-icarus.json) +retained separately. The literal-format case remains enabled for both tools. + Named unpacked array parameter forwarding is checked against IEEE 1800-2023 6.20.2 and 7.6. Verilator 5.052 passes the whole-array forwarding case, but reverses elements across opposite declaration directions and rejects a constant diff --git a/crates/celox-test-suite/src/sv/cases/scan.vtest b/crates/celox-test-suite/src/sv/cases/scan.vtest index 5c97a975b3b..5fa81851615 100644 --- a/crates/celox-test-suite/src/sv/cases/scan.vtest +++ b/crates/celox-test-suite/src/sv/cases/scan.vtest @@ -77,3 +77,52 @@ (top Top) (run_until 0) (assert_eq ok 1)) + +; IEEE 1800-2023 13.4.1 and 21.3.4.3: discarding the return value +; does not discard assignments performed by a scan. +(case sscanf_string_inputs_and_discarded_return + (source "sscanf_discard.sv" #" + module Top(output logic ok); + string source = "1234"; + int value, keep, count; + initial begin + $sscanf(source, "%d", value); + ok = value == 1234; + source = "42"; + count = $sscanf(source.substr(0, 1), "%d", value); + ok &= count == 1 && value == 42; + $sscanf("78", "%d", value); + ok &= value == 78; + source = ""; + count = $sscanf(source, "%d", value); + ok &= count == -1 && value == 78; + keep = 77; + $sscanf("bad", "%d", keep); + ok &= keep == 77; + end + endmodule + "#) + (top Top) + (run_until 0) + (assert_eq ok 1)) + +; 21.3.4.3 also permits a string expression as the format. +(case sscanf_string_format_expression + (source "sscanf_format.sv" #" + module Top(output logic ok); + string source = "42"; + string fmt = "%d"; + int value, count; + initial begin + count = $sscanf(source, fmt, value); + ok = count == 1 && value == 42; + count = $sscanf(source.substr(0, 1), fmt.substr(0, 1), value); + ok &= count == 1 && value == 42; + count = $sscanf("56", fmt, value); + ok &= count == 1 && value == 56; + end + endmodule + "#) + (top Top) + (run_until 0) + (assert_eq ok 1)) diff --git a/crates/celox-test-suite/verification/sv/icarus.json b/crates/celox-test-suite/verification/sv/icarus.json index f5fcd56f09e..3b5bc676699 100644 --- a/crates/celox-test-suite/verification/sv/icarus.json +++ b/crates/celox-test-suite/verification/sv/icarus.json @@ -14,6 +14,7 @@ "icarus/program.json", "icarus/random_plusargs.json", "icarus/review_regressions.json", + "icarus/scan.json", "icarus/string.json", "icarus/synthesizable.json", "icarus/system_functions.json", diff --git a/crates/celox-test-suite/verification/sv/icarus/scan.json b/crates/celox-test-suite/verification/sv/icarus/scan.json new file mode 100644 index 00000000000..cd2ecf7d0fb --- /dev/null +++ b/crates/celox-test-suite/verification/sv/icarus/scan.json @@ -0,0 +1,27 @@ +{ + "cases": [ + { + "category": "Sequential", + "detail": "IEEE 1800-2023 21.3.4.3 permits a string expression as the scan format. Icarus 13.0 compiles this case but vvp terminates with SIGSEGV. A reduced source using only a string format variable, without a method expression, also crashes. The string-source case with a literal format remains enabled.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_runtime_limitation", + "evidence": [ + "verification/sv/limitations/scan-string-format-icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_scan_string_format", + "observed_version": "Icarus Verilog 13.0", + "phase": "execute", + "reason": "IEEE 1800-2023 21.3.4.3 permits a string expression as the scan format. Icarus 13.0 compiles this case but vvp terminates with SIGSEGV. A reduced source using only a string format variable, without a method expression, also crashes. The string-source case with a literal format remains enabled.", + "upstream": [] + }, + "name": "scan::sscanf_string_format_expression", + "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 1a3d03d220e..9610bc6276a 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2458,5 +2458,39 @@ "class::randomization_cyclic_enum_alias" ] } + }, + { + "id": "sv_verilator_scan_string_format", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Verilator 5.052", + "reason": "IEEE 1800-2023 21.3.4.3 permits a string expression as the scan format. Verilator 5.052 requires a format string literal and rejects both a string variable and a string method expression with \"unexpected IDENTIFIER, expecting STRING\". The string-source case with a literal format remains enabled.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/scan-string-format-verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "scan::sscanf_string_format_expression" + ] + } + }, + { + "id": "sv_icarus_scan_string_format", + "category": "simulator_runtime_limitation", + "phase": "execute", + "observed_version": "Icarus Verilog 13.0", + "reason": "IEEE 1800-2023 21.3.4.3 permits a string expression as the scan format. Icarus 13.0 compiles this case but vvp terminates with SIGSEGV. A reduced source using only a string format variable, without a method expression, also crashes. The string-source case with a literal format remains enabled.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/scan-string-format-icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "scan::sscanf_string_format_expression" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/limitations/scan-string-format-icarus.json b/crates/celox-test-suite/verification/sv/limitations/scan-string-format-icarus.json new file mode 100644 index 00000000000..3896bc27c00 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/limitations/scan-string-format-icarus.json @@ -0,0 +1,12 @@ +{ + "tool": "icarus", + "version": "Icarus Verilog 13.0", + "case": "scan::sscanf_string_format_expression", + "source": "src/sv/cases/scan.vtest", + "method": "The unchanged shared source compiles with iverilog -g2012 -s tb and crashes when executed by vvp. Removing the string-method-expression call still crashes; the reduced source below isolates a format variable. The added testbench checks the same ok assertion.", + "status": "runtime_error", + "signal": 11, + "stdout": "", + "stderr": "", + "reduced_source": "\n module Top(output logic ok);\n string source = \"42\";\n string fmt = \"%d\";\n int value, count;\n initial begin\n count = $sscanf(source, fmt, value);\n ok = count == 1 && value == 42;\n count = $sscanf(\"56\", fmt, value);\n ok &= count == 1 && value == 56;\n end\n endmodule\n \nmodule tb; wire ok; Top dut(ok); initial begin #1; if (ok !== 1) $fatal(1, \"scan failed\"); $display(\"PASS\"); $finish; end endmodule\n" +} diff --git a/crates/celox-test-suite/verification/sv/limitations/scan-string-format-verilator.json b/crates/celox-test-suite/verification/sv/limitations/scan-string-format-verilator.json new file mode 100644 index 00000000000..f6c74999576 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/limitations/scan-string-format-verilator.json @@ -0,0 +1,10 @@ +{ + "tool": "verilator", + "version": "Verilator 5.052 2026-09-05 rev v5.052", + "case": "scan::sscanf_string_format_expression", + "source": "src/sv/cases/scan.vtest", + "method": "The source block from the named case was passed unchanged to verilator --lint-only --top-module Top.", + "status": "compile_error", + "exit_code": 1, + "detail": "%Error: /sscanf_format.sv:7:33: syntax error, unexpected IDENTIFIER, expecting STRING\n 7 | count = $sscanf(source, fmt, value);\n | ^~~\n ... See the manual at https://verilator.org/verilator_doc.html?v=5.052 for more assistance.\n%Error: /sscanf_format.sv:9:46: syntax error, unexpected IDENTIFIER, expecting STRING\n 9 | count = $sscanf(source.substr(0, 1), fmt.substr(0, 1), value);\n | ^~~\n%Error: /sscanf_format.sv:11:31: syntax error, unexpected IDENTIFIER, expecting STRING\n 11 | count = $sscanf(\"56\", fmt, value);\n | ^~~\n%Error: Exiting due to 3 error(s)\n" +} diff --git a/crates/celox-test-suite/verification/sv/verilator.json b/crates/celox-test-suite/verification/sv/verilator.json index 47395f55d5a..a361f80c1f2 100644 --- a/crates/celox-test-suite/verification/sv/verilator.json +++ b/crates/celox-test-suite/verification/sv/verilator.json @@ -15,6 +15,7 @@ "verilator/program.json", "verilator/random_plusargs.json", "verilator/review_regressions.json", + "verilator/scan.json", "verilator/string.json", "verilator/synthesizable.json", "verilator/system_functions.json", diff --git a/crates/celox-test-suite/verification/sv/verilator/scan.json b/crates/celox-test-suite/verification/sv/verilator/scan.json new file mode 100644 index 00000000000..17db7367923 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/verilator/scan.json @@ -0,0 +1,27 @@ +{ + "cases": [ + { + "category": "Sequential", + "detail": "IEEE 1800-2023 21.3.4.3 permits a string expression as the scan format. Verilator 5.052 requires a format string literal and rejects both a string variable and a string method expression with \"unexpected IDENTIFIER, expecting STRING\". The string-source case with a literal format remains enabled.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/scan-string-format-verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_scan_string_format", + "observed_version": "Verilator 5.052", + "phase": "compile", + "reason": "IEEE 1800-2023 21.3.4.3 permits a string expression as the scan format. Verilator 5.052 requires a format string literal and rejects both a string variable and a string method expression with \"unexpected IDENTIFIER, expecting STRING\". The string-source case with a literal format remains enabled.", + "upstream": [] + }, + "name": "scan::sscanf_string_format_expression", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index b6dbcd8681e..984c26ba14a 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 37; +const CONTAINER_VERSION: u16 = 38; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/simulator/host/scan.rs b/crates/celox/src/simulator/host/scan.rs index cbe633f2bf9..dd3c0a77ca6 100644 --- a/crates/celox/src/simulator/host/scan.rs +++ b/crates/celox/src/simulator/host/scan.rs @@ -1,5 +1,5 @@ use super::*; -use celox_design::HostRequestSite; +use celox_design::{HostRequestSite, ValueKind}; use celox_runtime::Halt; use celox_runtime::scan::{Input, SliceInput}; use num_bigint::BigUint; @@ -24,6 +24,12 @@ fn packed_bytes(value: BigUint, width: usize) -> Vec { result.extend(bytes); result } +fn trim_packed_padding(bytes: &[u8]) -> &[u8] { + bytes + .iter() + .position(|byte| *byte != 0) + .map_or(&[], |index| &bytes[index..]) +} impl Simulator { pub(crate) fn run_scan_request( &mut self, @@ -40,11 +46,21 @@ impl Simulator { let (format, format_mask) = self.backend.get_four_state(site.args[1].id); let mut count = -1i32; if source_mask.is_zero() && format_mask.is_zero() { - let format = packed_bytes(format, site.args[1].width); - let format = format - .iter() - .position(|byte| *byte != 0) - .map_or(&[][..], |index| &format[index..]); + // IEEE 1800-2023 21.3.4.3 permits both packed and string + // source/format expressions. String values are heap handles. + let format = if site.args[1].value_kind == ValueKind::StrRef { + self.backend + .heap() + .string(format.to_u32().unwrap_or_default()) + .to_vec() + } else { + packed_bytes(format, site.args[1].width) + }; + let format = if site.args[1].value_kind == ValueKind::StrRef { + format.as_slice() + } else { + trim_packed_padding(&format) + }; let destinations = site.results[1..] .iter() .map(|value| celox_runtime::scan::Destination { @@ -55,11 +71,19 @@ impl Simulator { let outcome = if site.operation == 0 { // Packed strings are right-aligned; leading zero padding is // outside their textual contents, including for %c. - let source = source.to_bytes_be(); - let source = source - .iter() - .position(|byte| *byte != 0) - .map_or(&[][..], |index| &source[index..]); + let source = if site.args[0].value_kind == ValueKind::StrRef { + self.backend + .heap() + .string(source.to_u32().unwrap_or_default()) + .to_vec() + } else { + source.to_bytes_be() + }; + let source = if site.args[0].value_kind == ValueKind::StrRef { + source.as_slice() + } else { + trim_packed_padding(&source) + }; celox_runtime::scan::scan_typed( &mut SliceInput::new(source), format, diff --git a/crates/celox/tests/frontends/systemverilog/scan.rs b/crates/celox/tests/frontends/systemverilog/scan.rs index 35f3348a1fc..7ca54681a82 100644 --- a/crates/celox/tests/frontends/systemverilog/scan.rs +++ b/crates/celox/tests/frontends/systemverilog/scan.rs @@ -1,6 +1,19 @@ sv_backends! { + fn sscanf_string_format(sim) { @case "scan::sscanf_string_format_expression"; } + fn sscanf_discarded_return(sim) { @case "scan::sscanf_string_inputs_and_discarded_return"; } fn sscanf_real_fields(sim) { @case "scan::sscanf_real_fields_width_and_suppression"; } fn sscanf_fields(sim) { @case "scan::sscanf_integral_fields_and_failure_counts"; } fn sscanf_outputs(sim) { @case "scan::sscanf_multiple_outputs_and_packed_input"; } fn sscanf_unknowns(sim) { @case "scan::sscanf_radix_unknowns_and_unknown_input"; } } + +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +#[test] +fn sscanf_strings_native_image() { + for case in [ + "scan::sscanf_string_inputs_and_discarded_return", + "scan::sscanf_string_format_expression", + ] { + crate::suite::run_case(case, "native-image"); + } +} diff --git a/crates/celox/tests/shared_jit_cache.rs b/crates/celox/tests/shared_jit_cache.rs index 33b47f0c5e0..43766a4dabe 100644 --- a/crates/celox/tests/shared_jit_cache.rs +++ b/crates/celox/tests/shared_jit_cache.rs @@ -678,6 +678,25 @@ fn native_program_image_rejects_v19_before_loading_float_helper_abi() { )); } +/// Version 38 adds host operand value kinds to the runtime metadata. +#[test] +fn native_program_image_rejects_v37_before_decoding_host_operand_value_kinds() { + let sim = Simulator::builder(ADDER, "Top").build().unwrap(); + let mut encoded = sim + .shared_code() + .program_image() + .to_container_bytes() + .unwrap(); + let trailer_start = encoded.len() - NATIVE_IMAGE_TRAILER_SIZE; + encoded[trailer_start + NATIVE_IMAGE_VERSION_OFFSET + ..trailer_start + NATIVE_IMAGE_VERSION_OFFSET + 2] + .copy_from_slice(&37u16.to_le_bytes()); + assert!(matches!( + celox::NativeProgramImage::discover_appended(&encoded), + Err(NativeImageContainerError::UnsupportedVersion(37)) + )); +} + /// Version 17 adds synchronous host requests to the runtime metadata. #[test] fn native_program_image_rejects_v16_before_decoding_host_request_schema() { diff --git a/crates/celox/tests/sv_scan.rs b/crates/celox/tests/sv_scan.rs index 1a53f2b8501..53728da9e57 100644 --- a/crates/celox/tests/sv_scan.rs +++ b/crates/celox/tests/sv_scan.rs @@ -37,11 +37,12 @@ fn exercise(mut simulation: Simulation) { const SOURCE: &str = r#"module Top(output int count,a,b,c,index,order,first,second,aliased,alias_count,eof,failure,partial,keep, output logic [67:0] wide,output logic [7:0] unknown,output bit [7:0] two_state); int values[0:1]; + string source = " 12,99 ffQ"; function automatic [31:0] scan_source(); order=order*10+1; scan_source="7 8"; endfunction function automatic [31:0] scan_format(); order=order*10+2; scan_format="%d%d"; endfunction function automatic int next_index(); order=order*10+3; next_index=index; index+=1; endfunction initial begin - count=$sscanf(" 12,99 ffQ","%2d,%*d %h%c",a,b,c); + count=$sscanf(source,"%2d,%*d %h%c",a,b,c); index=0; order=0; count=count+$sscanf(scan_source(),scan_format(),values[next_index()],values[next_index()])-2; first=values[0];second=values[1]; aliased=1;alias_count=$sscanf("9","%d",aliased,aliased); @@ -77,8 +78,8 @@ fn fscanf_preserves_mismatch_lookahead_and_rejects_checkpoint() { let path = directory.path().join("input.txt"); std::fs::write(&path, b"12 34Q 7").unwrap(); let source = format!( - r#"module Top(output int n,a,b,c,fail,last,eof);int fd; - initial begin fd=$fopen("{}","r");n=$fscanf({{32'h12345678,fd}},"%d",a); + r#"module Top(output int n,a,b,c,fail,last,eof);int fd;string fmt="%d"; + initial begin fd=$fopen("{}","r");n=$fscanf({{32'h12345678,fd}},fmt,a); n=n+$fscanf({{96'h123456789abcdef123456789,fd}},"%d",b); fail=$fscanf(fd,"%d",b);n=n+$fscanf(fd,"%c%d",c,last); eof=$fscanf(fd,"%d",b);end endmodule"#,