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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions conformance/sv-tests/expected.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 12 additions & 7 deletions crates/celox-sv-analyzer/src/ast/parameters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion crates/celox-sv-analyzer/src/ast/type_binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
155 changes: 155 additions & 0 deletions crates/celox-sv-analyzer/src/ast/type_binding/binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,27 @@ pub(in crate::ast) fn bind_in(
native: &celox_sv_syntax::Declarations,
tree: &AnalysisContext<'_>,
context: &PackedDimensions,
) -> Converted<Option<Type>> {
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<Option<Type>> {
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<Option<Type>> {
enum Job {
Enter(TypeId),
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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::<usize>()
&& 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.
Expand Down
72 changes: 72 additions & 0 deletions crates/celox-sv-analyzer/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}"));
}
}
19 changes: 18 additions & 1 deletion crates/celox/tests/frontends/systemverilog/review_regressions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
"#,
Expand All @@ -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#"
Expand Down
Loading