1use std::collections::HashSet;
2
3use crate::combine_errors::CombineErrors;
4#[cfg(feature = "experimental-inspect")]
5use crate::introspection::{attribute_introspection_code, function_introspection_code};
6#[cfg(feature = "experimental-inspect")]
7use crate::method::{FnSpec, FnType};
8#[cfg(feature = "experimental-inspect")]
9use crate::utils::expr_to_python;
10use crate::utils::{has_attribute, has_attribute_with_namespace, Ctx, PyO3CratePath};
11use crate::{
12 attributes::{take_pyo3_options, CrateAttribute},
13 konst::{ConstAttributes, ConstSpec},
14 pyfunction::PyFunctionOptions,
15 pymethod::{
16 self, is_proto_method, GeneratedPyMethod, MethodAndMethodDef, MethodAndSlotDef, PyMethod,
17 },
18};
19use proc_macro2::TokenStream;
20use quote::{format_ident, quote};
21#[cfg(feature = "experimental-inspect")]
22use syn::Ident;
23use syn::{
24 parse::{Parse, ParseStream},
25 spanned::Spanned,
26 ImplItemFn, Result,
27};
28
29#[derive(Copy, Clone)]
31pub enum PyClassMethodsType {
32 Specialization,
33 Inventory,
34}
35
36enum PyImplPyO3Option {
37 Crate(CrateAttribute),
38}
39
40impl Parse for PyImplPyO3Option {
41 fn parse(input: ParseStream<'_>) -> Result<Self> {
42 let lookahead = input.lookahead1();
43 if lookahead.peek(syn::Token![crate]) {
44 input.parse().map(PyImplPyO3Option::Crate)
45 } else {
46 Err(lookahead.error())
47 }
48 }
49}
50
51#[derive(Default)]
52pub struct PyImplOptions {
53 krate: Option<CrateAttribute>,
54}
55
56impl PyImplOptions {
57 pub fn from_attrs(attrs: &mut Vec<syn::Attribute>) -> Result<Self> {
58 let mut options: PyImplOptions = Default::default();
59
60 for option in take_pyo3_options(attrs)? {
61 match option {
62 PyImplPyO3Option::Crate(path) => options.set_crate(path)?,
63 }
64 }
65
66 Ok(options)
67 }
68
69 fn set_crate(&mut self, path: CrateAttribute) -> Result<()> {
70 ensure_spanned!(
71 self.krate.is_none(),
72 path.span() => "`crate` may only be specified once"
73 );
74
75 self.krate = Some(path);
76 Ok(())
77 }
78}
79
80pub fn build_py_methods(
81 ast: &mut syn::ItemImpl,
82 methods_type: PyClassMethodsType,
83) -> syn::Result<TokenStream> {
84 if let Some((_, path, _)) = &ast.trait_ {
85 bail_spanned!(path.span() => "#[pymethods] cannot be used on trait impl blocks");
86 } else if ast.generics != Default::default() {
87 bail_spanned!(
88 ast.generics.span() =>
89 "#[pymethods] cannot be used with lifetime parameters or generics"
90 );
91 } else {
92 let options = PyImplOptions::from_attrs(&mut ast.attrs)?;
93 impl_methods(&ast.self_ty, &mut ast.items, methods_type, options)
94 }
95}
96
97fn check_pyfunction(pyo3_path: &PyO3CratePath, meth: &mut ImplItemFn) -> syn::Result<()> {
98 let mut error = None;
99
100 meth.attrs.retain(|attr| {
101 let attrs = [attr.clone()];
102
103 if has_attribute(&attrs, "pyfunction")
104 || has_attribute_with_namespace(&attrs, Some(pyo3_path), &["pyfunction"])
105 || has_attribute_with_namespace(&attrs, Some(pyo3_path), &["prelude", "pyfunction"]) {
106 error = Some(err_spanned!(meth.sig.span() => "functions inside #[pymethods] do not need to be annotated with #[pyfunction]"));
107 false
108 } else {
109 true
110 }
111 });
112
113 error.map_or(Ok(()), Err)
114}
115
116pub fn impl_methods(
117 ty: &syn::Type,
118 impls: &mut [syn::ImplItem],
119 methods_type: PyClassMethodsType,
120 options: PyImplOptions,
121) -> syn::Result<TokenStream> {
122 let mut extra_fragments = Vec::new();
123 let mut proto_impls = Vec::new();
124 let mut methods = Vec::new();
125 let mut associated_methods = Vec::new();
126
127 let mut implemented_proto_fragments = HashSet::new();
128
129 let _: Vec<()> = impls
130 .iter_mut()
131 .map(|iimpl| {
132 match iimpl {
133 syn::ImplItem::Fn(meth) => {
134 let ctx = &Ctx::new(&options.krate, Some(&meth.sig));
135 let mut fun_options = PyFunctionOptions::from_attrs(&mut meth.attrs)?;
136 fun_options.krate = fun_options.krate.or_else(|| options.krate.clone());
137
138 check_pyfunction(&ctx.pyo3_path, meth)?;
139 let method = PyMethod::parse(&mut meth.sig, &mut meth.attrs, fun_options)?;
140 #[cfg(feature = "experimental-inspect")]
141 extra_fragments.push(method_introspection_code(&method.spec, ty, ctx));
142 match pymethod::gen_py_method(ty, method, &meth.attrs, ctx)? {
143 GeneratedPyMethod::Method(MethodAndMethodDef {
144 associated_method,
145 method_def,
146 }) => {
147 let attrs = get_cfg_attributes(&meth.attrs);
148 associated_methods.push(quote!(#(#attrs)* #associated_method));
149 methods.push(quote!(#(#attrs)* #method_def));
150 }
151 GeneratedPyMethod::SlotTraitImpl(method_name, token_stream) => {
152 implemented_proto_fragments.insert(method_name);
153 let attrs = get_cfg_attributes(&meth.attrs);
154 extra_fragments.push(quote!(#(#attrs)* #token_stream));
155 }
156 GeneratedPyMethod::Proto(MethodAndSlotDef {
157 associated_method,
158 slot_def,
159 }) => {
160 let attrs = get_cfg_attributes(&meth.attrs);
161 proto_impls.push(quote!(#(#attrs)* #slot_def));
162 associated_methods.push(quote!(#(#attrs)* #associated_method));
163 }
164 }
165 }
166 syn::ImplItem::Const(konst) => {
167 let ctx = &Ctx::new(&options.krate, None);
168 let attributes = ConstAttributes::from_attrs(&mut konst.attrs)?;
169 if attributes.is_class_attr {
170 let spec = ConstSpec {
171 rust_ident: konst.ident.clone(),
172 attributes,
173 };
174 let attrs = get_cfg_attributes(&konst.attrs);
175 let MethodAndMethodDef {
176 associated_method,
177 method_def,
178 } = gen_py_const(ty, &spec, ctx);
179 methods.push(quote!(#(#attrs)* #method_def));
180 associated_methods.push(quote!(#(#attrs)* #associated_method));
181 if is_proto_method(&spec.python_name().to_string()) {
182 konst
185 .attrs
186 .push(syn::parse_quote!(#[allow(non_upper_case_globals)]));
187 }
188 #[cfg(feature = "experimental-inspect")]
189 extra_fragments.push(attribute_introspection_code(
190 &ctx.pyo3_path,
191 Some(ty),
192 spec.python_name().to_string(),
193 expr_to_python(&konst.expr),
194 konst.ty.clone(),
195 true,
196 ));
197 }
198 }
199 syn::ImplItem::Macro(m) => bail_spanned!(
200 m.span() =>
201 "macros cannot be used as items in `#[pymethods]` impl blocks\n\
202 = note: this was previously accepted and ignored"
203 ),
204 _ => {}
205 }
206 Ok(())
207 })
208 .try_combine_syn_errors()?;
209
210 let ctx = &Ctx::new(&options.krate, None);
211
212 add_shared_proto_slots(ty, &mut proto_impls, implemented_proto_fragments, ctx);
213
214 let items = match methods_type {
215 PyClassMethodsType::Specialization => impl_py_methods(ty, methods, proto_impls, ctx),
216 PyClassMethodsType::Inventory => submit_methods_inventory(ty, methods, proto_impls, ctx),
217 };
218
219 Ok(quote! {
220 #(#extra_fragments)*
221
222 #items
223
224 #[doc(hidden)]
225 #[allow(non_snake_case)]
226 impl #ty {
227 #(#associated_methods)*
228 }
229 })
230}
231
232pub fn gen_py_const(cls: &syn::Type, spec: &ConstSpec, ctx: &Ctx) -> MethodAndMethodDef {
233 let member = &spec.rust_ident;
234 let wrapper_ident = format_ident!("__pymethod_{}__", member);
235 let python_name = spec.null_terminated_python_name(ctx);
236 let Ctx { pyo3_path, .. } = ctx;
237
238 let associated_method = quote! {
239 fn #wrapper_ident(py: #pyo3_path::Python<'_>) -> #pyo3_path::PyResult<#pyo3_path::Py<#pyo3_path::PyAny>> {
240 #pyo3_path::IntoPyObjectExt::into_py_any(#cls::#member, py)
241 }
242 };
243
244 let method_def = quote! {
245 #pyo3_path::impl_::pyclass::MaybeRuntimePyMethodDef::Static(
246 #pyo3_path::impl_::pymethods::PyMethodDefType::ClassAttribute({
247 #pyo3_path::impl_::pymethods::PyClassAttributeDef::new(
248 #python_name,
249 #cls::#wrapper_ident
250 )
251 })
252 )
253 };
254
255 MethodAndMethodDef {
256 associated_method,
257 method_def,
258 }
259}
260
261fn impl_py_methods(
262 ty: &syn::Type,
263 methods: Vec<TokenStream>,
264 proto_impls: Vec<TokenStream>,
265 ctx: &Ctx,
266) -> TokenStream {
267 let Ctx { pyo3_path, .. } = ctx;
268 quote! {
269 #[allow(unknown_lints, non_local_definitions)]
270 impl #pyo3_path::impl_::pyclass::PyMethods<#ty>
271 for #pyo3_path::impl_::pyclass::PyClassImplCollector<#ty>
272 {
273 fn py_methods(self) -> &'static #pyo3_path::impl_::pyclass::PyClassItems {
274 static ITEMS: #pyo3_path::impl_::pyclass::PyClassItems = #pyo3_path::impl_::pyclass::PyClassItems {
275 methods: &[#(#methods),*],
276 slots: &[#(#proto_impls),*]
277 };
278 &ITEMS
279 }
280 }
281 }
282}
283
284fn add_shared_proto_slots(
285 ty: &syn::Type,
286 proto_impls: &mut Vec<TokenStream>,
287 mut implemented_proto_fragments: HashSet<String>,
288 ctx: &Ctx,
289) {
290 let Ctx { pyo3_path, .. } = ctx;
291 macro_rules! try_add_shared_slot {
292 ($slot:ident, $($fragments:literal),*) => {{
293 let mut implemented = false;
294 $(implemented |= implemented_proto_fragments.remove($fragments));*;
295 if implemented {
296 proto_impls.push(quote! { #pyo3_path::impl_::pyclass::$slot!(#ty) })
297 }
298 }};
299 }
300
301 try_add_shared_slot!(
302 generate_pyclass_getattro_slot,
303 "__getattribute__",
304 "__getattr__"
305 );
306 try_add_shared_slot!(generate_pyclass_setattr_slot, "__setattr__", "__delattr__");
307 try_add_shared_slot!(generate_pyclass_setdescr_slot, "__set__", "__delete__");
308 try_add_shared_slot!(generate_pyclass_setitem_slot, "__setitem__", "__delitem__");
309 try_add_shared_slot!(generate_pyclass_add_slot, "__add__", "__radd__");
310 try_add_shared_slot!(generate_pyclass_sub_slot, "__sub__", "__rsub__");
311 try_add_shared_slot!(generate_pyclass_mul_slot, "__mul__", "__rmul__");
312 try_add_shared_slot!(generate_pyclass_mod_slot, "__mod__", "__rmod__");
313 try_add_shared_slot!(generate_pyclass_divmod_slot, "__divmod__", "__rdivmod__");
314 try_add_shared_slot!(generate_pyclass_lshift_slot, "__lshift__", "__rlshift__");
315 try_add_shared_slot!(generate_pyclass_rshift_slot, "__rshift__", "__rrshift__");
316 try_add_shared_slot!(generate_pyclass_and_slot, "__and__", "__rand__");
317 try_add_shared_slot!(generate_pyclass_or_slot, "__or__", "__ror__");
318 try_add_shared_slot!(generate_pyclass_xor_slot, "__xor__", "__rxor__");
319 try_add_shared_slot!(generate_pyclass_matmul_slot, "__matmul__", "__rmatmul__");
320 try_add_shared_slot!(generate_pyclass_truediv_slot, "__truediv__", "__rtruediv__");
321 try_add_shared_slot!(
322 generate_pyclass_floordiv_slot,
323 "__floordiv__",
324 "__rfloordiv__"
325 );
326 try_add_shared_slot!(generate_pyclass_pow_slot, "__pow__", "__rpow__");
327 try_add_shared_slot!(
328 generate_pyclass_richcompare_slot,
329 "__lt__",
330 "__le__",
331 "__eq__",
332 "__ne__",
333 "__gt__",
334 "__ge__"
335 );
336
337 assert!(implemented_proto_fragments.is_empty());
340}
341
342fn submit_methods_inventory(
343 ty: &syn::Type,
344 methods: Vec<TokenStream>,
345 proto_impls: Vec<TokenStream>,
346 ctx: &Ctx,
347) -> TokenStream {
348 let Ctx { pyo3_path, .. } = ctx;
349 quote! {
350 #pyo3_path::inventory::submit! {
351 type Inventory = <#ty as #pyo3_path::impl_::pyclass::PyClassImpl>::Inventory;
352 Inventory::new(#pyo3_path::impl_::pyclass::PyClassItems { methods: &[#(#methods),*], slots: &[#(#proto_impls),*] })
353 }
354 }
355}
356
357pub(crate) fn get_cfg_attributes(attrs: &[syn::Attribute]) -> Vec<&syn::Attribute> {
358 attrs
359 .iter()
360 .filter(|attr| attr.path().is_ident("cfg"))
361 .collect()
362}
363
364#[cfg(feature = "experimental-inspect")]
365fn method_introspection_code(spec: &FnSpec<'_>, parent: &syn::Type, ctx: &Ctx) -> TokenStream {
366 let Ctx { pyo3_path, .. } = ctx;
367
368 let name = spec.python_name.to_string();
369
370 if name == "__richcmp__" {
372 return ["__eq__", "__ne__", "__lt__", "__le__", "__gt__", "__ge__"]
374 .into_iter()
375 .map(|method_name| {
376 let mut spec = (*spec).clone();
377 spec.python_name = Ident::new(method_name, spec.python_name.span());
378 spec.signature.arguments.pop();
382 spec.signature.python_signature.positional_parameters.pop();
383 method_introspection_code(&spec, parent, ctx)
384 })
385 .collect();
386 }
387 let name = match name.as_str() {
390 "__concat__" => "__add__".into(),
391 "__repeat__" => "__mul__".into(),
392 "__inplace_concat__" => "__iadd__".into(),
393 "__inplace_repeat__" => "__imul__".into(),
394 "__getbuffer__" | "__releasebuffer__" | "__traverse__" | "__clear__" => return quote! {},
395 _ => name,
396 };
397
398 let mut first_argument = None;
400 let mut output = spec.output.clone();
401 let mut decorators = Vec::new();
402 match &spec.tp {
403 FnType::Getter(_) => {
404 first_argument = Some("self");
405 decorators.push("property".into());
406 }
407 FnType::Setter(_) => {
408 first_argument = Some("self");
409 decorators.push(format!("{name}.setter"));
410 }
411 FnType::Fn(_) => {
412 first_argument = Some("self");
413 }
414 FnType::FnNew | FnType::FnNewClass(_) => {
415 first_argument = Some("cls");
416 output = syn::ReturnType::Default; }
418 FnType::FnClass(_) => {
419 first_argument = Some("cls");
420 decorators.push("classmethod".into());
421 }
422 FnType::FnStatic => {
423 decorators.push("staticmethod".into());
424 }
425 FnType::FnModule(_) => (), FnType::ClassAttribute => {
427 first_argument = Some("cls");
428 decorators.push("classmethod".into());
430 decorators.push("property".into());
431 }
432 }
433 function_introspection_code(
434 pyo3_path,
435 None,
436 &name,
437 &spec.signature,
438 first_argument,
439 output,
440 decorators,
441 Some(parent),
442 )
443}