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::edition::Edition;
22use rustc_span::{Span, Symbol};
23use thin_vec::ThinVec;
24
25use crate::context::{AcceptContext, FinalizeContext, Stage};
26use crate::parser::ArgParser;
27use crate::session_diagnostics::UnusedMultiple;
28use crate::target_checking::AllowedTargets;
29
30/// All the parsers require roughly the same imports, so this prelude has most of the often-needed ones.
31mod prelude;
32
33pub(crate) mod allow_unstable;
34pub(crate) mod autodiff;
35pub(crate) mod body;
36pub(crate) mod cfg;
37pub(crate) mod cfg_select;
38pub(crate) mod cfi_encoding;
39pub(crate) mod codegen_attrs;
40pub(crate) mod confusables;
41pub(crate) mod crate_level;
42pub(crate) mod debugger;
43pub(crate) mod deprecation;
44pub(crate) mod diagnostic;
45pub(crate) mod doc;
46pub(crate) mod dummy;
47pub(crate) mod inline;
48pub(crate) mod instruction_set;
49pub(crate) mod link_attrs;
50pub(crate) mod lint_helpers;
51pub(crate) mod loop_match;
52pub(crate) mod macro_attrs;
53pub(crate) mod must_not_suspend;
54pub(crate) mod must_use;
55pub(crate) mod no_implicit_prelude;
56pub(crate) mod no_link;
57pub(crate) mod non_exhaustive;
58pub(crate) mod path;
59pub(crate) mod pin_v2;
60pub(crate) mod proc_macro_attrs;
61pub(crate) mod prototype;
62pub(crate) mod repr;
63pub(crate) mod rustc_allocator;
64pub(crate) mod rustc_dump;
65pub(crate) mod rustc_internal;
66pub(crate) mod semantics;
67pub(crate) mod stability;
68pub(crate) mod test_attrs;
69pub(crate) mod traits;
70pub(crate) mod transparency;
71pub(crate) mod util;
72
73type AcceptFn<T, S> = for<'sess> fn(&mut T, &mut AcceptContext<'_, 'sess, S>, &ArgParser);
74type AcceptMapping<T, S> = &'static [(&'static [Symbol], AttributeTemplate, AcceptFn<T, S>)];
75
76/// An [`AttributeParser`] is a type which searches for syntactic attributes.
77///
78/// Parsers are often tiny state machines that gets to see all syntactical attributes on an item.
79/// [`Default::default`] creates a fresh instance that sits in some kind of initial state, usually that the
80/// attribute it is looking for was not yet seen.
81///
82/// Then, it defines what paths this group will accept in [`AttributeParser::ATTRIBUTES`].
83/// These are listed as pairs, of symbols and function pointers. The function pointer will
84/// be called when that attribute is found on an item, which can influence the state of the little
85/// state machine.
86///
87/// Finally, after all attributes on an item have been seen, and possibly been accepted,
88/// the [`finalize`](AttributeParser::finalize) functions for all attribute parsers are called. Each can then report
89/// whether it has seen the attribute it has been looking for.
90///
91/// The state machine is automatically reset to parse attributes on the next item.
92///
93/// For a simpler attribute parsing interface, consider using [`SingleAttributeParser`]
94/// or [`CombineAttributeParser`] instead.
95pub(crate) trait AttributeParser<S: Stage>: Default + 'static {
96    /// The symbols for the attributes that this parser is interested in.
97    ///
98    /// If an attribute has this symbol, the `accept` function will be called on it.
99    const ATTRIBUTES: AcceptMapping<Self, S>;
100    const ALLOWED_TARGETS: AllowedTargets;
101    const SAFETY: AttributeSafety = AttributeSafety::Normal;
102
103    /// The parser has gotten a chance to accept the attributes on an item,
104    /// here it can produce an attribute.
105    ///
106    /// All finalize methods of all parsers are unconditionally called.
107    /// This means you can't unconditionally return `Some` here,
108    /// that'd be equivalent to unconditionally applying an attribute to
109    /// every single syntax item that could have attributes applied to it.
110    /// Your accept mappings should determine whether this returns something.
111    fn finalize(self, cx: &FinalizeContext<'_, '_, S>) -> Option<AttributeKind>;
112}
113
114/// Alternative to [`AttributeParser`] that automatically handles state management.
115/// A slightly simpler and more restricted way to convert attributes.
116/// Assumes that an attribute can only appear a single time on an item,
117/// and errors when it sees more.
118///
119/// [`Single<T> where T: SingleAttributeParser`](Single) implements [`AttributeParser`].
120///
121/// [`SingleAttributeParser`] can only convert attributes one-to-one, and cannot combine multiple
122/// attributes together like is necessary for `#[stable()]` and `#[unstable()]` for example.
123pub(crate) trait SingleAttributeParser<S: Stage>: 'static {
124    /// The single path of the attribute this parser accepts.
125    ///
126    /// If you need the parser to accept more than one path, use [`AttributeParser`] instead
127    const PATH: &[Symbol];
128
129    /// Configures what to do when when the same attribute is
130    /// applied more than once on the same syntax node.
131    const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
132    const SAFETY: AttributeSafety = AttributeSafety::Normal;
133
134    const ALLOWED_TARGETS: AllowedTargets;
135
136    /// The template this attribute parser should implement. Used for diagnostics.
137    const TEMPLATE: AttributeTemplate;
138
139    /// Converts a single syntactical attribute to a single semantic attribute, or [`AttributeKind`]
140    fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind>;
141}
142
143/// Use in combination with [`SingleAttributeParser`].
144/// `Single<T: SingleAttributeParser>` implements [`AttributeParser`].
145pub(crate) struct Single<T: SingleAttributeParser<S>, S: Stage>(
146    PhantomData<(S, T)>,
147    Option<(AttributeKind, Span)>,
148);
149
150impl<T: SingleAttributeParser<S>, S: Stage> Default for Single<T, S> {
151    fn default() -> Self {
152        Self(Default::default(), Default::default())
153    }
154}
155
156impl<T: SingleAttributeParser<S>, S: Stage> AttributeParser<S> for Single<T, S> {
157    const ATTRIBUTES: AcceptMapping<Self, S> = &[(
158        T::PATH,
159        <T as SingleAttributeParser<S>>::TEMPLATE,
160        |group: &mut Single<T, S>, cx, args| {
161            if let Some(pa) = T::convert(cx, args) {
162                if let Some((_, used)) = group.1 {
163                    T::ON_DUPLICATE.exec::<T>(cx, used, cx.attr_span);
164                } else {
165                    group.1 = Some((pa, cx.attr_span));
166                }
167            }
168        },
169    )];
170    const ALLOWED_TARGETS: AllowedTargets = T::ALLOWED_TARGETS;
171    const SAFETY: AttributeSafety = T::SAFETY;
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
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: unused,
212                    other: used,
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
224#[derive(#[automatically_derived]
impl ::core::marker::Copy for AttributeSafety { }Copy, #[automatically_derived]
impl ::core::clone::Clone for AttributeSafety {
    #[inline]
    fn clone(&self) -> AttributeSafety {
        let _: ::core::clone::AssertParamIsClone<Option<Edition>>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for AttributeSafety {
    #[inline]
    fn eq(&self, other: &AttributeSafety) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (AttributeSafety::Unsafe { unsafe_since: __self_0 },
                    AttributeSafety::Unsafe { unsafe_since: __arg1_0 }) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for AttributeSafety {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            AttributeSafety::Normal =>
                ::core::fmt::Formatter::write_str(f, "Normal"),
            AttributeSafety::Unsafe { unsafe_since: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Unsafe", "unsafe_since", &__self_0),
        }
    }
}Debug)]
225pub enum AttributeSafety {
226    /// Normal attribute that does not need `#[unsafe(...)]`
227    Normal,
228    /// Unsafe attribute that requires safety obligations to be discharged.
229    ///
230    /// An error is emitted when `#[unsafe(...)]` is omitted, except when the attribute's edition
231    /// is less than the one stored in `unsafe_since`. This handles attributes that were safe in
232    /// earlier editions, but become unsafe in later ones.
233    Unsafe { unsafe_since: Option<Edition> },
234}
235
236/// An even simpler version of [`SingleAttributeParser`]:
237/// now automatically check that there are no arguments provided to the attribute.
238///
239/// [`WithoutArgs<T> where T: NoArgsAttributeParser`](WithoutArgs) implements [`SingleAttributeParser`].
240//
241pub(crate) trait NoArgsAttributeParser<S: Stage>: 'static {
242    const PATH: &[Symbol];
243    const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
244    const ALLOWED_TARGETS: AllowedTargets;
245    const SAFETY: AttributeSafety = AttributeSafety::Normal;
246
247    /// Create the [`AttributeKind`] given attribute's [`Span`].
248    const CREATE: fn(Span) -> AttributeKind;
249}
250
251pub(crate) struct WithoutArgs<T: NoArgsAttributeParser<S>, S: Stage>(PhantomData<(S, T)>);
252
253impl<T: NoArgsAttributeParser<S>, S: Stage> Default for WithoutArgs<T, S> {
254    fn default() -> Self {
255        Self(Default::default())
256    }
257}
258
259impl<T: NoArgsAttributeParser<S>, S: Stage> SingleAttributeParser<S> for WithoutArgs<T, S> {
260    const PATH: &[Symbol] = T::PATH;
261    const ON_DUPLICATE: OnDuplicate<S> = T::ON_DUPLICATE;
262    const SAFETY: AttributeSafety = T::SAFETY;
263    const ALLOWED_TARGETS: AllowedTargets = T::ALLOWED_TARGETS;
264    const TEMPLATE: AttributeTemplate = ::rustc_feature::AttributeTemplate {
    word: true,
    list: None,
    one_of: &[],
    name_value_str: None,
    docs: None,
}template!(Word);
265
266    fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
267        if let Err(span) = args.no_args() {
268            cx.adcx().expected_no_args(span);
269        }
270        Some(T::CREATE(cx.attr_span))
271    }
272}
273
274type ConvertFn<E> = fn(ThinVec<E>, Span) -> AttributeKind;
275
276/// Alternative to [`AttributeParser`] that automatically handles state management.
277/// If multiple attributes appear on an element, combines the values of each into a
278/// [`ThinVec`].
279/// [`Combine<T> where T: CombineAttributeParser`](Combine) implements [`AttributeParser`].
280///
281/// [`CombineAttributeParser`] can only convert a single kind of attribute, and cannot combine multiple
282/// attributes together like is necessary for `#[stable()]` and `#[unstable()]` for example.
283pub(crate) trait CombineAttributeParser<S: Stage>: 'static {
284    const PATH: &[rustc_span::Symbol];
285
286    type Item;
287    /// A function that converts individual items (of type [`Item`](Self::Item)) into the final attribute.
288    ///
289    /// For example, individual representations from `#[repr(...)]` attributes into an `AttributeKind::Repr(x)`,
290    ///  where `x` is a vec of these individual reprs.
291    const CONVERT: ConvertFn<Self::Item>;
292    const SAFETY: AttributeSafety = AttributeSafety::Normal;
293
294    const ALLOWED_TARGETS: AllowedTargets;
295
296    /// The template this attribute parser should implement. Used for diagnostics.
297    const TEMPLATE: AttributeTemplate;
298
299    /// Converts a single syntactical attribute to a number of elements of the semantic attribute, or [`AttributeKind`]
300    fn extend(
301        cx: &mut AcceptContext<'_, '_, S>,
302        args: &ArgParser,
303    ) -> impl IntoIterator<Item = Self::Item>;
304}
305
306/// Use in combination with [`CombineAttributeParser`].
307/// `Combine<T: CombineAttributeParser>` implements [`AttributeParser`].
308pub(crate) struct Combine<T: CombineAttributeParser<S>, S: Stage> {
309    phantom: PhantomData<(S, T)>,
310    /// A list of all items produced by parsing attributes so far. One attribute can produce any amount of items.
311    items: ThinVec<<T as CombineAttributeParser<S>>::Item>,
312    /// The full span of the first attribute that was encountered.
313    first_span: Option<Span>,
314}
315
316impl<T: CombineAttributeParser<S>, S: Stage> Default for Combine<T, S> {
317    fn default() -> Self {
318        Self {
319            phantom: Default::default(),
320            items: Default::default(),
321            first_span: Default::default(),
322        }
323    }
324}
325
326impl<T: CombineAttributeParser<S>, S: Stage> AttributeParser<S> for Combine<T, S> {
327    const ATTRIBUTES: AcceptMapping<Self, S> =
328        &[(T::PATH, T::TEMPLATE, |group: &mut Combine<T, S>, cx, args| {
329            // Keep track of the span of the first attribute, for diagnostics
330            group.first_span.get_or_insert(cx.attr_span);
331            group.items.extend(T::extend(cx, args))
332        })];
333    const ALLOWED_TARGETS: AllowedTargets = T::ALLOWED_TARGETS;
334    const SAFETY: AttributeSafety = T::SAFETY;
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}