Skip to main content

rustc_attr_parsing/attributes/
proc_macro_attrs.rs

1use rustc_hir::lints::AttributeLintKind;
2use rustc_session::lint::builtin::AMBIGUOUS_DERIVE_HELPERS;
3
4use super::prelude::*;
5
6const PROC_MACRO_ALLOWED_TARGETS: AllowedTargets =
7    AllowedTargets::AllowList(&[Allow(Target::Fn), Warn(Target::Crate), Warn(Target::MacroCall)]);
8
9pub(crate) struct ProcMacroParser;
10impl<S: Stage> NoArgsAttributeParser<S> for ProcMacroParser {
11    const PATH: &[Symbol] = &[sym::proc_macro];
12    const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
13    const ALLOWED_TARGETS: AllowedTargets = PROC_MACRO_ALLOWED_TARGETS;
14    const CREATE: fn(Span) -> AttributeKind = AttributeKind::ProcMacro;
15}
16
17pub(crate) struct ProcMacroAttributeParser;
18impl<S: Stage> NoArgsAttributeParser<S> for ProcMacroAttributeParser {
19    const PATH: &[Symbol] = &[sym::proc_macro_attribute];
20    const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
21    const ALLOWED_TARGETS: AllowedTargets = PROC_MACRO_ALLOWED_TARGETS;
22    const CREATE: fn(Span) -> AttributeKind = AttributeKind::ProcMacroAttribute;
23}
24
25pub(crate) struct ProcMacroDeriveParser;
26impl<S: Stage> SingleAttributeParser<S> for ProcMacroDeriveParser {
27    const PATH: &[Symbol] = &[sym::proc_macro_derive];
28    const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
29    const ALLOWED_TARGETS: AllowedTargets = PROC_MACRO_ALLOWED_TARGETS;
30    const TEMPLATE: AttributeTemplate = ::rustc_feature::AttributeTemplate {
    word: false,
    list: Some(&["TraitName", "TraitName, attributes(name1, name2, ...)"]),
    one_of: &[],
    name_value_str: None,
    docs: Some("https://doc.rust-lang.org/reference/procedural-macros.html#derive-macros"),
}template!(
31        List: &["TraitName", "TraitName, attributes(name1, name2, ...)"],
32        "https://doc.rust-lang.org/reference/procedural-macros.html#derive-macros"
33    );
34
35    fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
36        let (trait_name, helper_attrs) = parse_derive_like(cx, args, true)?;
37        Some(AttributeKind::ProcMacroDerive {
38            trait_name: trait_name.expect("Trait name is mandatory, so it is present"),
39            helper_attrs,
40            span: cx.attr_span,
41        })
42    }
43}
44
45pub(crate) struct RustcBuiltinMacroParser;
46impl<S: Stage> SingleAttributeParser<S> for RustcBuiltinMacroParser {
47    const PATH: &[Symbol] = &[sym::rustc_builtin_macro];
48    const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
49    const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::MacroDef)]);
50    const TEMPLATE: AttributeTemplate =
51        ::rustc_feature::AttributeTemplate {
    word: false,
    list: Some(&["TraitName", "TraitName, attributes(name1, name2, ...)"]),
    one_of: &[],
    name_value_str: None,
    docs: None,
}template!(List: &["TraitName", "TraitName, attributes(name1, name2, ...)"]);
52
53    fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
54        let (builtin_name, helper_attrs) = parse_derive_like(cx, args, false)?;
55        Some(AttributeKind::RustcBuiltinMacro { builtin_name, helper_attrs, span: cx.attr_span })
56    }
57}
58
59fn parse_derive_like<S: Stage>(
60    cx: &mut AcceptContext<'_, '_, S>,
61    args: &ArgParser,
62    trait_name_mandatory: bool,
63) -> Option<(Option<Symbol>, ThinVec<Symbol>)> {
64    let Some(list) = args.list() else {
65        // For #[rustc_builtin_macro], it is permitted to leave out the trait name
66        if args.no_args().is_ok() && !trait_name_mandatory {
67            return Some((None, ThinVec::new()));
68        }
69        let attr_span = cx.attr_span;
70        cx.adcx().expected_list(attr_span, args);
71        return None;
72    };
73    let mut items = list.mixed();
74
75    // Parse the name of the trait that is derived.
76    let Some(trait_attr) = items.next() else {
77        cx.adcx().expected_at_least_one_argument(list.span);
78        return None;
79    };
80    let Some(trait_attr) = trait_attr.meta_item() else {
81        cx.adcx().unexpected_literal(trait_attr.span());
82        return None;
83    };
84    let Some(trait_ident) = trait_attr.path().word() else {
85        cx.adcx().expected_identifier(trait_attr.path().span());
86        return None;
87    };
88    if !trait_ident.name.can_be_raw() {
89        cx.adcx().expected_identifier(trait_ident.span);
90        return None;
91    }
92    if let Err(e) = trait_attr.args().no_args() {
93        cx.adcx().expected_no_args(e);
94        return None;
95    };
96
97    // Parse optional attributes
98    let mut attributes = ThinVec::new();
99    if let Some(attrs) = items.next() {
100        let Some(attr_list) = attrs.meta_item() else {
101            cx.adcx().unexpected_literal(attrs.span());
102            return None;
103        };
104        if !attr_list.path().word_is(sym::attributes) {
105            cx.adcx().expected_specific_argument(attrs.span(), &[sym::attributes]);
106            return None;
107        }
108        let Some(attr_list) = attr_list.args().list() else {
109            cx.adcx().expected_list(attrs.span(), attr_list.args());
110            return None;
111        };
112
113        // Parse item in `attributes(...)` argument
114        for attr in attr_list.mixed() {
115            let Some(attr) = attr.meta_item() else {
116                cx.adcx().expected_identifier(attr.span());
117                return None;
118            };
119            if let Err(e) = attr.args().no_args() {
120                cx.adcx().expected_no_args(e);
121                return None;
122            };
123            let Some(ident) = attr.path().word() else {
124                cx.adcx().expected_identifier(attr.path().span());
125                return None;
126            };
127            if !ident.name.can_be_raw() {
128                cx.adcx().expected_identifier(ident.span);
129                return None;
130            }
131            if rustc_feature::is_builtin_attr_name(ident.name) {
132                cx.emit_lint(
133                    AMBIGUOUS_DERIVE_HELPERS,
134                    AttributeLintKind::AmbiguousDeriveHelpers,
135                    ident.span,
136                );
137            }
138            attributes.push(ident.name);
139        }
140    }
141
142    // If anything else is specified, we should reject it
143    if let Some(next) = items.next() {
144        cx.adcx().expected_no_args(next.span());
145    }
146
147    Some((Some(trait_ident.name), attributes))
148}