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::DuplicateAttribute;
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 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;
8182type AcceptFn<T> = for<'sess> fn(&mut T, &mut AcceptContext<'_, 'sess>, &ArgParser);
83type AcceptMapping<T> =
84&'static [(&'static [Symbol], AttributeTemplate, AttributeStability, AcceptFn<T>)];
8586/// 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.
109const ATTRIBUTES: AcceptMapping<Self>;
110const ALLOWED_TARGETS: AllowedTargets<'_>;
111const SAFETY: AttributeSafety = AttributeSafety::Normal;
112113/// 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.
121fn finalize(self, cx: &FinalizeContext<'_, '_>) -> Option<AttributeKind>;
122123/// 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.
133fn deferred_finalize_check(&self) -> Option<(FinalizeCheckFn, Span)> {
134None135 }
136}
137138/// 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
151const PATH: &[Symbol];
152153/// Configures what to do when when the same attribute is
154 /// applied more than once on the same syntax node.
155const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error;
156const SAFETY: AttributeSafety = AttributeSafety::Normal;
157const STABILITY: AttributeStability;
158159const ALLOWED_TARGETS: AllowedTargets<'_>;
160161/// The template this attribute parser should implement. Used for diagnostics.
162const TEMPLATE: AttributeTemplate;
163164/// Converts a single syntactical attribute to a single semantic attribute, or [`AttributeKind`]
165fn convert(cx: &mut AcceptContext<'_, '_>, args: &ArgParser) -> Option<AttributeKind>;
166167/// 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.
174fn finalize_check(_cx: &mut FinalizeCheckContext<'_, '_>, _attr_span: Span) {}
175}
176177/// Use in combination with [`SingleAttributeParser`].
178/// `Single<T: SingleAttributeParser>` implements [`AttributeParser`].
179pub(crate) struct Single<T: SingleAttributeParser>(PhantomData<T>, Option<(AttributeKind, Span)>);
180181impl<T: SingleAttributeParser> Defaultfor Single<T> {
182fn default() -> Self {
183Self(Default::default(), Default::default())
184 }
185}
186187impl<T: SingleAttributeParser> AttributeParserfor Single<T> {
188const ATTRIBUTES: AcceptMapping<Self> = &[(
189 T::PATH,
190 <T as SingleAttributeParser>::TEMPLATE,
191 T::STABILITY,
192 |group: &mut Single<T>, cx, args| {
193if let Some(pa) = T::convert(cx, args) {
194if let Some((_, used)) = group.1 {
195 T::ON_DUPLICATE.exec::<T>(cx, used, cx.attr_span);
196 } else {
197group.1 = Some((pa, cx.attr_span));
198 }
199 }
200 },
201 )];
202const ALLOWED_TARGETS: AllowedTargets<'_> = T::ALLOWED_TARGETS;
203const SAFETY: AttributeSafety = T::SAFETY;
204205fn finalize(self, _cx: &FinalizeContext<'_, '_>) -> Option<AttributeKind> {
206let (kind, _span) = self.1?;
207Some(kind)
208 }
209210fn deferred_finalize_check(&self) -> Option<(FinalizeCheckFn, Span)> {
211let (_, span) = self.1.as_ref()?;
212Some((<T as SingleAttributeParser>::finalize_check, *span))
213 }
214}
215216pub(crate) enum OnDuplicate {
217/// Give a default warning
218Warn,
219220/// Duplicates will be a warning, with a note that this will be an error in the future.
221WarnButFutureError,
222223/// Give a default error
224Error,
225226/// Ignore duplicates
227Ignore,
228}
229230impl OnDuplicate {
231fn exec<P: SingleAttributeParser>(
232&self,
233 cx: &mut AcceptContext<'_, '_>,
234 used: Span,
235 unused: Span,
236 ) {
237let name =
238Symbol::intern(&P::PATH.iter().map(|i| i.to_string()).collect::<Vec<_>>().join("::"));
239match 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 => {
244cx.emit_err(DuplicateAttribute { this: unused, other: used, name, warning: false });
245 }
246 }
247 }
248}
249250#[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(...)]`
253Normal,
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.
259Unsafe {
260/// The `note` is emitted during the `unsafe_code`, and explains to the user why this attribute is unsafe.
261note: &'static str,
262 unsafe_since: Option<Edition>,
263 },
264}
265266/// 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 {
272const PATH: &[Symbol];
273const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error;
274const ALLOWED_TARGETS: AllowedTargets<'_>;
275const SAFETY: AttributeSafety = AttributeSafety::Normal;
276const STABILITY: AttributeStability;
277278/// Create the [`AttributeKind`] given attribute's [`Span`].
279const CREATE: fn(Span) -> AttributeKind;
280281/// 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.
288fn finalize_check(_cx: &mut FinalizeCheckContext<'_, '_>, _attr_span: Span) {}
289}
290291pub(crate) struct WithoutArgs<T: NoArgsAttributeParser>(PhantomData<T>);
292293impl<T: NoArgsAttributeParser> Defaultfor WithoutArgs<T> {
294fn default() -> Self {
295Self(Default::default())
296 }
297}
298299impl<T: NoArgsAttributeParser> SingleAttributeParserfor WithoutArgs<T> {
300const PATH: &[Symbol] = T::PATH;
301const ON_DUPLICATE: OnDuplicate = T::ON_DUPLICATE;
302const SAFETY: AttributeSafety = T::SAFETY;
303const STABILITY: AttributeStability = T::STABILITY;
304const ALLOWED_TARGETS: AllowedTargets<'_> = T::ALLOWED_TARGETS;
305const TEMPLATE: AttributeTemplate = crate::AttributeTemplate {
word: true,
list: None,
one_of: &[],
name_value_str: None,
docs: None,
}template!(Word);
306307fn convert(cx: &mut AcceptContext<'_, '_>, args: &ArgParser) -> Option<AttributeKind> {
308let _ = cx.expect_no_args(args);
309Some(T::CREATE(cx.attr_span))
310 }
311312fn finalize_check(cx: &mut FinalizeCheckContext<'_, '_>, attr_span: Span) {
313 T::finalize_check(cx, attr_span)
314 }
315}
316317type ConvertFn<E> = fn(ThinVec<E>, Span) -> AttributeKind;
318319/// 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 {
327const PATH: &[rustc_span::Symbol];
328329type 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.
334const CONVERT: ConvertFn<Self::Item>;
335const SAFETY: AttributeSafety = AttributeSafety::Normal;
336const STABILITY: AttributeStability;
337338const ALLOWED_TARGETS: AllowedTargets<'_>;
339340/// The template this attribute parser should implement. Used for diagnostics.
341const TEMPLATE: AttributeTemplate;
342343/// Converts a single syntactical attribute to a number of elements of the semantic attribute, or [`AttributeKind`]
344fn extend(
345 cx: &mut AcceptContext<'_, '_>,
346 args: &ArgParser,
347 ) -> impl IntoIterator<Item = Self::Item>;
348349/// 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.
356fn finalize_check(_cx: &mut FinalizeCheckContext<'_, '_>, _attr_span: Span) {}
357}
358359/// 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.
364items: ThinVec<<T as CombineAttributeParser>::Item>,
365/// The full span of the first attribute that was encountered.
366first_span: Option<Span>,
367}
368369impl<T: CombineAttributeParser> Defaultfor Combine<T> {
370fn default() -> Self {
371Self {
372 phantom: Default::default(),
373 items: Default::default(),
374 first_span: Default::default(),
375 }
376 }
377}
378379impl<T: CombineAttributeParser> AttributeParserfor Combine<T> {
380const 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
383group.first_span.get_or_insert(cx.attr_span);
384group.items.extend(T::extend(cx, args))
385 })];
386const ALLOWED_TARGETS: AllowedTargets<'_> = T::ALLOWED_TARGETS;
387const SAFETY: AttributeSafety = T::SAFETY;
388389fn finalize(self, _cx: &FinalizeContext<'_, '_>) -> Option<AttributeKind> {
390let first_span = self.first_span?;
391Some(T::CONVERT(self.items, first_span))
392 }
393394fn deferred_finalize_check(&self) -> Option<(FinalizeCheckFn, Span)> {
395Some((<T as CombineAttributeParser>::finalize_check, self.first_span?))
396 }
397}