Skip to content

Commit

Permalink
dsl_util: add helper function that formats arguments count error message
Browse files Browse the repository at this point in the history
  • Loading branch information
yuja committed May 29, 2024
1 parent a32cc9e commit 49d9b45
Showing 1 changed file with 17 additions and 9 deletions.
26 changes: 17 additions & 9 deletions lib/src/dsl_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ impl<'i, T> FunctionCallNode<'i, T> {
self.args
.as_slice()
.try_into()
.map_err(|_| self.invalid_arguments(format!("Expected {N} arguments")))
.map_err(|_| self.invalid_arguments_count(N, Some(N)))
}

/// Extracts N required arguments and remainders.
Expand All @@ -77,7 +77,7 @@ impl<'i, T> FunctionCallNode<'i, T> {
let (required, rest) = self.args.split_at(N);
Ok((required.try_into().unwrap(), rest))
} else {
Err(self.invalid_arguments(format!("Expected at least {N} arguments")))
Err(self.invalid_arguments_count(N, None))
}
}

Expand All @@ -103,7 +103,7 @@ impl<'i, T> FunctionCallNode<'i, T> {
))
} else {
let (min, max) = count_range.into_inner();
Err(self.invalid_arguments(format!("Expected {min} to {max} arguments")))
Err(self.invalid_arguments_count(min, Some(max)))
}
}

Expand All @@ -114,6 +114,15 @@ impl<'i, T> FunctionCallNode<'i, T> {
span: self.args_span,
}
}

fn invalid_arguments_count(&self, min: usize, max: Option<usize>) -> InvalidArguments<'i> {
let message = match (min, max) {
(min, Some(max)) if min == max => format!("Expected {min} arguments"),
(min, Some(max)) => format!("Expected {min} to {max} arguments"),
(min, None) => format!("Expected at least {min} arguments"),
};
self.invalid_arguments(message)
}
}

/// Unexpected number of arguments, or invalid combination of arguments.
Expand Down Expand Up @@ -444,12 +453,11 @@ where
span: pest::Span<'i>,
) -> Result<T, Self::Error> {
if let Some((id, params, defn)) = self.aliases_map.get_function(function.name) {
if function.args.len() != params.len() {
return Err(E::invalid_arguments(InvalidArguments {
name: function.name,
message: format!("Expected {} arguments", params.len()),
span: function.args_span,
}));
let arity = params.len();
if function.args.len() != arity {
return Err(E::invalid_arguments(
function.invalid_arguments_count(arity, Some(arity)),
));
}
// Resolve arguments in the current scope, and pass them in to the alias
// expansion scope.
Expand Down

0 comments on commit 49d9b45

Please sign in to comment.