1 //! Built-in attributes and `cfg` flag gating.
6 use crate::{Features, Stability};
8 use rustc_data_structures::fx::FxHashMap;
9 use rustc_span::symbol::{sym, Symbol};
11 use std::lazy::SyncLazy;
13 type GateFn = fn(&Features) -> bool;
17 (|features| features.$field) as GateFn
21 pub type GatedCfg = (Symbol, Symbol, GateFn);
23 /// `cfg(...)`'s that are feature gated.
24 const GATED_CFGS: &[GatedCfg] = &[
25 // (name in cfg, feature, function to check if the feature is enabled)
26 (sym::target_abi, sym::cfg_target_abi, cfg_fn!(cfg_target_abi)),
27 (sym::target_thread_local, sym::cfg_target_thread_local, cfg_fn!(cfg_target_thread_local)),
28 (sym::target_has_atomic, sym::cfg_target_has_atomic, cfg_fn!(cfg_target_has_atomic)),
29 (sym::target_has_atomic_load_store, sym::cfg_target_has_atomic, cfg_fn!(cfg_target_has_atomic)),
31 sym::target_has_atomic_equal_alignment,
32 sym::cfg_target_has_atomic,
33 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 (sym::panic, sym::cfg_panic, cfg_fn!(cfg_panic)),
40 /// Find a gated cfg determined by the `pred`icate which is given the cfg's name.
41 pub fn find_gated_cfg(pred: impl Fn(Symbol) -> bool) -> Option<&'static GatedCfg> {
42 GATED_CFGS.iter().find(|(cfg_sym, ..)| pred(*cfg_sym))
45 // If you change this, please modify `src/doc/unstable-book` as well. You must
46 // move that documentation into the relevant place in the other docs, and
47 // remove the chapter on the flag.
49 #[derive(Copy, Clone, PartialEq, Debug)]
50 pub enum AttributeType {
51 /// Normal, builtin attribute that is consumed
52 /// by the compiler before the unused_attribute check
55 /// Builtin attribute that is only allowed at the crate level
59 #[derive(Clone, Copy)]
60 pub enum AttributeGate {
61 /// Is gated by a given feature gate, reason
62 /// and function to check if enabled
63 Gated(Stability, Symbol, &'static str, fn(&Features) -> bool),
65 /// Ungated attribute, can be used on all release channels
70 impl std::fmt::Debug for AttributeGate {
71 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73 Self::Gated(ref stab, name, expl, _) => {
74 write!(fmt, "Gated({:?}, {}, {})", stab, name, expl)
76 Self::Ungated => write!(fmt, "Ungated"),
82 fn is_deprecated(&self) -> bool {
83 matches!(*self, Self::Gated(Stability::Deprecated(_, _), ..))
87 /// A template that the attribute input must match.
88 /// Only top-level shape (`#[attr]` vs `#[attr(...)]` vs `#[attr = ...]`) is considered now.
89 #[derive(Clone, Copy, Default)]
90 pub struct AttributeTemplate {
92 pub list: Option<&'static str>,
93 pub name_value_str: Option<&'static str>,
96 /// A convenience macro for constructing attribute templates.
97 /// E.g., `template!(Word, List: "description")` means that the attribute
98 /// supports forms `#[attr]` and `#[attr(description)]`.
99 macro_rules! template {
100 (Word) => { template!(@ true, None, None) };
101 (List: $descr: expr) => { template!(@ false, Some($descr), None) };
102 (NameValueStr: $descr: expr) => { template!(@ false, None, Some($descr)) };
103 (Word, List: $descr: expr) => { template!(@ true, Some($descr), None) };
104 (Word, NameValueStr: $descr: expr) => { template!(@ true, None, Some($descr)) };
105 (List: $descr1: expr, NameValueStr: $descr2: expr) => {
106 template!(@ false, Some($descr1), Some($descr2))
108 (Word, List: $descr1: expr, NameValueStr: $descr2: expr) => {
109 template!(@ true, Some($descr1), Some($descr2))
111 (@ $word: expr, $list: expr, $name_value_str: expr) => { AttributeTemplate {
112 word: $word, list: $list, name_value_str: $name_value_str
116 macro_rules! ungated {
117 ($attr:ident, $typ:expr, $tpl:expr $(,)?) => {
118 BuiltinAttribute { name: sym::$attr, type_: $typ, template: $tpl, gate: Ungated }
123 ($attr:ident, $typ:expr, $tpl:expr, $gate:ident, $msg:expr $(,)?) => {
128 gate: Gated(Stability::Unstable, sym::$gate, $msg, cfg_fn!($gate)),
131 ($attr:ident, $typ:expr, $tpl:expr, $msg:expr $(,)?) => {
136 gate: Gated(Stability::Unstable, sym::$attr, $msg, cfg_fn!($attr)),
141 macro_rules! rustc_attr {
142 (TEST, $attr:ident, $typ:expr, $tpl:expr $(,)?) => {
150 "]` attribute is just used for rustc unit tests \
151 and will never be stable",
155 ($attr:ident, $typ:expr, $tpl:expr, $msg:expr $(,)?) => {
160 gate: Gated(Stability::Unstable, sym::rustc_attrs, $msg, cfg_fn!(rustc_attrs)),
165 macro_rules! experimental {
167 concat!("the `#[", stringify!($attr), "]` attribute is an experimental feature")
171 const IMPL_DETAIL: &str = "internal implementation detail";
172 const INTERNAL_UNSTABLE: &str = "this is an internal attribute that will never be stable";
174 pub struct BuiltinAttribute {
176 pub type_: AttributeType,
177 pub template: AttributeTemplate,
178 pub gate: AttributeGate,
181 /// Attributes that have a special meaning to rustc or rustdoc.
183 pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
184 // ==========================================================================
185 // Stable attributes:
186 // ==========================================================================
188 // Conditional compilation:
189 ungated!(cfg, Normal, template!(List: "predicate")),
190 ungated!(cfg_attr, Normal, template!(List: "predicate, attr1, attr2, ...")),
193 ungated!(ignore, Normal, template!(Word, NameValueStr: "reason")),
195 should_panic, Normal,
196 template!(Word, List: r#"expected = "reason"#, NameValueStr: "reason"),
198 // FIXME(Centril): This can be used on stable but shouldn't.
199 ungated!(reexport_test_harness_main, CrateLevel, template!(NameValueStr: "name")),
202 ungated!(automatically_derived, Normal, template!(Word)),
204 ungated!(macro_use, Normal, template!(Word, List: "name1, name2, ...")),
205 ungated!(macro_escape, Normal, template!(Word)), // Deprecated synonym for `macro_use`.
206 ungated!(macro_export, Normal, template!(Word, List: "local_inner_macros")),
207 ungated!(proc_macro, Normal, template!(Word)),
209 proc_macro_derive, Normal,
210 template!(List: "TraitName, /*opt*/ attributes(name1, name2, ...)"),
212 ungated!(proc_macro_attribute, Normal, template!(Word)),
215 ungated!(warn, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#)),
216 ungated!(allow, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#)),
217 ungated!(forbid, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#)),
218 ungated!(deny, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#)),
219 ungated!(must_use, Normal, template!(Word, NameValueStr: "reason")),
221 must_not_suspend, Normal, template!(Word, NameValueStr: "reason"), must_not_suspend,
222 experimental!(must_not_suspend)
229 List: r#"/*opt*/ since = "version", /*opt*/ note = "reason""#,
230 NameValueStr: "reason"
235 ungated!(crate_name, CrateLevel, template!(NameValueStr: "name")),
236 ungated!(crate_type, CrateLevel, template!(NameValueStr: "bin|lib|...")),
237 ungated!(crate_id, CrateLevel, template!(NameValueStr: "ignored")),
239 // ABI, linking, symbols, and FFI
242 template!(List: r#"name = "...", /*opt*/ kind = "dylib|static|...", /*opt*/ wasm_import_module = "...""#),
244 ungated!(link_name, Normal, template!(NameValueStr: "name")),
245 ungated!(no_link, Normal, template!(Word)),
246 ungated!(repr, Normal, template!(List: "C")),
247 ungated!(export_name, Normal, template!(NameValueStr: "name")),
248 ungated!(link_section, Normal, template!(NameValueStr: "name")),
249 ungated!(no_mangle, Normal, template!(Word)),
250 ungated!(used, Normal, template!(Word)),
253 ungated!(recursion_limit, CrateLevel, template!(NameValueStr: "N")),
254 ungated!(type_length_limit, CrateLevel, template!(NameValueStr: "N")),
256 const_eval_limit, CrateLevel, template!(NameValueStr: "N"), const_eval_limit,
257 experimental!(const_eval_limit)
260 move_size_limit, CrateLevel, template!(NameValueStr: "N"), large_assignments,
261 experimental!(move_size_limit)
265 ungated!(main, Normal, template!(Word)),
266 ungated!(start, Normal, template!(Word)),
267 ungated!(no_start, CrateLevel, template!(Word)),
268 ungated!(no_main, CrateLevel, template!(Word)),
270 // Modules, prelude, and resolution:
271 ungated!(path, Normal, template!(NameValueStr: "file")),
272 ungated!(no_std, CrateLevel, template!(Word)),
273 ungated!(no_implicit_prelude, Normal, template!(Word)),
274 ungated!(non_exhaustive, Normal, template!(Word)),
277 ungated!(windows_subsystem, Normal, template!(NameValueStr: "windows|console")),
278 ungated!(panic_handler, Normal, template!(Word)), // RFC 2070
281 ungated!(inline, Normal, template!(Word, List: "always|never")),
282 ungated!(cold, Normal, template!(Word)),
283 ungated!(no_builtins, Normal, template!(Word)),
284 ungated!(target_feature, Normal, template!(List: r#"enable = "name""#)),
285 ungated!(track_caller, Normal, template!(Word)),
288 template!(List: "address, memory, thread"),
289 experimental!(no_sanitize)
291 gated!(no_coverage, Normal, template!(Word), experimental!(no_coverage)),
293 // FIXME: #14408 assume docs are used since rustdoc looks at them.
294 ungated!(doc, Normal, template!(List: "hidden|inline|...", NameValueStr: "string")),
296 // ==========================================================================
297 // Unstable attributes:
298 // ==========================================================================
301 gated!(naked, Normal, template!(Word), naked_functions, experimental!(naked)),
303 link_ordinal, Normal, template!(List: "ordinal"), raw_dylib,
304 experimental!(link_ordinal)
311 template: template!(List: "name"),
313 Stability::Deprecated(
314 "https://github.com/rust-lang/rust/pull/64675",
315 Some("may be removed in a future compiler version"),
318 "compiler plugins are deprecated",
324 gated!(allow_fail, Normal, template!(Word), experimental!(allow_fail)),
326 test_runner, CrateLevel, template!(List: "path"), custom_test_frameworks,
327 "custom test frameworks are an unstable feature",
330 gated!(marker, Normal, template!(Word), marker_trait_attr, experimental!(marker)),
332 thread_local, Normal, template!(Word),
333 "`#[thread_local]` is an experimental feature, and does not currently handle destructors",
335 gated!(no_core, CrateLevel, template!(Word), experimental!(no_core)),
338 optimize, Normal, template!(List: "size|speed"), optimize_attribute,
339 experimental!(optimize),
342 gated!(instruction_set, Normal, template!(List: "set"), isa_attribute, experimental!(instruction_set)),
344 gated!(ffi_returns_twice, Normal, template!(Word), experimental!(ffi_returns_twice)),
345 gated!(ffi_pure, Normal, template!(Word), experimental!(ffi_pure)),
346 gated!(ffi_const, Normal, template!(Word), experimental!(ffi_const)),
348 register_attr, CrateLevel, template!(List: "attr1, attr2, ..."),
349 experimental!(register_attr),
352 register_tool, CrateLevel, template!(List: "tool1, tool2, ..."),
353 experimental!(register_tool),
356 gated!(cmse_nonsecure_entry, Normal, template!(Word), experimental!(cmse_nonsecure_entry)),
359 default_method_body_is_const, Normal, template!(Word), const_trait_impl,
360 "`default_method_body_is_const` is a temporary placeholder for declaring default bodies \
361 as `const`, which may be removed or renamed in the future."
364 // ==========================================================================
365 // Internal attributes: Stability, deprecation, and unsafe:
366 // ==========================================================================
368 ungated!(feature, CrateLevel, template!(List: "name1, name1, ...")),
369 // FIXME(#14407) -- only looked at on-demand so we can't
370 // guarantee they'll have already been checked.
372 rustc_deprecated, Normal,
373 template!(List: r#"since = "version", reason = "...""#)
376 ungated!(stable, Normal, template!(List: r#"feature = "name", since = "version""#)),
380 template!(List: r#"feature = "name", reason = "...", issue = "N""#),
383 ungated!(rustc_const_unstable, Normal, template!(List: r#"feature = "name""#)),
385 ungated!(rustc_const_stable, Normal, template!(List: r#"feature = "name""#)),
387 allow_internal_unstable, Normal, template!(Word, List: "feat1, feat2, ..."),
388 "allow_internal_unstable side-steps feature gating and stability checks",
391 rustc_allow_const_fn_unstable, Normal, template!(Word, List: "feat1, feat2, ..."),
392 "rustc_allow_const_fn_unstable side-steps feature gating and stability checks"
395 allow_internal_unsafe, Normal, template!(Word),
396 "allow_internal_unsafe side-steps the unsafe_code lint",
399 // ==========================================================================
400 // Internal attributes: Type system related:
401 // ==========================================================================
403 gated!(fundamental, Normal, template!(Word), experimental!(fundamental)),
405 may_dangle, Normal, template!(Word), dropck_eyepatch,
406 "`may_dangle` has unstable semantics and may be removed in the future",
409 // ==========================================================================
410 // Internal attributes: Runtime related:
411 // ==========================================================================
413 rustc_attr!(rustc_allocator, Normal, template!(Word), IMPL_DETAIL),
414 rustc_attr!(rustc_allocator_nounwind, Normal, template!(Word), IMPL_DETAIL),
415 gated!(alloc_error_handler, Normal, template!(Word), experimental!(alloc_error_handler)),
417 default_lib_allocator, Normal, template!(Word), allocator_internals,
418 experimental!(default_lib_allocator),
421 needs_allocator, Normal, template!(Word), allocator_internals,
422 experimental!(needs_allocator),
424 gated!(panic_runtime, Normal, template!(Word), experimental!(panic_runtime)),
425 gated!(needs_panic_runtime, Normal, template!(Word), experimental!(needs_panic_runtime)),
427 compiler_builtins, Normal, template!(Word),
428 "the `#[compiler_builtins]` attribute is used to identify the `compiler_builtins` crate \
429 which contains compiler-rt intrinsics and will never be stable",
432 profiler_runtime, Normal, template!(Word),
433 "the `#[profiler_runtime]` attribute is used to identify the `profiler_builtins` crate \
434 which contains the profiler runtime and will never be stable",
437 // ==========================================================================
438 // Internal attributes, Linkage:
439 // ==========================================================================
442 linkage, Normal, template!(NameValueStr: "external|internal|..."),
443 "the `linkage` attribute is experimental and not portable across platforms",
445 rustc_attr!(rustc_std_internal_symbol, Normal, template!(Word), INTERNAL_UNSTABLE),
447 // ==========================================================================
448 // Internal attributes, Macro related:
449 // ==========================================================================
452 rustc_builtin_macro, Normal,
453 template!(Word, List: "name, /*opt*/ attributes(name1, name2, ...)"),
456 rustc_attr!(rustc_proc_macro_decls, Normal, template!(Word), INTERNAL_UNSTABLE),
458 rustc_macro_transparency, Normal,
459 template!(NameValueStr: "transparent|semitransparent|opaque"),
460 "used internally for testing macro hygiene",
463 // ==========================================================================
464 // Internal attributes, Diagnostics related:
465 // ==========================================================================
468 rustc_on_unimplemented, Normal,
470 List: r#"/*opt*/ message = "...", /*opt*/ label = "...", /*opt*/ note = "...""#,
471 NameValueStr: "message"
475 // Enumerates "identity-like" conversion methods to suggest on type mismatch.
476 rustc_attr!(rustc_conversion_suggestion, Normal, template!(Word), INTERNAL_UNSTABLE),
477 // Prevents field reads in the marked trait or method to be considered
478 // during dead code analysis.
479 rustc_attr!(rustc_trivial_field_reads, Normal, template!(Word), INTERNAL_UNSTABLE),
481 // ==========================================================================
482 // Internal attributes, Const related:
483 // ==========================================================================
485 rustc_attr!(rustc_promotable, Normal, template!(Word), IMPL_DETAIL),
486 rustc_attr!(rustc_legacy_const_generics, Normal, template!(List: "N"), INTERNAL_UNSTABLE),
487 // Do not const-check this function's body. It will always get replaced during CTFE.
488 rustc_attr!(rustc_do_not_const_check, Normal, template!(Word), INTERNAL_UNSTABLE),
490 // ==========================================================================
491 // Internal attributes, Layout related:
492 // ==========================================================================
495 rustc_layout_scalar_valid_range_start, Normal, template!(List: "value"),
496 "the `#[rustc_layout_scalar_valid_range_start]` attribute is just used to enable \
497 niche optimizations in libcore and will never be stable",
500 rustc_layout_scalar_valid_range_end, Normal, template!(List: "value"),
501 "the `#[rustc_layout_scalar_valid_range_end]` attribute is just used to enable \
502 niche optimizations in libcore and will never be stable",
505 rustc_nonnull_optimization_guaranteed, Normal, template!(Word),
506 "the `#[rustc_nonnull_optimization_guaranteed]` attribute is just used to enable \
507 niche optimizations in libcore and will never be stable",
510 // ==========================================================================
511 // Internal attributes, Misc:
512 // ==========================================================================
514 lang, Normal, template!(NameValueStr: "name"), lang_items,
515 "language items are subject to change",
518 name: sym::rustc_diagnostic_item,
520 template: template!(NameValueStr: "name"),
524 "diagnostic items compiler internal support for linting",
525 cfg_fn!(rustc_attrs),
530 prelude_import, Normal, template!(Word),
531 "`#[prelude_import]` is for use by rustc only",
534 rustc_paren_sugar, Normal, template!(Word), unboxed_closures,
535 "unboxed_closures are still evolving",
538 rustc_inherit_overflow_checks, Normal, template!(Word),
539 "the `#[rustc_inherit_overflow_checks]` attribute is just used to control \
540 overflow checking behavior of several libcore functions that are inlined \
541 across crates and will never be stable",
543 rustc_attr!(rustc_reservation_impl, Normal, template!(NameValueStr: "reservation message"),
544 "the `#[rustc_reservation_impl]` attribute is internally used \
545 for reserving for `for<T> From<!> for T` impl"
548 rustc_test_marker, Normal, template!(Word),
549 "the `#[rustc_test_marker]` attribute is used internally to track tests",
552 rustc_unsafe_specialization_marker, Normal, template!(Word),
553 "the `#[rustc_unsafe_specialization_marker]` attribute is used to check specializations"
556 rustc_specialization_trait, Normal, template!(Word),
557 "the `#[rustc_specialization_trait]` attribute is used to check specializations"
560 rustc_main, Normal, template!(Word),
561 "the `#[rustc_main]` attribute is used internally to specify test entry point function",
564 rustc_skip_array_during_method_dispatch, Normal, template!(Word),
565 "the `#[rustc_skip_array_during_method_dispatch]` attribute is used to exclude a trait \
566 from method dispatch when the receiver is an array, for compatibility in editions < 2021."
569 // ==========================================================================
570 // Internal attributes, Testing:
571 // ==========================================================================
573 rustc_attr!(TEST, rustc_outlives, Normal, template!(Word)),
574 rustc_attr!(TEST, rustc_capture_analysis, Normal, template!(Word)),
575 rustc_attr!(TEST, rustc_insignificant_dtor, Normal, template!(Word)),
576 rustc_attr!(TEST, rustc_strict_coherence, Normal, template!(Word)),
577 rustc_attr!(TEST, rustc_variance, Normal, template!(Word)),
578 rustc_attr!(TEST, rustc_layout, Normal, template!(List: "field1, field2, ...")),
579 rustc_attr!(TEST, rustc_regions, Normal, template!(Word)),
581 TEST, rustc_error, Normal,
582 template!(Word, List: "delay_span_bug_from_inside_query")
584 rustc_attr!(TEST, rustc_dump_user_substs, Normal, template!(Word)),
585 rustc_attr!(TEST, rustc_evaluate_where_clauses, Normal, template!(Word)),
586 rustc_attr!(TEST, rustc_if_this_changed, Normal, template!(Word, List: "DepNode")),
587 rustc_attr!(TEST, rustc_then_this_would_need, Normal, template!(List: "DepNode")),
589 TEST, rustc_clean, Normal,
590 template!(List: r#"cfg = "...", /*opt*/ label = "...", /*opt*/ except = "...""#),
593 TEST, rustc_partition_reused, Normal,
594 template!(List: r#"cfg = "...", module = "...""#),
597 TEST, rustc_partition_codegened, Normal,
598 template!(List: r#"cfg = "...", module = "...""#),
601 TEST, rustc_expected_cgu_reuse, Normal,
602 template!(List: r#"cfg = "...", module = "...", kind = "...""#),
604 rustc_attr!(TEST, rustc_synthetic, Normal, template!(Word)),
605 rustc_attr!(TEST, rustc_symbol_name, Normal, template!(Word)),
606 rustc_attr!(TEST, rustc_polymorphize_error, Normal, template!(Word)),
607 rustc_attr!(TEST, rustc_def_path, Normal, template!(Word)),
608 rustc_attr!(TEST, rustc_mir, Normal, template!(List: "arg1, arg2, ...")),
609 rustc_attr!(TEST, rustc_dump_program_clauses, Normal, template!(Word)),
610 rustc_attr!(TEST, rustc_dump_env_program_clauses, Normal, template!(Word)),
611 rustc_attr!(TEST, rustc_object_lifetime_default, Normal, template!(Word)),
612 rustc_attr!(TEST, rustc_dump_vtable, Normal, template!(Word)),
613 rustc_attr!(TEST, rustc_dummy, Normal, template!(Word /* doesn't matter*/)),
615 omit_gdb_pretty_printer_section, Normal, template!(Word),
616 "the `#[omit_gdb_pretty_printer_section]` attribute is just used for the Rust test suite",
620 pub fn deprecated_attributes() -> Vec<&'static BuiltinAttribute> {
621 BUILTIN_ATTRIBUTES.iter().filter(|attr| attr.gate.is_deprecated()).collect()
624 pub fn is_builtin_attr_name(name: Symbol) -> bool {
625 BUILTIN_ATTRIBUTE_MAP.get(&name).is_some()
628 pub static BUILTIN_ATTRIBUTE_MAP: SyncLazy<FxHashMap<Symbol, &BuiltinAttribute>> =
630 let mut map = FxHashMap::default();
631 for attr in BUILTIN_ATTRIBUTES.iter() {
632 if map.insert(attr.name, attr).is_some() {
633 panic!("duplicate builtin attribute `{}`", attr.name);