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::symbol::{Symbol, sym};
13 use crate::parse::ParseSess;
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::rustdoc, sym::doc_cfg, cfg_fn!(doc_cfg)),
33 (sym::doctest, sym::cfg_doctest, cfg_fn!(cfg_doctest)),
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 INTERAL_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, packed, ...")),
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)),
256 ungated!(windows_subsystem, Whitelisted, template!(NameValueStr: "windows|console")),
257 ungated!(panic_handler, Normal, template!(Word)), // RFC 2070
260 ungated!(inline, Whitelisted, template!(Word, List: "always|never")),
261 ungated!(cold, Whitelisted, template!(Word)),
262 ungated!(no_builtins, Whitelisted, template!(Word)),
263 ungated!(target_feature, Whitelisted, template!(List: r#"enable = "name""#)),
265 // FIXME: #14408 whitelist docs since rustdoc looks at them
266 ungated!(doc, Whitelisted, template!(List: "hidden|inline|...", NameValueStr: "string")),
268 // ==========================================================================
269 // Unstable attributes:
270 // ==========================================================================
273 gated!(naked, Whitelisted, template!(Word), naked_functions, experimental!(naked)),
275 link_args, Normal, template!(NameValueStr: "args"),
276 "the `link_args` attribute is experimental and not portable across platforms, \
277 it is recommended to use `#[link(name = \"foo\")] instead",
281 ungated!(plugin_registrar, Normal, template!(Word)),
283 plugin, CrateLevel, template!(List: "name|name(args)"),
284 "compiler plugins are experimental and possibly buggy",
288 gated!(allow_fail, Normal, template!(Word), experimental!(allow_fail)),
290 test_runner, CrateLevel, template!(List: "path"), custom_test_frameworks,
291 "custom test frameworks are an unstable feature",
295 gated!(non_exhaustive, Whitelisted, template!(Word), experimental!(non_exhaustive)),
297 gated!(marker, Normal, template!(Word), marker_trait_attr, experimental!(marker)),
299 thread_local, Whitelisted, template!(Word),
300 "`#[thread_local]` is an experimental feature, and does not currently handle destructors",
302 gated!(no_core, CrateLevel, template!(Word), experimental!(no_core)),
305 optimize, Whitelisted, template!(List: "size|speed"), optimize_attribute,
306 experimental!(optimize),
309 gated!(ffi_returns_twice, Whitelisted, template!(Word), experimental!(ffi_returns_twice)),
311 // ==========================================================================
312 // Internal attributes: Stability, deprecation, and unsafe:
313 // ==========================================================================
315 ungated!(feature, CrateLevel, template!(List: "name1, name1, ...")),
316 // FIXME(#14407) -- only looked at on-demand so we can't
317 // guarantee they'll have already been checked.
319 rustc_deprecated, Whitelisted,
320 template!(List: r#"since = "version", reason = "...""#)
323 ungated!(stable, Whitelisted, template!(List: r#"feature = "name", since = "version""#)),
326 unstable, Whitelisted,
327 template!(List: r#"feature = "name", reason = "...", issue = "N""#),
330 rustc_const_unstable, Normal, template!(List: r#"feature = "name""#),
331 "the `#[rustc_const_unstable]` attribute is an internal feature",
334 allow_internal_unstable, Normal, template!(Word, List: "feat1, feat2, ..."),
335 EXPLAIN_ALLOW_INTERNAL_UNSTABLE,
337 gated!(allow_internal_unsafe, Normal, template!(Word), EXPLAIN_ALLOW_INTERNAL_UNSAFE),
339 // ==========================================================================
340 // Internal attributes: Type system related:
341 // ==========================================================================
343 gated!(fundamental, Whitelisted, template!(Word), experimental!(fundamental)),
346 structural_match, Whitelisted, template!(Word),
347 "the semantics of constant patterns is not yet settled",
350 may_dangle, Normal, template!(Word), dropck_eyepatch,
351 "`may_dangle` has unstable semantics and may be removed in the future",
354 // ==========================================================================
355 // Internal attributes: Runtime related:
356 // ==========================================================================
358 rustc_attr!(rustc_allocator, Whitelisted, template!(Word), IMPL_DETAIL),
359 rustc_attr!(rustc_allocator_nounwind, Whitelisted, template!(Word), IMPL_DETAIL),
360 gated!(alloc_error_handler, Normal, template!(Word), experimental!(alloc_error_handler)),
362 default_lib_allocator, Whitelisted, template!(Word), allocator_internals,
363 experimental!(default_lib_allocator),
366 needs_allocator, Normal, template!(Word), allocator_internals,
367 experimental!(needs_allocator),
369 gated!(panic_runtime, Whitelisted, template!(Word), experimental!(panic_runtime)),
370 gated!(needs_panic_runtime, Whitelisted, template!(Word), experimental!(needs_panic_runtime)),
372 unwind, Whitelisted, template!(List: "allowed|aborts"), unwind_attributes,
373 experimental!(unwind),
376 compiler_builtins, Whitelisted, template!(Word),
377 "the `#[compiler_builtins]` attribute is used to identify the `compiler_builtins` crate \
378 which contains compiler-rt intrinsics and will never be stable",
381 sanitizer_runtime, Whitelisted, template!(Word),
382 "the `#[sanitizer_runtime]` attribute is used to identify crates that contain the runtime \
383 of a sanitizer and will never be stable",
386 profiler_runtime, Whitelisted, template!(Word),
387 "the `#[profiler_runtime]` attribute is used to identify the `profiler_builtins` crate \
388 which contains the profiler runtime and will never be stable",
391 // ==========================================================================
392 // Internal attributes, Linkage:
393 // ==========================================================================
396 linkage, Whitelisted, template!(NameValueStr: "external|internal|..."),
397 "the `linkage` attribute is experimental and not portable across platforms",
399 rustc_attr!(rustc_std_internal_symbol, Whitelisted, template!(Word), INTERAL_UNSTABLE),
401 // ==========================================================================
402 // Internal attributes, Macro related:
403 // ==========================================================================
405 rustc_attr!(rustc_builtin_macro, Whitelisted, template!(Word), IMPL_DETAIL),
406 rustc_attr!(rustc_proc_macro_decls, Normal, template!(Word), INTERAL_UNSTABLE),
408 rustc_macro_transparency, Whitelisted,
409 template!(NameValueStr: "transparent|semitransparent|opaque"),
410 "used internally for testing macro hygiene",
413 // ==========================================================================
414 // Internal attributes, Diagnostics related:
415 // ==========================================================================
418 rustc_on_unimplemented, Whitelisted,
420 List: r#"/*opt*/ message = "...", /*opt*/ label = "...", /*opt*/ note = "...""#,
421 NameValueStr: "message"
424 experimental!(rustc_on_unimplemented),
426 // Whitelists "identity-like" conversion methods to suggest on type mismatch.
427 rustc_attr!(rustc_conversion_suggestion, Whitelisted, template!(Word), INTERAL_UNSTABLE),
429 // ==========================================================================
430 // Internal attributes, Const related:
431 // ==========================================================================
433 rustc_attr!(rustc_promotable, Whitelisted, template!(Word), IMPL_DETAIL),
434 rustc_attr!(rustc_allow_const_fn_ptr, Whitelisted, template!(Word), IMPL_DETAIL),
435 rustc_attr!(rustc_args_required_const, Whitelisted, template!(List: "N"), INTERAL_UNSTABLE),
437 // ==========================================================================
438 // Internal attributes, Layout related:
439 // ==========================================================================
442 rustc_layout_scalar_valid_range_start, Whitelisted, template!(List: "value"),
443 "the `#[rustc_layout_scalar_valid_range_start]` attribute is just used to enable \
444 niche optimizations in libcore and will never be stable",
447 rustc_layout_scalar_valid_range_end, Whitelisted, template!(List: "value"),
448 "the `#[rustc_layout_scalar_valid_range_end]` attribute is just used to enable \
449 niche optimizations in libcore and will never be stable",
452 rustc_nonnull_optimization_guaranteed, Whitelisted, template!(Word),
453 "the `#[rustc_nonnull_optimization_guaranteed]` attribute is just used to enable \
454 niche optimizations in libcore and will never be stable",
457 // ==========================================================================
458 // Internal attributes, Misc:
459 // ==========================================================================
461 lang, Normal, template!(NameValueStr: "name"), lang_items,
462 "language items are subject to change",
465 sym::rustc_diagnostic_item,
467 template!(NameValueStr: "name"),
471 "diagnostic items compiler internal support for linting",
472 cfg_fn!(rustc_attrs),
476 sym::no_debug, Whitelisted, template!(Word),
478 Stability::Deprecated("https://github.com/rust-lang/rust/issues/29721", None),
480 "the `#[no_debug]` attribute was an experimental feature that has been \
481 deprecated due to lack of demand",
487 prelude_import, Whitelisted, template!(Word),
488 "`#[prelude_import]` is for use by rustc only",
491 rustc_paren_sugar, Normal, template!(Word), unboxed_closures,
492 "unboxed_closures are still evolving",
495 rustc_inherit_overflow_checks, Whitelisted, template!(Word),
496 "the `#[rustc_inherit_overflow_checks]` attribute is just used to control \
497 overflow checking behavior of several libcore functions that are inlined \
498 across crates and will never be stable",
500 rustc_attr!(rustc_reservation_impl, Normal, template!(NameValueStr: "reservation message"),
501 "the `#[rustc_reservation_impl]` attribute is internally used \
502 for reserving for `for<T> From<!> for T` impl"
505 rustc_test_marker, Normal, template!(Word),
506 "the `#[rustc_test_marker]` attribute is used internally to track tests",
509 // ==========================================================================
510 // Internal attributes, Testing:
511 // ==========================================================================
513 rustc_attr!(TEST, rustc_outlives, Normal, template!(Word)),
514 rustc_attr!(TEST, rustc_variance, Normal, template!(Word)),
515 rustc_attr!(TEST, rustc_layout, Normal, template!(List: "field1, field2, ...")),
516 rustc_attr!(TEST, rustc_regions, Normal, template!(Word)),
517 rustc_attr!(TEST, rustc_error, Whitelisted, template!(Word)),
518 rustc_attr!(TEST, rustc_dump_user_substs, Whitelisted, template!(Word)),
519 rustc_attr!(TEST, rustc_if_this_changed, Whitelisted, template!(Word, List: "DepNode")),
520 rustc_attr!(TEST, rustc_then_this_would_need, Whitelisted, template!(List: "DepNode")),
522 TEST, rustc_dirty, Whitelisted,
523 template!(List: r#"cfg = "...", /*opt*/ label = "...", /*opt*/ except = "...""#),
526 TEST, rustc_clean, Whitelisted,
527 template!(List: r#"cfg = "...", /*opt*/ label = "...", /*opt*/ except = "...""#),
530 TEST, rustc_partition_reused, Whitelisted,
531 template!(List: r#"cfg = "...", module = "...""#),
534 TEST, rustc_partition_codegened, Whitelisted,
535 template!(List: r#"cfg = "...", module = "...""#),
538 TEST, rustc_expected_cgu_reuse, Whitelisted,
539 template!(List: r#"cfg = "...", module = "...", kind = "...""#),
541 rustc_attr!(TEST, rustc_synthetic, Whitelisted, template!(Word)),
542 rustc_attr!(TEST, rustc_symbol_name, Whitelisted, template!(Word)),
543 rustc_attr!(TEST, rustc_def_path, Whitelisted, template!(Word)),
544 rustc_attr!(TEST, rustc_mir, Whitelisted, template!(List: "arg1, arg2, ...")),
545 rustc_attr!(TEST, rustc_dump_program_clauses, Whitelisted, template!(Word)),
546 rustc_attr!(TEST, rustc_dump_env_program_clauses, Whitelisted, template!(Word)),
547 rustc_attr!(TEST, rustc_object_lifetime_default, Whitelisted, template!(Word)),
548 rustc_attr!(TEST, rustc_dummy, Normal, template!(Word /* doesn't matter*/)),
550 omit_gdb_pretty_printer_section, Whitelisted, template!(Word),
551 "the `#[omit_gdb_pretty_printer_section]` attribute is just used for the Rust test suite",
555 pub fn deprecated_attributes() -> Vec<&'static BuiltinAttribute> {
556 BUILTIN_ATTRIBUTES.iter().filter(|(.., gate)| gate.is_deprecated()).collect()
559 pub fn is_builtin_attr_name(name: ast::Name) -> bool {
560 BUILTIN_ATTRIBUTE_MAP.get(&name).is_some()
563 pub fn is_builtin_attr(attr: &ast::Attribute) -> bool {
564 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)).is_some()
568 pub static ref BUILTIN_ATTRIBUTE_MAP: FxHashMap<Symbol, &'static BuiltinAttribute> = {
569 let mut map = FxHashMap::default();
570 for attr in BUILTIN_ATTRIBUTES.iter() {
571 if map.insert(attr.0, attr).is_some() {
572 panic!("duplicate builtin attribute `{}`", attr.0);