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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 6 additions & 43 deletions crates/celox-sv-analyzer/src/ast/classes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,51 +273,14 @@ impl Class {
&self,
arguments: &[celox_sv_syntax::Argument],
) -> Converted<(Vec<Option<celox_sv_syntax::ExprId>>, Vec<usize>)> {
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::<Vec<_>>();
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
Expand Down
2 changes: 1 addition & 1 deletion crates/celox-sv-analyzer/src/ast/expression_binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down
148 changes: 107 additions & 41 deletions crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>],
) -> Converted<(Vec<Option<ExprId>>, Vec<usize>)> {
// `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::<Vec<_>>();
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<Option<ExprId>>, Vec<(String, Option<ExprId>)>)> {
let mut positional = Vec::new();
let mut named = Vec::new();
for arg in args {
Expand All @@ -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(
Expand Down Expand Up @@ -248,14 +283,21 @@ enum Finish {
},
/// A read of property `property` of the object handle child.
ObjectLoad(Box<crate::ast::classes::Property>),
/// 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<Expr>,
},
MethodCall(Box<MethodCall>),
}

/// 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<bool>,
/// The formals in the order their actuals are evaluated.
order: Vec<usize>,
formals: usize,
receiver: objects::Receiver,
selection: Option<Expr>,
}

enum Job {
Expand Down Expand Up @@ -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));
Expand All @@ -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,
Expand All @@ -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,
)
}
Expand Down Expand Up @@ -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<Option<Expr>> = 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) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand All @@ -662,7 +662,7 @@ pub(in crate::ast) fn method(
id: ExprId,
native: &Declarations,
dimensions: &PackedDimensions,
) -> Converted<Option<(String, usize, Receiver)>> {
) -> Converted<Option<(String, Vec<Option<String>>, Receiver)>> {
let mut through_super = false;
let (class_name, method_name, receiver) = match &native.expression(ungroup(id, native)).kind {
ExprKind::Member {
Expand Down Expand Up @@ -724,7 +724,7 @@ pub(in crate::ast) fn method(
}
return Ok(Some((
Class::subroutine_name(&class_name, &method_name),
1,
vec![None],
receiver,
)));
}
Expand Down Expand Up @@ -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 {
Expand Down
43 changes: 32 additions & 11 deletions crates/celox-sv-analyzer/src/ast/expressions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T: Clone>(
name: &str,
mut positional: Vec<Option<T>>,
positional: Vec<Option<T>>,
named: Vec<(String, Option<T>)>,
signatures: &HashMap<String, Vec<String>>,
) -> Converted<(Vec<Option<T>>, Vec<usize>)> {
Expand All @@ -363,26 +363,47 @@ pub(super) fn bind_normalized_call_arguments<T: Clone>(
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<T>(
name: &str,
mut positional: Vec<Option<T>>,
named: Vec<(String, Option<T>)>,
formals: &[impl AsRef<str>],
) -> Converted<(Vec<Option<T>>, Vec<usize>)> {
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))
}
3 changes: 2 additions & 1 deletion crates/celox-sv-analyzer/src/ast/procedural.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading
Loading