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