Skip to content

Commit 7aa7e93

Browse files
committed
Bind every argument list the Argument Clinic way; parse legacy callers with ArgSpec
Remove FromArgs::CONVERTS_BEFORE_MISSING and #[pyarg(convert_before_missing)]. The missing-argument check in FuncArgs::bind_for is now FromArgs::missing_from. A binding with no PARAMS and arity 1..=1 counts as one required positional-only parameter, and tuple bindings walk their components, so math.comb(x) and list.insert(x) report "expected 2 arguments, got 1" before converting x. A method's instance argument is skipped without advancing the position. A required keyword-only parameter missing from the keywords is reported before any conversion. FromArgs::HAS_REQUIRED_KEYWORD_ONLY is computed from PARAMS at compile time, so a call that gives every required positional argument walks nothing unless the type has such a parameter. Make ArgSpec public and parse with it, converting each argument in kwlist order, the callables that 3.15.2 parses with PyArg_ParseTupleAndKeywords or _PyArg_ParseStackAndKeywords and whose earlier required arguments can fail to convert: mmap.mmap, _functools._lru_cache_wrapper, _json.make_encoder, _posixshmem.shm_open, and _winapi CreateEventW, CreateMutexW, OpenEventW, OpenMutexW, LCMapStringEx, ReadFile, WriteFile, CopyFile2. The pyfunctions take FuncArgs and carry their text signature in the Rust docstring. has_signature returns false for a bare FuncArgs argument, and a non-empty Rust docstring of such a function is used as written. Assisted-by: Claude Code:claude-opus-5-5 Assisted-by: Grok CLI:grok-4.7
1 parent 3cf7269 commit 7aa7e93

13 files changed

Lines changed: 767 additions & 201 deletions

File tree

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

Lines changed: 4 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -629,32 +629,17 @@ pub(crate) fn impl_from_args(input: DeriveInput) -> Result<TokenStream> {
629629
params.push(param_token(field, &ArgAttribute::try_from(field)?)?);
630630
}
631631

632-
let mut converts_before_missing = false;
633-
for attr in input
634-
.attrs
635-
.iter()
636-
.filter(|attr| attr.path().is_ident("pyarg"))
637-
{
638-
attr.parse_nested_meta(|meta| {
639-
if meta.path.is_ident("convert_before_missing") {
640-
converts_before_missing = true;
641-
Ok(())
642-
} else {
643-
Err(meta.error("Unrecognized struct-level pyarg attribute"))
644-
}
645-
})?;
646-
}
647-
648632
let name = input.ident;
649633
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
650634
let output = quote! {
651635
impl #impl_generics ::rustpython_vm::function::FromArgs for #name #ty_generics #where_clause {
652636
const PARAMS: Option<&'static [::rustpython_vm::function::Param]> =
653637
Some(&[#(#params),*]);
654638

655-
const CONVERTS_BEFORE_MISSING: bool = #converts_before_missing #(
656-
|| <#flattened as ::rustpython_vm::function::FromArgs>::CONVERTS_BEFORE_MISSING
657-
)*;
639+
const HAS_REQUIRED_KEYWORD_ONLY: bool =
640+
::rustpython_vm::function::params_have_required_keyword_only(Self::PARAMS) #(
641+
|| <#flattened as ::rustpython_vm::function::FromArgs>::HAS_REQUIRED_KEYWORD_ONLY
642+
)*;
658643

659644
fn arity() -> ::std::ops::RangeInclusive<usize> {
660645
let min = #min_arity;

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

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -906,17 +906,20 @@ pub(crate) fn internal_doc_tokens(
906906
{
907907
#args_const
908908
const BASE: ::rustpython_vm::function::ItemDoc = #doc;
909-
if !::rustpython_vm::function::has_signature(ARGS) {
910-
if BASE.len == 0 {
911-
match BASE.text {
912-
Some(text) if !text.is_empty() => {
913-
::rustpython_vm::function::ItemDoc::static_text(text)
914-
}
915-
_ => ::rustpython_vm::function::ItemDoc::NONE,
916-
}
917-
} else {
918-
BASE
909+
// A rust docstring is used as written when ARGS is not a signature
910+
// (`FuncArgs`, or a nameless type with no PARAMS). Database bodies
911+
// and items with no rust docstring still get a generated prefix.
912+
if !::rustpython_vm::function::has_signature(ARGS)
913+
&& BASE.len == 0
914+
&& match BASE.text {
915+
Some(text) => !text.is_empty(),
916+
None => false,
919917
}
918+
{
919+
::rustpython_vm::function::ItemDoc::static_text(match BASE.text {
920+
Some(text) => text,
921+
None => "",
922+
})
920923
} else if BASE.len != 0 {
921924
const N: usize = ::rustpython_vm::function::signature_prefix_len(#py_name, ARGS);
922925
const B: [u8; N] =

‎crates/derive/src/lib.rs‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,10 +45,6 @@ use syn::punctuated::Punctuated;
4545
/// real `py_default()`.
4646
/// - `error_msg = "..."`: type-error text when conversion fails.
4747
///
48-
/// `#[pyarg(convert_before_missing)]` on the struct converts the given arguments
49-
/// before reporting a missing one, as CPython's `PyArg_ParseTupleAndKeywords`
50-
/// does. Without it a missing argument is reported first, as Argument Clinic does.
51-
///
5248
/// # Signature default
5349
/// An explicit `py_default` is used as written. Otherwise:
5450
/// - a literal, a negative literal, or the path `None` becomes a typed default

‎crates/stdlib/src/json.rs‎

Lines changed: 63 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@ mod _json {
66
AsObject, Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine,
77
builtins::{
88
PyAnyDict, PyBaseExceptionRef, PyDict, PyDictRef, PyFloat, PyInt, PyList, PyListRef,
9-
PyStr, PyStrRef, PyTuple, PyType,
9+
PyStr, PyStrRef, PyTuple, PyType, PyTypeRef,
1010
},
11-
convert::ToPyResult,
12-
function::{ArgIntoBool, IntoFuncArgs},
11+
convert::{ToPyResult, TryFromObject},
12+
function::{ArgIntoBool, ArgSpec, FuncArgs, IntoFuncArgs},
1313
protocol::PyIterReturn,
1414
types::{Callable, Constructor},
1515
};
@@ -831,6 +831,66 @@ mod _json {
831831
impl Constructor for JsonEncoder {
832832
type Args = EncoderArgs;
833833

834+
fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
835+
let mut markers = None;
836+
let mut default = None;
837+
let mut encoder = None;
838+
let mut indent = None;
839+
let mut key_separator = None;
840+
let mut item_separator = None;
841+
let mut sort_keys = None;
842+
let mut skipkeys = None;
843+
let mut allow_nan = None;
844+
ArgSpec {
845+
fname: "make_encoder",
846+
keywords: &[
847+
"markers",
848+
"default",
849+
"encoder",
850+
"indent",
851+
"key_separator",
852+
"item_separator",
853+
"sort_keys",
854+
"skipkeys",
855+
"allow_nan",
856+
],
857+
required: 9,
858+
max_positional: 9,
859+
}
860+
.parse_with(
861+
&args,
862+
|i, obj, vm| {
863+
match i {
864+
0 => markers = Some(PyObjectRef::try_from_object(vm, obj.to_owned())?),
865+
1 => default = Some(PyObjectRef::try_from_object(vm, obj.to_owned())?),
866+
2 => encoder = Some(PyObjectRef::try_from_object(vm, obj.to_owned())?),
867+
3 => indent = Some(PyObjectRef::try_from_object(vm, obj.to_owned())?),
868+
4 => key_separator = Some(PyStrRef::try_from_object(vm, obj.to_owned())?),
869+
5 => item_separator = Some(PyStrRef::try_from_object(vm, obj.to_owned())?),
870+
6 => sort_keys = Some(ArgIntoBool::try_from_object(vm, obj.to_owned())?),
871+
7 => skipkeys = Some(ArgIntoBool::try_from_object(vm, obj.to_owned())?),
872+
8 => allow_nan = Some(ArgIntoBool::try_from_object(vm, obj.to_owned())?),
873+
_ => unreachable!(),
874+
}
875+
Ok(())
876+
},
877+
vm,
878+
)?;
879+
let args = EncoderArgs {
880+
markers: markers.unwrap(),
881+
default: default.unwrap(),
882+
encoder: encoder.unwrap(),
883+
indent: indent.unwrap(),
884+
key_separator: key_separator.unwrap(),
885+
item_separator: item_separator.unwrap(),
886+
sort_keys: sort_keys.unwrap(),
887+
skipkeys: skipkeys.unwrap(),
888+
allow_nan: allow_nan.unwrap(),
889+
};
890+
let payload = Self::py_new(&cls, args, vm)?;
891+
payload.into_ref_with_type(vm, cls).map(Into::into)
892+
}
893+
834894
fn py_new(
835895
_cls: &Py<PyType>,
836896
EncoderArgs {

‎crates/stdlib/src/mmap.rs‎

Lines changed: 96 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ mod mmap {
1313
TryFromBorrowedObject, VirtualMachine, atomic_func,
1414
builtins::{PyBytes, PyBytesRef, PyInt, PyIntRef, PyType, PyTypeRef, PyUtf8StrRef},
1515
byte::{bytes_from_object, value_from_object},
16-
convert::ToPyException,
17-
function::{ArgBytesLike, ArgIndex, ArgIntoBool},
16+
convert::{ToPyException, TryFromObject},
17+
function::{ArgBytesLike, ArgIndex, ArgIntoBool, ArgSpec, FuncArgs},
1818
protocol::{
1919
BufferDescriptor, BufferMethods, PyBuffer, PyMappingMethods, PySequenceMethods,
2020
},
@@ -248,7 +248,6 @@ mod mmap {
248248

249249
#[cfg(unix)]
250250
#[derive(FromArgs)]
251-
#[pyarg(convert_before_missing)]
252251
struct MmapNewArgs {
253252
#[pyarg(any)]
254253
fileno: i32,
@@ -268,7 +267,6 @@ mod mmap {
268267

269268
#[cfg(windows)]
270269
#[derive(FromArgs)]
271-
#[pyarg(convert_before_missing)]
272270
struct MmapNewArgs {
273271
#[pyarg(any)]
274272
fileno: i32,
@@ -295,6 +293,94 @@ mod mmap {
295293
}
296294
Ok(self.length as usize)
297295
}
296+
297+
#[cfg(unix)]
298+
fn from_func_args(args: FuncArgs, vm: &VirtualMachine) -> PyResult<Self> {
299+
let mut fileno = None;
300+
let mut length = None;
301+
let mut flags = None;
302+
let mut prot = None;
303+
let mut access = None;
304+
let mut offset = None;
305+
let mut trackfd = None;
306+
ArgSpec {
307+
fname: "mmap",
308+
keywords: &[
309+
"fileno", "length", "flags", "prot", "access", "offset", "trackfd",
310+
],
311+
required: 2,
312+
max_positional: 6,
313+
}
314+
.parse_with(
315+
&args,
316+
|i, obj, vm| {
317+
match i {
318+
0 => fileno = Some(i32::try_from_object(vm, obj.to_owned())?),
319+
1 => length = Some(isize::try_from_object(vm, obj.to_owned())?),
320+
2 => flags = Some(core::ffi::c_int::try_from_object(vm, obj.to_owned())?),
321+
3 => prot = Some(core::ffi::c_int::try_from_object(vm, obj.to_owned())?),
322+
4 => access = Some(AccessArg::try_from_object(vm, obj.to_owned())?),
323+
5 => offset = Some(i64::try_from_object(vm, obj.to_owned())?),
324+
6 => trackfd = Some(ArgIntoBool::try_from_object(vm, obj.to_owned())?),
325+
_ => unreachable!(),
326+
}
327+
Ok(())
328+
},
329+
vm,
330+
)?;
331+
Ok(Self {
332+
fileno: fileno.unwrap(),
333+
length: length.unwrap(),
334+
flags: flags.unwrap_or(host_mmap::MAP_SHARED),
335+
prot: prot.unwrap_or(host_mmap::PROT_WRITE | host_mmap::PROT_READ),
336+
access: access.unwrap_or(AccessArg::DEFAULT),
337+
offset: offset.unwrap_or_default(),
338+
trackfd: trackfd.unwrap_or(ArgIntoBool::TRUE),
339+
})
340+
}
341+
342+
#[cfg(windows)]
343+
fn from_func_args(args: FuncArgs, vm: &VirtualMachine) -> PyResult<Self> {
344+
let mut fileno = None;
345+
let mut length = None;
346+
let mut tagname = None;
347+
let mut access = None;
348+
let mut offset = None;
349+
let mut trackfd = None;
350+
ArgSpec {
351+
fname: "mmap",
352+
keywords: &["fileno", "length", "tagname", "access", "offset", "trackfd"],
353+
required: 2,
354+
max_positional: 5,
355+
}
356+
.parse_with(
357+
&args,
358+
|i, obj, vm| {
359+
match i {
360+
0 => fileno = Some(i32::try_from_object(vm, obj.to_owned())?),
361+
1 => length = Some(isize::try_from_object(vm, obj.to_owned())?),
362+
2 => {
363+
tagname =
364+
Some(Option::<PyObjectRef>::try_from_object(vm, obj.to_owned())?)
365+
}
366+
3 => access = Some(AccessArg::try_from_object(vm, obj.to_owned())?),
367+
4 => offset = Some(i64::try_from_object(vm, obj.to_owned())?),
368+
5 => trackfd = Some(ArgIntoBool::try_from_object(vm, obj.to_owned())?),
369+
_ => unreachable!(),
370+
}
371+
Ok(())
372+
},
373+
vm,
374+
)?;
375+
Ok(Self {
376+
fileno: fileno.unwrap(),
377+
length: length.unwrap(),
378+
tagname: tagname.unwrap_or(None),
379+
access: access.unwrap_or(AccessArg::DEFAULT),
380+
offset: offset.unwrap_or_default(),
381+
trackfd: trackfd.unwrap_or(ArgIntoBool::TRUE),
382+
})
383+
}
298384
}
299385

300386
#[derive(FromArgs)]
@@ -410,6 +496,12 @@ mod mmap {
410496
impl Constructor for PyMmap {
411497
type Args = MmapNewArgs;
412498

499+
fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
500+
let args = MmapNewArgs::from_func_args(args, vm)?;
501+
let payload = Self::py_new(&cls, args, vm)?;
502+
payload.into_ref_with_type(vm, cls).map(Into::into)
503+
}
504+
413505
#[cfg(unix)]
414506
fn py_new(_cls: &Py<PyType>, args: Self::Args, vm: &VirtualMachine) -> PyResult<Self> {
415507
use host_mmap::{MAP_PRIVATE, MAP_SHARED, PROT_READ, PROT_WRITE};

‎crates/stdlib/src/posixshmem.rs‎

Lines changed: 36 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,25 +7,46 @@ mod _posixshmem {
77
use alloc::ffi::CString;
88

99
use crate::vm::{
10-
FromArgs, PyResult, VirtualMachine, builtins::PyUtf8StrRef, convert::IntoPyException,
10+
PyResult, VirtualMachine,
11+
builtins::PyUtf8StrRef,
12+
convert::{IntoPyException, TryFromObject},
13+
function::{ArgSpec, FuncArgs},
1114
};
1215
use rustpython_host_env::shm;
1316

14-
#[derive(FromArgs)]
15-
struct ShmOpenArgs {
16-
#[pyarg(any)]
17-
path: PyUtf8StrRef,
18-
#[pyarg(any)]
19-
flags: core::ffi::c_int,
20-
#[pyarg(any, default = 0o777)]
21-
mode: shm::mode_t,
22-
}
23-
17+
/// shm_open($module, /, path, flags, mode=511)
18+
/// --
19+
///
20+
/// Open a shared memory object. Returns a file descriptor (integer).
2421
#[pyfunction]
25-
fn shm_open(args: ShmOpenArgs, vm: &VirtualMachine) -> PyResult<core::ffi::c_int> {
26-
let name = CString::new(args.path.as_str()).map_err(|e| e.into_pyexception(vm))?;
27-
let mode: core::ffi::c_uint = args.mode as _;
28-
shm::shm_open(name.as_c_str(), args.flags, mode).map_err(|e| e.into_pyexception(vm))
22+
fn shm_open(args: FuncArgs, vm: &VirtualMachine) -> PyResult<core::ffi::c_int> {
23+
let mut path = None;
24+
let mut flags = None;
25+
let mut mode: shm::mode_t = 0o777;
26+
ArgSpec {
27+
fname: "shm_open",
28+
keywords: &["path", "flags", "mode"],
29+
required: 2,
30+
max_positional: 3,
31+
}
32+
.parse_with(
33+
&args,
34+
|i, obj, vm| {
35+
match i {
36+
0 => path = Some(PyUtf8StrRef::try_from_object(vm, obj.to_owned())?),
37+
1 => flags = Some(core::ffi::c_int::try_from_object(vm, obj.to_owned())?),
38+
2 => mode = shm::mode_t::try_from_object(vm, obj.to_owned())?,
39+
_ => unreachable!(),
40+
}
41+
Ok(())
42+
},
43+
vm,
44+
)?;
45+
let path = path.unwrap();
46+
let flags = flags.unwrap();
47+
let name = CString::new(path.as_str()).map_err(|e| e.into_pyexception(vm))?;
48+
let mode: core::ffi::c_uint = mode as _;
49+
shm::shm_open(name.as_c_str(), flags, mode).map_err(|e| e.into_pyexception(vm))
2950
}
3051

3152
#[pyfunction]

0 commit comments

Comments
 (0)