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