pyo3_stub_gen_derive/gen_stub/
attr.rs

1use indexmap::IndexSet;
2
3use super::{RenamingRule, Signature};
4use proc_macro2::{Delimiter, TokenStream as TokenStream2, TokenTree};
5use quote::{quote, ToTokens, TokenStreamExt};
6use syn::{
7    parenthesized,
8    parse::{Parse, ParseStream},
9    punctuated::Punctuated,
10    Attribute, Expr, ExprLit, Ident, Lit, LitStr, Meta, MetaList, Result, Token, Type,
11};
12
13/// Represents the target of type ignore comments during parsing
14#[derive(Debug, Clone, PartialEq)]
15pub enum IgnoreTarget {
16    /// Ignore all type checking errors `(# type: ignore)`
17    All,
18    /// Ignore specific type checking rules (stored as LitStr during parsing)
19    SpecifiedLits(Vec<LitStr>),
20}
21
22/// Build a static string expression, leaving doc macros for Rust to expand.
23pub fn extract_documents(attrs: &[Attribute]) -> TokenStream2 {
24    let mut parts = Vec::new();
25    let mut literal = String::new();
26    let mut first = true;
27    for attr in attrs {
28        if attr.path().is_ident("doc") {
29            if let Meta::NameValue(syn::MetaNameValue { value, .. }) = &attr.meta {
30                if !first {
31                    literal.push('\n');
32                }
33                first = false;
34                if let Expr::Lit(ExprLit {
35                    lit: Lit::Str(doc), ..
36                }) = value
37                {
38                    // Match PyO3: strip one leading space from literal doc attributes
39                    // (including `///` comments), but preserve macro output verbatim.
40                    let doc = doc.value();
41                    literal.push_str(doc.strip_prefix(' ').unwrap_or(&doc));
42                } else {
43                    parts.push(quote! { #literal });
44                    literal.clear();
45                    // Keep the original spans so include_str! paths remain source-relative.
46                    parts.push(value.to_token_stream());
47                }
48            }
49        }
50    }
51    if parts.is_empty() {
52        quote! { #literal }
53    } else {
54        if !literal.is_empty() {
55            parts.push(quote! { #literal });
56        }
57        quote! { ::core::concat!(#(#parts),*) }
58    }
59}
60
61/// Extract `#[deprecated(...)]` attribute
62pub fn extract_deprecated(attrs: &[Attribute]) -> Option<DeprecatedInfo> {
63    for attr in attrs {
64        if attr.path().is_ident("deprecated") {
65            if let Ok(list) = attr.meta.require_list() {
66                let mut since = None;
67                let mut note = None;
68
69                list.parse_nested_meta(|meta| {
70                    if meta.path.is_ident("since") {
71                        let value = meta.value()?;
72                        let lit: LitStr = value.parse()?;
73                        since = Some(lit.value());
74                    } else if meta.path.is_ident("note") {
75                        let value = meta.value()?;
76                        let lit: LitStr = value.parse()?;
77                        note = Some(lit.value());
78                    }
79                    Ok(())
80                })
81                .ok()?;
82
83                return Some(DeprecatedInfo { since, note });
84            }
85        }
86    }
87    None
88}
89
90/// `#[pyo3(...)]` style attributes appear in `#[pyclass]` and `#[pymethods]` proc-macros
91///
92/// As the reference of PyO3 says:
93///
94/// https://docs.rs/pyo3/latest/pyo3/attr.pyclass.html
95/// > All of these parameters can either be passed directly on the `#[pyclass(...)]` annotation,
96/// > or as one or more accompanying `#[pyo3(...)]` annotations,
97///
98/// `#[pyclass(name = "MyClass", module = "MyModule")]` will be decomposed into
99/// `#[pyclass]` + `#[pyo3(name = "MyClass")]` + `#[pyo3(module = "MyModule")]`,
100/// i.e. two `Attr`s will be created for this case.
101///
102#[derive(Debug, Clone, PartialEq)]
103pub struct DeprecatedInfo {
104    pub since: Option<String>,
105    pub note: Option<String>,
106}
107
108impl ToTokens for DeprecatedInfo {
109    fn to_tokens(&self, tokens: &mut TokenStream2) {
110        let since = self
111            .since
112            .as_ref()
113            .map(|s| quote! { Some(#s) })
114            .unwrap_or_else(|| quote! { None });
115        let note = self
116            .note
117            .as_ref()
118            .map(|n| quote! { Some(#n) })
119            .unwrap_or_else(|| quote! { None });
120        tokens.append_all(quote! {
121            ::pyo3_stub_gen::type_info::DeprecatedInfo {
122                since: #since,
123                note: #note,
124            }
125        })
126    }
127}
128
129#[derive(Debug, Clone, PartialEq)]
130#[expect(clippy::enum_variant_names)]
131pub enum Attr {
132    // Attributes appears in `#[pyo3(...)]` form or its equivalence
133    Name(String),
134    Get,
135    GetAll,
136    Set,
137    SetAll,
138    Module(String),
139    Constructor(Signature),
140    Signature(Signature),
141    RenameAll(RenamingRule),
142    Extends(Type),
143
144    // Comparison and special method attributes for pyclass
145    Eq,
146    Ord,
147    Hash,
148    Str,
149    Subclass,
150
151    // Standalone #[gen_stub(...)] attribute
152    GenStubModule(String),
153
154    // Attributes appears in components within `#[pymethods]`
155    // <https://docs.rs/pyo3/latest/pyo3/attr.pymethods.html>
156    New,
157    Getter(Option<String>),
158    Setter(Option<String>),
159    StaticMethod,
160    ClassMethod,
161    ClassAttr,
162}
163
164pub fn parse_pyo3_attrs(attrs: &[Attribute]) -> Result<Vec<Attr>> {
165    let mut out = Vec::new();
166    for attr in attrs {
167        let mut new = parse_pyo3_attr(attr)?;
168        out.append(&mut new);
169        // Also parse standalone #[gen_stub(module = "...")] attributes
170        if let Some(gen_stub_attr) = parse_gen_stub_module_attr(attr)? {
171            out.push(gen_stub_attr);
172        }
173    }
174    Ok(out)
175}
176
177pub fn parse_pyo3_attr(attr: &Attribute) -> Result<Vec<Attr>> {
178    let mut pyo3_attrs = Vec::new();
179    let path = attr.path();
180    let is_full_path_pyo3_attr = path.segments.len() == 2
181        && path
182            .segments
183            .first()
184            .is_some_and(|seg| seg.ident.eq("pyo3"))
185        && path.segments.last().is_some_and(|seg| {
186            seg.ident.eq("pyclass") || seg.ident.eq("pymethods") || seg.ident.eq("pyfunction")
187        });
188    if path.is_ident("pyclass")
189        || path.is_ident("pymethods")
190        || path.is_ident("pyfunction")
191        || path.is_ident("pyo3")
192        || is_full_path_pyo3_attr
193    {
194        // Inner tokens of `#[pyo3(...)]` may not be nested meta
195        // which can be parsed by `Attribute::parse_nested_meta`
196        // due to the case of `#[pyo3(signature = (...))]`.
197        // https://pyo3.rs/v0.19.1/function/signature
198        if let Meta::List(MetaList { tokens, .. }) = &attr.meta {
199            use TokenTree::*;
200            // `macro_rules!` substitutions (e.g. `#[pyclass(name = $name)]` where
201            // `$name:literal`) wrap the inserted token in an "invisible group"
202            // (`Group { delimiter: None, .. }`). Flattening these first lets a
203            // single pattern arm handle both direct literals and macro-substituted
204            // values uniformly.
205            let tokens: Vec<TokenTree> = flatten_invisible_groups(tokens.clone()).collect();
206            // Since `(...)` part with `signature` becomes `TokenTree::Group`,
207            // we can split entire stream by `,` first, and then pattern match to each cases.
208            for tt in tokens.split(|tt| {
209                if let Punct(p) = tt {
210                    p.as_char() == ','
211                } else {
212                    false
213                }
214            }) {
215                match tt {
216                    [Ident(ident)] => {
217                        if ident == "get" {
218                            pyo3_attrs.push(Attr::Get);
219                        }
220                        if ident == "get_all" {
221                            pyo3_attrs.push(Attr::GetAll);
222                        }
223                        if ident == "set" {
224                            pyo3_attrs.push(Attr::Set);
225                        }
226                        if ident == "set_all" {
227                            pyo3_attrs.push(Attr::SetAll);
228                        }
229                        if ident == "eq" {
230                            pyo3_attrs.push(Attr::Eq);
231                        }
232                        if ident == "ord" {
233                            pyo3_attrs.push(Attr::Ord);
234                        }
235                        if ident == "hash" {
236                            pyo3_attrs.push(Attr::Hash);
237                        }
238                        if ident == "str" {
239                            pyo3_attrs.push(Attr::Str);
240                        }
241                        if ident == "subclass" {
242                            pyo3_attrs.push(Attr::Subclass);
243                        }
244                        // frozen is required by PyO3 when using hash, but doesn't affect stub generation
245                    }
246                    [Ident(ident), Punct(_), Literal(lit)] => {
247                        if ident == "name" {
248                            pyo3_attrs
249                                .push(Attr::Name(lit.to_string().trim_matches('"').to_string()));
250                        }
251                        if ident == "module" {
252                            pyo3_attrs
253                                .push(Attr::Module(lit.to_string().trim_matches('"').to_string()));
254                        }
255                        if ident == "rename_all" {
256                            let name = lit.to_string().trim_matches('"').to_string();
257                            if let Some(renaming_rule) = RenamingRule::try_new(&name) {
258                                pyo3_attrs.push(Attr::RenameAll(renaming_rule));
259                            }
260                        }
261                    }
262                    [Ident(ident), Punct(_), Group(group)] => {
263                        if ident == "signature" {
264                            pyo3_attrs.push(Attr::Signature(syn::parse2(group.to_token_stream())?));
265                        } else if ident == "constructor" {
266                            pyo3_attrs
267                                .push(Attr::Constructor(syn::parse2(group.to_token_stream())?));
268                        }
269                    }
270                    [Ident(ident), Punct(_), Ident(ident2)] => {
271                        if ident == "extends" {
272                            pyo3_attrs.push(Attr::Extends(syn::parse2(ident2.to_token_stream())?));
273                        }
274                    }
275                    _ => {}
276                }
277            }
278        }
279    } else if path.is_ident("new") {
280        pyo3_attrs.push(Attr::New);
281    } else if path.is_ident("staticmethod") {
282        pyo3_attrs.push(Attr::StaticMethod);
283    } else if path.is_ident("classmethod") {
284        pyo3_attrs.push(Attr::ClassMethod);
285    } else if path.is_ident("classattr") {
286        pyo3_attrs.push(Attr::ClassAttr);
287    } else if path.is_ident("getter") {
288        if let Ok(inner) = attr.parse_args::<Ident>() {
289            pyo3_attrs.push(Attr::Getter(Some(inner.to_string())));
290        } else {
291            pyo3_attrs.push(Attr::Getter(None));
292        }
293    } else if path.is_ident("setter") {
294        if let Ok(inner) = attr.parse_args::<Ident>() {
295            pyo3_attrs.push(Attr::Setter(Some(inner.to_string())));
296        } else {
297            pyo3_attrs.push(Attr::Setter(None));
298        }
299    }
300
301    Ok(pyo3_attrs)
302}
303
304/// Flatten `Group { delimiter: None, .. }` tokens (produced by `macro_rules!`
305/// substitutions) into their contents so downstream pattern matching can treat
306/// macro-substituted values the same as written-out literals.
307fn flatten_invisible_groups(tokens: TokenStream2) -> impl Iterator<Item = TokenTree> {
308    tokens
309        .into_iter()
310        .flat_map(|tt| -> Box<dyn Iterator<Item = TokenTree>> {
311            match tt {
312                TokenTree::Group(g) if g.delimiter() == Delimiter::None => {
313                    Box::new(flatten_invisible_groups(g.stream()))
314                }
315                other => Box::new(std::iter::once(other)),
316            }
317        })
318}
319
320/// Parse standalone `#[gen_stub(module = "...")]` attribute for module override
321pub fn parse_gen_stub_module_attr(attr: &Attribute) -> Result<Option<Attr>> {
322    let path = attr.path();
323    if path.is_ident("gen_stub") {
324        // Parse the inner tokens to find module = "..."
325        if let Meta::List(MetaList { tokens, .. }) = &attr.meta {
326            use TokenTree::*;
327            // See note in `parse_pyo3_attr` about invisible groups.
328            let tokens: Vec<TokenTree> = flatten_invisible_groups(tokens.clone()).collect();
329
330            // Split by comma and look for module = "..."
331            for tt in tokens.split(|tt| {
332                if let Punct(p) = tt {
333                    p.as_char() == ','
334                } else {
335                    false
336                }
337            }) {
338                match tt {
339                    [Ident(ident), Punct(_), Literal(lit)] if ident == "module" => {
340                        return Ok(Some(Attr::GenStubModule(
341                            lit.to_string().trim_matches('"').to_string(),
342                        )));
343                    }
344                    _ => {}
345                }
346            }
347        }
348    }
349    Ok(None)
350}
351
352#[derive(Debug, Clone, PartialEq)]
353pub enum StubGenAttr {
354    /// Default value for getter
355    Default(Expr),
356    /// Skip a function in #[pymethods]
357    Skip,
358    /// Override the python type for a function argument or return type
359    OverrideType(OverrideTypeAttribute),
360    /// Type checker rules to ignore for this function/method
361    TypeIgnore(IgnoreTarget),
362}
363
364pub fn prune_attrs(attrs: &mut Vec<Attribute>) {
365    attrs.retain(|attr| !attr.path().is_ident("gen_stub"));
366}
367
368pub fn parse_gen_stub_override_type(attrs: &[Attribute]) -> Result<Option<OverrideTypeAttribute>> {
369    for attr in parse_gen_stub_attrs(attrs, AttributeLocation::Argument, None)? {
370        if let StubGenAttr::OverrideType(attr) = attr {
371            return Ok(Some(attr));
372        }
373    }
374    Ok(None)
375}
376
377pub fn parse_gen_stub_override_return_type(
378    attrs: &[Attribute],
379) -> Result<Option<OverrideTypeAttribute>> {
380    for attr in parse_gen_stub_attrs(attrs, AttributeLocation::Function, None)? {
381        if let StubGenAttr::OverrideType(attr) = attr {
382            return Ok(Some(attr));
383        }
384    }
385    Ok(None)
386}
387
388pub fn parse_gen_stub_default(attrs: &[Attribute]) -> Result<Option<Expr>> {
389    for attr in parse_gen_stub_attrs(attrs, AttributeLocation::Function, None)? {
390        if let StubGenAttr::Default(default) = attr {
391            return Ok(Some(default));
392        }
393    }
394    Ok(None)
395}
396pub fn parse_gen_stub_skip(attrs: &[Attribute]) -> Result<bool> {
397    let skip = parse_gen_stub_attrs(
398        attrs,
399        AttributeLocation::Field,
400        Some(&["override_return_type", "default"]),
401    )?
402    .iter()
403    .any(|attr| matches!(attr, StubGenAttr::Skip));
404    Ok(skip)
405}
406
407pub fn parse_gen_stub_type_ignore(attrs: &[Attribute]) -> Result<Option<IgnoreTarget>> {
408    // Try Function location first (for regular functions)
409    for attr in parse_gen_stub_attrs(attrs, AttributeLocation::Function, None)? {
410        if let StubGenAttr::TypeIgnore(target) = attr {
411            return Ok(Some(target));
412        }
413    }
414    // Try Field location (for methods in #[pymethods] blocks)
415    for attr in parse_gen_stub_attrs(attrs, AttributeLocation::Field, None)? {
416        if let StubGenAttr::TypeIgnore(target) = attr {
417            return Ok(Some(target));
418        }
419    }
420    Ok(None)
421}
422
423fn parse_gen_stub_attrs(
424    attrs: &[Attribute],
425    location: AttributeLocation,
426    ignored_idents: Option<&[&str]>,
427) -> Result<Vec<StubGenAttr>> {
428    let mut out = Vec::new();
429    for attr in attrs {
430        let mut new = parse_gen_stub_attr(attr, location, ignored_idents.unwrap_or(&[]))?;
431        out.append(&mut new);
432    }
433    Ok(out)
434}
435
436fn parse_gen_stub_attr(
437    attr: &Attribute,
438    location: AttributeLocation,
439    ignored_idents: &[&str],
440) -> Result<Vec<StubGenAttr>> {
441    let mut gen_stub_attrs = Vec::new();
442    let path = attr.path();
443    if path.is_ident("gen_stub") {
444        attr.parse_args_with(|input: ParseStream| {
445            while !input.is_empty() {
446                let ident: Ident = input.parse()?;
447                let ignored_ident = ignored_idents.iter().any(|other| ident == other);
448                if (ident == "override_type"
449                    && (location == AttributeLocation::Argument || ignored_ident))
450                    || (ident == "override_return_type"
451                        && (location == AttributeLocation::Function || location == AttributeLocation::Field || ignored_ident))
452                {
453                    let content;
454                    parenthesized!(content in input);
455                    let override_attr: OverrideTypeAttribute = content.parse()?;
456                    gen_stub_attrs.push(StubGenAttr::OverrideType(override_attr));
457                } else if ident == "skip" && (location == AttributeLocation::Field || ignored_ident)
458                {
459                    gen_stub_attrs.push(StubGenAttr::Skip);
460                } else if ident == "default"
461                    && input.peek(Token![=])
462                    && (location == AttributeLocation::Field || location == AttributeLocation::Function || ignored_ident)
463                {
464                    input.parse::<Token![=]>()?;
465                    gen_stub_attrs.push(StubGenAttr::Default(input.parse()?));
466                } else if ident == "type_ignore"
467                    && (location == AttributeLocation::Function || location == AttributeLocation::Field || ignored_ident)
468                {
469                    // Handle two cases:
470                    // 1. type_ignore (without equals) -> IgnoreTarget::All
471                    // 2. type_ignore = [...] -> IgnoreTarget::Specified(rules)
472                    if input.peek(Token![=]) {
473                        input.parse::<Token![=]>()?;
474                        // Parse array of rule names
475                        let content;
476                        syn::bracketed!(content in input);
477                        let rules = Punctuated::<LitStr, Token![,]>::parse_terminated(&content)?;
478
479                        // Validate: empty Specified should be an error
480                        if rules.is_empty() {
481                            return Err(syn::Error::new(
482                                ident.span(),
483                                "type_ignore with empty array is not allowed. Use type_ignore without equals for catch-all, or specify rules in the array."
484                            ));
485                        }
486
487                        // Store the rules as LitStr for now, will be converted to strings during code generation
488                        let rule_lits: Vec<LitStr> = rules.into_iter().collect();
489                        gen_stub_attrs.push(StubGenAttr::TypeIgnore(IgnoreTarget::SpecifiedLits(rule_lits)));
490                    } else {
491                        // No equals sign means catch-all
492                        gen_stub_attrs.push(StubGenAttr::TypeIgnore(IgnoreTarget::All));
493                    }
494                } else if ident == "override_type" {
495                    return Err(syn::Error::new(
496                        ident.span(),
497                        "`override_type(...)` is only valid in argument position".to_string(),
498                    ));
499                } else if ident == "override_return_type" {
500                    return Err(syn::Error::new(
501                        ident.span(),
502                        "`override_return_type(...)` is only valid in function or method position"
503                            .to_string(),
504                    ));
505                } else if ident == "skip" {
506                    return Err(syn::Error::new(
507                        ident.span(),
508                        "`skip` is only valid in field position".to_string(),
509                    ));
510                } else if ident == "default" {
511                    return Err(syn::Error::new(
512                        ident.span(),
513                        "`default=xxx` is only valid in field or function position".to_string(),
514                    ));
515                } else if ident == "type_ignore" {
516                    return Err(syn::Error::new(
517                        ident.span(),
518                        "`type_ignore` or `type_ignore=[...]` is only valid in function or method position".to_string(),
519                    ));
520                } else if location == AttributeLocation::Argument {
521                    return Err(syn::Error::new(
522                        ident.span(),
523                        format!("Unsupported keyword `{ident}`, valid is `override_type(...)`"),
524                    ));
525                } else if location == AttributeLocation::Field {
526                    return Err(syn::Error::new(
527                        ident.span(),
528                        format!("Unsupported keyword `{ident}`, valid is `default=xxx`, `skip`, `override_return_type(...)`, `type_ignore`, or `type_ignore=[...]`"),
529                    ));
530                } else if location == AttributeLocation::Function {
531                    return Err(syn::Error::new(
532                        ident.span(),
533                        format!(
534                            "Unsupported keyword `{ident}`, valid is `default=xxx`, `override_return_type(...)`, `type_ignore`, or `type_ignore=[...]`"
535                        ),
536                    ));
537                } else {
538                    return Err(syn::Error::new(
539                        ident.span(),
540                        format!("Unsupported keyword `{ident}`"),
541                    ));
542                }
543                if input.peek(Token![,]) {
544                    input.parse::<Token![,]>()?;
545                } else {
546                    break;
547                }
548            }
549            Ok(())
550        })?;
551    }
552    Ok(gen_stub_attrs)
553}
554
555#[derive(Debug, Clone, Copy, PartialEq)]
556pub(crate) enum AttributeLocation {
557    Argument,
558    Field,
559    Function,
560}
561
562#[derive(Debug, Clone, PartialEq)]
563pub struct OverrideTypeAttribute {
564    pub(crate) type_repr: String,
565    pub(crate) imports: IndexSet<String>,
566}
567
568mod kw {
569    syn::custom_keyword!(type_repr);
570    syn::custom_keyword!(imports);
571    syn::custom_keyword!(override_type);
572}
573
574impl Parse for OverrideTypeAttribute {
575    fn parse(input: ParseStream) -> Result<Self> {
576        let mut type_repr = None;
577        let mut imports = IndexSet::new();
578
579        while !input.is_empty() {
580            let lookahead = input.lookahead1();
581
582            if lookahead.peek(kw::type_repr) {
583                input.parse::<kw::type_repr>()?;
584                input.parse::<Token![=]>()?;
585                type_repr = Some(input.parse::<LitStr>()?);
586            } else if lookahead.peek(kw::imports) {
587                input.parse::<kw::imports>()?;
588                input.parse::<Token![=]>()?;
589
590                let content;
591                parenthesized!(content in input);
592                let parsed_imports = Punctuated::<LitStr, Token![,]>::parse_terminated(&content)?;
593                imports = parsed_imports.into_iter().collect();
594            } else {
595                return Err(lookahead.error());
596            }
597
598            if !input.is_empty() {
599                input.parse::<Token![,]>()?;
600            }
601        }
602
603        Ok(OverrideTypeAttribute {
604            type_repr: type_repr
605                .ok_or_else(|| input.error("missing type_repr"))?
606                .value(),
607            imports: imports.iter().map(|i| i.value()).collect(),
608        })
609    }
610}
611
612/// Common attributes for `#[gen_stub_pyclass(...)]`, `#[gen_stub_pyclass_enum(...)]`,
613/// and `#[gen_stub_pyclass_complex_enum(...)]` macros
614#[derive(Default)]
615pub struct PyClassAttr {
616    pub skip_stub_type: bool,
617    pub module: Option<String>,
618}
619
620impl Parse for PyClassAttr {
621    fn parse(input: ParseStream) -> Result<Self> {
622        let mut skip_stub_type = false;
623        let mut module = None;
624
625        // Parse comma-separated flags
626        while !input.is_empty() {
627            let key: Ident = input.parse()?;
628
629            match key.to_string().as_str() {
630                "skip_stub_type" => {
631                    skip_stub_type = true;
632                }
633                "module" => {
634                    let _: Token![=] = input.parse()?;
635                    let value: LitStr = input.parse()?;
636                    module = Some(value.value());
637                }
638                _ => {
639                    return Err(syn::Error::new(
640                        key.span(),
641                        format!("Unknown parameter: {}", key),
642                    ));
643                }
644            }
645
646            // Check for comma separator
647            if input.peek(Token![,]) {
648                let _: Token![,] = input.parse()?;
649            } else {
650                break;
651            }
652        }
653
654        Ok(Self {
655            skip_stub_type,
656            module,
657        })
658    }
659}
660
661#[cfg(test)]
662mod test {
663    use super::*;
664    use syn::{parse_str, Fields, ItemFn, ItemStruct, PatType};
665
666    #[test]
667    fn test_parse_pyo3_attr() -> Result<()> {
668        let item: ItemStruct = parse_str(
669            r#"
670            #[pyclass(mapping, module = "my_module", name = "Placeholder")]
671            #[pyo3(rename_all = "SCREAMING_SNAKE_CASE")]
672            pub struct PyPlaceholder {
673                #[pyo3(get)]
674                pub name: String,
675            }
676            "#,
677        )?;
678        // `#[pyclass]` part
679        let attrs = parse_pyo3_attrs(&item.attrs)?;
680        assert_eq!(
681            attrs,
682            vec![
683                Attr::Module("my_module".to_string()),
684                Attr::Name("Placeholder".to_string()),
685                Attr::RenameAll(RenamingRule::ScreamingSnakeCase),
686            ]
687        );
688
689        // `#[pyo3(get)]` part
690        if let Fields::Named(fields) = item.fields {
691            let attrs = parse_pyo3_attr(&fields.named[0].attrs[0])?;
692            assert_eq!(attrs, vec![Attr::Get]);
693        } else {
694            unreachable!()
695        }
696        Ok(())
697    }
698
699    #[test]
700    fn test_parse_pyo3_attr_full_path() -> Result<()> {
701        let item: ItemStruct = parse_str(
702            r#"
703            #[pyo3::pyclass(mapping, module = "my_module", name = "Placeholder")]
704            pub struct PyPlaceholder {
705                #[pyo3(get)]
706                pub name: String,
707            }
708            "#,
709        )?;
710        // `#[pyclass]` part
711        let attrs = parse_pyo3_attr(&item.attrs[0])?;
712        assert_eq!(
713            attrs,
714            vec![
715                Attr::Module("my_module".to_string()),
716                Attr::Name("Placeholder".to_string())
717            ]
718        );
719
720        // `#[pyo3(get)]` part
721        if let Fields::Named(fields) = item.fields {
722            let attrs = parse_pyo3_attr(&fields.named[0].attrs[0])?;
723            assert_eq!(attrs, vec![Attr::Get]);
724        } else {
725            unreachable!()
726        }
727        Ok(())
728    }
729    /// Build a `Vec<Attribute>` whose tokens contain an "invisible group"
730    /// (`Group { delimiter: None, .. }`) for the value of a key, simulating
731    /// what `macro_rules!` produces when substituting a meta-variable into an
732    /// attribute argument list (e.g. `#[pyclass(name = $name)]`).
733    fn attrs_with_invisible_group(
734        attr_path: TokenStream2,
735        prefix: TokenStream2,
736        value: TokenStream2,
737    ) -> Vec<Attribute> {
738        let invisible = TokenTree::Group(proc_macro2::Group::new(Delimiter::None, value));
739        let item: ItemStruct = syn::parse2(quote! {
740            #[#attr_path(#prefix = #invisible)]
741            struct Dummy;
742        })
743        .unwrap();
744        item.attrs
745    }
746
747    #[test]
748    fn test_parse_pyo3_attr_name_from_macro_substitution() -> Result<()> {
749        // Simulates `macro_rules! { ($n:literal) => { #[pyclass(name = $n)] ... } }`.
750        let attrs = attrs_with_invisible_group(quote!(pyclass), quote!(name), quote!("FromMacro"));
751        let parsed = parse_pyo3_attrs(&attrs)?;
752        assert_eq!(parsed, vec![Attr::Name("FromMacro".to_string())]);
753        Ok(())
754    }
755
756    #[test]
757    fn test_parse_pyo3_attr_module_from_macro_substitution() -> Result<()> {
758        let attrs =
759            attrs_with_invisible_group(quote!(pyclass), quote!(module), quote!("my.mod.path"));
760        let parsed = parse_pyo3_attrs(&attrs)?;
761        assert_eq!(parsed, vec![Attr::Module("my.mod.path".to_string())]);
762        Ok(())
763    }
764
765    #[test]
766    fn test_parse_pyo3_attr_rename_all_from_macro_substitution() -> Result<()> {
767        let attrs = attrs_with_invisible_group(
768            quote!(pyo3),
769            quote!(rename_all),
770            quote!("SCREAMING_SNAKE_CASE"),
771        );
772        let parsed = parse_pyo3_attrs(&attrs)?;
773        assert_eq!(
774            parsed,
775            vec![Attr::RenameAll(RenamingRule::ScreamingSnakeCase)]
776        );
777        Ok(())
778    }
779
780    #[test]
781    fn test_parse_gen_stub_module_attr_from_macro_substitution() -> Result<()> {
782        let attrs =
783            attrs_with_invisible_group(quote!(gen_stub), quote!(module), quote!("explicit.mod"));
784        // `parse_pyo3_attrs` also dispatches to `parse_gen_stub_module_attr`.
785        let parsed = parse_pyo3_attrs(&attrs)?;
786        assert_eq!(
787            parsed,
788            vec![Attr::GenStubModule("explicit.mod".to_string())]
789        );
790        Ok(())
791    }
792
793    #[test]
794    fn test_parse_gen_stub_field_attr() -> Result<()> {
795        let item: ItemStruct = parse_str(
796            r#"
797            pub struct PyPlaceholder {
798                #[gen_stub(default = String::from("foo"), skip)]
799                pub field0: String,
800                #[gen_stub(skip)]
801                pub field1: String,
802                #[gen_stub(default = 1+2)]
803                pub field2: usize,
804            }
805            "#,
806        )?;
807        let fields: Vec<_> = item.fields.into_iter().collect();
808        let field0_attrs = parse_gen_stub_attrs(&fields[0].attrs, AttributeLocation::Field, None)?;
809        if let StubGenAttr::Default(expr) = &field0_attrs[0] {
810            assert_eq!(
811                expr.to_token_stream().to_string(),
812                "String :: from (\"foo\")"
813            );
814        } else {
815            panic!("attr should be Default");
816        };
817        assert_eq!(&StubGenAttr::Skip, &field0_attrs[1]);
818        let field1_attrs = parse_gen_stub_attrs(&fields[1].attrs, AttributeLocation::Field, None)?;
819        assert_eq!(vec![StubGenAttr::Skip], field1_attrs);
820        let field2_attrs = parse_gen_stub_attrs(&fields[2].attrs, AttributeLocation::Field, None)?;
821        if let StubGenAttr::Default(expr) = &field2_attrs[0] {
822            assert_eq!(expr.to_token_stream().to_string(), "1 + 2");
823        } else {
824            panic!("attr should be Default");
825        };
826        Ok(())
827    }
828    #[test]
829    fn test_parse_gen_stub_override_type_attr() -> Result<()> {
830        let item: ItemFn = parse_str(
831            r#"
832            #[gen_stub_pyfunction]
833            #[pyfunction]
834            #[gen_stub(override_return_type(type_repr="typing.Never", imports=("typing")))]
835            fn say_hello_forever<'a>(
836                #[gen_stub(override_type(type_repr="collections.abc.Callable[[str]]", imports=("collections.abc")))]
837                cb: Bound<'a, PyAny>,
838            ) -> PyResult<()> {
839                loop {
840                    cb.call1(("Hello!",))?;
841                }
842            }
843            "#,
844        )?;
845        let fn_attrs = parse_gen_stub_attrs(&item.attrs, AttributeLocation::Function, None)?;
846        assert_eq!(fn_attrs.len(), 1);
847        if let StubGenAttr::OverrideType(expr) = &fn_attrs[0] {
848            assert_eq!(
849                *expr,
850                OverrideTypeAttribute {
851                    type_repr: "typing.Never".into(),
852                    imports: IndexSet::from(["typing".into()])
853                }
854            );
855        } else {
856            panic!("attr should be OverrideType");
857        };
858        if let syn::FnArg::Typed(PatType { attrs, .. }) = &item.sig.inputs[0] {
859            let arg_attrs = parse_gen_stub_attrs(attrs, AttributeLocation::Argument, None)?;
860            assert_eq!(arg_attrs.len(), 1);
861            if let StubGenAttr::OverrideType(expr) = &arg_attrs[0] {
862                assert_eq!(
863                    *expr,
864                    OverrideTypeAttribute {
865                        type_repr: "collections.abc.Callable[[str]]".into(),
866                        imports: IndexSet::from(["collections.abc".into()])
867                    }
868                );
869            } else {
870                panic!("attr should be OverrideType");
871            };
872        }
873        Ok(())
874    }
875}