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