]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_feature/src/builtin_attrs.rs
Auto merge of #100150 - notriddle:notriddle/implementors-js, r=GuillaumeGomez
[rust.git] / compiler / rustc_feature / src / builtin_attrs.rs
1 //! Built-in attributes and `cfg` flag gating.
2
3 use AttributeDuplicates::*;
4 use AttributeGate::*;
5 use AttributeType::*;
6
7 use crate::{Features, Stability};
8
9 use rustc_data_structures::fx::FxHashMap;
10 use rustc_span::symbol::{sym, Symbol};
11
12 use std::sync::LazyLock;
13
14 type GateFn = fn(&Features) -> bool;
15
16 macro_rules! cfg_fn {
17     ($field: ident) => {
18         (|features| features.$field) as GateFn
19     };
20 }
21
22 pub type GatedCfg = (Symbol, Symbol, GateFn);
23
24 /// `cfg(...)`'s that are feature gated.
25 const GATED_CFGS: &[GatedCfg] = &[
26     // (name in cfg, feature, function to check if the feature is enabled)
27     (sym::target_abi, sym::cfg_target_abi, cfg_fn!(cfg_target_abi)),
28     (sym::target_thread_local, sym::cfg_target_thread_local, cfg_fn!(cfg_target_thread_local)),
29     (
30         sym::target_has_atomic_equal_alignment,
31         sym::cfg_target_has_atomic_equal_alignment,
32         cfg_fn!(cfg_target_has_atomic_equal_alignment),
33     ),
34     (sym::target_has_atomic_load_store, sym::cfg_target_has_atomic, cfg_fn!(cfg_target_has_atomic)),
35     (sym::sanitize, sym::cfg_sanitize, cfg_fn!(cfg_sanitize)),
36     (sym::version, sym::cfg_version, cfg_fn!(cfg_version)),
37 ];
38
39 /// Find a gated cfg determined by the `pred`icate which is given the cfg's name.
40 pub fn find_gated_cfg(pred: impl Fn(Symbol) -> bool) -> Option<&'static GatedCfg> {
41     GATED_CFGS.iter().find(|(cfg_sym, ..)| pred(*cfg_sym))
42 }
43
44 // If you change this, please modify `src/doc/unstable-book` as well. You must
45 // move that documentation into the relevant place in the other docs, and
46 // remove the chapter on the flag.
47
48 #[derive(Copy, Clone, PartialEq, Debug)]
49 pub enum AttributeType {
50     /// Normal, builtin attribute that is consumed
51     /// by the compiler before the unused_attribute check
52     Normal,
53
54     /// Builtin attribute that is only allowed at the crate level
55     CrateLevel,
56 }
57
58 #[derive(Clone, Copy)]
59 pub enum AttributeGate {
60     /// Is gated by a given feature gate, reason
61     /// and function to check if enabled
62     Gated(Stability, Symbol, &'static str, fn(&Features) -> bool),
63
64     /// Ungated attribute, can be used on all release channels
65     Ungated,
66 }
67
68 // fn() is not Debug
69 impl std::fmt::Debug for AttributeGate {
70     fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71         match *self {
72             Self::Gated(ref stab, name, expl, _) => {
73                 write!(fmt, "Gated({:?}, {}, {})", stab, name, expl)
74             }
75             Self::Ungated => write!(fmt, "Ungated"),
76         }
77     }
78 }
79
80 impl AttributeGate {
81     fn is_deprecated(&self) -> bool {
82         matches!(*self, Self::Gated(Stability::Deprecated(_, _), ..))
83     }
84 }
85
86 /// A template that the attribute input must match.
87 /// Only top-level shape (`#[attr]` vs `#[attr(...)]` vs `#[attr = ...]`) is considered now.
88 #[derive(Clone, Copy, Default)]
89 pub struct AttributeTemplate {
90     /// If `true`, the attribute is allowed to be a bare word like `#[test]`.
91     pub word: bool,
92     /// If `Some`, the attribute is allowed to take a list of items like `#[allow(..)]`.
93     pub list: Option<&'static str>,
94     /// If `Some`, the attribute is allowed to be a name/value pair where the
95     /// value is a string, like `#[must_use = "reason"]`.
96     pub name_value_str: Option<&'static str>,
97 }
98
99 /// How to handle multiple duplicate attributes on the same item.
100 #[derive(Clone, Copy, Default)]
101 pub enum AttributeDuplicates {
102     /// Duplicates of this attribute are allowed.
103     ///
104     /// This should only be used with attributes where duplicates have semantic
105     /// meaning, or some kind of "additive" behavior. For example, `#[warn(..)]`
106     /// can be specified multiple times, and it combines all the entries. Or use
107     /// this if there is validation done elsewhere.
108     #[default]
109     DuplicatesOk,
110     /// Duplicates after the first attribute will be an unused_attribute warning.
111     ///
112     /// This is usually used for "word" attributes, where they are used as a
113     /// boolean marker, like `#[used]`. It is not necessarily wrong that there
114     /// are duplicates, but the others should probably be removed.
115     WarnFollowing,
116     /// Same as `WarnFollowing`, but only issues warnings for word-style attributes.
117     ///
118     /// This is only for special cases, for example multiple `#[macro_use]` can
119     /// be warned, but multiple `#[macro_use(...)]` should not because the list
120     /// form has different meaning from the word form.
121     WarnFollowingWordOnly,
122     /// Duplicates after the first attribute will be an error.
123     ///
124     /// This should be used where duplicates would be ignored, but carry extra
125     /// meaning that could cause confusion. For example, `#[stable(since="1.0")]
126     /// #[stable(since="2.0")]`, which version should be used for `stable`?
127     ErrorFollowing,
128     /// Duplicates preceding the last instance of the attribute will be an error.
129     ///
130     /// This is the same as `ErrorFollowing`, except the last attribute is the
131     /// one that is "used". This is typically used in cases like codegen
132     /// attributes which usually only honor the last attribute.
133     ErrorPreceding,
134     /// Duplicates after the first attribute will be an unused_attribute warning
135     /// with a note that this will be an error in the future.
136     ///
137     /// This should be used for attributes that should be `ErrorFollowing`, but
138     /// because older versions of rustc silently accepted (and ignored) the
139     /// attributes, this is used to transition.
140     FutureWarnFollowing,
141     /// Duplicates preceding the last instance of the attribute will be a
142     /// warning, with a note that this will be an error in the future.
143     ///
144     /// This is the same as `FutureWarnFollowing`, except the last attribute is
145     /// the one that is "used". Ideally these can eventually migrate to
146     /// `ErrorPreceding`.
147     FutureWarnPreceding,
148 }
149
150 /// A conveniece macro to deal with `$($expr)?`.
151 macro_rules! or_default {
152     ($default:expr,) => {
153         $default
154     };
155     ($default:expr, $next:expr) => {
156         $next
157     };
158 }
159
160 /// A convenience macro for constructing attribute templates.
161 /// E.g., `template!(Word, List: "description")` means that the attribute
162 /// supports forms `#[attr]` and `#[attr(description)]`.
163 macro_rules! template {
164     (Word) => { template!(@ true, None, None) };
165     (List: $descr: expr) => { template!(@ false, Some($descr), None) };
166     (NameValueStr: $descr: expr) => { template!(@ false, None, Some($descr)) };
167     (Word, List: $descr: expr) => { template!(@ true, Some($descr), None) };
168     (Word, NameValueStr: $descr: expr) => { template!(@ true, None, Some($descr)) };
169     (List: $descr1: expr, NameValueStr: $descr2: expr) => {
170         template!(@ false, Some($descr1), Some($descr2))
171     };
172     (Word, List: $descr1: expr, NameValueStr: $descr2: expr) => {
173         template!(@ true, Some($descr1), Some($descr2))
174     };
175     (@ $word: expr, $list: expr, $name_value_str: expr) => { AttributeTemplate {
176         word: $word, list: $list, name_value_str: $name_value_str
177     } };
178 }
179
180 macro_rules! ungated {
181     ($attr:ident, $typ:expr, $tpl:expr, $duplicates:expr $(, @only_local: $only_local:expr)? $(,)?) => {
182         BuiltinAttribute {
183             name: sym::$attr,
184             only_local: or_default!(false, $($only_local)?),
185             type_: $typ,
186             template: $tpl,
187             gate: Ungated,
188             duplicates: $duplicates,
189         }
190     };
191 }
192
193 macro_rules! gated {
194     ($attr:ident, $typ:expr, $tpl:expr, $duplicates:expr $(, @only_local: $only_local:expr)?, $gate:ident, $msg:expr $(,)?) => {
195         BuiltinAttribute {
196             name: sym::$attr,
197             only_local: or_default!(false, $($only_local)?),
198             type_: $typ,
199             template: $tpl,
200             duplicates: $duplicates,
201             gate: Gated(Stability::Unstable, sym::$gate, $msg, cfg_fn!($gate)),
202         }
203     };
204     ($attr:ident, $typ:expr, $tpl:expr, $duplicates:expr $(, @only_local: $only_local:expr)?, $msg:expr $(,)?) => {
205         BuiltinAttribute {
206             name: sym::$attr,
207             only_local: or_default!(false, $($only_local)?),
208             type_: $typ,
209             template: $tpl,
210             duplicates: $duplicates,
211             gate: Gated(Stability::Unstable, sym::$attr, $msg, cfg_fn!($attr)),
212         }
213     };
214 }
215
216 macro_rules! rustc_attr {
217     (TEST, $attr:ident, $typ:expr, $tpl:expr, $duplicate:expr $(, @only_local: $only_local:expr)? $(,)?) => {
218         rustc_attr!(
219             $attr,
220             $typ,
221             $tpl,
222             $duplicate,
223             $(@only_local: $only_local,)?
224             concat!(
225                 "the `#[",
226                 stringify!($attr),
227                 "]` attribute is just used for rustc unit tests \
228                 and will never be stable",
229             ),
230         )
231     };
232     ($attr:ident, $typ:expr, $tpl:expr, $duplicates:expr $(, @only_local: $only_local:expr)?, $msg:expr $(,)?) => {
233         BuiltinAttribute {
234             name: sym::$attr,
235             only_local: or_default!(false, $($only_local)?),
236             type_: $typ,
237             template: $tpl,
238             duplicates: $duplicates,
239             gate: Gated(Stability::Unstable, sym::rustc_attrs, $msg, cfg_fn!(rustc_attrs)),
240         }
241     };
242 }
243
244 macro_rules! experimental {
245     ($attr:ident) => {
246         concat!("the `#[", stringify!($attr), "]` attribute is an experimental feature")
247     };
248 }
249
250 const IMPL_DETAIL: &str = "internal implementation detail";
251 const INTERNAL_UNSTABLE: &str = "this is an internal attribute that will never be stable";
252
253 pub struct BuiltinAttribute {
254     pub name: Symbol,
255     /// Whether this attribute is only used in the local crate.
256     ///
257     /// If so, it is not encoded in the crate metadata.
258     pub only_local: bool,
259     pub type_: AttributeType,
260     pub template: AttributeTemplate,
261     pub duplicates: AttributeDuplicates,
262     pub gate: AttributeGate,
263 }
264
265 /// Attributes that have a special meaning to rustc or rustdoc.
266 #[rustfmt::skip]
267 pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
268     // ==========================================================================
269     // Stable attributes:
270     // ==========================================================================
271
272     // Conditional compilation:
273     ungated!(cfg, Normal, template!(List: "predicate"), DuplicatesOk),
274     ungated!(cfg_attr, Normal, template!(List: "predicate, attr1, attr2, ..."), DuplicatesOk),
275
276     // Testing:
277     ungated!(ignore, Normal, template!(Word, NameValueStr: "reason"), WarnFollowing),
278     ungated!(
279         should_panic, Normal,
280         template!(Word, List: r#"expected = "reason"#, NameValueStr: "reason"), FutureWarnFollowing,
281     ),
282     // FIXME(Centril): This can be used on stable but shouldn't.
283     ungated!(reexport_test_harness_main, CrateLevel, template!(NameValueStr: "name"), ErrorFollowing),
284
285     // Macros:
286     ungated!(automatically_derived, Normal, template!(Word), WarnFollowing),
287     ungated!(macro_use, Normal, template!(Word, List: "name1, name2, ..."), WarnFollowingWordOnly),
288     ungated!(macro_escape, Normal, template!(Word), WarnFollowing), // Deprecated synonym for `macro_use`.
289     ungated!(macro_export, Normal, template!(Word, List: "local_inner_macros"), WarnFollowing),
290     ungated!(proc_macro, Normal, template!(Word), ErrorFollowing),
291     ungated!(
292         proc_macro_derive, Normal,
293         template!(List: "TraitName, /*opt*/ attributes(name1, name2, ...)"), ErrorFollowing,
294     ),
295     ungated!(proc_macro_attribute, Normal, template!(Word), ErrorFollowing),
296
297     // Lints:
298     ungated!(
299         warn, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#), DuplicatesOk
300     ),
301     ungated!(
302         allow, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#), DuplicatesOk
303     ),
304     gated!(
305         expect, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#), DuplicatesOk,
306         lint_reasons, experimental!(expect)
307     ),
308     ungated!(
309         forbid, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#), DuplicatesOk
310     ),
311     ungated!(
312         deny, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#), DuplicatesOk
313     ),
314     ungated!(must_use, Normal, template!(Word, NameValueStr: "reason"), FutureWarnFollowing),
315     gated!(
316         must_not_suspend, Normal, template!(Word, NameValueStr: "reason"), WarnFollowing,
317         experimental!(must_not_suspend)
318     ),
319     ungated!(
320         deprecated, Normal,
321         template!(
322             Word,
323             List: r#"/*opt*/ since = "version", /*opt*/ note = "reason""#,
324             NameValueStr: "reason"
325         ),
326         ErrorFollowing
327     ),
328
329     // Crate properties:
330     ungated!(crate_name, CrateLevel, template!(NameValueStr: "name"), FutureWarnFollowing),
331     ungated!(crate_type, CrateLevel, template!(NameValueStr: "bin|lib|..."), DuplicatesOk),
332     // crate_id is deprecated
333     ungated!(crate_id, CrateLevel, template!(NameValueStr: "ignored"), FutureWarnFollowing),
334
335     // ABI, linking, symbols, and FFI
336     ungated!(
337         link, Normal,
338         template!(List: r#"name = "...", /*opt*/ kind = "dylib|static|...", /*opt*/ wasm_import_module = "...""#),
339         DuplicatesOk,
340     ),
341     ungated!(link_name, Normal, template!(NameValueStr: "name"), FutureWarnPreceding),
342     ungated!(no_link, Normal, template!(Word), WarnFollowing),
343     ungated!(repr, Normal, template!(List: "C"), DuplicatesOk),
344     ungated!(export_name, Normal, template!(NameValueStr: "name"), FutureWarnPreceding),
345     ungated!(link_section, Normal, template!(NameValueStr: "name"), FutureWarnPreceding),
346     ungated!(no_mangle, Normal, template!(Word), WarnFollowing, @only_local: true),
347     ungated!(used, Normal, template!(Word, List: "compiler|linker"), WarnFollowing, @only_local: true),
348
349     // Limits:
350     ungated!(recursion_limit, CrateLevel, template!(NameValueStr: "N"), FutureWarnFollowing),
351     ungated!(type_length_limit, CrateLevel, template!(NameValueStr: "N"), FutureWarnFollowing),
352     gated!(
353         const_eval_limit, CrateLevel, template!(NameValueStr: "N"), ErrorFollowing,
354         const_eval_limit, experimental!(const_eval_limit)
355     ),
356     gated!(
357         move_size_limit, CrateLevel, template!(NameValueStr: "N"), ErrorFollowing,
358         large_assignments, experimental!(move_size_limit)
359     ),
360
361     // Entry point:
362     ungated!(start, Normal, template!(Word), WarnFollowing),
363     ungated!(no_start, CrateLevel, template!(Word), WarnFollowing),
364     ungated!(no_main, CrateLevel, template!(Word), WarnFollowing),
365
366     // Modules, prelude, and resolution:
367     ungated!(path, Normal, template!(NameValueStr: "file"), FutureWarnFollowing),
368     ungated!(no_std, CrateLevel, template!(Word), WarnFollowing),
369     ungated!(no_implicit_prelude, Normal, template!(Word), WarnFollowing),
370     ungated!(non_exhaustive, Normal, template!(Word), WarnFollowing),
371
372     // Runtime
373     ungated!(
374         windows_subsystem, CrateLevel,
375         template!(NameValueStr: "windows|console"), FutureWarnFollowing
376     ),
377     ungated!(panic_handler, Normal, template!(Word), WarnFollowing), // RFC 2070
378
379     // Code generation:
380     ungated!(inline, Normal, template!(Word, List: "always|never"), FutureWarnFollowing, @only_local: true),
381     ungated!(cold, Normal, template!(Word), WarnFollowing, @only_local: true),
382     ungated!(no_builtins, CrateLevel, template!(Word), WarnFollowing),
383     ungated!(target_feature, Normal, template!(List: r#"enable = "name""#), DuplicatesOk),
384     ungated!(track_caller, Normal, template!(Word), WarnFollowing),
385     gated!(
386         no_sanitize, Normal,
387         template!(List: "address, memory, thread"), DuplicatesOk,
388         experimental!(no_sanitize)
389     ),
390     gated!(no_coverage, Normal, template!(Word), WarnFollowing, experimental!(no_coverage)),
391
392     ungated!(
393         doc, Normal, template!(List: "hidden|inline|...", NameValueStr: "string"), DuplicatesOk
394     ),
395
396     // ==========================================================================
397     // Unstable attributes:
398     // ==========================================================================
399
400     // RFC #3191: #[debugger_visualizer] support
401     gated!(
402         debugger_visualizer, Normal, template!(List: r#"natvis_file = "...", gdb_script_file = "...""#),
403         DuplicatesOk, experimental!(debugger_visualizer)
404     ),
405
406     // Linking:
407     gated!(naked, Normal, template!(Word), WarnFollowing, @only_local: true, naked_functions, experimental!(naked)),
408     gated!(
409         link_ordinal, Normal, template!(List: "ordinal"), ErrorPreceding, raw_dylib,
410         experimental!(link_ordinal)
411     ),
412
413     // Plugins:
414     BuiltinAttribute {
415         name: sym::plugin,
416         only_local: false,
417         type_: CrateLevel,
418         template: template!(List: "name"),
419         duplicates: DuplicatesOk,
420         gate: Gated(
421             Stability::Deprecated(
422                 "https://github.com/rust-lang/rust/pull/64675",
423                 Some("may be removed in a future compiler version"),
424             ),
425             sym::plugin,
426             "compiler plugins are deprecated",
427             cfg_fn!(plugin)
428         ),
429     },
430
431     // Testing:
432     gated!(
433         test_runner, CrateLevel, template!(List: "path"), ErrorFollowing, custom_test_frameworks,
434         "custom test frameworks are an unstable feature",
435     ),
436     // RFC #1268
437     gated!(
438         marker, Normal, template!(Word), WarnFollowing, marker_trait_attr, experimental!(marker)
439     ),
440     gated!(
441         thread_local, Normal, template!(Word), WarnFollowing,
442         "`#[thread_local]` is an experimental feature, and does not currently handle destructors",
443     ),
444     gated!(no_core, CrateLevel, template!(Word), WarnFollowing, experimental!(no_core)),
445     // RFC 2412
446     gated!(
447         optimize, Normal, template!(List: "size|speed"), ErrorPreceding, optimize_attribute,
448         experimental!(optimize),
449     ),
450     // RFC 2867
451     gated!(
452         instruction_set, Normal, template!(List: "set"), ErrorPreceding,
453         isa_attribute, experimental!(instruction_set)
454     ),
455
456     gated!(
457         ffi_returns_twice, Normal, template!(Word), WarnFollowing, experimental!(ffi_returns_twice)
458     ),
459     gated!(ffi_pure, Normal, template!(Word), WarnFollowing, experimental!(ffi_pure)),
460     gated!(ffi_const, Normal, template!(Word), WarnFollowing, experimental!(ffi_const)),
461     gated!(
462         register_attr, CrateLevel, template!(List: "attr1, attr2, ..."), DuplicatesOk,
463         experimental!(register_attr),
464     ),
465     gated!(
466         register_tool, CrateLevel, template!(List: "tool1, tool2, ..."), DuplicatesOk,
467         experimental!(register_tool),
468     ),
469
470     gated!(
471         cmse_nonsecure_entry, Normal, template!(Word), WarnFollowing,
472         experimental!(cmse_nonsecure_entry)
473     ),
474     // RFC 2632
475     gated!(
476         const_trait, Normal, template!(Word), WarnFollowing, const_trait_impl,
477         "`const` is a temporary placeholder for marking a trait that is suitable for `const` \
478         `impls` and all default bodies as `const`, which may be removed or renamed in the \
479         future."
480     ),
481     // lang-team MCP 147
482     gated!(
483         deprecated_safe, Normal, template!(List: r#"since = "version", note = "...""#), ErrorFollowing,
484         experimental!(deprecated_safe),
485     ),
486
487     // ==========================================================================
488     // Internal attributes: Stability, deprecation, and unsafe:
489     // ==========================================================================
490
491     ungated!(feature, CrateLevel, template!(List: "name1, name2, ..."), DuplicatesOk),
492     // DuplicatesOk since it has its own validation
493     ungated!(
494         stable, Normal, template!(List: r#"feature = "name", since = "version""#), DuplicatesOk,
495     ),
496     ungated!(
497         unstable, Normal,
498         template!(List: r#"feature = "name", reason = "...", issue = "N""#), DuplicatesOk,
499     ),
500     ungated!(rustc_const_unstable, Normal, template!(List: r#"feature = "name""#), DuplicatesOk),
501     ungated!(rustc_const_stable, Normal, template!(List: r#"feature = "name""#), DuplicatesOk),
502     ungated!(
503         rustc_default_body_unstable, Normal,
504         template!(List: r#"feature = "name", reason = "...", issue = "N""#), DuplicatesOk
505     ),
506     gated!(
507         allow_internal_unstable, Normal, template!(Word, List: "feat1, feat2, ..."), DuplicatesOk,
508         "allow_internal_unstable side-steps feature gating and stability checks",
509     ),
510     gated!(
511         rustc_allow_const_fn_unstable, Normal,
512         template!(Word, List: "feat1, feat2, ..."), DuplicatesOk,
513         "rustc_allow_const_fn_unstable side-steps feature gating and stability checks"
514     ),
515     gated!(
516         allow_internal_unsafe, Normal, template!(Word), WarnFollowing,
517         "allow_internal_unsafe side-steps the unsafe_code lint",
518     ),
519     rustc_attr!(rustc_allowed_through_unstable_modules, Normal, template!(Word), WarnFollowing,
520     "rustc_allowed_through_unstable_modules special cases accidental stabilizations of stable items \
521     through unstable paths"),
522
523     // ==========================================================================
524     // Internal attributes: Type system related:
525     // ==========================================================================
526
527     gated!(fundamental, Normal, template!(Word), WarnFollowing, experimental!(fundamental)),
528     gated!(
529         may_dangle, Normal, template!(Word), WarnFollowing, dropck_eyepatch,
530         "`may_dangle` has unstable semantics and may be removed in the future",
531     ),
532
533     // ==========================================================================
534     // Internal attributes: Runtime related:
535     // ==========================================================================
536
537     rustc_attr!(rustc_allocator, Normal, template!(Word), WarnFollowing, IMPL_DETAIL),
538     rustc_attr!(rustc_allocator_nounwind, Normal, template!(Word), WarnFollowing, IMPL_DETAIL),
539     rustc_attr!(rustc_reallocator, Normal, template!(Word), WarnFollowing, IMPL_DETAIL),
540     rustc_attr!(rustc_deallocator, Normal, template!(Word), WarnFollowing, IMPL_DETAIL),
541     rustc_attr!(rustc_allocator_zeroed, Normal, template!(Word), WarnFollowing, IMPL_DETAIL),
542     gated!(
543         alloc_error_handler, Normal, template!(Word), WarnFollowing,
544         experimental!(alloc_error_handler)
545     ),
546     gated!(
547         default_lib_allocator, Normal, template!(Word), WarnFollowing, allocator_internals,
548         experimental!(default_lib_allocator),
549     ),
550     gated!(
551         needs_allocator, Normal, template!(Word), WarnFollowing, allocator_internals,
552         experimental!(needs_allocator),
553     ),
554     gated!(panic_runtime, Normal, template!(Word), WarnFollowing, experimental!(panic_runtime)),
555     gated!(
556         needs_panic_runtime, Normal, template!(Word), WarnFollowing,
557         experimental!(needs_panic_runtime)
558     ),
559     gated!(
560         compiler_builtins, Normal, template!(Word), WarnFollowing,
561         "the `#[compiler_builtins]` attribute is used to identify the `compiler_builtins` crate \
562         which contains compiler-rt intrinsics and will never be stable",
563     ),
564     gated!(
565         profiler_runtime, Normal, template!(Word), WarnFollowing,
566         "the `#[profiler_runtime]` attribute is used to identify the `profiler_builtins` crate \
567         which contains the profiler runtime and will never be stable",
568     ),
569
570     // ==========================================================================
571     // Internal attributes, Linkage:
572     // ==========================================================================
573
574     gated!(
575         linkage, Normal, template!(NameValueStr: "external|internal|..."), ErrorPreceding, @only_local: true,
576         "the `linkage` attribute is experimental and not portable across platforms",
577     ),
578     rustc_attr!(
579         rustc_std_internal_symbol, Normal, template!(Word), WarnFollowing, @only_local: true, INTERNAL_UNSTABLE
580     ),
581
582     // ==========================================================================
583     // Internal attributes, Macro related:
584     // ==========================================================================
585
586     rustc_attr!(
587         rustc_builtin_macro, Normal,
588         template!(Word, List: "name, /*opt*/ attributes(name1, name2, ...)"), ErrorFollowing,
589         IMPL_DETAIL,
590     ),
591     rustc_attr!(rustc_proc_macro_decls, Normal, template!(Word), WarnFollowing, INTERNAL_UNSTABLE),
592     rustc_attr!(
593         rustc_macro_transparency, Normal,
594         template!(NameValueStr: "transparent|semitransparent|opaque"), ErrorFollowing,
595         "used internally for testing macro hygiene",
596     ),
597
598     // ==========================================================================
599     // Internal attributes, Diagnostics related:
600     // ==========================================================================
601
602     rustc_attr!(
603         rustc_on_unimplemented, Normal,
604         template!(
605             List: r#"/*opt*/ message = "...", /*opt*/ label = "...", /*opt*/ note = "...""#,
606             NameValueStr: "message"
607         ),
608         ErrorFollowing,
609         INTERNAL_UNSTABLE
610     ),
611     // Enumerates "identity-like" conversion methods to suggest on type mismatch.
612     rustc_attr!(
613         rustc_conversion_suggestion, Normal, template!(Word), WarnFollowing, INTERNAL_UNSTABLE
614     ),
615     // Prevents field reads in the marked trait or method to be considered
616     // during dead code analysis.
617     rustc_attr!(
618         rustc_trivial_field_reads, Normal, template!(Word), WarnFollowing, INTERNAL_UNSTABLE
619     ),
620     // Used by the `rustc::potential_query_instability` lint to warn methods which
621     // might not be stable during incremental compilation.
622     rustc_attr!(rustc_lint_query_instability, Normal, template!(Word), WarnFollowing, INTERNAL_UNSTABLE),
623     // Used by the `rustc::untranslatable_diagnostic` and `rustc::diagnostic_outside_of_impl` lints
624     // to assist in changes to diagnostic APIs.
625     rustc_attr!(rustc_lint_diagnostics, Normal, template!(Word), WarnFollowing, INTERNAL_UNSTABLE),
626     // Used by the `rustc::bad_opt_access` lint to identify `DebuggingOptions` and `CodegenOptions`
627     // types (as well as any others in future).
628     rustc_attr!(rustc_lint_opt_ty, Normal, template!(Word), WarnFollowing, INTERNAL_UNSTABLE),
629     // Used by the `rustc::bad_opt_access` lint on fields
630     // types (as well as any others in future).
631     rustc_attr!(rustc_lint_opt_deny_field_access, Normal, template!(List: "message"), WarnFollowing, INTERNAL_UNSTABLE),
632
633     // ==========================================================================
634     // Internal attributes, Const related:
635     // ==========================================================================
636
637     rustc_attr!(rustc_promotable, Normal, template!(Word), WarnFollowing, IMPL_DETAIL),
638     rustc_attr!(
639         rustc_legacy_const_generics, Normal, template!(List: "N"), ErrorFollowing,
640         INTERNAL_UNSTABLE
641     ),
642     // Do not const-check this function's body. It will always get replaced during CTFE.
643     rustc_attr!(
644         rustc_do_not_const_check, Normal, template!(Word), WarnFollowing, INTERNAL_UNSTABLE
645     ),
646
647     // ==========================================================================
648     // Internal attributes, Layout related:
649     // ==========================================================================
650
651     rustc_attr!(
652         rustc_layout_scalar_valid_range_start, Normal, template!(List: "value"), ErrorFollowing,
653         "the `#[rustc_layout_scalar_valid_range_start]` attribute is just used to enable \
654         niche optimizations in libcore and libstd and will never be stable",
655     ),
656     rustc_attr!(
657         rustc_layout_scalar_valid_range_end, Normal, template!(List: "value"), ErrorFollowing,
658         "the `#[rustc_layout_scalar_valid_range_end]` attribute is just used to enable \
659         niche optimizations in libcore and libstd and will never be stable",
660     ),
661     rustc_attr!(
662         rustc_nonnull_optimization_guaranteed, Normal, template!(Word), WarnFollowing,
663         "the `#[rustc_nonnull_optimization_guaranteed]` attribute is just used to enable \
664         niche optimizations in libcore and libstd and will never be stable",
665     ),
666
667     // ==========================================================================
668     // Internal attributes, Misc:
669     // ==========================================================================
670     gated!(
671         lang, Normal, template!(NameValueStr: "name"), DuplicatesOk, @only_local: true, lang_items,
672         "language items are subject to change",
673     ),
674     rustc_attr!(
675         rustc_pass_by_value, Normal,
676         template!(Word), ErrorFollowing,
677         "#[rustc_pass_by_value] is used to mark types that must be passed by value instead of reference."
678     ),
679     rustc_attr!(
680         rustc_coherence_is_core, AttributeType::CrateLevel, template!(Word), ErrorFollowing, @only_local: true,
681         "#![rustc_coherence_is_core] allows inherent methods on builtin types, only intended to be used in `core`."
682     ),
683     rustc_attr!(
684         rustc_allow_incoherent_impl, AttributeType::Normal, template!(Word), ErrorFollowing, @only_local: true,
685         "#[rustc_allow_incoherent_impl] has to be added to all impl items of an incoherent inherent impl."
686     ),
687     rustc_attr!(
688         rustc_has_incoherent_inherent_impls, AttributeType::Normal, template!(Word), ErrorFollowing,
689         "#[rustc_has_incoherent_inherent_impls] allows the addition of incoherent inherent impls for \
690          the given type by annotating all impl items with #[rustc_allow_incoherent_impl]."
691     ),
692     rustc_attr!(
693         rustc_box, AttributeType::Normal, template!(Word), ErrorFollowing,
694         "#[rustc_box] allows creating boxes \
695         and it is only intended to be used in `alloc`."
696     ),
697
698     BuiltinAttribute {
699         name: sym::rustc_diagnostic_item,
700         // FIXME: This can be `true` once we always use `tcx.is_diagnostic_item`.
701         only_local: false,
702         type_: Normal,
703         template: template!(NameValueStr: "name"),
704         duplicates: ErrorFollowing,
705         gate: Gated(
706             Stability::Unstable,
707             sym::rustc_attrs,
708             "diagnostic items compiler internal support for linting",
709             cfg_fn!(rustc_attrs),
710         ),
711     },
712     gated!(
713         // Used in resolve:
714         prelude_import, Normal, template!(Word), WarnFollowing,
715         "`#[prelude_import]` is for use by rustc only",
716     ),
717     gated!(
718         rustc_paren_sugar, Normal, template!(Word), WarnFollowing, unboxed_closures,
719         "unboxed_closures are still evolving",
720     ),
721     rustc_attr!(
722         rustc_inherit_overflow_checks, Normal, template!(Word), WarnFollowing, @only_local: true,
723         "the `#[rustc_inherit_overflow_checks]` attribute is just used to control \
724         overflow checking behavior of several libcore functions that are inlined \
725         across crates and will never be stable",
726     ),
727     rustc_attr!(
728         rustc_reservation_impl, Normal,
729         template!(NameValueStr: "reservation message"), ErrorFollowing,
730         "the `#[rustc_reservation_impl]` attribute is internally used \
731          for reserving for `for<T> From<!> for T` impl"
732     ),
733     rustc_attr!(
734         rustc_test_marker, Normal, template!(Word), WarnFollowing,
735         "the `#[rustc_test_marker]` attribute is used internally to track tests",
736     ),
737     rustc_attr!(
738         rustc_unsafe_specialization_marker, Normal, template!(Word), WarnFollowing,
739         "the `#[rustc_unsafe_specialization_marker]` attribute is used to check specializations"
740     ),
741     rustc_attr!(
742         rustc_specialization_trait, Normal, template!(Word), WarnFollowing,
743         "the `#[rustc_specialization_trait]` attribute is used to check specializations"
744     ),
745     rustc_attr!(
746         rustc_main, Normal, template!(Word), WarnFollowing,
747         "the `#[rustc_main]` attribute is used internally to specify test entry point function",
748     ),
749     rustc_attr!(
750         rustc_skip_array_during_method_dispatch, Normal, template!(Word), WarnFollowing,
751         "the `#[rustc_skip_array_during_method_dispatch]` attribute is used to exclude a trait \
752         from method dispatch when the receiver is an array, for compatibility in editions < 2021."
753     ),
754     rustc_attr!(
755         rustc_must_implement_one_of, Normal, template!(List: "function1, function2, ..."), ErrorFollowing,
756         "the `#[rustc_must_implement_one_of]` attribute is used to change minimal complete \
757         definition of a trait, it's currently in experimental form and should be changed before \
758         being exposed outside of the std"
759     ),
760
761     // ==========================================================================
762     // Internal attributes, Testing:
763     // ==========================================================================
764
765     rustc_attr!(TEST, rustc_outlives, Normal, template!(Word), WarnFollowing),
766     rustc_attr!(TEST, rustc_capture_analysis, Normal, template!(Word), WarnFollowing),
767     rustc_attr!(TEST, rustc_insignificant_dtor, Normal, template!(Word), WarnFollowing),
768     rustc_attr!(TEST, rustc_strict_coherence, Normal, template!(Word), WarnFollowing),
769     rustc_attr!(TEST, rustc_variance, Normal, template!(Word), WarnFollowing),
770     rustc_attr!(TEST, rustc_layout, Normal, template!(List: "field1, field2, ..."), WarnFollowing),
771     rustc_attr!(TEST, rustc_regions, Normal, template!(Word), WarnFollowing),
772     rustc_attr!(
773         TEST, rustc_error, Normal,
774         template!(Word, List: "delay_span_bug_from_inside_query"), WarnFollowingWordOnly
775     ),
776     rustc_attr!(TEST, rustc_dump_user_substs, Normal, template!(Word), WarnFollowing),
777     rustc_attr!(TEST, rustc_evaluate_where_clauses, Normal, template!(Word), WarnFollowing),
778     rustc_attr!(
779         TEST, rustc_if_this_changed, Normal, template!(Word, List: "DepNode"), DuplicatesOk
780     ),
781     rustc_attr!(
782         TEST, rustc_then_this_would_need, Normal, template!(List: "DepNode"), DuplicatesOk
783     ),
784     rustc_attr!(
785         TEST, rustc_clean, Normal,
786         template!(List: r#"cfg = "...", /*opt*/ label = "...", /*opt*/ except = "...""#),
787         DuplicatesOk,
788     ),
789     rustc_attr!(
790         TEST, rustc_partition_reused, Normal,
791         template!(List: r#"cfg = "...", module = "...""#), DuplicatesOk,
792     ),
793     rustc_attr!(
794         TEST, rustc_partition_codegened, Normal,
795         template!(List: r#"cfg = "...", module = "...""#), DuplicatesOk,
796     ),
797     rustc_attr!(
798         TEST, rustc_expected_cgu_reuse, Normal,
799         template!(List: r#"cfg = "...", module = "...", kind = "...""#), DuplicatesOk,
800     ),
801     rustc_attr!(TEST, rustc_symbol_name, Normal, template!(Word), WarnFollowing),
802     rustc_attr!(TEST, rustc_polymorphize_error, Normal, template!(Word), WarnFollowing),
803     rustc_attr!(TEST, rustc_def_path, Normal, template!(Word), WarnFollowing),
804     rustc_attr!(TEST, rustc_mir, Normal, template!(List: "arg1, arg2, ..."), DuplicatesOk),
805     rustc_attr!(TEST, rustc_dump_program_clauses, Normal, template!(Word), WarnFollowing),
806     rustc_attr!(TEST, rustc_dump_env_program_clauses, Normal, template!(Word), WarnFollowing),
807     rustc_attr!(TEST, rustc_object_lifetime_default, Normal, template!(Word), WarnFollowing),
808     rustc_attr!(TEST, rustc_dump_vtable, Normal, template!(Word), WarnFollowing),
809     rustc_attr!(TEST, rustc_dummy, Normal, template!(Word /* doesn't matter*/), DuplicatesOk),
810     gated!(
811         omit_gdb_pretty_printer_section, Normal, template!(Word), WarnFollowing,
812         "the `#[omit_gdb_pretty_printer_section]` attribute is just used for the Rust test suite",
813     ),
814 ];
815
816 pub fn deprecated_attributes() -> Vec<&'static BuiltinAttribute> {
817     BUILTIN_ATTRIBUTES.iter().filter(|attr| attr.gate.is_deprecated()).collect()
818 }
819
820 pub fn is_builtin_attr_name(name: Symbol) -> bool {
821     BUILTIN_ATTRIBUTE_MAP.get(&name).is_some()
822 }
823
824 pub fn is_builtin_only_local(name: Symbol) -> bool {
825     BUILTIN_ATTRIBUTE_MAP.get(&name).map_or(false, |attr| attr.only_local)
826 }
827
828 pub static BUILTIN_ATTRIBUTE_MAP: LazyLock<FxHashMap<Symbol, &BuiltinAttribute>> =
829     LazyLock::new(|| {
830         let mut map = FxHashMap::default();
831         for attr in BUILTIN_ATTRIBUTES.iter() {
832             if map.insert(attr.name, attr).is_some() {
833                 panic!("duplicate builtin attribute `{}`", attr.name);
834             }
835         }
836         map
837     });