From 2f529644ce3cde547e348f4bbfb46005692f40f0 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 29 Oct 2026 01:23:30 +0900 Subject: [PATCH] feat(sv): support the chandle type Support `chandle` (IEEE 1800-2023 6.14), which UVM uses for the handles of its DPI-C functions. A chandle is held as 64 two-state bits that start as `null` (0), so variables, class properties, elements of dynamic arrays, queues and associative arrays, subroutine arguments and results lower like any 64-bit value; designs without chandles are unchanged. DPI-C imports pass chandle arguments and results as C pointers on every backend. The analyzer admits a chandle only where 6.14 allows one. The expression binder checks every value it reads: a chandle is accepted only as an operand of `==`, `!=`, `===` or `!==` with another chandle or `null`, as a Boolean test (a condition, `!`, `&&`, `||`), or as a value a chandle receives (an assignment with `=`, an initializer, an argument, a result, a container element, a property or an associative array index), which must itself be a chandle or `null`. Write targets are checked the same way, so only a procedural `=` writes a chandle. Every other context, an operator, a cast, an index, a count, a delay or event, a system subroutine argument, a concatenation, a stream or a continuous assignment, rejects a chandle without a check of its own. Chandle ports, packed chandle types and enumerations based on chandles are rejected. Fixed-size unpacked arrays of chandles, which UVM does not use, are not supported: the type binder rejects them wherever they are declared, also through a typedef. A new shared case passes on every backend, Verilator and xezim; Icarus rejects the chandle class property and the compile failure is retained. sv-tests `6.14--chandle` now passes in both state modes. Change-Id: Iad6401e7634f688c3a2baa55d801ca1dbbdec29c --- conformance/sv-tests/README.md | 4 + conformance/sv-tests/expected.tsv | 4 +- .../src/lowering/hierarchy.rs | 17 +- .../src/lowering/procedural.rs | 5 + crates/celox-sv-analyzer/src/ast.rs | 74 +- .../src/ast/array_parameters.rs | 2 +- .../src/ast/array_reductions.rs | 13 + crates/celox-sv-analyzer/src/ast/classes.rs | 1 + .../src/ast/classes/constraints.rs | 4 + .../celox-sv-analyzer/src/ast/containers.rs | 44 +- .../celox-sv-analyzer/src/ast/declarations.rs | 4 +- .../celox-sv-analyzer/src/ast/dimensions.rs | 6 + .../src/ast/dimensions/discovery.rs | 9 +- .../src/ast/dimensions/query_binding.rs | 50 +- .../src/ast/dimensions/tests.rs | 1 + crates/celox-sv-analyzer/src/ast/dpi.rs | 3 + .../src/ast/expression_binding.rs | 13 +- .../src/ast/expression_binding/calls.rs | 3 +- .../src/ast/expression_binding/chandles.rs | 1087 +++++++++++++++++ .../src/ast/expression_binding/direct.rs | 203 ++- .../src/ast/expression_binding/lvalues.rs | 24 +- .../src/ast/expression_binding/objects.rs | 31 +- .../src/ast/expression_binding/references.rs | 3 +- .../src/ast/expression_binding/streams.rs | 24 +- .../celox-sv-analyzer/src/ast/ff_process.rs | 3 + crates/celox-sv-analyzer/src/ast/functions.rs | 6 +- crates/celox-sv-analyzer/src/ast/generate.rs | 2 + .../src/ast/generate/memo/sites.rs | 2 + crates/celox-sv-analyzer/src/ast/locators.rs | 24 +- crates/celox-sv-analyzer/src/ast/mailboxes.rs | 3 + .../src/ast/packed_structs.rs | 2 +- .../src/ast/packed_structs/layout.rs | 3 +- .../src/ast/packed_structs/selects.rs | 3 +- .../src/ast/parameters/declaration_types.rs | 9 +- .../src/ast/parameters/skipped.rs | 2 + .../src/ast/patterns/binding.rs | 21 +- .../celox-sv-analyzer/src/ast/procedural.rs | 157 ++- .../src/ast/procedural/assertions.rs | 2 +- .../src/ast/procedural/control.rs | 88 +- .../src/ast/procedural/effects.rs | 5 +- .../src/ast/procedural/foreach.rs | 7 +- .../src/ast/procedural/timing.rs | 21 +- .../celox-sv-analyzer/src/ast/type_binding.rs | 6 + .../src/ast/type_binding/binding.rs | 14 + .../celox-sv-analyzer/src/ast/type_names.rs | 3 + crates/celox-sv-analyzer/src/ast/types.rs | 37 +- .../src/ast/unpacked_structs.rs | 2 + .../src/ast/virtual_interfaces.rs | 17 +- crates/celox-sv-analyzer/src/ir.rs | 13 + crates/celox-sv-analyzer/src/lib.rs | 3 + crates/celox-test-suite/LIMITATIONS.md | 10 + .../celox-test-suite/src/sv/cases/types.vtest | 32 + .../tests/retained_reports.rs | 3 + .../verification/sv/icarus/types.json | 11 + .../verification/sv/verilator/types.json | 11 + .../verification/sv/xezim/types.json | 11 + .../systemverilog/review_regressions.rs | 94 +- .../tests/frontends/systemverilog/types.rs | 3 + crates/celox/tests/sv_dpi.rs | 56 + docs/guide/systemverilog-reference.md | 6 +- docs/ja/guide/systemverilog-reference.md | 3 +- scripts/check-external-suite-report.test.mjs | 1 + 62 files changed, 2213 insertions(+), 112 deletions(-) create mode 100644 crates/celox-sv-analyzer/src/ast/expression_binding/chandles.rs diff --git a/conformance/sv-tests/README.md b/conformance/sv-tests/README.md index 936702237fd..99aa43da64e 100644 --- a/conformance/sv-tests/README.md +++ b/conformance/sv-tests/README.md @@ -76,6 +76,10 @@ modes of `13.3.1--task-static` now pass. Its `int a = 0;` in a static task is initialized once and shared by the four calls, which print 1, 2, 3 and 4 in the local simulation driver; the full run reports no other change. +The `chandle` type updates two expectations: both state modes of +`6.14--chandle`, which declares a chandle variable, now pass. It is the only +fail-to-pass transition in the full local run; no failure expectation is broadened. + The official runner’s process exit code is separate from the case verdict. The wrapper reads its `PASS`/`FAIL` log messages; it does not reconstruct their rules from tool exit codes or `should_fail` metadata. A negative test may pass diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index f52f691566c..15316befe32 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1107,8 +1107,8 @@ chapter-6/6.12--shortreal.sv 2state pass chapter-6/6.12--shortreal.sv 4state pass chapter-6/6.13--void.sv 2state pass chapter-6/6.13--void.sv 4state pass -chapter-6/6.14--chandle.sv 2state fail -chapter-6/6.14--chandle.sv 4state fail +chapter-6/6.14--chandle.sv 2state pass +chapter-6/6.14--chandle.sv 4state pass chapter-6/6.16--string.sv 2state pass chapter-6/6.16--string.sv 4state pass chapter-6/6.16.1--string_len.sv 2state pass diff --git a/crates/celox-frontend-sv/src/lowering/hierarchy.rs b/crates/celox-frontend-sv/src/lowering/hierarchy.rs index a58cd2b9e18..743902e367c 100644 --- a/crates/celox-frontend-sv/src/lowering/hierarchy.rs +++ b/crates/celox-frontend-sv/src/lowering/hierarchy.rs @@ -672,11 +672,14 @@ fn resolved_type(module: &ElaboratedModule, r#type: &sv::ir::Type) -> Option>>()?; - Some(sv::ast::Type::resolved( - kind, - r#type.is_signed(), - r#type.signed_element_depth(), - &packed, - &unpacked, - )) + Some( + sv::ast::Type::resolved( + kind, + r#type.is_signed(), + r#type.signed_element_depth(), + &packed, + &unpacked, + ) + .with_chandle(r#type.is_chandle()), + ) } diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 2dea5b369b9..4b6487c9f58 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -1288,6 +1288,11 @@ impl<'a> ProcModule<'a> { sv::ir::DpiType::Bit => ExternType::Bit, sv::ir::DpiType::Logic => ExternType::Logic, sv::ir::DpiType::Integer { width, signed } => ExternType::Integer { width, signed }, + // A pointer, 64 bits on the supported hosts. + sv::ir::DpiType::Chandle => ExternType::Integer { + width: 64, + signed: false, + }, }; let function = ExternFunction { name: import.c_name().to_string(), diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 39fd63d751b..b0c8e8101d1 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -1126,6 +1126,11 @@ impl Module { &type_aliases, header_ports, )?; + if let Some(port) = ports.iter().find(|port| port.r#type.holds_chandle()) { + return Err(AnalyzerError::IllegalChandleUse { + detail: format!("port `{}` of chandle type", port.name), + }); + } ports.extend(imported.ports.iter().cloned()); let mut port_names = HashSet::default(); if let Some(port) = ports.iter().find(|port| !port_names.insert(port.name())) { @@ -1242,6 +1247,37 @@ impl Module { let dpi_items = generate::items(syntax_tree, session, &const_env, &type_aliases)?; let mut dpi_imports = dpi::imports(&dpi_items, syntax_tree, session, &type_aliases)?; for import in &dpi_imports { + // Shapes check the actuals as assignments to the formals. + subroutine_shapes.insert( + import.name().to_string(), + import + .arguments() + .iter() + .filter_map(|argument| { + let r#type = match argument.r#type() { + crate::ir::DpiType::Bit => type_binding::builtin_type("bit", None), + crate::ir::DpiType::Logic => { + type_binding::builtin_type("logic", None) + } + crate::ir::DpiType::Chandle => { + type_binding::builtin_type("chandle", None) + } + crate::ir::DpiType::Integer { width, signed } => { + type_binding::builtin_type( + match width { + 8 => "byte", + 16 => "shortint", + 32 => "int", + _ => "longint", + }, + Some(signed), + ) + } + }?; + Some(procedural::dimensions_from_type(&r#type)) + }) + .collect(), + ); subroutine_params.insert( import.name().to_string(), import @@ -1434,6 +1470,7 @@ impl Module { signed: function.return_signed, is_2state: function.return_is_2state, string: function.return_string, + chandle: function.return_chandle, pattern_type: function.return_type.clone(), enum_domain: function.return_enum_domain.clone(), class: function.return_class.clone(), @@ -1452,10 +1489,13 @@ impl Module { width: Some(r#type.width()), first_packed_dimension_width: (r#type.width() > 1) .then_some(r#type.width()), - dimensions: Some(usize::from(r#type.width() > 1)), + dimensions: Some(usize::from( + r#type.width() > 1 && r#type != crate::ir::DpiType::Chandle, + )), signed: r#type.is_signed(), is_2state: !r#type.is_4state(), string: false, + chandle: r#type == crate::ir::DpiType::Chandle, pattern_type: None, enum_domain: None, class: None, @@ -2476,6 +2516,9 @@ pub struct Type { /// The typedef that names an enumeration, struct or union type, and how /// `$typename` spells the type where its structure does not tell. spelling: type_names::Spelling, + /// A `chandle` (IEEE 1800-2023 6.14): an opaque 64-bit C pointer, held + /// as 2-state bits, whose uses the analyzer restricts. + chandle: bool, } #[derive(Debug, Clone, PartialEq, Eq, Hash)] @@ -2505,6 +2548,7 @@ impl Type { container: None, unpacked_struct: None, spelling: type_names::Spelling::default(), + chandle: false, } } @@ -2524,6 +2568,7 @@ impl Type { container: None, unpacked_struct: None, spelling: type_names::Spelling::default(), + chandle: false, } } @@ -2544,6 +2589,16 @@ impl Type { self.spelling.declaration() } + /// Whether the type is a chandle or an unpacked structure with a + /// chandle member, which no port may have and no randomization fill + /// (IEEE 1800-2023 6.14). + pub(in crate::ast) fn holds_chandle(&self) -> bool { + self.chandle + || self + .unpacked_struct() + .is_some_and(|aggregate| aggregate.leaves().iter().any(|leaf| leaf.r#type.chandle)) + } + /// The members of an unpacked structure type. pub(in crate::ast) fn unpacked_struct(&self) -> Option<&Arc> { self.unpacked_struct.as_ref() @@ -2624,6 +2679,17 @@ impl Type { ..Self::new(kind) } } + + /// Whether the type is a `chandle`. + pub(crate) fn is_chandle(&self) -> bool { + self.chandle + } + + /// The type, a `chandle` if `chandle` (see [`crate::ir::Type::is_chandle`]). + pub fn with_chandle(mut self, chandle: bool) -> Self { + self.chandle = chandle; + self + } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] @@ -3103,6 +3169,8 @@ struct Function { return_string: bool, /// Whether the function returns a class handle. return_handle: bool, + /// The function returns a `chandle`. + return_chandle: bool, name: String, params: Vec, /// The function's value as one expression of its arguments, or `None` @@ -3357,6 +3425,8 @@ struct VariableDimensions { unpacked_struct: Option>, /// The declared type, for `$typename`. declared: type_names::Declared, + /// A `chandle` variable (see [`Type::chandle`]). + chandle: bool, } type VariablePackedDimensions = HashMap; @@ -3379,6 +3449,8 @@ struct FunctionReturnMetadata { is_2state: bool, /// The function returns a `string`. string: bool, + /// The function returns a `chandle` (IEEE 1800-2023 6.14). + chandle: bool, /// Declared aggregate type, available before function bodies are inlined. pattern_type: Option, /// The members of an enumerated return type, for its methods. diff --git a/crates/celox-sv-analyzer/src/ast/array_parameters.rs b/crates/celox-sv-analyzer/src/ast/array_parameters.rs index 4613b4ecead..afec002f6ed 100644 --- a/crates/celox-sv-analyzer/src/ast/array_parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/array_parameters.rs @@ -192,7 +192,7 @@ fn array_parameters_from_declaration( // default. Only defaults actually consumed here require their native ID. let native_pattern = if bound.is_none() { pattern } else { None }; let parameter = ArrayParameter { - signal: Signal::new(name, type_with_unpacked_ranges(element, ranges)), + signal: Signal::new(name, type_with_unpacked_ranges(element, ranges)?), native_pattern, bound, }; diff --git a/crates/celox-sv-analyzer/src/ast/array_reductions.rs b/crates/celox-sv-analyzer/src/ast/array_reductions.rs index d6a551f26dc..a1c9771f302 100644 --- a/crates/celox-sv-analyzer/src/ast/array_reductions.rs +++ b/crates/celox-sv-analyzer/src/ast/array_reductions.rs @@ -3,6 +3,13 @@ use super::*; use celox_sv_syntax::{Declarations, ExprId, ExprKind}; use system_functions::ContainerOp; +/// A chandle is no integral value to combine (IEEE 1800-2023 6.14). +fn chandle_elements() -> AnalyzerError { + AnalyzerError::IllegalChandleUse { + detail: "an array reduction of chandle elements".into(), + } +} + pub(super) fn bind( id: ExprId, native: &Declarations, @@ -53,6 +60,9 @@ pub(super) fn bind( "array reduction of elements wider than 64 bits", )); } + if expression_binding::type_holds_chandle(&container.element) { + return Err(chandle_elements()); + } if container.layout.handle.is_some() { return Err(unsupported("array reduction requires integral elements")); } @@ -87,6 +97,9 @@ pub(super) fn bind( "array reduction arguments require a with expression", )); } + if expression_binding::holds_chandle(shape) { + return Err(chandle_elements()); + } if shape.unpacked.len() != 1 || shape.real || shape.string || shape.class.is_some() { return Err(unsupported( "array reduction requires one-dimensional integral elements", diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index 21f6fb17bfb..16286a54f57 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -187,6 +187,7 @@ impl Class { } if (property.rand || property.randc) && (property.field.handle.is_some() + || property.r#type.holds_chandle() || (property.r#type.is_enum && property.r#type.enum_domain.is_none())) { return Err(unsupported( diff --git a/crates/celox-sv-analyzer/src/ast/classes/constraints.rs b/crates/celox-sv-analyzer/src/ast/classes/constraints.rs index d86791b998c..418a4bf4d4d 100644 --- a/crates/celox-sv-analyzer/src/ast/classes/constraints.rs +++ b/crates/celox-sv-analyzer/src/ast/classes/constraints.rs @@ -166,6 +166,10 @@ pub(in crate::ast) fn bind_inputs( if property.field.four_state { return Err("4-state class property in a constraint".into()); } + // A chandle has no integral value to constrain (6.14). + if property.r#type.holds_chandle() { + return Err("a chandle in a constraint".into()); + } Typed { kind: Kind::Leaf(ConstraintExpr::Field(index)), width: property.field.width, diff --git a/crates/celox-sv-analyzer/src/ast/containers.rs b/crates/celox-sv-analyzer/src/ast/containers.rs index 6f8542049a5..26c2b66226e 100644 --- a/crates/celox-sv-analyzer/src/ast/containers.rs +++ b/crates/celox-sv-analyzer/src/ast/containers.rs @@ -90,10 +90,10 @@ pub(super) fn with_dimensions( _ => None, }; let Some(kind) = kind else { - return Ok(types::type_with_unpacked_ranges( + return types::type_with_unpacked_ranges( base, constant_binding::bind_unpacked_ranges(dims, tree, session, context)?, - )); + ); }; // `T a[x][y]`: each element of `a` is a container `T [y]` (IEEE // 1800-2023 7.4.5, 7.8), held by its handle like any container value. @@ -464,6 +464,14 @@ fn element_value( if let Some(aggregate) = target.element.unpacked_struct() { unpacked_structs::check_value(aggregate, id, native, tree, session, dims)?; } + expression_binding::check_chandle_assignment( + target.element.chandle && target.element.unpacked_ranges.is_empty(), + id, + tree, + native, + dims, + session, + )?; let shape = procedural::dimensions_from_type(&target.element); let value = expression_binding::bind_value(id, native, tree, session, dims, Some(&shape))?; if let Some(record) = &target.record { @@ -521,6 +529,9 @@ fn index_value( || "associative array index".into(), )?; } + // Only an associative array indexed by chandles takes a chandle index. + let chandle = target.key.as_ref().is_some_and(|key| key.chandle); + expression_binding::check_chandle_assignment(chandle, id, tree, native, dims, session)?; if matches!( target.layout.kind, ContainerKind::Associative { string: true, .. } @@ -548,7 +559,7 @@ fn index_value( left, operator, right, - } if operator == "+" || operator == "-" => Expr::Binary { + } if !chandle && (operator == "+" || operator == "-") => Expr::Binary { left: Box::new(index_value(*left, base, tree, session, dims, target)?), op: if operator == "+" { BinaryOp::Add @@ -557,6 +568,9 @@ fn index_value( }, right: Box::new(index_value(*right, base, tree, session, dims, target)?), }, + _ if chandle => { + expression_binding::bind_chandle_value(id, native, tree, session, dims, None)? + } _ => expression_binding::value(id, native, tree, session, dims)?, }; Ok( @@ -718,6 +732,12 @@ pub(super) fn value( if op != ContainerOp::Reverse && target.record.is_some() { return Err(unsupported("sorting elements wider than 64 bits")); } + // Chandles have no relational operators (6.14, 7.12.2). + if op != ContainerOp::Reverse && target.element.chandle { + return Err(AnalyzerError::IllegalChandleUse { + detail: "sorting chandles".into(), + }); + } if op != ContainerOp::Reverse && target.layout.handle == Some(HandleProperty::Object) { @@ -812,6 +832,14 @@ pub(super) fn value( // reference, so it has the index's class (IEEE 1800-2023 // 7.9.4). let key_class = target.key.as_ref().and_then(|key| key.class()); + // So is the variable of a chandle index, which is no + // integral variable (6.14). + if shape.chandle != target.key.as_ref().is_some_and(|key| key.chandle) { + return Err(AnalyzerError::IllegalChandleUse { + detail: "an associative traversal index of another type than the index" + .into(), + }); + } if let ContainerKind::Associative { string, object, .. } = target.layout.kind && (shape.string != string || shape.container.is_some() @@ -822,7 +850,13 @@ pub(super) fn value( "incompatible associative traversal index variable", )); } - args.push(expression_binding::value(id, native, tree, session, dims)?); + args.push(if shape.chandle { + expression_binding::bind_chandle_value( + id, native, tree, session, dims, None, + )? + } else { + expression_binding::value(id, native, tree, session, dims)? + }); } else if matches!(op, ContainerOp::PushFront | ContainerOp::PushBack) || op == ContainerOp::Insert && index == 1 { @@ -905,12 +939,14 @@ fn query( if name.spelling == "$unpacked_dimensions" { unpacked } else { + // A chandle has no packed dimensions (IEEE 1800-2023 6.14). unpacked // An integral element kept in a record keeps its // packed dimensions; a structure has none. + if innermost.layout.handle.is_some() && (innermost.record.is_none() || innermost.element.unpacked_struct().is_some()) + || innermost.element.chandle { 0 } else { diff --git a/crates/celox-sv-analyzer/src/ast/declarations.rs b/crates/celox-sv-analyzer/src/ast/declarations.rs index 56bc4a11bb5..e7013f13a15 100644 --- a/crates/celox-sv-analyzer/src/ast/declarations.rs +++ b/crates/celox-sv-analyzer/src/ast/declarations.rs @@ -48,7 +48,7 @@ pub(super) fn ports_from_scope( const_env, type_aliases, )?, - ); + )?; if ty.container.is_some() { return Err(unsupported("dynamic container port")); } @@ -411,7 +411,7 @@ pub(super) fn signals_from_body_item( session, &context, )?, - ); + )?; values.push(Signal::new(name, ty)); } } diff --git a/crates/celox-sv-analyzer/src/ast/dimensions.rs b/crates/celox-sv-analyzer/src/ast/dimensions.rs index 2b256014436..cf0ed879530 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions.rs @@ -133,8 +133,10 @@ pub(super) fn packed_dimensions_from_ports_and_signals( port.name().to_string(), VariableDimensions { declared: type_names::Declared::new(port.r#type()), + chandle: port.r#type().chandle, container: port.r#type().container.clone(), randomizable: port.r#type().container.is_none() + && !port.r#type().holds_chandle() && (!port.r#type().is_enum || port.r#type().enum_domain.is_some()) && port.randomizable, enum_domain: port.r#type().enum_domain.clone(), @@ -180,8 +182,10 @@ pub(super) fn packed_dimensions_from_ports_and_signals( signal.name().to_string(), VariableDimensions { declared: type_names::Declared::new(signal.r#type()), + chandle: signal.r#type().chandle, container: signal.r#type().container.clone(), randomizable: signal.r#type().container.is_none() + && !signal.r#type().holds_chandle() && (!signal.r#type().is_enum || signal.r#type().enum_domain.is_some()) && !signal.is_net() && !signal.is_const, @@ -384,6 +388,7 @@ fn extend_variable_dimensions_from_const_env( let packed_ranges = ranges.split_off(unpacked); let ty = Type { container: None, + chandle: false, is_enum: false, enum_domain: None, packed_enum: false, @@ -601,6 +606,7 @@ pub(super) fn parameter_packed_dimensions(parameters: &[Parameter]) -> VariableP VariableDimensions { declared: type_names::Declared::default(), container: None, + chandle: false, randomizable: true, enum_domain: parameter.enum_domain.clone(), packed_enum: false, diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs index cf7078ecfa2..8c80aa7a620 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs @@ -433,7 +433,8 @@ fn return_metadata( .or(width), dimensions: ty.map(|ty| { ty.unpacked_ranges().len() - + if matches!(ty.kind(), TypeKind::Real | TypeKind::Shortreal) { + // A chandle has no packed dimensions (IEEE 1800-2023 6.14). + + if ty.chandle || matches!(ty.kind(), TypeKind::Real | TypeKind::Shortreal) { 0 } else { ty.packed_ranges().len() @@ -449,6 +450,7 @@ fn return_metadata( .filter(|ty| ty.unpacked_ranges.is_empty() && ty.container.is_none()) .and_then(|ty| ty.class().map(str::to_owned)), virtual_interface: ty.and_then(|ty| ty.virtual_interface.clone()), + chandle: ty.is_some_and(|ty| ty.chandle && ty.unpacked_ranges.is_empty()), pattern_type: ty .filter(|ty| { !ty.members.is_empty() @@ -961,10 +963,13 @@ fn subroutine_signatures( arguments: Some(dpi_argument_metadata(&import)), width: Some(ty.width()), first_packed_dimension_width: (ty.width() > 1).then_some(ty.width()), - dimensions: Some(usize::from(ty.width() > 1)), + dimensions: Some(usize::from( + ty.width() > 1 && ty != crate::ir::DpiType::Chandle, + )), signed: ty.is_signed(), is_2state: !ty.is_4state(), string: false, + chandle: ty == crate::ir::DpiType::Chandle, pattern_type: None, enum_domain: None, class: None, diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs index b4ecd046bf8..36761447494 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs @@ -136,20 +136,42 @@ pub(in crate::ast) fn query_value( { return Ok(Some(value)); } - let shape = shape(argument, tree, session, &context)?; + let mut shape = shape(argument, tree, session, &context)?; + // A value whose shape is rebuilt from its bits, such as a conditional + // choosing between chandles, is still a chandle. + if let Some(shape) = &mut shape + && !shape.chandle + && shape.unpacked.is_empty() + && expression_binding::native_chandle(tree, argument, native, &context, session) + { + shape.chandle = true; + } + // The 64 bits of a chandle are its storage, which `$bits` counts; they + // are no packed dimension the array queries see (IEEE 1800-2023 6.14, + // 20.7). + let bits = shape.clone(); + if let Some(shape) = &mut shape + && shape.chandle + { + shape.packed.clear(); + } let dimension = if let Some(argument) = arguments.get(1) { + // The dimension number is evaluated, unlike the queried operand, so + // it is bound as a value (IEEE 1800-2023 20.7). + let mut evaluated = context.clone(); + evaluated.type_query = false; Some(expression_binding::bind( argument.value.unwrap(), tree, session, - &context, + &evaluated, )?) } else { None }; let value = match function { SystemFunction::Bits => { - let width = if let Some(shape) = &shape { + let width = if let Some(shape) = &bits { shape .unpacked .iter() @@ -217,8 +239,12 @@ pub(in crate::ast) fn query_value( }) } .or_else(|| { - (shape.unpacked.is_empty() && shape.packed.is_empty() && index == Some(0)) - .then_some(1) + // A scalar has one element; a chandle has no dimension. + (shape.unpacked.is_empty() + && shape.packed.is_empty() + && !shape.chandle + && index == Some(0)) + .then_some(1) }) } else { None @@ -388,7 +414,9 @@ fn function_first_width( } context .function_return_types - .get(&name)? + .get(&name) + // A chandle result has no packed dimension (IEEE 1800-2023 6.14). + .filter(|metadata| !metadata.chandle)? .first_packed_dimension_width } @@ -916,7 +944,11 @@ pub(in crate::ast) fn shape( && let Some(metadata) = context.function_return_types.get(name) && let Some(count) = metadata.dimensions { - if count == 0 { + // The bits of a chandle are its storage, not a + // packed dimension (IEEE 1800-2023 6.14). + if metadata.chandle { + shape.chandle = true; + } else if count == 0 { shape.packed.clear(); } } @@ -1026,6 +1058,7 @@ mod tests { signed: false, is_2state: false, string: false, + chandle: false, pattern_type: None, enum_domain: None, class: None, @@ -1049,7 +1082,8 @@ mod tests { &context, ) .unwrap(), - ); + ) + .unwrap(); context.insert( instances::normalize_identifier(&variable.name.spelling), procedural::dimensions_from_type(&ty), diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs b/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs index 90e49ad658a..99a4f8c4d35 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs @@ -200,6 +200,7 @@ fn complete_scope_queries_match_syntax_discovery_without_rewalking_declarations( signed: f.return_signed, is_2state: f.return_is_2state, string: f.return_string, + chandle: false, pattern_type: f.return_type.clone(), enum_domain: None, class: None, diff --git a/crates/celox-sv-analyzer/src/ast/dpi.rs b/crates/celox-sv-analyzer/src/ast/dpi.rs index 384a1af075a..ada0717bd0c 100644 --- a/crates/celox-sv-analyzer/src/ast/dpi.rs +++ b/crates/celox-sv-analyzer/src/ast/dpi.rs @@ -242,6 +242,9 @@ fn native_dpi_type( signed: data_type.signed.unwrap_or(true), }) } + // A C pointer (`void *`), a 64-bit integer on the supported hosts + // (IEEE 1800-2023 6.14, H.7.4). + DataTypeKind::Builtin(name) if name == "chandle" => Ok(DpiType::Chandle), DataTypeKind::Builtin(name) if matches!(name.as_str(), "integer" | "time") => Err( unsupported(format!("DPI-C {role} of four-state integer type")), ), diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding.rs b/crates/celox-sv-analyzer/src/ast/expression_binding.rs index 04c9142c6ed..63805b64113 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding.rs @@ -2,6 +2,7 @@ use super::*; use celox_sv_syntax::{Declarations, DimensionKind, ExprId, ExprKind}; mod calls; +mod chandles; mod direct; mod enums; mod format_patterns; @@ -13,10 +14,16 @@ mod selected; mod streams; mod strings; pub(super) use calls::{statement as call_statement, statement_root as call_statement_root}; +pub(super) use chandles::{ + check_assignment as check_chandle_assignment, check_equality as check_chandle_equality, + check_memory as check_chandle_memory, check_target as check_chandle_target, holds_chandle, + native_chandle, read as check_chandle_read, type_holds_chandle, +}; +pub(super) use direct::bind_argument; pub(super) use direct::{ - arguments, bind_value, call_name as native_name, callable_name, cast_target_native, - formal_arguments, format_arguments, member_context, real_value, remove_real_division_guards, - string_literal_bytes, ungroup, + arguments, bind_chandle_value, bind_value, call_name as native_name, callable_name, + cast_target_native, formal_arguments, format_arguments, member_context, real_value, + remove_real_division_guards, string_literal_bytes, ungroup, }; pub(super) use format_patterns::{ bytes_literal, format as format_call, has_pattern, pattern as format_pattern, diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/calls.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/calls.rs index 0352e80637c..0126637694a 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/calls.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/calls.rs @@ -79,7 +79,8 @@ pub(in crate::ast) fn statement( arg_order: Vec::new(), })); } - super::bind_value(root, native, tree, session, &context, None).map(Some) + // The result, which may be a chandle, is discarded (13.4.1). + super::bind_chandle_value(root, native, tree, session, &context, None).map(Some) } #[cfg(test)] diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/chandles.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/chandles.rs new file mode 100644 index 00000000000..4bfbc4b64a3 --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/chandles.rs @@ -0,0 +1,1087 @@ +//! The uses IEEE 1800-2023 6.14 allows for a `chandle`: equality with +//! another chandle or `null`, a Boolean test, and assignment from another +//! chandle or `null`. +use super::*; + +/// Whether native expression `id` is a chandle: a chandle variable, a +/// chandle property, or an element of a container of chandles. +pub(in crate::ast) fn native_chandle( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, + session: &mut Session, +) -> bool { + let id = ungroup(id, native); + if let Some(chandle) = locator_index(tree, id, native, dimensions, session) { + return chandle; + } + match &native.expression(id).kind { + ExprKind::Name(name) => { + if let Some(shape) = dimensions.get(&instances::normalize_identifier(&name.spelling)) { + return shape.chandle && shape.unpacked.is_empty(); + } + } + ExprKind::Select { + expression, + dimension, + } => { + // A slice of an unpacked array is an array (7.4.6); `q[$]` is + // the last element of a queue (7.10.1). + if !element_select(&dimension.kind) { + return false; + } + if let Ok(Some(container)) = + containers::native_type(*expression, native, tree, session, dimensions) + { + return container.element.chandle; + } + let mut base = ungroup(*expression, native); + let mut indices = 1; + while let ExprKind::Select { + expression, + dimension, + } = &native.expression(base).kind + { + if !element_select(&dimension.kind) { + return false; + } + base = ungroup(*expression, native); + indices += 1; + } + return array_of_chandles(tree, base, native, dimensions, session) + .is_some_and(|rank| rank == indices); + } + ExprKind::Call { .. } => { + return call_result(tree, id, native, dimensions, session) == Some(true); + } + // A pop of a queue may omit its parentheses. + ExprKind::Member { + expression: receiver, + separator, + name, + } if separator == "." => { + if let Some(chandle) = + container_method(tree, *receiver, &name.spelling, native, dimensions, session) + { + return chandle; + } + } + // A conditional choosing between chandles, or a chandle and `null`. + ExprKind::Conditional { + then_expression, + else_expression, + .. + } => { + // Each branch is classified once, or nested conditionals would + // be classified exponentially often. + let branches = [*then_expression, *else_expression] + .map(|branch| native_chandle(tree, branch, native, dimensions, session)); + return branches.contains(&true) + && [*then_expression, *else_expression] + .iter() + .zip(branches) + .all(|(&branch, chandle)| chandle || null(branch, native)); + } + _ => {} + } + // A member of a variable of unpacked structure type is a variable. + if let Some(variable) = unpacked_structs::native_member(id, native, dimensions) { + return dimensions + .get(&variable) + .is_some_and(|shape| shape.chandle && shape.unpacked.is_empty()); + } + // A member selected through a virtual interface has its declared type. + if virtual_member(tree, id, native, dimensions, session) { + return true; + } + // A signal of another instance or interface named by a path. + if let ExprKind::Member { .. } = &native.expression(id).kind + && let Ok((mut parts, None)) = direct::path(id, native, tree, session, dimensions) + && parts.len() > 1 + && packed_structs::bind_interface_path(tree, &mut parts, dimensions) + && let [variable] = parts.as_slice() + { + return dimensions + .get(variable) + .is_some_and(|shape| shape.chandle && shape.unpacked.is_empty()); + } + // A member of an unpacked structure element of a container. + if let Ok(Some((member, _))) = containers::element_member(id, native, tree, session, dimensions) + { + return member.chandle && member.unpacked_ranges.is_empty(); + } + if let Ok(Some(variable)) = objects::static_property(tree, session, id, native, dimensions) { + return dimensions + .get(&variable) + .is_some_and(|shape| shape.chandle && shape.unpacked.is_empty()); + } + objects::property(tree, session, id, native, dimensions) + .ok() + .flatten() + .is_some_and(|(property, _)| { + property.r#type.chandle && property.r#type.unpacked_ranges.is_empty() + }) +} + +/// Whether `id`, an iterator index query `item.index` of a locator method +/// (7.12.4), has the chandle index type of its array; `None` if `id` is no +/// such query. +#[inline(never)] +fn locator_index( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, + session: &mut Session, +) -> Option { + let Ok(Some(Expr::Ident(index))) = locators::index(id, native, tree, session, dimensions) + else { + return None; + }; + Some( + dimensions + .get(&index) + .is_some_and(|shape| shape.chandle && shape.unpacked.is_empty()), + ) +} + +/// Whether call native expression `id` of a function, method or DPI-C +/// import returns a chandle, `None` if the callee has no known result. +fn call_result( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, + session: &mut Session, +) -> Option { + let ExprKind::Call { expression, .. } = &native.expression(ungroup(id, native)).kind else { + return None; + }; + match &native.expression(ungroup(*expression, native)).kind { + // No system function returns a chandle. + ExprKind::Name(name) if name.spelling.starts_with('$') => return Some(false), + // Of the built-in container methods, only the pops return an element. + ExprKind::Member { + expression: receiver, + separator, + name, + } if separator == "." => { + if let Some(chandle) = + container_method(tree, *receiver, &name.spelling, native, dimensions, session) + { + return Some(chandle); + } + } + _ => {} + } + dimensions + .function_return_types + .get(&callee_name( + tree, + *expression, + native, + dimensions, + session, + )?) + .map(|metadata| metadata.chandle) +} + +/// The subroutine that callee `callee`, a function, a method or a DPI-C +/// import, names. +fn callee_name( + tree: &AnalysisContext<'_>, + callee: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, + session: &mut Session, +) -> Option { + objects::method(tree, session, callee, native, dimensions) + .ok() + .flatten() + .map(|(name, ..)| name) + .or_else(|| { + direct::bound_callable_name(tree, session, callee, native, dimensions) + .ok() + .flatten() + }) +} + +/// The number of unpacked dimensions of array `id` of chandles: a variable +/// or a signal of another scope named by a path. `None` if `id` is no such +/// array. +#[inline(never)] +fn array_of_chandles( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, + session: &mut Session, +) -> Option { + variable(tree, id, native, dimensions, session) + .filter(|shape| shape.chandle && shape.container.is_none()) + .map(|shape| shape.unpacked.len()) +} + +/// The shape of variable `id`: a name, or a signal of another scope named +/// by a path. `None` if `id` is no such variable. +fn variable<'a>( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &'a PackedDimensions, + session: &mut Session, +) -> Option<&'a VariableDimensions> { + match &native.expression(id).kind { + ExprKind::Name(name) => { + return dimensions.get(&instances::normalize_identifier(&name.spelling)); + } + ExprKind::Member { .. } => {} + _ => return None, + } + let (mut parts, None) = direct::path(id, native, tree, session, dimensions).ok()? else { + return None; + }; + // A member of a structure variable is named by one collapsed path. + if parts.len() > 1 && !packed_structs::bind_interface_path(tree, &mut parts, dimensions) { + return None; + } + match parts.as_slice() { + [name] => dimensions.get(name), + _ => None, + } +} + +/// Whether `id` is a chandle member selected through a virtual interface +/// (25.9), whose members are scalar. +#[inline(never)] +fn virtual_member( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, + session: &mut Session, +) -> bool { + virtual_interfaces::native_member(tree, session, id, native, dimensions).is_some_and( + |(_, ty, member)| { + virtual_interfaces::member(session, &ty, &member) + .is_ok_and(|(member, _)| member.r#type.chandle) + }, + ) +} + +/// Whether a select of `kind` selects one element. +fn element_select(kind: &DimensionKind) -> bool { + matches!(kind, DimensionKind::Index(_) | DimensionKind::Queue(None)) +} + +/// Whether built-in method `name` of container `receiver` returns a +/// chandle, `None` if `receiver` is no container. Of these methods, only the +/// pops return an element. +fn container_method( + tree: &AnalysisContext<'_>, + receiver: ExprId, + name: &str, + native: &Declarations, + dimensions: &PackedDimensions, + session: &mut Session, +) -> Option { + let container = containers::native_type(receiver, native, tree, session, dimensions).ok()??; + Some( + matches!(name, "pop_front" | "pop_back") + && container.element.chandle + && container.element.unpacked_ranges.is_empty(), + ) +} + +/// Whether native expression `id` is a hierarchical name not yet bound to a +/// signal of another scope: the binder reports it, and the analysis that +/// binds it checks its type (IEEE 1800-2023 23.6). +fn unbound_hierarchical( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, + session: &mut Session, +) -> bool { + let id = ungroup(id, native); + if !matches!(native.expression(id).kind, ExprKind::Member { .. }) { + return false; + } + let Ok((mut parts, None)) = direct::path(id, native, tree, session, dimensions) else { + return false; + }; + parts.len() > 1 + && dimensions.get(&parts[0]).is_none() + && !packed_structs::bind_interface_path(tree, &mut parts, dimensions) +} + +fn null(id: ExprId, native: &Declarations) -> bool { + matches!(&native.expression(ungroup(id, native)).kind, ExprKind::Literal(text) if text == "null") +} + +/// Check that memory `memory`, which a file is read into or written from, +/// holds no chandle, also as a structure member: a file holds integral +/// words (6.14, 21.3.4.4, 21.4). +#[inline(never)] +pub(in crate::ast) fn check_memory( + memory: ExprId, + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, + session: &mut Session, +) -> Converted<()> { + let native = tree.declarations(); + let chandle = match containers::native_type(memory, native, tree, session, dimensions)? { + Some(container) => type_holds_chandle(&container.element), + // A variable, or a signal of another instance named by a path. + None => variable(tree, ungroup(memory, native), native, dimensions, session) + .is_some_and(holds_chandle), + }; + if chandle { + return Err(illegal("a memory of chandles")); + } + Ok(()) +} + +/// The error of a bit-select or part-select of a chandle. +pub(super) fn packed_select() -> AnalyzerError { + illegal("a chandle has no bits to select") +} + +fn illegal(detail: impl Into) -> AnalyzerError { + AnalyzerError::IllegalChandleUse { + detail: detail.into(), + } +} + +/// The values one binding of an expression may read as chandles. A chandle +/// is not integral: IEEE 1800-2023 6.14 lets one be compared for equality +/// with another chandle or `null`, tested as a Boolean, and assigned to a +/// chandle (passed to a chandle formal, returned as a chandle result, stored +/// as a chandle element or property). The binder checks every value it reads +/// against this list, so any other context, an operand, an index, a count, a +/// cast, an argument of a system subroutine, rejects a chandle without a +/// check of its own. +pub(super) struct Permits { + /// The native expressions that may be chandles. + granted: Vec, +} + +impl Permits { + /// The permits of a binding of `root`, which may be a chandle if + /// `chandle`. + pub(super) fn new(root: ExprId, chandle: bool) -> Self { + Self { + granted: if chandle { vec![root] } else { Vec::new() }, + } + } + + /// Let `id` be a chandle. + pub(super) fn grant(&mut self, id: ExprId) { + self.granted.push(id); + } + + /// Let `id` be a chandle if `granted`. + pub(super) fn grant_if(&mut self, granted: bool, id: ExprId) { + if granted { + self.grant(id); + } + } + + /// Check value `id`, which the binder reads for a destination of shape + /// `target`, returning whether it may be a chandle. + #[inline(never)] + pub(super) fn check( + &mut self, + session: &mut Session, + id: ExprId, + target: Option<&VariableDimensions>, + tree: &AnalysisContext<'_>, + native: &Declarations, + dimensions: &PackedDimensions, + ) -> Converted { + // A type query reads no value (20.6). + let permitted = self.granted.contains(&id) + || target.is_some_and(receives_chandle) + || dimensions.type_query; + if !permitted + && matches!( + native.expression(id).kind, + ExprKind::Name(_) + | ExprKind::Select { .. } + | ExprKind::Member { .. } + | ExprKind::Call { .. } + ) + && native_chandle(tree, id, native, dimensions, session) + { + return Err(illegal(format!( + "chandle `{}` used as a value of another type", + native.token_text(native.expression(id).tokens).trim() + ))); + } + Ok(permitted) + } + + /// Grant the branches of a conditional that may be a chandle if + /// `granted`. A conditional is a chandle only if both branches are + /// chandles or `null` (11.4.11), whatever reads it. + #[inline(never)] + pub(super) fn conditional( + &mut self, + session: &mut Session, + granted: bool, + branches: [ExprId; 2], + tree: &AnalysisContext<'_>, + native: &Declarations, + dimensions: &PackedDimensions, + ) -> Converted<()> { + if !granted { + return Ok(()); + } + if branches + .iter() + .any(|id| chandle_valued(*id, tree, native, dimensions, session)) + && !branches + .iter() + .all(|id| assignable(*id, tree, native, dimensions, session)) + { + return Err(illegal( + "a conditional chooses a chandle only with another chandle or null", + )); + } + branches.into_iter().for_each(|id| self.grant(id)); + Ok(()) + } + + /// Grant the operands of binary operator `operator` that may be + /// chandles: those of a Boolean operator, and those of an equality that + /// compares a chandle with another chandle or `null`. + #[inline(never)] + pub(super) fn binary( + &mut self, + session: &mut Session, + operator: &str, + left: ExprId, + right: ExprId, + tree: &AnalysisContext<'_>, + native: &Declarations, + dimensions: &PackedDimensions, + ) -> Converted<()> { + if operator == "&&" + || operator == "||" + || check_equality(operator, left, right, tree, native, dimensions, session)? + { + self.grant(left); + self.grant(right); + } + Ok(()) + } +} + +/// Whether `operator` compares `left` and `right` as chandles: an equality +/// of a chandle with another chandle or `null` (6.14), as a `case` +/// statement compares its expression with its items (12.5). An equality of +/// a chandle with another value is an error; other operators are left to +/// the binder, which rejects chandle operands. +#[inline(never)] +pub(in crate::ast) fn check_equality( + operator: &str, + left: ExprId, + right: ExprId, + tree: &AnalysisContext<'_>, + native: &Declarations, + dimensions: &PackedDimensions, + session: &mut Session, +) -> Converted { + if !matches!(operator, "==" | "!=" | "===" | "!==") { + return Ok(false); + } + let chandles = [left, right].map(|id| native_chandle(tree, id, native, dimensions, session)); + if !chandles.contains(&true) { + return Ok(false); + } + let mut comparable = |chandle: bool, id: ExprId| { + chandle || null(id, native) || unbound_hierarchical(tree, id, native, dimensions, session) + }; + if !(comparable(chandles[0], left) && comparable(chandles[1], right)) { + return Err(illegal(format!( + "`{operator}` compares a chandle only with another chandle or null" + ))); + } + Ok(true) +} + +/// Check write target `root`, which may be a chandle if `chandle`. Like +/// [`Permits`] for values, this is the one check of every target: a chandle +/// is written only by a procedural `=` assignment (6.14), not as a part of +/// a concatenation or stream, by a continuous assignment or an operator. +#[inline(never)] +pub(in crate::ast) fn check_target( + chandle: bool, + root: ExprId, + tree: &AnalysisContext<'_>, + native: &Declarations, + dimensions: &PackedDimensions, + session: &mut Session, +) -> Converted<()> { + if !chandle && native_chandle(tree, root, native, dimensions, session) { + return Err(illegal(format!( + "chandle `{}` written as a variable of another type", + native.token_text(native.expression(root).tokens).trim() + ))); + } + Ok(()) +} + +/// The check of [`Permits`] for a value `id` that a binder reads without +/// [`direct::bind_value`], such as the name of a delay. +pub(in crate::ast) fn read( + id: ExprId, + tree: &AnalysisContext<'_>, + native: &Declarations, + dimensions: &PackedDimensions, + session: &mut Session, +) -> Converted<()> { + Permits::new(id, false) + .check(session, id, None, tree, native, dimensions) + .map(drop) +} + +/// Whether data of `shape` holds a chandle, also as a structure member: no +/// integral or bit-stream value (IEEE 1800-2023 6.14, 6.24.3). +pub(in crate::ast) fn holds_chandle(shape: &VariableDimensions) -> bool { + shape.chandle + || shape + .unpacked_struct + .as_ref() + .is_some_and(|aggregate| aggregate.leaves().iter().any(|leaf| leaf.r#type.chandle)) +} + +/// [`holds_chandle`] for data of type `ty`, such as a container element. +pub(in crate::ast) fn type_holds_chandle(ty: &Type) -> bool { + ty.chandle || holds_chandle(&procedural::dimensions_from_type(ty)) +} + +/// Whether a destination of shape `shape` receives a chandle. +pub(super) fn receives_chandle(shape: &VariableDimensions) -> bool { + shape.chandle && shape.unpacked.is_empty() && shape.container.is_none() +} + +/// Check that value native expression `value` may be assigned to a target +/// that is a chandle if `target`: only a chandle or `null` (6.14). That a +/// chandle is assigned to no other target the binder checks (see +/// [`Permits`]). +pub(in crate::ast) fn check_assignment( + target: bool, + value: ExprId, + tree: &AnalysisContext<'_>, + native: &Declarations, + dimensions: &PackedDimensions, + session: &mut Session, +) -> Converted<()> { + if target && !assignable(value, tree, native, dimensions, session) { + return Err(illegal( + "only a chandle or null can be assigned to a chandle", + )); + } + Ok(()) +} + +/// Whether native expression `id` is a chandle, also as a branch of a +/// conditional. +fn chandle_valued( + id: ExprId, + tree: &AnalysisContext<'_>, + native: &Declarations, + dimensions: &PackedDimensions, + session: &mut Session, +) -> bool { + let id = ungroup(id, native); + match &native.expression(id).kind { + ExprKind::Conditional { + then_expression, + else_expression, + .. + } => [*then_expression, *else_expression] + .iter() + .any(|branch| chandle_valued(*branch, tree, native, dimensions, session)), + _ => native_chandle(tree, id, native, dimensions, session), + } +} + +/// Whether native expression `id` may be assigned to a chandle: a chandle, +/// `null`, a call without a known result (such as a container method), or a +/// conditional choosing between such values. +fn assignable( + id: ExprId, + tree: &AnalysisContext<'_>, + native: &Declarations, + dimensions: &PackedDimensions, + session: &mut Session, +) -> bool { + let id = ungroup(id, native); + match &native.expression(id).kind { + ExprKind::Call { .. } => call_result(tree, id, native, dimensions, session) == Some(true), + ExprKind::Conditional { + then_expression, + else_expression, + .. + } => { + assignable(*then_expression, tree, native, dimensions, session) + && assignable(*else_expression, tree, native, dimensions, session) + } + _ => { + null(id, native) + || native_chandle(tree, id, native, dimensions, session) + || unbound_hierarchical(tree, id, native, dimensions, session) + } + } +} + +#[cfg(test)] +mod tests { + use crate::{AnalyzerError, analyze_source}; + use std::path::Path; + + fn analyze(body: &str) -> Result { + analyze_source( + &format!("module Top; {body} endmodule"), + Path::new("chandle.sv"), + ) + } + + #[test] + fn chandles_are_compared_tested_assigned_and_passed() { + analyze( + "chandle a, b; chandle lookup[string]; + class Holder; local chandle h; function bit set(chandle x); h = x; return h != null; endfunction endclass + function automatic chandle pass(chandle h); return h; endfunction + export \"DPI-C\" function pass; + initial begin + automatic chandle c = null; + automatic Holder holder = new; + b = a; c = pass(b); lookup[\"k\"] = c; + if (a == b && c === null && !c && (a || b) && a != lookup[\"k\"]) a = null; + void'(holder.set(c)); + if (pass(a) == a && pass(b) != null) b = pass(a); + end + import \"DPI-C\" function chandle make(); + import \"DPI-C\" function int read(input chandle h); + initial if (make() != null && read(make()) == 0) a = make(); + initial void'(make()); + function automatic chandle defaulted(input chandle x = a); return x; endfunction + initial a = b != null ? pass(b) : null; + class Registry; static chandle h; endclass + initial if (Registry::h == a) a = Registry::h; + bit choose; + initial if ((choose ? a : b) == a && (choose ? null : a) != null) b = null; + initial if ((choose ? a : null) && !(choose ? null : b)) b = null; + function automatic chandle choose_handle(chandle h); return choose ? h : null; endfunction + function automatic chandle or_null(chandle h = null); return h; endfunction + chandle q[$]; + class Keeper; chandle h; function new(input chandle a[$]); h = a[0]; endfunction endclass + initial begin automatic Keeper k = new(q); end + class KeeperChild extends Keeper; function new(input chandle a[$]); super.new(a); endfunction endclass + bit clk; + initial @(posedge clk iff a) b = null; + initial @(posedge clk iff !a && b != null) b = null; + initial begin q.push_back(a); q.push_back(or_null()); a = q[0]; end + initial begin automatic chandle p[$] = '{a, null}; end + initial begin q.push_back(a); if (q.pop_front() == a) a = q.pop_back(); end + class Base; chandle h; function new(chandle x = null); h = x; endfunction endclass + class Derived extends Base; chandle k = null; function new(chandle y); super.new(y); k = y; endfunction endclass + initial begin automatic Derived d = new(a); automatic Base e = new(null); end + initial case (a) null, b: a = null; q[0]: b = null; endcase + int keyed[chandle]; + initial keyed[a] = 1; + typedef chandle H; + H aliased = null; + typedef struct { chandle h; int x; } Holds; + Holds holds; + initial begin holds.h = a; a = holds.h; if (holds.h == a) holds = '{h: null, x: 1}; end + Holds held[$]; + initial begin held.push_back(holds); a = held[0].h; if (held[0].h != a) a = null; end + initial begin a = q.pop_front; if (q.pop_back != a) a = null; end + initial begin q = keyed.find_index() with (item.index == a); q = keyed.find_first_index() with (item.index() != null); end + initial begin automatic chandle k; if (keyed.first(k)) void'(keyed.next(k)); end + initial begin q = q.find() with (item != null); q = q.unique(); q.reverse(); end + initial for (chandle i = null, j = i; i != j; i = null) a = j; + initial foreach (keyed[k]) begin keyed[k] = 2; a = k; end + initial begin q = q.min() with (item != null); q = q.unique() with (item); end + initial begin q.push_back(null); a = q[$]; if (q[$] == a) a = null; end + function automatic chandle take_ref(ref chandle x[$]); return x[0]; endfunction + initial a = take_ref(q); + int sizes; initial sizes = $size(q, 1); + class Source; function chandle get(); return null; endfunction endclass + initial begin automatic Source s = new; s.get(); void'(s.get()); end + initial case (a) default: a = null; endcase", + ) + .unwrap(); + } + + /// No context needs a check of its own to reject a chandle: the binder + /// lets one be only where IEEE 1800-2023 6.14 allows it. + #[test] + fn unlisted_contexts_reject_chandles() { + for body in [ + "chandle h; int n; initial n = $clog2(h);", + "chandle h; int n; initial n = $countones(h);", + "chandle h; longint b; initial b = $signed(h);", + "chandle h; int r; initial r = $urandom(h);", + "chandle h; string s; initial s = $sformatf(\"%d\", h);", + "chandle h; initial $display(h);", + "chandle h; longint unsigned b; initial b = h << 1;", + "chandle h; bit b; initial b = h < h;", + "chandle h; bit b; initial b = h ^ h;", + "chandle h; bit b; initial b = -h == 0;", + "chandle h; bit b; initial wait (h) b = 1;", + "chandle h; int q[$]; initial q.push_back(h);", + "chandle h; bit [63:0] w; initial w = h + 0;", + "chandle h; real r; initial r = h;", + "chandle h; string s; initial s = h;", + "chandle h; initial h += 64'd1;", + "chandle h, g; initial {h, g} = 128'd1;", + "int a[2]; chandle h; int n; initial n = $left(a, h);", + ] { + let result = analyze(body); + assert!( + matches!(result, Err(AnalyzerError::IllegalChandleUse { .. })), + "{body}: {result:?}" + ); + } + // The Boolean tests and comparisons 6.14 lists. + analyze( + "chandle h, g; bit b; int n; + initial begin + if (!h && h == null || g != h) n = 1; + while (h) h = null; + do h = null; while (h); + for (; h; ) h = null; + assert (h || !g); + b = h ? 1'b1 : 1'b0; + b = h === g; + b = (h != null) ? h == g : h !== null; + end", + ) + .unwrap(); + } + + #[test] + fn chandle_results_have_no_dimensions() { + analyze( + "function automatic chandle pass(chandle h); return h; endfunction + import \"DPI-C\" function chandle make(); + if ($dimensions(pass(null)) != 0 || $dimensions(make()) != 0) begin : wrong + chandle w, v; assign w = v; + end", + ) + .unwrap(); + // Container queries count no packed dimension for chandle elements. + let ir = analyze( + "chandle q[$]; chandle m[int][$]; chandle a, b; bit choose; int n, k, c; + initial begin n = $dimensions(q); k = $dimensions(m); c = $dimensions(choose ? a : b); end", + ) + .unwrap(); + let body = format!("{:?}", ir.modules()[0].initial_processes()); + assert!( + body.contains(r#"lhs: Ident("n"), rhs: Literal("1")"#) + && body.contains(r#"lhs: Ident("k"), rhs: Literal("2")"#) + && body.contains(r#"lhs: Ident("c"), rhs: Literal("0")"#), + "{body}" + ); + assert!( + analyze("if ($dimensions(64'd0) != 0) begin : wrong chandle w, v; assign w = v; end") + .is_err() + ); + // A chandle result has 64 bits of storage but no dimension to size. + let ir = analyze( + "function automatic chandle pass(chandle h); return h; endfunction + import \"DPI-C\" function chandle make(); + int b, d, s, t; + initial begin b = $bits(pass(null)); d = $bits(make()); s = $size(make()); t = $size(pass(null)); end", + ) + .unwrap(); + // Also where a declaration or generate condition is discovered. + analyze( + "function automatic chandle pass(chandle h); return h; endfunction + import \"DPI-C\" function chandle make(); + if ($size(make()) === 64 || $size(pass(null)) === 64) begin : wrong + chandle w, v; assign w = v; + end", + ) + .unwrap(); + let body = format!("{:?}", ir.modules()[0].initial_processes()); + assert!( + body.contains(r#"lhs: Ident("b"), rhs: Literal("64")"#) + && body.contains(r#"lhs: Ident("d"), rhs: Literal("64")"#) + && body.contains(r#"lhs: Ident("s"), rhs: Literal("32'bx")"#) + && body.contains(r#"lhs: Ident("t"), rhs: Literal("32'bx")"#), + "{body}" + ); + } + + /// Nested conditionals are classified in time linear in their depth. + #[test] + fn nested_conditionals_of_chandles_are_classified_once() { + let nested = (0..48).fold("h".to_owned(), |inner, _| format!("(c ? {inner} : null)")); + analyze(&format!( + "chandle h; bit c, r; initial begin r = {nested} == null; if ({nested}) r = 1; end" + )) + .unwrap(); + } + + /// UVM keeps chandles in scalars and dynamic containers only; a + /// fixed-size unpacked array of them is rejected where its type is + /// bound, whatever declares it. + #[test] + fn fixed_size_arrays_of_chandles_are_unsupported() { + for body in [ + "chandle a[2];", + "chandle a[0:1];", + "chandle a[2][3];", + "initial begin automatic chandle a[2]; end", + "typedef chandle H[2];", + "typedef chandle H; H a[2];", + "typedef chandle H[2]; H q[$];", + "chandle q[$][2];", + "chandle m[int][2];", + "class C; chandle h[2]; endclass", + "function automatic void f(input chandle a[2]); endfunction", + ] { + let result = analyze(body); + assert!( + matches!(&result, Err(AnalyzerError::Unsupported(reason)) if reason.contains("fixed-size unpacked array of chandle")), + "{body}: {result:?}" + ); + } + analyze("chandle h; chandle q[$]; chandle d[]; chandle m[string]; chandle n[int][$];") + .unwrap(); + } + + #[test] + fn chandles_are_named_chandle() { + let ir = analyze( + "chandle h; chandle q[$]; string s, t; + initial begin s = $typename(h); t = $typename(q); end", + ) + .unwrap(); + let body = format!("{:?}", ir.modules()[0].initial_processes()); + // "chandle" and "chandle$[$]" (IEEE 1800-2023 20.6.1). + assert!( + body.contains(r#"Literal("56'h6368616e646c65")"#) + && body.contains(r#"Literal("88'h6368616e646c65245b245d")"#), + "{body}" + ); + } + + #[test] + fn other_uses_of_chandles_are_rejected() { + for body in [ + "chandle a; int i; initial i = a;", + "chandle a; initial a = 1;", + "chandle q[$]; int i; initial i = q.pop_front;", + "int m[int]; chandle h; initial void'(m.first(h));", + "int m[chandle]; longint unsigned k; initial void'(m.last(k));", + "chandle q[$]; longint unsigned s; initial s = q.sum();", + "chandle q[$], r[$]; initial r = q.min();", + "chandle q[$], r[$]; initial r = q.min() with (item);", + "chandle q[$]; initial q.sort();", + "initial for (chandle h = 64'd1; h != null; h = null) begin end", + "chandle q[$]; int i; initial i = q[$];", + "typedef struct { chandle h; } S; S q[$]; longint unsigned b; initial b = q[0].h[63:0];", + "chandle h; longint unsigned b; initial b = {>>{h}};", + "chandle h; longint unsigned b; initial {>>{h}} = b;", + "class C; chandle h; endclass C c; longint unsigned b; initial b = {>>{c.h}};", + "typedef struct { chandle h; } S; S s; bit b; initial b = s.h[0];", + "class C; chandle h; endclass C c; bit b; initial b = c.h[3];", + "chandle q[]; initial $writememh(\"handles.hex\", q);", + "chandle h; bit done; initial #(h) done = 1;", + "chandle h; bit done; initial #h done = 1;", + "chandle a; int i; initial a = i;", + "chandle a; initial a = a + 1;", + "chandle a; initial if (a == 0) a = null;", + "chandle a; int i; initial i = int'(a);", + "chandle a; initial a += 1;", + "chandle a; initial @(a) a = null;", + "chandle a, b; assign a = b;", + "chandle a; function automatic void f(int x); endfunction initial f(a);", + "chandle a; int i; function automatic void f(chandle x); endfunction initial f(i);", + "import \"DPI-C\" function int read(input chandle h); int r; initial r = read(1);", + "chandle a; function automatic chandle f(); return null; endfunction initial if (f() + 1) a = null;", + "chandle a; function automatic int number(); return 1; endfunction initial a = number();", + "import \"DPI-C\" function int read(input chandle h); function automatic int number(); return 1; endfunction int r; initial r = read(number());", + "chandle a; initial a = a != null ? a : 1;", + "chandle a = 64'd1;", + "class C; static chandle h; endclass int i; initial i = C::h;", + "chandle a, b; bit c; int i; initial i = c ? a : b;", + "chandle h; bit c; int n; initial if (c ? h : 64'd1) n = 1;", + "chandle h, g; bit c, d; int n; initial if (c ? (d ? h : g) : 5) n = 1;", + "chandle h; bit c; int n; initial n = !(c ? 1 : h);", + "chandle a; initial a++;", + "chandle a; initial --a;", + "chandle a; int i; initial i = a++;", + "chandle a; int i; initial i = 1 + --a;", + "chandle a; function automatic chandle forge(); return 1; endfunction initial a = forge();", + "chandle a; function automatic int leak(); return a; endfunction", + "chandle a; initial a[63:0] = 64'd1;", + "chandle a; int i; initial i = a[3];", + "initial begin automatic chandle q[$] = '{64'd1}; end", + "chandle q[$]; initial q.push_back(64'd1);", + "chandle a; function automatic chandle forge(input chandle h = 64'd1); return h; endfunction initial a = forge();", + "chandle a; function automatic int f(input int x = a); return x; endfunction", + "chandle a; int q[$]; initial a = q.pop_front();", + "chandle a; chandle q[$]; int n; initial a = q.size();", + "chandle a; initial a = $urandom();", + "chandle a; longint unsigned bits; initial bits = {a};", + "chandle a; longint unsigned bits; initial bits = {1{a}};", + "chandle a; initial {a} = 64'd1;", + "class C; chandle h; function new(chandle x); h = x; endfunction endclass initial begin automatic C c = new(64'd1); end", + "class B; function new(chandle x); endfunction endclass class D extends B; function new(); super.new(64'd1); endfunction endclass", + "class B; function new(chandle x); endfunction endclass class D extends B(64'd1); endclass", + "class C; chandle h = 64'd1; endclass", + "chandle a; bit c; longint unsigned bits; initial bits = c ? a : 64'd0;", + "chandle a; bit c; initial a = c ? 64'd0 : a;", + "typedef chandle H; H [1:0] pair;", + "typedef chandle H; H [1:0] q[$];", + "typedef chandle H; function automatic void f(H [1:0] x); endfunction", + "typedef chandle H; class C; H [1:0] p; endclass", + "chandle a; int i; initial case (i) a: i = 1; endcase", + "chandle a; initial case (a) 0: a = null; endcase", + "chandle a; initial casez (a) null: a = null; endcase", + "chandle a; initial case (a) inside null: a = null; endcase", + "typedef struct { chandle h; int x; } S; S s; initial s.h = 64'd1;", + "typedef struct { chandle h; } S; S s; int i; initial i = s.h;", + "typedef struct { chandle h; } S; S s; initial s.h++;", + "class C; chandle h; endclass C c; initial begin c = new; c.h += null; end", + "class C; chandle h; endclass C c; initial begin c = new; c.h++; end", + "chandle q[$]; initial q[0] += null;", + "chandle a[string]; initial a[\"k\"] |= null;", + "typedef struct { chandle h; } S; S s; longint unsigned b; initial b = {s.h};", + ] { + let result = analyze(body); + assert!( + matches!( + &result, + Err(AnalyzerError::IllegalChandleUse { .. } + | AnalyzerError::IncompatibleUnpackedArray { .. }) + ), + "{body}: {result:?}" + ); + } + for body in [ + "class C; rand chandle h; endclass initial begin automatic C c = new; void'(c.randomize()); end", + "chandle h; initial void'(std::randomize(h));", + "typedef chandle H; localparam H P = 64'd1;", + "typedef chandle H; localparam H Q = null;", + "class C; chandle h; int x; endclass initial begin automatic C c = new; void'(c.randomize(h)); end", + "chandle q[$]; int fd, n; initial n = $fread(q, fd);", + "class C; chandle h; function new(input chandle a[$]); h = a[0]; endfunction endclass bit [63:0] words[$]; initial begin automatic C c = new(words); end", + "chandle h; function automatic void f(input chandle a[$]); h = a[0]; endfunction bit [63:0] words[$]; initial f(words);", + "class B; chandle h; function new(input chandle a[$]); h = a[0]; endfunction endclass class D extends B; function new(input bit [63:0] words[$]); super.new(words); endfunction endclass", + "typedef struct { chandle h; } S; S s; initial void'(std::randomize(s));", + "typedef chandle H; typedef struct { H [1:0] m; } S; S s;", + "typedef struct { chandle h; } S; S q[$]; int i; initial i = q[0].h;", + "chandle h; bit r; initial r = 64'd0 inside {h};", + "chandle h; bit r; initial r = 64'd0 inside {[h:h]};", + "chandle h; longint unsigned bits; initial bits = $unsigned(h);", + "chandle h; initial void'($value$plusargs(\"ptr=%h\", h));", + "chandle h; int a[2], x; initial x = a[h];", + "chandle h; int q[$], x; initial x = q[h];", + "chandle h; int m[int], x; initial x = m[h];", + "chandle h; int m[chandle], x; initial x = m[0];", + "chandle h; bit b; always @(posedge h) b = 1'b1;", + "chandle h; bit b; always_ff @(posedge h) b <= 1'b1;", + "mailbox #(chandle) m;", + "bit [63:0] words[$]; chandle h; function automatic chandle take(ref chandle x[$]); return x[0]; endfunction initial h = take(words);", + "chandle q[$]; function automatic void take(ref bit [63:0] x[$]); endfunction initial take(q);", + ] { + assert!(analyze(body).is_err(), "{body}"); + } + // The constraint solver supports no chandle operand. + for body in [ + "class C; chandle h; rand bit [63:0] bits; constraint leak { bits == h; } endclass initial begin automatic C c = new; void'(c.randomize()); end", + "class C; chandle h; rand bit [63:0] bits; constraint leak { h != null -> bits == 1; } endclass initial begin automatic C c = new; void'(c.randomize()); end", + ] { + let result = analyze(body); + assert!( + matches!(&result, Err(AnalyzerError::Unsupported(reason)) if reason.contains("a chandle in a constraint")), + "{body}: {result:?}" + ); + } + for body in [ + "chandle h; bit done; initial @h done = 1;", + "chandle h; int a[]; initial a = new[h];", + "chandle h; int a[]; initial a = new[h](a);", + "chandle q[$]; bit [63:0] b[$]; initial b = {>>{q}};", + "chandle d[]; bit [63:0] b; initial b = {<<64{d}};", + "chandle m[int]; bit [63:0] b[$]; initial b = {>>{m}};", + "chandle q[$]; bit [63:0] b[$]; initial q = {>>{b}};", + "chandle q[$]; bit [63:0] b[$]; initial {>>{q}} = b;", + "typedef struct { chandle h; } S; S q[$]; initial q = {>>{64'd1}};", + "typedef struct { chandle h; } S; S q[$]; longint unsigned b; initial b = q.sum();", + "typedef struct { chandle h; } S; S d[]; longint unsigned b; initial b = d.xor();", + "typedef struct { chandle h; } S; S q[$]; bit [63:0] b[$]; initial b = {>>{q}};", + "chandle h; string src = \"x\", dst; initial dst = {h{src}};", + "chandle h; string s = \"abc\"; int c; initial c = s[h];", + "chandle h; string s = \"abc\"; initial s[h] = \"z\";", + "chandle h; string s = \"abc\"; int c; initial c = s.getc(h);", + "chandle h; string s = \"abc\"; initial s.putc(h, \"z\");", + "chandle h; string s = \"abc\", t; initial t = s.substr(h, h);", + "class C; rand bit [63:0] bits; endclass chandle h; initial begin automatic C c = new; void'(c.randomize() with { bits == h; }); end", + "typedef chandle H; typedef enum H { BAD = 64'd1 } E;", + "chandle h; semaphore s; initial s = new(h);", + "chandle h; semaphore s = new; initial s.put(h);", + "chandle h; semaphore s = new; initial s.get(h);", + "chandle h; semaphore s = new; bit ok; initial ok = s.try_get(h);", + "chandle h; int n; initial repeat (h) n++;", + "string s = \"abc\"; chandle h; initial h = s.len();", + "string s = \"abc\"; chandle h; initial h = s.substr(0, 1);", + "typedef enum { A, B } E; E e; chandle h; initial h = e.first();", + "semaphore s = new; chandle h; initial h = s.try_get();", + "class C; rand int x; endclass chandle h; initial begin automatic C c = new; h = c.randomize(); end", + "class C; endclass C c; chandle h; bit ok; initial ok = $cast(c, h);", + "class C; endclass C c; chandle h; initial $cast(c, h);", + "chandle h; mailbox #(int) m; initial m = new(h);", + "chandle h; mailbox #(bit [63:0]) m = new; initial m.put(h);", + "chandle h; mailbox #(bit [63:0]) m = new; initial m.get(h);", + "chandle h; mailbox #(bit [63:0]) m = new; bit ok; initial ok = m.try_peek(h);", + "mailbox #(int) m = new; chandle h; initial h = m.num();", + "typedef enum { A, B, C } E; E e; chandle h; initial e = e.next(h);", + "typedef enum { A, B, C } E; E e; chandle h; initial e = e.prev(h);", + "int a[2]; chandle h; initial h = a.sum();", + "bit [63:0] a[2]; chandle h; initial h = a.xor() with (item);", + "chandle h; initial $fclose(h);", + "chandle h; initial $fflush(h);", + "chandle h; initial $fdisplay(h, \"x\");", + "chandle h; initial $fwrite(h, \"x\");", + "chandle h; initial $finish(h);", + "typedef struct { chandle h; } S; S s; initial s = '{h: '{default: 1}};", + "typedef struct { chandle h; } S; S s; initial s = '{h: '{64'd1}};", + "chandle h; wire [63:0] bits = h;", + "typedef struct { chandle h; } S; S s; int fd, n; initial n = $fread(s, fd);", + "typedef struct { chandle h; } Inner; typedef struct { Inner inner; } Outer; Outer s; int fd, n; initial n = $fread(s.inner, fd);", + "typedef struct { int x; chandle h; } S; S q[$]; int fd, n; initial n = $fread(q, fd);", + "typedef struct { chandle h; } S; S s; initial $writememh(\"s.hex\", s);", + ] { + let result = analyze(body); + assert!( + matches!(result, Err(AnalyzerError::IllegalChandleUse { .. })), + "{body}: {result:?}" + ); + } + // Ports shall not have the chandle data type, also as a structure + // member (6.14). + for source in [ + "module Top(input chandle h); endmodule", + "typedef struct { chandle h; int x; } S; module Top(input S s); endmodule", + "typedef struct { int x; chandle h; } S; module Top(output S s); endmodule", + "typedef struct { chandle h; } S; module Top(s); input S s; endmodule", + ] { + let result = analyze_source(source, Path::new("chandle_port.sv")); + assert!( + matches!(&result, Err(error) if error.to_string().contains("chandle")), + "{source}: {result:?}" + ); + } + } +} 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 c5b56bb1a4d..23bf2f08a75 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -371,6 +371,8 @@ fn check_written_container( Ok(()) } +/// Bind value native expression `root`, which is no chandle unless `target` +/// is a chandle (see [`chandles::Permits`]). pub(in crate::ast) fn bind_value( root: ExprId, native: &Declarations, @@ -379,12 +381,42 @@ pub(in crate::ast) fn bind_value( dimensions: &PackedDimensions, target: Option<&VariableDimensions>, ) -> Converted { + bind_value_in(root, native, tree, dimensions, target, false, session) +} + +/// Bind value native expression `root`, which may be a chandle: a condition +/// tested as a Boolean, or a value a chandle receives (IEEE 1800-2023 6.14). +pub(in crate::ast) fn bind_chandle_value( + root: ExprId, + native: &Declarations, + tree: &AnalysisContext<'_>, + session: &mut Session, + dimensions: &PackedDimensions, + target: Option<&VariableDimensions>, +) -> Converted { + bind_value_in(root, native, tree, dimensions, target, true, session) +} + +fn bind_value_in( + root: ExprId, + native: &Declarations, + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, + target: Option<&VariableDimensions>, + chandle: bool, + session: &mut Session, +) -> Converted { + let mut permits = chandles::Permits::new(root, chandle); let mut jobs = vec![Job::Enter(root, target.cloned().map(Rc::new), None)]; let mut values = Vec::new(); while let Some(job) = jobs.pop() { match job { Job::Enter(id, target, scope) => { let dimensions = scope.as_deref().unwrap_or(dimensions); + // The one check of every value the binder reads: a chandle + // is only where 6.14 allows one. + let permitted = + permits.check(session, id, target.as_deref(), tree, native, dimensions)?; if let Some(value) = dimensions.effect_values.get(&id) { values.push(value.clone()); continue; @@ -610,6 +642,7 @@ pub(in crate::ast) fn bind_value( } let (finish, children) = match &native.expression(id).kind { ExprKind::Group(inner) => { + permits.grant_if(permitted, *inner); jobs.push(Job::Enter(*inner, target, scope.clone())); continue; } @@ -677,6 +710,8 @@ pub(in crate::ast) fn bind_value( expression, postfix: false, } if !matches!(operator.as_str(), "++" | "--") => { + // A Boolean test (6.14). + permits.grant_if(operator == "!", *expression); (Finish::Unary(operator.clone()), vec![(*expression, None)]) } ExprKind::Binary { @@ -689,6 +724,8 @@ pub(in crate::ast) fn bind_value( tree, session, *left, *right, native, dimensions, )?; } + permits + .binary(session, operator, *left, *right, tree, native, dimensions)?; ( Finish::Binary(operator.clone()), vec![(*left, None), (*right, None)], @@ -699,7 +736,20 @@ pub(in crate::ast) fn bind_value( then_expression, else_expression, } => ( - Finish::Mux, + { + // The condition is a Boolean test; the branches + // are values where the conditional is one. + permits.grant(*condition); + permits.conditional( + session, + permitted, + [*then_expression, *else_expression], + tree, + native, + dimensions, + )?; + Finish::Mux + }, vec![ (*condition, None), (*then_expression, target.clone()), @@ -841,6 +891,16 @@ pub(in crate::ast) fn bind_value( session, dimensions, )?; + check_argument( + &name, + first + position, + position + 1, + value, + native, + tree, + dimensions, + session, + )?; check_written_container( &name, first + position, @@ -863,6 +923,7 @@ pub(in crate::ast) fn bind_value( let shape = shape .filter(|shape| { shape.unpacked_struct.is_some() + || chandles::receives_chandle(shape) || (shape.container.is_some() || shape.virtual_interface.is_some()) && copied_in @@ -1132,6 +1193,8 @@ pub(in crate::ast) fn bind_value( if function.writes_argument(position) && let Some(id) = id { + // Such as `$fread` into a memory. + chandles::check_memory(*id, tree, dimensions, session)?; check_tagged_copyout(*id, None, tree, session, dimensions)?; } } @@ -1151,6 +1214,16 @@ pub(in crate::ast) fn bind_value( references::check_actual( &name, position, *id, native, tree, session, dimensions, )?; + check_argument( + &name, + position, + position + 1, + *id, + native, + tree, + dimensions, + session, + )?; check_written_container( &name, position, *id, tree, session, dimensions, )?; @@ -1185,14 +1258,6 @@ pub(in crate::ast) fn bind_value( )?; } } - array_compatibility::check_native_unpacked_assignment( - tree, - session, - *id, - shape, - || format!("argument {} of `{name}`", position + 1), - dimensions, - )?; } } let children = actuals @@ -2228,6 +2293,20 @@ fn selected_value( )); } } + if let ExprKind::Name(name) = &native.expression(base).kind + && dimensions + .get(&instances::normalize_identifier(&name.spelling)) + .is_some_and(|ty| ty.chandle && suffix.len() > ty.unpacked.len()) + { + return Err(chandles::packed_select()); + } + // Nor does a chandle member, property or call result. + if !suffix.is_empty() + && !matches!(native.expression(base).kind, ExprKind::Name(_)) + && chandles::native_chandle(tree, base, native, dimensions, session) + { + return Err(chandles::packed_select()); + } // A select of a member of a container element reads the member first. let element_member = if suffix.is_empty() { None @@ -2391,6 +2470,12 @@ pub(in crate::ast) fn selected_lvalue( }) { return Err(unsupported("bit-select or part-select of a tagged union")); } + if context + .get(&name) + .is_some_and(|ty| ty.chandle && suffix.len() > ty.unpacked.len()) + { + return Err(chandles::packed_select()); + } if context .get(&name) .is_some_and(|ty| ty.real && suffix.len() > ty.unpacked.len()) @@ -2842,6 +2927,106 @@ fn zero_based_vector( zero_based && r#type.members.is_empty() } +/// An actual of formal `position` of subroutine `name` is assigned to the +/// formal, and is therefore a chandle exactly when the formal is one (IEEE +/// 1800-2023 6.14). +fn check_chandle_argument( + name: &str, + position: usize, + actual: ExprId, + native: &Declarations, + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, + session: &mut Session, +) -> Converted<()> { + let Some(formal) = dimensions + .subroutine_param_shapes + .get(name) + .and_then(|shapes| shapes.get(position)) + else { + return Ok(()); + }; + chandles::check_assignment( + formal.chandle && formal.unpacked.is_empty(), + actual, + tree, + native, + dimensions, + session, + ) +} + +/// Check actual `actual` of formal `position` of subroutine `name`, which +/// the call assigns to the formal (IEEE 1800-2023 13.5): a chandle formal +/// takes only a chandle or `null`, and an unpacked array formal an array of +/// its type. Every call binds its actuals after this check; `ordinal` +/// numbers the argument in diagnostics. +pub(in crate::ast) fn check_argument( + name: &str, + position: usize, + ordinal: usize, + actual: ExprId, + native: &Declarations, + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, + session: &mut Session, +) -> Converted<()> { + check_chandle_argument(name, position, actual, native, tree, dimensions, session)?; + if let Some(shape) = dimensions + .subroutine_param_shapes + .get(name) + .and_then(|shapes| shapes.get(position)) + { + array_compatibility::check_native_unpacked_assignment( + tree, + session, + actual, + shape, + || format!("argument {ordinal} of `{name}`"), + dimensions, + )?; + } + Ok(()) +} + +/// Bind actual `actual` of formal `position` of subroutine `name`, which +/// may be a chandle exactly when the formal is one. +pub(in crate::ast) fn bind_argument( + name: &str, + position: usize, + actual: ExprId, + native: &Declarations, + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, + session: &mut Session, +) -> Converted { + check_argument( + name, position, position, actual, native, tree, dimensions, session, + )?; + let target = copied_in_target(dimensions, name, position); + bind_value_in(actual, native, tree, dimensions, target, false, session) +} + +/// The shape that actual `position` of subroutine `name` is bound for: a +/// chandle formal receives a chandle (6.14), a virtual interface input +/// only a virtual interface of its type (25.9) and a container input a +/// container of an equivalent element type (7.6). +pub(in crate::ast) fn copied_in_target<'a>( + dimensions: &'a PackedDimensions, + name: &str, + position: usize, +) -> Option<&'a VariableDimensions> { + dimensions + .subroutine_param_shapes + .get(name) + .and_then(|shapes| shapes.get(position)) + .filter(|shape| { + chandles::receives_chandle(shape) + || (shape.virtual_interface.is_some() || shape.container.is_some()) + && copied_in(dimensions, name, position) + }) +} + #[cfg(test)] mod string_literal_tests { use super::packed_string_literal; diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/lvalues.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/lvalues.rs index ef6d636ec88..81563013c85 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/lvalues.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/lvalues.rs @@ -1,12 +1,16 @@ //! Assignment targets bind native name/member/selection identities directly. use super::*; +/// The variable target `root` of a procedural write, which may be a chandle +/// if `chandle`: an assignment with `=` writes one (IEEE 1800-2023 6.14). pub(in crate::ast) fn variable_lvalue( root: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, session: &mut Session, dimensions: &PackedDimensions, + chandle: bool, ) -> Converted { + chandles::check_target(chandle, root, tree, native, dimensions, session)?; direct::selected_lvalue(root, native, tree, session, dimensions, false) } pub(in crate::ast) fn net_lvalue( @@ -16,6 +20,8 @@ pub(in crate::ast) fn net_lvalue( session: &mut Session, dimensions: &PackedDimensions, ) -> Converted { + // No continuous assignment drives a chandle (6.14). + chandles::check_target(false, root, tree, native, dimensions, session)?; if direct::member_context(root, native, tree, session, dimensions)? .is_some_and(|(guards, _)| !guards.is_empty()) { @@ -66,7 +72,14 @@ mod tests { let target = if continuous { net_lvalue(root, &native, &tree, session, &PackedDimensions::default()) } else { - variable_lvalue(root, &native, &tree, session, &PackedDimensions::default()) + variable_lvalue( + root, + &native, + &tree, + session, + &PackedDimensions::default(), + false, + ) } .unwrap(); let LValue::Select { msb, lsb, .. } = target else { @@ -116,7 +129,14 @@ mod tests { let target = if continuous { net_lvalue(root, &native, &tree, session, &PackedDimensions::default()) } else { - variable_lvalue(root, &native, &tree, session, &PackedDimensions::default()) + variable_lvalue( + root, + &native, + &tree, + session, + &PackedDimensions::default(), + false, + ) } .unwrap(); let LValue::Select { msb, lsb, .. } = target else { diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs index 8711a964cb7..e3228a4f890 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -1062,17 +1062,22 @@ pub(in crate::ast) fn constructor( } let mut args = vec![Some(class.allocation())]; let (actuals, order) = class.constructor_arguments(arguments)?; - // A virtual interface formal receives only a virtual interface of its - // type (IEEE 1800-2023 25.9); the object is the first formal. + // The object is the first formal. let name = Class::subroutine_name(&class_name, "new"); - let shapes = dimensions.subroutine_param_shapes.get(&name); for (position, actual) in actuals.into_iter().enumerate() { - let target = shapes - .and_then(|shapes| shapes.get(position + 1)) - .filter(|shape| { - shape.virtual_interface.is_some() - && super::direct::copied_in(dimensions, &name, position + 1) - }); + if let Some(value) = actual { + direct::check_argument( + &name, + position + 1, + position + 1, + value, + native, + tree, + dimensions, + session, + )?; + } + let target = super::direct::copied_in_target(dimensions, &name, position + 1); args.push( actual .map(|value| bind_value(value, native, tree, session, dimensions, target)) @@ -1080,7 +1085,7 @@ pub(in crate::ast) fn constructor( ); } Ok(Some(Expr::Call { - callee: Callee::Subroutine(Class::subroutine_name(&class_name, "new")), + callee: Callee::Subroutine(name), args, // The allocation is passed first; the actuals are evaluated in the // order they are written (13.5.4). @@ -1135,6 +1140,7 @@ pub(super) fn random_selection( return Err(unsupported("randomization of a 4-state class property")); } if property.field.handle.is_some() + || property.r#type.holds_chandle() || (property.r#type.is_enum && property.r#type.enum_domain.is_none()) || (property.randc && property.cyclic_domain_size().is_none()) { @@ -1480,6 +1486,11 @@ pub(super) fn randomize_with( let variable = dimensions .get(&name) .ok_or_else(|| unsupported(format!("inline local variable `{name}`")))?; + if variable.chandle { + return Err(AnalyzerError::IllegalChandleUse { + detail: "a chandle in a constraint".into(), + }); + } if variable.real || variable.string || variable.class.is_some() diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/references.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/references.rs index 170879d450a..81e72ee472f 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/references.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/references.rs @@ -202,7 +202,8 @@ fn equivalent( env: &HashMap, ) -> bool { let functions = &tree.functions; - if a.virtual_interface != b.virtual_interface { + // A chandle is equivalent only to a chandle (IEEE 1800-2023 6.14). + if a.virtual_interface != b.virtual_interface || a.chandle != b.chandle { return false; } let count = |width: &ConstExpr| eval_ast_const_expr(functions, width, env); diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/streams.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/streams.rs index 325febbde6e..9a5dfb203da 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/streams.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/streams.rs @@ -99,6 +99,12 @@ fn fixed_array( Ok(Some((array.element_width, count))) } +fn chandle() -> AnalyzerError { + AnalyzerError::IllegalChandleUse { + detail: "a chandle is not of bit-stream type".into(), + } +} + /// Reject the kinds of data a fixed-size stream cannot hold. fn check_fixed(shape: &VariableDimensions) -> Converted<()> { if shape.container.is_some() { @@ -113,6 +119,9 @@ fn check_fixed(shape: &VariableDimensions) -> Converted<()> { // 6.24.3: real is not a bit-stream type. return Err(invalid("a real value is not of bit-stream type")); } + if chandles::holds_chandle(shape) { + return Err(chandle()); + } if shape.class.is_some() { return Err(unsupported("streaming concatenation of a class handle")); } @@ -137,6 +146,9 @@ pub(in crate::ast) enum Receiver { /// array of integral or string elements. fn stream_container(container: &ContainerType) -> Converted { let layout = container.layout; + if chandles::type_holds_chandle(&container.element) { + return Err(chandle()); + } if matches!(layout.kind, ContainerKind::Associative { .. }) { // 6.24.3: an associative array is illegal as a destination type. return Err(invalid("an associative array cannot receive a stream")); @@ -170,6 +182,9 @@ pub(in crate::ast) fn receiver( "the target of a stream shall be of bit-stream type", )); } + if chandles::holds_chandle(shape) { + return Err(chandle()); + } if shape.class.is_some() { return Err(unsupported("streaming concatenation into a class handle")); } @@ -343,6 +358,9 @@ fn operand( }; if let Some(container) = container { let layout = container.layout; + if chandles::type_holds_chandle(&container.element) { + return Err(chandle()); + } if layout.handle == Some(HandleProperty::Object) { return Err(unsupported( "streaming concatenation of class handles or structures in a container", @@ -818,7 +836,7 @@ pub(in crate::ast) fn unpack( second, ]), }); - lvalues.push(variable_lvalue(id, native, tree, session, dims)?); + lvalues.push(variable_lvalue(id, native, tree, session, dims, false)?); continue; } if dynamic { @@ -833,7 +851,7 @@ pub(in crate::ast) fn unpack( }, None => Take::String { reserve }, }); - lvalues.push(variable_lvalue(id, native, tree, session, dims)?); + lvalues.push(variable_lvalue(id, native, tree, session, dims, false)?); continue; } check_fixed(&shape)?; @@ -869,7 +887,7 @@ pub(in crate::ast) fn unpack( unreachable!("a fixed-size variable receives fixed-size data"); }; takes.push(Take::Fixed(target)); - lvalues.push(variable_lvalue(id, native, tree, session, dims)?); + lvalues.push(variable_lvalue(id, native, tree, session, dims, false)?); } let source = if is_stream(right, native) { vec![match packed(right, native, tree, session, dims)? { diff --git a/crates/celox-sv-analyzer/src/ast/ff_process.rs b/crates/celox-sv-analyzer/src/ast/ff_process.rs index a174aac40e6..c61c4f498e1 100644 --- a/crates/celox-sv-analyzer/src/ast/ff_process.rs +++ b/crates/celox-sv-analyzer/src/ast/ff_process.rs @@ -160,6 +160,9 @@ fn ff_event_control_and_body( { return Ok(None); } + // Bound without the types of the scope, so its value is checked + // with them. + expression_binding::check_chandle_read(item.expression, tree, native, dimensions, session)?; let expression = expression_binding::value( item.expression, native, diff --git a/crates/celox-sv-analyzer/src/ast/functions.rs b/crates/celox-sv-analyzer/src/ast/functions.rs index 270715cd883..cdfec916ee7 100644 --- a/crates/celox-sv-analyzer/src/ast/functions.rs +++ b/crates/celox-sv-analyzer/src/ast/functions.rs @@ -248,6 +248,9 @@ fn native_signature( .is_some_and(|ty| matches!(ty.kind(), TypeKind::Real | TypeKind::Shortreal)), return_string: ty.as_ref().is_some_and(|ty| ty.kind() == TypeKind::String), return_handle: ty.as_ref().is_some_and(|ty| ty.kind() == TypeKind::Object), + return_chandle: ty + .as_ref() + .is_some_and(|ty| ty.chandle && ty.unpacked_ranges.is_empty()), name: instances::normalize_identifier(&native.name.spelling), params, body: None, @@ -256,7 +259,8 @@ fn native_signature( return_first_packed_dimension_width: first, return_dimensions: ty.as_ref().map(|ty| { ty.unpacked_ranges().len() - + if matches!(ty.kind(), TypeKind::Real | TypeKind::Shortreal) { + // A chandle has no packed dimensions (IEEE 1800-2023 6.14). + + if ty.chandle || matches!(ty.kind(), TypeKind::Real | TypeKind::Shortreal) { 0 } else { ty.packed_ranges().len() diff --git a/crates/celox-sv-analyzer/src/ast/generate.rs b/crates/celox-sv-analyzer/src/ast/generate.rs index 170fbebc2a9..aee64d7b87b 100644 --- a/crates/celox-sv-analyzer/src/ast/generate.rs +++ b/crates/celox-sv-analyzer/src/ast/generate.rs @@ -2129,6 +2129,7 @@ mod tests { signed: false, is_2state: false, string: false, + chandle: false, pattern_type: None, enum_domain: None, class: None, @@ -2142,6 +2143,7 @@ mod tests { signed: true, is_2state: true, string: false, + chandle: false, pattern_type: None, enum_domain: None, class: None, diff --git a/crates/celox-sv-analyzer/src/ast/generate/memo/sites.rs b/crates/celox-sv-analyzer/src/ast/generate/memo/sites.rs index 592cca1c4a9..d15a83d207a 100644 --- a/crates/celox-sv-analyzer/src/ast/generate/memo/sites.rs +++ b/crates/celox-sv-analyzer/src/ast/generate/memo/sites.rs @@ -163,6 +163,7 @@ impl CallSites for Type { container: _, unpacked_struct: _, spelling: _, + chandle: _, } = self; packed_ranges.call_sites(visit); unpacked_ranges.call_sites(visit); @@ -206,6 +207,7 @@ impl CallSites for VariableDimensions { members, signed_element_depth: _, unpacked_struct: _, + chandle: _, } = self; packed.call_sites(visit); unpacked.call_sites(visit); diff --git a/crates/celox-sv-analyzer/src/ast/locators.rs b/crates/celox-sv-analyzer/src/ast/locators.rs index 29dec868117..f62dd8dd97a 100644 --- a/crates/celox-sv-analyzer/src/ast/locators.rs +++ b/crates/celox-sv-analyzer/src/ast/locators.rs @@ -259,6 +259,13 @@ fn parse( })) } +/// Chandles have no relational operators to order them (6.14, 7.12.1). +fn min_max_chandles() -> AnalyzerError { + AnalyzerError::IllegalChandleUse { + detail: "the minimum or maximum of chandles".into(), + } +} + /// The array that `base` names, if it is an unpacked array whose elements a /// locator method can return. fn array( @@ -326,6 +333,7 @@ fn array( ty.enum_domain = shape.enum_domain.clone(); ty.packed_enum = shape.packed_enum; ty.signed_element_depth = shape.signed_element_depth; + ty.chandle = shape.chandle; ty }; let width = casts::expr_type_from_type(&tree.functions, &element, &dims.const_env) @@ -465,7 +473,16 @@ pub(super) fn bind( scope .expression_signedness .insert(index.clone(), index_type.is_signed()); - let mut value = expression_binding::value(predicate, native, tree, session, &scope)?; + // A find tests its expression as a Boolean, and `unique` + // compares the values for equality, either of which takes a + // chandle (6.14); the order `min` and `max` take does not. + let mut value = if matches!(call.method, LocatorMethod::Min | LocatorMethod::Max) { + expression_binding::value(predicate, native, tree, session, &scope)? + } else { + expression_binding::bind_chandle_value( + predicate, native, tree, session, &scope, None, + )? + }; let key = if call.method.finds() { None } else if expression_binding::string_value(&value, &scope) { @@ -500,6 +517,11 @@ pub(super) fn bind( None => { let key = match &call.array { _ if element.kind() == TypeKind::String => LocatorKey::String, + _ if element.chandle + && matches!(call.method, LocatorMethod::Min | LocatorMethod::Max) => + { + return Err(min_max_chandles()); + } _ if element.class().is_some() || element.unpacked_struct().is_some() || element.container.is_some() => diff --git a/crates/celox-sv-analyzer/src/ast/mailboxes.rs b/crates/celox-sv-analyzer/src/ast/mailboxes.rs index 5ce21117aaa..db335672340 100644 --- a/crates/celox-sv-analyzer/src/ast/mailboxes.rs +++ b/crates/celox-sv-analyzer/src/ast/mailboxes.rs @@ -40,6 +40,9 @@ impl Message { "mailbox messages that are not integral values, strings or handles", )); } + if ty.is_chandle() { + return Err(unsupported("mailbox messages that are chandles")); + } let shape = casts::expr_type_from_type(functions, ty, env) .ok_or_else(|| unsupported("mailbox message type"))?; if shape.width == 0 || shape.width > 64 { diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs.rs b/crates/celox-sv-analyzer/src/ast/packed_structs.rs index e06d9aa2356..0db3eb9d9fb 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs.rs @@ -12,7 +12,7 @@ pub(in crate::ast) use tagged::{ mod tests; pub(super) use layout::{AggregateKind, capture_member_type, native_type}; -pub(super) use selects::{select_member, whole_member}; +pub(super) use selects::{bind_interface_path, select_member, whole_member}; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub(super) struct PackedMember { diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs b/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs index d86e72a8f1f..214a4c5f28f 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs @@ -53,7 +53,8 @@ pub(in crate::ast) fn native_type( let members = fields .into_iter() .map(|(name, ty, is_void)| { - if !names.insert(name.clone()) { + // A chandle is no packed type (IEEE 1800-2023 6.14). + if !names.insert(name.clone()) || ty.chandle { return None; } Some(PackedMember { 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 b8a501d88a3..3eddd4dbbf6 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs @@ -4,7 +4,7 @@ use super::*; /// Collapse an interface handle/member prefix using its bound symbols. Any /// remaining path selects a packed-structure member of the interface signal. -pub(super) fn bind_interface_path( +pub(in crate::ast) fn bind_interface_path( tree: &AnalysisContext<'_>, path: &mut Vec, dimensions: &PackedDimensions, @@ -76,6 +76,7 @@ fn member_dimensions(name: &str, r#type: &Type, dimensions: &PackedDimensions) - VariableDimensions { declared: type_names::Declared::default(), container: None, + chandle: false, randomizable: true, enum_domain: None, packed_enum: false, diff --git a/crates/celox-sv-analyzer/src/ast/parameters/declaration_types.rs b/crates/celox-sv-analyzer/src/ast/parameters/declaration_types.rs index 5ee5ed7b395..727154d4607 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/declaration_types.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/declaration_types.rs @@ -30,6 +30,8 @@ pub(super) fn prefix<'a>( None, Some( type_binding::builtin_type(name, data.signed) + // A chandle is no constant (IEEE 1800-2023 6.14). + .filter(|ty| !ty.chandle) .ok_or_else(|| unsupported("unsupported parameter data type"))?, ), ), @@ -39,7 +41,12 @@ pub(super) fn prefix<'a>( .map(|part| instances::normalize_identifier(&part.name.spelling)) .collect::>() .join("::"); - (aliases.get(&name).cloned(), None) + let alias = aliases.get(&name).cloned(); + // Nor is a chandle named by a typedef. + if alias.as_ref().is_some_and(Type::holds_chandle) { + return Err(unsupported("unsupported parameter data type")); + } + (alias, None) } _ => return Err(unsupported("unsupported parameter data type")), }; diff --git a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs index b7a5b7745d0..828fc03a09f 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs @@ -484,6 +484,7 @@ fn pattern_items( VariableDimensions { declared: type_names::Declared::default(), container: None, + chandle: false, real: false, string: false, class: None, @@ -525,6 +526,7 @@ fn pattern_items( VariableDimensions { declared: type_names::Declared::default(), container: None, + chandle: false, randomizable: true, enum_domain: None, packed_enum: false, diff --git a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs index 070d9a2d04c..4d253b32e0d 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs @@ -149,6 +149,7 @@ fn select<'a>( let sub = Shape::Owned(Rc::new(VariableDimensions { declared: type_names::Declared::default(), container: None, + chandle: false, randomizable: true, enum_domain: None, packed_enum: false, @@ -264,6 +265,7 @@ fn select<'a>( let bit = Shape::Owned(Rc::new(VariableDimensions { declared: type_names::Declared::default(), container: None, + chandle: false, randomizable: true, enum_domain: None, packed_enum: false, @@ -504,6 +506,12 @@ pub(in crate::ast) fn bind_native( continue; } if pattern { + // A chandle has no elements a pattern could give (6.14). + if shape.chandle && shape.unpacked.is_empty() { + expression_binding::check_chandle_assignment( + true, id, tree, native, dims, session, + )?; + } let typed = typed_shape(id, tree, dims)?; jobs.push(Job::Pattern( id, @@ -512,8 +520,17 @@ pub(in crate::ast) fn bind_native( .unwrap_or(shape), )); } else { - let value = - expression_binding::bind_value(id, native, tree, session, dims, None)?; + let chandle = shape.chandle && shape.unpacked.is_empty(); + expression_binding::check_chandle_assignment( + chandle, id, tree, native, dims, session, + )?; + let value = if chandle { + expression_binding::bind_chandle_value( + id, native, tree, session, dims, None, + )? + } else { + expression_binding::bind_value(id, native, tree, session, dims, None)? + }; let type_dims = dimensions::query_context_for_operand(id, tree, session, dims)?; let signed = dimensions::expression_signedness(&value, &type_dims, &type_dims.const_env) diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index df448b4cef3..2335bdb0cc2 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -86,6 +86,8 @@ pub(super) struct BodyBuilder<'s, 't, 'a> { /// The shape of any return type, which a returned stream is aligned to /// (IEEE 1800-2023 11.4.14). stream_return_shape: Option, + /// Whether the function's result is a chandle, `None` without a result. + return_chandle: Option, pub(super) sensitivity_body: Vec, } @@ -170,8 +172,10 @@ impl Names { /// The packed and unpacked shape of a declared type, as selects see it. pub(super) fn dimensions_from_type(r#type: &Type) -> VariableDimensions { VariableDimensions { + chandle: r#type.chandle, container: r#type.container.clone(), randomizable: r#type.container.is_none() + && !r#type.holds_chandle() && (!r#type.is_enum || r#type.enum_domain.is_some()), enum_domain: r#type.enum_domain.clone(), packed_enum: r#type.packed_enum, @@ -379,6 +383,7 @@ pub(super) fn rename_expr_idents( pub(super) fn int_type() -> Type { Type { container: None, + chandle: false, is_enum: false, enum_domain: None, packed_enum: false, @@ -421,6 +426,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { task_timing: false, return_shape: None, stream_return_shape: None, + return_chandle: None, sensitivity_body: Vec::new(), tree, session, @@ -643,9 +649,27 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { Ok(value) } + /// [`Self::native_value`] of a value that may be a chandle: a condition + /// tested as a Boolean, or a value compared or assigned as a chandle + /// (IEEE 1800-2023 6.14). + fn native_chandle_value(&mut self, id: celox_sv_syntax::ExprId) -> Result { + let mut value = expression_binding::bind_chandle_value( + id, + self.tree.declarations(), + self.tree, + self.session, + &self.dims, + None, + )?; + self.rename_expr(&mut value); + Ok(value) + } + + /// The target `id` of a write, which may be a chandle if `chandle`. fn native_lvalue( &mut self, id: celox_sv_syntax::ExprId, + chandle: bool, ) -> Result<(LValue, LValue), AnalyzerError> { let lowered = expression_binding::variable_lvalue( id, @@ -653,6 +677,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { self.tree, self.session, &self.dims, + chandle, )?; virtual_interfaces::check_target(&lowered)?; let mut renamed = lowered.clone(); @@ -692,6 +717,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { self.tree, self.session, &self.dims, + false, )?; virtual_interfaces::check_target(&target)?; self.rename_lvalue(&mut target); @@ -721,6 +747,33 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { "assignment to a member of a dynamic container element", )); } + let declarations = self.tree.declarations(); + // A chandle is only assigned (IEEE 1800-2023 6.14); the destinations + // dispatched below write without `variable_lvalue`, so its target + // check runs here. + expression_binding::check_chandle_target( + op == "=", + left, + self.tree, + declarations, + &self.dims, + self.session, + )?; + let chandle = expression_binding::native_chandle( + self.tree, + left, + declarations, + &self.dims, + self.session, + ); + expression_binding::check_chandle_assignment( + chandle, + right, + self.tree, + declarations, + &self.dims, + self.session, + )?; if let Some(mut stmt) = containers::set( left, right, @@ -818,7 +871,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { if op != "=" { self.reject_tagged_integral_target(left)?; } - let (written, lhs) = self.native_lvalue(left)?; + let (written, lhs) = self.native_lvalue(left, op == "=")?; if op != "=" && expression_binding::native_string( self.tree, @@ -925,6 +978,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { self.tree, self.session, &self.dims, + op == "=", ) else { return Ok(None); }; @@ -1180,7 +1234,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { stmts.push(self.property_store(&property, handle, "=", value)?); return Ok(stmts); } - let (_, lhs) = self.native_lvalue(output)?; + let (_, lhs) = self.native_lvalue(output, false)?; let mut rhs = value; self.rename_expr(&mut rhs); stmts.push(Stmt::Assign { @@ -1399,6 +1453,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { self.tree, self.session, &self.dims, + false, )?; let mut renamed = lowered.clone(); self.rename_lvalue(&mut renamed); @@ -1588,7 +1643,16 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { { return Ok(None); } - expression_binding::value(root, native, self.tree, self.session, &self.dims)? + // The result of a call statement is discarded, which a + // chandle result may be (IEEE 1800-2023 6.14). + expression_binding::bind_chandle_value( + root, + native, + self.tree, + self.session, + &self.dims, + None, + )? } _ => { let Some((name, formals, receiver)) = expression_binding::object_method( @@ -1693,7 +1757,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { self.rename_expr(&mut store); return Ok(Stmt::Eval(store)); } - let (written, lhs) = self.native_lvalue(string)?; + let (written, lhs) = self.native_lvalue(string, false)?; let LValue::Ident(name) = &written else { return Err(unsupported(format!( "string method `{op}` on an array element" @@ -1954,6 +2018,14 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { signal.name().to_string(), dimensions_from_type(signal.r#type()), ); + expression_binding::check_chandle_assignment( + signal.r#type().chandle && signal.r#type().unpacked_ranges.is_empty(), + root, + self.tree, + self.tree.declarations(), + &self.dims, + self.session, + )?; let mut init = expression_binding::expression( root, self.tree.declarations(), @@ -2236,7 +2308,8 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { .map(|arg| arg.value.filter(|_| arg.name.is_none())) .collect::>>() .filter(|args| args.len() == count) - .ok_or_else(|| unsupported(format!("arguments of string method `{op}`")))? + .ok_or_else(|| unsupported(format!("arguments of string method `{op}`")))?; + let args = args .into_iter() .map(|arg| { expression_binding::value(arg, native, self.tree, self.session, &self.dims) @@ -2562,6 +2635,11 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { } system_functions::SystemCall::Task(task) => task, }; + if matches!(task, SystemTask::Readmem(_) | SystemTask::Writemem(_)) + && let Some(memory) = arguments.get(1).and_then(|arg| arg.value) + { + expression_binding::check_chandle_memory(memory, self.tree, &self.dims, self.session)?; + } let args = arguments .iter() .enumerate() @@ -2696,12 +2774,14 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { if item.pattern.is_some() { return Err(unsupported("pattern matching in a condition")); } - let condition = expression_binding::value( + // A Boolean test, which may be of a chandle (IEEE 1800-2023 6.14). + let condition = expression_binding::bind_chandle_value( item.expression, self.tree.declarations(), self.tree, self.session, &self.dims, + None, )?; let mut condition = statements::simplify_condition(self.tree, self.session, condition, &self.dims); @@ -2734,6 +2814,14 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { let target = LValue::Ident(source.clone()); let mut scoped = self.dims.clone(); scoped.insert(source.clone(), dimensions_from_type(&ty)); + expression_binding::check_chandle_assignment( + ty.chandle && ty.unpacked_ranges.is_empty(), + variable.value, + self.tree, + self.tree.declarations(), + &self.dims, + self.session, + )?; let mut value = expression_binding::expression( variable.value, self.tree.declarations(), @@ -2769,7 +2857,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { None => (None, Vec::new()), Some(id) => match self.loop_condition(id)? { Some(prologue) => (None, prologue), - None => (Some(self.native_value(id)?), Vec::new()), + None => (Some(self.native_chandle_value(id)?), Vec::new()), }, }; let mut steps = Vec::new(); @@ -3568,9 +3656,19 @@ pub(super) fn lower_subroutine( &builder.dims, )?; } - // The default of a container input is a container value. + expression_binding::check_chandle_assignment( + ty.chandle && ty.unpacked_ranges.is_empty(), + root, + tree, + tree.declarations(), + &builder.dims, + builder.session, + )?; + // The default of a container input is a container value; + // that of a chandle, a chandle. let shape = (ty.tagged_identity().is_some() || ty.unpacked_struct().is_some() + || ty.chandle && ty.unpacked_ranges.is_empty() || ty.container.is_some() && *direction == ParamDirection::Input) .then(|| dimensions_from_type(ty)); let mut value = expression_binding::bind_value( @@ -3708,6 +3806,9 @@ pub(super) fn lower_subroutine( } // The members of formals and of the result have the subroutine's // lifetime, like the formals themselves. + builder.return_chandle = return_type + .as_ref() + .map(|ty| ty.chandle && ty.unpacked_ranges.is_empty()); let parameter_locals_end = builder.state.locals.len(); let mut items = native.items.clone(); let mut prologue = Vec::new(); @@ -4089,16 +4190,20 @@ impl BodyBuilder<'_, '_, '_> { } let mut args = vec![Some(Expr::Ident(this.to_owned()))]; let (actuals, order) = base.constructor_arguments(arguments)?; - for actual in actuals { + let name = classes::Class::subroutine_name(&base.name, "new"); + for (index, actual) in actuals.into_iter().enumerate() { args.push( actual .map(|value| { - let mut value = expression_binding::value( + // The formals start with the object's handle. + let mut value = expression_binding::bind_argument( + &name, + index + 1, value, native, self.tree, - self.session, &self.dims, + self.session, )?; self.rename_expr(&mut value); Ok::<_, AnalyzerError>(value) @@ -4107,7 +4212,7 @@ impl BodyBuilder<'_, '_, '_> { ); } body.push(Stmt::Call { - name: classes::Class::subroutine_name(&base.name, "new"), + name, args, arg_order: std::iter::once(0) .chain(order.into_iter().map(|index| index + 1)) @@ -4154,6 +4259,14 @@ impl BodyBuilder<'_, '_, '_> { )?, None => None, }; + expression_binding::check_chandle_assignment( + property.r#type.chandle && property.r#type.unpacked_ranges.is_empty(), + initializer, + self.tree, + native, + &self.dims, + self.session, + )?; let mut value = match value.take() { Some(value) => value, None => expression_binding::bind_value( @@ -4373,8 +4486,14 @@ impl BodyBuilder<'_, '_, '_> { property.r#type.clone(), ); self.dims.property_select_base = Some(base); - let lhs = - expression_binding::variable_lvalue(left, native, self.tree, self.session, &self.dims); + let lhs = expression_binding::variable_lvalue( + left, + native, + self.tree, + self.session, + &self.dims, + false, + ); self.dims.property_select_base = None; let lhs = lhs.and_then(|lhs| self.hoist_index_calls(lhs, op != "=", &mut body)); // The width of the selection, which a runtime position leaves unknown @@ -5129,6 +5248,16 @@ pub(super) fn initial_processes_from_scope( item_dimensions, )?; } + expression_binding::check_chandle_assignment( + item_dimensions + .get(&name) + .is_some_and(|shape| shape.chandle && shape.unpacked.is_empty()), + native, + tree, + tree.declarations(), + item_dimensions, + session, + )?; let lhs = LValue::Ident(name); let rhs = expression_binding::expression( native, diff --git a/crates/celox-sv-analyzer/src/ast/procedural/assertions.rs b/crates/celox-sv-analyzer/src/ast/procedural/assertions.rs index d757d4d0962..a6b9039458a 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/assertions.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/assertions.rs @@ -14,7 +14,7 @@ impl BodyBuilder<'_, '_, '_> { if !matches!(keyword, "assert" | "assume" | "cover") { return Err(unsupported("immediate assertion keyword")); } - self.native_value(*condition) + self.native_chandle_value(*condition) .map(procedural_truth_condition) } } diff --git a/crates/celox-sv-analyzer/src/ast/procedural/control.rs b/crates/celox-sv-analyzer/src/ast/procedural/control.rs index 09fba671ca7..904c01f3ff8 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/control.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/control.rs @@ -15,6 +15,8 @@ struct CaseState { index: usize, kind: CaseKind, selector: Expr, + /// Whether the statement compares chandles (6.14). + chandles: bool, items: Vec>, default: Option>, } @@ -255,7 +257,11 @@ impl BodyBuilder<'_, '_, '_> { prologue = stmts; (LoopKind::For, None, false) } - None => (LoopKind::While, Some(self.native_value(*value)?), false), + None => ( + LoopKind::While, + Some(self.native_chandle_value(*value)?), + false, + ), }, LoopSyntax::Repeat(value) => { // The count is evaluated once (12.7.2). @@ -312,11 +318,43 @@ impl BodyBuilder<'_, '_, '_> { keyword, mode, expression: Some(value), + arms, .. } if keyword != "randcase" => { if mode.as_deref() == Some("matches") { return Err(unsupported("pattern-matching case statement")); } + // A case statement compares with `===` (IEEE 1800-2023 12.5). + let operator = match (mode.as_deref(), keyword.as_str()) { + (Some("inside"), _) => "inside", + (_, "case") => "===", + (_, keyword) => keyword, + }; + // Only `case` compares chandles, with chandle or + // `null` items (6.14); the binder rejects them + // elsewhere. A selector is a chandle also when only + // a default arm compares nothing with it. + let mut chandles = operator == "===" + && expression_binding::native_chandle( + self.tree, + *value, + native, + &self.dims, + self.session, + ); + for case_match in arms.iter().flat_map(|arm| &arm.matches) { + if let celox_sv_syntax::CaseMatch::Expression(label) = case_match { + chandles |= expression_binding::check_chandle_equality( + operator, + *value, + *label, + self.tree, + native, + &self.dims, + self.session, + )?; + } + } let kind = if mode.as_deref() == Some("inside") { CaseKind::Inside } else { @@ -328,12 +366,17 @@ impl BodyBuilder<'_, '_, '_> { } }; output.extend(self.effects(&[*value])?); - let selector = self.native_value(*value)?; + let selector = if chandles { + self.native_chandle_value(*value)? + } else { + self.native_value(*value)? + }; jobs.push(Job::CaseNext(CaseState { id, index: 0, kind, selector, + chandles, items: Vec::new(), default: None, })); @@ -506,7 +549,22 @@ impl BodyBuilder<'_, '_, '_> { } let value = value .map(|id| { - let mut value = expression_binding::bind_value( + if let Some(chandle) = self.return_chandle { + expression_binding::check_chandle_assignment( + chandle, + id, + self.tree, + native, + &self.dims, + self.session, + )?; + } + let bind = if self.return_chandle == Some(true) { + expression_binding::bind_chandle_value + } else { + expression_binding::bind_value + }; + let mut value = bind( id, native, self.tree, @@ -684,15 +742,15 @@ impl BodyBuilder<'_, '_, '_> { }); } else { let arm = &arms[state.index]; - let labels = - if arm.default { - None - } else { - Some(self.native_case_labels( - &arm.matches, - state.kind == CaseKind::Inside, - )?) - }; + let labels = if arm.default { + None + } else { + Some(self.native_case_labels( + &arm.matches, + state.kind == CaseKind::Inside, + state.chandles, + )?) + }; jobs.push(Job::CaseBranch { state, labels, @@ -769,7 +827,7 @@ impl BodyBuilder<'_, '_, '_> { }); continue; } - let condition = self.native_value(native)?; + let condition = self.native_chandle_value(native)?; output.push(Stmt::Loop { kind: LoopKind::DoWhile, init: Vec::new(), @@ -791,6 +849,7 @@ impl BodyBuilder<'_, '_, '_> { &mut self, labels: &[celox_sv_syntax::CaseMatch], inside: bool, + chandles: bool, ) -> Result>, AnalyzerError> { if labels.is_empty() { return Err(AnalyzerError::Parse("native case arm has no labels".into())); @@ -798,6 +857,9 @@ impl BodyBuilder<'_, '_, '_> { labels .iter() .map(|label| match label { + celox_sv_syntax::CaseMatch::Expression(id) if chandles => { + self.native_chandle_value(*id).map(CaseLabel::Value) + } celox_sv_syntax::CaseMatch::Expression(id) => { self.native_value(*id).map(CaseLabel::Value) } diff --git a/crates/celox-sv-analyzer/src/ast/procedural/effects.rs b/crates/celox-sv-analyzer/src/ast/procedural/effects.rs index edb536a7726..a5c0c8c6d61 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/effects.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/effects.rs @@ -284,12 +284,13 @@ impl BodyBuilder<'_, '_, '_> { /// Evaluate the truth of `id` into a hidden 1-bit local, which `id` /// binds to from now on, and return its unique name. fn truth(&mut self, id: ExprId, stmts: &mut Vec) -> Converted { - let value = expression_binding::value( + let value = expression_binding::bind_chandle_value( id, self.tree.declarations(), self.tree, self.session, &self.dims, + None, )?; let (source, unique) = self.hidden(Type::new(TypeKind::Logic)); let truth = |value: Expr| Expr::Unary { @@ -438,7 +439,7 @@ impl BodyBuilder<'_, '_, '_> { return Ok(None); } stmts.push(Stmt::If { - condition: self.native_value(id)?, + condition: self.native_chandle_value(id)?, then_body: Vec::new(), else_body: vec![Stmt::Break], }); diff --git a/crates/celox-sv-analyzer/src/ast/procedural/foreach.rs b/crates/celox-sv-analyzer/src/ast/procedural/foreach.rs index 1890e52cd27..418327df427 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/foreach.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/foreach.rs @@ -57,8 +57,11 @@ impl BodyBuilder<'_, '_, '_> { .key .as_ref() .filter(|key| key.kind() == TypeKind::Process); - index_type = if object { - container.key.clone().expect("a class index type") + index_type = if object || container.key.as_ref().is_some_and(|key| key.chandle) { + container + .key + .clone() + .expect("a class or chandle index type") } else if let Some(process) = process { process.clone() } else if string { diff --git a/crates/celox-sv-analyzer/src/ast/procedural/timing.rs b/crates/celox-sv-analyzer/src/ast/procedural/timing.rs index ce861f4b166..cc23485daa2 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/timing.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/timing.rs @@ -83,7 +83,10 @@ impl BodyBuilder<'_, '_, '_> { result.push(EventItemBase { edge, expr: self.native_value(item.expression)?, - iff: item.iff.map(|iff| self.native_value(iff)).transpose()?, + iff: item + .iff + .map(|iff| self.native_chandle_value(iff)) + .transpose()?, }); } Ok(Stmt::WaitEvent(result)) @@ -157,7 +160,18 @@ impl BodyBuilder<'_, '_, '_> { TimingEdge::Neg => EventEdge::Neg, TimingEdge::Both => EventEdge::Both, }; - let iff = item.iff.map(|iff| self.native_value(iff)).transpose()?; + // The member is read below without the binder. + expression_binding::check_chandle_read( + item.expression, + self.tree, + native, + &self.dims, + self.session, + )?; + let iff = item + .iff + .map(|iff| self.native_chandle_value(iff)) + .transpose()?; let expr = match virtual_interfaces::native_member( self.tree, self.session, @@ -265,8 +279,11 @@ impl BodyBuilder<'_, '_, '_> { if let ExprKind::MinTypMax { typical, .. } = native.expression(value).kind { value = typical; } + } + if parenthesized { return self.native_value(value); } + expression_binding::check_chandle_read(value, self.tree, native, &self.dims, self.session)?; match &native.expression(value).kind { ExprKind::Literal(text) if text.chars().all(|c| c.is_ascii_digit() || c == '_') => { Ok(Expr::Literal(text.replace('_', ""))) diff --git a/crates/celox-sv-analyzer/src/ast/type_binding.rs b/crates/celox-sv-analyzer/src/ast/type_binding.rs index 6e24559762b..841ba578a4e 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding.rs @@ -204,6 +204,10 @@ pub(super) fn argument_type( return Ok(None); }; let ranges = binding::packed_ranges(&dimensions, tree, session, &context)?; + // A chandle is no packed array element (IEEE 1800-2023 6.14). + if base.chandle && !ranges.is_empty() { + return types::packed_chandles(); + } Ok(Some(types::enclose_aliased_packed_type( base.clone(), ranges, @@ -305,11 +309,13 @@ pub(super) fn builtin_type(name: &str, signing: Option) -> Option { "longint" => (TypeKind::Bit, Some(64), true), "integer" => (TypeKind::Logic, Some(32), true), "time" => (TypeKind::Logic, Some(64), false), + "chandle" => (TypeKind::Bit, Some(64), false), // A named event is a handle (IEEE 1800-2023 15.5). "event" => return Some(super::classes::handle(super::events::CLASS)), _ => return None, }; let mut ty = Type::new(kind); + ty.chandle = name == "chandle"; ty.is_signed = signing.unwrap_or(signed); let keyword = match name { "byte" => Some("byte"), 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 0e01475141e..f1479a46118 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs @@ -467,6 +467,20 @@ fn bind_in_mode( } } } + // A chandle has its own packed range only; it is no packed array + // element or enumeration base (IEEE 1800-2023 6.14, 6.19), such as + // through a typedef. This checks in place, which keeps the recursive + // frame small. + if let Some(ty) = values.last() + && ty.chandle + { + if ty.is_enum { + return types::chandle_enum(); + } + if ty.packed_ranges.len() > 1 { + return types::packed_chandles(); + } + } Ok(values.pop()) } diff --git a/crates/celox-sv-analyzer/src/ast/type_names.rs b/crates/celox-sv-analyzer/src/ast/type_names.rs index 26cc9350612..74ba2161969 100644 --- a/crates/celox-sv-analyzer/src/ast/type_names.rs +++ b/crates/celox-sv-analyzer/src/ast/type_names.rs @@ -427,6 +427,9 @@ fn element_name( if let Some(class) = r#type.class().filter(|_| r#type.kind != TypeKind::Event) { return class_name(class, tree, session, env); } + if r#type.chandle { + return Ok("chandle".to_owned()); + } match r#type.kind { TypeKind::Event => return Ok("event".to_owned()), TypeKind::Real => return Ok("real".to_owned()), diff --git a/crates/celox-sv-analyzer/src/ast/types.rs b/crates/celox-sv-analyzer/src/ast/types.rs index 7ad06e0b9d8..34b1f150a25 100644 --- a/crates/celox-sv-analyzer/src/ast/types.rs +++ b/crates/celox-sv-analyzer/src/ast/types.rs @@ -292,11 +292,44 @@ pub(super) fn enclose_aliased_packed_type( r#type } -pub(super) fn type_with_unpacked_ranges(mut r#type: Type, ranges: Vec) -> Type { +/// The error of packed dimensions on a chandle, returned directly by the +/// recursive type binder, which keeps its frames small. +#[inline(never)] +#[cold] +pub(super) fn packed_chandles() -> Result { + Err(AnalyzerError::IllegalChandleUse { + detail: "a packed array of chandles".into(), + }) +} + +/// The error of an enumeration whose base type is a chandle, which is not +/// integral (IEEE 1800-2023 6.19). Out of line like [`packed_chandles`]. +#[inline(never)] +#[cold] +pub(super) fn chandle_enum() -> Result { + Err(AnalyzerError::IllegalChandleUse { + detail: "an enumeration of chandle base type".into(), + }) +} + +/// `r#type` with the fixed-size unpacked dimensions `ranges` (IEEE 1800-2023 +/// 7.4) in front of its own. Every declaration of a fixed-size unpacked +/// array, also of a typedef, a parameter or a container element, takes its +/// type here. +pub(super) fn type_with_unpacked_ranges( + mut r#type: Type, + ranges: Vec, +) -> Result { + // UVM keeps chandles in scalars and dynamic containers only. + if r#type.chandle && !ranges.is_empty() { + return Err(AnalyzerError::Unsupported( + "fixed-size unpacked array of chandle".into(), + )); + } let mut unpacked_ranges = ranges; unpacked_ranges.extend(r#type.unpacked_ranges); r#type.unpacked_ranges = unpacked_ranges; - r#type + Ok(r#type) } pub(super) fn validate_unpacked_dimension_sizes( diff --git a/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs b/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs index 37fc29caaf5..3940f704d22 100644 --- a/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs +++ b/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs @@ -127,8 +127,10 @@ pub(in crate::ast) fn native_type( let members = fields .into_iter() .map(|(name, ty)| { + // A chandle is no packed array element (IEEE 1800-2023 6.14). if !ty.unpacked_ranges.is_empty() || ty.container.is_some() + || (ty.chandle && ty.packed_ranges.len() > 1) // Each event member would need its own synchronization // object (IEEE 1800-2023 15.5). || matches!( diff --git a/crates/celox-sv-analyzer/src/ast/virtual_interfaces.rs b/crates/celox-sv-analyzer/src/ast/virtual_interfaces.rs index 5e59c7651fc..dddb4188c73 100644 --- a/crates/celox-sv-analyzer/src/ast/virtual_interfaces.rs +++ b/crates/celox-sv-analyzer/src/ast/virtual_interfaces.rs @@ -183,13 +183,16 @@ fn resolved_type(r#type: &crate::ir::Type, constants: &HashMap) -> if !r#type.unpacked_ranges().is_empty() { return None; } - Some(Type::resolved( - kind, - r#type.is_signed(), - r#type.signed_element_depth(), - &packed, - &[], - )) + Some( + Type::resolved( + kind, + r#type.is_signed(), + r#type.signed_element_depth(), + &packed, + &[], + ) + .with_chandle(r#type.is_chandle()), + ) } /// A signal of a module that the frontend binds for virtual interfaces. diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 05797163314..0894a6185a4 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -773,6 +773,8 @@ pub struct Type { resolved_width: Option, signed_element_depth: Option, class: Option, + /// A `chandle`, held as 64 bits (IEEE 1800-2023 6.14). + chandle: bool, } /// Shared metadata, allocated only for unpacked structure types. Ordinary @@ -798,6 +800,12 @@ impl Type { .map_or(&[], |structure| structure.leaves.as_slice()) } + /// Whether the type is a `chandle`, which other analyses of names of + /// this signal must keep (see [`crate::ast::Type::with_chandle`]). + pub fn is_chandle(&self) -> bool { + self.chandle + } + /// How many leading packed dimensions select an element of a signed /// named type (IEEE 1800-2023 7.4.1). pub fn signed_element_depth(&self) -> Option { @@ -908,6 +916,7 @@ impl Type { let is_signed = r#type.is_signed(); let class = r#type.class().map(str::to_owned); let signed_element_depth = r#type.signed_element_depth(); + let chandle = r#type.is_chandle(); let (packed_ranges, unpacked_ranges, resolved_width) = convert_type(r#type, constants); Self { structure, @@ -919,6 +928,7 @@ impl Type { resolved_width, signed_element_depth, class, + chandle, } } } @@ -1992,6 +2002,8 @@ pub enum DpiType { /// `byte`, `shortint`, `int` or `longint`, passed as the C integer of /// that width. Integer { width: usize, signed: bool }, + /// `chandle`, passed as a C pointer (IEEE 1800-2023 6.14). + Chandle, } impl DpiType { @@ -1999,6 +2011,7 @@ impl DpiType { match self { DpiType::Bit | DpiType::Logic => 1, DpiType::Integer { width, .. } => *width, + DpiType::Chandle => 64, } } diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index 544bbcd5c38..bec00dd4a62 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -229,6 +229,9 @@ pub enum AnalyzerError { UnknownClassParameter { class: String, name: String }, /// A `ref` or `const ref` formal bound to an actual, or used in a way, /// that IEEE 1800-2023 13.5.2 forbids. + /// A use of a `chandle` that IEEE 1800-2023 6.14 does not allow. + #[error("chandle: {detail} (IEEE 1800-2023 6.14)")] + IllegalChandleUse { detail: String }, #[error("ref argument `{argument}` of `{subroutine}`: {detail}")] InvalidRefArgument { subroutine: String, diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 7aa1d2ed81d..f665e32c137 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -1598,3 +1598,13 @@ its exact mismatch remains an executed failure in not support unpacked array formals; its exact compile diagnostic remains an executed failure in [the Icarus types report](verification/sv/icarus/types.json). No assertions or exclusions are weakened. + +### Chandles + +`types::chandles_hold_null_and_copies` checks the uses IEEE 1800-2023 6.14 allows +for a `chandle`: it starts as `null`, compares with another chandle or `null`, +tests as a Boolean, and is copied through a class property, an associative array +and subroutine arguments and results. Verilator 5.052 and the installed xezim +0.11.3 build pass it. Icarus 13.0 rejects the `chandle` class property with +"Invalid class item"; that compile failure remains executed evidence in +[the Icarus report](verification/sv/icarus/types.json). diff --git a/crates/celox-test-suite/src/sv/cases/types.vtest b/crates/celox-test-suite/src/sv/cases/types.vtest index 4369d4df1c3..9bcd012d171 100644 --- a/crates/celox-test-suite/src/sv/cases/types.vtest +++ b/crates/celox-test-suite/src/sv/cases/types.vtest @@ -562,3 +562,35 @@ module Top(output int sum); endmodule "#) (top Top) (run_until 0) (assert_eq sum 18324313)) + +; IEEE 1800-2023 6.14: a chandle starts as null, compares with another +; chandle or null, tests as a Boolean, and can be copied, kept in a class, +; an associative array, and passed to and returned from subroutines. +(case chandles_hold_null_and_copies + (source "chandles_hold_null_and_copies.sv" #" + module Top(output int checks); + class Holder; + local chandle h; + function void set(chandle x); h = x; endfunction + function bit is_null(); return h == null; endfunction + endclass + chandle a, b; + chandle lookup[string]; + function automatic chandle pass(chandle h); return h; endfunction + initial begin + automatic Holder holder = new; + automatic chandle c = null; + checks = 0; + if (a == null && a === b && !a) checks++; + b = pass(a); + lookup["k"] = b; + c = lookup["k"]; + if (c == a && !(c != null) && !(a || b)) checks++; + holder.set(c); + if (holder.is_null() && lookup.num() == 1) checks++; + end + endmodule + "#) + (top Top) + (run_until 1) + (assert_eq checks 3)) diff --git a/crates/celox-test-suite/tests/retained_reports.rs b/crates/celox-test-suite/tests/retained_reports.rs index 5f548861d5a..a319d78f917 100644 --- a/crates/celox-test-suite/tests/retained_reports.rs +++ b/crates/celox-test-suite/tests/retained_reports.rs @@ -676,6 +676,9 @@ fn systemverilog_retained_reports_explain_exclusions_and_executed_failures() { ("icarus", "class::foreign_generic_unit_type_constructor") => { ("compile_error", "compile", "source_0.sv:3: syntax error") } + ("icarus", "types::chandles_hold_null_and_copies") => { + ("compile_error", "compile", "Invalid class item") + } _ => panic!("unreviewed failure: {tool} {name}: {status}"), }; assert_eq!(status, expected_status, "{name}"); diff --git a/crates/celox-test-suite/verification/sv/icarus/types.json b/crates/celox-test-suite/verification/sv/icarus/types.json index 53f1854bce6..f6715fb9367 100644 --- a/crates/celox-test-suite/verification/sv/icarus/types.json +++ b/crates/celox-test-suite/verification/sv/icarus/types.json @@ -1,5 +1,16 @@ { "cases": [ + { + "category": "Types", + "detail": "Icarus build exit status: 79; see /build.log\n/source_0.sv:4: syntax error\n/source_0.sv:4: error: Invalid class item.\n/source_0.sv:5: syntax error\n/source_0.sv:8: error: Syntax error in task/function port declaration.\n/source_0.sv:8: error: ';' is an invalid port declaration separator.\n/source_0.sv:9: syntax error\n/source_0.sv:5: error: Syntax error defining function.\n/source_0.sv:11: syntax error\n/source_0.sv:12: error: Invalid class item.\n/source_0.sv:13: syntax error\n/source_0.sv:13: error: Invalid class item.\n/source_0.sv:14: syntax error\n/source_0.sv:14: error: checks doesn't name a type.\n/source_0.sv:15: syntax error\n/source_0.sv:15: error: Invalid class item.\n/source_0.sv:16: syntax error\n/source_0.sv:16: error: b doesn't name a type.\n/source_0.sv:17: syntax error\n/source_0.sv:17: error: lookup doesn't name a type.\n/source_0.sv:18: syntax error\n/source_0.sv:18: error: c doesn't name a type.\n/source_0.sv:19: syntax error\n/source_0.sv:19: error: Invalid class item.\n/source_0.sv:20: syntax error\n/source_0.sv:20: error: holder doesn't name a type.\n/source_0.sv:21: syntax error\n/source_0.sv:21: error: Invalid class item.\n/source_0.sv:22: syntax error\n/testbench.sv:11: error: Invalid class item.\n/testbench.sv:12: syntax error\n/testbench.sv:12: error: Invalid class item.\n/testbench.sv:13: syntax error\n/testbench.sv:13: error: Invalid class item.\n/testbench.sv:14: syntax error\n/testbench.sv:14: error: Top doesn't name a type.\n/testbench.sv:85: syntax error\n/testbench.sv:88: error: Invalid class item.\n/testbench.sv:89: syntax error\n/testbench.sv:89: error: Invalid class item.\n/testbench.sv:90: syntax error\n/testbench.sv:91: error: Invalid class item.\n/testbench.sv:92: syntax error\n/testbench.sv:93: error: Invalid class item.\n/testbench.sv:94: syntax error\n/testbench.sv:94: error: Invalid class item.\n/testbench.sv:95: syntax error\n/testbench.sv:97: error: Invalid class item.\n/testbench.sv:98: syntax error\n/testbench.sv:98: error: t1 doesn't name a type.\n/testbench.sv:99: syntax error\n/testbench.sv:100: error: Invalid class item.\n/testbench.sv:101: syntax error\n/testbench.sv:101: error: Invalid class item.\n/testbench.sv:102: syntax error\n/testbench.sv:103: error: Invalid class item.\n/testbench.sv:104: syntax error\n/testbench.sv:104: error: settle_now doesn't name a type.\n/testbench.sv:105: syntax error\n/testbench.sv:106: error: Invalid class item.\n/testbench.sv:107: syntax error\n/testbench.sv:107: error: expected doesn't name a type.\n/testbench.sv:108: syntax error\n/testbench.sv:108: error: actual doesn't name a type.\n/testbench.sv:109: syntax error\n/testbench.sv:110: error: Invalid class item.\n/testbench.sv:111: syntax error\n/testbench.sv:111: error: Invalid class item.\n/testbench.sv:112: syntax error\n/testbench.sv:114: error: Invalid class item.\n/testbench.sv:115: syntax error\n/testbench.sv:115: error: Invalid class item.\n/testbench.sv:116: syntax error\n/testbench.sv:118: error: Invalid class item.\n/testbench.sv:120: syntax error\n/testbench.sv:120: error: Invalid class item.\n/testbench.sv:122: syntax error\n/testbench.sv:122: error: Invalid class item.\n/testbench.sv:123: syntax error\nI give up.\n", + "expectation": "Simulation", + "name": "types::chandles_hold_null_and_copies", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", diff --git a/crates/celox-test-suite/verification/sv/verilator/types.json b/crates/celox-test-suite/verification/sv/verilator/types.json index 736d1d6f9f9..5c8813af427 100644 --- a/crates/celox-test-suite/verification/sv/verilator/types.json +++ b/crates/celox-test-suite/verification/sv/verilator/types.json @@ -1,5 +1,16 @@ { "cases": [ + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "types::chandles_hold_null_and_copies", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", diff --git a/crates/celox-test-suite/verification/sv/xezim/types.json b/crates/celox-test-suite/verification/sv/xezim/types.json index ed6711b57dc..1e0d046d761 100644 --- a/crates/celox-test-suite/verification/sv/xezim/types.json +++ b/crates/celox-test-suite/verification/sv/xezim/types.json @@ -1,5 +1,16 @@ { "cases": [ + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "types::chandles_hold_null_and_copies", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index 6407dc7dbb0..26b5fd044cc 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -244,12 +244,102 @@ fn rejects_non_integral_ports_instead_of_scalarizing_them() { endmodule "#, ); + // A chandle port is illegal (IEEE 1800-2023 6.14). assert!( - error.contains("unsupported port data type"), + error.contains("port `value` of chandle type"), "unexpected error: {error}" ); } +#[test] +fn chandles_of_child_instances_keep_their_type() { + // A hierarchical name denotes the child's chandle (IEEE 1800-2023 6.14, 23.6). + let accepted = celox::Simulation::from_sv_sources( + vec![( + r#" + module Child; chandle h; endmodule + module Top(output logic y); + Child u(); + chandle a; + initial begin a = u.h; if (u.h == a) u.h = a; end + assign y = 1'b0; + endmodule + "#, + std::path::Path::new("child_chandle.sv"), + )], + "Top", + ) + .build(); + assert!(accepted.is_ok(), "{:?}", accepted.err()); + for body in [ + "initial u.h = 64'd1;", + "bit [63:0] w; initial w = u.h;", + "initial u.h += null;", + ] { + let error = cranelift_build_error(&format!( + r#" + module Child; chandle h; endmodule + module Top(output logic y); + Child u(); + {body} + assign y = 1'b0; + endmodule + "# + )); + assert!( + error.contains("chandle"), + "{body}: unexpected error: {error}" + ); + } +} + +#[test] +fn chandles_through_virtual_interfaces_keep_their_type() { + // A member selected through a virtual interface has its declared type + // (IEEE 1800-2023 6.14, 25.9). + let accepted = celox::Simulation::from_sv_sources( + vec![( + r#" + interface Bus; chandle h; endinterface + module Top(output logic y); + Bus bus(); + virtual Bus v = bus; + chandle a; + initial begin a = v.h; if (v.h == a) v.h = a; end + assign y = 1'b0; + endmodule + "#, + std::path::Path::new("vif_chandle.sv"), + )], + "Top", + ) + .build(); + assert!(accepted.is_ok(), "{:?}", accepted.err()); + for body in [ + "initial v.h = 64'd1;", + "bit [63:0] b; initial b = v.h;", + "bit d; initial @(v.h) d = 1;", + "bit d; initial @(posedge v.h or v.h) d = 1;", + "initial v.h += null;", + ] { + let error = cranelift_build_error(&format!( + r#" + interface Bus; chandle h; endinterface + module Top(output logic y); + Bus bus(); + virtual Bus v = bus; + {body} + assign y = 1'b0; + endmodule + "# + )); + assert!( + error.contains("chandle"), + "{body}: unexpected error: {error}" + ); + } +} + #[test] fn rejects_internal_signals_that_shadow_ports() { let error = cranelift_build_error( @@ -6475,7 +6565,7 @@ fn rejects_unsupported_internal_data_types() { let error = cranelift_build_error( r#" module Top(output logic y); - chandle value; + type(y) value; assign y = 1'b0; endmodule "#, diff --git a/crates/celox/tests/frontends/systemverilog/types.rs b/crates/celox/tests/frontends/systemverilog/types.rs index 2a5753e1fde..42bc08f01e9 100644 --- a/crates/celox/tests/frontends/systemverilog/types.rs +++ b/crates/celox/tests/frontends/systemverilog/types.rs @@ -74,6 +74,9 @@ sv_backends! { fn undriven_internal_nets_convert_to_two_state_zero(sim) { @case "types::undriven_internal_nets_convert_to_two_state_zero"; } + fn chandles_hold_null_and_copies(sim) { + @case "types::chandles_hold_null_and_copies"; + } } sv_backends! { diff --git a/crates/celox/tests/sv_dpi.rs b/crates/celox/tests/sv_dpi.rs index 19944c97d49..2fc5eda6e3f 100644 --- a/crates/celox/tests/sv_dpi.rs +++ b/crates/celox/tests/sv_dpi.rs @@ -819,3 +819,59 @@ dpi_backends! { assert_eq!(QUERY_DPI_CALLS.load(std::sync::atomic::Ordering::SeqCst), 0); } } + +static CHANDLE_TARGET: [i32; 2] = [17, 29]; + +/// A `chandle` is a C pointer (IEEE 1800-2023 6.14): one function returns +/// one, another dereferences it. +extern "C" fn dpi_element_handle(index: i32) -> *const i32 { + if index < 0 { + std::ptr::null() + } else { + &CHANDLE_TARGET[index as usize] + } +} + +extern "C" fn dpi_read_handle(handle: *const i32) -> i32 { + if handle.is_null() { + -1 + } else { + // SAFETY: the handle comes from `dpi_element_handle`. + unsafe { *handle } + } +} + +dpi_backends! { + fn chandles_pass_c_pointers_through(sim) { + @build unsafe { + builder(r#" + module Top(input logic clk, input int index, output int value, output bit is_null); + import "DPI-C" function chandle element(input int index); + import "DPI-C" function int read(input chandle handle); + chandle handle; + always_ff @(posedge clk) begin + handle <= element(index); + value <= read(handle); + is_null <= handle == null; + end + endmodule + "#) + .dpi_function("element", dpi_element_handle as *const ()) + .dpi_function("read", dpi_read_handle as *const ()) + }; + let clk = sim.event("clk"); + let (index, value, is_null) = (sim.signal("index"), sim.signal("value"), sim.signal("is_null")); + sim.modify(|io| io.set(index, 1u32)).unwrap(); + sim.tick(clk).unwrap(); + assert_eq!(sim.get(value), BigUint::from(0xffff_ffffu32)); + assert_eq!(sim.get(is_null), BigUint::from(1u32)); + sim.tick(clk).unwrap(); + assert_eq!(sim.get(value), BigUint::from(29u32)); + assert_eq!(sim.get(is_null), BigUint::from(0u32)); + sim.modify(|io| io.set(index, 0xffff_ffffu32)).unwrap(); + sim.tick(clk).unwrap(); + sim.tick(clk).unwrap(); + assert_eq!(sim.get(value), BigUint::from(0xffff_ffffu32)); + assert_eq!(sim.get(is_null), BigUint::from(1u32)); + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index e786d78594e..8a52bb67ced 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -32,6 +32,7 @@ synthesis and is tested at the design level. | Selects | constant and run-time bit selects and indexed part-selects (`[i]`, `[i +: W]`, `[i -: W]`), in reads and writes, in either declaration direction | | Patterns | assignment patterns for packed and unpacked structs, packed arrays and unpacked arrays (`'{a, b}`, `'{x: a, default: 0}`, `'{n{a}}`, `T'{...}`) | | Dynamic containers | dynamic arrays, queues (including bounded queues), and associative arrays with integral, string or class handle keys, also nested (`int m[string][$]`, `T m[C][C][E]`); element access, value assignment, equality, `foreach` and built-in container methods. See [dynamic containers](#dynamic-containers) | +| Chandles | `chandle` variables, class properties, elements of dynamic arrays, queues and associative arrays, subroutine arguments and results, and DPI-C arguments and results (passed as C pointers): they start as `null`, compare with `==`, `!=`, `===` and `!==` against another chandle or `null`, test as Booleans, and are assigned from another chandle or `null`. Other operators, assignments from or to other types, casts, ports, event expressions, continuous assignments and packed types of chandles are rejected (IEEE 1800-2023 6.14). Fixed-size unpacked arrays of chandles (`chandle a[4]`, also through a typedef) are not supported | | Strings | `string` variables, function arguments and results: assignment of strings, string literals and casts (`string'(x)`), `==`, `!=` and ordering comparisons, concatenation and replication (with a run-time count), character reads and writes (`s[i]`), and the methods `len`, `getc`, `putc`, `toupper`, `tolower`, `compare`, `icompare`, `substr`, `atoi` / `atohex` / `atooct` / `atobin` and `itoa` / `hextoa` / `octtoa` / `bintoa`; `%s` and format-less display of string values; text formatted by `$sformatf` / `$sformat` / `$swrite`. See [strings](#strings) | | Classes | classes declared in a module, a package or the compilation unit: properties of 2-state and 4-state integral types of any width (4-state properties start as X and keep X/Z bits), `string` and class handle types, unpacked structures of those types (see [unpacked structures](#unpacked-structures)), plus dynamic arrays, queues and associative arrays, with initializers; `new` with and without arguments, implicit and explicit constructors; methods (`function` and `task`, also `extern` with an out-of-block body) called through a handle or unqualified inside the class; `this`, `null`, handle assignment and comparison; inheritance of properties and methods, with base constructors called by `super.new(...)` or `extends Base(...)`; `super.` members; virtual methods, abstract (`virtual`) classes and pure virtual methods; classes that implement interface classes and method calls through interface class handles; `$cast` of class handles, as a function and as a task; static properties and methods; `C::` scope resolution of static members and `C::new`; arrays of handles; parameterized classes with value and type parameters, parameters read through a handle or `C#(...)::`, typedefs of classes and interface classes and `C::T`; named and defaulted method and constructor arguments; shallow copies (`new h`); bit and part selects of properties, read and written like selects of a variable (11.5.1). See [classes](#classes) | | Parameters | integral parameters and overrides preserving widths beyond 128 bits and X/Z values, and parameters of unpacked array or packed struct type given by an assignment pattern (constant tables), including unpacked-array pattern overrides | @@ -1648,11 +1649,12 @@ first release supports this subset: argument types, with up to 16 `input` arguments. Imports linked to one C name must declare the same prototype. - Argument and result types `bit`, `logic` (passed as `svBit` / `svLogic`), - `byte`, `shortint`, `int` and `longint`, signed or `unsigned`. + `byte`, `shortint`, `int` and `longint`, signed or `unsigned`, and + `chandle` (passed as a C pointer). Imports at compilation-unit scope, `output` and `inout` arguments, `context` imports, task imports, packed vector arguments (`svBitVecVal` / -`svLogicVecVal`), `integer`, `real`, `chandle` and `string` are rejected. +`svLogicVecVal`), `integer`, `real` and `string` are rejected. `export "DPI-C"` declarations of functions and tasks defined in the same module or package are accepted and checked: the subroutine is exported once, diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index af3fda6d41c..8425d3b6bae 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -30,6 +30,7 @@ outline: [2, 3] | 選択 | 定数・実行時のビット選択と indexed part-select(`[i]`、`[i +: W]`、`[i -: W]`)。読み書きの両方、宣言の向きによらず | | パターン | packed・unpacked 構造体、packed 配列、unpacked 配列の assignment pattern(`'{a, b}`、`'{x: a, default: 0}`、`'{n{a}}`、`T'{...}`) | | クラス | モジュール・package・コンパイル単位で宣言したクラス。任意の幅の 2 値・4 値整数型(4 値のプロパティは X で始まり、X/Z ビットを保持します)・`string`・クラスハンドル型と、それらをメンバとする unpacked 構造体([unpacked 構造体](#unpacked-structures)を参照)のプロパティ(初期値つきも可)、引数あり・なしの `new`、暗黙と明示のコンストラクタ、ハンドル経由またはクラス内から修飾なしで呼ぶメソッド(`function` と `task`、本体をクラス外に書く `extern` も可)、`this`、`null`、ハンドルの代入と比較、プロパティとメソッドの継承(基底クラスのコンストラクタは `super.new(...)` か `extends Base(...)` で呼ぶ)、`super.` によるメンバ参照、virtual メソッド、抽象クラス(`virtual class`)と pure virtual メソッド、interface クラスを実装するクラスと interface クラスのハンドルを通したメソッド呼び出し、関数とタスクとしてのクラスハンドルの `$cast`、static プロパティとメソッド、static メンバと `C::new` の `C::` によるスコープ解決、ハンドルの配列、値パラメータと型パラメータを持つパラメータ付きクラス、ハンドルや `C#(...)::` を通したパラメータの参照、クラスと interface クラスの typedef と `C::T`、名前付きのコンストラクタ引数、浅いコピー(`new h`)、変数の選択と同じように読み書きするプロパティのビット選択・部分選択(11.5.1)。[クラス](#classes)を参照 | +| chandle | `chandle` 型の変数、クラスプロパティ、動的配列・キュー・連想配列の要素、サブルーチンの引数と戻り値、DPI-C の引数と戻り値(C のポインタとして渡す)。初期値は `null`。別の chandle または `null` との `==`・`!=`・`===`・`!==`、真偽値としての判定、別の chandle または `null` からの代入に対応。それ以外の演算子、他の型との代入、キャスト、ポート、イベント式、連続代入、packed 型での使用は拒否します(IEEE 1800-2023 6.14)。固定長の unpacked 配列(`chandle a[4]`、typedef 経由も含む)は未対応です | | 文字列 | `string` 型の変数、関数の引数と戻り値。文字列・文字列リテラル・キャスト(`string'(x)`)の代入、`==` / `!=` と大小比較、連結と複製(実行時の回数も可)、文字の読み書き(`s[i]`)、メソッド `len`、`getc`、`putc`、`toupper`、`tolower`、`compare`、`icompare`、`substr`、`atoi` / `atohex` / `atooct` / `atobin`、`itoa` / `hextoa` / `octtoa` / `bintoa`。`%s` と書式なしの表示。[文字列](#strings)を参照 | | パラメータ | 整数のパラメータ、128ビットを超える幅と X/Z を保持するパラメータ上書き、assignment pattern で与える unpacked 配列型・packed 構造体型のパラメータ(定数テーブル)と unpacked 配列のパターンによる上書き | @@ -932,7 +933,7 @@ interface の既定値で呼び出す定数関数は、native analyzer が本体 `dpi_function` または `dpi_library` で関数を登録します。どちらも C 側の型との一致を呼び出し側が保証する `unsafe` API です。 対応するのは、モジュール・package で宣言した関数を `always_ff` とそこから呼ぶ関数で使う場合です。 -最大16個の `input` 引数を扱い、型は `bit`、`logic`、`byte`、`shortint`、`int`、`longint`(符号付き・符号なし)、戻り値はそれらか `void` です。 +最大16個の `input` 引数を扱い、型は `bit`、`logic`、`byte`、`shortint`、`int`、`longint`(符号付き・符号なし)と `chandle`(C のポインタとして渡す)、戻り値はそれらか `void` です。 組み合わせ回路からの呼び出し、`context`、task import、`output` / `inout`、packed vector、`real`、`string` などは未対応です。 同じモジュール・package で定義した関数・task の `export "DPI-C"` 宣言は受理して検査します(1 つのサブルーチンにつき 1 回、C 名の重複なし、`ref` 仮引数とクラスハンドルなし、35.7)。export はサブルーチンを変えず(35.7)、export したサブルーチンを呼べるのは `context` import だけなので(35.5.3)、C から呼ばれることはありません。 diff --git a/scripts/check-external-suite-report.test.mjs b/scripts/check-external-suite-report.test.mjs index 4177cd427e5..ecc52368585 100644 --- a/scripts/check-external-suite-report.test.mjs +++ b/scripts/check-external-suite-report.test.mjs @@ -394,6 +394,7 @@ test("every retained baseline accepts only its existing failures", () => { "tagged_unions::writable_system_arguments", "tagged_unions::writable_task_arguments", "timing::final_procedure_output_survives_program_completion", + "types::chandles_hold_null_and_copies", "types::unpacked_array_assignments_through_selects_and_calls", "unions::packed_mixed_state", "unions::soft_overlay",