Skip to content

Commit 599705b

Browse files
committed
Convert first where CPython does, and name date()
mmap() is parsed by PyArg_ParseTupleAndKeywords, which converts the arguments it was given before it reports a missing one, so mmap.mmap(x) raises whatever x.__index__ raises. Reporting the missing length first broke that. Add FromArgs::CONVERTS_BEFORE_MISSING, set by #[pyarg(convert_before_missing)] on the struct, skip the early check for it, and mark both MmapNewArgs. date and datetime moved to Argument Clinic in 3.15, so they now report the missing argument first, but bound with no name and said "function missing required argument". Bind them for "date" and "datetime". Assisted-by: Claude Code:claude-opus-5-5
1 parent 712cbd2 commit 599705b

6 files changed

Lines changed: 55 additions & 2 deletions

File tree

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

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -618,13 +618,31 @@ pub(crate) fn impl_from_args(input: DeriveInput) -> Result<TokenStream> {
618618
params.push(param_token(field, &ArgAttribute::try_from(field)?)?);
619619
}
620620

621+
let mut converts_before_missing = false;
622+
for attr in input
623+
.attrs
624+
.iter()
625+
.filter(|attr| attr.path().is_ident("pyarg"))
626+
{
627+
attr.parse_nested_meta(|meta| {
628+
if meta.path.is_ident("convert_before_missing") {
629+
converts_before_missing = true;
630+
Ok(())
631+
} else {
632+
Err(meta.error("Unrecognized struct-level pyarg attribute"))
633+
}
634+
})?;
635+
}
636+
621637
let name = input.ident;
622638
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
623639
let output = quote! {
624640
impl #impl_generics ::rustpython_vm::function::FromArgs for #name #ty_generics #where_clause {
625641
const PARAMS: Option<&'static [::rustpython_vm::function::Param]> =
626642
Some(&[#(#params),*]);
627643

644+
const CONVERTS_BEFORE_MISSING: bool = #converts_before_missing;
645+
628646
fn arity() -> ::std::ops::RangeInclusive<usize> {
629647
#min_arity..=#max_arity #(
630648
.saturating_add(*<#flattened as ::rustpython_vm::function::FromArgs>::arity().end())

‎crates/derive/src/lib.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,11 @@ use syn::punctuated::Punctuated;
4040
/// when a missing argument is a distinct state, or give the default's type a
4141
/// real `py_default()`.
4242
/// - `error_msg = "..."`: type-error text when conversion fails.
43+
///
44+
/// `#[pyarg(convert_before_missing)]` on the struct converts the given arguments
45+
/// before reporting a missing one, as CPython's `PyArg_ParseTupleAndKeywords`
46+
/// does. Without it a missing argument is reported first, as Argument Clinic does.
47+
///
4348
/// # Signature default
4449
/// An explicit `py_default` is used as written. Otherwise:
4550
/// - a literal, a negative literal, or the path `None` becomes a typed default

‎crates/stdlib/src/_datetime.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1742,7 +1742,7 @@ mod _datetime {
17421742
{
17431743
return Ok(Self::from_state(&state));
17441744
}
1745-
let DateArgs { year, month, day } = args.bind(vm)?;
1745+
let DateArgs { year, month, day } = args.bind_for(vm, "date")?;
17461746
check_date_args(year, month, day, vm)?;
17471747
Ok(Self::new(year, month, day))
17481748
}
@@ -3613,7 +3613,7 @@ mod _datetime {
36133613
i32::from(fold),
36143614
));
36153615
}
3616-
let a: DateTimeArgs = args.bind(vm)?;
3616+
let a: DateTimeArgs = args.bind_for(vm, "datetime")?;
36173617
let tzinfo = a.tzinfo.into_option().and_then(|tz| tzinfo_arg(tz, vm));
36183618
check_date_args(a.year, a.month, a.day, vm)?;
36193619
check_time_args(a.hour, a.minute, a.second, a.microsecond, a.fold, vm)?;

‎crates/stdlib/src/mmap.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,7 @@ mod mmap {
248248

249249
#[cfg(unix)]
250250
#[derive(FromArgs)]
251+
#[pyarg(convert_before_missing)]
251252
struct MmapNewArgs {
252253
#[pyarg(any)]
253254
fileno: i32,
@@ -267,6 +268,7 @@ mod mmap {
267268

268269
#[cfg(windows)]
269270
#[derive(FromArgs)]
271+
#[pyarg(convert_before_missing)]
270272
struct MmapNewArgs {
271273
#[pyarg(any)]
272274
fileno: i32,

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,7 @@ impl FuncArgs {
325325
// A missing required argument is reported before the arguments ahead
326326
// of it are converted, for the same reason.
327327
if num_given < *arity.start()
328+
&& !T::CONVERTS_BEFORE_MISSING
328329
&& let Some(params) = T::PARAMS
329330
&& let Some(missing) = missing_positional(params, num_given, &self.kwargs)
330331
{
@@ -649,6 +650,10 @@ pub trait FromArgs: Sized {
649650
/// is ignored.
650651
const PARAMS: Option<&'static [Param]> = None;
651652

653+
/// CPython parses the function with `PyArg_ParseTupleAndKeywords`, which
654+
/// converts the arguments it was given before it reports a missing one.
655+
const CONVERTS_BEFORE_MISSING: bool = false;
656+
652657
/// Extracts this item from the next argument(s).
653658
fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result<Self, ArgumentError>;
654659
}

‎extra_tests/snippets/vm_argument_errors.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@
55
import array
66
import collections
77
import csv
8+
import datetime
89
import itertools
10+
import mmap
911
import operator
1012
import typing
1113
import weakref
@@ -168,6 +170,10 @@ def __index__(self):
168170

169171

170172
def test_a_missing_argument_is_reported_before_any_is_converted():
173+
class FailingIndex:
174+
def __index__(self):
175+
raise RuntimeError
176+
171177
check(
172178
TypeError,
173179
"compress() missing required argument 'selectors' (pos 2)",
@@ -187,6 +193,22 @@ def test_a_missing_argument_is_reported_before_any_is_converted():
187193
TestFailingIter(),
188194
sel=1,
189195
)
196+
check(
197+
TypeError,
198+
"date() missing required argument 'month' (pos 2)",
199+
datetime.date,
200+
FailingIndex(),
201+
)
202+
203+
204+
def test_mmap_converts_before_reporting_a_missing_argument():
205+
# CPython parses mmap() with PyArg_ParseTupleAndKeywords, not Argument Clinic.
206+
class FailingIndex:
207+
def __index__(self):
208+
raise RuntimeError
209+
210+
with assert_raises(RuntimeError):
211+
mmap.mmap(FailingIndex())
190212

191213

192214
test_the_message_names_the_function()
@@ -199,3 +221,4 @@ def test_a_missing_argument_is_reported_before_any_is_converted():
199221
test_a_keyword_check_of_its_own_says_the_same_thing()
200222
test_too_many_arguments_are_counted_before_any_is_converted()
201223
test_a_missing_argument_is_reported_before_any_is_converted()
224+
test_mmap_converts_before_reporting_a_missing_argument()

0 commit comments

Comments
 (0)