Skip to main content

rustpython_derive_impl/
pymodule.rs

1use crate::error::Diagnostic;
2use crate::pystructseq::PyStructSequenceMeta;
3use crate::util::{
4    ALL_ALLOWED_NAMES, AttrItemMeta, AttributeExt, ClassItemMeta, ContentItem, ContentItemInner,
5    ErrorVec, ItemMeta, ItemNursery, ModuleItemMeta, SimpleItemMeta, infer_native_call_flags,
6    internal_doc_tokens, iter_use_idents, pyclass_ident_and_attrs,
7};
8use core::str::FromStr;
9use proc_macro2::{Delimiter, Group, TokenStream, TokenTree};
10use quote::{ToTokens, format_ident, quote, quote_spanned};
11
12use std::collections::HashSet;
13use syn::{Attribute, Ident, Item, Result, parse_quote, spanned::Spanned};
14use syn_ext::ext::*;
15use syn_ext::types::NestedMeta;
16
17/// A `with(...)` item that may be gated by `#[cfg(...)]` attributes.
18pub struct WithItem {
19    pub cfg_attrs: Vec<Attribute>,
20    pub path: syn::Path,
21}
22
23impl syn::parse::Parse for WithItem {
24    fn parse(input: syn::parse::ParseStream<'_>) -> Result<Self> {
25        let cfg_attrs = Attribute::parse_outer(input)?;
26        for attr in &cfg_attrs {
27            if !attr.path().is_ident("cfg") {
28                return Err(syn::Error::new_spanned(
29                    attr,
30                    "only #[cfg(...)] is supported in with()",
31                ));
32            }
33        }
34        let path = input.parse()?;
35        Ok(Self { cfg_attrs, path })
36    }
37}
38
39/// Parsed arguments for `#[pymodule(...)]`, supporting `#[cfg]` inside `with(...)`.
40pub struct PyModuleArgs {
41    pub metas: Vec<NestedMeta>,
42    pub with_items: Vec<WithItem>,
43}
44
45impl syn::parse::Parse for PyModuleArgs {
46    fn parse(input: syn::parse::ParseStream<'_>) -> Result<Self> {
47        let mut metas = Vec::new();
48        let mut with_items = Vec::new();
49
50        while !input.is_empty() {
51            // Detect `with(...)` — an ident "with" followed by a paren group
52            if input.peek(Ident) && input.peek2(syn::token::Paren) {
53                let fork = input.fork();
54                let ident: Ident = fork.parse()?;
55                if ident == "with" {
56                    // Advance past "with"
57                    let _: Ident = input.parse()?;
58                    let content;
59                    syn::parenthesized!(content in input);
60                    let items =
61                        syn::punctuated::Punctuated::<WithItem, syn::Token![,]>::parse_terminated(
62                            &content,
63                        )?;
64                    with_items.extend(items);
65                    if !input.is_empty() {
66                        input.parse::<syn::Token![,]>()?;
67                    }
68                    continue;
69                }
70            }
71            metas.push(input.parse::<NestedMeta>()?);
72            if input.is_empty() {
73                break;
74            }
75            input.parse::<syn::Token![,]>()?;
76        }
77
78        Ok(Self { metas, with_items })
79    }
80}
81
82/// Generate `#[cfg(not(...))]` attributes that negate the given `#[cfg(...)]` attributes.
83fn negate_cfg_attrs(cfg_attrs: &[Attribute]) -> Vec<Attribute> {
84    if cfg_attrs.is_empty() {
85        return vec![];
86    }
87    let predicates = cfg_attrs
88        .iter()
89        .map(|attr| match &attr.meta {
90            syn::Meta::List(list) => list.tokens.clone(),
91            _ => unreachable!("only #[cfg(...)] should be here"),
92        })
93        .collect::<Vec<_>>();
94    if predicates.len() == 1 {
95        let predicate = &predicates[0];
96        vec![parse_quote!(#[cfg(not(#predicate))])]
97    } else {
98        vec![parse_quote!(#[cfg(not(all(#(#predicates),*)))])]
99    }
100}
101
102#[derive(Clone, Copy, Eq, PartialEq)]
103enum AttrName {
104    Function,
105    Attr,
106    Class,
107    Exception,
108    StructSequence,
109}
110
111impl core::fmt::Display for AttrName {
112    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
113        let s = match self {
114            Self::Function => "pyfunction",
115            Self::Attr => "pyattr",
116            Self::Class => "pyclass",
117            Self::Exception => "pyexception",
118            Self::StructSequence => "pystruct_sequence",
119        };
120        s.fmt(f)
121    }
122}
123
124impl FromStr for AttrName {
125    type Err = String;
126
127    fn from_str(s: &str) -> core::result::Result<Self, Self::Err> {
128        Ok(match s {
129            "pyfunction" => Self::Function,
130            "pyattr" => Self::Attr,
131            "pyclass" => Self::Class,
132            "pyexception" => Self::Exception,
133            "pystruct_sequence" => Self::StructSequence,
134            s => {
135                return Err(s.to_owned());
136            }
137        })
138    }
139}
140
141#[derive(Default)]
142struct ModuleContext {
143    name: String,
144    /// `#[pymodule(sub)]` is merged into its parent. Doc lookup uses `name`
145    /// only when the attribute sets `name`. Without `name`, the Rust module
146    /// name is not a Python module, so the doc DB is not consulted. A `///`
147    /// doc on an item still applies.
148    is_sub: bool,
149    /// `true` when `#[pymodule(name = "...")]` set the Python module name.
150    explicit_name: bool,
151    function_items: FunctionNursery,
152    attribute_items: ItemNursery,
153    has_module_exec: bool,
154    errors: Vec<syn::Error>,
155}
156
157pub(crate) fn impl_pymodule(args: PyModuleArgs, module_item: Item) -> Result<TokenStream> {
158    let PyModuleArgs { metas, with_items } = args;
159    let (doc, mut module_item) = match module_item {
160        Item::Mod(m) => (m.attrs.doc(), m),
161        other => bail_span!(other, "#[pymodule] can only be on a full module"),
162    };
163    let fake_ident = Ident::new("pymodule", module_item.span());
164    let module_meta =
165        ModuleItemMeta::from_nested(module_item.ident.clone(), fake_ident, metas.into_iter())?;
166
167    // generation resources
168    let mut context = ModuleContext {
169        name: module_meta.simple_name()?,
170        is_sub: module_meta.sub()?,
171        explicit_name: module_meta.optional_name().is_some(),
172        ..Default::default()
173    };
174    let items = module_item.items_mut().ok_or_else(|| {
175        module_meta.new_meta_error("requires actual module, not a module declaration")
176    })?;
177
178    // collect to context
179    for item in items.iter_mut() {
180        // Check if module_exec function is already defined
181        if let Item::Fn(func) = item
182            && func.sig.ident == "module_exec"
183        {
184            context.has_module_exec = true;
185        }
186        if matches!(item, Item::Impl(_) | Item::Trait(_)) {
187            // #[pyclass] implementations
188            continue;
189        }
190        let r = item.try_split_attr_mut(|attrs, item| {
191            let (py_items, cfgs) = attrs_to_module_items(attrs, module_item_new)?;
192            for py_item in py_items.iter().rev() {
193                let r = py_item.gen_module_item(ModuleItemArgs {
194                    item,
195                    attrs,
196                    context: &mut context,
197                    cfgs: cfgs.as_slice(),
198                });
199                context.errors.ok_or_push(r);
200            }
201            Ok(())
202        });
203        context.errors.ok_or_push(r);
204    }
205
206    // Detect nested #[pymodule] items (non-sub) and generate submodule init code
207    let mut submodule_inits: Vec<TokenStream> = Vec::new();
208    for item in items.iter() {
209        if let Item::Mod(item_mod) = item {
210            let r = (|| -> Result<()> {
211                let attr = match item_mod
212                    .attrs
213                    .iter()
214                    .find(|a| a.path().is_ident("pymodule"))
215                {
216                    Some(attr) => attr,
217                    None => return Ok(()),
218                };
219                let args_tokens = match &attr.meta {
220                    syn::Meta::Path(_) => TokenStream::new(),
221                    syn::Meta::List(list) => list.tokens.clone(),
222                    _ => return Ok(()),
223                };
224                let mod_args: PyModuleArgs = syn::parse2(args_tokens)?;
225                let fake_ident = Ident::new("pymodule", attr.span());
226                let mod_meta = ModuleItemMeta::from_nested(
227                    item_mod.ident.clone(),
228                    fake_ident,
229                    mod_args.metas.into_iter(),
230                )?;
231                if mod_meta.sub()? {
232                    return Ok(());
233                }
234                let py_name = mod_meta.simple_name()?;
235                let mod_ident = &item_mod.ident;
236                let cfgs: Vec<_> = item_mod
237                    .attrs
238                    .iter()
239                    .filter(|a| a.path().is_ident("cfg"))
240                    .cloned()
241                    .collect();
242                submodule_inits.push(quote! {
243                    #(#cfgs)*
244                    {
245                        let child_def = #mod_ident::module_def(ctx);
246                        let child = child_def.create_module(vm).expect("submodule create_module failed");
247                        child.__init_methods(vm).expect("submodule __init_methods failed");
248                        #mod_ident::module_exec(vm, &child).expect("submodule module_exec failed");
249                        let child: ::rustpython_vm::PyObjectRef = child.into();
250                        vm.__module_set_attr(module, ctx.intern_str(#py_name), child).expect("module set_attr submodule failed");
251                    }
252                });
253                Ok(())
254            })();
255            context.errors.ok_or_push(r);
256        }
257    }
258
259    // append additional items
260    let module_name = context.name.as_str();
261    let function_items = context.function_items.validate()?;
262    let attribute_items = context.attribute_items.validate()?;
263    let rust_doc = doc.filter(|doc| !doc.is_empty());
264    let db_doc = if rust_doc.is_some() || (context.is_sub && !context.explicit_name) {
265        None
266    } else {
267        rustpython_doc::get(module_name)
268    };
269    let doc = crate::class_docs::item_doc_tokens(db_doc, rust_doc);
270    let is_submodule = module_meta.sub()?;
271    if !is_submodule {
272        items.extend([
273            parse_quote! {
274                pub(crate) const MODULE_NAME: &'static str = #module_name;
275            },
276            parse_quote! {
277                pub(crate) const DOC: ::rustpython_vm::function::ItemDoc = #doc;
278            },
279            parse_quote! {
280                pub(crate) fn module_def(
281                    ctx: &::rustpython_vm::Context,
282                ) -> &'static ::rustpython_vm::builtins::PyModuleDef {
283                    DEF.get_or_init(|| {
284                        let mut def = ::rustpython_vm::builtins::PyModuleDef {
285                            name: ctx.intern_str(MODULE_NAME),
286                            doc: ::rustpython_vm::function::plain_doc(DOC).map(|doc| ctx.intern_str(doc)),
287                            methods: METHOD_DEFS,
288                            slots: Default::default(),
289                        };
290                        def.slots.exec = Some(module_exec);
291                        def
292                    })
293                }
294            },
295        ]);
296    }
297    if !is_submodule && !context.has_module_exec {
298        items.push(parse_quote! {
299            pub(crate) fn module_exec(vm: &::rustpython_vm::VirtualMachine, module: &::rustpython_vm::Py<::rustpython_vm::builtins::PyModule>) -> ::rustpython_vm::PyResult<()> {
300                __module_exec(vm, module);
301                Ok(())
302            }
303        });
304    }
305    // Split with_items into unconditional and cfg-gated groups
306    let (uncond_withs, cond_withs): (Vec<_>, Vec<_>) =
307        with_items.iter().partition(|w| w.cfg_attrs.is_empty());
308    let uncond_paths = uncond_withs.iter().map(|w| &w.path).collect::<Vec<_>>();
309
310    let method_defs = if with_items.is_empty() {
311        quote!(#function_items)
312    } else {
313        // For cfg-gated with items, generate conditional const declarations
314        // so the total array size adapts to the cfg at compile time
315        let cond_const_names = cond_withs
316            .iter()
317            .enumerate()
318            .map(|(i, _)| format_ident!("__WITH_METHODS_{}", i))
319            .collect::<Vec<_>>();
320
321        let cond_const_decls= cond_withs
322            .iter()
323            .zip(&cond_const_names)
324            .map(|(w, name)| {
325                let cfg_attrs = &w.cfg_attrs;
326                let neg_attrs = negate_cfg_attrs(&w.cfg_attrs);
327                let path = &w.path;
328                quote! {
329                    #(#cfg_attrs)*
330                    const #name: &'static [::rustpython_vm::function::PyMethodDef] = super::#path::METHOD_DEFS;
331                    #(#neg_attrs)*
332                    const #name: &'static [::rustpython_vm::function::PyMethodDef] = &[];
333                }
334            })
335            .collect::<Vec<_>>();
336
337        quote!({
338            const OWN_METHODS: &'static [::rustpython_vm::function::PyMethodDef] = &#function_items;
339            #(#cond_const_decls)*
340            rustpython_vm::function::PyMethodDef::__const_concat_arrays::<
341                { OWN_METHODS.len()
342                    #(+ super::#uncond_paths::METHOD_DEFS.len())*
343                    #(+ #cond_const_names.len())*
344                },
345            >(&[
346                #(super::#uncond_paths::METHOD_DEFS,)*
347                #(#cond_const_names,)*
348                OWN_METHODS
349            ])
350        })
351    };
352
353    // Generate __init_attributes calls, wrapping cfg-gated items
354    let init_with_calls = with_items
355        .iter()
356        .map(|w| {
357            let cfg_attrs = &w.cfg_attrs;
358            let path = &w.path;
359            quote! {
360                #(#cfg_attrs)*
361                super::#path::__init_attributes(vm, module);
362            }
363        })
364        .collect::<Vec<_>>();
365
366    items.extend([
367        parse_quote! {
368            ::rustpython_vm::common::static_cell! {
369                pub(crate) static DEF: ::rustpython_vm::builtins::PyModuleDef;
370            }
371        },
372        parse_quote! {
373            pub(crate) const METHOD_DEFS: &'static [::rustpython_vm::function::PyMethodDef] = &#method_defs;
374        },
375        parse_quote! {
376            pub(crate) fn __init_attributes(
377                vm: &::rustpython_vm::VirtualMachine,
378                module: &::rustpython_vm::Py<::rustpython_vm::builtins::PyModule>,
379            ) {
380                #(#init_with_calls)*
381                let ctx = &vm.ctx;
382                #attribute_items
383                #(#submodule_inits)*
384            }
385        },
386        parse_quote! {
387            pub(crate) fn __module_exec(
388                vm: &::rustpython_vm::VirtualMachine,
389                module: &::rustpython_vm::Py<::rustpython_vm::builtins::PyModule>,
390            ) {
391                __init_attributes(vm, module);
392            }
393        },
394        parse_quote! {
395            pub(crate) fn __init_dict(
396                vm: &::rustpython_vm::VirtualMachine,
397                module: &::rustpython_vm::Py<::rustpython_vm::builtins::PyModule>,
398            ) {
399                ::rustpython_vm::builtins::PyModule::__init_dict_from_def(vm, module);
400            }
401        },
402    ]);
403
404    Ok(if let Some(error) = context.errors.into_error() {
405        let error = Diagnostic::from(error);
406        quote! {
407            #module_item
408            #error
409        }
410    } else {
411        module_item.into_token_stream()
412    })
413}
414
415fn module_item_new(
416    index: usize,
417    attr_name: AttrName,
418    py_attrs: Vec<usize>,
419) -> Box<dyn ModuleItem<AttrName = AttrName>> {
420    match attr_name {
421        AttrName::Function => Box::new(FunctionItem {
422            inner: ContentItemInner { index, attr_name },
423            py_attrs,
424        }),
425        AttrName::Attr => Box::new(AttributeItem {
426            inner: ContentItemInner { index, attr_name },
427            py_attrs,
428        }),
429        // pyexception is treated like pyclass - both define types
430        AttrName::Class | AttrName::Exception => Box::new(ClassItem {
431            inner: ContentItemInner { index, attr_name },
432            py_attrs,
433        }),
434        AttrName::StructSequence => Box::new(StructSequenceItem {
435            inner: ContentItemInner { index, attr_name },
436            py_attrs,
437        }),
438    }
439}
440
441fn attrs_to_module_items<F, R>(attrs: &[Attribute], item_new: F) -> Result<(Vec<R>, Vec<Attribute>)>
442where
443    F: Fn(usize, AttrName, Vec<usize>) -> R,
444{
445    let mut cfgs: Vec<Attribute> = Vec::new();
446    let mut result = Vec::new();
447
448    let mut iter = attrs.iter().enumerate().peekable();
449    while let Some((_, attr)) = iter.peek() {
450        // take all cfgs but no py items
451        let attr = *attr;
452        if let Some(ident) = attr.get_ident() {
453            let attr_name = ident.to_string();
454            if attr_name == "cfg" {
455                cfgs.push(attr.clone());
456            } else if ALL_ALLOWED_NAMES.contains(&attr_name.as_str()) {
457                break;
458            }
459        }
460        iter.next();
461    }
462
463    let mut closed = false;
464    let mut py_attrs = Vec::new();
465    for (i, attr) in iter {
466        // take py items but no cfgs
467        let attr_name = if let Some(ident) = attr.get_ident() {
468            ident.to_string()
469        } else {
470            continue;
471        };
472        if attr_name == "cfg" {
473            bail_span!(attr, "#[py*] items must be placed under `cfgs`")
474        }
475
476        let attr_name = match AttrName::from_str(attr_name.as_str()) {
477            Ok(name) => name,
478            Err(wrong_name) => {
479                if !ALL_ALLOWED_NAMES.contains(&wrong_name.as_str()) {
480                    continue;
481                } else if closed {
482                    bail_span!(attr, "Only one #[pyattr] annotated #[py*] item can exist")
483                }
484                bail_span!(attr, "#[pymodule] doesn't accept #[{}]", wrong_name)
485            }
486        };
487
488        if attr_name == AttrName::Attr {
489            if !result.is_empty() {
490                bail_span!(
491                    attr,
492                    "#[pyattr] must be placed on top of other #[py*] items",
493                )
494            }
495            py_attrs.push(i);
496            continue;
497        }
498
499        if py_attrs.is_empty() {
500            result.push(item_new(i, attr_name, Vec::new()));
501        } else {
502            match attr_name {
503                AttrName::Class
504                | AttrName::Function
505                | AttrName::Exception
506                | AttrName::StructSequence => {
507                    result.push(item_new(i, attr_name, py_attrs.clone()));
508                }
509                _ => {
510                    bail_span!(
511                        attr,
512                        "#[pyclass], #[pyfunction], #[pyexception], or #[pystruct_sequence] can follow #[pyattr]",
513                    )
514                }
515            }
516            py_attrs.clear();
517            closed = true;
518        }
519    }
520
521    if let Some(last) = py_attrs.pop() {
522        assert!(!closed);
523        result.push(item_new(last, AttrName::Attr, py_attrs));
524    }
525    Ok((result, cfgs))
526}
527
528#[derive(Default)]
529struct FunctionNursery {
530    items: Vec<FunctionNurseryItem>,
531}
532
533struct FunctionNurseryItem {
534    py_names: Vec<String>,
535    cfgs: Vec<Attribute>,
536    ident: Ident,
537    /// One internal doc per [`py_names`](Self::py_names) entry.
538    docs: Vec<TokenStream>,
539    call_flags: TokenStream,
540}
541
542impl FunctionNursery {
543    fn add_item(&mut self, item: FunctionNurseryItem) {
544        self.items.push(item);
545    }
546
547    fn validate(self) -> Result<ValidatedFunctionNursery> {
548        let mut name_set = HashSet::new();
549        for item in &self.items {
550            for py_name in &item.py_names {
551                if !name_set.insert((py_name.to_owned(), &item.cfgs)) {
552                    bail_span!(item.ident, "duplicate method name `{}`", py_name);
553                }
554            }
555        }
556        Ok(ValidatedFunctionNursery(self))
557    }
558}
559
560struct ValidatedFunctionNursery(FunctionNursery);
561
562impl ToTokens for ValidatedFunctionNursery {
563    fn to_tokens(&self, tokens: &mut TokenStream) {
564        let mut inner_tokens = TokenStream::new();
565        for item in &self.0.items {
566            let ident = &item.ident;
567            let cfgs = &item.cfgs;
568            let cfgs = quote!(#(#cfgs)*);
569            let flags = &item.call_flags;
570            for (py_name, doc) in item.py_names.iter().zip(&item.docs) {
571                inner_tokens.extend(quote![
572                    #cfgs
573                    rustpython_vm::function::PyMethodDef::new_const(
574                        #py_name,
575                        #ident,
576                        #flags,
577                        #doc,
578                    ),
579                ]);
580            }
581        }
582        let array: TokenTree = Group::new(Delimiter::Bracket, inner_tokens).into();
583        tokens.extend([array]);
584    }
585}
586
587/// #[pyfunction]
588struct FunctionItem {
589    inner: ContentItemInner<AttrName>,
590    py_attrs: Vec<usize>,
591}
592
593/// #[pyclass]
594struct ClassItem {
595    inner: ContentItemInner<AttrName>,
596    py_attrs: Vec<usize>,
597}
598
599/// #[pyattr]
600struct AttributeItem {
601    inner: ContentItemInner<AttrName>,
602    py_attrs: Vec<usize>,
603}
604
605/// #[pystruct_sequence]
606struct StructSequenceItem {
607    inner: ContentItemInner<AttrName>,
608    py_attrs: Vec<usize>,
609}
610
611impl ContentItem for FunctionItem {
612    type AttrName = AttrName;
613
614    fn inner(&self) -> &ContentItemInner<AttrName> {
615        &self.inner
616    }
617}
618
619impl ContentItem for ClassItem {
620    type AttrName = AttrName;
621
622    fn inner(&self) -> &ContentItemInner<AttrName> {
623        &self.inner
624    }
625}
626
627impl ContentItem for AttributeItem {
628    type AttrName = AttrName;
629
630    fn inner(&self) -> &ContentItemInner<AttrName> {
631        &self.inner
632    }
633}
634
635impl ContentItem for StructSequenceItem {
636    type AttrName = AttrName;
637
638    fn inner(&self) -> &ContentItemInner<AttrName> {
639        &self.inner
640    }
641}
642
643struct ModuleItemArgs<'a> {
644    item: &'a mut Item,
645    attrs: &'a mut Vec<Attribute>,
646    context: &'a mut ModuleContext,
647    cfgs: &'a [Attribute],
648}
649
650impl<'a> ModuleItemArgs<'a> {
651    /// Python module consulted in the doc DB. `None` for `#[pymodule(sub)]`
652    /// without `name`.
653    fn doc_module(&'a self) -> Option<&'a str> {
654        if self.context.is_sub && !self.context.explicit_name {
655            None
656        } else {
657            Some(self.context.name.as_str())
658        }
659    }
660}
661
662trait ModuleItem: ContentItem {
663    fn gen_module_item(&self, args: ModuleItemArgs<'_>) -> Result<()>;
664}
665
666impl ModuleItem for FunctionItem {
667    fn gen_module_item(&self, args: ModuleItemArgs<'_>) -> Result<()> {
668        let func = args
669            .item
670            .function_or_method()
671            .map_err(|_| self.new_syn_error(args.item.span(), "can only be on a function"))?;
672        let ident = &func.sig().ident;
673
674        let item_attr = args.attrs.remove(self.index());
675        let item_meta = SimpleItemMeta::from_attr(ident.clone(), &item_attr)?;
676
677        let py_name = item_meta.simple_name()?;
678        let mut py_names = vec![py_name];
679        for attr_index in self.py_attrs.iter().rev() {
680            let mut loop_unit = || {
681                let attr_attr = args.attrs.remove(*attr_index);
682                let item_meta = SimpleItemMeta::from_attr(ident.clone(), &attr_attr)?;
683
684                let py_name = item_meta.simple_name()?;
685                if py_names.iter().any(|name| name == &py_name) {
686                    return Err(self.new_syn_error(
687                        ident.span(),
688                        &format!("`{py_name}` is duplicated name for multiple py* attribute"),
689                    ));
690                }
691                py_names.push(py_name);
692                Ok(())
693            };
694            let r = loop_unit();
695            args.context.errors.ok_or_push(r);
696        }
697
698        let module = args.doc_module();
699        let rust_doc = args.attrs.doc().filter(|doc| !doc.is_empty());
700        let docs = py_names
701            .iter()
702            .map(|py_name| {
703                let db_doc = if rust_doc.is_some() {
704                    None
705                } else {
706                    module.and_then(|module| {
707                        rustpython_doc::get_qualified(module, py_name, None, false)
708                    })
709                };
710                let doc = crate::class_docs::item_doc_tokens(db_doc, rust_doc.clone());
711                internal_doc_tokens(func.sig(), py_name, None, doc, None, Some("$module"))
712            })
713            .collect();
714        let call_flags = infer_native_call_flags(func.sig(), 0);
715
716        args.context.function_items.add_item(FunctionNurseryItem {
717            ident: ident.to_owned(),
718            py_names,
719            cfgs: args.cfgs.to_vec(),
720            docs,
721            call_flags,
722        });
723        Ok(())
724    }
725}
726
727impl ModuleItem for ClassItem {
728    fn gen_module_item(&self, args: ModuleItemArgs<'_>) -> Result<()> {
729        let (ident, _) = pyclass_ident_and_attrs(args.item)?;
730        let (class_name, class_new) = {
731            let class_attr = &mut args.attrs[self.inner.index];
732            let no_attr = class_attr.try_remove_name("no_attr")?;
733            if self.py_attrs.is_empty() {
734                // check no_attr before ClassItemMeta::from_attr
735                if no_attr.is_none() {
736                    bail_span!(
737                        ident,
738                        "#[{name}] requires #[pyattr] to be a module attribute. \
739                         To keep it free type, try #[{name}(no_attr)]",
740                        name = self.attr_name()
741                    )
742                }
743            }
744            let no_attr = no_attr.is_some();
745            let is_use = matches!(&args.item, syn::Item::Use(_));
746
747            let class_meta = ClassItemMeta::from_attr(ident.clone(), class_attr)?;
748            let explicit_module = class_meta.module().ok().flatten();
749            let module_name = if let Some(class_module_name) = explicit_module.clone() {
750                class_module_name
751            } else {
752                let module_name = args.context.name.clone();
753                class_attr.fill_nested_meta("module", || {
754                    parse_quote! {module = #module_name}
755                })?;
756                module_name
757            };
758            let class_name = if no_attr && is_use {
759                "<NO ATTR>".to_owned()
760            } else {
761                class_meta.class_name()?
762            };
763            // The class's own module first, then the module it is published on.
764            // A `sub` module without `name` has no Python module to consult.
765            let mut doc_modules = Vec::new();
766            if let Some(module) = explicit_module.as_deref() {
767                doc_modules.push(module);
768            }
769            if let Some(module) = args.doc_module()
770                && !doc_modules.contains(&module)
771            {
772                doc_modules.push(module);
773            }
774            let class_doc = doc_modules
775                .into_iter()
776                .find_map(|module| {
777                    rustpython_doc::get_qualified(module, &class_name, None, true)
778                        .filter(|doc| doc.len != 0)
779                })
780                .map(|doc| {
781                    let doc = crate::class_docs::item_doc_tokens(Some(doc), None);
782                    quote!(::rustpython_vm::class::assign_missing_doc(vm, &new_class, #doc);)
783                });
784            let class_new = quote_spanned!(ident.span() =>
785                let new_class = <#ident as ::rustpython_vm::class::PyClassImpl>::make_static_type();
786                // Only set __module__ string if the class doesn't already have a
787                // getset descriptor for __module__ (which provides instance-level
788                // module resolution, e.g. TypeAliasType)
789                {
790                    let module_key = rustpython_vm::identifier!(ctx, __module__);
791                    let has_module_getset = new_class.payload().attributes
792                        .get(module_key)
793                        .is_some_and(|v| v.downcastable::<rustpython_vm::builtins::PyGetSet>());
794                    if !has_module_getset {
795                        new_class.set_attr(module_key, vm.new_pyobj(#module_name));
796                    }
797                }
798                #class_doc
799            );
800            (class_name, class_new)
801        };
802
803        let mut py_names = Vec::new();
804        for attr_index in self.py_attrs.iter().rev() {
805            let mut loop_unit = || {
806                let attr_attr = args.attrs.remove(*attr_index);
807                let item_meta = SimpleItemMeta::from_attr(ident.clone(), &attr_attr)?;
808
809                let py_name = item_meta
810                    .optional_name()
811                    .unwrap_or_else(|| class_name.clone());
812                py_names.push(py_name);
813
814                Ok(())
815            };
816            let r = loop_unit();
817            args.context.errors.ok_or_push(r);
818        }
819
820        let set_attr = match py_names.len() {
821            0 => quote! {
822                let _ = new_class;  // suppress warning
823                let _ = vm.ctx.intern_str(#class_name);
824            },
825            1 => {
826                let py_name = &py_names[0];
827                quote! {
828                    vm.__module_set_attr(&module, vm.ctx.intern_str(#py_name), new_class).unwrap();
829                }
830            }
831            _ => quote! {
832                for name in [#(#py_names,)*] {
833                    vm.__module_set_attr(&module, vm.ctx.intern_str(name), new_class.clone()).unwrap();
834                }
835            },
836        };
837
838        args.context.attribute_items.add_item(
839            ident.clone(),
840            py_names,
841            args.cfgs.to_vec(),
842            quote_spanned! { ident.span() =>
843                #class_new
844                #set_attr
845            },
846            0,
847        );
848        Ok(())
849    }
850}
851
852impl ModuleItem for StructSequenceItem {
853    fn gen_module_item(&self, args: ModuleItemArgs<'_>) -> Result<()> {
854        // Get the struct identifier (this IS the Python type, e.g., PyStructTime)
855        let pytype_ident = match args.item {
856            Item::Struct(s) => s.ident.clone(),
857            other => bail_span!(other, "#[pystruct_sequence] can only be on a struct"),
858        };
859
860        // Parse the #[pystruct_sequence(name = "...", module = "...", no_attr)] attribute
861        let structseq_attr = &args.attrs[self.inner.index];
862        let meta = PyStructSequenceMeta::from_attr(pytype_ident.clone(), structseq_attr)?;
863
864        let class_name = meta.class_name()?.ok_or_else(|| {
865            syn::Error::new_spanned(
866                structseq_attr,
867                "#[pystruct_sequence] requires name parameter",
868            )
869        })?;
870        let module_opt = meta.module()?;
871        let has_module = module_opt.is_some();
872        let module_name = module_opt.unwrap_or_else(|| args.context.name.clone());
873        if !has_module {
874            let structseq_attr = &mut args.attrs[self.inner.index];
875            structseq_attr.fill_nested_meta("module", || {
876                parse_quote! {module = #module_name}
877            })?;
878        }
879        let no_attr = meta.no_attr()?;
880
881        // Generate the class creation code
882        let class_new = quote_spanned!(pytype_ident.span() =>
883            let new_class = <#pytype_ident as ::rustpython_vm::class::PyClassImpl>::make_static_type();
884            {
885                let module_key = rustpython_vm::identifier!(ctx, __module__);
886                let has_module_getset = new_class.payload().attributes
887                    .get(module_key)
888                    .is_some_and(|v| v.downcastable::<rustpython_vm::builtins::PyGetSet>());
889                if !has_module_getset {
890                    new_class.set_attr(module_key, vm.new_pyobj(#module_name));
891                }
892            }
893        );
894
895        // Handle py_attrs for custom names, or use class_name as default
896        let mut py_names = Vec::new();
897        for attr_index in self.py_attrs.iter().rev() {
898            let attr_attr = args.attrs.remove(*attr_index);
899            let item_meta = SimpleItemMeta::from_attr(pytype_ident.clone(), &attr_attr)?;
900            let py_name = item_meta
901                .optional_name()
902                .unwrap_or_else(|| class_name.clone());
903            py_names.push(py_name);
904        }
905
906        // Require explicit #[pyattr] or no_attr, like #[pyclass]
907        if self.py_attrs.is_empty() && !no_attr {
908            bail_span!(
909                pytype_ident,
910                "#[pystruct_sequence] requires #[pyattr] to be a module attribute. \
911                 To keep it free type, try #[pystruct_sequence(..., no_attr)]"
912            )
913        }
914
915        let set_attr = match py_names.len() {
916            0 => quote! {
917                let _ = new_class;  // suppress warning
918            },
919            1 => {
920                let py_name = &py_names[0];
921                quote! {
922                    vm.__module_set_attr(&module, vm.ctx.intern_str(#py_name), new_class).unwrap();
923                }
924            }
925            _ => quote! {
926                for name in [#(#py_names,)*] {
927                    vm.__module_set_attr(&module, vm.ctx.intern_str(name), new_class.clone()).unwrap();
928                }
929            },
930        };
931
932        args.context.attribute_items.add_item(
933            pytype_ident.clone(),
934            py_names,
935            args.cfgs.to_vec(),
936            quote_spanned! { pytype_ident.span() =>
937                #class_new
938                #set_attr
939            },
940            0,
941        );
942        Ok(())
943    }
944}
945
946impl ModuleItem for AttributeItem {
947    fn gen_module_item(&self, args: ModuleItemArgs<'_>) -> Result<()> {
948        let cfgs = args.cfgs.to_vec();
949        let attr = args.attrs.remove(self.index());
950        let (ident, py_name, let_obj) = match args.item {
951            Item::Fn(syn::ItemFn { sig, block, .. }) => {
952                let ident = &sig.ident;
953                // If `once` keyword is in #[pyattr],
954                // wrapping it with static_cell for preventing it from using it as function
955                let attr_meta = AttrItemMeta::from_attr(ident.clone(), &attr)?;
956                if attr_meta.inner()._bool("once")? {
957                    let stmts = &block.stmts;
958                    let return_type = match &sig.output {
959                        syn::ReturnType::Default => {
960                            unreachable!("#[pyattr] attached function must have return type.")
961                        }
962                        syn::ReturnType::Type(_, ty) => ty,
963                    };
964                    let stmt: syn::Stmt = parse_quote! {
965                        {
966                            rustpython_common::static_cell! {
967                                static ERROR: #return_type;
968                            }
969                            ERROR
970                                .get_or_init(|| {
971                                    #(#stmts)*
972                                })
973                                .clone()
974                        }
975                    };
976                    block.stmts = vec![stmt];
977                }
978
979                let py_name = attr_meta.simple_name()?;
980                (
981                    ident.clone(),
982                    py_name,
983                    quote_spanned! { ident.span() =>
984                        let obj = vm.new_pyobj(#ident(vm));
985                    },
986                )
987            }
988            Item::Const(syn::ItemConst { ident, .. }) => {
989                let item_meta = SimpleItemMeta::from_attr(ident.clone(), &attr)?;
990                let py_name = item_meta.simple_name()?;
991                (
992                    ident.clone(),
993                    py_name,
994                    quote_spanned! { ident.span() =>
995                        let obj = vm.new_pyobj(#ident);
996                    },
997                )
998            }
999            Item::Use(item) => {
1000                if !self.py_attrs.is_empty() {
1001                    return Err(self
1002                        .new_syn_error(item.span(), "Only single #[pyattr] is allowed for `use`"));
1003                }
1004                let _ = iter_use_idents(item, |ident, is_unique| {
1005                    let item_meta = SimpleItemMeta::from_attr(ident.clone(), &attr)?;
1006                    let py_name = if is_unique {
1007                        item_meta.simple_name()?
1008                    } else if item_meta.optional_name().is_some() {
1009                        // this check actually doesn't need to be placed in loop
1010                        return Err(self.new_syn_error(
1011                            ident.span(),
1012                            "`name` attribute is not allowed for multiple use items",
1013                        ));
1014                    } else {
1015                        ident.to_string()
1016                    };
1017                    let tokens = quote_spanned! { ident.span() =>
1018                        vm.__module_set_attr(module, vm.ctx.intern_str(#py_name), vm.new_pyobj(#ident)).unwrap();
1019                    };
1020                    args.context.attribute_items.add_item(
1021                        ident.clone(),
1022                        vec![py_name],
1023                        cfgs.clone(),
1024                        tokens,
1025                        1,
1026                    );
1027                    Ok(())
1028                });
1029                return Ok(());
1030            }
1031            other => {
1032                return Err(
1033                    self.new_syn_error(other.span(), "can only be on a function, const and use")
1034                );
1035            }
1036        };
1037
1038        let (tokens, py_names) = if self.py_attrs.is_empty() {
1039            (
1040                quote_spanned! { ident.span() => {
1041                    #let_obj
1042                    vm.__module_set_attr(module, vm.ctx.intern_str(#py_name), obj).unwrap();
1043                }},
1044                vec![py_name],
1045            )
1046        } else {
1047            let mut names = vec![py_name];
1048            for attr_index in self.py_attrs.iter().rev() {
1049                let mut loop_unit = || {
1050                    let attr_attr = args.attrs.remove(*attr_index);
1051                    let item_meta = AttrItemMeta::from_attr(ident.clone(), &attr_attr)?;
1052                    if item_meta.inner()._bool("once")? {
1053                        return Err(self.new_syn_error(
1054                            ident.span(),
1055                            "#[pyattr(once)] is only allowed for the bottom-most item",
1056                        ));
1057                    }
1058
1059                    let py_name = item_meta.optional_name().ok_or_else(|| {
1060                        self.new_syn_error(
1061                            ident.span(),
1062                            "#[pyattr(name = ...)] is mandatory except for the bottom-most item",
1063                        )
1064                    })?;
1065                    names.push(py_name);
1066                    Ok(())
1067                };
1068                let r = loop_unit();
1069                args.context.errors.ok_or_push(r);
1070            }
1071            (
1072                quote_spanned! { ident.span() => {
1073                    #let_obj
1074                    for name in [#(#names),*] {
1075                        vm.__module_set_attr(module, vm.ctx.intern_str(name), obj.clone()).unwrap();
1076                    }
1077                }},
1078                names,
1079            )
1080        };
1081
1082        args.context
1083            .attribute_items
1084            .add_item(ident, py_names, cfgs, tokens, 1);
1085
1086        Ok(())
1087    }
1088}