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_thread_local, sym::cfg_target_thread_local, cfg_fn!(cfg_target_thread_local)),
27 (sym::target_has_atomic, sym::cfg_target_has_atomic, cfg_fn!(cfg_target_has_atomic)),
28 (sym::target_has_atomic_load_store, sym::cfg_target_has_atomic, cfg_fn!(cfg_target_has_atomic)),
30 sym::target_has_atomic_equal_alignment,
31 sym::cfg_target_has_atomic,
32 cfg_fn!(cfg_target_has_atomic),
34 (sym::sanitize, sym::cfg_sanitize, cfg_fn!(cfg_sanitize)),
35 (sym::version, sym::cfg_version, cfg_fn!(cfg_version)),
38 /// Find a gated cfg determined by the `pred`icate which is given the cfg's name.
39 pub fn find_gated_cfg(pred: impl Fn(Symbol) -> bool) -> Option<&'static GatedCfg> {
40 GATED_CFGS.iter().find(|(cfg_sym, ..)| pred(*cfg_sym))
43 // If you change this, please modify `src/doc/unstable-book` as well. You must
44 // move that documentation into the relevant place in the other docs, and
45 // remove the chapter on the flag.
47 #[derive(Copy, Clone, PartialEq, Debug)]
48 pub enum AttributeType {
49 /// Normal, builtin attribute that is consumed
50 /// by the compiler before the unused_attribute check
53 /// Builtin attribute that may not be consumed by the compiler
54 /// before the unused_attribute check. These attributes
55 /// will be ignored by the unused_attribute lint
58 /// Builtin attribute that is only allowed at the crate level
62 #[derive(Clone, Copy)]
63 pub enum AttributeGate {
64 /// Is gated by a given feature gate, reason
65 /// and function to check if enabled
66 Gated(Stability, Symbol, &'static str, fn(&Features) -> bool),
68 /// Ungated attribute, can be used on all release channels
73 impl std::fmt::Debug for AttributeGate {
74 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76 Self::Gated(ref stab, name, expl, _) => {
77 write!(fmt, "Gated({:?}, {}, {})", stab, name, expl)
79 Self::Ungated => write!(fmt, "Ungated"),
85 fn is_deprecated(&self) -> bool {
87 Self::Gated(Stability::Deprecated(_, _), ..) => true,
93 /// A template that the attribute input must match.
94 /// Only top-level shape (`#[attr]` vs `#[attr(...)]` vs `#[attr = ...]`) is considered now.
95 #[derive(Clone, Copy, Default)]
96 pub struct AttributeTemplate {
98 pub list: Option<&'static str>,
99 pub name_value_str: Option<&'static str>,
102 /// A convenience macro for constructing attribute templates.
103 /// E.g., `template!(Word, List: "description")` means that the attribute
104 /// supports forms `#[attr]` and `#[attr(description)]`.
105 macro_rules! template {
106 (Word) => { template!(@ true, None, None) };
107 (List: $descr: expr) => { template!(@ false, Some($descr), None) };
108 (NameValueStr: $descr: expr) => { template!(@ false, None, Some($descr)) };
109 (Word, List: $descr: expr) => { template!(@ true, Some($descr), None) };
110 (Word, NameValueStr: $descr: expr) => { template!(@ true, None, Some($descr)) };
111 (List: $descr1: expr, NameValueStr: $descr2: expr) => {
112 template!(@ false, Some($descr1), Some($descr2))
114 (Word, List: $descr1: expr, NameValueStr: $descr2: expr) => {
115 template!(@ true, Some($descr1), Some($descr2))
117 (@ $word: expr, $list: expr, $name_value_str: expr) => { AttributeTemplate {
118 word: $word, list: $list, name_value_str: $name_value_str
122 macro_rules! ungated {
123 ($attr:ident, $typ:expr, $tpl:expr $(,)?) => {
124 (sym::$attr, $typ, $tpl, Ungated)
129 ($attr:ident, $typ:expr, $tpl:expr, $gate:ident, $msg:expr $(,)?) => {
130 (sym::$attr, $typ, $tpl, Gated(Stability::Unstable, sym::$gate, $msg, cfg_fn!($gate)))
132 ($attr:ident, $typ:expr, $tpl:expr, $msg:expr $(,)?) => {
133 (sym::$attr, $typ, $tpl, Gated(Stability::Unstable, sym::$attr, $msg, cfg_fn!($attr)))
137 macro_rules! rustc_attr {
138 (TEST, $attr:ident, $typ:expr, $tpl:expr $(,)?) => {
146 "]` attribute is just used for rustc unit tests \
147 and will never be stable",
151 ($attr:ident, $typ:expr, $tpl:expr, $msg:expr $(,)?) => {
156 Gated(Stability::Unstable, sym::rustc_attrs, $msg, cfg_fn!(rustc_attrs)),
161 macro_rules! experimental {
163 concat!("the `#[", stringify!($attr), "]` attribute is an experimental feature")
167 const IMPL_DETAIL: &str = "internal implementation detail";
168 const INTERNAL_UNSTABLE: &str = "this is an internal attribute that will never be stable";
170 pub type BuiltinAttribute = (Symbol, AttributeType, AttributeTemplate, AttributeGate);
172 /// Attributes that have a special meaning to rustc or rustdoc.
174 pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
175 // ==========================================================================
176 // Stable attributes:
177 // ==========================================================================
179 // Conditional compilation:
180 ungated!(cfg, Normal, template!(List: "predicate")),
181 ungated!(cfg_attr, Normal, template!(List: "predicate, attr1, attr2, ...")),
184 ungated!(ignore, Normal, template!(Word, NameValueStr: "reason")),
186 should_panic, Normal,
187 template!(Word, List: r#"expected = "reason"#, NameValueStr: "reason"),
189 // FIXME(Centril): This can be used on stable but shouldn't.
190 ungated!(reexport_test_harness_main, Normal, template!(NameValueStr: "name")),
193 ungated!(derive, Normal, template!(List: "Trait1, Trait2, ...")),
194 ungated!(automatically_derived, Normal, template!(Word)),
196 ungated!(macro_use, Normal, template!(Word, List: "name1, name2, ...")),
197 ungated!(macro_escape, Normal, template!(Word)), // Deprecated synonym for `macro_use`.
198 ungated!(macro_export, Normal, template!(Word, List: "local_inner_macros")),
199 ungated!(proc_macro, Normal, template!(Word)),
201 proc_macro_derive, Normal,
202 template!(List: "TraitName, /*opt*/ attributes(name1, name2, ...)"),
204 ungated!(proc_macro_attribute, Normal, template!(Word)),
207 ungated!(warn, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#)),
208 ungated!(allow, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#)),
209 ungated!(forbid, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#)),
210 ungated!(deny, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#)),
211 ungated!(must_use, AssumedUsed, template!(Word, NameValueStr: "reason")),
217 List: r#"/*opt*/ since = "version", /*opt*/ note = "reason""#,
218 NameValueStr: "reason"
223 ungated!(crate_name, CrateLevel, template!(NameValueStr: "name")),
224 ungated!(crate_type, CrateLevel, template!(NameValueStr: "bin|lib|...")),
225 ungated!(crate_id, CrateLevel, template!(NameValueStr: "ignored")),
227 // ABI, linking, symbols, and FFI
230 template!(List: r#"name = "...", /*opt*/ kind = "dylib|static|...", /*opt*/ wasm_import_module = "...""#),
232 ungated!(link_name, AssumedUsed, template!(NameValueStr: "name")),
233 ungated!(no_link, Normal, template!(Word)),
234 ungated!(repr, Normal, template!(List: "C")),
235 ungated!(export_name, AssumedUsed, template!(NameValueStr: "name")),
236 ungated!(link_section, AssumedUsed, template!(NameValueStr: "name")),
237 ungated!(no_mangle, AssumedUsed, template!(Word)),
238 ungated!(used, AssumedUsed, template!(Word)),
241 ungated!(recursion_limit, CrateLevel, template!(NameValueStr: "N")),
242 ungated!(type_length_limit, CrateLevel, template!(NameValueStr: "N")),
244 const_eval_limit, CrateLevel, template!(NameValueStr: "N"), const_eval_limit,
245 experimental!(const_eval_limit)
249 ungated!(main, Normal, template!(Word)),
250 ungated!(start, Normal, template!(Word)),
251 ungated!(no_start, CrateLevel, template!(Word)),
252 ungated!(no_main, CrateLevel, template!(Word)),
254 // Modules, prelude, and resolution:
255 ungated!(path, Normal, template!(NameValueStr: "file")),
256 ungated!(no_std, CrateLevel, template!(Word)),
257 ungated!(no_implicit_prelude, Normal, template!(Word)),
258 ungated!(non_exhaustive, AssumedUsed, template!(Word)),
261 ungated!(windows_subsystem, AssumedUsed, template!(NameValueStr: "windows|console")),
262 ungated!(panic_handler, Normal, template!(Word)), // RFC 2070
265 ungated!(inline, AssumedUsed, template!(Word, List: "always|never")),
266 ungated!(cold, AssumedUsed, template!(Word)),
267 ungated!(no_builtins, AssumedUsed, template!(Word)),
268 ungated!(target_feature, AssumedUsed, template!(List: r#"enable = "name""#)),
269 ungated!(track_caller, AssumedUsed, template!(Word)),
271 no_sanitize, AssumedUsed,
272 template!(List: "address, memory, thread"),
273 experimental!(no_sanitize)
276 // FIXME: #14408 assume docs are used since rustdoc looks at them.
277 ungated!(doc, AssumedUsed, template!(List: "hidden|inline|...", NameValueStr: "string")),
279 // ==========================================================================
280 // Unstable attributes:
281 // ==========================================================================
284 gated!(naked, AssumedUsed, template!(Word), naked_functions, experimental!(naked)),
286 link_args, Normal, template!(NameValueStr: "args"),
287 "the `link_args` attribute is experimental and not portable across platforms, \
288 it is recommended to use `#[link(name = \"foo\")] instead",
291 link_ordinal, AssumedUsed, template!(List: "ordinal"), raw_dylib,
292 experimental!(link_ordinal)
297 sym::plugin_registrar, Normal, template!(Word),
299 Stability::Deprecated(
300 "https://github.com/rust-lang/rust/pull/64675",
301 Some("may be removed in a future compiler version"),
303 sym::plugin_registrar,
304 "compiler plugins are deprecated",
305 cfg_fn!(plugin_registrar)
309 sym::plugin, CrateLevel, template!(List: "name"),
311 Stability::Deprecated(
312 "https://github.com/rust-lang/rust/pull/64675",
313 Some("may be removed in a future compiler version"),
316 "compiler plugins are deprecated",
322 gated!(allow_fail, Normal, template!(Word), experimental!(allow_fail)),
324 test_runner, CrateLevel, template!(List: "path"), custom_test_frameworks,
325 "custom test frameworks are an unstable feature",
328 gated!(marker, Normal, template!(Word), marker_trait_attr, experimental!(marker)),
330 thread_local, AssumedUsed, template!(Word),
331 "`#[thread_local]` is an experimental feature, and does not currently handle destructors",
333 gated!(no_core, CrateLevel, template!(Word), experimental!(no_core)),
336 optimize, AssumedUsed, template!(List: "size|speed"), optimize_attribute,
337 experimental!(optimize),
340 gated!(ffi_returns_twice, AssumedUsed, template!(Word), experimental!(ffi_returns_twice)),
341 gated!(ffi_pure, AssumedUsed, template!(Word), experimental!(ffi_pure)),
342 gated!(ffi_const, AssumedUsed, template!(Word), experimental!(ffi_const)),
344 register_attr, CrateLevel, template!(List: "attr1, attr2, ..."),
345 experimental!(register_attr),
348 register_tool, CrateLevel, template!(List: "tool1, tool2, ..."),
349 experimental!(register_tool),
352 // ==========================================================================
353 // Internal attributes: Stability, deprecation, and unsafe:
354 // ==========================================================================
356 ungated!(feature, CrateLevel, template!(List: "name1, name1, ...")),
357 // FIXME(#14407) -- only looked at on-demand so we can't
358 // guarantee they'll have already been checked.
360 rustc_deprecated, AssumedUsed,
361 template!(List: r#"since = "version", reason = "...""#)
364 ungated!(stable, AssumedUsed, template!(List: r#"feature = "name", since = "version""#)),
367 unstable, AssumedUsed,
368 template!(List: r#"feature = "name", reason = "...", issue = "N""#),
371 ungated!(rustc_const_unstable, AssumedUsed, template!(List: r#"feature = "name""#)),
373 ungated!(rustc_const_stable, AssumedUsed, template!(List: r#"feature = "name""#)),
375 allow_internal_unstable, AssumedUsed, template!(Word, List: "feat1, feat2, ..."),
376 "allow_internal_unstable side-steps feature gating and stability checks",
379 allow_internal_unsafe, Normal, template!(Word),
380 "allow_internal_unsafe side-steps the unsafe_code lint",
383 // ==========================================================================
384 // Internal attributes: Type system related:
385 // ==========================================================================
387 gated!(fundamental, AssumedUsed, template!(Word), experimental!(fundamental)),
389 may_dangle, Normal, template!(Word), dropck_eyepatch,
390 "`may_dangle` has unstable semantics and may be removed in the future",
393 // ==========================================================================
394 // Internal attributes: Runtime related:
395 // ==========================================================================
397 rustc_attr!(rustc_allocator, AssumedUsed, template!(Word), IMPL_DETAIL),
398 rustc_attr!(rustc_allocator_nounwind, AssumedUsed, template!(Word), IMPL_DETAIL),
399 gated!(alloc_error_handler, Normal, template!(Word), experimental!(alloc_error_handler)),
401 default_lib_allocator, AssumedUsed, template!(Word), allocator_internals,
402 experimental!(default_lib_allocator),
405 needs_allocator, Normal, template!(Word), allocator_internals,
406 experimental!(needs_allocator),
408 gated!(panic_runtime, AssumedUsed, template!(Word), experimental!(panic_runtime)),
409 gated!(needs_panic_runtime, AssumedUsed, template!(Word), experimental!(needs_panic_runtime)),
411 unwind, AssumedUsed, template!(List: "allowed|aborts"), unwind_attributes,
412 experimental!(unwind),
415 compiler_builtins, AssumedUsed, template!(Word),
416 "the `#[compiler_builtins]` attribute is used to identify the `compiler_builtins` crate \
417 which contains compiler-rt intrinsics and will never be stable",
420 profiler_runtime, AssumedUsed, template!(Word),
421 "the `#[profiler_runtime]` attribute is used to identify the `profiler_builtins` crate \
422 which contains the profiler runtime and will never be stable",
425 // ==========================================================================
426 // Internal attributes, Linkage:
427 // ==========================================================================
430 linkage, AssumedUsed, template!(NameValueStr: "external|internal|..."),
431 "the `linkage` attribute is experimental and not portable across platforms",
433 rustc_attr!(rustc_std_internal_symbol, AssumedUsed, template!(Word), INTERNAL_UNSTABLE),
435 // ==========================================================================
436 // Internal attributes, Macro related:
437 // ==========================================================================
439 rustc_attr!(rustc_builtin_macro, AssumedUsed, template!(Word), IMPL_DETAIL),
440 rustc_attr!(rustc_proc_macro_decls, Normal, template!(Word), INTERNAL_UNSTABLE),
442 rustc_macro_transparency, AssumedUsed,
443 template!(NameValueStr: "transparent|semitransparent|opaque"),
444 "used internally for testing macro hygiene",
447 // ==========================================================================
448 // Internal attributes, Diagnostics related:
449 // ==========================================================================
452 rustc_on_unimplemented, AssumedUsed,
454 List: r#"/*opt*/ message = "...", /*opt*/ label = "...", /*opt*/ note = "...""#,
455 NameValueStr: "message"
459 // Enumerates "identity-like" conversion methods to suggest on type mismatch.
460 rustc_attr!(rustc_conversion_suggestion, AssumedUsed, template!(Word), INTERNAL_UNSTABLE),
462 // ==========================================================================
463 // Internal attributes, Const related:
464 // ==========================================================================
466 rustc_attr!(rustc_promotable, AssumedUsed, template!(Word), IMPL_DETAIL),
467 rustc_attr!(rustc_allow_const_fn_ptr, AssumedUsed, template!(Word), IMPL_DETAIL),
468 rustc_attr!(rustc_args_required_const, AssumedUsed, template!(List: "N"), INTERNAL_UNSTABLE),
470 // ==========================================================================
471 // Internal attributes, Layout related:
472 // ==========================================================================
475 rustc_layout_scalar_valid_range_start, AssumedUsed, template!(List: "value"),
476 "the `#[rustc_layout_scalar_valid_range_start]` attribute is just used to enable \
477 niche optimizations in libcore and will never be stable",
480 rustc_layout_scalar_valid_range_end, AssumedUsed, template!(List: "value"),
481 "the `#[rustc_layout_scalar_valid_range_end]` attribute is just used to enable \
482 niche optimizations in libcore and will never be stable",
485 rustc_nonnull_optimization_guaranteed, AssumedUsed, template!(Word),
486 "the `#[rustc_nonnull_optimization_guaranteed]` attribute is just used to enable \
487 niche optimizations in libcore and will never be stable",
490 // ==========================================================================
491 // Internal attributes, Misc:
492 // ==========================================================================
494 lang, Normal, template!(NameValueStr: "name"), lang_items,
495 "language items are subject to change",
498 sym::rustc_diagnostic_item,
500 template!(NameValueStr: "name"),
504 "diagnostic items compiler internal support for linting",
505 cfg_fn!(rustc_attrs),
510 prelude_import, AssumedUsed, template!(Word),
511 "`#[prelude_import]` is for use by rustc only",
514 rustc_paren_sugar, Normal, template!(Word), unboxed_closures,
515 "unboxed_closures are still evolving",
518 rustc_inherit_overflow_checks, AssumedUsed, template!(Word),
519 "the `#[rustc_inherit_overflow_checks]` attribute is just used to control \
520 overflow checking behavior of several libcore functions that are inlined \
521 across crates and will never be stable",
523 rustc_attr!(rustc_reservation_impl, Normal, template!(NameValueStr: "reservation message"),
524 "the `#[rustc_reservation_impl]` attribute is internally used \
525 for reserving for `for<T> From<!> for T` impl"
528 rustc_test_marker, Normal, template!(Word),
529 "the `#[rustc_test_marker]` attribute is used internally to track tests",
532 rustc_unsafe_specialization_marker, Normal, template!(Word),
533 "the `#[rustc_unsafe_specialization_marker]` attribute is used to check specializations"
536 rustc_specialization_trait, Normal, template!(Word),
537 "the `#[rustc_specialization_trait]` attribute is used to check specializations"
540 // ==========================================================================
541 // Internal attributes, Testing:
542 // ==========================================================================
544 rustc_attr!(TEST, rustc_outlives, Normal, template!(Word)),
545 rustc_attr!(TEST, rustc_variance, Normal, template!(Word)),
546 rustc_attr!(TEST, rustc_layout, Normal, template!(List: "field1, field2, ...")),
547 rustc_attr!(TEST, rustc_regions, Normal, template!(Word)),
549 TEST, rustc_error, AssumedUsed,
550 template!(Word, List: "delay_span_bug_from_inside_query")
552 rustc_attr!(TEST, rustc_dump_user_substs, AssumedUsed, template!(Word)),
553 rustc_attr!(TEST, rustc_if_this_changed, AssumedUsed, template!(Word, List: "DepNode")),
554 rustc_attr!(TEST, rustc_then_this_would_need, AssumedUsed, template!(List: "DepNode")),
556 TEST, rustc_dirty, AssumedUsed,
557 template!(List: r#"cfg = "...", /*opt*/ label = "...", /*opt*/ except = "...""#),
560 TEST, rustc_clean, AssumedUsed,
561 template!(List: r#"cfg = "...", /*opt*/ label = "...", /*opt*/ except = "...""#),
564 TEST, rustc_partition_reused, AssumedUsed,
565 template!(List: r#"cfg = "...", module = "...""#),
568 TEST, rustc_partition_codegened, AssumedUsed,
569 template!(List: r#"cfg = "...", module = "...""#),
572 TEST, rustc_expected_cgu_reuse, AssumedUsed,
573 template!(List: r#"cfg = "...", module = "...", kind = "...""#),
575 rustc_attr!(TEST, rustc_synthetic, AssumedUsed, template!(Word)),
576 rustc_attr!(TEST, rustc_symbol_name, AssumedUsed, template!(Word)),
577 rustc_attr!(TEST, rustc_polymorphize_error, AssumedUsed, template!(Word)),
578 rustc_attr!(TEST, rustc_def_path, AssumedUsed, template!(Word)),
579 rustc_attr!(TEST, rustc_mir, AssumedUsed, template!(List: "arg1, arg2, ...")),
580 rustc_attr!(TEST, rustc_dump_program_clauses, AssumedUsed, template!(Word)),
581 rustc_attr!(TEST, rustc_dump_env_program_clauses, AssumedUsed, template!(Word)),
582 rustc_attr!(TEST, rustc_object_lifetime_default, AssumedUsed, template!(Word)),
583 rustc_attr!(TEST, rustc_dummy, Normal, template!(Word /* doesn't matter*/)),
585 omit_gdb_pretty_printer_section, AssumedUsed, template!(Word),
586 "the `#[omit_gdb_pretty_printer_section]` attribute is just used for the Rust test suite",
590 pub fn deprecated_attributes() -> Vec<&'static BuiltinAttribute> {
591 BUILTIN_ATTRIBUTES.iter().filter(|(.., gate)| gate.is_deprecated()).collect()
594 pub fn is_builtin_attr_name(name: Symbol) -> bool {
595 BUILTIN_ATTRIBUTE_MAP.get(&name).is_some()
598 pub static BUILTIN_ATTRIBUTE_MAP: SyncLazy<FxHashMap<Symbol, &'static BuiltinAttribute>> =
600 let mut map = FxHashMap::default();
601 for attr in BUILTIN_ATTRIBUTES.iter() {
602 if map.insert(attr.0, attr).is_some() {
603 panic!("duplicate builtin attribute `{}`", attr.0);