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
52 changes: 51 additions & 1 deletion crates/vm/src/function/argument.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::{
convert::ToPyObject,
object::{Traverse, TraverseFn},
};
use core::ops::{Deref, DerefMut, RangeInclusive};
use core::ops::{ControlFlow, Deref, DerefMut, RangeInclusive};
use indexmap::IndexMap;
use itertools::Itertools;
use std::hash::DefaultHasher;
Expand Down Expand Up @@ -322,6 +322,14 @@ impl FuncArgs {
return Err(callee.given_by_name_and_position(name, pos, vm));
}

// A missing required parameter is reported before any argument is
// converted, so a conversion cannot run user code first.
if let Some(params) = T::PARAMS
&& let Some(missing) = first_missing_required(params, num_given, &self.kwargs)
{
return Err(callee.missing_argument(missing.0, missing.1, vm));
}

let bound = T::from_args(vm, &mut self)
.map_err(|e| e.into_exception(&arity, num_given, callee, vm))?;

Expand Down Expand Up @@ -534,6 +542,48 @@ fn duplicate_name_and_position<'a>(
walk(params, nargs, kwargs, &mut 0)
}

/// First required positional-or-keyword parameter that neither a positional
/// nor a keyword argument fills. A positional-only parameter is left to the
/// type, since a hand-written `FromArgs` may declare it for the signature only.
fn first_missing_required<'a>(
params: &'a [Param],
nargs: usize,
kwargs: &KwArgs,
) -> Option<(&'a str, usize)> {
fn walk<'a>(
params: &'a [Param],
nargs: usize,
kwargs: &KwArgs,
pos: &mut usize,
) -> ControlFlow<Option<(&'a str, usize)>> {
for param in params {
match param.kind {
ParamKind::Flatten(Some(inner)) => walk(inner, nargs, kwargs, pos)?,
ParamKind::Flatten(None) | ParamKind::VarPositional => {
return ControlFlow::Break(None);
}
ParamKind::PositionalOnly => *pos += 1,
ParamKind::PositionalOrKeyword => {
*pos += 1;
if nargs < *pos
&& param.default.is_none()
&& !param.name.is_empty()
&& !kwargs.contains_key(param.name)
{
return ControlFlow::Break(Some((param.name, *pos)));
}
}
ParamKind::KeywordOnly | ParamKind::VarKeyword => {}
}
}
ControlFlow::Continue(())
}
match walk(params, nargs, kwargs, &mut 0) {
ControlFlow::Break(missing) => missing,
ControlFlow::Continue(()) => None,
}
}

/// The branch of _PyArg_UnpackKeywords that names a parameter it didn't get.
pub(crate) fn missing_argument_message(name: Option<&str>, keyword: &str, pos: usize) -> String {
let (name, parens) = call_form(name, "function");
Expand Down
20 changes: 20 additions & 0 deletions extra_tests/snippets/vm_argument_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,25 @@ def __index__(self):
hex(FailingIndex(), 1)


def test_a_missing_argument_is_reported_before_any_is_converted():
class RaisingIter:
def __iter__(self):
raise RuntimeError("__iter__ called")

message = "compress() missing required argument 'selectors' (pos 2)"
check(TypeError, message, itertools.compress, RaisingIter())
check(TypeError, message, itertools.compress, data=RaisingIter())
check(
TypeError,
"compress() missing required argument 'data' (pos 1)",
itertools.compress,
selectors=RaisingIter(),
)
# With every argument given, the conversion still runs.
with assert_raises(RuntimeError):
itertools.compress(RaisingIter(), [])


test_the_message_names_the_function()
test_a_method_does_not_count_its_instance()
test_one_argument_is_singular()
Expand All @@ -176,3 +195,4 @@ def __index__(self):
test_a_slot_that_counts_its_own_arguments_says_the_same_thing()
test_a_keyword_check_of_its_own_says_the_same_thing()
test_too_many_arguments_are_counted_before_any_is_converted()
test_a_missing_argument_is_reported_before_any_is_converted()