rustc_feature/
builtin_attrs.rs

1//! Built-in attributes and `cfg` flag gating.
2
3use std::sync::LazyLock;
4
5use AttributeDuplicates::*;
6use AttributeGate::*;
7use AttributeType::*;
8use rustc_data_structures::fx::FxHashMap;
9use rustc_hir::AttrStyle;
10use rustc_hir::attrs::EncodeCrossCrate;
11use rustc_span::edition::Edition;
12use rustc_span::{Symbol, sym};
13
14use crate::Features;
15
16type GateFn = fn(&Features) -> bool;
17
18pub type GatedCfg = (Symbol, Symbol, GateFn);
19
20/// `cfg(...)`'s that are feature gated.
21const GATED_CFGS: &[GatedCfg] = &[
22    // (name in cfg, feature, function to check if the feature is enabled)
23    (sym::overflow_checks, sym::cfg_overflow_checks, Features::cfg_overflow_checks),
24    (sym::ub_checks, sym::cfg_ub_checks, Features::cfg_ub_checks),
25    (sym::contract_checks, sym::cfg_contract_checks, Features::cfg_contract_checks),
26    (sym::target_thread_local, sym::cfg_target_thread_local, Features::cfg_target_thread_local),
27    (
28        sym::target_has_atomic_equal_alignment,
29        sym::cfg_target_has_atomic_equal_alignment,
30        Features::cfg_target_has_atomic_equal_alignment,
31    ),
32    (
33        sym::target_has_atomic_load_store,
34        sym::cfg_target_has_atomic,
35        Features::cfg_target_has_atomic,
36    ),
37    (sym::sanitize, sym::cfg_sanitize, Features::cfg_sanitize),
38    (sym::version, sym::cfg_version, Features::cfg_version),
39    (sym::relocation_model, sym::cfg_relocation_model, Features::cfg_relocation_model),
40    (sym::sanitizer_cfi_generalize_pointers, sym::cfg_sanitizer_cfi, Features::cfg_sanitizer_cfi),
41    (sym::sanitizer_cfi_normalize_integers, sym::cfg_sanitizer_cfi, Features::cfg_sanitizer_cfi),
42    // this is consistent with naming of the compiler flag it's for
43    (sym::fmt_debug, sym::fmt_debug, Features::fmt_debug),
44    (sym::emscripten_wasm_eh, sym::cfg_emscripten_wasm_eh, Features::cfg_emscripten_wasm_eh),
45    (
46        sym::target_has_reliable_f16,
47        sym::cfg_target_has_reliable_f16_f128,
48        Features::cfg_target_has_reliable_f16_f128,
49    ),
50    (
51        sym::target_has_reliable_f16_math,
52        sym::cfg_target_has_reliable_f16_f128,
53        Features::cfg_target_has_reliable_f16_f128,
54    ),
55    (
56        sym::target_has_reliable_f128,
57        sym::cfg_target_has_reliable_f16_f128,
58        Features::cfg_target_has_reliable_f16_f128,
59    ),
60    (
61        sym::target_has_reliable_f128_math,
62        sym::cfg_target_has_reliable_f16_f128,
63        Features::cfg_target_has_reliable_f16_f128,
64    ),
65];
66
67/// Find a gated cfg determined by the `pred`icate which is given the cfg's name.
68pub fn find_gated_cfg(pred: impl Fn(Symbol) -> bool) -> Option<&'static GatedCfg> {
69    GATED_CFGS.iter().find(|(cfg_sym, ..)| pred(*cfg_sym))
70}
71
72// If you change this, please modify `src/doc/unstable-book` as well. You must
73// move that documentation into the relevant place in the other docs, and
74// remove the chapter on the flag.
75
76#[derive(Copy, Clone, PartialEq, Debug)]
77pub enum AttributeType {
78    /// Normal, builtin attribute that is consumed
79    /// by the compiler before the unused_attribute check
80    Normal,
81
82    /// Builtin attribute that is only allowed at the crate level
83    CrateLevel,
84}
85
86#[derive(Copy, Clone, PartialEq, Debug)]
87pub enum AttributeSafety {
88    /// Normal attribute that does not need `#[unsafe(...)]`
89    Normal,
90
91    /// Unsafe attribute that requires safety obligations to be discharged.
92    ///
93    /// An error is emitted when `#[unsafe(...)]` is omitted, except when the attribute's edition
94    /// is less than the one stored in `unsafe_since`. This handles attributes that were safe in
95    /// earlier editions, but become unsafe in later ones.
96    Unsafe { unsafe_since: Option<Edition> },
97}
98
99#[derive(Clone, Debug, Copy)]
100pub enum AttributeGate {
101    /// A gated attribute which requires a feature gate to be enabled.
102    Gated {
103        /// The feature gate, for example `#![feature(rustc_attrs)]` for rustc_* attributes.
104        feature: Symbol,
105        /// The error message displayed when an attempt is made to use the attribute without its feature gate.
106        message: &'static str,
107        /// Check function to be called during the `PostExpansionVisitor` pass.
108        check: fn(&Features) -> bool,
109        /// Notes to be displayed when an attempt is made to use the attribute without its feature gate.
110        notes: &'static [&'static str],
111    },
112    /// Ungated attribute, can be used on all release channels
113    Ungated,
114}
115
116// FIXME(jdonszelmann): move to rustc_hir::attrs
117/// A template that the attribute input must match.
118/// Only top-level shape (`#[attr]` vs `#[attr(...)]` vs `#[attr = ...]`) is considered now.
119#[derive(Clone, Copy, Default)]
120pub struct AttributeTemplate {
121    /// If `true`, the attribute is allowed to be a bare word like `#[test]`.
122    pub word: bool,
123    /// If `Some`, the attribute is allowed to take a list of items like `#[allow(..)]`.
124    pub list: Option<&'static [&'static str]>,
125    /// If non-empty, the attribute is allowed to take a list containing exactly
126    /// one of the listed words, like `#[coverage(off)]`.
127    pub one_of: &'static [Symbol],
128    /// If `Some`, the attribute is allowed to be a name/value pair where the
129    /// value is a string, like `#[must_use = "reason"]`.
130    pub name_value_str: Option<&'static [&'static str]>,
131    /// A link to the document for this attribute.
132    pub docs: Option<&'static str>,
133}
134
135pub enum AttrSuggestionStyle {
136    /// The suggestion is styled for a normal attribute.
137    /// The `AttrStyle` determines whether this is an inner or outer attribute.
138    Attribute(AttrStyle),
139    /// The suggestion is styled for an attribute embedded into another attribute.
140    /// For example, attributes inside `#[cfg_attr(true, attr(...)]`.
141    EmbeddedAttribute,
142    /// The suggestion is styled for macros that are parsed with attribute parsers.
143    /// For example, the `cfg!(predicate)` macro.
144    Macro,
145}
146
147impl AttributeTemplate {
148    pub fn suggestions(
149        &self,
150        style: AttrSuggestionStyle,
151        name: impl std::fmt::Display,
152    ) -> Vec<String> {
153        let (start, macro_call, end) = match style {
154            AttrSuggestionStyle::Attribute(AttrStyle::Outer) => ("#[", "", "]"),
155            AttrSuggestionStyle::Attribute(AttrStyle::Inner) => ("#![", "", "]"),
156            AttrSuggestionStyle::Macro => ("", "!", ""),
157            AttrSuggestionStyle::EmbeddedAttribute => ("", "", ""),
158        };
159
160        let mut suggestions = vec![];
161
162        if self.word {
163            debug_assert!(macro_call.is_empty(), "Macro suggestions use list style");
164            suggestions.push(format!("{start}{name}{end}"));
165        }
166        if let Some(descr) = self.list {
167            for descr in descr {
168                suggestions.push(format!("{start}{name}{macro_call}({descr}){end}"));
169            }
170        }
171        suggestions.extend(self.one_of.iter().map(|&word| format!("{start}{name}({word}){end}")));
172        if let Some(descr) = self.name_value_str {
173            debug_assert!(macro_call.is_empty(), "Macro suggestions use list style");
174            for descr in descr {
175                suggestions.push(format!("{start}{name} = \"{descr}\"{end}"));
176            }
177        }
178        suggestions.sort();
179
180        suggestions
181    }
182}
183
184/// How to handle multiple duplicate attributes on the same item.
185#[derive(Clone, Copy, Default)]
186pub enum AttributeDuplicates {
187    /// Duplicates of this attribute are allowed.
188    ///
189    /// This should only be used with attributes where duplicates have semantic
190    /// meaning, or some kind of "additive" behavior. For example, `#[warn(..)]`
191    /// can be specified multiple times, and it combines all the entries. Or use
192    /// this if there is validation done elsewhere.
193    #[default]
194    DuplicatesOk,
195    /// Duplicates after the first attribute will be an unused_attribute warning.
196    ///
197    /// This is usually used for "word" attributes, where they are used as a
198    /// boolean marker, like `#[used]`. It is not necessarily wrong that there
199    /// are duplicates, but the others should probably be removed.
200    WarnFollowing,
201    /// Same as `WarnFollowing`, but only issues warnings for word-style attributes.
202    ///
203    /// This is only for special cases, for example multiple `#[macro_use]` can
204    /// be warned, but multiple `#[macro_use(...)]` should not because the list
205    /// form has different meaning from the word form.
206    WarnFollowingWordOnly,
207    /// Duplicates after the first attribute will be an error.
208    ///
209    /// This should be used where duplicates would be ignored, but carry extra
210    /// meaning that could cause confusion. For example, `#[stable(since="1.0")]
211    /// #[stable(since="2.0")]`, which version should be used for `stable`?
212    ErrorFollowing,
213    /// Duplicates preceding the last instance of the attribute will be an error.
214    ///
215    /// This is the same as `ErrorFollowing`, except the last attribute is the
216    /// one that is "used". This is typically used in cases like codegen
217    /// attributes which usually only honor the last attribute.
218    ErrorPreceding,
219    /// Duplicates after the first attribute will be an unused_attribute warning
220    /// with a note that this will be an error in the future.
221    ///
222    /// This should be used for attributes that should be `ErrorFollowing`, but
223    /// because older versions of rustc silently accepted (and ignored) the
224    /// attributes, this is used to transition.
225    FutureWarnFollowing,
226    /// Duplicates preceding the last instance of the attribute will be a
227    /// warning, with a note that this will be an error in the future.
228    ///
229    /// This is the same as `FutureWarnFollowing`, except the last attribute is
230    /// the one that is "used". Ideally these can eventually migrate to
231    /// `ErrorPreceding`.
232    FutureWarnPreceding,
233}
234
235/// A convenience macro for constructing attribute templates.
236/// E.g., `template!(Word, List: "description")` means that the attribute
237/// supports forms `#[attr]` and `#[attr(description)]`.
238#[macro_export]
239macro_rules! template {
240    (Word) => { $crate::template!(@ true, None, &[], None, None) };
241    (Word, $link: literal) => { $crate::template!(@ true, None, &[], None, Some($link)) };
242    (List: $descr: expr) => { $crate::template!(@ false, Some($descr), &[], None, None) };
243    (List: $descr: expr, $link: literal) => { $crate::template!(@ false, Some($descr), &[], None, Some($link)) };
244    (OneOf: $one_of: expr) => { $crate::template!(@ false, None, $one_of, None, None) };
245    (NameValueStr: [$($descr: literal),* $(,)?]) => { $crate::template!(@ false, None, &[], Some(&[$($descr,)*]), None) };
246    (NameValueStr: [$($descr: literal),* $(,)?], $link: literal) => { $crate::template!(@ false, None, &[], Some(&[$($descr,)*]), Some($link)) };
247    (NameValueStr: $descr: literal) => { $crate::template!(@ false, None, &[], Some(&[$descr]), None) };
248    (NameValueStr: $descr: literal, $link: literal) => { $crate::template!(@ false, None, &[], Some(&[$descr]), Some($link)) };
249    (Word, List: $descr: expr) => { $crate::template!(@ true, Some($descr), &[], None, None) };
250    (Word, List: $descr: expr, $link: literal) => { $crate::template!(@ true, Some($descr), &[], None, Some($link)) };
251    (Word, NameValueStr: $descr: expr) => { $crate::template!(@ true, None, &[], Some(&[$descr]), None) };
252    (Word, NameValueStr: $descr: expr, $link: literal) => { $crate::template!(@ true, None, &[], Some(&[$descr]), Some($link)) };
253    (List: $descr1: expr, NameValueStr: $descr2: expr) => {
254        $crate::template!(@ false, Some($descr1), &[], Some(&[$descr2]), None)
255    };
256    (List: $descr1: expr, NameValueStr: $descr2: expr, $link: literal) => {
257        $crate::template!(@ false, Some($descr1), &[], Some(&[$descr2]), Some($link))
258    };
259    (Word, List: $descr1: expr, NameValueStr: $descr2: expr) => {
260        $crate::template!(@ true, Some($descr1), &[], Some(&[$descr2]), None)
261    };
262    (Word, List: $descr1: expr, NameValueStr: $descr2: expr, $link: literal) => {
263        $crate::template!(@ true, Some($descr1), &[], Some(&[$descr2]), Some($link))
264    };
265    (@ $word: expr, $list: expr, $one_of: expr, $name_value_str: expr, $link: expr) => { $crate::AttributeTemplate {
266        word: $word, list: $list, one_of: $one_of, name_value_str: $name_value_str, docs: $link,
267    } };
268}
269
270macro_rules! ungated {
271    (unsafe($edition:ident) $attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr $(,)?) => {
272        BuiltinAttribute {
273            name: sym::$attr,
274            encode_cross_crate: $encode_cross_crate,
275            type_: $typ,
276            safety: AttributeSafety::Unsafe { unsafe_since: Some(Edition::$edition) },
277            template: $tpl,
278            gate: Ungated,
279            duplicates: $duplicates,
280        }
281    };
282    (unsafe $attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr $(,)?) => {
283        BuiltinAttribute {
284            name: sym::$attr,
285            encode_cross_crate: $encode_cross_crate,
286            type_: $typ,
287            safety: AttributeSafety::Unsafe { unsafe_since: None },
288            template: $tpl,
289            gate: Ungated,
290            duplicates: $duplicates,
291        }
292    };
293    ($attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr $(,)?) => {
294        BuiltinAttribute {
295            name: sym::$attr,
296            encode_cross_crate: $encode_cross_crate,
297            type_: $typ,
298            safety: AttributeSafety::Normal,
299            template: $tpl,
300            gate: Ungated,
301            duplicates: $duplicates,
302        }
303    };
304}
305
306macro_rules! gated {
307    (unsafe $attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr, $gate:ident, $message:expr $(,)?) => {
308        BuiltinAttribute {
309            name: sym::$attr,
310            encode_cross_crate: $encode_cross_crate,
311            type_: $typ,
312            safety: AttributeSafety::Unsafe { unsafe_since: None },
313            template: $tpl,
314            duplicates: $duplicates,
315            gate: Gated {
316                feature: sym::$gate,
317                message: $message,
318                check: Features::$gate,
319                notes: &[],
320            },
321        }
322    };
323    (unsafe $attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr, $message:expr $(,)?) => {
324        BuiltinAttribute {
325            name: sym::$attr,
326            encode_cross_crate: $encode_cross_crate,
327            type_: $typ,
328            safety: AttributeSafety::Unsafe { unsafe_since: None },
329            template: $tpl,
330            duplicates: $duplicates,
331            gate: Gated {
332                feature: sym::$attr,
333                message: $message,
334                check: Features::$attr,
335                notes: &[],
336            },
337        }
338    };
339    ($attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr, $gate:ident, $message:expr $(,)?) => {
340        BuiltinAttribute {
341            name: sym::$attr,
342            encode_cross_crate: $encode_cross_crate,
343            type_: $typ,
344            safety: AttributeSafety::Normal,
345            template: $tpl,
346            duplicates: $duplicates,
347            gate: Gated {
348                feature: sym::$gate,
349                message: $message,
350                check: Features::$gate,
351                notes: &[],
352            },
353        }
354    };
355    ($attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr, $message:expr $(,)?) => {
356        BuiltinAttribute {
357            name: sym::$attr,
358            encode_cross_crate: $encode_cross_crate,
359            type_: $typ,
360            safety: AttributeSafety::Normal,
361            template: $tpl,
362            duplicates: $duplicates,
363            gate: Gated {
364                feature: sym::$attr,
365                message: $message,
366                check: Features::$attr,
367                notes: &[],
368            },
369        }
370    };
371}
372
373macro_rules! rustc_attr {
374    (TEST, $attr:ident, $typ:expr, $tpl:expr, $duplicate:expr, $encode_cross_crate:expr $(,)?) => {
375        rustc_attr!(
376            $attr,
377            $typ,
378            $tpl,
379            $duplicate,
380            $encode_cross_crate,
381            concat!(
382                "the `#[",
383                stringify!($attr),
384                "]` attribute is used for rustc unit tests"
385            ),
386        )
387    };
388    ($attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr, $($notes:expr),* $(,)?) => {
389        BuiltinAttribute {
390            name: sym::$attr,
391            encode_cross_crate: $encode_cross_crate,
392            type_: $typ,
393            safety: AttributeSafety::Normal,
394            template: $tpl,
395            duplicates: $duplicates,
396            gate: Gated {
397                feature: sym::rustc_attrs,
398                message: "use of an internal attribute",
399                check: Features::rustc_attrs,
400                notes: &[
401                    concat!("the `#[",
402                    stringify!($attr),
403                    "]` attribute is an internal implementation detail that will never be stable"),
404                    $($notes),*
405                    ]
406            },
407        }
408    };
409}
410
411macro_rules! experimental {
412    ($attr:ident) => {
413        concat!("the `#[", stringify!($attr), "]` attribute is an experimental feature")
414    };
415}
416
417pub struct BuiltinAttribute {
418    pub name: Symbol,
419    /// Whether this attribute is encode cross crate.
420    ///
421    /// If so, it is encoded in the crate metadata.
422    /// Otherwise, it can only be used in the local crate.
423    pub encode_cross_crate: EncodeCrossCrate,
424    pub type_: AttributeType,
425    pub safety: AttributeSafety,
426    pub template: AttributeTemplate,
427    pub duplicates: AttributeDuplicates,
428    pub gate: AttributeGate,
429}
430
431/// Attributes that have a special meaning to rustc or rustdoc.
432#[rustfmt::skip]
433pub static BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
434    // ==========================================================================
435    // Stable attributes:
436    // ==========================================================================
437
438    // Conditional compilation:
439    ungated!(
440        cfg, Normal,
441        template!(
442            List: &["predicate"],
443            "https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg-attribute"
444        ),
445        DuplicatesOk, EncodeCrossCrate::No
446    ),
447    ungated!(
448        cfg_attr, Normal,
449        template!(
450            List: &["predicate, attr1, attr2, ..."],
451            "https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg_attr-attribute"
452        ),
453        DuplicatesOk, EncodeCrossCrate::No
454    ),
455
456    // Testing:
457    ungated!(
458        ignore, Normal,
459        template!(
460            Word,
461            NameValueStr: "reason",
462            "https://doc.rust-lang.org/reference/attributes/testing.html#the-ignore-attribute"
463        ),
464        WarnFollowing, EncodeCrossCrate::No,
465    ),
466    ungated!(
467        should_panic, Normal,
468        template!(
469            Word,
470            List: &[r#"expected = "reason""#],
471            NameValueStr: "reason",
472            "https://doc.rust-lang.org/reference/attributes/testing.html#the-should_panic-attribute"
473        ),
474        FutureWarnFollowing, EncodeCrossCrate::No,
475    ),
476    // FIXME(Centril): This can be used on stable but shouldn't.
477    ungated!(
478        reexport_test_harness_main, CrateLevel, template!(NameValueStr: "name"), ErrorFollowing,
479        EncodeCrossCrate::No,
480    ),
481
482    // Macros:
483    ungated!(
484        automatically_derived, Normal,
485        template!(
486            Word,
487            "https://doc.rust-lang.org/reference/attributes/derive.html#the-automatically_derived-attribute"
488        ),
489        WarnFollowing, EncodeCrossCrate::Yes
490    ),
491    ungated!(
492        macro_use, Normal,
493        template!(
494            Word,
495            List: &["name1, name2, ..."],
496            "https://doc.rust-lang.org/reference/macros-by-example.html#the-macro_use-attribute"
497        ),
498        WarnFollowingWordOnly, EncodeCrossCrate::No,
499    ),
500    ungated!(macro_escape, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No), // Deprecated synonym for `macro_use`.
501    ungated!(
502        macro_export, Normal,
503        template!(
504            Word,
505            List: &["local_inner_macros"],
506            "https://doc.rust-lang.org/reference/macros-by-example.html#path-based-scope"
507        ),
508        WarnFollowing, EncodeCrossCrate::Yes
509    ),
510    ungated!(
511        proc_macro, Normal,
512        template!(
513            Word,
514            "https://doc.rust-lang.org/reference/procedural-macros.html#function-like-procedural-macros"),
515        ErrorFollowing, EncodeCrossCrate::No
516    ),
517    ungated!(
518        proc_macro_derive, Normal,
519        template!(
520            List: &["TraitName", "TraitName, attributes(name1, name2, ...)"],
521            "https://doc.rust-lang.org/reference/procedural-macros.html#derive-macros"
522        ),
523        ErrorFollowing, EncodeCrossCrate::No,
524    ),
525    ungated!(
526        proc_macro_attribute, Normal,
527        template!(Word, "https://doc.rust-lang.org/reference/procedural-macros.html#attribute-macros"),
528        ErrorFollowing, EncodeCrossCrate::No
529    ),
530
531    // Lints:
532    ungated!(
533        warn, Normal,
534        template!(
535            List: &["lint1", "lint1, lint2, ...", r#"lint1, lint2, lint3, reason = "...""#],
536            "https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-check-attributes"
537        ),
538        DuplicatesOk, EncodeCrossCrate::No,
539    ),
540    ungated!(
541        allow, Normal,
542        template!(
543            List: &["lint1", "lint1, lint2, ...", r#"lint1, lint2, lint3, reason = "...""#],
544            "https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-check-attributes"
545        ),
546        DuplicatesOk, EncodeCrossCrate::No,
547    ),
548    ungated!(
549        expect, Normal,
550        template!(
551            List: &["lint1", "lint1, lint2, ...", r#"lint1, lint2, lint3, reason = "...""#],
552            "https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-check-attributes"
553        ),
554        DuplicatesOk, EncodeCrossCrate::No,
555    ),
556    ungated!(
557        forbid, Normal,
558        template!(
559            List: &["lint1", "lint1, lint2, ...", r#"lint1, lint2, lint3, reason = "...""#],
560            "https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-check-attributes"
561        ),
562        DuplicatesOk, EncodeCrossCrate::No
563    ),
564    ungated!(
565        deny, Normal,
566        template!(
567            List: &["lint1", "lint1, lint2, ...", r#"lint1, lint2, lint3, reason = "...""#],
568            "https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-check-attributes"
569        ),
570        DuplicatesOk, EncodeCrossCrate::No
571    ),
572    ungated!(
573        must_use, Normal,
574        template!(
575            Word,
576            NameValueStr: "reason",
577            "https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute"
578        ),
579        FutureWarnFollowing, EncodeCrossCrate::Yes
580    ),
581    gated!(
582        must_not_suspend, Normal, template!(Word, NameValueStr: "reason"), WarnFollowing,
583        EncodeCrossCrate::Yes, experimental!(must_not_suspend)
584    ),
585    ungated!(
586        deprecated, Normal,
587        template!(
588            Word,
589            List: &[r#"/*opt*/ since = "version", /*opt*/ note = "reason""#],
590            NameValueStr: "reason",
591            "https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-deprecated-attribute"
592        ),
593        ErrorFollowing, EncodeCrossCrate::Yes
594    ),
595
596    // Crate properties:
597    ungated!(
598        crate_name, CrateLevel,
599        template!(
600            NameValueStr: "name",
601            "https://doc.rust-lang.org/reference/crates-and-source-files.html#the-crate_name-attribute"
602        ),
603        FutureWarnFollowing, EncodeCrossCrate::No,
604    ),
605    ungated!(
606        crate_type, CrateLevel,
607        template!(
608            NameValueStr: ["bin", "lib", "dylib", "cdylib", "rlib", "staticlib", "sdylib", "proc-macro"],
609            "https://doc.rust-lang.org/reference/linkage.html"
610        ),
611        DuplicatesOk, EncodeCrossCrate::No,
612    ),
613
614    // ABI, linking, symbols, and FFI
615    ungated!(
616        link, Normal,
617        template!(List: &[
618            r#"name = "...""#,
619            r#"name = "...", kind = "dylib|static|...""#,
620            r#"name = "...", wasm_import_module = "...""#,
621            r#"name = "...", import_name_type = "decorated|noprefix|undecorated""#,
622            r#"name = "...", kind = "dylib|static|...", wasm_import_module = "...", import_name_type = "decorated|noprefix|undecorated""#,
623        ], "https://doc.rust-lang.org/reference/items/external-blocks.html#the-link-attribute"),
624        DuplicatesOk, EncodeCrossCrate::No,
625    ),
626    ungated!(
627        link_name, Normal,
628        template!(NameValueStr: "name", "https://doc.rust-lang.org/reference/items/external-blocks.html#the-link_name-attribute"),
629        FutureWarnPreceding, EncodeCrossCrate::Yes
630    ),
631    ungated!(
632        no_link, Normal,
633        template!(Word, "https://doc.rust-lang.org/reference/items/extern-crates.html#the-no_link-attribute"),
634        WarnFollowing, EncodeCrossCrate::No
635    ),
636    ungated!(
637        repr, Normal,
638        template!(
639            List: &["C", "Rust", "transparent", "align(...)", "packed(...)", "<integer type>"],
640            "https://doc.rust-lang.org/reference/type-layout.html#representations"
641        ),
642        DuplicatesOk, EncodeCrossCrate::No
643    ),
644    // FIXME(#82232, #143834): temporarily renamed to mitigate `#[align]` nameres ambiguity
645    gated!(rustc_align, Normal, template!(List: &["alignment"]), DuplicatesOk, EncodeCrossCrate::No, fn_align, experimental!(rustc_align)),
646    gated!(rustc_align_static, Normal, template!(List: &["alignment"]), DuplicatesOk, EncodeCrossCrate::No, static_align, experimental!(rustc_align_static)),
647    ungated!(
648        unsafe(Edition2024) export_name, Normal,
649        template!(NameValueStr: "name", "https://doc.rust-lang.org/reference/abi.html#the-export_name-attribute"),
650        FutureWarnPreceding, EncodeCrossCrate::No
651    ),
652    ungated!(
653        unsafe(Edition2024) link_section, Normal,
654        template!(NameValueStr: "name", "https://doc.rust-lang.org/reference/abi.html#the-link_section-attribute"),
655        FutureWarnPreceding, EncodeCrossCrate::No
656    ),
657    ungated!(
658        unsafe(Edition2024) no_mangle, Normal,
659        template!(Word, "https://doc.rust-lang.org/reference/abi.html#the-no_mangle-attribute"),
660        WarnFollowing, EncodeCrossCrate::No
661    ),
662    ungated!(
663        used, Normal,
664        template!(Word, List: &["compiler", "linker"], "https://doc.rust-lang.org/reference/abi.html#the-used-attribute"),
665        WarnFollowing, EncodeCrossCrate::No
666    ),
667    ungated!(
668        link_ordinal, Normal,
669        template!(List: &["ordinal"], "https://doc.rust-lang.org/reference/items/external-blocks.html#the-link_ordinal-attribute"),
670        ErrorPreceding, EncodeCrossCrate::Yes
671    ),
672    ungated!(
673        unsafe naked, Normal,
674        template!(Word, "https://doc.rust-lang.org/reference/attributes/codegen.html#the-naked-attribute"),
675        WarnFollowing, EncodeCrossCrate::No
676    ),
677    // See `TyAndLayout::pass_indirectly_in_non_rustic_abis` for details.
678    rustc_attr!(
679        rustc_pass_indirectly_in_non_rustic_abis, Normal, template!(Word), ErrorFollowing,
680        EncodeCrossCrate::No,
681        "types marked with `#[rustc_pass_indirectly_in_non_rustic_abis]` are always passed indirectly by non-Rustic abis."
682    ),
683
684    // Limits:
685    ungated!(
686        recursion_limit, CrateLevel,
687        template!(NameValueStr: "N", "https://doc.rust-lang.org/reference/attributes/limits.html#the-recursion_limit-attribute"),
688        FutureWarnFollowing, EncodeCrossCrate::No
689    ),
690    ungated!(
691        type_length_limit, CrateLevel,
692        template!(NameValueStr: "N", "https://doc.rust-lang.org/reference/attributes/limits.html#the-type_length_limit-attribute"),
693        FutureWarnFollowing, EncodeCrossCrate::No
694    ),
695    gated!(
696        move_size_limit, CrateLevel, template!(NameValueStr: "N"), ErrorFollowing,
697        EncodeCrossCrate::No, large_assignments, experimental!(move_size_limit)
698    ),
699
700    // Entry point:
701    ungated!(
702        no_main, CrateLevel,
703        template!(Word, "https://doc.rust-lang.org/reference/crates-and-source-files.html#the-no_main-attribute"),
704        WarnFollowing, EncodeCrossCrate::No
705    ),
706
707    // Modules, prelude, and resolution:
708    ungated!(
709        path, Normal,
710        template!(NameValueStr: "file", "https://doc.rust-lang.org/reference/items/modules.html#the-path-attribute"),
711        FutureWarnFollowing, EncodeCrossCrate::No
712    ),
713    ungated!(
714        no_std, CrateLevel,
715        template!(Word, "https://doc.rust-lang.org/reference/names/preludes.html#the-no_std-attribute"),
716        WarnFollowing, EncodeCrossCrate::No
717    ),
718    ungated!(
719        no_implicit_prelude, Normal,
720        template!(Word, "https://doc.rust-lang.org/reference/names/preludes.html#the-no_implicit_prelude-attribute"),
721        WarnFollowing, EncodeCrossCrate::No
722    ),
723    ungated!(
724        non_exhaustive, Normal,
725        template!(Word, "https://doc.rust-lang.org/reference/attributes/type_system.html#the-non_exhaustive-attribute"),
726        WarnFollowing, EncodeCrossCrate::Yes
727    ),
728
729    // Runtime
730    ungated!(
731        windows_subsystem, CrateLevel,
732        template!(NameValueStr: ["windows", "console"], "https://doc.rust-lang.org/reference/runtime.html#the-windows_subsystem-attribute"),
733        FutureWarnFollowing, EncodeCrossCrate::No
734    ),
735    ungated!( // RFC 2070
736        panic_handler, Normal,
737        template!(Word, "https://doc.rust-lang.org/reference/panic.html#the-panic_handler-attribute"),
738        WarnFollowing, EncodeCrossCrate::Yes
739    ),
740
741    // Code generation:
742    ungated!(
743        inline, Normal,
744        template!(
745            Word,
746            List: &["always", "never"],
747            "https://doc.rust-lang.org/reference/attributes/codegen.html#the-inline-attribute"
748        ),
749        FutureWarnFollowing, EncodeCrossCrate::No
750    ),
751    ungated!(
752        cold, Normal,
753        template!(Word, "https://doc.rust-lang.org/reference/attributes/codegen.html#the-cold-attribute"),
754        WarnFollowing, EncodeCrossCrate::No
755    ),
756    ungated!(
757        no_builtins, CrateLevel,
758        template!(Word, "https://doc.rust-lang.org/reference/attributes/codegen.html#the-no_builtins-attribute"),
759        WarnFollowing, EncodeCrossCrate::Yes
760    ),
761    ungated!(
762        target_feature, Normal,
763        template!(List: &[r#"enable = "name""#], "https://doc.rust-lang.org/reference/attributes/codegen.html#the-target_feature-attribute"),
764        DuplicatesOk, EncodeCrossCrate::No,
765    ),
766    ungated!(
767        track_caller, Normal,
768        template!(Word, "https://doc.rust-lang.org/reference/attributes/codegen.html#the-track_caller-attribute"),
769        WarnFollowing, EncodeCrossCrate::Yes
770    ),
771    ungated!(
772        instruction_set, Normal,
773        template!(List: &["set"], "https://doc.rust-lang.org/reference/attributes/codegen.html#the-instruction_set-attribute"),
774        ErrorPreceding, EncodeCrossCrate::No
775    ),
776    gated!(
777        unsafe force_target_feature, Normal, template!(List: &[r#"enable = "name""#]),
778        DuplicatesOk, EncodeCrossCrate::No, effective_target_features, experimental!(force_target_feature)
779    ),
780    gated!(
781        sanitize, Normal, template!(List: &[r#"address = "on|off""#, r#"kernel_address = "on|off""#, r#"cfi = "on|off""#, r#"hwaddress = "on|off""#, r#"kcfi = "on|off""#, r#"memory = "on|off""#, r#"memtag = "on|off""#, r#"shadow_call_stack = "on|off""#, r#"thread = "on|off""#]), ErrorPreceding,
782        EncodeCrossCrate::No, sanitize, experimental!(sanitize),
783    ),
784    gated!(
785        coverage, Normal, template!(OneOf: &[sym::off, sym::on]),
786        ErrorPreceding, EncodeCrossCrate::No,
787        coverage_attribute, experimental!(coverage)
788    ),
789
790    ungated!(
791        doc, Normal,
792        template!(
793            List: &["hidden", "inline"],
794            NameValueStr: "string",
795            "https://doc.rust-lang.org/rustdoc/write-documentation/the-doc-attribute.html"
796        ),
797        DuplicatesOk, EncodeCrossCrate::Yes
798    ),
799
800    // Debugging
801    ungated!(
802        debugger_visualizer, Normal,
803        template!(
804            List: &[r#"natvis_file = "...", gdb_script_file = "...""#],
805            "https://doc.rust-lang.org/reference/attributes/debugger.html#the-debugger_visualizer-attribute"
806        ),
807        DuplicatesOk, EncodeCrossCrate::No
808    ),
809    ungated!(
810        collapse_debuginfo, Normal,
811        template!(
812            List: &["no", "external", "yes"],
813            "https://doc.rust-lang.org/reference/attributes/debugger.html#the-collapse_debuginfo-attribute"
814        ),
815        ErrorFollowing, EncodeCrossCrate::Yes
816    ),
817
818    // ==========================================================================
819    // Unstable attributes:
820    // ==========================================================================
821
822    // Linking:
823    gated!(
824        export_stable, Normal, template!(Word), WarnFollowing,
825        EncodeCrossCrate::No, experimental!(export_stable)
826    ),
827
828    // Testing:
829    gated!(
830        test_runner, CrateLevel, template!(List: &["path"]), ErrorFollowing,
831        EncodeCrossCrate::Yes, custom_test_frameworks,
832        "custom test frameworks are an unstable feature",
833    ),
834    // RFC #1268
835    gated!(
836        marker, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No,
837        marker_trait_attr, experimental!(marker)
838    ),
839    gated!(
840        thread_local, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No,
841        "`#[thread_local]` is an experimental feature, and does not currently handle destructors",
842    ),
843    gated!(
844        no_core, CrateLevel, template!(Word), WarnFollowing,
845        EncodeCrossCrate::No, experimental!(no_core)
846    ),
847    // RFC 2412
848    gated!(
849        optimize, Normal, template!(List: &["none", "size", "speed"]), ErrorPreceding,
850        EncodeCrossCrate::No, optimize_attribute, experimental!(optimize)
851    ),
852
853    gated!(
854        unsafe ffi_pure, Normal, template!(Word), WarnFollowing,
855        EncodeCrossCrate::No, experimental!(ffi_pure)
856    ),
857    gated!(
858        unsafe ffi_const, Normal, template!(Word), WarnFollowing,
859        EncodeCrossCrate::No, experimental!(ffi_const)
860    ),
861    gated!(
862        register_tool, CrateLevel, template!(List: &["tool1, tool2, ..."]), DuplicatesOk,
863        EncodeCrossCrate::No, experimental!(register_tool),
864    ),
865
866    // lang-team MCP 147
867    gated!(
868        deprecated_safe, Normal, template!(List: &[r#"since = "version", note = "...""#]), ErrorFollowing,
869        EncodeCrossCrate::Yes, experimental!(deprecated_safe),
870    ),
871
872    // `#[cfi_encoding = ""]`
873    gated!(
874        cfi_encoding, Normal, template!(NameValueStr: "encoding"), ErrorPreceding,
875        EncodeCrossCrate::Yes, experimental!(cfi_encoding)
876    ),
877
878    // `#[coroutine]` attribute to be applied to closures to make them coroutines instead
879    gated!(
880        coroutine, Normal, template!(Word), ErrorFollowing,
881        EncodeCrossCrate::No, coroutines, experimental!(coroutine)
882    ),
883
884    // RFC 3543
885    // `#[patchable_function_entry(prefix_nops = m, entry_nops = n)]`
886    gated!(
887        patchable_function_entry, Normal, template!(List: &["prefix_nops = m, entry_nops = n"]), ErrorPreceding,
888        EncodeCrossCrate::Yes, experimental!(patchable_function_entry)
889    ),
890
891    // Probably temporary component of min_generic_const_args.
892    // `#[type_const] const ASSOC: usize;`
893    gated!(
894        type_const, Normal, template!(Word), ErrorFollowing,
895        EncodeCrossCrate::Yes, min_generic_const_args, experimental!(type_const),
896    ),
897
898    // The `#[loop_match]` and `#[const_continue]` attributes are part of the
899    // lang experiment for RFC 3720 tracked in:
900    //
901    // - https://github.com/rust-lang/rust/issues/132306
902    gated!(
903        const_continue, Normal, template!(Word), ErrorFollowing,
904        EncodeCrossCrate::No, loop_match, experimental!(const_continue)
905    ),
906    gated!(
907        loop_match, Normal, template!(Word), ErrorFollowing,
908        EncodeCrossCrate::No, loop_match, experimental!(loop_match)
909    ),
910
911    // The `#[pin_v2]` attribute is part of the `pin_ergonomics` experiment
912    // that allows structurally pinning, tracked in:
913    //
914    // - https://github.com/rust-lang/rust/issues/130494
915    gated!(
916        pin_v2, Normal, template!(Word), ErrorFollowing,
917        EncodeCrossCrate::Yes, pin_ergonomics, experimental!(pin_v2),
918    ),
919
920    // ==========================================================================
921    // Internal attributes: Stability, deprecation, and unsafe:
922    // ==========================================================================
923
924    ungated!(
925        feature, CrateLevel,
926        template!(List: &["name1, name2, ..."]), DuplicatesOk, EncodeCrossCrate::No,
927    ),
928    // DuplicatesOk since it has its own validation
929    ungated!(
930        stable, Normal,
931        template!(List: &[r#"feature = "name", since = "version""#]), DuplicatesOk, EncodeCrossCrate::No,
932    ),
933    ungated!(
934        unstable, Normal,
935        template!(List: &[r#"feature = "name", reason = "...", issue = "N""#]), DuplicatesOk,
936        EncodeCrossCrate::Yes
937    ),
938    ungated!(
939        unstable_feature_bound, Normal, template!(Word, List: &["feat1, feat2, ..."]),
940        DuplicatesOk, EncodeCrossCrate::No,
941    ),
942    ungated!(
943        rustc_const_unstable, Normal, template!(List: &[r#"feature = "name""#]),
944        DuplicatesOk, EncodeCrossCrate::Yes
945    ),
946    ungated!(
947        rustc_const_stable, Normal,
948        template!(List: &[r#"feature = "name""#]), DuplicatesOk, EncodeCrossCrate::No,
949    ),
950    ungated!(
951        rustc_default_body_unstable, Normal,
952        template!(List: &[r#"feature = "name", reason = "...", issue = "N""#]),
953        DuplicatesOk, EncodeCrossCrate::No
954    ),
955    gated!(
956        allow_internal_unstable, Normal, template!(Word, List: &["feat1, feat2, ..."]),
957        DuplicatesOk, EncodeCrossCrate::Yes,
958        "allow_internal_unstable side-steps feature gating and stability checks",
959    ),
960    gated!(
961        allow_internal_unsafe, Normal, template!(Word), WarnFollowing,
962        EncodeCrossCrate::No, "allow_internal_unsafe side-steps the unsafe_code lint",
963    ),
964    rustc_attr!(
965        rustc_allowed_through_unstable_modules, Normal, template!(NameValueStr: "deprecation message"),
966        WarnFollowing, EncodeCrossCrate::No,
967        "rustc_allowed_through_unstable_modules special cases accidental stabilizations of stable items \
968        through unstable paths"
969    ),
970    rustc_attr!(
971        rustc_deprecated_safe_2024, Normal, template!(List: &[r#"audit_that = "...""#]),
972        ErrorFollowing, EncodeCrossCrate::Yes,
973        "`#[rustc_deprecated_safe_2024]` is used to declare functions unsafe across the edition 2024 boundary",
974    ),
975    rustc_attr!(
976        rustc_pub_transparent, Normal, template!(Word),
977        ErrorFollowing, EncodeCrossCrate::Yes,
978        "used internally to mark types with a `transparent` representation when it is guaranteed by the documentation",
979    ),
980
981
982    // ==========================================================================
983    // Internal attributes: Type system related:
984    // ==========================================================================
985
986    gated!(fundamental, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::Yes, experimental!(fundamental)),
987    gated!(
988        may_dangle, Normal, template!(Word), WarnFollowing,
989        EncodeCrossCrate::No, dropck_eyepatch,
990        "`may_dangle` has unstable semantics and may be removed in the future",
991    ),
992
993    rustc_attr!(
994        rustc_never_type_options,
995        Normal,
996        template!(List: &[
997            "",
998            r#"fallback = "unit""#,
999            r#"fallback = "niko""#,
1000            r#"fallback = "never""#,
1001            r#"fallback = "no""#,
1002        ]),
1003        ErrorFollowing,
1004        EncodeCrossCrate::No,
1005        "`rustc_never_type_options` is used to experiment with never type fallback and work on \
1006         never type stabilization"
1007    ),
1008
1009    // ==========================================================================
1010    // Internal attributes: Runtime related:
1011    // ==========================================================================
1012
1013    rustc_attr!(
1014        rustc_allocator, Normal, template!(Word), WarnFollowing,
1015        EncodeCrossCrate::No,
1016    ),
1017    rustc_attr!(
1018        rustc_nounwind, Normal, template!(Word), WarnFollowing,
1019        EncodeCrossCrate::No,
1020    ),
1021    rustc_attr!(
1022        rustc_reallocator, Normal, template!(Word), WarnFollowing,
1023        EncodeCrossCrate::No,
1024    ),
1025    rustc_attr!(
1026        rustc_deallocator, Normal, template!(Word), WarnFollowing,
1027        EncodeCrossCrate::No,
1028    ),
1029    rustc_attr!(
1030        rustc_allocator_zeroed, Normal, template!(Word), WarnFollowing,
1031        EncodeCrossCrate::No,
1032    ),
1033    rustc_attr!(
1034        rustc_allocator_zeroed_variant, Normal, template!(NameValueStr: "function"), ErrorPreceding,
1035        EncodeCrossCrate::Yes,
1036    ),
1037    gated!(
1038        default_lib_allocator, Normal, template!(Word), WarnFollowing,
1039        EncodeCrossCrate::No, allocator_internals, experimental!(default_lib_allocator),
1040    ),
1041    gated!(
1042        needs_allocator, Normal, template!(Word), WarnFollowing,
1043        EncodeCrossCrate::No, allocator_internals, experimental!(needs_allocator),
1044    ),
1045    gated!(
1046        panic_runtime, CrateLevel, template!(Word), WarnFollowing,
1047        EncodeCrossCrate::No, experimental!(panic_runtime)
1048    ),
1049    gated!(
1050        needs_panic_runtime, CrateLevel, template!(Word), WarnFollowing,
1051        EncodeCrossCrate::No, experimental!(needs_panic_runtime)
1052    ),
1053    gated!(
1054        compiler_builtins, CrateLevel, template!(Word), WarnFollowing,
1055        EncodeCrossCrate::No,
1056        "the `#[compiler_builtins]` attribute is used to identify the `compiler_builtins` crate \
1057        which contains compiler-rt intrinsics and will never be stable",
1058    ),
1059    gated!(
1060        profiler_runtime, CrateLevel, template!(Word), WarnFollowing,
1061        EncodeCrossCrate::No,
1062        "the `#[profiler_runtime]` attribute is used to identify the `profiler_builtins` crate \
1063        which contains the profiler runtime and will never be stable",
1064    ),
1065
1066    // ==========================================================================
1067    // Internal attributes, Linkage:
1068    // ==========================================================================
1069
1070    gated!(
1071        linkage, Normal, template!(NameValueStr: [
1072            "available_externally",
1073            "common",
1074            "extern_weak",
1075            "external",
1076            "internal",
1077            "linkonce",
1078            "linkonce_odr",
1079            "weak",
1080            "weak_odr",
1081        ], "https://doc.rust-lang.org/reference/linkage.html"),
1082        ErrorPreceding, EncodeCrossCrate::No,
1083        "the `linkage` attribute is experimental and not portable across platforms",
1084    ),
1085    rustc_attr!(
1086        rustc_std_internal_symbol, Normal, template!(Word), WarnFollowing,
1087        EncodeCrossCrate::No,
1088    ),
1089    rustc_attr!(
1090        rustc_objc_class, Normal, template!(NameValueStr: "ClassName"), ErrorPreceding,
1091        EncodeCrossCrate::No,
1092    ),
1093    rustc_attr!(
1094        rustc_objc_selector, Normal, template!(NameValueStr: "methodName"), ErrorPreceding,
1095        EncodeCrossCrate::No,
1096    ),
1097
1098    // ==========================================================================
1099    // Internal attributes, Macro related:
1100    // ==========================================================================
1101
1102    rustc_attr!(
1103        rustc_builtin_macro, Normal,
1104        template!(Word, List: &["name", "name, /*opt*/ attributes(name1, name2, ...)"]), ErrorFollowing,
1105        EncodeCrossCrate::Yes,
1106    ),
1107    rustc_attr!(
1108        rustc_proc_macro_decls, Normal, template!(Word), WarnFollowing,
1109        EncodeCrossCrate::No,
1110    ),
1111    rustc_attr!(
1112        rustc_macro_transparency, Normal,
1113        template!(NameValueStr: ["transparent", "semiopaque", "opaque"]), ErrorFollowing,
1114        EncodeCrossCrate::Yes, "used internally for testing macro hygiene",
1115    ),
1116    rustc_attr!(
1117        rustc_autodiff, Normal,
1118        template!(Word, List: &[r#""...""#]), DuplicatesOk,
1119        EncodeCrossCrate::Yes,
1120    ),
1121    // Traces that are left when `cfg` and `cfg_attr` attributes are expanded.
1122    // The attributes are not gated, to avoid stability errors, but they cannot be used in stable
1123    // or unstable code directly because `sym::cfg_(attr_)trace` are not valid identifiers, they
1124    // can only be generated by the compiler.
1125    ungated!(
1126        cfg_trace, Normal, template!(Word /* irrelevant */), DuplicatesOk,
1127        EncodeCrossCrate::Yes
1128    ),
1129    ungated!(
1130        cfg_attr_trace, Normal, template!(Word /* irrelevant */), DuplicatesOk,
1131        EncodeCrossCrate::No
1132    ),
1133
1134    // ==========================================================================
1135    // Internal attributes, Diagnostics related:
1136    // ==========================================================================
1137
1138    rustc_attr!(
1139        rustc_on_unimplemented, Normal,
1140        template!(
1141            List: &[r#"/*opt*/ message = "...", /*opt*/ label = "...", /*opt*/ note = "...""#],
1142            NameValueStr: "message"
1143        ),
1144        ErrorFollowing, EncodeCrossCrate::Yes,
1145        "see `#[diagnostic::on_unimplemented]` for the stable equivalent of this attribute"
1146    ),
1147    rustc_attr!(
1148        rustc_confusables, Normal,
1149        template!(List: &[r#""name1", "name2", ..."#]),
1150        ErrorFollowing, EncodeCrossCrate::Yes,
1151    ),
1152    // Enumerates "identity-like" conversion methods to suggest on type mismatch.
1153    rustc_attr!(
1154        rustc_conversion_suggestion, Normal, template!(Word),
1155        WarnFollowing, EncodeCrossCrate::Yes,
1156    ),
1157    // Prevents field reads in the marked trait or method to be considered
1158    // during dead code analysis.
1159    rustc_attr!(
1160        rustc_trivial_field_reads, Normal, template!(Word),
1161        WarnFollowing, EncodeCrossCrate::Yes,
1162    ),
1163    // Used by the `rustc::potential_query_instability` lint to warn methods which
1164    // might not be stable during incremental compilation.
1165    rustc_attr!(
1166        rustc_lint_query_instability, Normal, template!(Word),
1167        WarnFollowing, EncodeCrossCrate::Yes,
1168    ),
1169    // Used by the `rustc::untracked_query_information` lint to warn methods which
1170    // might not be stable during incremental compilation.
1171    rustc_attr!(
1172        rustc_lint_untracked_query_information, Normal, template!(Word),
1173        WarnFollowing, EncodeCrossCrate::Yes,
1174    ),
1175    // Used by the `rustc::diagnostic_outside_of_impl` lints to assist in changes to diagnostic
1176    // APIs. Any function with this attribute will be checked by that lint.
1177    rustc_attr!(
1178        rustc_lint_diagnostics, Normal, template!(Word),
1179        WarnFollowing, EncodeCrossCrate::Yes,
1180    ),
1181    // Used by the `rustc::bad_opt_access` lint to identify `DebuggingOptions` and `CodegenOptions`
1182    // types (as well as any others in future).
1183    rustc_attr!(
1184        rustc_lint_opt_ty, Normal, template!(Word),
1185        WarnFollowing, EncodeCrossCrate::Yes,
1186    ),
1187    // Used by the `rustc::bad_opt_access` lint on fields
1188    // types (as well as any others in future).
1189    rustc_attr!(
1190        rustc_lint_opt_deny_field_access, Normal, template!(List: &["message"]),
1191        WarnFollowing, EncodeCrossCrate::Yes,
1192    ),
1193
1194    // ==========================================================================
1195    // Internal attributes, Const related:
1196    // ==========================================================================
1197
1198    rustc_attr!(
1199        rustc_promotable, Normal, template!(Word), WarnFollowing,
1200        EncodeCrossCrate::No, ),
1201    rustc_attr!(
1202        rustc_legacy_const_generics, Normal, template!(List: &["N"]), ErrorFollowing,
1203        EncodeCrossCrate::Yes,
1204    ),
1205    // Do not const-check this function's body. It will always get replaced during CTFE via `hook_special_const_fn`.
1206    rustc_attr!(
1207        rustc_do_not_const_check, Normal, template!(Word), WarnFollowing,
1208        EncodeCrossCrate::Yes, "`#[rustc_do_not_const_check]` skips const-check for this function's body",
1209    ),
1210    rustc_attr!(
1211        rustc_const_stable_indirect, Normal,
1212        template!(Word),
1213        WarnFollowing,
1214        EncodeCrossCrate::No,
1215        "this is an internal implementation detail",
1216    ),
1217    rustc_attr!(
1218        rustc_intrinsic_const_stable_indirect, Normal,
1219        template!(Word), WarnFollowing, EncodeCrossCrate::No,  "this is an internal implementation detail",
1220    ),
1221    gated!(
1222        rustc_allow_const_fn_unstable, Normal,
1223        template!(Word, List: &["feat1, feat2, ..."]), DuplicatesOk, EncodeCrossCrate::No,
1224        "rustc_allow_const_fn_unstable side-steps feature gating and stability checks"
1225    ),
1226
1227    // ==========================================================================
1228    // Internal attributes, Layout related:
1229    // ==========================================================================
1230
1231    rustc_attr!(
1232        rustc_layout_scalar_valid_range_start, Normal, template!(List: &["value"]), ErrorFollowing,
1233        EncodeCrossCrate::Yes,
1234        "the `#[rustc_layout_scalar_valid_range_start]` attribute is just used to enable \
1235        niche optimizations in the standard library",
1236    ),
1237    rustc_attr!(
1238        rustc_layout_scalar_valid_range_end, Normal, template!(List: &["value"]), ErrorFollowing,
1239        EncodeCrossCrate::Yes,
1240        "the `#[rustc_layout_scalar_valid_range_end]` attribute is just used to enable \
1241        niche optimizations in the standard library",
1242    ),
1243    rustc_attr!(
1244        rustc_simd_monomorphize_lane_limit, Normal, template!(NameValueStr: "N"), ErrorFollowing,
1245        EncodeCrossCrate::Yes,
1246        "the `#[rustc_simd_monomorphize_lane_limit]` attribute is just used by std::simd \
1247        for better error messages",
1248    ),
1249    rustc_attr!(
1250        rustc_nonnull_optimization_guaranteed, Normal, template!(Word), WarnFollowing,
1251        EncodeCrossCrate::Yes,
1252        "the `#[rustc_nonnull_optimization_guaranteed]` attribute is just used to document \
1253        guaranteed niche optimizations in the standard library",
1254        "the compiler does not even check whether the type indeed is being non-null-optimized; \
1255        it is your responsibility to ensure that the attribute is only used on types that are optimized",
1256    ),
1257
1258    // ==========================================================================
1259    // Internal attributes, Misc:
1260    // ==========================================================================
1261    gated!(
1262        lang, Normal, template!(NameValueStr: "name"), DuplicatesOk, EncodeCrossCrate::No, lang_items,
1263        "lang items are subject to change",
1264    ),
1265    rustc_attr!(
1266        rustc_as_ptr, Normal, template!(Word), ErrorFollowing,
1267        EncodeCrossCrate::Yes,
1268        "`#[rustc_as_ptr]` is used to mark functions returning pointers to their inner allocations."
1269    ),
1270    rustc_attr!(
1271        rustc_should_not_be_called_on_const_items, Normal, template!(Word), ErrorFollowing,
1272        EncodeCrossCrate::Yes,
1273        "`#[rustc_should_not_be_called_on_const_items]` is used to mark methods that don't make sense to be called on interior mutable consts."
1274    ),
1275    rustc_attr!(
1276        rustc_pass_by_value, Normal, template!(Word), ErrorFollowing,
1277        EncodeCrossCrate::Yes,
1278        "`#[rustc_pass_by_value]` is used to mark types that must be passed by value instead of reference."
1279    ),
1280    rustc_attr!(
1281        rustc_never_returns_null_ptr, Normal, template!(Word), ErrorFollowing,
1282        EncodeCrossCrate::Yes,
1283        "`#[rustc_never_returns_null_ptr]` is used to mark functions returning non-null pointers."
1284    ),
1285    rustc_attr!(
1286        rustc_no_implicit_autorefs, AttributeType::Normal, template!(Word), ErrorFollowing, EncodeCrossCrate::Yes,
1287        "`#[rustc_no_implicit_autorefs]` is used to mark functions for which an autoref to the dereference of a raw pointer should not be used as an argument."
1288    ),
1289    rustc_attr!(
1290        rustc_coherence_is_core, AttributeType::CrateLevel, template!(Word), ErrorFollowing, EncodeCrossCrate::No,
1291        "`#![rustc_coherence_is_core]` allows inherent methods on builtin types, only intended to be used in `core`."
1292    ),
1293    rustc_attr!(
1294        rustc_coinductive, AttributeType::Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No,
1295        "`#[rustc_coinductive]` changes a trait to be coinductive, allowing cycles in the trait solver."
1296    ),
1297    rustc_attr!(
1298        rustc_allow_incoherent_impl, AttributeType::Normal, template!(Word), ErrorFollowing, EncodeCrossCrate::No,
1299        "`#[rustc_allow_incoherent_impl]` has to be added to all impl items of an incoherent inherent impl."
1300    ),
1301    rustc_attr!(
1302        rustc_preserve_ub_checks, AttributeType::CrateLevel, template!(Word), ErrorFollowing, EncodeCrossCrate::No,
1303        "`#![rustc_preserve_ub_checks]` prevents the designated crate from evaluating whether UB checks are enabled when optimizing MIR",
1304    ),
1305    rustc_attr!(
1306        rustc_deny_explicit_impl,
1307        AttributeType::Normal,
1308        template!(Word),
1309        ErrorFollowing,
1310        EncodeCrossCrate::No,
1311        "`#[rustc_deny_explicit_impl]` enforces that a trait can have no user-provided impls"
1312    ),
1313    rustc_attr!(
1314        rustc_do_not_implement_via_object,
1315        AttributeType::Normal,
1316        template!(Word),
1317        ErrorFollowing,
1318        EncodeCrossCrate::No,
1319        "`#[rustc_do_not_implement_via_object]` opts out of the automatic trait impl for trait objects \
1320        (`impl Trait for dyn Trait`)"
1321    ),
1322    rustc_attr!(
1323        rustc_has_incoherent_inherent_impls, AttributeType::Normal, template!(Word),
1324        ErrorFollowing, EncodeCrossCrate::Yes,
1325        "`#[rustc_has_incoherent_inherent_impls]` allows the addition of incoherent inherent impls for \
1326         the given type by annotating all impl items with `#[rustc_allow_incoherent_impl]`."
1327    ),
1328
1329    BuiltinAttribute {
1330        name: sym::rustc_diagnostic_item,
1331        // FIXME: This can be `true` once we always use `tcx.is_diagnostic_item`.
1332        encode_cross_crate: EncodeCrossCrate::Yes,
1333        type_: Normal,
1334        safety: AttributeSafety::Normal,
1335        template: template!(NameValueStr: "name"),
1336        duplicates: ErrorFollowing,
1337        gate: Gated{
1338            feature: sym::rustc_attrs,
1339            message: "use of an internal attribute",
1340            check: Features::rustc_attrs,
1341            notes: &["the `#[rustc_diagnostic_item]` attribute allows the compiler to reference types \
1342            from the standard library for diagnostic purposes"],
1343        },
1344    },
1345    gated!(
1346        // Used in resolve:
1347        prelude_import, Normal, template!(Word), WarnFollowing,
1348        EncodeCrossCrate::No, "`#[prelude_import]` is for use by rustc only",
1349    ),
1350    gated!(
1351        rustc_paren_sugar, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No,
1352        unboxed_closures, "unboxed_closures are still evolving",
1353    ),
1354    rustc_attr!(
1355        rustc_inherit_overflow_checks, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No,
1356        "the `#[rustc_inherit_overflow_checks]` attribute is just used to control \
1357        overflow checking behavior of several functions in the standard library that are inlined \
1358        across crates",
1359    ),
1360    rustc_attr!(
1361        rustc_reservation_impl, Normal,
1362        template!(NameValueStr: "reservation message"), ErrorFollowing, EncodeCrossCrate::Yes,
1363        "the `#[rustc_reservation_impl]` attribute is internally used \
1364        for reserving `impl<T> From<!> for T` as part of the effort to stabilize `!`"
1365    ),
1366    rustc_attr!(
1367        rustc_test_marker, Normal, template!(NameValueStr: "name"), WarnFollowing,
1368        EncodeCrossCrate::No, "the `#[rustc_test_marker]` attribute is used internally to track tests",
1369    ),
1370    rustc_attr!(
1371        rustc_unsafe_specialization_marker, Normal, template!(Word),
1372        WarnFollowing, EncodeCrossCrate::No,
1373        "the `#[rustc_unsafe_specialization_marker]` attribute is used to check specializations"
1374    ),
1375    rustc_attr!(
1376        rustc_specialization_trait, Normal, template!(Word),
1377        WarnFollowing, EncodeCrossCrate::No,
1378        "the `#[rustc_specialization_trait]` attribute is used to check specializations"
1379    ),
1380    rustc_attr!(
1381        rustc_main, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No,
1382        "the `#[rustc_main]` attribute is used internally to specify test entry point function",
1383    ),
1384    rustc_attr!(
1385        rustc_skip_during_method_dispatch, Normal, template!(List: &["array, boxed_slice"]), ErrorFollowing,
1386        EncodeCrossCrate::No,
1387        "the `#[rustc_skip_during_method_dispatch]` attribute is used to exclude a trait \
1388        from method dispatch when the receiver is of the following type, for compatibility in \
1389        editions < 2021 (array) or editions < 2024 (boxed_slice)."
1390    ),
1391    rustc_attr!(
1392        rustc_must_implement_one_of, Normal, template!(List: &["function1, function2, ..."]),
1393        ErrorFollowing, EncodeCrossCrate::No,
1394        "the `#[rustc_must_implement_one_of]` attribute is used to change minimal complete \
1395        definition of a trait. Its syntax and semantics are highly experimental and will be \
1396        subject to change before stabilization",
1397    ),
1398    rustc_attr!(
1399        rustc_doc_primitive, Normal, template!(NameValueStr: "primitive name"), ErrorFollowing,
1400        EncodeCrossCrate::Yes, "the `#[rustc_doc_primitive]` attribute is used by the standard library \
1401        to provide a way to generate documentation for primitive types",
1402    ),
1403    gated!(
1404        rustc_intrinsic, Normal, template!(Word), ErrorFollowing, EncodeCrossCrate::Yes, intrinsics,
1405        "the `#[rustc_intrinsic]` attribute is used to declare intrinsics as function items",
1406    ),
1407    rustc_attr!(
1408        rustc_no_mir_inline, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::Yes,
1409        "`#[rustc_no_mir_inline]` prevents the MIR inliner from inlining a function while not affecting codegen"
1410    ),
1411    rustc_attr!(
1412        rustc_force_inline, Normal, template!(Word, NameValueStr: "reason"), WarnFollowing, EncodeCrossCrate::Yes,
1413        "`#[rustc_force_inline]` forces a free function to be inlined"
1414    ),
1415
1416    // ==========================================================================
1417    // Internal attributes, Testing:
1418    // ==========================================================================
1419
1420    rustc_attr!(TEST, rustc_effective_visibility, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::Yes),
1421    rustc_attr!(
1422        TEST, rustc_outlives, Normal, template!(Word),
1423        WarnFollowing, EncodeCrossCrate::No
1424    ),
1425    rustc_attr!(
1426        TEST, rustc_capture_analysis, Normal, template!(Word),
1427        WarnFollowing, EncodeCrossCrate::No
1428    ),
1429    rustc_attr!(
1430        TEST, rustc_insignificant_dtor, Normal, template!(Word),
1431        WarnFollowing, EncodeCrossCrate::Yes
1432    ),
1433    rustc_attr!(
1434        TEST, rustc_no_implicit_bounds, CrateLevel, template!(Word),
1435        WarnFollowing, EncodeCrossCrate::No
1436    ),
1437    rustc_attr!(
1438        TEST, rustc_strict_coherence, Normal, template!(Word),
1439        WarnFollowing, EncodeCrossCrate::Yes
1440    ),
1441    rustc_attr!(
1442        TEST, rustc_variance, Normal, template!(Word),
1443        WarnFollowing, EncodeCrossCrate::No
1444    ),
1445    rustc_attr!(
1446        TEST, rustc_variance_of_opaques, Normal, template!(Word),
1447        WarnFollowing, EncodeCrossCrate::No
1448    ),
1449    rustc_attr!(
1450        TEST, rustc_hidden_type_of_opaques, Normal, template!(Word),
1451        WarnFollowing, EncodeCrossCrate::No
1452    ),
1453    rustc_attr!(
1454        TEST, rustc_layout, Normal, template!(List: &["field1, field2, ..."]),
1455        WarnFollowing, EncodeCrossCrate::Yes
1456    ),
1457    rustc_attr!(
1458        TEST, rustc_abi, Normal, template!(List: &["field1, field2, ..."]),
1459        WarnFollowing, EncodeCrossCrate::No
1460    ),
1461    rustc_attr!(
1462        TEST, rustc_regions, Normal, template!(Word),
1463        WarnFollowing, EncodeCrossCrate::No
1464    ),
1465    rustc_attr!(
1466        TEST, rustc_delayed_bug_from_inside_query, Normal,
1467        template!(Word),
1468        WarnFollowing, EncodeCrossCrate::No
1469    ),
1470    rustc_attr!(
1471        TEST, rustc_dump_user_args, Normal, template!(Word),
1472        WarnFollowing, EncodeCrossCrate::No
1473    ),
1474    rustc_attr!(
1475        TEST, rustc_evaluate_where_clauses, Normal, template!(Word), WarnFollowing,
1476        EncodeCrossCrate::Yes
1477    ),
1478    rustc_attr!(
1479        TEST, rustc_if_this_changed, Normal, template!(Word, List: &["DepNode"]), DuplicatesOk,
1480        EncodeCrossCrate::No
1481    ),
1482    rustc_attr!(
1483        TEST, rustc_then_this_would_need, Normal, template!(List: &["DepNode"]), DuplicatesOk,
1484        EncodeCrossCrate::No
1485    ),
1486    rustc_attr!(
1487        TEST, rustc_clean, Normal,
1488        template!(List: &[r#"cfg = "...", /*opt*/ label = "...", /*opt*/ except = "...""#]),
1489        DuplicatesOk, EncodeCrossCrate::No
1490    ),
1491    rustc_attr!(
1492        TEST, rustc_partition_reused, Normal,
1493        template!(List: &[r#"cfg = "...", module = "...""#]), DuplicatesOk, EncodeCrossCrate::No
1494    ),
1495    rustc_attr!(
1496        TEST, rustc_partition_codegened, Normal,
1497        template!(List: &[r#"cfg = "...", module = "...""#]), DuplicatesOk, EncodeCrossCrate::No
1498    ),
1499    rustc_attr!(
1500        TEST, rustc_expected_cgu_reuse, Normal,
1501        template!(List: &[r#"cfg = "...", module = "...", kind = "...""#]), DuplicatesOk,
1502        EncodeCrossCrate::No
1503    ),
1504    rustc_attr!(
1505        TEST, rustc_symbol_name, Normal, template!(Word),
1506        WarnFollowing, EncodeCrossCrate::No
1507    ),
1508    rustc_attr!(
1509        TEST, rustc_def_path, Normal, template!(Word),
1510        WarnFollowing, EncodeCrossCrate::No
1511    ),
1512    rustc_attr!(
1513        TEST, rustc_mir, Normal, template!(List: &["arg1, arg2, ..."]),
1514        DuplicatesOk, EncodeCrossCrate::Yes
1515    ),
1516    gated!(
1517        custom_mir, Normal, template!(List: &[r#"dialect = "...", phase = "...""#]),
1518        ErrorFollowing, EncodeCrossCrate::No,
1519        "the `#[custom_mir]` attribute is just used for the Rust test suite",
1520    ),
1521    rustc_attr!(
1522        TEST, rustc_dump_item_bounds, Normal, template!(Word),
1523        WarnFollowing, EncodeCrossCrate::No
1524    ),
1525    rustc_attr!(
1526        TEST, rustc_dump_predicates, Normal, template!(Word),
1527        WarnFollowing, EncodeCrossCrate::No
1528    ),
1529    rustc_attr!(
1530        TEST, rustc_dump_def_parents, Normal, template!(Word),
1531        WarnFollowing, EncodeCrossCrate::No
1532    ),
1533    rustc_attr!(
1534        TEST, rustc_object_lifetime_default, Normal, template!(Word),
1535        WarnFollowing, EncodeCrossCrate::No
1536    ),
1537    rustc_attr!(
1538        TEST, rustc_dump_vtable, Normal, template!(Word),
1539        WarnFollowing, EncodeCrossCrate::No
1540    ),
1541    rustc_attr!(
1542        TEST, rustc_dummy, Normal, template!(Word /* doesn't matter*/),
1543        DuplicatesOk, EncodeCrossCrate::No
1544    ),
1545    rustc_attr!(
1546        TEST, pattern_complexity_limit, CrateLevel, template!(NameValueStr: "N"),
1547        ErrorFollowing, EncodeCrossCrate::No,
1548    ),
1549];
1550
1551pub fn is_builtin_attr_name(name: Symbol) -> bool {
1552    BUILTIN_ATTRIBUTE_MAP.get(&name).is_some()
1553}
1554
1555/// Whether this builtin attribute is encoded cross crate.
1556/// This means it can be used cross crate.
1557pub fn encode_cross_crate(name: Symbol) -> bool {
1558    if let Some(attr) = BUILTIN_ATTRIBUTE_MAP.get(&name) {
1559        attr.encode_cross_crate == EncodeCrossCrate::Yes
1560    } else {
1561        true
1562    }
1563}
1564
1565pub fn is_valid_for_get_attr(name: Symbol) -> bool {
1566    BUILTIN_ATTRIBUTE_MAP.get(&name).is_some_and(|attr| match attr.duplicates {
1567        WarnFollowing | ErrorFollowing | ErrorPreceding | FutureWarnFollowing
1568        | FutureWarnPreceding => true,
1569        DuplicatesOk | WarnFollowingWordOnly => false,
1570    })
1571}
1572
1573pub static BUILTIN_ATTRIBUTE_MAP: LazyLock<FxHashMap<Symbol, &BuiltinAttribute>> =
1574    LazyLock::new(|| {
1575        let mut map = FxHashMap::default();
1576        for attr in BUILTIN_ATTRIBUTES.iter() {
1577            if map.insert(attr.name, attr).is_some() {
1578                panic!("duplicate builtin attribute `{}`", attr.name);
1579            }
1580        }
1581        map
1582    });
1583
1584pub fn is_stable_diagnostic_attribute(sym: Symbol, _features: &Features) -> bool {
1585    match sym {
1586        sym::on_unimplemented | sym::do_not_recommend => true,
1587        _ => false,
1588    }
1589}