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