rustc_attr_parsing/attributes/
mod.rs

1//! This module defines traits for attribute parsers, little state machines that recognize and parse
2//! attributes out of a longer list of attributes. The main trait is called [`AttributeParser`].
3//! You can find more docs about [`AttributeParser`]s on the trait itself.
4//! However, for many types of attributes, implementing [`AttributeParser`] is not necessary.
5//! It allows for a lot of flexibility you might not want.
6//!
7//! Specifically, you might not care about managing the state of your [`AttributeParser`]
8//! state machine yourself. In this case you can choose to implement:
9//!
10//! - [`SingleAttributeParser`](crate::attributes::SingleAttributeParser): makes it easy to implement an attribute which should error if it
11//! appears more than once in a list of attributes
12//! - [`CombineAttributeParser`](crate::attributes::CombineAttributeParser): makes it easy to implement an attribute which should combine the
13//! contents of attributes, if an attribute appear multiple times in a list
14//!
15//! Attributes should be added to `crate::context::ATTRIBUTE_PARSERS` to be parsed.
16
17use std::marker::PhantomData;
18
19use rustc_feature::{AttributeTemplate, template};
20use rustc_hir::attrs::AttributeKind;
21use rustc_span::{Span, Symbol};
22use thin_vec::ThinVec;
23
24use crate::context::{AcceptContext, FinalizeContext, Stage};
25use crate::parser::ArgParser;
26use crate::session_diagnostics::UnusedMultiple;
27use crate::target_checking::AllowedTargets;
28
29/// All the parsers require roughly the same imports, so this prelude has most of the often-needed ones.
30mod prelude;
31
32pub(crate) mod allow_unstable;
33pub(crate) mod body;
34pub(crate) mod cfg;
35pub(crate) mod cfg_select;
36pub(crate) mod cfi_encoding;
37pub(crate) mod codegen_attrs;
38pub(crate) mod confusables;
39pub(crate) mod crate_level;
40pub(crate) mod debugger;
41pub(crate) mod deprecation;
42pub(crate) mod doc;
43pub(crate) mod dummy;
44pub(crate) mod inline;
45pub(crate) mod instruction_set;
46pub(crate) mod link_attrs;
47pub(crate) mod lint_helpers;
48pub(crate) mod loop_match;
49pub(crate) mod macro_attrs;
50pub(crate) mod must_not_suspend;
51pub(crate) mod must_use;
52pub(crate) mod no_implicit_prelude;
53pub(crate) mod no_link;
54pub(crate) mod non_exhaustive;
55pub(crate) mod path;
56pub(crate) mod pin_v2;
57pub(crate) mod proc_macro_attrs;
58pub(crate) mod prototype;
59pub(crate) mod repr;
60pub(crate) mod rustc_internal;
61pub(crate) mod semantics;
62pub(crate) mod stability;
63pub(crate) mod test_attrs;
64pub(crate) mod traits;
65pub(crate) mod transparency;
66pub(crate) mod util;
67
68type AcceptFn<T, S> = for<'sess> fn(&mut T, &mut AcceptContext<'_, 'sess, S>, &ArgParser);
69type AcceptMapping<T, S> = &'static [(&'static [Symbol], AttributeTemplate, AcceptFn<T, S>)];
70
71/// An [`AttributeParser`] is a type which searches for syntactic attributes.
72///
73/// Parsers are often tiny state machines that gets to see all syntactical attributes on an item.
74/// [`Default::default`] creates a fresh instance that sits in some kind of initial state, usually that the
75/// attribute it is looking for was not yet seen.
76///
77/// Then, it defines what paths this group will accept in [`AttributeParser::ATTRIBUTES`].
78/// These are listed as pairs, of symbols and function pointers. The function pointer will
79/// be called when that attribute is found on an item, which can influence the state of the little
80/// state machine.
81///
82/// Finally, after all attributes on an item have been seen, and possibly been accepted,
83/// the [`finalize`](AttributeParser::finalize) functions for all attribute parsers are called. Each can then report
84/// whether it has seen the attribute it has been looking for.
85///
86/// The state machine is automatically reset to parse attributes on the next item.
87///
88/// For a simpler attribute parsing interface, consider using [`SingleAttributeParser`]
89/// or [`CombineAttributeParser`] instead.
90pub(crate) trait AttributeParser<S: Stage>: Default + 'static {
91    /// The symbols for the attributes that this parser is interested in.
92    ///
93    /// If an attribute has this symbol, the `accept` function will be called on it.
94    const ATTRIBUTES: AcceptMapping<Self, S>;
95    const ALLOWED_TARGETS: AllowedTargets;
96
97    /// The parser has gotten a chance to accept the attributes on an item,
98    /// here it can produce an attribute.
99    ///
100    /// All finalize methods of all parsers are unconditionally called.
101    /// This means you can't unconditionally return `Some` here,
102    /// that'd be equivalent to unconditionally applying an attribute to
103    /// every single syntax item that could have attributes applied to it.
104    /// Your accept mappings should determine whether this returns something.
105    fn finalize(self, cx: &FinalizeContext<'_, '_, S>) -> Option<AttributeKind>;
106}
107
108/// Alternative to [`AttributeParser`] that automatically handles state management.
109/// A slightly simpler and more restricted way to convert attributes.
110/// Assumes that an attribute can only appear a single time on an item,
111/// and errors when it sees more.
112///
113/// [`Single<T> where T: SingleAttributeParser`](Single) implements [`AttributeParser`].
114///
115/// [`SingleAttributeParser`] can only convert attributes one-to-one, and cannot combine multiple
116/// attributes together like is necessary for `#[stable()]` and `#[unstable()]` for example.
117pub(crate) trait SingleAttributeParser<S: Stage>: 'static {
118    /// The single path of the attribute this parser accepts.
119    ///
120    /// If you need the parser to accept more than one path, use [`AttributeParser`] instead
121    const PATH: &[Symbol];
122
123    /// Configures the precedence of attributes with the same `PATH` on a syntax node.
124    const ATTRIBUTE_ORDER: AttributeOrder;
125
126    /// Configures what to do when when the same attribute is
127    /// applied more than once on the same syntax node.
128    ///
129    /// [`ATTRIBUTE_ORDER`](Self::ATTRIBUTE_ORDER) specified which one is assumed to be correct,
130    /// and this specified whether to, for example, warn or error on the other one.
131    const ON_DUPLICATE: OnDuplicate<S>;
132
133    const ALLOWED_TARGETS: AllowedTargets;
134
135    /// The template this attribute parser should implement. Used for diagnostics.
136    const TEMPLATE: AttributeTemplate;
137
138    /// Converts a single syntactical attribute to a single semantic attribute, or [`AttributeKind`]
139    fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind>;
140}
141
142/// Use in combination with [`SingleAttributeParser`].
143/// `Single<T: SingleAttributeParser>` implements [`AttributeParser`].
144pub(crate) struct Single<T: SingleAttributeParser<S>, S: Stage>(
145    PhantomData<(S, T)>,
146    Option<(AttributeKind, Span)>,
147);
148
149impl<T: SingleAttributeParser<S>, S: Stage> Default for Single<T, S> {
150    fn default() -> Self {
151        Self(Default::default(), Default::default())
152    }
153}
154
155impl<T: SingleAttributeParser<S>, S: Stage> AttributeParser<S> for Single<T, S> {
156    const ATTRIBUTES: AcceptMapping<Self, S> = &[(
157        T::PATH,
158        <T as SingleAttributeParser<S>>::TEMPLATE,
159        |group: &mut Single<T, S>, cx, args| {
160            if let Some(pa) = T::convert(cx, args) {
161                match T::ATTRIBUTE_ORDER {
162                    // keep the first and report immediately. ignore this attribute
163                    AttributeOrder::KeepInnermost => {
164                        if let Some((_, unused)) = group.1 {
165                            T::ON_DUPLICATE.exec::<T>(cx, cx.attr_span, unused);
166                            return;
167                        }
168                    }
169                    // keep the new one and warn about the previous,
170                    // then replace
171                    AttributeOrder::KeepOutermost => {
172                        if let Some((_, used)) = group.1 {
173                            T::ON_DUPLICATE.exec::<T>(cx, used, cx.attr_span);
174                        }
175                    }
176                }
177
178                group.1 = Some((pa, cx.attr_span));
179            }
180        },
181    )];
182    const ALLOWED_TARGETS: AllowedTargets = T::ALLOWED_TARGETS;
183
184    fn finalize(self, _cx: &FinalizeContext<'_, '_, S>) -> Option<AttributeKind> {
185        Some(self.1?.0)
186    }
187}
188
189pub(crate) enum OnDuplicate<S: Stage> {
190    /// Give a default warning
191    Warn,
192
193    /// Duplicates will be a warning, with a note that this will be an error in the future.
194    WarnButFutureError,
195
196    /// Give a default error
197    Error,
198
199    /// Ignore duplicates
200    Ignore,
201
202    /// Custom function called when a duplicate attribute is found.
203    ///
204    /// - `unused` is the span of the attribute that was unused or bad because of some
205    ///   duplicate reason (see [`AttributeOrder`])
206    /// - `used` is the span of the attribute that was used in favor of the unused attribute
207    Custom(fn(cx: &AcceptContext<'_, '_, S>, used: Span, unused: Span)),
208}
209
210impl<S: Stage> OnDuplicate<S> {
211    fn exec<P: SingleAttributeParser<S>>(
212        &self,
213        cx: &mut AcceptContext<'_, '_, S>,
214        used: Span,
215        unused: Span,
216    ) {
217        match self {
218            OnDuplicate::Warn => cx.warn_unused_duplicate(used, unused),
219            OnDuplicate::WarnButFutureError => cx.warn_unused_duplicate_future_error(used, unused),
220            OnDuplicate::Error => {
221                cx.emit_err(UnusedMultiple {
222                    this: used,
223                    other: unused,
224                    name: Symbol::intern(
225                        &P::PATH.into_iter().map(|i| i.to_string()).collect::<Vec<_>>().join(".."),
226                    ),
227                });
228            }
229            OnDuplicate::Ignore => {}
230            OnDuplicate::Custom(f) => f(cx, used, unused),
231        }
232    }
233}
234
235pub(crate) enum AttributeOrder {
236    /// Duplicates after the innermost instance of the attribute will be an error/warning.
237    /// Only keep the lowest attribute.
238    ///
239    /// Attributes are processed from bottom to top, so this raises a warning/error on all the attributes
240    /// further above the lowest one:
241    /// ```
242    /// #[stable(since="1.0")] //~ WARNING duplicated attribute
243    /// #[stable(since="2.0")]
244    /// ```
245    KeepInnermost,
246
247    /// Duplicates before the outermost instance of the attribute will be an error/warning.
248    /// Only keep the highest attribute.
249    ///
250    /// Attributes are processed from bottom to top, so this raises a warning/error on all the attributes
251    /// below the highest one:
252    /// ```
253    /// #[path="foo.rs"]
254    /// #[path="bar.rs"] //~ WARNING duplicated attribute
255    /// ```
256    KeepOutermost,
257}
258
259/// An even simpler version of [`SingleAttributeParser`]:
260/// now automatically check that there are no arguments provided to the attribute.
261///
262/// [`WithoutArgs<T> where T: NoArgsAttributeParser`](WithoutArgs) implements [`SingleAttributeParser`].
263//
264pub(crate) trait NoArgsAttributeParser<S: Stage>: 'static {
265    const PATH: &[Symbol];
266    const ON_DUPLICATE: OnDuplicate<S>;
267    const ALLOWED_TARGETS: AllowedTargets;
268
269    /// Create the [`AttributeKind`] given attribute's [`Span`].
270    const CREATE: fn(Span) -> AttributeKind;
271}
272
273pub(crate) struct WithoutArgs<T: NoArgsAttributeParser<S>, S: Stage>(PhantomData<(S, T)>);
274
275impl<T: NoArgsAttributeParser<S>, S: Stage> Default for WithoutArgs<T, S> {
276    fn default() -> Self {
277        Self(Default::default())
278    }
279}
280
281impl<T: NoArgsAttributeParser<S>, S: Stage> SingleAttributeParser<S> for WithoutArgs<T, S> {
282    const PATH: &[Symbol] = T::PATH;
283    const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepOutermost;
284    const ON_DUPLICATE: OnDuplicate<S> = T::ON_DUPLICATE;
285    const ALLOWED_TARGETS: AllowedTargets = T::ALLOWED_TARGETS;
286    const TEMPLATE: AttributeTemplate = template!(Word);
287
288    fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
289        if let Err(span) = args.no_args() {
290            cx.expected_no_args(span);
291        }
292        Some(T::CREATE(cx.attr_span))
293    }
294}
295
296type ConvertFn<E> = fn(ThinVec<E>, Span) -> AttributeKind;
297
298/// Alternative to [`AttributeParser`] that automatically handles state management.
299/// If multiple attributes appear on an element, combines the values of each into a
300/// [`ThinVec`].
301/// [`Combine<T> where T: CombineAttributeParser`](Combine) implements [`AttributeParser`].
302///
303/// [`CombineAttributeParser`] can only convert a single kind of attribute, and cannot combine multiple
304/// attributes together like is necessary for `#[stable()]` and `#[unstable()]` for example.
305pub(crate) trait CombineAttributeParser<S: Stage>: 'static {
306    const PATH: &[rustc_span::Symbol];
307
308    type Item;
309    /// A function that converts individual items (of type [`Item`](Self::Item)) into the final attribute.
310    ///
311    /// For example, individual representations from `#[repr(...)]` attributes into an `AttributeKind::Repr(x)`,
312    ///  where `x` is a vec of these individual reprs.
313    const CONVERT: ConvertFn<Self::Item>;
314
315    const ALLOWED_TARGETS: AllowedTargets;
316
317    /// The template this attribute parser should implement. Used for diagnostics.
318    const TEMPLATE: AttributeTemplate;
319
320    /// Converts a single syntactical attribute to a number of elements of the semantic attribute, or [`AttributeKind`]
321    fn extend(
322        cx: &mut AcceptContext<'_, '_, S>,
323        args: &ArgParser,
324    ) -> impl IntoIterator<Item = Self::Item>;
325}
326
327/// Use in combination with [`CombineAttributeParser`].
328/// `Combine<T: CombineAttributeParser>` implements [`AttributeParser`].
329pub(crate) struct Combine<T: CombineAttributeParser<S>, S: Stage> {
330    phantom: PhantomData<(S, T)>,
331    /// A list of all items produced by parsing attributes so far. One attribute can produce any amount of items.
332    items: ThinVec<<T as CombineAttributeParser<S>>::Item>,
333    /// The full span of the first attribute that was encountered.
334    first_span: Option<Span>,
335}
336
337impl<T: CombineAttributeParser<S>, S: Stage> Default for Combine<T, S> {
338    fn default() -> Self {
339        Self {
340            phantom: Default::default(),
341            items: Default::default(),
342            first_span: Default::default(),
343        }
344    }
345}
346
347impl<T: CombineAttributeParser<S>, S: Stage> AttributeParser<S> for Combine<T, S> {
348    const ATTRIBUTES: AcceptMapping<Self, S> =
349        &[(T::PATH, T::TEMPLATE, |group: &mut Combine<T, S>, cx, args| {
350            // Keep track of the span of the first attribute, for diagnostics
351            group.first_span.get_or_insert(cx.attr_span);
352            group.items.extend(T::extend(cx, args))
353        })];
354    const ALLOWED_TARGETS: AllowedTargets = T::ALLOWED_TARGETS;
355
356    fn finalize(self, _cx: &FinalizeContext<'_, '_, S>) -> Option<AttributeKind> {
357        if let Some(first_span) = self.first_span {
358            Some(T::CONVERT(self.items, first_span))
359        } else {
360            None
361        }
362    }
363}