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