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