Skip to content

Commit 5955305

Browse files
committed
Report argument type mismatches with _PyArg_BadArgument
A PyRef<T> argument that fails its isinstance check while binding arguments now raises "{name}() {displayname} must be {expected}, not {found}", with the expected name taken from T's tp_name. The display name is "argument 'name'" for a keyword-capable parameter, "argument" for a function taking exactly one positional argument, and "argument N" otherwise. Option<T> reports "X or None". TryFromObject gains try_from_argument, overridden by PyRef<T> and Option<T>; other conversions keep their errors. The derive converts fields through it, so the pyarg `expected` attribute is removed. A callee without a name, or a failing instance argument, keeps the previous downcast message. Assisted-by: Claude:claude-opus-5-5 Assisted-by: Grok:grok-4.7
1 parent 2e807e5 commit 5955305

7 files changed

Lines changed: 172 additions & 56 deletions

File tree

‎crates/derive-impl/src/from_args.rs‎

Lines changed: 13 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,6 @@ struct ArgAttribute {
4747
optional: bool,
4848
py_default: Option<String>,
4949
error_msg: Option<String>,
50-
expected: Option<String>,
5150
}
5251

5352
impl ArgAttribute {
@@ -77,7 +76,6 @@ impl ArgAttribute {
7776
optional: false,
7877
py_default: None,
7978
error_msg: None,
80-
expected: None,
8179
});
8280
return Ok(());
8381
};
@@ -133,23 +131,8 @@ impl ArgAttribute {
133131
if self.error_msg.is_some() {
134132
return Err(meta.error("already have an error_msg"));
135133
}
136-
if self.expected.is_some() {
137-
return Err(meta.error("cannot combine expected with error_msg"));
138-
}
139134
let val = meta.value()?.parse::<syn::LitStr>()?;
140135
self.error_msg = Some(val.value())
141-
} else if meta.path.is_ident("expected") {
142-
if self.expected.is_some() {
143-
return Err(meta.error("already have an expected"));
144-
}
145-
if self.kind != ParameterKind::PositionalOnly {
146-
return Err(meta.error("`expected` is only valid on a positional argument"));
147-
}
148-
if self.error_msg.is_some() {
149-
return Err(meta.error("cannot combine expected with error_msg"));
150-
}
151-
let val = meta.value()?.parse::<syn::LitStr>()?;
152-
self.expected = Some(val.value())
153136
} else {
154137
return Err(meta.error("Unrecognized pyarg attribute"));
155138
}
@@ -202,28 +185,25 @@ fn generate_field((i, field): (usize, &Field)) -> Result<TokenStream> {
202185
.or(name_string)
203186
.ok_or_else(|| err_span!(field, "field in tuple struct must have name attribute"))?;
204187

205-
let middle = if let Some(expected) = &attr.expected {
206-
let pos = i + 1;
207-
quote! {
208-
.map(|x| {
209-
let found = x.clone();
210-
::rustpython_vm::convert::TryFromObject::try_from_object(vm, x).map_err(|_| {
211-
::rustpython_vm::function::ArgumentError::BadArgument {
212-
pos: #pos,
213-
expected: #expected,
214-
found,
215-
}
216-
})
217-
}).transpose()?
218-
}
219-
} else if let Some(error_msg) = &attr.error_msg {
188+
let convert = match attr.kind {
189+
ParameterKind::PositionalOnly => quote! {
190+
|x| ::rustpython_vm::convert::TryFromObject::try_from_argument(vm, x)
191+
},
192+
ParameterKind::PositionalOrKeyword | ParameterKind::KeywordOnly => quote! {
193+
|x| ::rustpython_vm::convert::TryFromObject::try_from_argument(vm, x)
194+
.map_err(|err| err.with_argument_name(#pyname))
195+
},
196+
ParameterKind::Flatten => unreachable!(),
197+
};
198+
199+
let middle = if let Some(error_msg) = &attr.error_msg {
220200
quote! {
221201
.map(|x| ::rustpython_vm::convert::TryFromObject::try_from_object(vm, x)
222202
.map_err(|_| vm.new_type_error(#error_msg))).transpose()?
223203
}
224204
} else {
225205
quote! {
226-
.map(|x| ::rustpython_vm::convert::TryFromObject::try_from_object(vm, x)).transpose()?
206+
.map(#convert).transpose()?
227207
}
228208
};
229209

‎crates/derive-impl/src/from_args/integer_alias_tests.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ fn integer_alias_literal_defaults_stay_native() {
2525
assert!(!tokens.contains("ToPyObject"));
2626
assert!(
2727
tokens.contains(
28-
&quote!(::rustpython_vm::convert::TryFromObject::try_from_object(
28+
&quote!(::rustpython_vm::convert::TryFromObject::try_from_argument(
2929
vm, x
3030
))
3131
.to_string()

‎crates/derive/src/lib.rs‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,6 @@ use syn::punctuated::Punctuated;
4444
/// when a missing argument is a distinct state, or give the default's type a
4545
/// real `py_default()`.
4646
/// - `error_msg = "..."`: type-error text when conversion fails.
47-
/// - `expected = "..."`: `_PyArg_BadArgument` type for a positional conversion
48-
/// failure. Cannot be combined with `error_msg`.
4947
/// # Signature default
5048
/// An explicit `py_default` is used as written. Otherwise:
5149
/// - a literal, a negative literal, or the path `None` becomes a typed default

‎crates/vm/src/convert/try_from.rs‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use num_traits::ToPrimitive;
44
use crate::{
55
Py, VirtualMachine,
66
builtins::PyFloat,
7+
function::ArgumentError,
78
object::{AsObject, PyObject, PyObjectRef, PyPayload, PyRef, PyResult},
89
};
910

@@ -14,6 +15,13 @@ use crate::{
1415
pub trait TryFromObject: Sized {
1516
/// Attempt to convert a Python object to a value of this type.
1617
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self>;
18+
19+
/// Convert a call argument. `PyRef<T>` turns an isinstance failure into
20+
/// `_PyArg_BadArgument`; other types keep `try_from_object`.
21+
#[inline]
22+
fn try_from_argument(vm: &VirtualMachine, obj: PyObjectRef) -> Result<Self, ArgumentError> {
23+
Self::try_from_object(vm, obj).map_err(Into::into)
24+
}
1725
}
1826

1927
/// Rust-side only version of TryFromObject to reduce unnecessary Rc::clone
@@ -86,6 +94,22 @@ where
8694
Err(vm.new_downcast_type_error(class, &obj))
8795
}
8896
}
97+
98+
#[inline]
99+
fn try_from_argument(vm: &VirtualMachine, obj: PyObjectRef) -> Result<Self, ArgumentError> {
100+
let class = T::class(&vm.ctx);
101+
if obj.fast_isinstance(class) {
102+
T::try_downcast_from(&obj, vm)?;
103+
Ok(unsafe { obj.downcast_unchecked() })
104+
} else {
105+
Err(ArgumentError::BadArgument {
106+
expected: class,
107+
or_none: false,
108+
found: obj,
109+
name: None,
110+
})
111+
}
112+
}
89113
}
90114

91115
impl TryFromObject for PyObjectRef {
@@ -103,6 +127,16 @@ impl<T: TryFromObject> TryFromObject for Option<T> {
103127
T::try_from_object(vm, obj).map(Some)
104128
}
105129
}
130+
131+
fn try_from_argument(vm: &VirtualMachine, obj: PyObjectRef) -> Result<Self, ArgumentError> {
132+
if vm.is_none(&obj) {
133+
Ok(None)
134+
} else {
135+
T::try_from_argument(vm, obj)
136+
.map(Some)
137+
.map_err(ArgumentError::with_or_none)
138+
}
139+
}
106140
}
107141

108142
impl<'a, T: 'a + TryFromObject> TryFromBorrowedObject<'a> for Vec<T> {

‎crates/vm/src/function/argument.rs‎

Lines changed: 102 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use crate::{
66
convert::ToPyObject,
77
object::{Traverse, TraverseFn},
88
};
9+
use alloc::borrow::Cow;
910
use core::ops::{Deref, DerefMut, RangeInclusive};
1011
use indexmap::IndexMap;
1112
use itertools::Itertools;
@@ -305,7 +306,8 @@ impl FuncArgs {
305306
let instance = callee.instance_args();
306307
let arity = T::arity();
307308
let arity = arity.start().saturating_sub(instance)..=arity.end().saturating_sub(instance);
308-
let num_given = self.args.len().saturating_sub(instance);
309+
let nargs = self.args.len();
310+
let num_given = nargs.saturating_sub(instance);
309311

310312
// A function that takes no keywords refuses them before counting its
311313
// arguments.
@@ -316,13 +318,13 @@ impl FuncArgs {
316318
// Too many positional arguments are reported before any argument is
317319
// converted, so a conversion cannot run user code first.
318320
if num_given > *arity.end() {
319-
return Err(ArgumentError::TooManyArgs.into_exception(&arity, num_given, callee, vm));
321+
return Err(ArgumentError::TooManyArgs.into_exception(&arity, num_given, 0, callee, vm));
320322
}
321323

322324
// No keyword can fill a missing parameter of such a function, so too few
323325
// arguments are also reported before any is converted.
324326
if T::TAKES_NO_KEYWORDS && num_given < *arity.start() {
325-
return Err(ArgumentError::TooFewArgs.into_exception(&arity, num_given, callee, vm));
327+
return Err(ArgumentError::TooFewArgs.into_exception(&arity, num_given, 0, callee, vm));
326328
}
327329

328330
// A keyword that fills a parameter already given by position is
@@ -334,11 +336,20 @@ impl FuncArgs {
334336
return Err(callee.given_by_name_and_position(name, pos, vm));
335337
}
336338

337-
let bound = T::from_args(vm, &mut self)
338-
.map_err(|e| e.into_exception(&arity, num_given, callee, vm))?;
339+
let bound = match T::from_args(vm, &mut self) {
340+
Ok(bound) => bound,
341+
Err(e) => {
342+
// take_positional has just removed the failed argument, so N is
343+
// nargs - remaining, minus the instance.
344+
let pos = nargs
345+
.saturating_sub(self.args.len())
346+
.saturating_sub(instance);
347+
return Err(e.into_exception(&arity, num_given, pos, callee, vm));
348+
}
349+
};
339350

340351
if !self.args.is_empty() {
341-
Err(ArgumentError::TooManyArgs.into_exception(&arity, num_given, callee, vm))
352+
Err(ArgumentError::TooManyArgs.into_exception(&arity, num_given, 0, callee, vm))
342353
} else if let Some(err) = self.check_kwargs_empty_for(vm, callee) {
343354
Err(err)
344355
} else {
@@ -462,19 +473,31 @@ impl Callee {
462473
/// _PyArg_BadArgument
463474
fn bad_argument(
464475
self,
465-
pos: usize,
466-
expected: &'static str,
476+
displayname: &str,
477+
expected: &'static Py<PyType>,
478+
or_none: bool,
467479
found: &PyObject,
468480
vm: &VirtualMachine,
469481
) -> PyBaseExceptionRef {
482+
let expected_ty = expected.slot_name();
483+
let expected = if or_none {
484+
Cow::Owned(format!("{expected_ty} or None"))
485+
} else {
486+
Cow::Borrowed(&*expected_ty)
487+
};
470488
let class = found.class();
471489
let found_ty = class.slot_name();
472490
let found_name = if vm.is_none(found) {
473491
"None"
474492
} else {
475493
&*found_ty
476494
};
477-
vm.new_type_error(bad_argument_message(self.name, pos, expected, found_name))
495+
vm.new_type_error(bad_argument_message(
496+
self.name,
497+
displayname,
498+
&expected,
499+
found_name,
500+
))
478501
}
479502
}
480503

@@ -529,15 +552,26 @@ pub(crate) fn no_keywords_message(name: Option<&str>) -> String {
529552
format!("{name}{parens} takes no keyword arguments")
530553
}
531554

555+
/// get_displayname
556+
fn get_displayname(name: Option<&str>, pos: usize, meth_o: bool) -> Cow<'static, str> {
557+
if let Some(name) = name {
558+
Cow::Owned(format!("argument '{name}'"))
559+
} else if meth_o {
560+
Cow::Borrowed("argument")
561+
} else {
562+
Cow::Owned(format!("argument {pos}"))
563+
}
564+
}
565+
532566
/// _PyArg_BadArgument
533567
pub(crate) fn bad_argument_message(
534568
name: Option<&str>,
535-
pos: usize,
569+
displayname: &str,
536570
expected: &str,
537571
found: &str,
538572
) -> String {
539573
let (name, parens) = call_form(name, "this function");
540-
format!("{name}{parens} argument {pos} must be {expected}, not {found}")
574+
format!("{name}{parens} {displayname} must be {expected}, not {found}")
541575
}
542576

543577
pub(crate) fn given_by_name_and_position_message(
@@ -604,12 +638,13 @@ pub enum ArgumentError {
604638
/// The function requires an argument for the named parameter, at the given
605639
/// 1-based position, but the call didn't pass one.
606640
MissingRequiredArgument { name: String, pos: usize },
607-
/// The argument at the 1-based position is not the expected type.
608-
/// `_PyArg_BadArgument`.
641+
/// The argument is not the expected type. `_PyArg_BadArgument`.
642+
/// `name` is `None` for a positional-only parameter.
609643
BadArgument {
610-
pos: usize,
611-
expected: &'static str,
644+
expected: &'static Py<PyType>,
645+
or_none: bool,
612646
found: PyObjectRef,
647+
name: Option<&'static str>,
613648
},
614649
/// An exception was raised while binding arguments to the function
615650
/// parameters.
@@ -623,10 +658,49 @@ impl From<PyBaseExceptionRef> for ArgumentError {
623658
}
624659

625660
impl ArgumentError {
661+
/// Attach the parameter name for get_displayname (`argument 'name'`).
662+
#[must_use]
663+
pub fn with_argument_name(self, name: &'static str) -> Self {
664+
match self {
665+
Self::BadArgument {
666+
expected,
667+
or_none,
668+
found,
669+
..
670+
} => Self::BadArgument {
671+
expected,
672+
or_none,
673+
found,
674+
name: Some(name),
675+
},
676+
other => other,
677+
}
678+
}
679+
680+
/// Mark `{expected}` as `X or None`.
681+
#[must_use]
682+
pub(crate) fn with_or_none(self) -> Self {
683+
match self {
684+
Self::BadArgument {
685+
expected,
686+
found,
687+
name,
688+
..
689+
} => Self::BadArgument {
690+
expected,
691+
or_none: true,
692+
found,
693+
name,
694+
},
695+
other => other,
696+
}
697+
}
698+
626699
fn into_exception(
627700
self,
628701
arity: &RangeInclusive<usize>,
629702
num_given: usize,
703+
pos: usize,
630704
callee: Callee,
631705
vm: &VirtualMachine,
632706
) -> PyBaseExceptionRef {
@@ -636,10 +710,19 @@ impl ArgumentError {
636710
Self::InvalidKeywordArgument(name) => callee.unexpected_keyword(&name, vm),
637711
Self::MissingRequiredArgument { name, pos } => callee.missing_argument(&name, pos, vm),
638712
Self::BadArgument {
639-
pos,
640713
expected,
714+
or_none,
641715
found,
642-
} => callee.bad_argument(pos, expected, &found, vm),
716+
name,
717+
} => {
718+
if callee.name.is_none() || (name.is_none() && pos == 0) {
719+
vm.new_downcast_type_error(expected, &found)
720+
} else {
721+
let meth_o = *arity.start() == 1 && *arity.end() == 1;
722+
let displayname = get_displayname(name, pos, meth_o);
723+
callee.bad_argument(&displayname, expected, or_none, &found, vm)
724+
}
725+
}
643726
Self::Exception(ex) => ex,
644727
}
645728
}
@@ -996,7 +1079,7 @@ where
9961079

9971080
fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result<Self, ArgumentError> {
9981081
let value = args.take_positional().ok_or(ArgumentError::TooFewArgs)?;
999-
Ok(value.try_into_value(vm)?)
1082+
T::try_from_argument(vm, value)
10001083
}
10011084
}
10021085

@@ -1059,7 +1142,7 @@ where
10591142

10601143
fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result<Self, ArgumentError> {
10611144
let r = if let Some(value) = args.take_positional() {
1062-
Self::Present(value.try_into_value(vm)?)
1145+
Self::Present(T::try_from_argument(vm, value)?)
10631146
} else {
10641147
Self::Missing
10651148
};

0 commit comments

Comments
 (0)