Skip to main content

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