Skip to content

Commit 9dccad3

Browse files
mejrsdavidhewitt
authored andcommitted
Emit a better error for bad argument names
1 parent 24d2ddd commit 9dccad3

File tree

3 files changed

+36
-5
lines changed

3 files changed

+36
-5
lines changed

pyo3-macros-backend/src/method.rs

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,14 +40,14 @@ impl<'a> FnArg<'a> {
4040
}
4141

4242
let arg_attrs = PyFunctionArgPyO3Attributes::from_attrs(&mut cap.attrs)?;
43-
let (ident, by_ref, mutability) = match *cap.pat {
43+
let (ident, by_ref, mutability) = match &*cap.pat {
4444
syn::Pat::Ident(syn::PatIdent {
45-
ref ident,
46-
ref by_ref,
47-
ref mutability,
45+
ident,
46+
by_ref,
47+
mutability,
4848
..
4949
}) => (ident, by_ref, mutability),
50-
_ => bail_spanned!(cap.pat.span() => "unsupported argument"),
50+
other => return Err(handle_argument_error(other)),
5151
};
5252

5353
Ok(FnArg {
@@ -67,6 +67,19 @@ impl<'a> FnArg<'a> {
6767
}
6868
}
6969

70+
fn handle_argument_error(pat: &syn::Pat) -> syn::Error {
71+
let span = pat.span();
72+
let msg = match pat {
73+
syn::Pat::Wild(_) => "wildcard argument names are not supported",
74+
syn::Pat::Struct(_)
75+
| syn::Pat::Tuple(_)
76+
| syn::Pat::TupleStruct(_)
77+
| syn::Pat::Slice(_) => "destructuring in arguments is not supported",
78+
_ => "unsupported argument",
79+
};
80+
syn::Error::new(span, msg)
81+
}
82+
7083
#[derive(Clone, PartialEq, Debug, Copy, Eq)]
7184
pub enum MethodTypeAttribute {
7285
/// `#[new]`

tests/ui/invalid_pyfunctions.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,10 @@ fn impl_trait_function(impl_trait: impl AsRef<PyAny>) {}
99
#[pyfunction]
1010
async fn async_function() {}
1111

12+
#[pyfunction]
13+
fn wildcard_argument(_: i32) {}
14+
15+
#[pyfunction]
16+
fn destructured_argument((a, b): (i32, i32)) {}
17+
1218
fn main() {}

tests/ui/invalid_pyfunctions.stderr

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,15 @@ error: `async fn` is not yet supported for Python functions.
1717
|
1818
10 | async fn async_function() {}
1919
| ^^^^^
20+
21+
error: wildcard argument names are not supported
22+
--> tests/ui/invalid_pyfunctions.rs:13:22
23+
|
24+
13 | fn wildcard_argument(_: i32) {}
25+
| ^
26+
27+
error: destructuring in arguments is not supported
28+
--> tests/ui/invalid_pyfunctions.rs:16:26
29+
|
30+
16 | fn destructured_argument((a, b): (i32, i32)) {}
31+
| ^^^^^^

0 commit comments

Comments
 (0)