1 //! Built-in attributes and `cfg` flag gating.
6 use crate::{Features, Stability};
8 use lazy_static::lazy_static;
9 use rustc_data_structures::fx::FxHashMap;
10 use rustc_span::symbol::{sym, Symbol};
12 type GateFn = fn(&Features) -> bool;
16 (|features| features.$field) as GateFn
20 pub type GatedCfg = (Symbol, Symbol, GateFn);
22 /// `cfg(...)`'s that are feature gated.
23 const GATED_CFGS: &[GatedCfg] = &[
24 // (name in cfg, feature, function to check if the feature is enabled)
25 (sym::target_thread_local, sym::cfg_target_thread_local, cfg_fn!(cfg_target_thread_local)),
26 (sym::target_has_atomic, sym::cfg_target_has_atomic, cfg_fn!(cfg_target_has_atomic)),
27 (sym::target_has_atomic_load_store, sym::cfg_target_has_atomic, cfg_fn!(cfg_target_has_atomic)),
28 (sym::sanitize, sym::cfg_sanitize, cfg_fn!(cfg_sanitize)),
29 (sym::version, sym::cfg_version, cfg_fn!(cfg_version)),
32 /// Find a gated cfg determined by the `pred`icate which is given the cfg's name.
33 pub fn find_gated_cfg(pred: impl Fn(Symbol) -> bool) -> Option<&'static GatedCfg> {
34 GATED_CFGS.iter().find(|(cfg_sym, ..)| pred(*cfg_sym))
37 // If you change this, please modify `src/doc/unstable-book` as well. You must
38 // move that documentation into the relevant place in the other docs, and
39 // remove the chapter on the flag.
41 #[derive(Copy, Clone, PartialEq, Debug)]
42 pub enum AttributeType {
43 /// Normal, builtin attribute that is consumed
44 /// by the compiler before the unused_attribute check
47 /// Builtin attribute that may not be consumed by the compiler
48 /// before the unused_attribute check. These attributes
49 /// will be ignored by the unused_attribute lint
52 /// Builtin attribute that is only allowed at the crate level
56 #[derive(Clone, Copy)]
57 pub enum AttributeGate {
58 /// Is gated by a given feature gate, reason
59 /// and function to check if enabled
60 Gated(Stability, Symbol, &'static str, fn(&Features) -> bool),
62 /// Ungated attribute, can be used on all release channels
67 impl std::fmt::Debug for AttributeGate {
68 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70 Self::Gated(ref stab, name, expl, _) => {
71 write!(fmt, "Gated({:?}, {}, {})", stab, name, expl)
73 Self::Ungated => write!(fmt, "Ungated"),
79 fn is_deprecated(&self) -> bool {
81 Self::Gated(Stability::Deprecated(_, _), ..) => true,
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 (sym::$attr, $typ, $tpl, Ungated)
123 ($attr:ident, $typ:expr, $tpl:expr, $gate:ident, $msg:expr $(,)?) => {
124 (sym::$attr, $typ, $tpl, Gated(Stability::Unstable, sym::$gate, $msg, cfg_fn!($gate)))
126 ($attr:ident, $typ:expr, $tpl:expr, $msg:expr $(,)?) => {
127 (sym::$attr, $typ, $tpl, Gated(Stability::Unstable, sym::$attr, $msg, cfg_fn!($attr)))
131 macro_rules! rustc_attr {
132 (TEST, $attr:ident, $typ:expr, $tpl:expr $(,)?) => {
140 "]` attribute is just used for rustc unit tests \
141 and will never be stable",
145 ($attr:ident, $typ:expr, $tpl:expr, $msg:expr $(,)?) => {
150 Gated(Stability::Unstable, sym::rustc_attrs, $msg, cfg_fn!(rustc_attrs)),
155 macro_rules! experimental {
157 concat!("the `#[", stringify!($attr), "]` attribute is an experimental feature")
161 const IMPL_DETAIL: &str = "internal implementation detail";
162 const INTERNAL_UNSTABLE: &str = "this is an internal attribute that will never be stable";
164 pub type BuiltinAttribute = (Symbol, AttributeType, AttributeTemplate, AttributeGate);
166 /// Attributes that have a special meaning to rustc or rustdoc.
168 pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
169 // ==========================================================================
170 // Stable attributes:
171 // ==========================================================================
173 // Conditional compilation:
174 ungated!(cfg, Normal, template!(List: "predicate")),
175 ungated!(cfg_attr, Normal, template!(List: "predicate, attr1, attr2, ...")),
178 ungated!(ignore, Normal, template!(Word, NameValueStr: "reason")),
180 should_panic, Normal,
181 template!(Word, List: r#"expected = "reason"#, NameValueStr: "reason"),
183 // FIXME(Centril): This can be used on stable but shouldn't.
184 ungated!(reexport_test_harness_main, Normal, template!(NameValueStr: "name")),
187 ungated!(derive, Normal, template!(List: "Trait1, Trait2, ...")),
188 ungated!(automatically_derived, Normal, template!(Word)),
190 ungated!(macro_use, Normal, template!(Word, List: "name1, name2, ...")),
191 ungated!(macro_escape, Normal, template!(Word)), // Deprecated synonym for `macro_use`.
192 ungated!(macro_export, Normal, template!(Word, List: "local_inner_macros")),
193 ungated!(proc_macro, Normal, template!(Word)),
195 proc_macro_derive, Normal,
196 template!(List: "TraitName, /*opt*/ attributes(name1, name2, ...)"),
198 ungated!(proc_macro_attribute, Normal, template!(Word)),
201 ungated!(warn, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#)),
202 ungated!(allow, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#)),
203 ungated!(forbid, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#)),
204 ungated!(deny, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#)),
205 ungated!(must_use, AssumedUsed, template!(Word, NameValueStr: "reason")),
211 List: r#"/*opt*/ since = "version", /*opt*/ note = "reason""#,
212 NameValueStr: "reason"
217 ungated!(crate_name, CrateLevel, template!(NameValueStr: "name")),
218 ungated!(crate_type, CrateLevel, template!(NameValueStr: "bin|lib|...")),
219 ungated!(crate_id, CrateLevel, template!(NameValueStr: "ignored")),
221 // ABI, linking, symbols, and FFI
224 template!(List: r#"name = "...", /*opt*/ kind = "dylib|static|...", /*opt*/ wasm_import_module = "...""#),
226 ungated!(link_name, AssumedUsed, template!(NameValueStr: "name")),
227 ungated!(no_link, Normal, template!(Word)),
228 ungated!(repr, Normal, template!(List: "C")),
229 ungated!(export_name, AssumedUsed, template!(NameValueStr: "name")),
230 ungated!(link_section, AssumedUsed, template!(NameValueStr: "name")),
231 ungated!(no_mangle, AssumedUsed, template!(Word)),
232 ungated!(used, AssumedUsed, template!(Word)),
235 ungated!(recursion_limit, CrateLevel, template!(NameValueStr: "N")),
236 ungated!(type_length_limit, CrateLevel, template!(NameValueStr: "N")),
238 const_eval_limit, CrateLevel, template!(NameValueStr: "N"), const_eval_limit,
239 experimental!(const_eval_limit)
243 ungated!(main, Normal, template!(Word)),
244 ungated!(start, Normal, template!(Word)),
245 ungated!(no_start, CrateLevel, template!(Word)),
246 ungated!(no_main, CrateLevel, template!(Word)),
248 // Modules, prelude, and resolution:
249 ungated!(path, Normal, template!(NameValueStr: "file")),
250 ungated!(no_std, CrateLevel, template!(Word)),
251 ungated!(no_implicit_prelude, Normal, template!(Word)),
252 ungated!(non_exhaustive, AssumedUsed, template!(Word)),
255 ungated!(windows_subsystem, AssumedUsed, template!(NameValueStr: "windows|console")),
256 ungated!(panic_handler, Normal, template!(Word)), // RFC 2070
259 ungated!(inline, AssumedUsed, template!(Word, List: "always|never")),
260 ungated!(cold, AssumedUsed, template!(Word)),
261 ungated!(no_builtins, AssumedUsed, template!(Word)),
262 ungated!(target_feature, AssumedUsed, template!(List: r#"enable = "name""#)),
263 ungated!(track_caller, AssumedUsed, template!(Word)),
265 no_sanitize, AssumedUsed,
266 template!(List: "address, memory, thread"),
267 experimental!(no_sanitize)
270 // FIXME: #14408 assume docs are used since rustdoc looks at them.
271 ungated!(doc, AssumedUsed, template!(List: "hidden|inline|...", NameValueStr: "string")),
273 // ==========================================================================
274 // Unstable attributes:
275 // ==========================================================================
278 gated!(naked, AssumedUsed, template!(Word), naked_functions, experimental!(naked)),
280 link_args, Normal, template!(NameValueStr: "args"),
281 "the `link_args` attribute is experimental and not portable across platforms, \
282 it is recommended to use `#[link(name = \"foo\")] instead",
285 link_ordinal, AssumedUsed, template!(List: "ordinal"), raw_dylib,
286 experimental!(link_ordinal)
291 sym::plugin_registrar, Normal, template!(Word),
293 Stability::Deprecated(
294 "https://github.com/rust-lang/rust/pull/64675",
295 Some("may be removed in a future compiler version"),
297 sym::plugin_registrar,
298 "compiler plugins are deprecated",
299 cfg_fn!(plugin_registrar)
303 sym::plugin, CrateLevel, template!(List: "name"),
305 Stability::Deprecated(
306 "https://github.com/rust-lang/rust/pull/64675",
307 Some("may be removed in a future compiler version"),
310 "compiler plugins are deprecated",
316 gated!(allow_fail, Normal, template!(Word), experimental!(allow_fail)),
318 test_runner, CrateLevel, template!(List: "path"), custom_test_frameworks,
319 "custom test frameworks are an unstable feature",
322 gated!(marker, Normal, template!(Word), marker_trait_attr, experimental!(marker)),
324 thread_local, AssumedUsed, template!(Word),
325 "`#[thread_local]` is an experimental feature, and does not currently handle destructors",
327 gated!(no_core, CrateLevel, template!(Word), experimental!(no_core)),
330 optimize, AssumedUsed, template!(List: "size|speed"), optimize_attribute,
331 experimental!(optimize),
334 gated!(ffi_returns_twice, AssumedUsed, template!(Word), experimental!(ffi_returns_twice)),
335 gated!(ffi_pure, AssumedUsed, template!(Word), experimental!(ffi_pure)),
336 gated!(ffi_const, AssumedUsed, template!(Word), experimental!(ffi_const)),
338 register_attr, CrateLevel, template!(List: "attr1, attr2, ..."),
339 experimental!(register_attr),
342 register_tool, CrateLevel, template!(List: "tool1, tool2, ..."),
343 experimental!(register_tool),
346 // ==========================================================================
347 // Internal attributes: Stability, deprecation, and unsafe:
348 // ==========================================================================
350 ungated!(feature, CrateLevel, template!(List: "name1, name1, ...")),
351 // FIXME(#14407) -- only looked at on-demand so we can't
352 // guarantee they'll have already been checked.
354 rustc_deprecated, AssumedUsed,
355 template!(List: r#"since = "version", reason = "...""#)
358 ungated!(stable, AssumedUsed, template!(List: r#"feature = "name", since = "version""#)),
361 unstable, AssumedUsed,
362 template!(List: r#"feature = "name", reason = "...", issue = "N""#),
365 ungated!(rustc_const_unstable, AssumedUsed, template!(List: r#"feature = "name""#)),
367 ungated!(rustc_const_stable, AssumedUsed, template!(List: r#"feature = "name""#)),
369 allow_internal_unstable, AssumedUsed, template!(Word, List: "feat1, feat2, ..."),
370 "allow_internal_unstable side-steps feature gating and stability checks",
373 allow_internal_unsafe, Normal, template!(Word),
374 "allow_internal_unsafe side-steps the unsafe_code lint",
377 // ==========================================================================
378 // Internal attributes: Type system related:
379 // ==========================================================================
381 gated!(fundamental, AssumedUsed, template!(Word), experimental!(fundamental)),
383 may_dangle, Normal, template!(Word), dropck_eyepatch,
384 "`may_dangle` has unstable semantics and may be removed in the future",
387 // ==========================================================================
388 // Internal attributes: Runtime related:
389 // ==========================================================================
391 rustc_attr!(rustc_allocator, AssumedUsed, template!(Word), IMPL_DETAIL),
392 rustc_attr!(rustc_allocator_nounwind, AssumedUsed, template!(Word), IMPL_DETAIL),
393 gated!(alloc_error_handler, Normal, template!(Word), experimental!(alloc_error_handler)),
395 default_lib_allocator, AssumedUsed, template!(Word), allocator_internals,
396 experimental!(default_lib_allocator),
399 needs_allocator, Normal, template!(Word), allocator_internals,
400 experimental!(needs_allocator),
402 gated!(panic_runtime, AssumedUsed, template!(Word), experimental!(panic_runtime)),
403 gated!(needs_panic_runtime, AssumedUsed, template!(Word), experimental!(needs_panic_runtime)),
405 unwind, AssumedUsed, template!(List: "allowed|aborts"), unwind_attributes,
406 experimental!(unwind),
409 compiler_builtins, AssumedUsed, template!(Word),
410 "the `#[compiler_builtins]` attribute is used to identify the `compiler_builtins` crate \
411 which contains compiler-rt intrinsics and will never be stable",
414 profiler_runtime, AssumedUsed, template!(Word),
415 "the `#[profiler_runtime]` attribute is used to identify the `profiler_builtins` crate \
416 which contains the profiler runtime and will never be stable",
419 // ==========================================================================
420 // Internal attributes, Linkage:
421 // ==========================================================================
424 linkage, AssumedUsed, template!(NameValueStr: "external|internal|..."),
425 "the `linkage` attribute is experimental and not portable across platforms",
427 rustc_attr!(rustc_std_internal_symbol, AssumedUsed, template!(Word), INTERNAL_UNSTABLE),
429 // ==========================================================================
430 // Internal attributes, Macro related:
431 // ==========================================================================
433 rustc_attr!(rustc_builtin_macro, AssumedUsed, template!(Word), IMPL_DETAIL),
434 rustc_attr!(rustc_proc_macro_decls, Normal, template!(Word), INTERNAL_UNSTABLE),
436 rustc_macro_transparency, AssumedUsed,
437 template!(NameValueStr: "transparent|semitransparent|opaque"),
438 "used internally for testing macro hygiene",
441 // ==========================================================================
442 // Internal attributes, Diagnostics related:
443 // ==========================================================================
446 rustc_on_unimplemented, AssumedUsed,
448 List: r#"/*opt*/ message = "...", /*opt*/ label = "...", /*opt*/ note = "...""#,
449 NameValueStr: "message"
453 // Enumerates "identity-like" conversion methods to suggest on type mismatch.
454 rustc_attr!(rustc_conversion_suggestion, AssumedUsed, template!(Word), INTERNAL_UNSTABLE),
456 // ==========================================================================
457 // Internal attributes, Const related:
458 // ==========================================================================
460 rustc_attr!(rustc_promotable, AssumedUsed, template!(Word), IMPL_DETAIL),
461 rustc_attr!(rustc_allow_const_fn_ptr, AssumedUsed, template!(Word), IMPL_DETAIL),
462 rustc_attr!(rustc_args_required_const, AssumedUsed, template!(List: "N"), INTERNAL_UNSTABLE),
464 // ==========================================================================
465 // Internal attributes, Layout related:
466 // ==========================================================================
469 rustc_layout_scalar_valid_range_start, AssumedUsed, template!(List: "value"),
470 "the `#[rustc_layout_scalar_valid_range_start]` attribute is just used to enable \
471 niche optimizations in libcore and will never be stable",
474 rustc_layout_scalar_valid_range_end, AssumedUsed, template!(List: "value"),
475 "the `#[rustc_layout_scalar_valid_range_end]` attribute is just used to enable \
476 niche optimizations in libcore and will never be stable",
479 rustc_nonnull_optimization_guaranteed, AssumedUsed, template!(Word),
480 "the `#[rustc_nonnull_optimization_guaranteed]` attribute is just used to enable \
481 niche optimizations in libcore and will never be stable",
484 // ==========================================================================
485 // Internal attributes, Misc:
486 // ==========================================================================
488 lang, Normal, template!(NameValueStr: "name"), lang_items,
489 "language items are subject to change",
492 sym::rustc_diagnostic_item,
494 template!(NameValueStr: "name"),
498 "diagnostic items compiler internal support for linting",
499 cfg_fn!(rustc_attrs),
504 prelude_import, AssumedUsed, template!(Word),
505 "`#[prelude_import]` is for use by rustc only",
508 rustc_paren_sugar, Normal, template!(Word), unboxed_closures,
509 "unboxed_closures are still evolving",
512 rustc_inherit_overflow_checks, AssumedUsed, template!(Word),
513 "the `#[rustc_inherit_overflow_checks]` attribute is just used to control \
514 overflow checking behavior of several libcore functions that are inlined \
515 across crates and will never be stable",
517 rustc_attr!(rustc_reservation_impl, Normal, template!(NameValueStr: "reservation message"),
518 "the `#[rustc_reservation_impl]` attribute is internally used \
519 for reserving for `for<T> From<!> for T` impl"
522 rustc_test_marker, Normal, template!(Word),
523 "the `#[rustc_test_marker]` attribute is used internally to track tests",
526 rustc_unsafe_specialization_marker, Normal, template!(Word),
527 "the `#[rustc_unsafe_specialization_marker]` attribute is used to check specializations"
530 rustc_specialization_trait, Normal, template!(Word),
531 "the `#[rustc_specialization_trait]` attribute is used to check specializations"
534 // ==========================================================================
535 // Internal attributes, Testing:
536 // ==========================================================================
538 rustc_attr!(TEST, rustc_outlives, Normal, template!(Word)),
539 rustc_attr!(TEST, rustc_variance, Normal, template!(Word)),
540 rustc_attr!(TEST, rustc_layout, Normal, template!(List: "field1, field2, ...")),
541 rustc_attr!(TEST, rustc_regions, Normal, template!(Word)),
543 TEST, rustc_error, AssumedUsed,
544 template!(Word, List: "delay_span_bug_from_inside_query")
546 rustc_attr!(TEST, rustc_dump_user_substs, AssumedUsed, template!(Word)),
547 rustc_attr!(TEST, rustc_if_this_changed, AssumedUsed, template!(Word, List: "DepNode")),
548 rustc_attr!(TEST, rustc_then_this_would_need, AssumedUsed, template!(List: "DepNode")),
550 TEST, rustc_dirty, AssumedUsed,
551 template!(List: r#"cfg = "...", /*opt*/ label = "...", /*opt*/ except = "...""#),
554 TEST, rustc_clean, AssumedUsed,
555 template!(List: r#"cfg = "...", /*opt*/ label = "...", /*opt*/ except = "...""#),
558 TEST, rustc_partition_reused, AssumedUsed,
559 template!(List: r#"cfg = "...", module = "...""#),
562 TEST, rustc_partition_codegened, AssumedUsed,
563 template!(List: r#"cfg = "...", module = "...""#),
566 TEST, rustc_expected_cgu_reuse, AssumedUsed,
567 template!(List: r#"cfg = "...", module = "...", kind = "...""#),
569 rustc_attr!(TEST, rustc_synthetic, AssumedUsed, template!(Word)),
570 rustc_attr!(TEST, rustc_symbol_name, AssumedUsed, template!(Word)),
571 rustc_attr!(TEST, rustc_polymorphize_error, AssumedUsed, template!(Word)),
572 rustc_attr!(TEST, rustc_def_path, AssumedUsed, template!(Word)),
573 rustc_attr!(TEST, rustc_mir, AssumedUsed, template!(List: "arg1, arg2, ...")),
574 rustc_attr!(TEST, rustc_dump_program_clauses, AssumedUsed, template!(Word)),
575 rustc_attr!(TEST, rustc_dump_env_program_clauses, AssumedUsed, template!(Word)),
576 rustc_attr!(TEST, rustc_object_lifetime_default, AssumedUsed, template!(Word)),
577 rustc_attr!(TEST, rustc_dummy, Normal, template!(Word /* doesn't matter*/)),
579 omit_gdb_pretty_printer_section, AssumedUsed, template!(Word),
580 "the `#[omit_gdb_pretty_printer_section]` attribute is just used for the Rust test suite",
584 pub fn deprecated_attributes() -> Vec<&'static BuiltinAttribute> {
585 BUILTIN_ATTRIBUTES.iter().filter(|(.., gate)| gate.is_deprecated()).collect()
588 pub fn is_builtin_attr_name(name: Symbol) -> bool {
589 BUILTIN_ATTRIBUTE_MAP.get(&name).is_some()
593 pub static ref BUILTIN_ATTRIBUTE_MAP: FxHashMap<Symbol, &'static BuiltinAttribute> = {
594 let mut map = FxHashMap::default();
595 for attr in BUILTIN_ATTRIBUTES.iter() {
596 if map.insert(attr.0, attr).is_some() {
597 panic!("duplicate builtin attribute `{}`", attr.0);