3 //! This module implements the gating necessary for preventing certain compiler
4 //! features from being used by default. This module will crawl a pre-expanded
5 //! AST to ensure that there are no features which are used that are not
8 //! Features are enabled in programs via the crate-level attributes of
9 //! `#![feature(...)]` with a comma-separated list of features.
11 //! For the purpose of future feature-tracking, once code for detection of feature
12 //! gate usage is added, *do not remove it again* even once the feature
19 self, AssocTyConstraint, AssocTyConstraintKind, NodeId, GenericParam, GenericParamKind,
22 use crate::attr::{self, check_builtin_attribute, AttributeTemplate};
23 use crate::source_map::Spanned;
24 use crate::edition::{ALL_EDITIONS, Edition};
25 use crate::visit::{self, FnKind, Visitor};
26 use crate::parse::{token, ParseSess};
27 use crate::parse::parser::Parser;
28 use crate::symbol::{Symbol, sym};
29 use crate::tokenstream::TokenTree;
31 use errors::{Applicability, DiagnosticBuilder, Handler};
32 use rustc_data_structures::fx::FxHashMap;
33 use rustc_data_structures::sync::Lock;
34 use rustc_target::spec::abi::Abi;
35 use syntax_pos::{Span, DUMMY_SP, MultiSpan};
37 use lazy_static::lazy_static;
43 fn f(features: &mut Features, _: Span) {
44 features.$field = true;
46 f as fn(&mut Features, Span)
50 macro_rules! declare_features {
51 ($((active, $feature: ident, $ver: expr, $issue: expr, $edition: expr),)+) => {
52 /// Represents active features that are currently being implemented or
53 /// currently being considered for addition/removal.
54 const ACTIVE_FEATURES:
55 &[(Symbol, &str, Option<u32>, Option<Edition>, fn(&mut Features, Span))] =
56 &[$((sym::$feature, $ver, $issue, $edition, set!($feature))),+];
58 /// A set of features to be used by later passes.
61 /// `#![feature]` attrs for language features, for error reporting
62 pub declared_lang_features: Vec<(Symbol, Span, Option<Symbol>)>,
63 /// `#![feature]` attrs for non-language (library) features
64 pub declared_lib_features: Vec<(Symbol, Span)>,
65 $(pub $feature: bool),+
69 pub fn new() -> Features {
71 declared_lang_features: Vec::new(),
72 declared_lib_features: Vec::new(),
77 pub fn walk_feature_fields<F>(&self, mut f: F)
78 where F: FnMut(&str, bool)
80 $(f(stringify!($feature), self.$feature);)+
85 ($((removed, $feature: ident, $ver: expr, $issue: expr, None, $reason: expr),)+) => {
86 /// Represents unstable features which have since been removed (it was once Active)
87 const REMOVED_FEATURES: &[(Symbol, &str, Option<u32>, Option<&str>)] = &[
88 $((sym::$feature, $ver, $issue, $reason)),+
92 ($((stable_removed, $feature: ident, $ver: expr, $issue: expr, None),)+) => {
93 /// Represents stable features which have since been removed (it was once Accepted)
94 const STABLE_REMOVED_FEATURES: &[(Symbol, &str, Option<u32>, Option<&str>)] = &[
95 $((sym::$feature, $ver, $issue, None)),+
99 ($((accepted, $feature: ident, $ver: expr, $issue: expr, None),)+) => {
100 /// Those language feature has since been Accepted (it was once Active)
101 const ACCEPTED_FEATURES: &[(Symbol, &str, Option<u32>, Option<&str>)] = &[
102 $((sym::$feature, $ver, $issue, None)),+
107 // If you change this, please modify `src/doc/unstable-book` as well.
109 // Don't ever remove anything from this list; set them to 'Removed'.
111 // The version numbers here correspond to the version in which the current status
112 // was set. This is most important for knowing when a particular feature became
115 // Note that the features are grouped into internal/user-facing and then
116 // sorted by version inside those groups. This is inforced with tidy.
118 // N.B., `tools/tidy/src/features.rs` parses this information directly out of the
119 // source, so take care when modifying it.
122 // -------------------------------------------------------------------------
123 // feature-group-start: internal feature gates
124 // -------------------------------------------------------------------------
126 // no-tracking-issue-start
128 // Allows using compiler's own crates.
129 (active, rustc_private, "1.0.0", Some(27812), None),
131 // Allows using the `rust-intrinsic`'s "ABI".
132 (active, intrinsics, "1.0.0", None, None),
134 // Allows using `#[lang = ".."]` attribute for linking items to special compiler logic.
135 (active, lang_items, "1.0.0", None, None),
137 // Allows using the `#[stable]` and `#[unstable]` attributes.
138 (active, staged_api, "1.0.0", None, None),
140 // Allows using `#[allow_internal_unstable]`. This is an
141 // attribute on `macro_rules!` and can't use the attribute handling
142 // below (it has to be checked before expansion possibly makes
143 // macros disappear).
144 (active, allow_internal_unstable, "1.0.0", None, None),
146 // Allows using `#[allow_internal_unsafe]`. This is an
147 // attribute on `macro_rules!` and can't use the attribute handling
148 // below (it has to be checked before expansion possibly makes
149 // macros disappear).
150 (active, allow_internal_unsafe, "1.0.0", None, None),
152 // Allows using the macros:
153 // + `__diagnostic_used`
154 // + `__register_diagnostic`
155 // +`__build_diagnostic_array`
156 (active, rustc_diagnostic_macros, "1.0.0", None, None),
158 // Allows using `#[rustc_const_unstable(feature = "foo", ..)]` which
159 // lets a function to be `const` when opted into with `#![feature(foo)]`.
160 (active, rustc_const_unstable, "1.0.0", None, None),
162 // no-tracking-issue-end
164 // Allows using `#[link_name="llvm.*"]`.
165 (active, link_llvm_intrinsics, "1.0.0", Some(29602), None),
167 // Allows using `rustc_*` attributes (RFC 572).
168 (active, rustc_attrs, "1.0.0", Some(29642), None),
170 // Allows using `#[on_unimplemented(..)]` on traits.
171 (active, on_unimplemented, "1.0.0", Some(29628), None),
173 // Allows using the `box $expr` syntax.
174 (active, box_syntax, "1.0.0", Some(49733), None),
176 // Allows using `#[main]` to replace the entrypoint `#[lang = "start"]` calls.
177 (active, main, "1.0.0", Some(29634), None),
179 // Allows using `#[start]` on a function indicating that it is the program entrypoint.
180 (active, start, "1.0.0", Some(29633), None),
182 // Allows using the `#[fundamental]` attribute.
183 (active, fundamental, "1.0.0", Some(29635), None),
185 // Allows using the `rust-call` ABI.
186 (active, unboxed_closures, "1.0.0", Some(29625), None),
188 // Allows using the `#[linkage = ".."]` attribute.
189 (active, linkage, "1.0.0", Some(29603), None),
191 // Allows features specific to OIBIT (auto traits).
192 (active, optin_builtin_traits, "1.0.0", Some(13231), None),
194 // Allows using `box` in patterns (RFC 469).
195 (active, box_patterns, "1.0.0", Some(29641), None),
197 // no-tracking-issue-start
199 // Allows using `#[prelude_import]` on glob `use` items.
200 (active, prelude_import, "1.2.0", None, None),
202 // no-tracking-issue-end
204 // no-tracking-issue-start
206 // Allows using `#[omit_gdb_pretty_printer_section]`.
207 (active, omit_gdb_pretty_printer_section, "1.5.0", None, None),
209 // Allows using the `vectorcall` ABI.
210 (active, abi_vectorcall, "1.7.0", None, None),
212 // no-tracking-issue-end
214 // Allows using `#[structural_match]` which indicates that a type is structurally matchable.
215 (active, structural_match, "1.8.0", Some(31434), None),
217 // Allows using the `may_dangle` attribute (RFC 1327).
218 (active, dropck_eyepatch, "1.10.0", Some(34761), None),
220 // Allows using the `#![panic_runtime]` attribute.
221 (active, panic_runtime, "1.10.0", Some(32837), None),
223 // Allows declaring with `#![needs_panic_runtime]` that a panic runtime is needed.
224 (active, needs_panic_runtime, "1.10.0", Some(32837), None),
226 // no-tracking-issue-start
228 // Allows identifying the `compiler_builtins` crate.
229 (active, compiler_builtins, "1.13.0", None, None),
231 // Allows using the `unadjusted` ABI; perma-unstable.
232 (active, abi_unadjusted, "1.16.0", None, None),
234 // Allows identifying crates that contain sanitizer runtimes.
235 (active, sanitizer_runtime, "1.17.0", None, None),
237 // Used to identify crates that contain the profiler runtime.
238 (active, profiler_runtime, "1.18.0", None, None),
240 // Allows using the `thiscall` ABI.
241 (active, abi_thiscall, "1.19.0", None, None),
243 // Allows using `#![needs_allocator]`, an implementation detail of `#[global_allocator]`.
244 (active, allocator_internals, "1.20.0", None, None),
246 // Allows using the `format_args_nl` macro.
247 (active, format_args_nl, "1.29.0", Some(0), None),
249 // no-tracking-issue-end
251 // Added for testing E0705; perma-unstable.
252 (active, test_2018_feature, "1.31.0", Some(0), Some(Edition::Edition2018)),
254 // -------------------------------------------------------------------------
255 // feature-group-end: internal feature gates
256 // -------------------------------------------------------------------------
258 // -------------------------------------------------------------------------
259 // feature-group-start: actual feature gates (target features)
260 // -------------------------------------------------------------------------
262 // FIXME: Document these and merge with the list below.
264 // Unstable `#[target_feature]` directives.
265 (active, arm_target_feature, "1.27.0", Some(44839), None),
266 (active, aarch64_target_feature, "1.27.0", Some(44839), None),
267 (active, hexagon_target_feature, "1.27.0", Some(44839), None),
268 (active, powerpc_target_feature, "1.27.0", Some(44839), None),
269 (active, mips_target_feature, "1.27.0", Some(44839), None),
270 (active, avx512_target_feature, "1.27.0", Some(44839), None),
271 (active, mmx_target_feature, "1.27.0", Some(44839), None),
272 (active, sse4a_target_feature, "1.27.0", Some(44839), None),
273 (active, tbm_target_feature, "1.27.0", Some(44839), None),
274 (active, wasm_target_feature, "1.30.0", Some(44839), None),
275 (active, adx_target_feature, "1.32.0", Some(44839), None),
276 (active, cmpxchg16b_target_feature, "1.32.0", Some(44839), None),
277 (active, movbe_target_feature, "1.34.0", Some(44839), None),
278 (active, rtm_target_feature, "1.35.0", Some(44839), None),
279 (active, f16c_target_feature, "1.36.0", Some(44839), None),
281 // -------------------------------------------------------------------------
282 // feature-group-end: actual feature gates (target features)
283 // -------------------------------------------------------------------------
285 // -------------------------------------------------------------------------
286 // feature-group-start: actual feature gates
287 // -------------------------------------------------------------------------
289 // Allows using `asm!` macro with which inline assembly can be embedded.
290 (active, asm, "1.0.0", Some(29722), None),
292 // Allows using the `concat_idents!` macro with which identifiers can be concatenated.
293 (active, concat_idents, "1.0.0", Some(29599), None),
295 // Allows using the `#[link_args]` attribute.
296 (active, link_args, "1.0.0", Some(29596), None),
298 // Allows defining identifiers beyond ASCII.
299 (active, non_ascii_idents, "1.0.0", Some(55467), None),
301 // Allows using `#[plugin_registrar]` on functions.
302 (active, plugin_registrar, "1.0.0", Some(29597), None),
304 // Allows using `#![plugin(myplugin)]`.
305 (active, plugin, "1.0.0", Some(29597), None),
307 // Allows using `#[thread_local]` on `static` items.
308 (active, thread_local, "1.0.0", Some(29594), None),
310 // Allows using the `log_syntax!` macro.
311 (active, log_syntax, "1.0.0", Some(29598), None),
313 // Allows using the `trace_macros!` macro.
314 (active, trace_macros, "1.0.0", Some(29598), None),
316 // Allows the use of SIMD types in functions declared in `extern` blocks.
317 (active, simd_ffi, "1.0.0", Some(27731), None),
319 // Allows using custom attributes (RFC 572).
320 (active, custom_attribute, "1.0.0", Some(29642), None),
322 // Allows using non lexical lifetimes (RFC 2094).
323 (active, nll, "1.0.0", Some(43234), None),
325 // Allows using slice patterns.
326 (active, slice_patterns, "1.0.0", Some(62254), None),
328 // Allows the definition of `const` functions with some advanced features.
329 (active, const_fn, "1.2.0", Some(57563), None),
331 // Allows associated type defaults.
332 (active, associated_type_defaults, "1.2.0", Some(29661), None),
334 // Allows `#![no_core]`.
335 (active, no_core, "1.3.0", Some(29639), None),
337 // Allows default type parameters to influence type inference.
338 (active, default_type_parameter_fallback, "1.3.0", Some(27336), None),
340 // Allows `repr(simd)` and importing the various simd intrinsics.
341 (active, repr_simd, "1.4.0", Some(27731), None),
343 // Allows `extern "platform-intrinsic" { ... }`.
344 (active, platform_intrinsics, "1.4.0", Some(27731), None),
346 // Allows `#[unwind(..)]`.
348 // Permits specifying whether a function should permit unwinding or abort on unwind.
349 (active, unwind_attributes, "1.4.0", Some(58760), None),
351 // Allows `#[no_debug]`.
352 (active, no_debug, "1.5.0", Some(29721), None),
354 // Allows attributes on expressions and non-item statements.
355 (active, stmt_expr_attributes, "1.6.0", Some(15701), None),
357 // Allows the use of type ascription in expressions.
358 (active, type_ascription, "1.6.0", Some(23416), None),
360 // Allows `cfg(target_thread_local)`.
361 (active, cfg_target_thread_local, "1.7.0", Some(29594), None),
363 // Allows specialization of implementations (RFC 1210).
364 (active, specialization, "1.7.0", Some(31844), None),
366 // Allows using `#[naked]` on functions.
367 (active, naked_functions, "1.9.0", Some(32408), None),
369 // Allows `cfg(target_has_atomic = "...")`.
370 (active, cfg_target_has_atomic, "1.9.0", Some(32976), None),
372 // Allows `X..Y` patterns.
373 (active, exclusive_range_pattern, "1.11.0", Some(37854), None),
375 // Allows the `!` type. Does not imply 'exhaustive_patterns' (below) any more.
376 (active, never_type, "1.13.0", Some(35121), None),
378 // Allows exhaustive pattern matching on types that contain uninhabited types.
379 (active, exhaustive_patterns, "1.13.0", Some(51085), None),
381 // Allows untagged unions `union U { ... }`.
382 (active, untagged_unions, "1.13.0", Some(32836), None),
384 // Allows `#[link(..., cfg(..))]`.
385 (active, link_cfg, "1.14.0", Some(37406), None),
387 // Allows `extern "ptx-*" fn()`.
388 (active, abi_ptx, "1.15.0", Some(38788), None),
390 // Allows the `#[repr(i128)]` attribute for enums.
391 (active, repr128, "1.16.0", Some(35118), None),
393 // Allows `#[link(kind="static-nobundle"...)]`.
394 (active, static_nobundle, "1.16.0", Some(37403), None),
396 // Allows `extern "msp430-interrupt" fn()`.
397 (active, abi_msp430_interrupt, "1.16.0", Some(38487), None),
399 // Allows declarative macros 2.0 (`macro`).
400 (active, decl_macro, "1.17.0", Some(39412), None),
402 // Allows `extern "x86-interrupt" fn()`.
403 (active, abi_x86_interrupt, "1.17.0", Some(40180), None),
405 // Allows module-level inline assembly by way of `global_asm!()`.
406 (active, global_asm, "1.18.0", Some(35119), None),
408 // Allows overlapping impls of marker traits.
409 (active, overlapping_marker_traits, "1.18.0", Some(29864), None),
411 // Allows a test to fail without failing the whole suite.
412 (active, allow_fail, "1.19.0", Some(46488), None),
414 // Allows unsized tuple coercion.
415 (active, unsized_tuple_coercion, "1.20.0", Some(42877), None),
417 // Allows defining generators.
418 (active, generators, "1.21.0", Some(43122), None),
420 // Allows `#[doc(cfg(...))]`.
421 (active, doc_cfg, "1.21.0", Some(43781), None),
423 // Allows `#[doc(masked)]`.
424 (active, doc_masked, "1.21.0", Some(44027), None),
426 // Allows `#[doc(spotlight)]`.
427 (active, doc_spotlight, "1.22.0", Some(45040), None),
429 // Allows `#[doc(include = "some-file")]`.
430 (active, external_doc, "1.22.0", Some(44732), None),
432 // Allows future-proofing enums/structs with the `#[non_exhaustive]` attribute (RFC 2008).
433 (active, non_exhaustive, "1.22.0", Some(44109), None),
435 // Allows using `crate` as visibility modifier, synonymous with `pub(crate)`.
436 (active, crate_visibility_modifier, "1.23.0", Some(53120), None),
438 // Allows defining `extern type`s.
439 (active, extern_types, "1.23.0", Some(43467), None),
441 // Allows trait methods with arbitrary self types.
442 (active, arbitrary_self_types, "1.23.0", Some(44874), None),
444 // Allows in-band quantification of lifetime bindings (e.g., `fn foo(x: &'a u8) -> &'a u8`).
445 (active, in_band_lifetimes, "1.23.0", Some(44524), None),
447 // Allows associated types to be generic, e.g., `type Foo<T>;` (RFC 1598).
448 (active, generic_associated_types, "1.23.0", Some(44265), None),
450 // Allows defining `trait X = A + B;` alias items.
451 (active, trait_alias, "1.24.0", Some(41517), None),
453 // Allows infering `'static` outlives requirements (RFC 2093).
454 (active, infer_static_outlives_requirements, "1.26.0", Some(54185), None),
456 // Allows macro invocations in `extern {}` blocks.
457 (active, macros_in_extern, "1.27.0", Some(49476), None),
459 // Allows accessing fields of unions inside `const` functions.
460 (active, const_fn_union, "1.27.0", Some(51909), None),
462 // Allows casting raw pointers to `usize` during const eval.
463 (active, const_raw_ptr_to_usize_cast, "1.27.0", Some(51910), None),
465 // Allows dereferencing raw pointers during const eval.
466 (active, const_raw_ptr_deref, "1.27.0", Some(51911), None),
468 // Allows comparing raw pointers during const eval.
469 (active, const_compare_raw_pointers, "1.27.0", Some(53020), None),
471 // Allows `#[doc(alias = "...")]`.
472 (active, doc_alias, "1.27.0", Some(50146), None),
474 // Allows defining `existential type`s.
475 (active, existential_type, "1.28.0", Some(34511), None),
477 // Allows inconsistent bounds in where clauses.
478 (active, trivial_bounds, "1.28.0", Some(48214), None),
480 // Allows `'a: { break 'a; }`.
481 (active, label_break_value, "1.28.0", Some(48594), None),
483 // Allows using `#[doc(keyword = "...")]`.
484 (active, doc_keyword, "1.28.0", Some(51315), None),
486 // Allows async and await syntax.
487 (active, async_await, "1.28.0", Some(50547), None),
489 // Allows await! macro-like syntax.
490 // This will likely be removed prior to stabilization of async/await.
491 (active, await_macro, "1.28.0", Some(50547), None),
493 // Allows reinterpretation of the bits of a value of one type as another type during const eval.
494 (active, const_transmute, "1.29.0", Some(53605), None),
496 // Allows using `try {...}` expressions.
497 (active, try_blocks, "1.29.0", Some(31436), None),
499 // Allows defining an `#[alloc_error_handler]`.
500 (active, alloc_error_handler, "1.29.0", Some(51540), None),
502 // Allows using the `amdgpu-kernel` ABI.
503 (active, abi_amdgpu_kernel, "1.29.0", Some(51575), None),
505 // Allows panicking during const eval (producing compile-time errors).
506 (active, const_panic, "1.30.0", Some(51999), None),
508 // Allows `#[marker]` on certain traits allowing overlapping implementations.
509 (active, marker_trait_attr, "1.30.0", Some(29864), None),
511 // Allows macro invocations on modules expressions and statements and
512 // procedural macros to expand to non-items.
513 (active, proc_macro_hygiene, "1.30.0", Some(54727), None),
515 // Allows unsized rvalues at arguments and parameters.
516 (active, unsized_locals, "1.30.0", Some(48055), None),
518 // Allows custom test frameworks with `#![test_runner]` and `#[test_case]`.
519 (active, custom_test_frameworks, "1.30.0", Some(50297), None),
521 // Allows non-builtin attributes in inner attribute position.
522 (active, custom_inner_attributes, "1.30.0", Some(54726), None),
524 // Allows mixing bind-by-move in patterns and references to those identifiers in guards.
525 (active, bind_by_move_pattern_guards, "1.30.0", Some(15287), None),
527 // Allows `impl Trait` in bindings (`let`, `const`, `static`).
528 (active, impl_trait_in_bindings, "1.30.0", Some(34511), None),
530 // Allows using `reason` in lint attributes and the `#[expect(lint)]` lint check.
531 (active, lint_reasons, "1.31.0", Some(54503), None),
533 // Allows exhaustive integer pattern matching on `usize` and `isize`.
534 (active, precise_pointer_size_matching, "1.32.0", Some(56354), None),
536 // Allows relaxing the coherence rules such that
537 // `impl<T> ForeignTrait<LocalType> for ForeignType<T> is permitted.
538 (active, re_rebalance_coherence, "1.32.0", Some(55437), None),
540 // Allows using `#[ffi_returns_twice]` on foreign functions.
541 (active, ffi_returns_twice, "1.34.0", Some(58314), None),
543 // Allows const generic types (e.g. `struct Foo<const N: usize>(...);`).
544 (active, const_generics, "1.34.0", Some(44580), None),
546 // Allows using `#[optimize(X)]`.
547 (active, optimize_attribute, "1.34.0", Some(54882), None),
549 // Allows using C-variadics.
550 (active, c_variadic, "1.34.0", Some(44930), None),
552 // Allows the user of associated type bounds.
553 (active, associated_type_bounds, "1.34.0", Some(52662), None),
555 // Attributes on formal function params.
556 (active, param_attrs, "1.36.0", Some(60406), None),
558 // Allows calling constructor functions in `const fn`.
559 (active, const_constructor, "1.37.0", Some(61456), None),
561 // Allows `if/while p && let q = r && ...` chains.
562 (active, let_chains, "1.37.0", Some(53667), None),
564 // Allows #[repr(transparent)] on enums (RFC 2645).
565 (active, transparent_enums, "1.37.0", Some(60405), None),
567 // Allows #[repr(transparent)] on unions (RFC 2645).
568 (active, transparent_unions, "1.37.0", Some(60405), None),
570 // Allows explicit discriminants on non-unit enum variants.
571 (active, arbitrary_enum_discriminant, "1.37.0", Some(60553), None),
573 // Allows `impl Trait` with multiple unrelated lifetimes.
574 (active, member_constraints, "1.37.0", Some(61977), None),
576 // Allows `async || body` closures.
577 (active, async_closure, "1.37.0", Some(62290), None),
579 // Allows the use of `#[cfg(doctest)]`, set when rustdoc is collecting doctests
580 (active, cfg_doctest, "1.37.0", Some(62210), None),
582 // Allows `[x; N]` where `x` is a constant (RFC 2203).
583 (active, const_in_array_repeat_expressions, "1.37.0", Some(49147), None),
585 // -------------------------------------------------------------------------
586 // feature-group-end: actual feature gates
587 // -------------------------------------------------------------------------
590 // Some features are known to be incomplete and using them is likely to have
591 // unanticipated results, such as compiler crashes. We warn the user about these
593 const INCOMPLETE_FEATURES: &[Symbol] = &[
594 sym::impl_trait_in_bindings,
595 sym::generic_associated_types,
601 // -------------------------------------------------------------------------
602 // feature-group-start: removed features
603 // -------------------------------------------------------------------------
605 (removed, import_shadowing, "1.0.0", None, None, None),
606 (removed, managed_boxes, "1.0.0", None, None, None),
607 // Allows use of unary negate on unsigned integers, e.g., -e for e: u8
608 (removed, negate_unsigned, "1.0.0", Some(29645), None, None),
609 (removed, reflect, "1.0.0", Some(27749), None, None),
610 // A way to temporarily opt out of opt in copy. This will *never* be accepted.
611 (removed, opt_out_copy, "1.0.0", None, None, None),
612 (removed, quad_precision_float, "1.0.0", None, None, None),
613 (removed, struct_inherit, "1.0.0", None, None, None),
614 (removed, test_removed_feature, "1.0.0", None, None, None),
615 (removed, visible_private_types, "1.0.0", None, None, None),
616 (removed, unsafe_no_drop_flag, "1.0.0", None, None, None),
617 // Allows using items which are missing stability attributes
618 (removed, unmarked_api, "1.0.0", None, None, None),
619 (removed, allocator, "1.0.0", None, None, None),
620 (removed, simd, "1.0.0", Some(27731), None,
621 Some("removed in favor of `#[repr(simd)]`")),
622 (removed, advanced_slice_patterns, "1.0.0", Some(62254), None,
623 Some("merged into `#![feature(slice_patterns)]`")),
624 (removed, macro_reexport, "1.0.0", Some(29638), None,
625 Some("subsumed by `pub use`")),
626 (removed, pushpop_unsafe, "1.2.0", None, None, None),
627 (removed, needs_allocator, "1.4.0", Some(27389), None,
628 Some("subsumed by `#![feature(allocator_internals)]`")),
629 (removed, proc_macro_mod, "1.27.0", Some(54727), None,
630 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
631 (removed, proc_macro_expr, "1.27.0", Some(54727), None,
632 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
633 (removed, proc_macro_non_items, "1.27.0", Some(54727), None,
634 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
635 (removed, proc_macro_gen, "1.27.0", Some(54727), None,
636 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
637 (removed, panic_implementation, "1.28.0", Some(44489), None,
638 Some("subsumed by `#[panic_handler]`")),
639 // Allows the use of `#[derive(Anything)]` as sugar for `#[derive_Anything]`.
640 (removed, custom_derive, "1.32.0", Some(29644), None,
641 Some("subsumed by `#[proc_macro_derive]`")),
642 // Paths of the form: `extern::foo::bar`
643 (removed, extern_in_paths, "1.33.0", Some(55600), None,
644 Some("subsumed by `::foo::bar` paths")),
645 (removed, quote, "1.33.0", Some(29601), None, None),
646 // Allows using `#[unsafe_destructor_blind_to_params]` (RFC 1238).
647 (removed, dropck_parametricity, "1.38.0", Some(28498), None, None),
649 // -------------------------------------------------------------------------
650 // feature-group-end: removed features
651 // -------------------------------------------------------------------------
655 (stable_removed, no_stack_check, "1.0.0", None, None),
659 // -------------------------------------------------------------------------
660 // feature-group-start: for testing purposes
661 // -------------------------------------------------------------------------
663 // A temporary feature gate used to enable parser extensions needed
664 // to bootstrap fix for #5723.
665 (accepted, issue_5723_bootstrap, "1.0.0", None, None),
666 // These are used to test this portion of the compiler,
667 // they don't actually mean anything.
668 (accepted, test_accepted_feature, "1.0.0", None, None),
670 // -------------------------------------------------------------------------
671 // feature-group-end: for testing purposes
672 // -------------------------------------------------------------------------
674 // -------------------------------------------------------------------------
675 // feature-group-start: accepted features
676 // -------------------------------------------------------------------------
678 // Allows using associated `type`s in `trait`s.
679 (accepted, associated_types, "1.0.0", None, None),
680 // Allows using assigning a default type to type parameters in algebraic data type definitions.
681 (accepted, default_type_params, "1.0.0", None, None),
682 // FIXME: explain `globs`.
683 (accepted, globs, "1.0.0", None, None),
684 // Allows `macro_rules!` items.
685 (accepted, macro_rules, "1.0.0", None, None),
686 // Allows use of `&foo[a..b]` as a slicing syntax.
687 (accepted, slicing_syntax, "1.0.0", None, None),
688 // Allows struct variants `Foo { baz: u8, .. }` in enums (RFC 418).
689 (accepted, struct_variant, "1.0.0", None, None),
690 // Allows indexing tuples.
691 (accepted, tuple_indexing, "1.0.0", None, None),
692 // Allows the use of `if let` expressions.
693 (accepted, if_let, "1.0.0", None, None),
694 // Allows the use of `while let` expressions.
695 (accepted, while_let, "1.0.0", None, None),
696 // Allows using `#![no_std]`.
697 (accepted, no_std, "1.6.0", None, None),
698 // Allows overloading augmented assignment operations like `a += b`.
699 (accepted, augmented_assignments, "1.8.0", Some(28235), None),
700 // Allows empty structs and enum variants with braces.
701 (accepted, braced_empty_structs, "1.8.0", Some(29720), None),
702 // Allows `#[deprecated]` attribute.
703 (accepted, deprecated, "1.9.0", Some(29935), None),
704 // Allows macros to appear in the type position.
705 (accepted, type_macros, "1.13.0", Some(27245), None),
706 // Allows use of the postfix `?` operator in expressions.
707 (accepted, question_mark, "1.13.0", Some(31436), None),
708 // Allows `..` in tuple (struct) patterns.
709 (accepted, dotdot_in_tuple_patterns, "1.14.0", Some(33627), None),
710 // Allows some increased flexibility in the name resolution rules,
711 // especially around globs and shadowing (RFC 1560).
712 (accepted, item_like_imports, "1.15.0", Some(35120), None),
713 // Allows using `Self` and associated types in struct expressions and patterns.
714 (accepted, more_struct_aliases, "1.16.0", Some(37544), None),
715 // Allows elision of `'static` lifetimes in `static`s and `const`s.
716 (accepted, static_in_const, "1.17.0", Some(35897), None),
717 // Allows field shorthands (`x` meaning `x: x`) in struct literal expressions.
718 (accepted, field_init_shorthand, "1.17.0", Some(37340), None),
719 // Allows the definition recursive static items.
720 (accepted, static_recursion, "1.17.0", Some(29719), None),
721 // Allows `pub(restricted)` visibilities (RFC 1422).
722 (accepted, pub_restricted, "1.18.0", Some(32409), None),
723 // Allows `#![windows_subsystem]`.
724 (accepted, windows_subsystem, "1.18.0", Some(37499), None),
725 // Allows `break {expr}` with a value inside `loop`s.
726 (accepted, loop_break_value, "1.19.0", Some(37339), None),
727 // Allows numeric fields in struct expressions and patterns.
728 (accepted, relaxed_adts, "1.19.0", Some(35626), None),
729 // Allows coercing non capturing closures to function pointers.
730 (accepted, closure_to_fn_coercion, "1.19.0", Some(39817), None),
731 // Allows attributes on struct literal fields.
732 (accepted, struct_field_attributes, "1.20.0", Some(38814), None),
733 // Allows the definition of associated constants in `trait` or `impl` blocks.
734 (accepted, associated_consts, "1.20.0", Some(29646), None),
735 // Allows usage of the `compile_error!` macro.
736 (accepted, compile_error, "1.20.0", Some(40872), None),
737 // Allows code like `let x: &'static u32 = &42` to work (RFC 1414).
738 (accepted, rvalue_static_promotion, "1.21.0", Some(38865), None),
739 // Allows `Drop` types in constants (RFC 1440).
740 (accepted, drop_types_in_const, "1.22.0", Some(33156), None),
741 // Allows the sysV64 ABI to be specified on all platforms
742 // instead of just the platforms on which it is the C ABI.
743 (accepted, abi_sysv64, "1.24.0", Some(36167), None),
744 // Allows `repr(align(16))` struct attribute (RFC 1358).
745 (accepted, repr_align, "1.25.0", Some(33626), None),
746 // Allows '|' at beginning of match arms (RFC 1925).
747 (accepted, match_beginning_vert, "1.25.0", Some(44101), None),
748 // Allows nested groups in `use` items (RFC 2128).
749 (accepted, use_nested_groups, "1.25.0", Some(44494), None),
750 // Allows indexing into constant arrays.
751 (accepted, const_indexing, "1.26.0", Some(29947), None),
752 // Allows using `a..=b` and `..=b` as inclusive range syntaxes.
753 (accepted, inclusive_range_syntax, "1.26.0", Some(28237), None),
754 // Allows `..=` in patterns (RFC 1192).
755 (accepted, dotdoteq_in_patterns, "1.26.0", Some(28237), None),
756 // Allows `fn main()` with return types which implements `Termination` (RFC 1937).
757 (accepted, termination_trait, "1.26.0", Some(43301), None),
758 // Allows implementing `Clone` for closures where possible (RFC 2132).
759 (accepted, clone_closures, "1.26.0", Some(44490), None),
760 // Allows implementing `Copy` for closures where possible (RFC 2132).
761 (accepted, copy_closures, "1.26.0", Some(44490), None),
762 // Allows `impl Trait` in function arguments.
763 (accepted, universal_impl_trait, "1.26.0", Some(34511), None),
764 // Allows `impl Trait` in function return types.
765 (accepted, conservative_impl_trait, "1.26.0", Some(34511), None),
766 // Allows using the `u128` and `i128` types.
767 (accepted, i128_type, "1.26.0", Some(35118), None),
768 // Allows default match binding modes (RFC 2005).
769 (accepted, match_default_bindings, "1.26.0", Some(42640), None),
770 // Allows `'_` placeholder lifetimes.
771 (accepted, underscore_lifetimes, "1.26.0", Some(44524), None),
772 // Allows attributes on lifetime/type formal parameters in generics (RFC 1327).
773 (accepted, generic_param_attrs, "1.27.0", Some(48848), None),
774 // Allows `cfg(target_feature = "...")`.
775 (accepted, cfg_target_feature, "1.27.0", Some(29717), None),
776 // Allows `#[target_feature(...)]`.
777 (accepted, target_feature, "1.27.0", None, None),
778 // Allows using `dyn Trait` as a syntax for trait objects.
779 (accepted, dyn_trait, "1.27.0", Some(44662), None),
780 // Allows `#[must_use]` on functions, and introduces must-use operators (RFC 1940).
781 (accepted, fn_must_use, "1.27.0", Some(43302), None),
782 // Allows use of the `:lifetime` macro fragment specifier.
783 (accepted, macro_lifetime_matcher, "1.27.0", Some(34303), None),
784 // Allows `#[test]` functions where the return type implements `Termination` (RFC 1937).
785 (accepted, termination_trait_test, "1.27.0", Some(48854), None),
786 // Allows the `#[global_allocator]` attribute.
787 (accepted, global_allocator, "1.28.0", Some(27389), None),
788 // Allows `#[repr(transparent)]` attribute on newtype structs.
789 (accepted, repr_transparent, "1.28.0", Some(43036), None),
790 // Allows procedural macros in `proc-macro` crates.
791 (accepted, proc_macro, "1.29.0", Some(38356), None),
792 // Allows `foo.rs` as an alternative to `foo/mod.rs`.
793 (accepted, non_modrs_mods, "1.30.0", Some(44660), None),
794 // Allows use of the `:vis` macro fragment specifier
795 (accepted, macro_vis_matcher, "1.30.0", Some(41022), None),
796 // Allows importing and reexporting macros with `use`,
797 // enables macro modularization in general.
798 (accepted, use_extern_macros, "1.30.0", Some(35896), None),
799 // Allows keywords to be escaped for use as identifiers.
800 (accepted, raw_identifiers, "1.30.0", Some(48589), None),
801 // Allows attributes scoped to tools.
802 (accepted, tool_attributes, "1.30.0", Some(44690), None),
803 // Allows multi-segment paths in attributes and derives.
804 (accepted, proc_macro_path_invoc, "1.30.0", Some(38356), None),
805 // Allows all literals in attribute lists and values of key-value pairs.
806 (accepted, attr_literals, "1.30.0", Some(34981), None),
807 // Allows inferring outlives requirements (RFC 2093).
808 (accepted, infer_outlives_requirements, "1.30.0", Some(44493), None),
809 // Allows annotating functions conforming to `fn(&PanicInfo) -> !` with `#[panic_handler]`.
810 // This defines the behavior of panics.
811 (accepted, panic_handler, "1.30.0", Some(44489), None),
812 // Allows `#[used]` to preserve symbols (see llvm.used).
813 (accepted, used, "1.30.0", Some(40289), None),
814 // Allows `crate` in paths.
815 (accepted, crate_in_paths, "1.30.0", Some(45477), None),
816 // Allows resolving absolute paths as paths from other crates.
817 (accepted, extern_absolute_paths, "1.30.0", Some(44660), None),
818 // Allows access to crate names passed via `--extern` through prelude.
819 (accepted, extern_prelude, "1.30.0", Some(44660), None),
820 // Allows parentheses in patterns.
821 (accepted, pattern_parentheses, "1.31.0", Some(51087), None),
822 // Allows the definition of `const fn` functions.
823 (accepted, min_const_fn, "1.31.0", Some(53555), None),
824 // Allows scoped lints.
825 (accepted, tool_lints, "1.31.0", Some(44690), None),
826 // Allows lifetime elision in `impl` headers. For example:
827 // + `impl<I:Iterator> Iterator for &mut Iterator`
828 // + `impl Debug for Foo<'_>`
829 (accepted, impl_header_lifetime_elision, "1.31.0", Some(15872), None),
830 // Allows `extern crate foo as bar;`. This puts `bar` into extern prelude.
831 (accepted, extern_crate_item_prelude, "1.31.0", Some(55599), None),
832 // Allows use of the `:literal` macro fragment specifier (RFC 1576).
833 (accepted, macro_literal_matcher, "1.32.0", Some(35625), None),
834 // Allows use of `?` as the Kleene "at most one" operator in macros.
835 (accepted, macro_at_most_once_rep, "1.32.0", Some(48075), None),
836 // Allows `Self` struct constructor (RFC 2302).
837 (accepted, self_struct_ctor, "1.32.0", Some(51994), None),
838 // Allows `Self` in type definitions (RFC 2300).
839 (accepted, self_in_typedefs, "1.32.0", Some(49303), None),
840 // Allows `use x::y;` to search `x` in the current scope.
841 (accepted, uniform_paths, "1.32.0", Some(53130), None),
842 // Allows integer match exhaustiveness checking (RFC 2591).
843 (accepted, exhaustive_integer_patterns, "1.33.0", Some(50907), None),
844 // Allows `use path as _;` and `extern crate c as _;`.
845 (accepted, underscore_imports, "1.33.0", Some(48216), None),
846 // Allows `#[repr(packed(N))]` attribute on structs.
847 (accepted, repr_packed, "1.33.0", Some(33158), None),
848 // Allows irrefutable patterns in `if let` and `while let` statements (RFC 2086).
849 (accepted, irrefutable_let_patterns, "1.33.0", Some(44495), None),
850 // Allows calling `const unsafe fn` inside `unsafe` blocks in `const fn` functions.
851 (accepted, min_const_unsafe_fn, "1.33.0", Some(55607), None),
852 // Allows let bindings, assignments and destructuring in `const` functions and constants.
853 // As long as control flow is not implemented in const eval, `&&` and `||` may not be used
854 // at the same time as let bindings.
855 (accepted, const_let, "1.33.0", Some(48821), None),
856 // Allows `#[cfg_attr(predicate, multiple, attributes, here)]`.
857 (accepted, cfg_attr_multi, "1.33.0", Some(54881), None),
858 // Allows top level or-patterns (`p | q`) in `if let` and `while let`.
859 (accepted, if_while_or_patterns, "1.33.0", Some(48215), None),
860 // Allows `cfg(target_vendor = "...")`.
861 (accepted, cfg_target_vendor, "1.33.0", Some(29718), None),
862 // Allows `extern crate self as foo;`.
863 // This puts local crate root into extern prelude under name `foo`.
864 (accepted, extern_crate_self, "1.34.0", Some(56409), None),
865 // Allows arbitrary delimited token streams in non-macro attributes.
866 (accepted, unrestricted_attribute_tokens, "1.34.0", Some(55208), None),
867 // Allows paths to enum variants on type aliases including `Self`.
868 (accepted, type_alias_enum_variants, "1.37.0", Some(49683), None),
869 // Allows using `#[repr(align(X))]` on enums with equivalent semantics
870 // to wrapping an enum in a wrapper struct with `#[repr(align(X))]`.
871 (accepted, repr_align_enum, "1.37.0", Some(57996), None),
872 // Allows `const _: TYPE = VALUE`.
873 (accepted, underscore_const_names, "1.37.0", Some(54912), None),
875 // -------------------------------------------------------------------------
876 // feature-group-end: accepted features
877 // -------------------------------------------------------------------------
880 // If you change this, please modify `src/doc/unstable-book` as well. You must
881 // move that documentation into the relevant place in the other docs, and
882 // remove the chapter on the flag.
884 #[derive(Copy, Clone, PartialEq, Debug)]
885 pub enum AttributeType {
886 /// Normal, builtin attribute that is consumed
887 /// by the compiler before the unused_attribute check
890 /// Builtin attribute that may not be consumed by the compiler
891 /// before the unused_attribute check. These attributes
892 /// will be ignored by the unused_attribute lint
895 /// Builtin attribute that is only allowed at the crate level
899 pub enum AttributeGate {
900 /// Is gated by a given feature gate, reason
901 /// and function to check if enabled
902 Gated(Stability, Symbol, &'static str, fn(&Features) -> bool),
904 /// Ungated attribute, can be used on all release channels
908 /// A convenience macro for constructing attribute templates.
909 /// E.g., `template!(Word, List: "description")` means that the attribute
910 /// supports forms `#[attr]` and `#[attr(description)]`.
911 macro_rules! template {
912 (Word) => { template!(@ true, None, None) };
913 (List: $descr: expr) => { template!(@ false, Some($descr), None) };
914 (NameValueStr: $descr: expr) => { template!(@ false, None, Some($descr)) };
915 (Word, List: $descr: expr) => { template!(@ true, Some($descr), None) };
916 (Word, NameValueStr: $descr: expr) => { template!(@ true, None, Some($descr)) };
917 (List: $descr1: expr, NameValueStr: $descr2: expr) => {
918 template!(@ false, Some($descr1), Some($descr2))
920 (Word, List: $descr1: expr, NameValueStr: $descr2: expr) => {
921 template!(@ true, Some($descr1), Some($descr2))
923 (@ $word: expr, $list: expr, $name_value_str: expr) => { AttributeTemplate {
924 word: $word, list: $list, name_value_str: $name_value_str
929 fn is_deprecated(&self) -> bool {
931 Gated(Stability::Deprecated(_, _), ..) => true,
937 #[derive(Copy, Clone, Debug)]
940 // First argument is tracking issue link; second argument is an optional
941 // help message, which defaults to "remove this attribute"
942 Deprecated(&'static str, Option<&'static str>),
946 impl std::fmt::Debug for AttributeGate {
947 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
949 Gated(ref stab, name, expl, _) =>
950 write!(fmt, "Gated({:?}, {}, {})", stab, name, expl),
951 Ungated => write!(fmt, "Ungated")
956 macro_rules! cfg_fn {
957 ($field: ident) => {{
958 fn f(features: &Features) -> bool {
961 f as fn(&Features) -> bool
965 pub fn deprecated_attributes() -> Vec<&'static (Symbol, AttributeType,
966 AttributeTemplate, AttributeGate)> {
967 BUILTIN_ATTRIBUTES.iter().filter(|(.., gate)| gate.is_deprecated()).collect()
970 pub fn is_builtin_attr_name(name: ast::Name) -> bool {
971 BUILTIN_ATTRIBUTE_MAP.get(&name).is_some()
974 pub fn is_builtin_attr(attr: &ast::Attribute) -> bool {
975 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)).is_some()
978 /// Attributes that have a special meaning to rustc or rustdoc
979 pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
985 template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#),
991 template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#),
997 template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#),
1003 template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#),
1007 (sym::macro_use, Normal, template!(Word, List: "name1, name2, ..."), Ungated),
1008 (sym::macro_export, Normal, template!(Word, List: "local_inner_macros"), Ungated),
1009 (sym::plugin_registrar, Normal, template!(Word), Ungated),
1011 (sym::cfg, Normal, template!(List: "predicate"), Ungated),
1012 (sym::cfg_attr, Normal, template!(List: "predicate, attr1, attr2, ..."), Ungated),
1013 (sym::main, Normal, template!(Word), Ungated),
1014 (sym::start, Normal, template!(Word), Ungated),
1015 (sym::repr, Normal, template!(List: "C, packed, ..."), Ungated),
1016 (sym::path, Normal, template!(NameValueStr: "file"), Ungated),
1017 (sym::automatically_derived, Normal, template!(Word), Ungated),
1018 (sym::no_mangle, Whitelisted, template!(Word), Ungated),
1019 (sym::no_link, Normal, template!(Word), Ungated),
1020 (sym::derive, Normal, template!(List: "Trait1, Trait2, ..."), Ungated),
1024 template!(Word, List: r#"expected = "reason"#, NameValueStr: "reason"),
1027 (sym::ignore, Normal, template!(Word, NameValueStr: "reason"), Ungated),
1028 (sym::no_implicit_prelude, Normal, template!(Word), Ungated),
1029 (sym::reexport_test_harness_main, Normal, template!(NameValueStr: "name"), Ungated),
1030 (sym::link_args, Normal, template!(NameValueStr: "args"), Gated(Stability::Unstable,
1032 "the `link_args` attribute is experimental and not \
1033 portable across platforms, it is recommended to \
1034 use `#[link(name = \"foo\")] instead",
1035 cfg_fn!(link_args))),
1036 (sym::macro_escape, Normal, template!(Word), Ungated),
1039 (sym::structural_match, Whitelisted, template!(Word), Gated(Stability::Unstable,
1040 sym::structural_match,
1041 "the semantics of constant patterns is \
1043 cfg_fn!(structural_match))),
1046 (sym::non_exhaustive, Whitelisted, template!(Word), Gated(Stability::Unstable,
1047 sym::non_exhaustive,
1048 "non exhaustive is an experimental feature",
1049 cfg_fn!(non_exhaustive))),
1052 (sym::marker, Normal, template!(Word), Gated(Stability::Unstable,
1053 sym::marker_trait_attr,
1054 "marker traits is an experimental feature",
1055 cfg_fn!(marker_trait_attr))),
1057 (sym::plugin, CrateLevel, template!(List: "name|name(args)"), Gated(Stability::Unstable,
1059 "compiler plugins are experimental \
1060 and possibly buggy",
1063 (sym::no_std, CrateLevel, template!(Word), Ungated),
1064 (sym::no_core, CrateLevel, template!(Word), Gated(Stability::Unstable,
1066 "no_core is experimental",
1068 (sym::lang, Normal, template!(NameValueStr: "name"), Gated(Stability::Unstable,
1070 "language items are subject to change",
1071 cfg_fn!(lang_items))),
1072 (sym::linkage, Whitelisted, template!(NameValueStr: "external|internal|..."),
1073 Gated(Stability::Unstable,
1075 "the `linkage` attribute is experimental \
1076 and not portable across platforms",
1078 (sym::thread_local, Whitelisted, template!(Word), Gated(Stability::Unstable,
1080 "`#[thread_local]` is an experimental feature, and does \
1081 not currently handle destructors",
1082 cfg_fn!(thread_local))),
1084 (sym::rustc_on_unimplemented, Whitelisted, template!(List:
1085 r#"/*opt*/ message = "...", /*opt*/ label = "...", /*opt*/ note = "...""#,
1086 NameValueStr: "message"),
1087 Gated(Stability::Unstable,
1088 sym::on_unimplemented,
1089 "the `#[rustc_on_unimplemented]` attribute \
1090 is an experimental feature",
1091 cfg_fn!(on_unimplemented))),
1092 (sym::rustc_const_unstable, Normal, template!(List: r#"feature = "name""#),
1093 Gated(Stability::Unstable,
1094 sym::rustc_const_unstable,
1095 "the `#[rustc_const_unstable]` attribute \
1096 is an internal feature",
1097 cfg_fn!(rustc_const_unstable))),
1098 (sym::default_lib_allocator, Whitelisted, template!(Word), Gated(Stability::Unstable,
1099 sym::allocator_internals,
1100 "the `#[default_lib_allocator]` \
1101 attribute is an experimental feature",
1102 cfg_fn!(allocator_internals))),
1103 (sym::needs_allocator, Normal, template!(Word), Gated(Stability::Unstable,
1104 sym::allocator_internals,
1105 "the `#[needs_allocator]` \
1106 attribute is an experimental \
1108 cfg_fn!(allocator_internals))),
1109 (sym::panic_runtime, Whitelisted, template!(Word), Gated(Stability::Unstable,
1111 "the `#[panic_runtime]` attribute is \
1112 an experimental feature",
1113 cfg_fn!(panic_runtime))),
1114 (sym::needs_panic_runtime, Whitelisted, template!(Word), Gated(Stability::Unstable,
1115 sym::needs_panic_runtime,
1116 "the `#[needs_panic_runtime]` \
1117 attribute is an experimental \
1119 cfg_fn!(needs_panic_runtime))),
1120 (sym::rustc_outlives, Normal, template!(Word), Gated(Stability::Unstable,
1122 "the `#[rustc_outlives]` attribute \
1123 is just used for rustc unit tests \
1124 and will never be stable",
1125 cfg_fn!(rustc_attrs))),
1126 (sym::rustc_variance, Normal, template!(Word), Gated(Stability::Unstable,
1128 "the `#[rustc_variance]` attribute \
1129 is just used for rustc unit tests \
1130 and will never be stable",
1131 cfg_fn!(rustc_attrs))),
1132 (sym::rustc_layout, Normal, template!(List: "field1, field2, ..."),
1133 Gated(Stability::Unstable,
1135 "the `#[rustc_layout]` attribute \
1136 is just used for rustc unit tests \
1137 and will never be stable",
1138 cfg_fn!(rustc_attrs))),
1139 (sym::rustc_layout_scalar_valid_range_start, Whitelisted, template!(List: "value"),
1140 Gated(Stability::Unstable,
1142 "the `#[rustc_layout_scalar_valid_range_start]` attribute \
1143 is just used to enable niche optimizations in libcore \
1144 and will never be stable",
1145 cfg_fn!(rustc_attrs))),
1146 (sym::rustc_layout_scalar_valid_range_end, Whitelisted, template!(List: "value"),
1147 Gated(Stability::Unstable,
1149 "the `#[rustc_layout_scalar_valid_range_end]` attribute \
1150 is just used to enable niche optimizations in libcore \
1151 and will never be stable",
1152 cfg_fn!(rustc_attrs))),
1153 (sym::rustc_nonnull_optimization_guaranteed, Whitelisted, template!(Word),
1154 Gated(Stability::Unstable,
1156 "the `#[rustc_nonnull_optimization_guaranteed]` attribute \
1157 is just used to enable niche optimizations in libcore \
1158 and will never be stable",
1159 cfg_fn!(rustc_attrs))),
1160 (sym::rustc_regions, Normal, template!(Word), Gated(Stability::Unstable,
1162 "the `#[rustc_regions]` attribute \
1163 is just used for rustc unit tests \
1164 and will never be stable",
1165 cfg_fn!(rustc_attrs))),
1166 (sym::rustc_error, Whitelisted, template!(Word), Gated(Stability::Unstable,
1168 "the `#[rustc_error]` attribute \
1169 is just used for rustc unit tests \
1170 and will never be stable",
1171 cfg_fn!(rustc_attrs))),
1172 (sym::rustc_dump_user_substs, Whitelisted, template!(Word), Gated(Stability::Unstable,
1175 is just used for rustc unit tests \
1176 and will never be stable",
1177 cfg_fn!(rustc_attrs))),
1178 (sym::rustc_if_this_changed, Whitelisted, template!(Word, List: "DepNode"),
1179 Gated(Stability::Unstable,
1181 "the `#[rustc_if_this_changed]` attribute \
1182 is just used for rustc unit tests \
1183 and will never be stable",
1184 cfg_fn!(rustc_attrs))),
1185 (sym::rustc_then_this_would_need, Whitelisted, template!(List: "DepNode"),
1186 Gated(Stability::Unstable,
1188 "the `#[rustc_if_this_changed]` attribute \
1189 is just used for rustc unit tests \
1190 and will never be stable",
1191 cfg_fn!(rustc_attrs))),
1192 (sym::rustc_dirty, Whitelisted, template!(List: r#"cfg = "...", /*opt*/ label = "...",
1193 /*opt*/ except = "...""#),
1194 Gated(Stability::Unstable,
1196 "the `#[rustc_dirty]` attribute \
1197 is just used for rustc unit tests \
1198 and will never be stable",
1199 cfg_fn!(rustc_attrs))),
1200 (sym::rustc_clean, Whitelisted, template!(List: r#"cfg = "...", /*opt*/ label = "...",
1201 /*opt*/ except = "...""#),
1202 Gated(Stability::Unstable,
1204 "the `#[rustc_clean]` attribute \
1205 is just used for rustc unit tests \
1206 and will never be stable",
1207 cfg_fn!(rustc_attrs))),
1209 sym::rustc_partition_reused,
1211 template!(List: r#"cfg = "...", module = "...""#),
1213 Stability::Unstable,
1216 is just used for rustc unit tests \
1217 and will never be stable",
1218 cfg_fn!(rustc_attrs)
1222 sym::rustc_partition_codegened,
1224 template!(List: r#"cfg = "...", module = "...""#),
1226 Stability::Unstable,
1229 is just used for rustc unit tests \
1230 and will never be stable",
1231 cfg_fn!(rustc_attrs),
1234 (sym::rustc_expected_cgu_reuse, Whitelisted, template!(List: r#"cfg = "...", module = "...",
1236 Gated(Stability::Unstable,
1239 is just used for rustc unit tests \
1240 and will never be stable",
1241 cfg_fn!(rustc_attrs))),
1242 (sym::rustc_synthetic, Whitelisted, template!(Word), Gated(Stability::Unstable,
1245 is just used for rustc unit tests \
1246 and will never be stable",
1247 cfg_fn!(rustc_attrs))),
1248 (sym::rustc_symbol_name, Whitelisted, template!(Word), Gated(Stability::Unstable,
1250 "internal rustc attributes will never be stable",
1251 cfg_fn!(rustc_attrs))),
1252 (sym::rustc_def_path, Whitelisted, template!(Word), Gated(Stability::Unstable,
1254 "internal rustc attributes will never be stable",
1255 cfg_fn!(rustc_attrs))),
1256 (sym::rustc_mir, Whitelisted, template!(List: "arg1, arg2, ..."), Gated(Stability::Unstable,
1258 "the `#[rustc_mir]` attribute \
1259 is just used for rustc unit tests \
1260 and will never be stable",
1261 cfg_fn!(rustc_attrs))),
1263 sym::rustc_inherit_overflow_checks,
1267 Stability::Unstable,
1269 "the `#[rustc_inherit_overflow_checks]` \
1270 attribute is just used to control \
1271 overflow checking behavior of several \
1272 libcore functions that are inlined \
1273 across crates and will never be stable",
1274 cfg_fn!(rustc_attrs),
1278 (sym::rustc_dump_program_clauses, Whitelisted, template!(Word), Gated(Stability::Unstable,
1280 "the `#[rustc_dump_program_clauses]` \
1281 attribute is just used for rustc unit \
1282 tests and will never be stable",
1283 cfg_fn!(rustc_attrs))),
1284 (sym::rustc_dump_env_program_clauses, Whitelisted, template!(Word), Gated(Stability::Unstable,
1286 "the `#[rustc_dump_env_program_clauses]` \
1287 attribute is just used for rustc unit \
1288 tests and will never be stable",
1289 cfg_fn!(rustc_attrs))),
1290 (sym::rustc_object_lifetime_default, Whitelisted, template!(Word), Gated(Stability::Unstable,
1292 "the `#[rustc_object_lifetime_default]` \
1293 attribute is just used for rustc unit \
1294 tests and will never be stable",
1295 cfg_fn!(rustc_attrs))),
1296 (sym::rustc_test_marker, Normal, template!(Word), Gated(Stability::Unstable,
1298 "the `#[rustc_test_marker]` attribute \
1299 is used internally to track tests",
1300 cfg_fn!(rustc_attrs))),
1301 (sym::rustc_macro_transparency, Whitelisted, template!(NameValueStr:
1302 "transparent|semitransparent|opaque"),
1303 Gated(Stability::Unstable,
1305 "used internally for testing macro hygiene",
1306 cfg_fn!(rustc_attrs))),
1307 (sym::compiler_builtins, Whitelisted, template!(Word), Gated(Stability::Unstable,
1308 sym::compiler_builtins,
1309 "the `#[compiler_builtins]` attribute is used to \
1310 identify the `compiler_builtins` crate which \
1311 contains compiler-rt intrinsics and will never be \
1313 cfg_fn!(compiler_builtins))),
1314 (sym::sanitizer_runtime, Whitelisted, template!(Word), Gated(Stability::Unstable,
1315 sym::sanitizer_runtime,
1316 "the `#[sanitizer_runtime]` attribute is used to \
1317 identify crates that contain the runtime of a \
1318 sanitizer and will never be stable",
1319 cfg_fn!(sanitizer_runtime))),
1320 (sym::profiler_runtime, Whitelisted, template!(Word), Gated(Stability::Unstable,
1321 sym::profiler_runtime,
1322 "the `#[profiler_runtime]` attribute is used to \
1323 identify the `profiler_builtins` crate which \
1324 contains the profiler runtime and will never be \
1326 cfg_fn!(profiler_runtime))),
1328 (sym::allow_internal_unstable, Normal, template!(Word, List: "feat1, feat2, ..."),
1329 Gated(Stability::Unstable,
1330 sym::allow_internal_unstable,
1331 EXPLAIN_ALLOW_INTERNAL_UNSTABLE,
1332 cfg_fn!(allow_internal_unstable))),
1334 (sym::allow_internal_unsafe, Normal, template!(Word), Gated(Stability::Unstable,
1335 sym::allow_internal_unsafe,
1336 EXPLAIN_ALLOW_INTERNAL_UNSAFE,
1337 cfg_fn!(allow_internal_unsafe))),
1339 (sym::fundamental, Whitelisted, template!(Word), Gated(Stability::Unstable,
1341 "the `#[fundamental]` attribute \
1342 is an experimental feature",
1343 cfg_fn!(fundamental))),
1345 (sym::proc_macro_derive, Normal, template!(List: "TraitName, \
1346 /*opt*/ attributes(name1, name2, ...)"),
1349 (sym::rustc_copy_clone_marker, Whitelisted, template!(Word), Gated(Stability::Unstable,
1351 "internal implementation detail",
1352 cfg_fn!(rustc_attrs))),
1354 (sym::rustc_allocator, Whitelisted, template!(Word), Gated(Stability::Unstable,
1356 "internal implementation detail",
1357 cfg_fn!(rustc_attrs))),
1359 (sym::rustc_allocator_nounwind, Whitelisted, template!(Word), Gated(Stability::Unstable,
1361 "internal implementation detail",
1362 cfg_fn!(rustc_attrs))),
1364 (sym::rustc_builtin_macro, Whitelisted, template!(Word), Gated(Stability::Unstable,
1366 "internal implementation detail",
1367 cfg_fn!(rustc_attrs))),
1369 (sym::rustc_promotable, Whitelisted, template!(Word), Gated(Stability::Unstable,
1371 "internal implementation detail",
1372 cfg_fn!(rustc_attrs))),
1374 (sym::rustc_allow_const_fn_ptr, Whitelisted, template!(Word), Gated(Stability::Unstable,
1376 "internal implementation detail",
1377 cfg_fn!(rustc_attrs))),
1379 (sym::rustc_dummy, Normal, template!(Word /* doesn't matter*/), Gated(Stability::Unstable,
1381 "used by the test suite",
1382 cfg_fn!(rustc_attrs))),
1384 // FIXME: #14408 whitelist docs since rustdoc looks at them
1388 template!(List: "hidden|inline|...", NameValueStr: "string"),
1392 // FIXME: #14406 these are processed in codegen, which happens after the
1394 (sym::cold, Whitelisted, template!(Word), Ungated),
1395 (sym::naked, Whitelisted, template!(Word), Gated(Stability::Unstable,
1396 sym::naked_functions,
1397 "the `#[naked]` attribute \
1398 is an experimental feature",
1399 cfg_fn!(naked_functions))),
1400 (sym::ffi_returns_twice, Whitelisted, template!(Word), Gated(Stability::Unstable,
1401 sym::ffi_returns_twice,
1402 "the `#[ffi_returns_twice]` attribute \
1403 is an experimental feature",
1404 cfg_fn!(ffi_returns_twice))),
1405 (sym::target_feature, Whitelisted, template!(List: r#"enable = "name""#), Ungated),
1406 (sym::export_name, Whitelisted, template!(NameValueStr: "name"), Ungated),
1407 (sym::inline, Whitelisted, template!(Word, List: "always|never"), Ungated),
1408 (sym::link, Whitelisted, template!(List: r#"name = "...", /*opt*/ kind = "dylib|static|...",
1409 /*opt*/ cfg = "...""#), Ungated),
1410 (sym::link_name, Whitelisted, template!(NameValueStr: "name"), Ungated),
1411 (sym::link_section, Whitelisted, template!(NameValueStr: "name"), Ungated),
1412 (sym::no_builtins, Whitelisted, template!(Word), Ungated),
1413 (sym::no_debug, Whitelisted, template!(Word), Gated(
1414 Stability::Deprecated("https://github.com/rust-lang/rust/issues/29721", None),
1416 "the `#[no_debug]` attribute was an experimental feature that has been \
1417 deprecated due to lack of demand",
1418 cfg_fn!(no_debug))),
1420 sym::omit_gdb_pretty_printer_section,
1424 Stability::Unstable,
1425 sym::omit_gdb_pretty_printer_section,
1426 "the `#[omit_gdb_pretty_printer_section]` \
1427 attribute is just used for the Rust test \
1429 cfg_fn!(omit_gdb_pretty_printer_section)
1435 Gated(Stability::Unstable,
1436 sym::dropck_eyepatch,
1437 "`may_dangle` has unstable semantics and may be removed in the future",
1438 cfg_fn!(dropck_eyepatch))),
1439 (sym::unwind, Whitelisted, template!(List: "allowed|aborts"), Gated(Stability::Unstable,
1440 sym::unwind_attributes,
1441 "`#[unwind]` is experimental",
1442 cfg_fn!(unwind_attributes))),
1443 (sym::used, Whitelisted, template!(Word), Ungated),
1446 (sym::prelude_import, Whitelisted, template!(Word), Gated(Stability::Unstable,
1447 sym::prelude_import,
1448 "`#[prelude_import]` is for use by rustc only",
1449 cfg_fn!(prelude_import))),
1451 // FIXME: #14407 these are only looked at on-demand so we can't
1452 // guarantee they'll have already been checked
1454 sym::rustc_deprecated,
1456 template!(List: r#"since = "version", reason = "...""#),
1459 (sym::must_use, Whitelisted, template!(Word, NameValueStr: "reason"), Ungated),
1463 template!(List: r#"feature = "name", since = "version""#),
1469 template!(List: r#"feature = "name", reason = "...", issue = "N""#),
1476 List: r#"/*opt*/ since = "version", /*opt*/ note = "reason""#,
1477 NameValueStr: "reason"
1482 (sym::rustc_paren_sugar, Normal, template!(Word), Gated(Stability::Unstable,
1483 sym::unboxed_closures,
1484 "unboxed_closures are still evolving",
1485 cfg_fn!(unboxed_closures))),
1487 (sym::windows_subsystem, Whitelisted, template!(NameValueStr: "windows|console"), Ungated),
1489 (sym::proc_macro_attribute, Normal, template!(Word), Ungated),
1490 (sym::proc_macro, Normal, template!(Word), Ungated),
1492 (sym::rustc_proc_macro_decls, Normal, template!(Word), Gated(Stability::Unstable,
1494 "used internally by rustc",
1495 cfg_fn!(rustc_attrs))),
1497 (sym::allow_fail, Normal, template!(Word), Gated(Stability::Unstable,
1499 "allow_fail attribute is currently unstable",
1500 cfg_fn!(allow_fail))),
1502 (sym::rustc_std_internal_symbol, Whitelisted, template!(Word), Gated(Stability::Unstable,
1504 "this is an internal attribute that will \
1506 cfg_fn!(rustc_attrs))),
1508 // whitelists "identity-like" conversion methods to suggest on type mismatch
1509 (sym::rustc_conversion_suggestion, Whitelisted, template!(Word), Gated(Stability::Unstable,
1511 "this is an internal attribute that will \
1513 cfg_fn!(rustc_attrs))),
1516 sym::rustc_args_required_const,
1518 template!(List: "N"),
1519 Gated(Stability::Unstable, sym::rustc_attrs, "never will be stable",
1520 cfg_fn!(rustc_attrs))
1523 (sym::panic_handler, Normal, template!(Word), Ungated),
1525 (sym::alloc_error_handler, Normal, template!(Word), Gated(Stability::Unstable,
1526 sym::alloc_error_handler,
1527 "`#[alloc_error_handler]` is an unstable feature",
1528 cfg_fn!(alloc_error_handler))),
1531 (sym::optimize, Whitelisted, template!(List: "size|speed"), Gated(Stability::Unstable,
1532 sym::optimize_attribute,
1533 "`#[optimize]` attribute is an unstable feature",
1534 cfg_fn!(optimize_attribute))),
1536 // Crate level attributes
1537 (sym::crate_name, CrateLevel, template!(NameValueStr: "name"), Ungated),
1538 (sym::crate_type, CrateLevel, template!(NameValueStr: "bin|lib|..."), Ungated),
1539 (sym::crate_id, CrateLevel, template!(NameValueStr: "ignored"), Ungated),
1540 (sym::feature, CrateLevel, template!(List: "name1, name1, ..."), Ungated),
1541 (sym::no_start, CrateLevel, template!(Word), Ungated),
1542 (sym::no_main, CrateLevel, template!(Word), Ungated),
1543 (sym::recursion_limit, CrateLevel, template!(NameValueStr: "N"), Ungated),
1544 (sym::type_length_limit, CrateLevel, template!(NameValueStr: "N"), Ungated),
1545 (sym::test_runner, CrateLevel, template!(List: "path"), Gated(Stability::Unstable,
1546 sym::custom_test_frameworks,
1547 "custom test frameworks are an unstable feature",
1548 cfg_fn!(custom_test_frameworks))),
1551 pub type BuiltinAttribute = (Symbol, AttributeType, AttributeTemplate, AttributeGate);
1554 pub static ref BUILTIN_ATTRIBUTE_MAP: FxHashMap<Symbol, &'static BuiltinAttribute> = {
1555 let mut map = FxHashMap::default();
1556 for attr in BUILTIN_ATTRIBUTES.iter() {
1557 if map.insert(attr.0, attr).is_some() {
1558 panic!("duplicate builtin attribute `{}`", attr.0);
1565 // cfg(...)'s that are feature gated
1566 const GATED_CFGS: &[(Symbol, Symbol, fn(&Features) -> bool)] = &[
1567 // (name in cfg, feature, function to check if the feature is enabled)
1568 (sym::target_thread_local, sym::cfg_target_thread_local, cfg_fn!(cfg_target_thread_local)),
1569 (sym::target_has_atomic, sym::cfg_target_has_atomic, cfg_fn!(cfg_target_has_atomic)),
1570 (sym::rustdoc, sym::doc_cfg, cfg_fn!(doc_cfg)),
1571 (sym::doctest, sym::cfg_doctest, cfg_fn!(cfg_doctest)),
1575 pub struct GatedCfg {
1581 pub fn gate(cfg: &ast::MetaItem) -> Option<GatedCfg> {
1583 .position(|info| cfg.check_name(info.0))
1592 pub fn check_and_emit(&self, sess: &ParseSess, features: &Features) {
1593 let (cfg, feature, has_feature) = GATED_CFGS[self.index];
1594 if !has_feature(features) && !self.span.allows_unstable(feature) {
1595 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
1596 emit_feature_err(sess, feature, self.span, GateIssue::Language, &explain);
1601 struct Context<'a> {
1602 features: &'a Features,
1603 parse_sess: &'a ParseSess,
1604 plugin_attributes: &'a [(Symbol, AttributeType)],
1607 macro_rules! gate_feature_fn {
1608 ($cx: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr, $level: expr) => {{
1609 let (cx, has_feature, span,
1610 name, explain, level) = ($cx, $has_feature, $span, $name, $explain, $level);
1611 let has_feature: bool = has_feature(&$cx.features);
1612 debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
1613 if !has_feature && !span.allows_unstable($name) {
1614 leveled_feature_err(cx.parse_sess, name, span, GateIssue::Language, explain, level)
1620 macro_rules! gate_feature {
1621 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {
1622 gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
1623 sym::$feature, $explain, GateStrength::Hard)
1625 ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {
1626 gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
1627 sym::$feature, $explain, $level)
1631 impl<'a> Context<'a> {
1634 attr: &ast::Attribute,
1635 attr_info: Option<&BuiltinAttribute>,
1638 debug!("check_attribute(attr = {:?})", attr);
1639 if let Some(&(name, ty, _template, ref gateage)) = attr_info {
1640 if let Gated(_, name, desc, ref has_feature) = *gateage {
1641 if !attr.span.allows_unstable(name) {
1643 self, has_feature, attr.span, name, desc, GateStrength::Hard
1646 } else if name == sym::doc {
1647 if let Some(content) = attr.meta_item_list() {
1648 if content.iter().any(|c| c.check_name(sym::include)) {
1649 gate_feature!(self, external_doc, attr.span,
1650 "`#[doc(include = \"...\")]` is experimental"
1655 debug!("check_attribute: {:?} is builtin, {:?}, {:?}", attr.path, ty, gateage);
1658 for segment in &attr.path.segments {
1659 if segment.ident.as_str().starts_with("rustc") {
1660 let msg = "attributes starting with `rustc` are \
1661 reserved for use by the `rustc` compiler";
1662 gate_feature!(self, rustc_attrs, segment.ident.span, msg);
1666 for &(n, ty) in self.plugin_attributes {
1668 // Plugins can't gate attributes, so we don't check for it
1669 // unlike the code above; we only use this loop to
1670 // short-circuit to avoid the checks below.
1671 debug!("check_attribute: {:?} is registered by a plugin, {:?}", attr.path, ty);
1675 if !is_macro && !attr::is_known(attr) {
1676 // Only run the custom attribute lint during regular feature gate
1677 // checking. Macro gating runs before the plugin attributes are
1678 // registered, so we skip this in that case.
1679 let msg = format!("the attribute `{}` is currently unknown to the compiler and \
1680 may have meaning added to it in the future", attr.path);
1681 gate_feature!(self, custom_attribute, attr.span, &msg);
1686 pub fn check_attribute(attr: &ast::Attribute, parse_sess: &ParseSess, features: &Features) {
1687 let cx = Context { features, parse_sess, plugin_attributes: &[] };
1690 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name).map(|a| *a)),
1695 fn find_lang_feature_issue(feature: Symbol) -> Option<u32> {
1696 if let Some(info) = ACTIVE_FEATURES.iter().find(|t| t.0 == feature) {
1698 // FIXME (#28244): enforce that active features have issue numbers
1699 // assert!(issue.is_some())
1702 // search in Accepted, Removed, or Stable Removed features
1703 let found = ACCEPTED_FEATURES.iter().chain(REMOVED_FEATURES).chain(STABLE_REMOVED_FEATURES)
1704 .find(|t| t.0 == feature);
1706 Some(&(_, _, issue, _)) => issue,
1707 None => panic!("Feature `{}` is not declared anywhere", feature),
1712 pub enum GateIssue {
1714 Library(Option<u32>)
1717 #[derive(Debug, Copy, Clone, PartialEq)]
1718 pub enum GateStrength {
1719 /// A hard error. (Most feature gates should use this.)
1721 /// Only a warning. (Use this only as backwards-compatibility demands.)
1725 pub fn emit_feature_err(
1732 feature_err(sess, feature, span, issue, explain).emit();
1735 pub fn feature_err<'a, S: Into<MultiSpan>>(
1736 sess: &'a ParseSess,
1741 ) -> DiagnosticBuilder<'a> {
1742 leveled_feature_err(sess, feature, span, issue, explain, GateStrength::Hard)
1745 fn leveled_feature_err<'a, S: Into<MultiSpan>>(
1746 sess: &'a ParseSess,
1751 level: GateStrength,
1752 ) -> DiagnosticBuilder<'a> {
1753 let diag = &sess.span_diagnostic;
1755 let issue = match issue {
1756 GateIssue::Language => find_lang_feature_issue(feature),
1757 GateIssue::Library(lib) => lib,
1760 let mut err = match level {
1761 GateStrength::Hard => {
1762 diag.struct_span_err_with_code(span, explain, stringify_error_code!(E0658))
1764 GateStrength::Soft => diag.struct_span_warn(span, explain),
1768 None | Some(0) => {} // We still accept `0` as a stand-in for backwards compatibility
1771 "for more information, see https://github.com/rust-lang/rust/issues/{}",
1777 // #23973: do not suggest `#![feature(...)]` if we are in beta/stable
1778 if sess.unstable_features.is_nightly_build() {
1779 err.help(&format!("add `#![feature({})]` to the crate attributes to enable", feature));
1782 // If we're on stable and only emitting a "soft" warning, add a note to
1783 // clarify that the feature isn't "on" (rather than being on but
1785 if !sess.unstable_features.is_nightly_build() && level == GateStrength::Soft {
1786 err.help("a nightly build of the compiler is required to enable this feature");
1793 const EXPLAIN_BOX_SYNTAX: &str =
1794 "box expression syntax is experimental; you can call `Box::new` instead";
1796 pub const EXPLAIN_STMT_ATTR_SYNTAX: &str =
1797 "attributes on expressions are experimental";
1799 pub const EXPLAIN_ALLOW_INTERNAL_UNSTABLE: &str =
1800 "allow_internal_unstable side-steps feature gating and stability checks";
1801 pub const EXPLAIN_ALLOW_INTERNAL_UNSAFE: &str =
1802 "allow_internal_unsafe side-steps the unsafe_code lint";
1804 pub const EXPLAIN_UNSIZED_TUPLE_COERCION: &str =
1805 "unsized tuple coercion is not stable enough for use and is subject to change";
1807 struct PostExpansionVisitor<'a> {
1808 context: &'a Context<'a>,
1809 builtin_attributes: &'static FxHashMap<Symbol, &'static BuiltinAttribute>,
1812 macro_rules! gate_feature_post {
1813 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {{
1814 let (cx, span) = ($cx, $span);
1815 if !span.allows_unstable(sym::$feature) {
1816 gate_feature!(cx.context, $feature, span, $explain)
1819 ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {{
1820 let (cx, span) = ($cx, $span);
1821 if !span.allows_unstable(sym::$feature) {
1822 gate_feature!(cx.context, $feature, span, $explain, $level)
1827 impl<'a> PostExpansionVisitor<'a> {
1828 fn check_abi(&self, abi: Abi, span: Span) {
1830 Abi::RustIntrinsic => {
1831 gate_feature_post!(&self, intrinsics, span,
1832 "intrinsics are subject to change");
1834 Abi::PlatformIntrinsic => {
1835 gate_feature_post!(&self, platform_intrinsics, span,
1836 "platform intrinsics are experimental and possibly buggy");
1838 Abi::Vectorcall => {
1839 gate_feature_post!(&self, abi_vectorcall, span,
1840 "vectorcall is experimental and subject to change");
1843 gate_feature_post!(&self, abi_thiscall, span,
1844 "thiscall is experimental and subject to change");
1847 gate_feature_post!(&self, unboxed_closures, span,
1848 "rust-call ABI is subject to change");
1851 gate_feature_post!(&self, abi_ptx, span,
1852 "PTX ABIs are experimental and subject to change");
1854 Abi::Unadjusted => {
1855 gate_feature_post!(&self, abi_unadjusted, span,
1856 "unadjusted ABI is an implementation detail and perma-unstable");
1858 Abi::Msp430Interrupt => {
1859 gate_feature_post!(&self, abi_msp430_interrupt, span,
1860 "msp430-interrupt ABI is experimental and subject to change");
1862 Abi::X86Interrupt => {
1863 gate_feature_post!(&self, abi_x86_interrupt, span,
1864 "x86-interrupt ABI is experimental and subject to change");
1866 Abi::AmdGpuKernel => {
1867 gate_feature_post!(&self, abi_amdgpu_kernel, span,
1868 "amdgpu-kernel ABI is experimental and subject to change");
1884 impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
1885 fn visit_attribute(&mut self, attr: &ast::Attribute) {
1886 let attr_info = attr.ident().and_then(|ident| {
1887 self.builtin_attributes.get(&ident.name).map(|a| *a)
1890 // Check for gated attributes.
1891 self.context.check_attribute(attr, attr_info, false);
1893 if attr.check_name(sym::doc) {
1894 if let Some(content) = attr.meta_item_list() {
1895 if content.len() == 1 && content[0].check_name(sym::cfg) {
1896 gate_feature_post!(&self, doc_cfg, attr.span,
1897 "`#[doc(cfg(...))]` is experimental"
1899 } else if content.iter().any(|c| c.check_name(sym::masked)) {
1900 gate_feature_post!(&self, doc_masked, attr.span,
1901 "`#[doc(masked)]` is experimental"
1903 } else if content.iter().any(|c| c.check_name(sym::spotlight)) {
1904 gate_feature_post!(&self, doc_spotlight, attr.span,
1905 "`#[doc(spotlight)]` is experimental"
1907 } else if content.iter().any(|c| c.check_name(sym::alias)) {
1908 gate_feature_post!(&self, doc_alias, attr.span,
1909 "`#[doc(alias = \"...\")]` is experimental"
1911 } else if content.iter().any(|c| c.check_name(sym::keyword)) {
1912 gate_feature_post!(&self, doc_keyword, attr.span,
1913 "`#[doc(keyword = \"...\")]` is experimental"
1920 // `rustc_dummy` doesn't have any restrictions specific to built-in attributes.
1921 Some(&(name, _, template, _)) if name != sym::rustc_dummy =>
1922 check_builtin_attribute(self.context.parse_sess, attr, name, template),
1923 _ => if let Some(TokenTree::Token(token)) = attr.tokens.trees().next() {
1924 if token == token::Eq {
1925 // All key-value attributes are restricted to meta-item syntax.
1926 attr.parse_meta(self.context.parse_sess).map_err(|mut err| err.emit()).ok();
1932 fn visit_name(&mut self, sp: Span, name: ast::Name) {
1933 if !name.as_str().is_ascii() {
1937 self.context.parse_sess.source_map().def_span(sp),
1938 "non-ascii idents are not fully supported"
1943 fn visit_item(&mut self, i: &'a ast::Item) {
1945 ast::ItemKind::ForeignMod(ref foreign_module) => {
1946 self.check_abi(foreign_module.abi, i.span);
1949 ast::ItemKind::Fn(..) => {
1950 if attr::contains_name(&i.attrs[..], sym::plugin_registrar) {
1951 gate_feature_post!(&self, plugin_registrar, i.span,
1952 "compiler plugins are experimental and possibly buggy");
1954 if attr::contains_name(&i.attrs[..], sym::start) {
1955 gate_feature_post!(&self, start, i.span,
1956 "a `#[start]` function is an experimental \
1957 feature whose signature may change \
1960 if attr::contains_name(&i.attrs[..], sym::main) {
1961 gate_feature_post!(&self, main, i.span,
1962 "declaration of a non-standard `#[main]` \
1963 function may change over time, for now \
1964 a top-level `fn main()` is required");
1968 ast::ItemKind::Struct(..) => {
1969 for attr in attr::filter_by_name(&i.attrs[..], sym::repr) {
1970 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
1971 if item.check_name(sym::simd) {
1972 gate_feature_post!(&self, repr_simd, attr.span,
1973 "SIMD types are experimental and possibly buggy");
1979 ast::ItemKind::Enum(ast::EnumDef{ref variants, ..}, ..) => {
1980 for variant in variants {
1981 match (&variant.node.data, &variant.node.disr_expr) {
1982 (ast::VariantData::Unit(..), _) => {},
1983 (_, Some(disr_expr)) =>
1986 arbitrary_enum_discriminant,
1987 disr_expr.value.span,
1988 "discriminants on non-unit variants are experimental"),
1993 let has_feature = self.context.features.arbitrary_enum_discriminant;
1994 if !has_feature && !i.span.allows_unstable(sym::arbitrary_enum_discriminant) {
1995 Parser::maybe_report_invalid_custom_discriminants(
1996 self.context.parse_sess,
2002 ast::ItemKind::Impl(_, polarity, defaultness, _, _, _, _) => {
2003 if polarity == ast::ImplPolarity::Negative {
2004 gate_feature_post!(&self, optin_builtin_traits,
2006 "negative trait bounds are not yet fully implemented; \
2007 use marker types for now");
2010 if let ast::Defaultness::Default = defaultness {
2011 gate_feature_post!(&self, specialization,
2013 "specialization is unstable");
2017 ast::ItemKind::Trait(ast::IsAuto::Yes, ..) => {
2018 gate_feature_post!(&self, optin_builtin_traits,
2020 "auto traits are experimental and possibly buggy");
2023 ast::ItemKind::TraitAlias(..) => {
2028 "trait aliases are experimental"
2032 ast::ItemKind::MacroDef(ast::MacroDef { legacy: false, .. }) => {
2033 let msg = "`macro` is experimental";
2034 gate_feature_post!(&self, decl_macro, i.span, msg);
2037 ast::ItemKind::Existential(..) => {
2042 "existential types are unstable"
2049 visit::walk_item(self, i);
2052 fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
2054 ast::ForeignItemKind::Fn(..) |
2055 ast::ForeignItemKind::Static(..) => {
2056 let link_name = attr::first_attr_value_str_by_name(&i.attrs, sym::link_name);
2057 let links_to_llvm = match link_name {
2058 Some(val) => val.as_str().starts_with("llvm."),
2062 gate_feature_post!(&self, link_llvm_intrinsics, i.span,
2063 "linking to LLVM intrinsics is experimental");
2066 ast::ForeignItemKind::Ty => {
2067 gate_feature_post!(&self, extern_types, i.span,
2068 "extern types are experimental");
2070 ast::ForeignItemKind::Macro(..) => {}
2073 visit::walk_foreign_item(self, i)
2076 fn visit_ty(&mut self, ty: &'a ast::Ty) {
2078 ast::TyKind::BareFn(ref bare_fn_ty) => {
2079 self.check_abi(bare_fn_ty.abi, ty.span);
2081 ast::TyKind::Never => {
2082 gate_feature_post!(&self, never_type, ty.span,
2083 "The `!` type is experimental");
2087 visit::walk_ty(self, ty)
2090 fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FunctionRetTy) {
2091 if let ast::FunctionRetTy::Ty(ref output_ty) = *ret_ty {
2092 if let ast::TyKind::Never = output_ty.node {
2095 self.visit_ty(output_ty)
2100 fn visit_expr(&mut self, e: &'a ast::Expr) {
2102 ast::ExprKind::Box(_) => {
2103 gate_feature_post!(&self, box_syntax, e.span, EXPLAIN_BOX_SYNTAX);
2105 ast::ExprKind::Type(..) => {
2106 // To avoid noise about type ascription in common syntax errors, only emit if it
2107 // is the *only* error.
2108 if self.context.parse_sess.span_diagnostic.err_count() == 0 {
2109 gate_feature_post!(&self, type_ascription, e.span,
2110 "type ascription is experimental");
2113 ast::ExprKind::Yield(..) => {
2114 gate_feature_post!(&self, generators,
2116 "yield syntax is experimental");
2118 ast::ExprKind::TryBlock(_) => {
2119 gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
2121 ast::ExprKind::Block(_, opt_label) => {
2122 if let Some(label) = opt_label {
2123 gate_feature_post!(&self, label_break_value, label.ident.span,
2124 "labels on blocks are unstable");
2127 ast::ExprKind::Async(..) => {
2128 gate_feature_post!(&self, async_await, e.span, "async blocks are unstable");
2130 ast::ExprKind::Await(origin, _) => {
2132 ast::AwaitOrigin::FieldLike =>
2133 gate_feature_post!(&self, async_await, e.span, "async/await is unstable"),
2134 ast::AwaitOrigin::MacroLike =>
2139 "`await!(<expr>)` macro syntax is unstable, and will soon be removed \
2140 in favor of `<expr>.await` syntax."
2146 visit::walk_expr(self, e)
2149 fn visit_arm(&mut self, arm: &'a ast::Arm) {
2150 visit::walk_arm(self, arm)
2153 fn visit_pat(&mut self, pattern: &'a ast::Pat) {
2154 match &pattern.node {
2155 PatKind::Slice(pats) => {
2157 let span = pat.span;
2158 let inner_pat = match &pat.node {
2159 PatKind::Ident(.., Some(pat)) => pat,
2162 if inner_pat.is_rest() {
2167 "subslice patterns are unstable"
2172 PatKind::Box(..) => {
2173 gate_feature_post!(&self, box_patterns,
2175 "box pattern syntax is experimental");
2177 PatKind::Range(_, _, Spanned { node: RangeEnd::Excluded, .. }) => {
2178 gate_feature_post!(&self, exclusive_range_pattern, pattern.span,
2179 "exclusive range pattern syntax is experimental");
2183 visit::walk_pat(self, pattern)
2186 fn visit_fn(&mut self,
2187 fn_kind: FnKind<'a>,
2188 fn_decl: &'a ast::FnDecl,
2191 if let Some(header) = fn_kind.header() {
2192 // Check for const fn and async fn declarations.
2193 if header.asyncness.node.is_async() {
2194 gate_feature_post!(&self, async_await, span, "async fn is unstable");
2197 // Stability of const fn methods are covered in
2198 // `visit_trait_item` and `visit_impl_item` below; this is
2199 // because default methods don't pass through this point.
2200 self.check_abi(header.abi, span);
2203 if fn_decl.c_variadic {
2204 gate_feature_post!(&self, c_variadic, span, "C-variadic functions are unstable");
2207 visit::walk_fn(self, fn_kind, fn_decl, span)
2210 fn visit_generic_param(&mut self, param: &'a GenericParam) {
2212 GenericParamKind::Const { .. } =>
2213 gate_feature_post!(&self, const_generics, param.ident.span,
2214 "const generics are unstable"),
2217 visit::walk_generic_param(self, param)
2220 fn visit_assoc_ty_constraint(&mut self, constraint: &'a AssocTyConstraint) {
2221 match constraint.kind {
2222 AssocTyConstraintKind::Bound { .. } =>
2223 gate_feature_post!(&self, associated_type_bounds, constraint.span,
2224 "associated type bounds are unstable"),
2227 visit::walk_assoc_ty_constraint(self, constraint)
2230 fn visit_trait_item(&mut self, ti: &'a ast::TraitItem) {
2232 ast::TraitItemKind::Method(ref sig, ref block) => {
2233 if block.is_none() {
2234 self.check_abi(sig.header.abi, ti.span);
2236 if sig.header.asyncness.node.is_async() {
2237 gate_feature_post!(&self, async_await, ti.span, "async fn is unstable");
2239 if sig.decl.c_variadic {
2240 gate_feature_post!(&self, c_variadic, ti.span,
2241 "C-variadic functions are unstable");
2243 if sig.header.constness.node == ast::Constness::Const {
2244 gate_feature_post!(&self, const_fn, ti.span, "const fn is unstable");
2247 ast::TraitItemKind::Type(_, ref default) => {
2248 // We use three if statements instead of something like match guards so that all
2249 // of these errors can be emitted if all cases apply.
2250 if default.is_some() {
2251 gate_feature_post!(&self, associated_type_defaults, ti.span,
2252 "associated type defaults are unstable");
2254 if !ti.generics.params.is_empty() {
2255 gate_feature_post!(&self, generic_associated_types, ti.span,
2256 "generic associated types are unstable");
2258 if !ti.generics.where_clause.predicates.is_empty() {
2259 gate_feature_post!(&self, generic_associated_types, ti.span,
2260 "where clauses on associated types are unstable");
2265 visit::walk_trait_item(self, ti)
2268 fn visit_impl_item(&mut self, ii: &'a ast::ImplItem) {
2269 if ii.defaultness == ast::Defaultness::Default {
2270 gate_feature_post!(&self, specialization,
2272 "specialization is unstable");
2276 ast::ImplItemKind::Method(..) => {}
2277 ast::ImplItemKind::Existential(..) => {
2282 "existential types are unstable"
2285 ast::ImplItemKind::Type(_) => {
2286 if !ii.generics.params.is_empty() {
2287 gate_feature_post!(&self, generic_associated_types, ii.span,
2288 "generic associated types are unstable");
2290 if !ii.generics.where_clause.predicates.is_empty() {
2291 gate_feature_post!(&self, generic_associated_types, ii.span,
2292 "where clauses on associated types are unstable");
2297 visit::walk_impl_item(self, ii)
2300 fn visit_vis(&mut self, vis: &'a ast::Visibility) {
2301 if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.node {
2302 gate_feature_post!(&self, crate_visibility_modifier, vis.span,
2303 "`crate` visibility modifier is experimental");
2305 visit::walk_vis(self, vis)
2309 pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
2310 crate_edition: Edition, allow_features: &Option<Vec<String>>) -> Features {
2311 fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) {
2312 let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
2313 if let Some(reason) = reason {
2314 err.span_note(span, reason);
2316 err.span_label(span, "feature has been removed");
2321 let mut features = Features::new();
2322 let mut edition_enabled_features = FxHashMap::default();
2324 for &edition in ALL_EDITIONS {
2325 if edition <= crate_edition {
2326 // The `crate_edition` implies its respective umbrella feature-gate
2327 // (i.e., `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX).
2328 edition_enabled_features.insert(edition.feature_name(), edition);
2332 for &(name, .., f_edition, set) in ACTIVE_FEATURES {
2333 if let Some(f_edition) = f_edition {
2334 if f_edition <= crate_edition {
2335 set(&mut features, DUMMY_SP);
2336 edition_enabled_features.insert(name, crate_edition);
2341 // Process the edition umbrella feature-gates first, to ensure
2342 // `edition_enabled_features` is completed before it's queried.
2343 for attr in krate_attrs {
2344 if !attr.check_name(sym::feature) {
2348 let list = match attr.meta_item_list() {
2358 let name = mi.name_or_empty();
2359 if INCOMPLETE_FEATURES.iter().any(|f| name == *f) {
2360 span_handler.struct_span_warn(
2363 "the feature `{}` is incomplete and may cause the compiler to crash",
2369 if let Some(edition) = ALL_EDITIONS.iter().find(|e| name == e.feature_name()) {
2370 if *edition <= crate_edition {
2374 for &(name, .., f_edition, set) in ACTIVE_FEATURES {
2375 if let Some(f_edition) = f_edition {
2376 if f_edition <= *edition {
2377 // FIXME(Manishearth) there is currently no way to set
2378 // lib features by edition
2379 set(&mut features, DUMMY_SP);
2380 edition_enabled_features.insert(name, *edition);
2388 for attr in krate_attrs {
2389 if !attr.check_name(sym::feature) {
2393 let list = match attr.meta_item_list() {
2398 let bad_input = |span| {
2399 struct_span_err!(span_handler, span, E0556, "malformed `feature` attribute input")
2403 let name = match mi.ident() {
2404 Some(ident) if mi.is_word() => ident.name,
2406 bad_input(mi.span()).span_suggestion(
2408 "expected just one word",
2409 format!("{}", ident.name),
2410 Applicability::MaybeIncorrect,
2415 bad_input(mi.span()).span_label(mi.span(), "expected just one word").emit();
2420 if let Some(edition) = edition_enabled_features.get(&name) {
2425 "the feature `{}` is included in the Rust {} edition",
2432 if ALL_EDITIONS.iter().any(|e| name == e.feature_name()) {
2433 // Handled in the separate loop above.
2437 let removed = REMOVED_FEATURES.iter().find(|f| name == f.0);
2438 let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.0);
2439 if let Some((.., reason)) = removed.or(stable_removed) {
2440 feature_removed(span_handler, mi.span(), *reason);
2444 if let Some((_, since, ..)) = ACCEPTED_FEATURES.iter().find(|f| name == f.0) {
2445 let since = Some(Symbol::intern(since));
2446 features.declared_lang_features.push((name, mi.span(), since));
2450 if let Some(allowed) = allow_features.as_ref() {
2451 if allowed.iter().find(|f| *f == name.as_str()).is_none() {
2452 span_err!(span_handler, mi.span(), E0725,
2453 "the feature `{}` is not in the list of allowed features",
2459 if let Some((.., set)) = ACTIVE_FEATURES.iter().find(|f| name == f.0) {
2460 set(&mut features, mi.span());
2461 features.declared_lang_features.push((name, mi.span(), None));
2465 features.declared_lib_features.push((name, mi.span()));
2472 fn for_each_in_lock<T>(vec: &Lock<Vec<T>>, f: impl Fn(&T)) {
2473 vec.borrow().iter().for_each(f);
2476 pub fn check_crate(krate: &ast::Crate,
2478 features: &Features,
2479 plugin_attributes: &[(Symbol, AttributeType)],
2480 unstable: UnstableFeatures) {
2481 maybe_stage_features(&sess.span_diagnostic, krate, unstable);
2488 for_each_in_lock(&sess.param_attr_spans, |span| gate_feature!(
2492 "attributes on function parameters are unstable"
2495 for_each_in_lock(&sess.let_chains_spans, |span| gate_feature!(
2499 "`let` expressions in this position are experimental"
2502 for_each_in_lock(&sess.async_closure_spans, |span| gate_feature!(
2506 "async closures are unstable"
2509 let visitor = &mut PostExpansionVisitor {
2511 builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP,
2513 visit::walk_crate(visitor, krate);
2516 #[derive(Clone, Copy, Hash)]
2517 pub enum UnstableFeatures {
2518 /// Hard errors for unstable features are active, as on beta/stable channels.
2520 /// Allow features to be activated, as on nightly.
2522 /// Errors are bypassed for bootstrapping. This is required any time
2523 /// during the build that feature-related lints are set to warn or above
2524 /// because the build turns on warnings-as-errors and uses lots of unstable
2525 /// features. As a result, this is always required for building Rust itself.
2529 impl UnstableFeatures {
2530 pub fn from_environment() -> UnstableFeatures {
2531 // Whether this is a feature-staged build, i.e., on the beta or stable channel
2532 let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
2533 // Whether we should enable unstable features for bootstrapping
2534 let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok();
2535 match (disable_unstable_features, bootstrap) {
2536 (_, true) => UnstableFeatures::Cheat,
2537 (true, _) => UnstableFeatures::Disallow,
2538 (false, _) => UnstableFeatures::Allow
2542 pub fn is_nightly_build(&self) -> bool {
2544 UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
2550 fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate,
2551 unstable: UnstableFeatures) {
2552 let allow_features = match unstable {
2553 UnstableFeatures::Allow => true,
2554 UnstableFeatures::Disallow => false,
2555 UnstableFeatures::Cheat => true
2557 if !allow_features {
2558 for attr in &krate.attrs {
2559 if attr.check_name(sym::feature) {
2560 let release_channel = option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)");
2561 span_err!(span_handler, attr.span, E0554,
2562 "`#![feature]` may not be used on the {} release channel",