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.
2021use std::marker::PhantomData;
2223use rustc_attr_ir::AttributeKind;
24use rustc_feature::AttributeStability;
25use rustc_span::edition::Edition;
26use rustc_span::{Span, Symbol};
27use thin_vec::ThinVec;
2829use crate::context::{AcceptContext, FinalizeCheckContext, FinalizeCheckFn, FinalizeContext};
30use crate::diagnostics::UnusedMultiple;
31use crate::parser::ArgParser;
32use crate::target_checking::AllowedTargets;
33use crate::{AttributeTemplate, template};
3435/// All the parsers require roughly the same imports, so this prelude has most of the often-needed ones.
36mod prelude;
3738pub(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;
8081type AcceptFn<T> = for<'sess> fn(&mut T, &mut AcceptContext<'_, 'sess>, &ArgParser);
82type AcceptMapping<T> =
83&'static [(&'static [Symbol], AttributeTemplate, AttributeStability, AcceptFn<T>)];
8485/// 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.
108const ATTRIBUTES: AcceptMapping<Self>;
109const ALLOWED_TARGETS: AllowedTargets<'_>;
110const SAFETY: AttributeSafety = AttributeSafety::Normal;
111112/// 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.
120fn finalize(self, cx: &FinalizeContext<'_, '_>) -> Option<AttributeKind>;
121122/// 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.
132fn deferred_finalize_check(&self) -> Option<(FinalizeCheckFn, Span)> {
133None134 }
135}
136137/// 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
150const PATH: &[Symbol];
151152/// Configures what to do when when the same attribute is
153 /// applied more than once on the same syntax node.
154const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error;
155const SAFETY: AttributeSafety = AttributeSafety::Normal;
156const STABILITY: AttributeStability;
157158const ALLOWED_TARGETS: AllowedTargets<'_>;
159160/// The template this attribute parser should implement. Used for diagnostics.
161const TEMPLATE: AttributeTemplate;
162163/// Converts a single syntactical attribute to a single semantic attribute, or [`AttributeKind`]
164fn convert(cx: &mut AcceptContext<'_, '_>, args: &ArgParser) -> Option<AttributeKind>;
165166/// 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.
173fn finalize_check(_cx: &mut FinalizeCheckContext<'_, '_>, _attr_span: Span) {}
174}
175176/// Use in combination with [`SingleAttributeParser`].
177/// `Single<T: SingleAttributeParser>` implements [`AttributeParser`].
178pub(crate) struct Single<T: SingleAttributeParser>(PhantomData<T>, Option<(AttributeKind, Span)>);
179180impl<T: SingleAttributeParser> Defaultfor Single<T> {
181fn default() -> Self {
182Self(Default::default(), Default::default())
183 }
184}
185186impl<T: SingleAttributeParser> AttributeParserfor Single<T> {
187const ATTRIBUTES: AcceptMapping<Self> = &[(
188 T::PATH,
189 <T as SingleAttributeParser>::TEMPLATE,
190 T::STABILITY,
191 |group: &mut Single<T>, cx, args| {
192if let Some(pa) = T::convert(cx, args) {
193if let Some((_, used)) = group.1 {
194 T::ON_DUPLICATE.exec::<T>(cx, used, cx.attr_span);
195 } else {
196group.1 = Some((pa, cx.attr_span));
197 }
198 }
199 },
200 )];
201const ALLOWED_TARGETS: AllowedTargets<'_> = T::ALLOWED_TARGETS;
202const SAFETY: AttributeSafety = T::SAFETY;
203204fn finalize(self, _cx: &FinalizeContext<'_, '_>) -> Option<AttributeKind> {
205let (kind, _span) = self.1?;
206Some(kind)
207 }
208209fn deferred_finalize_check(&self) -> Option<(FinalizeCheckFn, Span)> {
210let (_, span) = self.1.as_ref()?;
211Some((<T as SingleAttributeParser>::finalize_check, *span))
212 }
213}
214215pub(crate) enum OnDuplicate {
216/// Give a default warning
217Warn,
218219/// Duplicates will be a warning, with a note that this will be an error in the future.
220WarnButFutureError,
221222/// Give a default error
223Error,
224225/// Ignore duplicates
226Ignore,
227}
228229impl OnDuplicate {
230fn exec<P: SingleAttributeParser>(
231&self,
232 cx: &mut AcceptContext<'_, '_>,
233 used: Span,
234 unused: Span,
235 ) {
236match self {
237 OnDuplicate::Warn => cx.warn_unused_duplicate(used, unused),
238 OnDuplicate::WarnButFutureError => cx.warn_unused_duplicate_future_error(used, unused),
239 OnDuplicate::Error => {
240cx.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}
252253#[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(...)]`
256Normal,
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.
262Unsafe {
263/// The `note` is emitted during the `unsafe_code`, and explains to the user why this attribute is unsafe.
264note: &'static str,
265 unsafe_since: Option<Edition>,
266 },
267}
268269/// 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 {
275const PATH: &[Symbol];
276const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error;
277const ALLOWED_TARGETS: AllowedTargets<'_>;
278const SAFETY: AttributeSafety = AttributeSafety::Normal;
279const STABILITY: AttributeStability;
280281/// Create the [`AttributeKind`] given attribute's [`Span`].
282const CREATE: fn(Span) -> AttributeKind;
283284/// 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.
291fn finalize_check(_cx: &mut FinalizeCheckContext<'_, '_>, _attr_span: Span) {}
292}
293294pub(crate) struct WithoutArgs<T: NoArgsAttributeParser>(PhantomData<T>);
295296impl<T: NoArgsAttributeParser> Defaultfor WithoutArgs<T> {
297fn default() -> Self {
298Self(Default::default())
299 }
300}
301302impl<T: NoArgsAttributeParser> SingleAttributeParserfor WithoutArgs<T> {
303const PATH: &[Symbol] = T::PATH;
304const ON_DUPLICATE: OnDuplicate = T::ON_DUPLICATE;
305const SAFETY: AttributeSafety = T::SAFETY;
306const STABILITY: AttributeStability = T::STABILITY;
307const ALLOWED_TARGETS: AllowedTargets<'_> = T::ALLOWED_TARGETS;
308const TEMPLATE: AttributeTemplate = crate::AttributeTemplate {
word: true,
list: None,
one_of: &[],
name_value_str: None,
docs: None,
}template!(Word);
309310fn convert(cx: &mut AcceptContext<'_, '_>, args: &ArgParser) -> Option<AttributeKind> {
311let _ = cx.expect_no_args(args);
312Some(T::CREATE(cx.attr_span))
313 }
314315fn finalize_check(cx: &mut FinalizeCheckContext<'_, '_>, attr_span: Span) {
316 T::finalize_check(cx, attr_span)
317 }
318}
319320type ConvertFn<E> = fn(ThinVec<E>, Span) -> AttributeKind;
321322/// 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 {
330const PATH: &[rustc_span::Symbol];
331332type 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.
337const CONVERT: ConvertFn<Self::Item>;
338const SAFETY: AttributeSafety = AttributeSafety::Normal;
339const STABILITY: AttributeStability;
340341const ALLOWED_TARGETS: AllowedTargets<'_>;
342343/// The template this attribute parser should implement. Used for diagnostics.
344const TEMPLATE: AttributeTemplate;
345346/// Converts a single syntactical attribute to a number of elements of the semantic attribute, or [`AttributeKind`]
347fn extend(
348 cx: &mut AcceptContext<'_, '_>,
349 args: &ArgParser,
350 ) -> impl IntoIterator<Item = Self::Item>;
351352/// 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.
359fn finalize_check(_cx: &mut FinalizeCheckContext<'_, '_>, _attr_span: Span) {}
360}
361362/// 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.
367items: ThinVec<<T as CombineAttributeParser>::Item>,
368/// The full span of the first attribute that was encountered.
369first_span: Option<Span>,
370}
371372impl<T: CombineAttributeParser> Defaultfor Combine<T> {
373fn default() -> Self {
374Self {
375 phantom: Default::default(),
376 items: Default::default(),
377 first_span: Default::default(),
378 }
379 }
380}
381382impl<T: CombineAttributeParser> AttributeParserfor Combine<T> {
383const 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
386group.first_span.get_or_insert(cx.attr_span);
387group.items.extend(T::extend(cx, args))
388 })];
389const ALLOWED_TARGETS: AllowedTargets<'_> = T::ALLOWED_TARGETS;
390const SAFETY: AttributeSafety = T::SAFETY;
391392fn finalize(self, _cx: &FinalizeContext<'_, '_>) -> Option<AttributeKind> {
393let first_span = self.first_span?;
394Some(T::CONVERT(self.items, first_span))
395 }
396397fn deferred_finalize_check(&self) -> Option<(FinalizeCheckFn, Span)> {
398Some((<T as CombineAttributeParser>::finalize_check, self.first_span?))
399 }
400}