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