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