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