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};
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> = for<'sess> fn(&mut T, &mut AcceptContext<'_, 'sess>, &ArgParser);
74type AcceptMapping<T> = &'static [(&'static [Symbol], AttributeTemplate, AcceptFn<T>)];
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: 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>;
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<'_, '_>) -> 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: '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 = 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<'_, '_>, args: &ArgParser) -> Option<AttributeKind>;
141}
142
143/// Use in combination with [`SingleAttributeParser`].
144/// `Single<T: SingleAttributeParser>` implements [`AttributeParser`].
145pub(crate) struct Single<T: SingleAttributeParser>(PhantomData<T>, Option<(AttributeKind, Span)>);
146
147impl<T: SingleAttributeParser> Default for Single<T> {
148    fn default() -> Self {
149        Self(Default::default(), Default::default())
150    }
151}
152
153impl<T: SingleAttributeParser> AttributeParser for Single<T> {
154    const ATTRIBUTES: AcceptMapping<Self> =
155        &[(T::PATH, <T as SingleAttributeParser>::TEMPLATE, |group: &mut Single<T>, cx, args| {
156            if let Some(pa) = T::convert(cx, args) {
157                if let Some((_, used)) = group.1 {
158                    T::ON_DUPLICATE.exec::<T>(cx, used, cx.attr_span);
159                } else {
160                    group.1 = Some((pa, cx.attr_span));
161                }
162            }
163        })];
164    const ALLOWED_TARGETS: AllowedTargets = T::ALLOWED_TARGETS;
165    const SAFETY: AttributeSafety = T::SAFETY;
166
167    fn finalize(self, _cx: &FinalizeContext<'_, '_>) -> Option<AttributeKind> {
168        Some(self.1?.0)
169    }
170}
171
172pub(crate) enum OnDuplicate {
173    /// Give a default warning
174    Warn,
175
176    /// Duplicates will be a warning, with a note that this will be an error in the future.
177    WarnButFutureError,
178
179    /// Give a default error
180    Error,
181
182    /// Ignore duplicates
183    Ignore,
184
185    /// Custom function called when a duplicate attribute is found.
186    ///
187    /// - `unused` is the span of the attribute that was unused or bad because of some
188    ///   duplicate reason
189    /// - `used` is the span of the attribute that was used in favor of the unused attribute
190    Custom(fn(cx: &AcceptContext<'_, '_>, used: Span, unused: Span)),
191}
192
193impl OnDuplicate {
194    fn exec<P: SingleAttributeParser>(
195        &self,
196        cx: &mut AcceptContext<'_, '_>,
197        used: Span,
198        unused: Span,
199    ) {
200        match self {
201            OnDuplicate::Warn => cx.warn_unused_duplicate(used, unused),
202            OnDuplicate::WarnButFutureError => cx.warn_unused_duplicate_future_error(used, unused),
203            OnDuplicate::Error => {
204                cx.emit_err(UnusedMultiple {
205                    this: unused,
206                    other: used,
207                    name: Symbol::intern(
208                        &P::PATH.into_iter().map(|i| i.to_string()).collect::<Vec<_>>().join(".."),
209                    ),
210                });
211            }
212            OnDuplicate::Ignore => {}
213            OnDuplicate::Custom(f) => f(cx, used, unused),
214        }
215    }
216}
217
218#[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)]
219pub enum AttributeSafety {
220    /// Normal attribute that does not need `#[unsafe(...)]`
221    Normal,
222    /// Unsafe attribute that requires safety obligations to be discharged.
223    ///
224    /// An error is emitted when `#[unsafe(...)]` is omitted, except when the attribute's edition
225    /// is less than the one stored in `unsafe_since`. This handles attributes that were safe in
226    /// earlier editions, but become unsafe in later ones.
227    Unsafe { unsafe_since: Option<Edition> },
228}
229
230/// An even simpler version of [`SingleAttributeParser`]:
231/// now automatically check that there are no arguments provided to the attribute.
232///
233/// [`WithoutArgs<T> where T: NoArgsAttributeParser`](WithoutArgs) implements [`SingleAttributeParser`].
234//
235pub(crate) trait NoArgsAttributeParser: 'static {
236    const PATH: &[Symbol];
237    const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error;
238    const ALLOWED_TARGETS: AllowedTargets;
239    const SAFETY: AttributeSafety = AttributeSafety::Normal;
240
241    /// Create the [`AttributeKind`] given attribute's [`Span`].
242    const CREATE: fn(Span) -> AttributeKind;
243}
244
245pub(crate) struct WithoutArgs<T: NoArgsAttributeParser>(PhantomData<T>);
246
247impl<T: NoArgsAttributeParser> Default for WithoutArgs<T> {
248    fn default() -> Self {
249        Self(Default::default())
250    }
251}
252
253impl<T: NoArgsAttributeParser> SingleAttributeParser for WithoutArgs<T> {
254    const PATH: &[Symbol] = T::PATH;
255    const ON_DUPLICATE: OnDuplicate = T::ON_DUPLICATE;
256    const SAFETY: AttributeSafety = T::SAFETY;
257    const ALLOWED_TARGETS: AllowedTargets = T::ALLOWED_TARGETS;
258    const TEMPLATE: AttributeTemplate = ::rustc_feature::AttributeTemplate {
    word: true,
    list: None,
    one_of: &[],
    name_value_str: None,
    docs: None,
}template!(Word);
259
260    fn convert(cx: &mut AcceptContext<'_, '_>, args: &ArgParser) -> Option<AttributeKind> {
261        if let Err(span) = args.no_args() {
262            cx.adcx().expected_no_args(span);
263        }
264        Some(T::CREATE(cx.attr_span))
265    }
266}
267
268type ConvertFn<E> = fn(ThinVec<E>, Span) -> AttributeKind;
269
270/// Alternative to [`AttributeParser`] that automatically handles state management.
271/// If multiple attributes appear on an element, combines the values of each into a
272/// [`ThinVec`].
273/// [`Combine<T> where T: CombineAttributeParser`](Combine) implements [`AttributeParser`].
274///
275/// [`CombineAttributeParser`] can only convert a single kind of attribute, and cannot combine multiple
276/// attributes together like is necessary for `#[stable()]` and `#[unstable()]` for example.
277pub(crate) trait CombineAttributeParser: 'static {
278    const PATH: &[rustc_span::Symbol];
279
280    type Item;
281    /// A function that converts individual items (of type [`Item`](Self::Item)) into the final attribute.
282    ///
283    /// For example, individual representations from `#[repr(...)]` attributes into an `AttributeKind::Repr(x)`,
284    ///  where `x` is a vec of these individual reprs.
285    const CONVERT: ConvertFn<Self::Item>;
286    const SAFETY: AttributeSafety = AttributeSafety::Normal;
287
288    const ALLOWED_TARGETS: AllowedTargets;
289
290    /// The template this attribute parser should implement. Used for diagnostics.
291    const TEMPLATE: AttributeTemplate;
292
293    /// Converts a single syntactical attribute to a number of elements of the semantic attribute, or [`AttributeKind`]
294    fn extend(
295        cx: &mut AcceptContext<'_, '_>,
296        args: &ArgParser,
297    ) -> impl IntoIterator<Item = Self::Item>;
298}
299
300/// Use in combination with [`CombineAttributeParser`].
301/// `Combine<T: CombineAttributeParser>` implements [`AttributeParser`].
302pub(crate) struct Combine<T: CombineAttributeParser> {
303    phantom: PhantomData<T>,
304    /// A list of all items produced by parsing attributes so far. One attribute can produce any amount of items.
305    items: ThinVec<<T as CombineAttributeParser>::Item>,
306    /// The full span of the first attribute that was encountered.
307    first_span: Option<Span>,
308}
309
310impl<T: CombineAttributeParser> Default for Combine<T> {
311    fn default() -> Self {
312        Self {
313            phantom: Default::default(),
314            items: Default::default(),
315            first_span: Default::default(),
316        }
317    }
318}
319
320impl<T: CombineAttributeParser> AttributeParser for Combine<T> {
321    const ATTRIBUTES: AcceptMapping<Self> =
322        &[(T::PATH, T::TEMPLATE, |group: &mut Combine<T>, cx, args| {
323            // Keep track of the span of the first attribute, for diagnostics
324            group.first_span.get_or_insert(cx.attr_span);
325            group.items.extend(T::extend(cx, args))
326        })];
327    const ALLOWED_TARGETS: AllowedTargets = T::ALLOWED_TARGETS;
328    const SAFETY: AttributeSafety = T::SAFETY;
329
330    fn finalize(self, _cx: &FinalizeContext<'_, '_>) -> Option<AttributeKind> {
331        if let Some(first_span) = self.first_span {
332            Some(T::CONVERT(self.items, first_span))
333        } else {
334            None
335        }
336    }
337}