rustc_attr_parsing/attributes/
proc_macro_attrs.rs

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