1 //! Built-in attributes and `cfg` flag gating.
6 use super::check::{emit_feature_err, GateIssue};
7 use super::check::{Stability, EXPLAIN_ALLOW_INTERNAL_UNSAFE, EXPLAIN_ALLOW_INTERNAL_UNSTABLE};
8 use super::active::Features;
11 use crate::attr::AttributeTemplate;
12 use crate::sess::ParseSess;
13 use crate::symbol::{Symbol, sym};
16 use rustc_data_structures::fx::FxHashMap;
17 use lazy_static::lazy_static;
19 type GateFn = fn(&Features) -> bool;
23 (|features| { features.$field }) as GateFn
27 /// `cfg(...)`'s that are feature gated.
28 const GATED_CFGS: &[(Symbol, Symbol, GateFn)] = &[
29 // (name in cfg, feature, function to check if the feature is enabled)
30 (sym::target_thread_local, sym::cfg_target_thread_local, cfg_fn!(cfg_target_thread_local)),
31 (sym::target_has_atomic, sym::cfg_target_has_atomic, cfg_fn!(cfg_target_has_atomic)),
32 (sym::target_has_atomic_load_store, sym::cfg_target_has_atomic, cfg_fn!(cfg_target_has_atomic)),
33 (sym::doc, sym::doc_cfg, cfg_fn!(doc_cfg)),
43 pub fn gate(cfg: &ast::MetaItem) -> Option<GatedCfg> {
45 .position(|info| cfg.check_name(info.0))
54 pub fn check_and_emit(&self, sess: &ParseSess, features: &Features) {
55 let (cfg, feature, has_feature) = GATED_CFGS[self.index];
56 if !has_feature(features) && !self.span.allows_unstable(feature) {
57 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
58 emit_feature_err(sess, feature, self.span, GateIssue::Language, &explain);
63 // If you change this, please modify `src/doc/unstable-book` as well. You must
64 // move that documentation into the relevant place in the other docs, and
65 // remove the chapter on the flag.
67 #[derive(Copy, Clone, PartialEq, Debug)]
68 pub enum AttributeType {
69 /// Normal, builtin attribute that is consumed
70 /// by the compiler before the unused_attribute check
73 /// Builtin attribute that may not be consumed by the compiler
74 /// before the unused_attribute check. These attributes
75 /// will be ignored by the unused_attribute lint
78 /// Builtin attribute that is only allowed at the crate level
82 #[derive(Clone, Copy)]
83 pub enum AttributeGate {
84 /// Is gated by a given feature gate, reason
85 /// and function to check if enabled
86 Gated(Stability, Symbol, &'static str, fn(&Features) -> bool),
88 /// Ungated attribute, can be used on all release channels
93 impl std::fmt::Debug for AttributeGate {
94 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96 Self::Gated(ref stab, name, expl, _) =>
97 write!(fmt, "Gated({:?}, {}, {})", stab, name, expl),
98 Self::Ungated => write!(fmt, "Ungated")
104 fn is_deprecated(&self) -> bool {
106 Self::Gated(Stability::Deprecated(_, _), ..) => true,
112 /// A convenience macro for constructing attribute templates.
113 /// E.g., `template!(Word, List: "description")` means that the attribute
114 /// supports forms `#[attr]` and `#[attr(description)]`.
115 macro_rules! template {
116 (Word) => { template!(@ true, None, None) };
117 (List: $descr: expr) => { template!(@ false, Some($descr), None) };
118 (NameValueStr: $descr: expr) => { template!(@ false, None, Some($descr)) };
119 (Word, List: $descr: expr) => { template!(@ true, Some($descr), None) };
120 (Word, NameValueStr: $descr: expr) => { template!(@ true, None, Some($descr)) };
121 (List: $descr1: expr, NameValueStr: $descr2: expr) => {
122 template!(@ false, Some($descr1), Some($descr2))
124 (Word, List: $descr1: expr, NameValueStr: $descr2: expr) => {
125 template!(@ true, Some($descr1), Some($descr2))
127 (@ $word: expr, $list: expr, $name_value_str: expr) => { AttributeTemplate {
128 word: $word, list: $list, name_value_str: $name_value_str
132 macro_rules! ungated {
133 ($attr:ident, $typ:expr, $tpl:expr $(,)?) => {
134 (sym::$attr, $typ, $tpl, Ungated)
139 ($attr:ident, $typ:expr, $tpl:expr, $gate:ident, $msg:expr $(,)?) => {
140 (sym::$attr, $typ, $tpl, Gated(Stability::Unstable, sym::$gate, $msg, cfg_fn!($gate)))
142 ($attr:ident, $typ:expr, $tpl:expr, $msg:expr $(,)?) => {
143 (sym::$attr, $typ, $tpl, Gated(Stability::Unstable, sym::$attr, $msg, cfg_fn!($attr)))
147 macro_rules! rustc_attr {
148 (TEST, $attr:ident, $typ:expr, $tpl:expr $(,)?) => {
151 concat!("the `#[", stringify!($attr), "]` attribute is just used for rustc unit tests \
152 and will never be stable",
156 ($attr:ident, $typ:expr, $tpl:expr, $msg:expr $(,)?) => {
157 (sym::$attr, $typ, $tpl,
158 Gated(Stability::Unstable, sym::rustc_attrs, $msg, cfg_fn!(rustc_attrs)))
162 macro_rules! experimental {
164 concat!("the `#[", stringify!($attr), "]` attribute is an experimental feature")
168 const IMPL_DETAIL: &str = "internal implementation detail";
169 const INTERNAL_UNSTABLE: &str = "this is an internal attribute that will never be stable";
171 pub type BuiltinAttribute = (Symbol, AttributeType, AttributeTemplate, AttributeGate);
173 /// Attributes that have a special meaning to rustc or rustdoc.
174 pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
175 // ==========================================================================
176 // Stable attributes:
177 // ==========================================================================
179 // Condtional 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, Whitelisted, 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*/ cfg = "...""#),
232 ungated!(link_name, Whitelisted, template!(NameValueStr: "name")),
233 ungated!(no_link, Normal, template!(Word)),
234 ungated!(repr, Normal, template!(List: "C")),
235 ungated!(export_name, Whitelisted, template!(NameValueStr: "name")),
236 ungated!(link_section, Whitelisted, template!(NameValueStr: "name")),
237 ungated!(no_mangle, Whitelisted, template!(Word)),
238 ungated!(used, Whitelisted, template!(Word)),
241 ungated!(recursion_limit, CrateLevel, template!(NameValueStr: "N")),
242 ungated!(type_length_limit, CrateLevel, template!(NameValueStr: "N")),
245 ungated!(main, Normal, template!(Word)),
246 ungated!(start, Normal, template!(Word)),
247 ungated!(no_start, CrateLevel, template!(Word)),
248 ungated!(no_main, CrateLevel, template!(Word)),
250 // Modules, prelude, and resolution:
251 ungated!(path, Normal, template!(NameValueStr: "file")),
252 ungated!(no_std, CrateLevel, template!(Word)),
253 ungated!(no_implicit_prelude, Normal, template!(Word)),
254 ungated!(non_exhaustive, Whitelisted, template!(Word)),
257 ungated!(windows_subsystem, Whitelisted, template!(NameValueStr: "windows|console")),
258 ungated!(panic_handler, Normal, template!(Word)), // RFC 2070
261 ungated!(inline, Whitelisted, template!(Word, List: "always|never")),
262 ungated!(cold, Whitelisted, template!(Word)),
263 ungated!(no_builtins, Whitelisted, template!(Word)),
264 ungated!(target_feature, Whitelisted, template!(List: r#"enable = "name""#)),
266 // FIXME: #14408 whitelist docs since rustdoc looks at them
267 ungated!(doc, Whitelisted, template!(List: "hidden|inline|...", NameValueStr: "string")),
269 // ==========================================================================
270 // Unstable attributes:
271 // ==========================================================================
274 gated!(naked, Whitelisted, template!(Word), naked_functions, experimental!(naked)),
276 link_args, Normal, template!(NameValueStr: "args"),
277 "the `link_args` attribute is experimental and not portable across platforms, \
278 it is recommended to use `#[link(name = \"foo\")] instead",
281 link_ordinal, Whitelisted, template!(List: "ordinal"), raw_dylib,
282 experimental!(link_ordinal)
287 sym::plugin_registrar, Normal, template!(Word),
289 Stability::Deprecated(
290 "https://github.com/rust-lang/rust/pull/64675",
291 Some("may be removed in a future compiler version"),
293 sym::plugin_registrar,
294 "compiler plugins are deprecated",
295 cfg_fn!(plugin_registrar)
299 sym::plugin, CrateLevel, template!(List: "name|name(args)"),
301 Stability::Deprecated(
302 "https://github.com/rust-lang/rust/pull/64675",
303 Some("may be removed in a future compiler version"),
306 "compiler plugins are deprecated",
312 gated!(allow_fail, Normal, template!(Word), experimental!(allow_fail)),
314 test_runner, CrateLevel, template!(List: "path"), custom_test_frameworks,
315 "custom test frameworks are an unstable feature",
318 gated!(marker, Normal, template!(Word), marker_trait_attr, experimental!(marker)),
320 thread_local, Whitelisted, template!(Word),
321 "`#[thread_local]` is an experimental feature, and does not currently handle destructors",
323 gated!(no_core, CrateLevel, template!(Word), experimental!(no_core)),
326 optimize, Whitelisted, template!(List: "size|speed"), optimize_attribute,
327 experimental!(optimize),
330 gated!(ffi_returns_twice, Whitelisted, template!(Word), experimental!(ffi_returns_twice)),
331 gated!(track_caller, Whitelisted, template!(Word), experimental!(track_caller)),
333 register_attr, CrateLevel, template!(List: "attr1, attr2, ..."),
334 experimental!(register_attr),
337 register_tool, CrateLevel, template!(List: "tool1, tool2, ..."),
338 experimental!(register_tool),
341 // ==========================================================================
342 // Internal attributes: Stability, deprecation, and unsafe:
343 // ==========================================================================
345 ungated!(feature, CrateLevel, template!(List: "name1, name1, ...")),
346 // FIXME(#14407) -- only looked at on-demand so we can't
347 // guarantee they'll have already been checked.
349 rustc_deprecated, Whitelisted,
350 template!(List: r#"since = "version", reason = "...""#)
353 ungated!(stable, Whitelisted, template!(List: r#"feature = "name", since = "version""#)),
356 unstable, Whitelisted,
357 template!(List: r#"feature = "name", reason = "...", issue = "N""#),
360 rustc_const_unstable, Normal, template!(List: r#"feature = "name""#),
361 "the `#[rustc_const_unstable]` attribute is an internal feature",
364 allow_internal_unstable, Normal, template!(Word, List: "feat1, feat2, ..."),
365 EXPLAIN_ALLOW_INTERNAL_UNSTABLE,
367 gated!(allow_internal_unsafe, Normal, template!(Word), EXPLAIN_ALLOW_INTERNAL_UNSAFE),
369 // ==========================================================================
370 // Internal attributes: Type system related:
371 // ==========================================================================
373 gated!(fundamental, Whitelisted, template!(Word), experimental!(fundamental)),
376 structural_match, Whitelisted, template!(Word),
377 "the semantics of constant patterns is not yet settled",
380 may_dangle, Normal, template!(Word), dropck_eyepatch,
381 "`may_dangle` has unstable semantics and may be removed in the future",
384 // ==========================================================================
385 // Internal attributes: Runtime related:
386 // ==========================================================================
388 rustc_attr!(rustc_allocator, Whitelisted, template!(Word), IMPL_DETAIL),
389 rustc_attr!(rustc_allocator_nounwind, Whitelisted, template!(Word), IMPL_DETAIL),
390 gated!(alloc_error_handler, Normal, template!(Word), experimental!(alloc_error_handler)),
392 default_lib_allocator, Whitelisted, template!(Word), allocator_internals,
393 experimental!(default_lib_allocator),
396 needs_allocator, Normal, template!(Word), allocator_internals,
397 experimental!(needs_allocator),
399 gated!(panic_runtime, Whitelisted, template!(Word), experimental!(panic_runtime)),
400 gated!(needs_panic_runtime, Whitelisted, template!(Word), experimental!(needs_panic_runtime)),
402 unwind, Whitelisted, template!(List: "allowed|aborts"), unwind_attributes,
403 experimental!(unwind),
406 compiler_builtins, Whitelisted, template!(Word),
407 "the `#[compiler_builtins]` attribute is used to identify the `compiler_builtins` crate \
408 which contains compiler-rt intrinsics and will never be stable",
411 sanitizer_runtime, Whitelisted, template!(Word),
412 "the `#[sanitizer_runtime]` attribute is used to identify crates that contain the runtime \
413 of a sanitizer and will never be stable",
416 profiler_runtime, Whitelisted, template!(Word),
417 "the `#[profiler_runtime]` attribute is used to identify the `profiler_builtins` crate \
418 which contains the profiler runtime and will never be stable",
421 // ==========================================================================
422 // Internal attributes, Linkage:
423 // ==========================================================================
426 linkage, Whitelisted, template!(NameValueStr: "external|internal|..."),
427 "the `linkage` attribute is experimental and not portable across platforms",
429 rustc_attr!(rustc_std_internal_symbol, Whitelisted, template!(Word), INTERNAL_UNSTABLE),
431 // ==========================================================================
432 // Internal attributes, Macro related:
433 // ==========================================================================
435 rustc_attr!(rustc_builtin_macro, Whitelisted, template!(Word), IMPL_DETAIL),
436 rustc_attr!(rustc_proc_macro_decls, Normal, template!(Word), INTERNAL_UNSTABLE),
438 rustc_macro_transparency, Whitelisted,
439 template!(NameValueStr: "transparent|semitransparent|opaque"),
440 "used internally for testing macro hygiene",
443 // ==========================================================================
444 // Internal attributes, Diagnostics related:
445 // ==========================================================================
448 rustc_on_unimplemented, Whitelisted,
450 List: r#"/*opt*/ message = "...", /*opt*/ label = "...", /*opt*/ note = "...""#,
451 NameValueStr: "message"
455 // Whitelists "identity-like" conversion methods to suggest on type mismatch.
456 rustc_attr!(rustc_conversion_suggestion, Whitelisted, template!(Word), INTERNAL_UNSTABLE),
458 // ==========================================================================
459 // Internal attributes, Const related:
460 // ==========================================================================
462 rustc_attr!(rustc_promotable, Whitelisted, template!(Word), IMPL_DETAIL),
463 rustc_attr!(rustc_allow_const_fn_ptr, Whitelisted, template!(Word), IMPL_DETAIL),
464 rustc_attr!(rustc_args_required_const, Whitelisted, template!(List: "N"), INTERNAL_UNSTABLE),
466 // ==========================================================================
467 // Internal attributes, Layout related:
468 // ==========================================================================
471 rustc_layout_scalar_valid_range_start, Whitelisted, template!(List: "value"),
472 "the `#[rustc_layout_scalar_valid_range_start]` attribute is just used to enable \
473 niche optimizations in libcore and will never be stable",
476 rustc_layout_scalar_valid_range_end, Whitelisted, template!(List: "value"),
477 "the `#[rustc_layout_scalar_valid_range_end]` attribute is just used to enable \
478 niche optimizations in libcore and will never be stable",
481 rustc_nonnull_optimization_guaranteed, Whitelisted, template!(Word),
482 "the `#[rustc_nonnull_optimization_guaranteed]` attribute is just used to enable \
483 niche optimizations in libcore and will never be stable",
486 // ==========================================================================
487 // Internal attributes, Misc:
488 // ==========================================================================
490 lang, Normal, template!(NameValueStr: "name"), lang_items,
491 "language items are subject to change",
494 sym::rustc_diagnostic_item,
496 template!(NameValueStr: "name"),
500 "diagnostic items compiler internal support for linting",
501 cfg_fn!(rustc_attrs),
505 sym::no_debug, Whitelisted, template!(Word),
507 Stability::Deprecated("https://github.com/rust-lang/rust/issues/29721", None),
509 "the `#[no_debug]` attribute was an experimental feature that has been \
510 deprecated due to lack of demand",
516 prelude_import, Whitelisted, template!(Word),
517 "`#[prelude_import]` is for use by rustc only",
520 rustc_paren_sugar, Normal, template!(Word), unboxed_closures,
521 "unboxed_closures are still evolving",
524 rustc_inherit_overflow_checks, Whitelisted, template!(Word),
525 "the `#[rustc_inherit_overflow_checks]` attribute is just used to control \
526 overflow checking behavior of several libcore functions that are inlined \
527 across crates and will never be stable",
529 rustc_attr!(rustc_reservation_impl, Normal, template!(NameValueStr: "reservation message"),
530 "the `#[rustc_reservation_impl]` attribute is internally used \
531 for reserving for `for<T> From<!> for T` impl"
534 rustc_test_marker, Normal, template!(Word),
535 "the `#[rustc_test_marker]` attribute is used internally to track tests",
538 // ==========================================================================
539 // Internal attributes, Testing:
540 // ==========================================================================
542 rustc_attr!(TEST, rustc_outlives, Normal, template!(Word)),
543 rustc_attr!(TEST, rustc_variance, Normal, template!(Word)),
544 rustc_attr!(TEST, rustc_layout, Normal, template!(List: "field1, field2, ...")),
545 rustc_attr!(TEST, rustc_regions, Normal, template!(Word)),
547 TEST, rustc_error, Whitelisted,
548 template!(Word, List: "delay_span_bug_from_inside_query")
550 rustc_attr!(TEST, rustc_dump_user_substs, Whitelisted, template!(Word)),
551 rustc_attr!(TEST, rustc_if_this_changed, Whitelisted, template!(Word, List: "DepNode")),
552 rustc_attr!(TEST, rustc_then_this_would_need, Whitelisted, template!(List: "DepNode")),
554 TEST, rustc_dirty, Whitelisted,
555 template!(List: r#"cfg = "...", /*opt*/ label = "...", /*opt*/ except = "...""#),
558 TEST, rustc_clean, Whitelisted,
559 template!(List: r#"cfg = "...", /*opt*/ label = "...", /*opt*/ except = "...""#),
562 TEST, rustc_partition_reused, Whitelisted,
563 template!(List: r#"cfg = "...", module = "...""#),
566 TEST, rustc_partition_codegened, Whitelisted,
567 template!(List: r#"cfg = "...", module = "...""#),
570 TEST, rustc_expected_cgu_reuse, Whitelisted,
571 template!(List: r#"cfg = "...", module = "...", kind = "...""#),
573 rustc_attr!(TEST, rustc_synthetic, Whitelisted, template!(Word)),
574 rustc_attr!(TEST, rustc_symbol_name, Whitelisted, template!(Word)),
575 rustc_attr!(TEST, rustc_def_path, Whitelisted, template!(Word)),
576 rustc_attr!(TEST, rustc_mir, Whitelisted, template!(List: "arg1, arg2, ...")),
577 rustc_attr!(TEST, rustc_dump_program_clauses, Whitelisted, template!(Word)),
578 rustc_attr!(TEST, rustc_dump_env_program_clauses, Whitelisted, template!(Word)),
579 rustc_attr!(TEST, rustc_object_lifetime_default, Whitelisted, template!(Word)),
580 rustc_attr!(TEST, rustc_dummy, Normal, template!(Word /* doesn't matter*/)),
582 omit_gdb_pretty_printer_section, Whitelisted, template!(Word),
583 "the `#[omit_gdb_pretty_printer_section]` attribute is just used for the Rust test suite",
587 pub fn deprecated_attributes() -> Vec<&'static BuiltinAttribute> {
588 BUILTIN_ATTRIBUTES.iter().filter(|(.., gate)| gate.is_deprecated()).collect()
591 pub fn is_builtin_attr_name(name: ast::Name) -> bool {
592 BUILTIN_ATTRIBUTE_MAP.get(&name).is_some()
595 pub fn is_builtin_attr(attr: &ast::Attribute) -> bool {
596 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)).is_some()
600 pub static ref BUILTIN_ATTRIBUTE_MAP: FxHashMap<Symbol, &'static BuiltinAttribute> = {
601 let mut map = FxHashMap::default();
602 for attr in BUILTIN_ATTRIBUTES.iter() {
603 if map.insert(attr.0, attr).is_some() {
604 panic!("duplicate builtin attribute `{}`", attr.0);