rustc_attr_parsing/attributes/
macro_attrs.rs

1use rustc_hir::attrs::MacroUseArgs;
2use rustc_session::lint::builtin::INVALID_MACRO_EXPORT_ARGUMENTS;
3
4use super::prelude::*;
5
6pub(crate) struct MacroEscapeParser;
7impl<S: Stage> NoArgsAttributeParser<S> for MacroEscapeParser {
8    const PATH: &[Symbol] = &[sym::macro_escape];
9    const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
10    const ALLOWED_TARGETS: AllowedTargets = MACRO_USE_ALLOWED_TARGETS;
11    const CREATE: fn(Span) -> AttributeKind = AttributeKind::MacroEscape;
12}
13
14/// `#[macro_use]` attributes can either:
15/// - Use all macros from a crate, if provided without arguments
16/// - Use specific macros from a crate, if provided with arguments `#[macro_use(macro1, macro2)]`
17/// A warning should be provided if an use all is combined with specific uses, or if multiple use-alls are used.
18#[derive(Default)]
19pub(crate) struct MacroUseParser {
20    state: MacroUseArgs,
21
22    /// Spans of all `#[macro_use]` arguments with arguments, used for linting
23    uses_attr_spans: ThinVec<Span>,
24    /// If `state` is `UseSpecific`, stores the span of the first `#[macro_use]` argument, used as the span for this attribute
25    /// If `state` is `UseAll`, stores the span of the first `#[macro_use]` arguments without arguments
26    first_span: Option<Span>,
27}
28
29const MACRO_USE_TEMPLATE: AttributeTemplate = template!(
30    Word, List: &["name1, name2, ..."],
31    "https://doc.rust-lang.org/reference/macros-by-example.html#the-macro_use-attribute"
32);
33const MACRO_USE_ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowListWarnRest(&[
34    Allow(Target::Mod),
35    Allow(Target::ExternCrate),
36    Allow(Target::Crate),
37    Error(Target::WherePredicate),
38]);
39
40impl<S: Stage> AttributeParser<S> for MacroUseParser {
41    const ATTRIBUTES: AcceptMapping<Self, S> = &[(
42        &[sym::macro_use],
43        MACRO_USE_TEMPLATE,
44        |group: &mut Self, cx: &mut AcceptContext<'_, '_, S>, args| {
45            let span = cx.attr_span;
46            group.first_span.get_or_insert(span);
47            match args {
48                ArgParser::NoArgs => {
49                    match group.state {
50                        MacroUseArgs::UseAll => {
51                            let first_span = group.first_span.expect(
52                                "State is UseAll is some so this is not the first attribute",
53                            );
54                            // Since there is a `#[macro_use]` import already, give a warning
55                            cx.warn_unused_duplicate(first_span, span);
56                        }
57                        MacroUseArgs::UseSpecific(_) => {
58                            group.state = MacroUseArgs::UseAll;
59                            group.first_span = Some(span);
60                            // If there is a `#[macro_use]` attribute, warn on all `#[macro_use(...)]` attributes since everything is already imported
61                            for specific_use in group.uses_attr_spans.drain(..) {
62                                cx.warn_unused_duplicate(span, specific_use);
63                            }
64                        }
65                    }
66                }
67                ArgParser::List(list) => {
68                    if list.is_empty() {
69                        cx.warn_empty_attribute(list.span);
70                        return;
71                    }
72
73                    match &mut group.state {
74                        MacroUseArgs::UseAll => {
75                            let first_span = group.first_span.expect(
76                                "State is UseAll is some so this is not the first attribute",
77                            );
78                            cx.warn_unused_duplicate(first_span, span);
79                        }
80                        MacroUseArgs::UseSpecific(arguments) => {
81                            // Store here so if we encounter a `UseAll` later we can still lint this attribute
82                            group.uses_attr_spans.push(cx.attr_span);
83
84                            for item in list.mixed() {
85                                let Some(item) = item.meta_item() else {
86                                    cx.expected_identifier(item.span());
87                                    continue;
88                                };
89                                if let Err(err_span) = item.args().no_args() {
90                                    cx.expected_no_args(err_span);
91                                    continue;
92                                }
93                                let Some(item) = item.path().word() else {
94                                    cx.expected_identifier(item.span());
95                                    continue;
96                                };
97                                arguments.push(item);
98                            }
99                        }
100                    }
101                }
102                ArgParser::NameValue(nv) => {
103                    cx.expected_list_or_no_args(nv.args_span());
104                }
105            }
106        },
107    )];
108    const ALLOWED_TARGETS: AllowedTargets = MACRO_USE_ALLOWED_TARGETS;
109
110    fn finalize(self, _cx: &FinalizeContext<'_, '_, S>) -> Option<AttributeKind> {
111        Some(AttributeKind::MacroUse { span: self.first_span?, arguments: self.state })
112    }
113}
114
115pub(crate) struct AllowInternalUnsafeParser;
116
117impl<S: Stage> NoArgsAttributeParser<S> for AllowInternalUnsafeParser {
118    const PATH: &[Symbol] = &[sym::allow_internal_unsafe];
119    const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Ignore;
120    const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
121        Allow(Target::Fn),
122        Allow(Target::MacroDef),
123        Warn(Target::Field),
124        Warn(Target::Arm),
125    ]);
126    const CREATE: fn(Span) -> AttributeKind = |span| AttributeKind::AllowInternalUnsafe(span);
127}
128
129pub(crate) struct MacroExportParser;
130
131impl<S: Stage> SingleAttributeParser<S> for MacroExportParser {
132    const PATH: &[Symbol] = &[sym::macro_export];
133    const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepOutermost;
134    const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
135    const TEMPLATE: AttributeTemplate = template!(Word, List: &["local_inner_macros"]);
136    const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowListWarnRest(&[
137        Allow(Target::MacroDef),
138        Error(Target::WherePredicate),
139        Error(Target::Crate),
140    ]);
141
142    fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
143        let local_inner_macros = match args {
144            ArgParser::NoArgs => false,
145            ArgParser::List(list) => {
146                let Some(l) = list.single() else {
147                    cx.warn_ill_formed_attribute_input(INVALID_MACRO_EXPORT_ARGUMENTS);
148                    return None;
149                };
150                match l.meta_item().and_then(|i| i.path().word_sym()) {
151                    Some(sym::local_inner_macros) => true,
152                    _ => {
153                        cx.warn_ill_formed_attribute_input(INVALID_MACRO_EXPORT_ARGUMENTS);
154                        return None;
155                    }
156                }
157            }
158            ArgParser::NameValue(nv) => {
159                cx.expected_list_or_no_args(nv.args_span());
160                return None;
161            }
162        };
163        Some(AttributeKind::MacroExport { span: cx.attr_span, local_inner_macros })
164    }
165}