Skip to main content

pyo3_macros_backend/
params.rs

1use crate::utils::Ctx;
2use crate::{
3    attributes::FromPyWithAttribute,
4    method::{FnArg, FnSpec, RegularArg},
5    pyfunction::FunctionSignature,
6    quotes::some_wrap,
7};
8use proc_macro2::{Span, TokenStream};
9use quote::{format_ident, quote, quote_spanned};
10use syn::spanned::Spanned;
11
12pub struct Holders {
13    holders: Vec<syn::Ident>,
14}
15
16impl Holders {
17    pub fn new() -> Self {
18        Holders {
19            holders: Vec::new(),
20        }
21    }
22
23    pub fn push_holder(&mut self, span: Span) -> syn::Ident {
24        let holder = syn::Ident::new(&format!("holder_{}", self.holders.len()), span);
25        self.holders.push(holder.clone());
26        holder
27    }
28
29    pub fn init_holders(&self, ctx: &Ctx) -> TokenStream {
30        let Ctx { pyo3_path, .. } = ctx;
31        let holders = &self.holders;
32        quote! {
33            #[allow(clippy::let_unit_value, reason = "many holders are just `()`")]
34            #(let mut #holders = #pyo3_path::impl_::extract_argument::FunctionArgumentHolder::INIT;)*
35        }
36    }
37}
38
39/// Return true if the argument list is simply (*args, **kwds).
40pub fn is_forwarded_args(signature: &FunctionSignature<'_>) -> bool {
41    matches!(
42        signature.arguments.as_slice(),
43        [FnArg::VarArgs(..), FnArg::KwArgs(..),]
44    )
45}
46
47pub fn impl_arg_params(
48    spec: &FnSpec<'_>,
49    self_: Option<&syn::Type>,
50    fastcall: bool,
51    holders: &mut Holders,
52    ctx: &Ctx,
53) -> (TokenStream, Vec<TokenStream>) {
54    let args_array = syn::Ident::new("output", Span::call_site());
55    let Ctx { pyo3_path, .. } = ctx;
56
57    let from_py_with = spec
58        .signature
59        .arguments
60        .iter()
61        .enumerate()
62        .filter_map(|(i, arg)| {
63            let from_py_with = &arg.from_py_with()?.value;
64            let from_py_with_holder = format_ident!("from_py_with_{}", i);
65            Some(quote_spanned! { from_py_with.span() =>
66                let #from_py_with_holder = #from_py_with;
67            })
68        })
69        .collect::<TokenStream>();
70
71    if !fastcall && is_forwarded_args(&spec.signature) {
72        // In the varargs convention, we can just pass though if the signature
73        // is (*args, **kwds).
74        let arg_convert = spec
75            .signature
76            .arguments
77            .iter()
78            .enumerate()
79            .map(|(i, arg)| impl_arg_param(arg, i, &mut 0, holders, ctx))
80            .collect();
81        return (
82            quote! {
83                let _args = unsafe { #pyo3_path::impl_::extract_argument::cast_function_argument(py, _args) };
84                let _kwargs = unsafe { #pyo3_path::impl_::extract_argument::cast_optional_function_argument(py, _kwargs) };
85                #from_py_with
86            },
87            arg_convert,
88        );
89    };
90
91    let positional_parameter_names = &spec.signature.python_signature.positional_parameters;
92    let positional_only_parameters = &spec.signature.python_signature.positional_only_parameters;
93    let required_positional_parameters = spec
94        .signature
95        .python_signature
96        .required_positional_parameters();
97    let keyword_only_parameters = spec
98        .signature
99        .python_signature
100        .keyword_only_parameters
101        .iter()
102        .map(|(name, default_value)| {
103            let required = default_value.is_none();
104            quote! {
105                #pyo3_path::impl_::extract_argument::KeywordOnlyParameterDescription {
106                    name: #name,
107                    required: #required,
108                }
109            }
110        });
111
112    let num_params = positional_parameter_names.len() + keyword_only_parameters.len();
113
114    let mut option_pos = 0usize;
115    let param_conversion = spec
116        .signature
117        .arguments
118        .iter()
119        .enumerate()
120        .map(|(i, arg)| impl_arg_param(arg, i, &mut option_pos, holders, ctx))
121        .collect();
122
123    let args_handler = if spec.signature.python_signature.varargs.is_some() {
124        quote! { #pyo3_path::impl_::extract_argument::TupleVarargs }
125    } else {
126        quote! { #pyo3_path::impl_::extract_argument::NoVarargs }
127    };
128    let kwargs_handler = if spec.signature.python_signature.kwargs.is_some() {
129        quote! { #pyo3_path::impl_::extract_argument::DictVarkeywords }
130    } else {
131        quote! { #pyo3_path::impl_::extract_argument::NoVarkeywords }
132    };
133
134    let cls_name = if let Some(cls) = self_ {
135        quote! { ::std::option::Option::Some(<#cls as #pyo3_path::PyClass>::NAME) }
136    } else {
137        quote! { ::std::option::Option::None }
138    };
139    let python_name = &spec.python_name;
140
141    let extract_expression = if fastcall {
142        quote! {
143            DESCRIPTION.extract_arguments_fastcall::<#args_handler, #kwargs_handler>(
144                py,
145                _args,
146                _nargs,
147                _kwnames,
148                &mut #args_array
149            )?
150        }
151    } else {
152        quote! {
153            DESCRIPTION.extract_arguments_tuple_dict::<#args_handler, #kwargs_handler>(
154                py,
155                _args,
156                _kwargs,
157                &mut #args_array
158            )?
159        }
160    };
161
162    // create array of arguments, and then parse
163    (
164        quote! {
165                const DESCRIPTION: #pyo3_path::impl_::extract_argument::FunctionDescription = #pyo3_path::impl_::extract_argument::FunctionDescription {
166                    cls_name: #cls_name,
167                    func_name: stringify!(#python_name),
168                    positional_parameter_names: &[#(#positional_parameter_names),*],
169                    positional_only_parameters: #positional_only_parameters,
170                    required_positional_parameters: #required_positional_parameters,
171                    keyword_only_parameters: &[#(#keyword_only_parameters),*],
172                };
173                let mut #args_array = [::std::option::Option::None; #num_params];
174                let (_args, _kwargs) = #extract_expression;
175                #from_py_with
176        },
177        param_conversion,
178    )
179}
180
181fn impl_arg_param(
182    arg: &FnArg<'_>,
183    pos: usize,
184    option_pos: &mut usize,
185    holders: &mut Holders,
186    ctx: &Ctx,
187) -> TokenStream {
188    let Ctx { pyo3_path, .. } = ctx;
189    let args_array = syn::Ident::new("output", Span::call_site());
190
191    match arg {
192        FnArg::Regular(arg) => {
193            let from_py_with = format_ident!("from_py_with_{}", pos);
194            let arg_value = quote!(#args_array[#option_pos]);
195            *option_pos += 1;
196            impl_regular_arg_param(arg, from_py_with, arg_value, holders, ctx)
197        }
198        FnArg::VarArgs(arg) => {
199            let span = Span::call_site().located_at(arg.ty.span());
200            let holder = holders.push_holder(span);
201            let name_str = arg.name.to_string();
202            quote_spanned! { span =>
203                #pyo3_path::impl_::extract_argument::extract_argument(
204                    _args.as_any().as_borrowed(),
205                    &mut #holder,
206                    #name_str
207                )?
208            }
209        }
210        FnArg::KwArgs(arg) => {
211            let span = Span::call_site().located_at(arg.ty.span());
212            let holder = holders.push_holder(span);
213            let name_str = arg.name.to_string();
214            quote_spanned! { span =>
215                #pyo3_path::impl_::extract_argument::extract_argument_with_default(
216                    _kwargs.as_ref().map(|d| d.as_any().as_borrowed()),
217                    &mut #holder,
218                    #name_str,
219                    || ::std::option::Option::None
220                )?
221            }
222        }
223        FnArg::Py(..) => quote! { py },
224        FnArg::CancelHandle(..) => quote! { __cancel_handle },
225    }
226}
227
228/// Re option_pos: The option slice doesn't contain the py: Python argument, so the argument
229/// index and the index in option diverge when using py: Python
230pub(crate) fn impl_regular_arg_param(
231    arg: &RegularArg<'_>,
232    from_py_with: syn::Ident,
233    arg_value: TokenStream, // expected type: Option<&'a Bound<'py, PyAny>>
234    holders: &mut Holders,
235    ctx: &Ctx,
236) -> TokenStream {
237    let Ctx { pyo3_path, .. } = ctx;
238    let pyo3_path = pyo3_path.to_tokens_spanned(arg.ty.span());
239
240    // Use this macro inside this function, to ensure that all code generated here is associated
241    // with the function argument
242    let use_probe = quote! {
243        #[allow(unused_imports, reason = "`Probe` trait used on negative case only")]
244        use #pyo3_path::impl_::pyclass::Probe as _;
245    };
246    macro_rules! quote_arg_span {
247        ($($tokens:tt)*) => { quote_spanned!(arg.ty.span() => { #use_probe $($tokens)* }) }
248    }
249
250    let name_str = arg.name.to_string();
251    let mut default = arg.default_value.as_ref().map(|expr| quote!(#expr));
252
253    // Option<T> arguments have special treatment: the default should be specified _without_ the
254    // Some() wrapper. Maybe this should be changed in future?!
255    if arg.option_wrapped_type.is_some() {
256        default = default.map(|tokens| some_wrap(tokens, ctx));
257    }
258
259    if let Some(FromPyWithAttribute { kw, .. }) = arg.from_py_with {
260        let extractor = quote_spanned! { kw.span =>
261            { let from_py_with: fn(_) -> _ = #from_py_with; from_py_with }
262        };
263        if let Some(default) = default {
264            quote_arg_span! {
265                #pyo3_path::impl_::extract_argument::from_py_with_with_default(
266                    #arg_value.as_deref(),
267                    #name_str,
268                    #extractor,
269                    #[allow(clippy::redundant_closure, reason = "wrapping user-provided default expression")]
270                    {
271                        || #default
272                    }
273                )?
274            }
275        } else {
276            let unwrap = quote! {unsafe { #pyo3_path::impl_::extract_argument::unwrap_required_argument_bound(#arg_value.as_deref()) }};
277            quote_arg_span! {
278                #pyo3_path::impl_::extract_argument::from_py_with(
279                    #unwrap,
280                    #name_str,
281                    #extractor,
282                )?
283            }
284        }
285    } else if let Some(default) = default {
286        let holder = holders.push_holder(arg.name.span());
287        quote_arg_span! {
288            #pyo3_path::impl_::extract_argument::extract_argument_with_default(
289                #arg_value,
290                &mut #holder,
291                #name_str,
292                #[allow(clippy::redundant_closure, reason = "wrapping user-provided default expression")]
293                {
294                    || #default
295                }
296            )?
297        }
298    } else {
299        let holder = holders.push_holder(arg.name.span());
300        let unwrap = quote! {unsafe { #pyo3_path::impl_::extract_argument::unwrap_required_argument(#arg_value) }};
301        quote_arg_span! {
302            #pyo3_path::impl_::extract_argument::extract_argument(
303                #unwrap,
304                &mut #holder,
305                #name_str
306            )?
307        }
308    }
309}