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 body;
34pub(crate) mod cfg;
35pub(crate) mod cfg_select;
36pub(crate) mod cfi_encoding;
37pub(crate) mod codegen_attrs;
38pub(crate) mod confusables;
39pub(crate) mod crate_level;
40pub(crate) mod debugger;
41pub(crate) mod deprecation;
42pub(crate) mod doc;
43pub(crate) mod dummy;
44pub(crate) mod inline;
45pub(crate) mod instruction_set;
46pub(crate) mod link_attrs;
47pub(crate) mod lint_helpers;
48pub(crate) mod loop_match;
49pub(crate) mod macro_attrs;
50pub(crate) mod must_use;
51pub(crate) mod no_implicit_prelude;
52pub(crate) mod no_link;
53pub(crate) mod non_exhaustive;
54pub(crate) mod path;
55pub(crate) mod pin_v2;
56pub(crate) mod proc_macro_attrs;
57pub(crate) mod prototype;
58pub(crate) mod repr;
59pub(crate) mod rustc_internal;
60pub(crate) mod semantics;
61pub(crate) mod stability;
62pub(crate) mod test_attrs;
63pub(crate) mod traits;
64pub(crate) mod transparency;
65pub(crate) mod util;
66
67type AcceptFn<T, S> = for<'sess> fn(&mut T, &mut AcceptContext<'_, 'sess, S>, &ArgParser);
68type AcceptMapping<T, S> = &'static [(&'static [Symbol], AttributeTemplate, AcceptFn<T, S>)];
69
70/// An [`AttributeParser`] is a type which searches for syntactic attributes.
71///
72/// Parsers are often tiny state machines that gets to see all syntactical attributes on an item.
73/// [`Default::default`] creates a fresh instance that sits in some kind of initial state, usually that the
74/// attribute it is looking for was not yet seen.
75///
76/// Then, it defines what paths this group will accept in [`AttributeParser::ATTRIBUTES`].
77/// These are listed as pairs, of symbols and function pointers. The function pointer will
78/// be called when that attribute is found on an item, which can influence the state of the little
79/// state machine.
80///
81/// Finally, after all attributes on an item have been seen, and possibly been accepted,
82/// the [`finalize`](AttributeParser::finalize) functions for all attribute parsers are called. Each can then report
83/// whether it has seen the attribute it has been looking for.
84///
85/// The state machine is automatically reset to parse attributes on the next item.
86///
87/// For a simpler attribute parsing interface, consider using [`SingleAttributeParser`]
88/// or [`CombineAttributeParser`] instead.
89pub(crate) trait AttributeParser<S: Stage>: Default + 'static {
90    /// The symbols for the attributes that this parser is interested in.
91    ///
92    /// If an attribute has this symbol, the `accept` function will be called on it.
93    const ATTRIBUTES: AcceptMapping<Self, S>;
94    const ALLOWED_TARGETS: AllowedTargets;
95
96    /// The parser has gotten a chance to accept the attributes on an item,
97    /// here it can produce an attribute.
98    ///
99    /// All finalize methods of all parsers are unconditionally called.
100    /// This means you can't unconditionally return `Some` here,
101    /// that'd be equivalent to unconditionally applying an attribute to
102    /// every single syntax item that could have attributes applied to it.
103    /// Your accept mappings should determine whether this returns something.
104    fn finalize(self, cx: &FinalizeContext<'_, '_, S>) -> Option<AttributeKind>;
105}
106
107/// Alternative to [`AttributeParser`] that automatically handles state management.
108/// A slightly simpler and more restricted way to convert attributes.
109/// Assumes that an attribute can only appear a single time on an item,
110/// and errors when it sees more.
111///
112/// [`Single<T> where T: SingleAttributeParser`](Single) implements [`AttributeParser`].
113///
114/// [`SingleAttributeParser`] can only convert attributes one-to-one, and cannot combine multiple
115/// attributes together like is necessary for `#[stable()]` and `#[unstable()]` for example.
116pub(crate) trait SingleAttributeParser<S: Stage>: 'static {
117    /// The single path of the attribute this parser accepts.
118    ///
119    /// If you need the parser to accept more than one path, use [`AttributeParser`] instead
120    const PATH: &[Symbol];
121
122    /// Configures the precedence of attributes with the same `PATH` on a syntax node.
123    const ATTRIBUTE_ORDER: AttributeOrder;
124
125    /// Configures what to do when when the same attribute is
126    /// applied more than once on the same syntax node.
127    ///
128    /// [`ATTRIBUTE_ORDER`](Self::ATTRIBUTE_ORDER) specified which one is assumed to be correct,
129    /// and this specified whether to, for example, warn or error on the other one.
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                match T::ATTRIBUTE_ORDER {
161                    // keep the first and report immediately. ignore this attribute
162                    AttributeOrder::KeepInnermost => {
163                        if let Some((_, unused)) = group.1 {
164                            T::ON_DUPLICATE.exec::<T>(cx, cx.attr_span, unused);
165                            return;
166                        }
167                    }
168                    // keep the new one and warn about the previous,
169                    // then replace
170                    AttributeOrder::KeepOutermost => {
171                        if let Some((_, used)) = group.1 {
172                            T::ON_DUPLICATE.exec::<T>(cx, used, cx.attr_span);
173                        }
174                    }
175                }
176
177                group.1 = Some((pa, cx.attr_span));
178            }
179        },
180    )];
181    const ALLOWED_TARGETS: AllowedTargets = T::ALLOWED_TARGETS;
182
183    fn finalize(self, _cx: &FinalizeContext<'_, '_, S>) -> Option<AttributeKind> {
184        Some(self.1?.0)
185    }
186}
187
188pub(crate) enum OnDuplicate<S: Stage> {
189    /// Give a default warning
190    Warn,
191
192    /// Duplicates will be a warning, with a note that this will be an error in the future.
193    WarnButFutureError,
194
195    /// Give a default error
196    Error,
197
198    /// Ignore duplicates
199    Ignore,
200
201    /// Custom function called when a duplicate attribute is found.
202    ///
203    /// - `unused` is the span of the attribute that was unused or bad because of some
204    ///   duplicate reason (see [`AttributeOrder`])
205    /// - `used` is the span of the attribute that was used in favor of the unused attribute
206    Custom(fn(cx: &AcceptContext<'_, '_, S>, used: Span, unused: Span)),
207}
208
209impl<S: Stage> OnDuplicate<S> {
210    fn exec<P: SingleAttributeParser<S>>(
211        &self,
212        cx: &mut AcceptContext<'_, '_, S>,
213        used: Span,
214        unused: Span,
215    ) {
216        match self {
217            OnDuplicate::Warn => cx.warn_unused_duplicate(used, unused),
218            OnDuplicate::WarnButFutureError => cx.warn_unused_duplicate_future_error(used, unused),
219            OnDuplicate::Error => {
220                cx.emit_err(UnusedMultiple {
221                    this: used,
222                    other: unused,
223                    name: Symbol::intern(
224                        &P::PATH.into_iter().map(|i| i.to_string()).collect::<Vec<_>>().join(".."),
225                    ),
226                });
227            }
228            OnDuplicate::Ignore => {}
229            OnDuplicate::Custom(f) => f(cx, used, unused),
230        }
231    }
232}
233
234pub(crate) enum AttributeOrder {
235    /// Duplicates after the innermost instance of the attribute will be an error/warning.
236    /// Only keep the lowest attribute.
237    ///
238    /// Attributes are processed from bottom to top, so this raises a warning/error on all the attributes
239    /// further above the lowest one:
240    /// ```
241    /// #[stable(since="1.0")] //~ WARNING duplicated attribute
242    /// #[stable(since="2.0")]
243    /// ```
244    KeepInnermost,
245
246    /// Duplicates before the outermost instance of the attribute will be an error/warning.
247    /// Only keep the highest attribute.
248    ///
249    /// Attributes are processed from bottom to top, so this raises a warning/error on all the attributes
250    /// below the highest one:
251    /// ```
252    /// #[path="foo.rs"]
253    /// #[path="bar.rs"] //~ WARNING duplicated attribute
254    /// ```
255    KeepOutermost,
256}
257
258/// An even simpler version of [`SingleAttributeParser`]:
259/// now automatically check that there are no arguments provided to the attribute.
260///
261/// [`WithoutArgs<T> where T: NoArgsAttributeParser`](WithoutArgs) implements [`SingleAttributeParser`].
262//
263pub(crate) trait NoArgsAttributeParser<S: Stage>: 'static {
264    const PATH: &[Symbol];
265    const ON_DUPLICATE: OnDuplicate<S>;
266    const ALLOWED_TARGETS: AllowedTargets;
267
268    /// Create the [`AttributeKind`] given attribute's [`Span`].
269    const CREATE: fn(Span) -> AttributeKind;
270}
271
272pub(crate) struct WithoutArgs<T: NoArgsAttributeParser<S>, S: Stage>(PhantomData<(S, T)>);
273
274impl<T: NoArgsAttributeParser<S>, S: Stage> Default for WithoutArgs<T, S> {
275    fn default() -> Self {
276        Self(Default::default())
277    }
278}
279
280impl<T: NoArgsAttributeParser<S>, S: Stage> SingleAttributeParser<S> for WithoutArgs<T, S> {
281    const PATH: &[Symbol] = T::PATH;
282    const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepOutermost;
283    const ON_DUPLICATE: OnDuplicate<S> = T::ON_DUPLICATE;
284    const ALLOWED_TARGETS: AllowedTargets = T::ALLOWED_TARGETS;
285    const TEMPLATE: AttributeTemplate = template!(Word);
286
287    fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
288        if let Err(span) = args.no_args() {
289            cx.expected_no_args(span);
290        }
291        Some(T::CREATE(cx.attr_span))
292    }
293}
294
295type ConvertFn<E> = fn(ThinVec<E>, Span) -> AttributeKind;
296
297/// Alternative to [`AttributeParser`] that automatically handles state management.
298/// If multiple attributes appear on an element, combines the values of each into a
299/// [`ThinVec`].
300/// [`Combine<T> where T: CombineAttributeParser`](Combine) implements [`AttributeParser`].
301///
302/// [`CombineAttributeParser`] can only convert a single kind of attribute, and cannot combine multiple
303/// attributes together like is necessary for `#[stable()]` and `#[unstable()]` for example.
304pub(crate) trait CombineAttributeParser<S: Stage>: 'static {
305    const PATH: &[rustc_span::Symbol];
306
307    type Item;
308    /// A function that converts individual items (of type [`Item`](Self::Item)) into the final attribute.
309    ///
310    /// For example, individual representations from `#[repr(...)]` attributes into an `AttributeKind::Repr(x)`,
311    ///  where `x` is a vec of these individual reprs.
312    const CONVERT: ConvertFn<Self::Item>;
313
314    const ALLOWED_TARGETS: AllowedTargets;
315
316    /// The template this attribute parser should implement. Used for diagnostics.
317    const TEMPLATE: AttributeTemplate;
318
319    /// Converts a single syntactical attribute to a number of elements of the semantic attribute, or [`AttributeKind`]
320    fn extend(
321        cx: &mut AcceptContext<'_, '_, S>,
322        args: &ArgParser,
323    ) -> impl IntoIterator<Item = Self::Item>;
324}
325
326/// Use in combination with [`CombineAttributeParser`].
327/// `Combine<T: CombineAttributeParser>` implements [`AttributeParser`].
328pub(crate) struct Combine<T: CombineAttributeParser<S>, S: Stage> {
329    phantom: PhantomData<(S, T)>,
330    /// A list of all items produced by parsing attributes so far. One attribute can produce any amount of items.
331    items: ThinVec<<T as CombineAttributeParser<S>>::Item>,
332    /// The full span of the first attribute that was encountered.
333    first_span: Option<Span>,
334}
335
336impl<T: CombineAttributeParser<S>, S: Stage> Default for Combine<T, S> {
337    fn default() -> Self {
338        Self {
339            phantom: Default::default(),
340            items: Default::default(),
341            first_span: Default::default(),
342        }
343    }
344}
345
346impl<T: CombineAttributeParser<S>, S: Stage> AttributeParser<S> for Combine<T, S> {
347    const ATTRIBUTES: AcceptMapping<Self, S> =
348        &[(T::PATH, T::TEMPLATE, |group: &mut Combine<T, S>, cx, args| {
349            // Keep track of the span of the first attribute, for diagnostics
350            group.first_span.get_or_insert(cx.attr_span);
351            group.items.extend(T::extend(cx, args))
352        })];
353    const ALLOWED_TARGETS: AllowedTargets = T::ALLOWED_TARGETS;
354
355    fn finalize(self, _cx: &FinalizeContext<'_, '_, S>) -> Option<AttributeKind> {
356        if let Some(first_span) = self.first_span {
357            Some(T::CONVERT(self.items, first_span))
358        } else {
359            None
360        }
361    }
362}