Skip to main content

rustc_attr_parsing/attributes/
mod.rs

1//! Traits for parsing attributes.
2//!
3//! This module defines traits for attribute parsers, little state machines that recognize and parse
4//! attributes out of a longer list of attributes. The main trait is called [`AttributeParser`].
5//! You can find more docs about [`AttributeParser`]s on the trait itself.
6//! However, for many types of attributes, implementing [`AttributeParser`] is not necessary.
7//! It allows for a lot of flexibility you might not want.
8//!
9//! Specifically, you might not care about managing the state of your [`AttributeParser`]
10//! state machine yourself. In this case you can choose to implement:
11//!
12//! - [`NoArgsAttributeParser`]: used for implementing an attribute that appears only once and
13//! accepts no arguments
14//! - [`SingleAttributeParser`]: makes it easy to implement an attribute which should error if it
15//! appears more than once in a list of attributes
16//! - [`CombineAttributeParser`]: makes it easy to implement an attribute which should combine the
17//! contents of attributes, if an attribute appear multiple times in a list
18//!
19//! Attributes should be added to `crate::context::ATTRIBUTE_PARSERS` to be parsed.
20
21use std::marker::PhantomData;
22
23use rustc_feature::AttributeStability;
24use rustc_hir::attrs::AttributeKind;
25use rustc_span::edition::Edition;
26use rustc_span::{Span, Symbol};
27use thin_vec::ThinVec;
28
29use crate::context::{AcceptContext, FinalizeCheckContext, FinalizeCheckFn, FinalizeContext};
30use crate::parser::ArgParser;
31use crate::session_diagnostics::UnusedMultiple;
32use crate::target_checking::AllowedTargets;
33use crate::{AttributeTemplate, template};
34
35/// All the parsers require roughly the same imports, so this prelude has most of the often-needed ones.
36mod prelude;
37
38pub(crate) mod allow_unstable;
39pub(crate) mod autodiff;
40pub(crate) mod body;
41pub(crate) mod cfg;
42pub(crate) mod cfg_select;
43pub(crate) mod cfi_encoding;
44pub(crate) mod codegen_attrs;
45pub(crate) mod confusables;
46pub(crate) mod crate_level;
47pub(crate) mod debugger;
48pub(crate) mod deprecation;
49pub(crate) mod diagnostic;
50pub(crate) mod doc;
51pub(crate) mod dummy;
52pub(crate) mod inline;
53pub(crate) mod instruction_set;
54pub(crate) mod link_attrs;
55pub(crate) mod lint_helpers;
56pub(crate) mod loop_match;
57pub(crate) mod macro_attrs;
58pub(crate) mod must_not_suspend;
59pub(crate) mod must_use;
60pub(crate) mod no_implicit_prelude;
61pub(crate) mod no_link;
62pub(crate) mod non_exhaustive;
63pub(crate) mod path;
64pub(crate) mod pin_v2;
65pub(crate) mod proc_macro_attrs;
66pub(crate) mod prototype;
67pub(crate) mod repr;
68pub(crate) mod rustc_allocator;
69pub(crate) mod rustc_dump;
70pub(crate) mod rustc_internal;
71pub(crate) mod semantics;
72pub(crate) mod splat;
73pub(crate) mod stability;
74pub(crate) mod test_attrs;
75pub(crate) mod traits;
76pub(crate) mod transparency;
77pub(crate) mod unroll;
78pub(crate) mod util;
79
80type AcceptFn<T> = for<'sess> fn(&mut T, &mut AcceptContext<'_, 'sess>, &ArgParser);
81type AcceptMapping<T> =
82    &'static [(&'static [Symbol], AttributeTemplate, AttributeStability, AcceptFn<T>)];
83
84/// An [`AttributeParser`] is a type which searches for syntactic attributes.
85///
86/// Parsers are often tiny state machines that gets to see all syntactical attributes on an item.
87/// [`Default::default`] creates a fresh instance that sits in some kind of initial state, usually that the
88/// attribute it is looking for was not yet seen.
89///
90/// Then, it defines what paths this group will accept in [`AttributeParser::ATTRIBUTES`].
91/// These are listed as pairs, of symbols and function pointers. The function pointer will
92/// be called when that attribute is found on an item, which can influence the state of the little
93/// state machine.
94///
95/// Finally, after all attributes on an item have been seen, and possibly been accepted,
96/// the [`finalize`](AttributeParser::finalize) functions for all attribute parsers are called. Each can then report
97/// whether it has seen the attribute it has been looking for.
98///
99/// The state machine is automatically reset to parse attributes on the next item.
100///
101/// For a simpler attribute parsing interface, consider using [`SingleAttributeParser`]
102/// or [`CombineAttributeParser`] instead.
103pub(crate) trait AttributeParser: Default + 'static {
104    /// The symbols for the attributes that this parser is interested in.
105    ///
106    /// If an attribute has this symbol, the `accept` function will be called on it.
107    const ATTRIBUTES: AcceptMapping<Self>;
108    const ALLOWED_TARGETS: AllowedTargets<'_>;
109    const SAFETY: AttributeSafety = AttributeSafety::Normal;
110
111    /// The parser has gotten a chance to accept the attributes on an item,
112    /// here it can produce an attribute.
113    ///
114    /// All finalize methods of all parsers are unconditionally called.
115    /// This means you can't unconditionally return `Some` here,
116    /// that'd be equivalent to unconditionally applying an attribute to
117    /// every single syntax item that could have attributes applied to it.
118    /// Your accept mappings should determine whether this returns something.
119    fn finalize(self, cx: &FinalizeContext<'_, '_>) -> Option<AttributeKind>;
120
121    /// If this parser produced an attribute, optionally returns a cross-attribute check
122    /// to run once *all* attributes on the item have been finalized, together with the
123    /// span it should be reported at.
124    ///
125    /// Running after finalization means the check can inspect the fully parsed attributes
126    /// via [`FinalizeCheckContext::parsed_attrs`], which are not yet all available during
127    /// [`finalize`](Self::finalize). This is queried right before `finalize` consumes the
128    /// parser state.
129    ///
130    /// Defaults to no check.
131    fn deferred_finalize_check(&self) -> Option<(FinalizeCheckFn, Span)> {
132        None
133    }
134}
135
136/// Alternative to [`AttributeParser`] that automatically handles state management.
137/// A slightly simpler and more restricted way to convert attributes.
138/// Assumes that an attribute can only appear a single time on an item,
139/// and errors when it sees more.
140///
141/// [`Single<T> where T: SingleAttributeParser`](Single) implements [`AttributeParser`].
142///
143/// [`SingleAttributeParser`] can only convert attributes one-to-one, and cannot combine multiple
144/// attributes together like is necessary for `#[stable()]` and `#[unstable()]` for example.
145pub(crate) trait SingleAttributeParser: 'static {
146    /// The single path of the attribute this parser accepts.
147    ///
148    /// If you need the parser to accept more than one path, use [`AttributeParser`] instead
149    const PATH: &[Symbol];
150
151    /// Configures what to do when when the same attribute is
152    /// applied more than once on the same syntax node.
153    const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error;
154    const SAFETY: AttributeSafety = AttributeSafety::Normal;
155    const STABILITY: AttributeStability;
156
157    const ALLOWED_TARGETS: AllowedTargets<'_>;
158
159    /// The template this attribute parser should implement. Used for diagnostics.
160    const TEMPLATE: AttributeTemplate;
161
162    /// Converts a single syntactical attribute to a single semantic attribute, or [`AttributeKind`]
163    fn convert(cx: &mut AcceptContext<'_, '_>, args: &ArgParser) -> Option<AttributeKind>;
164
165    /// Optional cross-attribute validation, run once *after* all attributes on the item
166    /// have been finalized. Unlike [`convert`](Self::convert), this has access to the
167    /// sibling attributes via [`FinalizeCheckContext::all_attrs`] and the fully parsed
168    /// attributes via [`FinalizeCheckContext::parsed_attrs`], so it can reject incompatible
169    /// combinations. `attr_span` is the span of this attribute.
170    ///
171    /// Defaults to a no-op.
172    fn finalize_check(_cx: &FinalizeCheckContext<'_, '_>, _attr_span: Span) {}
173}
174
175/// Use in combination with [`SingleAttributeParser`].
176/// `Single<T: SingleAttributeParser>` implements [`AttributeParser`].
177pub(crate) struct Single<T: SingleAttributeParser>(PhantomData<T>, Option<(AttributeKind, Span)>);
178
179impl<T: SingleAttributeParser> Default for Single<T> {
180    fn default() -> Self {
181        Self(Default::default(), Default::default())
182    }
183}
184
185impl<T: SingleAttributeParser> AttributeParser for Single<T> {
186    const ATTRIBUTES: AcceptMapping<Self> = &[(
187        T::PATH,
188        <T as SingleAttributeParser>::TEMPLATE,
189        T::STABILITY,
190        |group: &mut Single<T>, cx, args| {
191            if let Some(pa) = T::convert(cx, args) {
192                if let Some((_, used)) = group.1 {
193                    T::ON_DUPLICATE.exec::<T>(cx, used, cx.attr_span);
194                } else {
195                    group.1 = Some((pa, cx.attr_span));
196                }
197            }
198        },
199    )];
200    const ALLOWED_TARGETS: AllowedTargets<'_> = T::ALLOWED_TARGETS;
201    const SAFETY: AttributeSafety = T::SAFETY;
202
203    fn finalize(self, _cx: &FinalizeContext<'_, '_>) -> Option<AttributeKind> {
204        let (kind, _span) = self.1?;
205        Some(kind)
206    }
207
208    fn deferred_finalize_check(&self) -> Option<(FinalizeCheckFn, Span)> {
209        let (_, span) = self.1.as_ref()?;
210        Some((<T as SingleAttributeParser>::finalize_check, *span))
211    }
212}
213
214pub(crate) enum OnDuplicate {
215    /// Give a default warning
216    Warn,
217
218    /// Duplicates will be a warning, with a note that this will be an error in the future.
219    WarnButFutureError,
220
221    /// Give a default error
222    Error,
223
224    /// Ignore duplicates
225    Ignore,
226
227    /// Custom function called when a duplicate attribute is found.
228    ///
229    /// - `unused` is the span of the attribute that was unused or bad because of some
230    ///   duplicate reason
231    /// - `used` is the span of the attribute that was used in favor of the unused attribute
232    Custom(fn(cx: &AcceptContext<'_, '_>, used: Span, unused: Span)),
233}
234
235impl OnDuplicate {
236    fn exec<P: SingleAttributeParser>(
237        &self,
238        cx: &mut AcceptContext<'_, '_>,
239        used: Span,
240        unused: Span,
241    ) {
242        match self {
243            OnDuplicate::Warn => cx.warn_unused_duplicate(used, unused),
244            OnDuplicate::WarnButFutureError => cx.warn_unused_duplicate_future_error(used, unused),
245            OnDuplicate::Error => {
246                cx.emit_err(UnusedMultiple {
247                    this: unused,
248                    other: used,
249                    name: Symbol::intern(
250                        &P::PATH.into_iter().map(|i| i.to_string()).collect::<Vec<_>>().join(".."),
251                    ),
252                });
253            }
254            OnDuplicate::Ignore => {}
255            OnDuplicate::Custom(f) => f(cx, used, unused),
256        }
257    }
258}
259
260#[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<&'static str>;
        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 {
                    note: __self_0, unsafe_since: __self_1 },
                    AttributeSafety::Unsafe {
                    note: __arg1_0, unsafe_since: __arg1_1 }) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                _ => 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 { note: __self_0, unsafe_since: __self_1 }
                =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "Unsafe", "note", __self_0, "unsafe_since", &__self_1),
        }
    }
}Debug)]
261pub enum AttributeSafety {
262    /// Normal attribute that does not need `#[unsafe(...)]`
263    Normal,
264    /// Unsafe attribute that requires safety obligations to be discharged.
265    ///
266    /// An error is emitted when `#[unsafe(...)]` is omitted, except when the attribute's edition
267    /// is less than the one stored in `unsafe_since`. This handles attributes that were safe in
268    /// earlier editions, but become unsafe in later ones.
269    Unsafe {
270        /// The `note` is emitted during the `unsafe_code`, and explains to the user why this attribute is unsafe.
271        note: &'static str,
272        unsafe_since: Option<Edition>,
273    },
274}
275
276/// An even simpler version of [`SingleAttributeParser`]:
277/// now automatically check that there are no arguments provided to the attribute.
278///
279/// [`WithoutArgs<T> where T: NoArgsAttributeParser`](WithoutArgs) implements [`SingleAttributeParser`].
280//
281pub(crate) trait NoArgsAttributeParser: 'static {
282    const PATH: &[Symbol];
283    const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error;
284    const ALLOWED_TARGETS: AllowedTargets<'_>;
285    const SAFETY: AttributeSafety = AttributeSafety::Normal;
286    const STABILITY: AttributeStability;
287
288    /// Create the [`AttributeKind`] given attribute's [`Span`].
289    const CREATE: fn(Span) -> AttributeKind;
290
291    /// Optional cross-attribute validation, run once *after* all attributes on the item
292    /// have been finalized. Has access to the sibling attributes via
293    /// [`FinalizeCheckContext::all_attrs`] and the fully parsed attributes via
294    /// [`FinalizeCheckContext::parsed_attrs`], so it can reject incompatible combinations.
295    /// `attr_span` is the span of this attribute.
296    ///
297    /// Defaults to a no-op.
298    fn finalize_check(_cx: &FinalizeCheckContext<'_, '_>, _attr_span: Span) {}
299}
300
301pub(crate) struct WithoutArgs<T: NoArgsAttributeParser>(PhantomData<T>);
302
303impl<T: NoArgsAttributeParser> Default for WithoutArgs<T> {
304    fn default() -> Self {
305        Self(Default::default())
306    }
307}
308
309impl<T: NoArgsAttributeParser> SingleAttributeParser for WithoutArgs<T> {
310    const PATH: &[Symbol] = T::PATH;
311    const ON_DUPLICATE: OnDuplicate = T::ON_DUPLICATE;
312    const SAFETY: AttributeSafety = T::SAFETY;
313    const STABILITY: AttributeStability = T::STABILITY;
314    const ALLOWED_TARGETS: AllowedTargets<'_> = T::ALLOWED_TARGETS;
315    const TEMPLATE: AttributeTemplate = crate::AttributeTemplate {
    word: true,
    list: None,
    one_of: &[],
    name_value_str: None,
    docs: None,
}template!(Word);
316
317    fn convert(cx: &mut AcceptContext<'_, '_>, args: &ArgParser) -> Option<AttributeKind> {
318        let _ = cx.expect_no_args(args);
319        Some(T::CREATE(cx.attr_span))
320    }
321
322    fn finalize_check(cx: &FinalizeCheckContext<'_, '_>, attr_span: Span) {
323        T::finalize_check(cx, attr_span)
324    }
325}
326
327type ConvertFn<E> = fn(ThinVec<E>, Span) -> AttributeKind;
328
329/// Alternative to [`AttributeParser`] that automatically handles state management.
330/// If multiple attributes appear on an element, combines the values of each into a
331/// [`ThinVec`].
332/// [`Combine<T> where T: CombineAttributeParser`](Combine) implements [`AttributeParser`].
333///
334/// [`CombineAttributeParser`] can only convert a single kind of attribute, and cannot combine multiple
335/// attributes together like is necessary for `#[stable()]` and `#[unstable()]` for example.
336pub(crate) trait CombineAttributeParser: 'static {
337    const PATH: &[rustc_span::Symbol];
338
339    type Item;
340    /// A function that converts individual items (of type [`Item`](Self::Item)) into the final attribute.
341    ///
342    /// For example, individual representations from `#[repr(...)]` attributes into an `AttributeKind::Repr(x)`,
343    ///  where `x` is a vec of these individual reprs.
344    const CONVERT: ConvertFn<Self::Item>;
345    const SAFETY: AttributeSafety = AttributeSafety::Normal;
346    const STABILITY: AttributeStability;
347
348    const ALLOWED_TARGETS: AllowedTargets<'_>;
349
350    /// The template this attribute parser should implement. Used for diagnostics.
351    const TEMPLATE: AttributeTemplate;
352
353    /// Converts a single syntactical attribute to a number of elements of the semantic attribute, or [`AttributeKind`]
354    fn extend(
355        cx: &mut AcceptContext<'_, '_>,
356        args: &ArgParser,
357    ) -> impl IntoIterator<Item = Self::Item>;
358
359    /// Optional cross-attribute validation, run once *after* all attributes on the item
360    /// have been finalized. Has access to the sibling attributes via
361    /// [`FinalizeCheckContext::all_attrs`] and the fully parsed attributes via
362    /// [`FinalizeCheckContext::parsed_attrs`], so it can reject incompatible combinations.
363    /// `attr_span` is the span of the first attribute that was encountered.
364    ///
365    /// Defaults to a no-op.
366    fn finalize_check(_cx: &FinalizeCheckContext<'_, '_>, _attr_span: Span) {}
367}
368
369/// Use in combination with [`CombineAttributeParser`].
370/// `Combine<T: CombineAttributeParser>` implements [`AttributeParser`].
371pub(crate) struct Combine<T: CombineAttributeParser> {
372    phantom: PhantomData<T>,
373    /// A list of all items produced by parsing attributes so far. One attribute can produce any amount of items.
374    items: ThinVec<<T as CombineAttributeParser>::Item>,
375    /// The full span of the first attribute that was encountered.
376    first_span: Option<Span>,
377}
378
379impl<T: CombineAttributeParser> Default for Combine<T> {
380    fn default() -> Self {
381        Self {
382            phantom: Default::default(),
383            items: Default::default(),
384            first_span: Default::default(),
385        }
386    }
387}
388
389impl<T: CombineAttributeParser> AttributeParser for Combine<T> {
390    const ATTRIBUTES: AcceptMapping<Self> =
391        &[(T::PATH, T::TEMPLATE, T::STABILITY, |group: &mut Combine<T>, cx, args| {
392            // Keep track of the span of the first attribute, for diagnostics
393            group.first_span.get_or_insert(cx.attr_span);
394            group.items.extend(T::extend(cx, args))
395        })];
396    const ALLOWED_TARGETS: AllowedTargets<'_> = T::ALLOWED_TARGETS;
397    const SAFETY: AttributeSafety = T::SAFETY;
398
399    fn finalize(self, _cx: &FinalizeContext<'_, '_>) -> Option<AttributeKind> {
400        let first_span = self.first_span?;
401        Some(T::CONVERT(self.items, first_span))
402    }
403
404    fn deferred_finalize_check(&self) -> Option<(FinalizeCheckFn, Span)> {
405        Some((<T as CombineAttributeParser>::finalize_check, self.first_span?))
406    }
407}