diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index 72e88c35b85..d6fba506ffd 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -273,51 +273,14 @@ impl Class { &self, arguments: &[celox_sv_syntax::Argument], ) -> Converted<(Vec>, Vec)> { - let names = self + let formals = self .method("new") .map_or_else(Vec::new, |method| method.formals.clone()); - let mut actuals = vec![None; names.len()]; - let mut order = Vec::new(); - let mut named = false; - for (index, argument) in arguments.iter().enumerate() { - let index = match &argument.name { - Some(name) => { - named = true; - let name = instances::normalize_identifier(&name.spelling); - names - .iter() - .position(|formal| formal.as_ref() == Some(&name)) - .ok_or_else(|| { - unsupported(format!( - "constructor of class `{}` without an argument `{name}`", - self.name - )) - })? - } - None if named => { - return Err(unsupported("positional argument after named argument")); - } - None => index, - }; - let Some(actual) = actuals.get_mut(index) else { - return Err(unsupported(format!( - "constructor of class `{}` with {} arguments", - self.name, - arguments.len() - ))); - }; - // An omitted actual `.x()` binds its formal too. - if order.contains(&index) { - return Err(unsupported("constructor argument passed twice")); - } - order.push(index); - *actual = argument.value; - } - let unbound = (0..names.len()) - .filter(|index| !order.contains(index)) - .collect::>(); - order.extend(unbound); - Ok((actuals, order)) + expression_binding::formal_arguments( + &Self::subroutine_name(&self.name, "new"), + arguments, + &formals, + ) } /// The subroutine name of `method` of `owner`, and the variable name of diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding.rs b/crates/celox-sv-analyzer/src/ast/expression_binding.rs index 2fb1a538e7c..eaa60aaef26 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding.rs @@ -13,7 +13,7 @@ mod strings; pub(super) use calls::{statement as call_statement, statement_root as call_statement_root}; pub(super) use direct::{ arguments, bind_value, call_name as native_name, callable_name, cast_target_native, - format_arguments, member_context, real_value, remove_real_division_guards, + formal_arguments, format_arguments, member_context, real_value, remove_real_division_guards, string_literal_bytes, ungroup, }; pub(super) use lvalues::{net_lvalue, variable_lvalue}; 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 d6eab346513..5f9cc17e5c5 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -114,6 +114,42 @@ pub(in crate::ast) fn arguments( } else { args }; + let (positional, named) = split_arguments(name, args)?; + let signatures = expressions::call_signatures(name, dimensions); + let (values, order) = + expressions::bind_normalized_call_arguments(name, positional, named, &signatures)?; + expressions::check_query_omissions(name, &values, dimensions)?; + Ok((values, order)) +} + +/// The actuals `args` of a call of `name` pass to each of `formals`, by +/// position or by name, and the order they are evaluated in, see +/// [`expressions::bind_to_formals`]. +pub(in crate::ast) fn formal_arguments( + name: &str, + args: &[celox_sv_syntax::Argument], + formals: &[Option], +) -> Converted<(Vec>, Vec)> { + // `f()` lists one empty actual, which a subroutine without formals + // does not take. + let args = match args { + [arg] if formals.is_empty() && arg.name.is_none() && arg.value.is_none() => &[], + args => args, + }; + let (positional, named) = split_arguments(name, args)?; + let formals = formals + .iter() + .map(|formal| formal.as_deref().unwrap_or_default()) + .collect::>(); + expressions::bind_to_formals(name, positional, named, &formals) +} + +/// The positional actuals, which come first, and the named ones with their +/// normalized names (IEEE 1800-2023 13.5.4). +fn split_arguments( + name: &str, + args: &[celox_sv_syntax::Argument], +) -> Converted<(Vec>, Vec<(String, Option)>)> { let mut positional = Vec::new(); let mut named = Vec::new(); for arg in args { @@ -122,14 +158,13 @@ pub(in crate::ast) fn arguments( } else if named.is_empty() { positional.push(arg.value); } else { - return Err(unsupported("positional argument after named argument")); + return Err(AnalyzerError::InvalidCallArguments { + subroutine: name.to_string(), + detail: "a positional actual after a named one (IEEE 1800-2023 13.5.4)".into(), + }); } } - let signatures = expressions::call_signatures(name, dimensions); - let (values, order) = - expressions::bind_normalized_call_arguments(name, positional, named, &signatures)?; - expressions::check_query_omissions(name, &values, dimensions)?; - Ok((values, order)) + Ok((positional, named)) } pub(in crate::ast) fn cast_target_native( @@ -248,14 +283,21 @@ enum Finish { }, /// A read of property `property` of the object handle child. ObjectLoad(Box), - /// A call of method subroutine `name` with `formals` formals; the first - /// child is the object handle when `receiver` is one. - MethodCall { - name: String, - formals: usize, - receiver: objects::Receiver, - selection: Option, - }, + MethodCall(Box), +} + +/// A call of method subroutine `name` with `formals` formals; the first +/// child is the object handle when `receiver` is one, then come the given +/// actuals in the order of the formals. +struct MethodCall { + name: String, + /// Whether each formal has an actual. + given: Vec, + /// The formals in the order their actuals are evaluated. + order: Vec, + formals: usize, + receiver: objects::Receiver, + selection: Option, } enum Job { @@ -568,13 +610,19 @@ pub(in crate::ast) fn bind_value( objects::random_selection(tree, dimensions, &name, args, native) }) .transpose()?; - if selection.is_none() - && (args.len() > formals - || (name.ends_with("::srandom") && args.len() != 1) - || args.iter().any(|arg| arg.name.is_some())) + if name.ends_with("::srandom") + && (args.len() != 1 || args[0].name.is_some()) { return Err(unsupported(format!("arguments of method `{name}`"))); } + let (actuals, order) = match selection { + Some(_) => (Vec::new(), Vec::new()), + None => formal_arguments( + name.strip_suffix("$virtual").unwrap_or(&name), + args, + &formals, + )?, + }; let mut children = Vec::new(); if let objects::Receiver::Handle(handle) = receiver { children.push((handle, None)); @@ -583,14 +631,8 @@ pub(in crate::ast) fn bind_value( // that is not static, receive assignment patterns. let first = usize::from(receiver != objects::Receiver::Static); let shapes = dimensions.subroutine_param_shapes.get(&name); - for (position, arg) in - args.iter().filter(|_| selection.is_none()).enumerate() - { - let Some(value) = arg.value else { - return Err(unsupported(format!( - "omitted argument of method `{name}`" - ))); - }; + for (position, value) in actuals.iter().enumerate() { + let Some(value) = *value else { continue }; references::check_actual( &name, first + position, @@ -607,12 +649,14 @@ pub(in crate::ast) fn bind_value( children.push((value, shape)); } ( - Finish::MethodCall { + Finish::MethodCall(Box::new(MethodCall { name, - formals, + given: actuals.iter().map(Option::is_some).collect(), + order, + formals: formals.len(), receiver, selection, - }, + })), children, ) } @@ -1272,25 +1316,47 @@ pub(in crate::ast) fn bind_value( let handle = operands.pop().ok_or_else(disagreement)?; objects::load(&property, handle) } - Finish::MethodCall { - name, - formals, - receiver, - selection, - } => { + Finish::MethodCall(call) => { + let MethodCall { + name, + given, + order, + formals, + receiver, + selection, + } = *call; let mut args: Vec> = Vec::with_capacity(formals + 1); - if receiver == objects::Receiver::This { - args.push(Some(objects::this())); + let mut operands = operands.into_iter(); + if receiver != objects::Receiver::Static { + args.push(Some(match receiver { + objects::Receiver::This => objects::this(), + _ => operands.next().ok_or_else(disagreement)?, + })); + } + let handles = args.len(); + for given in given { + args.push(if given { + Some(operands.next().ok_or_else(disagreement)?) + } else { + None + }); } - let handles = usize::from(receiver != objects::Receiver::Static); - args.extend(operands.into_iter().map(Some)); args.extend(selection.map(Some)); - // Omitted trailing arguments take their defaults. + // Omitted arguments take their defaults (13.5.3). args.resize(formals + handles, None); + // The receiver is evaluated before the actuals. + let arg_order = if order.iter().enumerate().all(|(at, index)| at == *index) + { + Vec::new() + } else { + (0..handles) + .chain(order.into_iter().map(|index| index + handles)) + .collect() + }; Expr::Call { callee: Callee::Subroutine(name), args, - arg_order: Vec::new(), + arg_order, } } Finish::Cast(target) => { 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 cbde300a9a2..c9b0923e9f8 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -653,7 +653,7 @@ pub(in crate::ast) enum Receiver { /// The method that native callee expression `id` names: through a handle /// (`h.m`), `this.m`, `super.m`, `C::m`, or unqualified inside a method. -/// Returns the method's subroutine, its number of formals, and the object +/// Returns the method's subroutine, the names of its formals, and the object /// it is called on. A virtual method is called through its dispatcher, /// except as `super.m`, which names the base's implementation (IEEE /// 1800-2023 8.15, 8.20). @@ -662,7 +662,7 @@ pub(in crate::ast) fn method( id: ExprId, native: &Declarations, dimensions: &PackedDimensions, -) -> Converted> { +) -> Converted>, Receiver)>> { let mut through_super = false; let (class_name, method_name, receiver) = match &native.expression(ungroup(id, native)).kind { ExprKind::Member { @@ -724,7 +724,7 @@ pub(in crate::ast) fn method( } return Ok(Some(( Class::subroutine_name(&class_name, &method_name), - 1, + vec![None], receiver, ))); } @@ -764,7 +764,7 @@ pub(in crate::ast) fn method( receiver => receiver, } }; - let formals = method.formals.len(); + let formals = method.formals.clone(); let subroutine = if method.is_virtual && !through_super && receiver != Receiver::Static { Class::dispatcher_name(&method.owner, &method.name) } else { diff --git a/crates/celox-sv-analyzer/src/ast/expressions.rs b/crates/celox-sv-analyzer/src/ast/expressions.rs index 26524a5f22a..d1f8390477b 100644 --- a/crates/celox-sv-analyzer/src/ast/expressions.rs +++ b/crates/celox-sv-analyzer/src/ast/expressions.rs @@ -353,7 +353,7 @@ pub(super) fn query_actual_is_writable(expression: &Expr, dimensions: &PackedDim /// Syntax adapters provide normalized names and optional values, not source text. pub(super) fn bind_normalized_call_arguments( name: &str, - mut positional: Vec>, + positional: Vec>, named: Vec<(String, Option)>, signatures: &HashMap>, ) -> Converted<(Vec>, Vec)> { @@ -363,26 +363,47 @@ pub(super) fn bind_normalized_call_arguments( let params = signatures .get(name) .ok_or_else(|| unsupported(format!("named arguments of `{name}`")))?; - if positional.len() > params.len() { - return Err(unsupported(format!("too many arguments of `{name}`"))); + bind_to_formals(name, positional, named, params) +} + +/// Binds the positional actuals, then the named ones, to `formals`. An +/// unnamed formal is the empty string. Returns the actual of each formal, +/// `None` for one that takes its default (13.5.3), and the formals in the +/// order their actuals are written, then the rest, which is the order they +/// are evaluated in. +pub(super) fn bind_to_formals( + name: &str, + mut positional: Vec>, + named: Vec<(String, Option)>, + formals: &[impl AsRef], +) -> Converted<(Vec>, Vec)> { + let invalid = |detail: String| AnalyzerError::InvalidCallArguments { + subroutine: name.to_string(), + detail: format!("{detail} (IEEE 1800-2023 13.5.4)"), + }; + if positional.len() > formals.len() { + return Err(invalid(format!( + "{} actuals for {} formals", + positional.len() + named.len(), + formals.len() + ))); } let mut order: Vec<_> = (0..positional.len()).collect(); let mut bound: HashSet<_> = order.iter().copied().collect(); - positional.resize(params.len(), None); + positional.resize_with(formals.len(), || None); for (formal, expr) in named { - let position = params + let position = formals .iter() - .position(|param| *param == formal) - .ok_or_else(|| unsupported(format!("argument `{formal}` of `{name}`")))?; + .position(|param| !formal.is_empty() && param.as_ref() == formal) + .ok_or_else(|| invalid(format!("no formal named `{formal}`")))?; + // An empty named actual `.a()` binds its formal too. if !bound.insert(position) { - return Err(unsupported(format!( - "duplicate argument `{formal}` of `{name}`" - ))); + return Err(invalid(format!("formal `{formal}` is bound twice"))); } positional[position] = expr; order.push(position); } // Defaults for unbound formals are resolved by the call lowerer. - order.extend((0..params.len()).filter(|position| !bound.contains(position))); + order.extend((0..formals.len()).filter(|position| !bound.contains(position))); Ok((positional, order)) } diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 8d360c66a55..ffc59212e4a 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -1055,7 +1055,8 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { return Err(unsupported("srandom requires a seed argument")); } args.resize( - formals + usize::from(receiver != expression_binding::ObjectReceiver::Static), + formals.len() + + usize::from(receiver != expression_binding::ObjectReceiver::Static), None, ); Expr::Call { diff --git a/crates/celox-sv-analyzer/src/ast/procedural/references.rs b/crates/celox-sv-analyzer/src/ast/procedural/references.rs index d3398066219..e098ba465d3 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/references.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/references.rs @@ -1,5 +1,6 @@ //! Uses of reference formals and calls passing by reference that IEEE -//! 1800-2023 forbids, checked once the bodies are bound. +//! 1800-2023 forbids, and calls that omit an actual without a default, +//! checked once the bodies are bound. use super::*; use crate::procedural::ParamDirection; use lifetimes::{expr_reads, stmt_exprs, visit_calls}; @@ -32,8 +33,36 @@ pub(in crate::ast) fn validate<'a>( .and_then(|directions| directions.get(position)) .copied() }; - // A net is never passed by reference (13.5.2). + let subroutines = subroutines.collect::>(); + let params = subroutines + .iter() + .map(|subroutine| (subroutine.name.as_str(), subroutine.params.as_slice())) + .collect::>(); let check_call = |name: &str, args: &[Option]| -> Result<(), AnalyzerError> { + let unbindable = |detail: String| AnalyzerError::InvalidCallArguments { + subroutine: name.strip_suffix("$virtual").unwrap_or(name).to_owned(), + detail, + }; + if let Some(params) = params.get(name) { + if args.len() > params.len() { + return Err(unbindable(format!( + "{} actuals for {} formals (IEEE 1800-2023 13.5.4)", + args.len(), + params.len() + ))); + } + // An omitted actual takes the default of its formal, which + // shall have one (IEEE 1800-2023 13.5.3). + if let Some((_, missing)) = params.iter().enumerate().find(|(position, param)| { + param.default.is_none() && args.get(*position).is_none_or(Option::is_none) + }) { + return Err(unbindable(format!( + "formal `{}` has no default and is not given an actual (IEEE 1800-2023 13.5.3)", + missing.source_name + ))); + } + } + // A net is never passed by reference (13.5.2). for (position, arg) in args.iter().enumerate() { if let Some(actual) = arg.as_ref().and_then(root_variable) && direction(name, position).is_some_and(ParamDirection::is_reference) diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index ae7b1992bd4..54f5ddb8e40 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -215,6 +215,12 @@ pub enum AnalyzerError { argument: String, detail: String, }, + /// Actuals that cannot be bound to the formals of a task or function: + /// a name it has no formal for, a formal bound twice, too many actuals, + /// a positional actual after a named one (IEEE 1800-2023 13.5.4), or + /// none for a formal without a default (13.5.3). + #[error("arguments of `{subroutine}`: {detail}")] + InvalidCallArguments { subroutine: String, detail: String }, } impl miette::Diagnostic for AnalyzerError {} diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 4571b041648..dfbb33c00df 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -552,7 +552,7 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_icarus_unpacked_subroutine_ports` | compile | icarus | 2 | Icarus 13.0 reports that subroutine ports with unpacked dimensions are not yet supported. Verilator passes the valid case. | | `sv_icarus_classes` | compile | icarus | 5 | Icarus 13.0 does not support extern methods ("sorry: External methods are not yet supported") or string methods called on a class property ("Can't find task itoa in class Named") or comparisons of class handles ("SORRY: Compare class handles not implemented"), aborts on a failed assertion in dup_expr.cc while compiling objects_referring_to_objects, and crashes with a segmentation fault while compiling implicit_constructors_and_this. IEEE 1800-2023 8.4, 8.7, 8.8 and 8.24 define these constructs. Verilator passes all but the string-method case, see sv_verilator_class_property_string_methods. | | `sv_icarus_nested_class_members` | execute | icarus | 1 | Icarus 13.0 reads an empty string through a nested property path (kept.inner.text) after reporting "sorry: Nested member path not yet supported for class properties" for its assignment. IEEE 1800-2023 8.5 permits accessing a property of an object referred to by a property. Verilator passes the case. | -| `sv_icarus_class_scope_resolution` | compile | icarus | 3 | Icarus 13.0 rejects class scope resolution with a syntax error: reading a static property (Counter::created), calling a static method (Counter::next()) and assigning a static property (Counter::last = "set"). IEEE 1800-2023 8.9, 8.10 and 8.23 define these accesses. Verilator passes both cases. | +| `sv_icarus_class_scope_resolution` | compile | icarus | 4 | Icarus 13.0 rejects class scope resolution with a syntax error: reading a static property (Counter::created), calling a static method (Counter::next()) and assigning a static property (Counter::last = "set"). IEEE 1800-2023 8.9, 8.10 and 8.23 define these accesses. Verilator passes both cases. | | `sv_icarus_virtual_dispatch` | execute | icarus | 1 | Icarus 13.0 binds a virtual function called through a base-class handle to the handle's class instead of the object's: the shared case prints area=0 for every shape, and the adapter-free source prints 1 1 1 3 where IEEE 1800-2023 8.20 requires 2 3 4 4. Verilator and Celox print 2 3 4 4 and pass the case. | | `sv_icarus_abstract_and_interface_classes` | compile | icarus | 8 | Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors ("Invalid class item", "Invalid module item") and fails code generation without a diagnostic ("Code generation had 2 error(s)") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes all but two cases; see sv_verilator_interface_class_casts and sv_verilator_extended_interface_class_methods. | | `sv_verilator_interface_class_casts` | execute | verilator | 1 | Verilator 5.052 returns 0 from $cast of a handle of one interface class to a variable of another interface class that the object's class also implements, so the case dereferences the unassigned null handle; the adapter-free source prints 0 1 where IEEE 1800-2023 8.16 and 8.26.5 require 1 1. Celox prints 1 1. Icarus rejects interface classes, see sv_icarus_abstract_and_interface_classes. | diff --git a/crates/celox-test-suite/src/sv/cases/class.vtest b/crates/celox-test-suite/src/sv/cases/class.vtest index cf6e2042d71..0822afdb950 100644 --- a/crates/celox-test-suite/src/sv/cases/class.vtest +++ b/crates/celox-test-suite/src/sv/cases/class.vtest @@ -911,6 +911,64 @@ endmodule (top Top) (run_until 0) (assert_eq done 1) (expect_output "1 18 31\n44\n")) +(case named_method_arguments + (source "class.sv" #" +module Top(output bit done); + class Pair; + string name; + function new(string name); + this.name = name; + endfunction + endclass + class Base; + virtual function int m(int a, int b = 5, int c = 7); + return a * 100 + b * 10 + c; + endfunction + endclass + class Derived extends Base; + static function int sf(int x = 1, int y = 2); + return x * 10 + y; + endfunction + virtual function int m(int a, int b = 6, int c = 8); + return 1000 + super.m(.c(c), .a(a)); + endfunction + function int own(); + return this.m(.b(1), .a(2)) + m(3, .c(4)); + endfunction + task automatic t(input int a, output int o, input int d = 9); + #1 o = a + d; + endtask + function bit pair_matches(Pair match_pair, Pair requested, string requested_name); + return match_pair == requested || match_pair.name == requested_name; + endfunction + function int find(Pair pair, string name); + if (pair_matches(.match_pair(pair), .requested(null), .requested_name(name))) + return 1; + return pair_matches(.requested_name(name), .requested(pair), .match_pair(pair)) ? 2 : 0; + endfunction + endclass + Derived d; + Base b; + Pair pair; + int o; + initial begin + d = new; + pair = new("x"); + b = d; + $display("%0d %0d %0d", d.m(.a(1)), b.m(.c(2), .a(1)), d.m(1, , 3)); + $display("%0d %0d %0d", Derived::sf(.y(5)), Derived::sf(.x(), .y()), d.own()); + d.t(.o(o), .a(4)); + $display("%0d", o); + d.t(5, .o(o), .d()); + $display("%0d", o); + $display("%0d %0d", d.find(pair, "x"), d.find(pair, "y")); + done = 1; + end +endmodule +"#) + (top Top) (run_until 2) (assert_eq done 1) + (expect_output "1158 1152 1153\n15 12 2612\n13\n14\n1 2\n")) + (case typedefs_of_interface_classes (source "class.sv" #" module Top(output bit done); diff --git a/crates/celox-test-suite/verification/sv/icarus/class.json b/crates/celox-test-suite/verification/sv/icarus/class.json index 758123372ed..5c658331af6 100644 --- a/crates/celox-test-suite/verification/sv/icarus/class.json +++ b/crates/celox-test-suite/verification/sv/icarus/class.json @@ -1046,6 +1046,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "Icarus 13.0 rejects class scope resolution with a syntax error: reading a static property (Counter::created), calling a static method (Counter::next()) and assigning a static property (Counter::last = \"set\"). IEEE 1800-2023 8.9, 8.10 and 8.23 define these accesses. Verilator passes both cases.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_class_scope_resolution", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects class scope resolution with a syntax error: reading a static property (Counter::created), calling a static method (Counter::next()) and assigning a static property (Counter::last = \"set\"). IEEE 1800-2023 8.9, 8.10 and 8.23 define these accesses. Verilator passes both cases.", + "upstream": [] + }, + "name": "class::named_method_arguments", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 678cda31ec5..a153841389c 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -1921,7 +1921,8 @@ "icarus": [ "class::static_properties_and_methods", "class::classes_of_the_compilation_unit", - "class::package_classes_by_their_qualified_names" + "class::package_classes_by_their_qualified_names", + "class::named_method_arguments" ] } }, diff --git a/crates/celox-test-suite/verification/sv/limitations/icarus.json b/crates/celox-test-suite/verification/sv/limitations/icarus.json index facf02b146f..2363c511726 100644 --- a/crates/celox-test-suite/verification/sv/limitations/icarus.json +++ b/crates/celox-test-suite/verification/sv/limitations/icarus.json @@ -9,7 +9,7 @@ "unexpected_accept": 1, "mismatch": 17, "emission_error": 0, - "compile_error": 138, + "compile_error": 139, "runtime_error": 8, "unsupported": 0, "ignored": 0 @@ -1503,6 +1503,14 @@ "name": "class::package_classes_by_their_qualified_names", "phase": "compile", "status": "compile_error" + }, + { + "category": "Types", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:45: syntax error\n/source_0.sv:45: error: Malformed statement\n", + "expectation": "Simulation", + "name": "class::named_method_arguments", + "phase": "compile", + "status": "compile_error" } ] } diff --git a/crates/celox/tests/frontends/systemverilog/class.rs b/crates/celox/tests/frontends/systemverilog/class.rs index ff8642e8241..941ffe470da 100644 --- a/crates/celox/tests/frontends/systemverilog/class.rs +++ b/crates/celox/tests/frontends/systemverilog/class.rs @@ -45,6 +45,7 @@ sv_backends! { fn class_class_scoped_parameters_and_types(sim) { @case "class::class_scoped_parameters_and_types"; } fn class_specializations_of_interface_classes(sim) { @case "class::specializations_of_interface_classes"; } fn class_named_constructor_arguments(sim) { @case "class::named_constructor_arguments"; } + fn class_named_method_arguments(sim) { @case "class::named_method_arguments"; } fn class_typedefs_of_interface_classes(sim) { @case "class::typedefs_of_interface_classes"; } fn class_specializations_in_generate_blocks(sim) { @case "class::specializations_in_generate_blocks"; } fn class_specializations_keep_their_parameter_scopes(sim) { @case "class::specializations_keep_their_parameter_scopes"; } @@ -92,6 +93,85 @@ sv_backends! { assert_eq!(sim.get(sim.signal("y")), 1u32.into()); } + fn named_method_arguments_are_evaluated_in_written_order(sim) { + @setup { + let source = r#"module Top(output int x, output int y); + class Point; + int x; + int y; + function void set(int x = 0, int y = 0); + this.x = x; + this.y = y; + endfunction + endclass + int count; + function int next(); + count++; + return count; + endfunction + Point point; + initial begin + point = new; + point.set(.y(next()), .x(next())); + x = point.x; + y = point.y; + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("order.sv"))], "Top"); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("x")), 2u32.into()); + assert_eq!(sim.get(sim.signal("y")), 1u32.into()); + } + + // The shape of uvm_factory's `m_matches_type_pair` calls: an + // out-of-block method bound by name, with a `null` actual. Out of the + // shared cases because Icarus does not support out-of-block methods and + // xezim evaluates them wrongly in an instantiated module. + fn named_arguments_of_out_of_block_methods(sim) { + @setup { + let source = r#"module Top(output int hits); + class Pair; + string name; + function new(string name); + this.name = name; + endfunction + endclass + class Factory; + extern protected function bit matches_type_pair(Pair match_type_pair, + Pair requested_type, string requested_type_name); + function int find(Pair pair, string name); + int found = 0; + if (matches_type_pair(.match_type_pair(pair), + .requested_type(null), + .requested_type_name(name))) + found += 1; + if (matches_type_pair(.requested_type_name("other"), + .requested_type(pair), + .match_type_pair(pair))) + found += 10; + return found; + endfunction + endclass + function bit Factory::matches_type_pair(Pair match_type_pair, + Pair requested_type, string requested_type_name); + return match_type_pair == requested_type + || match_type_pair.name == requested_type_name; + endfunction + Factory factory; + Pair pair; + initial begin + factory = new; + pair = new("x"); + hits = factory.find(pair, "x") * 100 + factory.find(pair, "y"); + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("factory.sv"))], "Top"); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("hits")), 1110u32.into()); + } + fn null_dereferences_are_runtime_errors(sim) { @setup { let source = r#"module Top(output int value, output bit done); @@ -454,7 +534,7 @@ fn misused_parameterized_classes_are_rejected() { ( "class Point; function new(int x = 0); endfunction endclass Point p; initial p = new(.x(), .x(1));", - ["constructor argument passed twice", ""], + ["formal `x` is bound twice", "13.5.4"], ), ( "Box #(.N(), .N(2)) twice;", @@ -507,6 +587,48 @@ fn misused_parameterized_classes_are_rejected() { } } +/// Calls whose actuals cannot be bound to the formals are compile errors +/// (IEEE 1800-2023 13.5.3, 13.5.4), for methods as for other subroutines. +#[test] +fn unbindable_call_arguments_are_rejected() { + for (call, want) in [ + ("c.f(.a(1), .a(2))", "formal `a` is bound twice"), + ("c.f(1, .a(2))", "formal `a` is bound twice"), + ("c.f(.q(1))", "no formal named `q`"), + ("c.f(.b(1), 3)", "a positional actual after a named one"), + ("c.f(1, 2, 3)", "3 actuals for 2 formals"), + ("c.f(.b(1))", "formal `a` has no default"), + ("c.f(, 1)", "formal `a` has no default"), + ("c.f(.a(), .b(1))", "formal `a` has no default"), + ("C::s(.z(1))", "no formal named `z`"), + ("f(.a(1), .a(2))", "formal `a` is bound twice"), + ("f(.z(1))", "no formal named `z`"), + ("f(.b(1), 2)", "a positional actual after a named one"), + ("f(.b(1))", "formal `a` has no default"), + ("f(1, 2, 3)", "3 actuals for 2 formals"), + ] { + let source = format!( + "module Top; + class C; + function int f(int a, int b = 2); return a + b; endfunction + static function int s(int a = 1); return a; endfunction + endclass + function automatic int f(int a, int b = 2); return a + b; endfunction + C c = new; + initial $display(\"%0d\", {call}); + endmodule" + ); + let Err(error) = + Simulator::from_sv_sources(vec![(source.as_str(), Path::new("call.sv"))], "Top") + .build_cranelift() + else { + panic!("`{call}` is accepted"); + }; + let error = error.to_string(); + assert!(error.contains(want), "{call}: {error}"); + } +} + sv_backends! { fn class_unconstrained_randomize(sim) { @case "class::unconstrained_randomize"; } fn class_randomize_without_rand_members(sim) { @case "class::randomize_without_rand_members"; } diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index 7179f02173f..fbd311c0ebe 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -710,7 +710,9 @@ fn rejects_dropped_unrepresentable_function_call_actuals() { "#, ); assert!( - error.contains("combinational expression") || error.contains("function call"), + error.contains("combinational expression") + || error.contains("function call") + || error.contains("2 actuals for 1 formals"), "unexpected error: {error}" ); } diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 6548eb8681b..7a9703d18db 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -33,7 +33,7 @@ synthesis and is tested at the design level. | 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) | | 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 up to 64 bits (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 constructor arguments; shallow copies (`new h`). See [classes](#classes) | +| Classes | classes declared in a module, a package or the compilation unit: properties of 2-state and 4-state integral types up to 64 bits (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`). See [classes](#classes) | | Parameters | integral parameters and overrides preserving widths beyond 128 bits and X/Z values, and parameters of unpacked array or packed struct type given by an assignment pattern (constant tables), including unpacked-array pattern overrides | ### Processes and control flow @@ -780,9 +780,16 @@ to an `output` or `inout` argument; it is written back when that call returns. ### Named subroutine arguments -Named subroutine arguments bind by formal name. Input evaluation and output +Named subroutine arguments bind by formal name, in calls of functions, tasks +and class methods alike: through a handle, `this.`, `super.`, unqualified +inside the class, static methods through `C::` and constructors (IEEE +1800-2023 13.5.4). Positional arguments may precede named ones, and an empty +named argument `.a()` takes the default. Input evaluation and output copy-out retain source order. Expressions and call statements support omitted -arguments with ANSI-declared defaults. Defaults are evaluated only when used, +arguments with ANSI-declared defaults, also between given ones. A name with no +formal, a formal bound twice, a positional argument after a named one, too +many arguments, and an omitted argument whose formal has no default are +compile errors. Defaults are evaluated only when used, in the enclosing declaration scope (IEEE 1800-2023 13.5.3). Constant calls use the same formal names in parameter initializers, ranges and generate conditions; generate-local declarations retain their own signatures. Named calls with