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,
23 use crate::early_buffered_lints::BufferedEarlyLintId;
24 use crate::source_map::Spanned;
25 use crate::edition::{ALL_EDITIONS, Edition};
26 use crate::visit::{self, FnKind, Visitor};
27 use crate::parse::{token, ParseSess};
28 use crate::parse::parser::Parser;
29 use crate::symbol::{Symbol, sym};
30 use crate::tokenstream::TokenTree;
32 use errors::{Applicability, DiagnosticBuilder, Handler};
33 use rustc_data_structures::fx::FxHashMap;
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 the `rust-intrinsic`'s "ABI".
129 (active, intrinsics, "1.0.0", None, None),
131 // Allows using `#[lang = ".."]` attribute for linking items to special compiler logic.
132 (active, lang_items, "1.0.0", None, None),
134 // Allows using the `#[stable]` and `#[unstable]` attributes.
135 (active, staged_api, "1.0.0", None, None),
137 // Allows using `#[allow_internal_unstable]`. This is an
138 // attribute on `macro_rules!` and can't use the attribute handling
139 // below (it has to be checked before expansion possibly makes
140 // macros disappear).
141 (active, allow_internal_unstable, "1.0.0", None, None),
143 // Allows using `#[allow_internal_unsafe]`. This is an
144 // attribute on `macro_rules!` and can't use the attribute handling
145 // below (it has to be checked before expansion possibly makes
146 // macros disappear).
147 (active, allow_internal_unsafe, "1.0.0", None, None),
149 // Allows using the macros:
150 // + `__diagnostic_used`
151 // + `__register_diagnostic`
152 // +`__build_diagnostic_array`
153 (active, rustc_diagnostic_macros, "1.0.0", None, None),
155 // Allows using `#[rustc_const_unstable(feature = "foo", ..)]` which
156 // lets a function to be `const` when opted into with `#![feature(foo)]`.
157 (active, rustc_const_unstable, "1.0.0", None, None),
159 // no-tracking-issue-end
161 // Allows using `#[link_name="llvm.*"]`.
162 (active, link_llvm_intrinsics, "1.0.0", Some(29602), None),
164 // Allows using `rustc_*` attributes (RFC 572).
165 (active, rustc_attrs, "1.0.0", Some(29642), None),
167 // Allows using `#[on_unimplemented(..)]` on traits.
168 (active, on_unimplemented, "1.0.0", Some(29628), None),
170 // Allows using the `box $expr` syntax.
171 (active, box_syntax, "1.0.0", Some(49733), None),
173 // Allows using `#[main]` to replace the entrypoint `#[lang = "start"]` calls.
174 (active, main, "1.0.0", Some(29634), None),
176 // Allows using `#[start]` on a function indicating that it is the program entrypoint.
177 (active, start, "1.0.0", Some(29633), None),
179 // Allows using the `#[fundamental]` attribute.
180 (active, fundamental, "1.0.0", Some(29635), None),
182 // Allows using the `rust-call` ABI.
183 (active, unboxed_closures, "1.0.0", Some(29625), None),
185 // Allows using the `#[linkage = ".."]` attribute.
186 (active, linkage, "1.0.0", Some(29603), None),
188 // Allows features specific to OIBIT (auto traits).
189 (active, optin_builtin_traits, "1.0.0", Some(13231), None),
191 // Allows using `box` in patterns (RFC 469).
192 (active, box_patterns, "1.0.0", Some(29641), None),
194 // no-tracking-issue-start
196 // Allows using `#[prelude_import]` on glob `use` items.
197 (active, prelude_import, "1.2.0", None, None),
199 // no-tracking-issue-end
201 // Allows using `#[unsafe_destructor_blind_to_params]` (RFC 1238).
202 (active, dropck_parametricity, "1.3.0", Some(28498), None),
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", None, 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(23121), 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 paths to enum variants on type aliases.
534 (active, type_alias_enum_variants, "1.31.0", Some(49683), None),
536 // Allows exhaustive integer pattern matching on `usize` and `isize`.
537 (active, precise_pointer_size_matching, "1.32.0", Some(56354), None),
539 // Allows relaxing the coherence rules such that
540 // `impl<T> ForeignTrait<LocalType> for ForeignType<T> is permitted.
541 (active, re_rebalance_coherence, "1.32.0", Some(55437), None),
543 // Allows using `#[ffi_returns_twice]` on foreign functions.
544 (active, ffi_returns_twice, "1.34.0", Some(58314), None),
546 // Allows const generic types (e.g. `struct Foo<const N: usize>(...);`).
547 (active, const_generics, "1.34.0", Some(44580), None),
549 // Allows using `#[optimize(X)]`.
550 (active, optimize_attribute, "1.34.0", Some(54882), None),
552 // Allows using C-variadics.
553 (active, c_variadic, "1.34.0", Some(44930), None),
555 // Allows the user of associated type bounds.
556 (active, associated_type_bounds, "1.34.0", Some(52662), None),
558 // Attributes on formal function params.
559 (active, param_attrs, "1.36.0", Some(60406), None),
561 // Allows calling constructor functions in `const fn`.
562 (active, const_constructor, "1.37.0", Some(61456), None),
564 // Allows `if/while p && let q = r && ...` chains.
565 (active, let_chains, "1.37.0", Some(53667), None),
567 // #[repr(transparent)] on enums.
568 (active, transparent_enums, "1.37.0", Some(60405), None),
570 // #[repr(transparent)] on unions.
571 (active, transparent_unions, "1.37.0", Some(60405), None),
573 // Allows explicit discriminants on non-unit enum variants.
574 (active, arbitrary_enum_discriminant, "1.37.0", Some(60553), None),
576 // -------------------------------------------------------------------------
577 // feature-group-end: actual feature gates
578 // -------------------------------------------------------------------------
581 // Some features are known to be incomplete and using them is likely to have
582 // unanticipated results, such as compiler crashes. We warn the user about these
584 const INCOMPLETE_FEATURES: &[Symbol] = &[
585 sym::impl_trait_in_bindings,
586 sym::generic_associated_types,
592 // -------------------------------------------------------------------------
593 // feature-group-start: removed features
594 // -------------------------------------------------------------------------
596 (removed, import_shadowing, "1.0.0", None, None, None),
597 (removed, managed_boxes, "1.0.0", None, None, None),
598 // Allows use of unary negate on unsigned integers, e.g., -e for e: u8
599 (removed, negate_unsigned, "1.0.0", Some(29645), None, None),
600 (removed, reflect, "1.0.0", Some(27749), None, None),
601 // A way to temporarily opt out of opt in copy. This will *never* be accepted.
602 (removed, opt_out_copy, "1.0.0", None, None, None),
603 (removed, quad_precision_float, "1.0.0", None, None, None),
604 (removed, struct_inherit, "1.0.0", None, None, None),
605 (removed, test_removed_feature, "1.0.0", None, None, None),
606 (removed, visible_private_types, "1.0.0", None, None, None),
607 (removed, unsafe_no_drop_flag, "1.0.0", None, None, None),
608 // Allows using items which are missing stability attributes
609 (removed, unmarked_api, "1.0.0", None, None, None),
610 (removed, allocator, "1.0.0", None, None, None),
611 (removed, simd, "1.0.0", Some(27731), None,
612 Some("removed in favor of `#[repr(simd)]`")),
613 (removed, advanced_slice_patterns, "1.0.0", Some(23121), None,
614 Some("merged into `#![feature(slice_patterns)]`")),
615 (removed, macro_reexport, "1.0.0", Some(29638), None,
616 Some("subsumed by `pub use`")),
617 (removed, pushpop_unsafe, "1.2.0", None, None, None),
618 (removed, needs_allocator, "1.4.0", Some(27389), None,
619 Some("subsumed by `#![feature(allocator_internals)]`")),
620 (removed, proc_macro_mod, "1.27.0", Some(54727), None,
621 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
622 (removed, proc_macro_expr, "1.27.0", Some(54727), None,
623 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
624 (removed, proc_macro_non_items, "1.27.0", Some(54727), None,
625 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
626 (removed, proc_macro_gen, "1.27.0", Some(54727), None,
627 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
628 (removed, panic_implementation, "1.28.0", Some(44489), None,
629 Some("subsumed by `#[panic_handler]`")),
630 // Allows the use of `#[derive(Anything)]` as sugar for `#[derive_Anything]`.
631 (removed, custom_derive, "1.32.0", Some(29644), None,
632 Some("subsumed by `#[proc_macro_derive]`")),
633 // Paths of the form: `extern::foo::bar`
634 (removed, extern_in_paths, "1.33.0", Some(55600), None,
635 Some("subsumed by `::foo::bar` paths")),
636 (removed, quote, "1.33.0", Some(29601), None, None),
638 // -------------------------------------------------------------------------
639 // feature-group-end: removed features
640 // -------------------------------------------------------------------------
644 (stable_removed, no_stack_check, "1.0.0", None, None),
648 // -------------------------------------------------------------------------
649 // feature-group-start: for testing purposes
650 // -------------------------------------------------------------------------
652 // A temporary feature gate used to enable parser extensions needed
653 // to bootstrap fix for #5723.
654 (accepted, issue_5723_bootstrap, "1.0.0", None, None),
655 // These are used to test this portion of the compiler,
656 // they don't actually mean anything.
657 (accepted, test_accepted_feature, "1.0.0", None, None),
659 // -------------------------------------------------------------------------
660 // feature-group-end: for testing purposes
661 // -------------------------------------------------------------------------
663 // -------------------------------------------------------------------------
664 // feature-group-start: accepted features
665 // -------------------------------------------------------------------------
667 // Allows using associated `type`s in `trait`s.
668 (accepted, associated_types, "1.0.0", None, None),
669 // Allows using assigning a default type to type parameters in algebraic data type definitions.
670 (accepted, default_type_params, "1.0.0", None, None),
671 // FIXME: explain `globs`.
672 (accepted, globs, "1.0.0", None, None),
673 // Allows `macro_rules!` items.
674 (accepted, macro_rules, "1.0.0", None, None),
675 // Allows use of `&foo[a..b]` as a slicing syntax.
676 (accepted, slicing_syntax, "1.0.0", None, None),
677 // Allows struct variants `Foo { baz: u8, .. }` in enums (RFC 418).
678 (accepted, struct_variant, "1.0.0", None, None),
679 // Allows indexing tuples.
680 (accepted, tuple_indexing, "1.0.0", None, None),
681 // Allows the use of `if let` expressions.
682 (accepted, if_let, "1.0.0", None, None),
683 // Allows the use of `while let` expressions.
684 (accepted, while_let, "1.0.0", None, None),
685 // Allows using `#![no_std]`.
686 (accepted, no_std, "1.6.0", None, None),
687 // Allows overloading augmented assignment operations like `a += b`.
688 (accepted, augmented_assignments, "1.8.0", Some(28235), None),
689 // Allows empty structs and enum variants with braces.
690 (accepted, braced_empty_structs, "1.8.0", Some(29720), None),
691 // Allows `#[deprecated]` attribute.
692 (accepted, deprecated, "1.9.0", Some(29935), None),
693 // Allows macros to appear in the type position.
694 (accepted, type_macros, "1.13.0", Some(27245), None),
695 // Allows use of the postfix `?` operator in expressions.
696 (accepted, question_mark, "1.13.0", Some(31436), None),
697 // Allows `..` in tuple (struct) patterns.
698 (accepted, dotdot_in_tuple_patterns, "1.14.0", Some(33627), None),
699 // Allows some increased flexibility in the name resolution rules,
700 // especially around globs and shadowing (RFC 1560).
701 (accepted, item_like_imports, "1.15.0", Some(35120), None),
702 // Allows using `Self` and associated types in struct expressions and patterns.
703 (accepted, more_struct_aliases, "1.16.0", Some(37544), None),
704 // Allows elision of `'static` lifetimes in `static`s and `const`s.
705 (accepted, static_in_const, "1.17.0", Some(35897), None),
706 // Allows field shorthands (`x` meaning `x: x`) in struct literal expressions.
707 (accepted, field_init_shorthand, "1.17.0", Some(37340), None),
708 // Allows the definition recursive static items.
709 (accepted, static_recursion, "1.17.0", Some(29719), None),
710 // Allows `pub(restricted)` visibilities (RFC 1422).
711 (accepted, pub_restricted, "1.18.0", Some(32409), None),
712 // Allows `#![windows_subsystem]`.
713 (accepted, windows_subsystem, "1.18.0", Some(37499), None),
714 // Allows `break {expr}` with a value inside `loop`s.
715 (accepted, loop_break_value, "1.19.0", Some(37339), None),
716 // Allows numeric fields in struct expressions and patterns.
717 (accepted, relaxed_adts, "1.19.0", Some(35626), None),
718 // Allows coercing non capturing closures to function pointers.
719 (accepted, closure_to_fn_coercion, "1.19.0", Some(39817), None),
720 // Allows attributes on struct literal fields.
721 (accepted, struct_field_attributes, "1.20.0", Some(38814), None),
722 // Allows the definition of associated constants in `trait` or `impl` blocks.
723 (accepted, associated_consts, "1.20.0", Some(29646), None),
724 // Allows usage of the `compile_error!` macro.
725 (accepted, compile_error, "1.20.0", Some(40872), None),
726 // Allows code like `let x: &'static u32 = &42` to work (RFC 1414).
727 (accepted, rvalue_static_promotion, "1.21.0", Some(38865), None),
728 // Allows `Drop` types in constants (RFC 1440).
729 (accepted, drop_types_in_const, "1.22.0", Some(33156), None),
730 // Allows the sysV64 ABI to be specified on all platforms
731 // instead of just the platforms on which it is the C ABI.
732 (accepted, abi_sysv64, "1.24.0", Some(36167), None),
733 // Allows `repr(align(16))` struct attribute (RFC 1358).
734 (accepted, repr_align, "1.25.0", Some(33626), None),
735 // Allows '|' at beginning of match arms (RFC 1925).
736 (accepted, match_beginning_vert, "1.25.0", Some(44101), None),
737 // Allows nested groups in `use` items (RFC 2128).
738 (accepted, use_nested_groups, "1.25.0", Some(44494), None),
739 // Allows indexing into constant arrays.
740 (accepted, const_indexing, "1.26.0", Some(29947), None),
741 // Allows using `a..=b` and `..=b` as inclusive range syntaxes.
742 (accepted, inclusive_range_syntax, "1.26.0", Some(28237), None),
743 // Allows `..=` in patterns (RFC 1192).
744 (accepted, dotdoteq_in_patterns, "1.26.0", Some(28237), None),
745 // Allows `fn main()` with return types which implements `Termination` (RFC 1937).
746 (accepted, termination_trait, "1.26.0", Some(43301), None),
747 // Allows implementing `Clone` for closures where possible (RFC 2132).
748 (accepted, clone_closures, "1.26.0", Some(44490), None),
749 // Allows implementing `Copy` for closures where possible (RFC 2132).
750 (accepted, copy_closures, "1.26.0", Some(44490), None),
751 // Allows `impl Trait` in function arguments.
752 (accepted, universal_impl_trait, "1.26.0", Some(34511), None),
753 // Allows `impl Trait` in function return types.
754 (accepted, conservative_impl_trait, "1.26.0", Some(34511), None),
755 // Allows using the `u128` and `i128` types.
756 (accepted, i128_type, "1.26.0", Some(35118), None),
757 // Allows default match binding modes (RFC 2005).
758 (accepted, match_default_bindings, "1.26.0", Some(42640), None),
759 // Allows `'_` placeholder lifetimes.
760 (accepted, underscore_lifetimes, "1.26.0", Some(44524), None),
761 // Allows attributes on lifetime/type formal parameters in generics (RFC 1327).
762 (accepted, generic_param_attrs, "1.27.0", Some(48848), None),
763 // Allows `cfg(target_feature = "...")`.
764 (accepted, cfg_target_feature, "1.27.0", Some(29717), None),
765 // Allows `#[target_feature(...)]`.
766 (accepted, target_feature, "1.27.0", None, None),
767 // Allows using `dyn Trait` as a syntax for trait objects.
768 (accepted, dyn_trait, "1.27.0", Some(44662), None),
769 // Allows `#[must_use]` on functions, and introduces must-use operators (RFC 1940).
770 (accepted, fn_must_use, "1.27.0", Some(43302), None),
771 // Allows use of the `:lifetime` macro fragment specifier.
772 (accepted, macro_lifetime_matcher, "1.27.0", Some(34303), None),
773 // Allows `#[test]` functions where the return type implements `Termination` (RFC 1937).
774 (accepted, termination_trait_test, "1.27.0", Some(48854), None),
775 // Allows the `#[global_allocator]` attribute.
776 (accepted, global_allocator, "1.28.0", Some(27389), None),
777 // Allows `#[repr(transparent)]` attribute on newtype structs.
778 (accepted, repr_transparent, "1.28.0", Some(43036), None),
779 // Allows procedural macros in `proc-macro` crates.
780 (accepted, proc_macro, "1.29.0", Some(38356), None),
781 // Allows `foo.rs` as an alternative to `foo/mod.rs`.
782 (accepted, non_modrs_mods, "1.30.0", Some(44660), None),
783 // Allows use of the `:vis` macro fragment specifier
784 (accepted, macro_vis_matcher, "1.30.0", Some(41022), None),
785 // Allows importing and reexporting macros with `use`,
786 // enables macro modularization in general.
787 (accepted, use_extern_macros, "1.30.0", Some(35896), None),
788 // Allows keywords to be escaped for use as identifiers.
789 (accepted, raw_identifiers, "1.30.0", Some(48589), None),
790 // Allows attributes scoped to tools.
791 (accepted, tool_attributes, "1.30.0", Some(44690), None),
792 // Allows multi-segment paths in attributes and derives.
793 (accepted, proc_macro_path_invoc, "1.30.0", Some(38356), None),
794 // Allows all literals in attribute lists and values of key-value pairs.
795 (accepted, attr_literals, "1.30.0", Some(34981), None),
796 // Allows inferring outlives requirements (RFC 2093).
797 (accepted, infer_outlives_requirements, "1.30.0", Some(44493), None),
798 // Allows annotating functions conforming to `fn(&PanicInfo) -> !` with `#[panic_handler]`.
799 // This defines the behavior of panics.
800 (accepted, panic_handler, "1.30.0", Some(44489), None),
801 // Allows `#[used]` to preserve symbols (see llvm.used).
802 (accepted, used, "1.30.0", Some(40289), None),
803 // Allows `crate` in paths.
804 (accepted, crate_in_paths, "1.30.0", Some(45477), None),
805 // Allows resolving absolute paths as paths from other crates.
806 (accepted, extern_absolute_paths, "1.30.0", Some(44660), None),
807 // Allows access to crate names passed via `--extern` through prelude.
808 (accepted, extern_prelude, "1.30.0", Some(44660), None),
809 // Allows parentheses in patterns.
810 (accepted, pattern_parentheses, "1.31.0", Some(51087), None),
811 // Allows the definition of `const fn` functions.
812 (accepted, min_const_fn, "1.31.0", Some(53555), None),
813 // Allows scoped lints.
814 (accepted, tool_lints, "1.31.0", Some(44690), None),
815 // Allows lifetime elision in `impl` headers. For example:
816 // + `impl<I:Iterator> Iterator for &mut Iterator`
817 // + `impl Debug for Foo<'_>`
818 (accepted, impl_header_lifetime_elision, "1.31.0", Some(15872), None),
819 // Allows `extern crate foo as bar;`. This puts `bar` into extern prelude.
820 (accepted, extern_crate_item_prelude, "1.31.0", Some(55599), None),
821 // Allows use of the `:literal` macro fragment specifier (RFC 1576).
822 (accepted, macro_literal_matcher, "1.32.0", Some(35625), None),
823 // Allows use of `?` as the Kleene "at most one" operator in macros.
824 (accepted, macro_at_most_once_rep, "1.32.0", Some(48075), None),
825 // Allows `Self` struct constructor (RFC 2302).
826 (accepted, self_struct_ctor, "1.32.0", Some(51994), None),
827 // Allows `Self` in type definitions (RFC 2300).
828 (accepted, self_in_typedefs, "1.32.0", Some(49303), None),
829 // Allows `use x::y;` to search `x` in the current scope.
830 (accepted, uniform_paths, "1.32.0", Some(53130), None),
831 // Allows integer match exhaustiveness checking (RFC 2591).
832 (accepted, exhaustive_integer_patterns, "1.33.0", Some(50907), None),
833 // Allows `use path as _;` and `extern crate c as _;`.
834 (accepted, underscore_imports, "1.33.0", Some(48216), None),
835 // Allows `#[repr(packed(N))]` attribute on structs.
836 (accepted, repr_packed, "1.33.0", Some(33158), None),
837 // Allows irrefutable patterns in `if let` and `while let` statements (RFC 2086).
838 (accepted, irrefutable_let_patterns, "1.33.0", Some(44495), None),
839 // Allows calling `const unsafe fn` inside `unsafe` blocks in `const fn` functions.
840 (accepted, min_const_unsafe_fn, "1.33.0", Some(55607), None),
841 // Allows let bindings, assignments and destructuring in `const` functions and constants.
842 // As long as control flow is not implemented in const eval, `&&` and `||` may not be used
843 // at the same time as let bindings.
844 (accepted, const_let, "1.33.0", Some(48821), None),
845 // Allows `#[cfg_attr(predicate, multiple, attributes, here)]`.
846 (accepted, cfg_attr_multi, "1.33.0", Some(54881), None),
847 // Allows top level or-patterns (`p | q`) in `if let` and `while let`.
848 (accepted, if_while_or_patterns, "1.33.0", Some(48215), None),
849 // Allows `cfg(target_vendor = "...")`.
850 (accepted, cfg_target_vendor, "1.33.0", Some(29718), None),
851 // Allows `extern crate self as foo;`.
852 // This puts local crate root into extern prelude under name `foo`.
853 (accepted, extern_crate_self, "1.34.0", Some(56409), None),
854 // Allows arbitrary delimited token streams in non-macro attributes.
855 (accepted, unrestricted_attribute_tokens, "1.34.0", Some(55208), None),
856 // Allows using `#[repr(align(X))]` on enums with equivalent semantics
857 // to wrapping an enum in a wrapper struct with `#[repr(align(X))]`.
858 (accepted, repr_align_enum, "1.37.0", Some(57996), None),
859 // Allows `const _: TYPE = VALUE`.
860 (accepted, underscore_const_names, "1.37.0", Some(54912), None),
862 // -------------------------------------------------------------------------
863 // feature-group-end: accepted features
864 // -------------------------------------------------------------------------
867 // If you change this, please modify `src/doc/unstable-book` as well. You must
868 // move that documentation into the relevant place in the other docs, and
869 // remove the chapter on the flag.
871 #[derive(Copy, Clone, PartialEq, Debug)]
872 pub enum AttributeType {
873 /// Normal, builtin attribute that is consumed
874 /// by the compiler before the unused_attribute check
877 /// Builtin attribute that may not be consumed by the compiler
878 /// before the unused_attribute check. These attributes
879 /// will be ignored by the unused_attribute lint
882 /// Builtin attribute that is only allowed at the crate level
886 pub enum AttributeGate {
887 /// Is gated by a given feature gate, reason
888 /// and function to check if enabled
889 Gated(Stability, Symbol, &'static str, fn(&Features) -> bool),
891 /// Ungated attribute, can be used on all release channels
895 /// A template that the attribute input must match.
896 /// Only top-level shape (`#[attr]` vs `#[attr(...)]` vs `#[attr = ...]`) is considered now.
897 #[derive(Clone, Copy)]
898 pub struct AttributeTemplate {
900 list: Option<&'static str>,
901 name_value_str: Option<&'static str>,
904 impl AttributeTemplate {
905 /// Checks that the given meta-item is compatible with this template.
906 fn compatible(&self, meta_item_kind: &ast::MetaItemKind) -> bool {
907 match meta_item_kind {
908 ast::MetaItemKind::Word => self.word,
909 ast::MetaItemKind::List(..) => self.list.is_some(),
910 ast::MetaItemKind::NameValue(lit) if lit.node.is_str() => self.name_value_str.is_some(),
911 ast::MetaItemKind::NameValue(..) => false,
916 /// A convenience macro for constructing attribute templates.
917 /// E.g., `template!(Word, List: "description")` means that the attribute
918 /// supports forms `#[attr]` and `#[attr(description)]`.
919 macro_rules! template {
920 (Word) => { template!(@ true, None, None) };
921 (List: $descr: expr) => { template!(@ false, Some($descr), None) };
922 (NameValueStr: $descr: expr) => { template!(@ false, None, Some($descr)) };
923 (Word, List: $descr: expr) => { template!(@ true, Some($descr), None) };
924 (Word, NameValueStr: $descr: expr) => { template!(@ true, None, Some($descr)) };
925 (List: $descr1: expr, NameValueStr: $descr2: expr) => {
926 template!(@ false, Some($descr1), Some($descr2))
928 (Word, List: $descr1: expr, NameValueStr: $descr2: expr) => {
929 template!(@ true, Some($descr1), Some($descr2))
931 (@ $word: expr, $list: expr, $name_value_str: expr) => { AttributeTemplate {
932 word: $word, list: $list, name_value_str: $name_value_str
937 fn is_deprecated(&self) -> bool {
939 Gated(Stability::Deprecated(_, _), ..) => true,
945 #[derive(Copy, Clone, Debug)]
948 // First argument is tracking issue link; second argument is an optional
949 // help message, which defaults to "remove this attribute"
950 Deprecated(&'static str, Option<&'static str>),
954 impl std::fmt::Debug for AttributeGate {
955 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
957 Gated(ref stab, name, expl, _) =>
958 write!(fmt, "Gated({:?}, {}, {})", stab, name, expl),
959 Ungated => write!(fmt, "Ungated")
964 macro_rules! cfg_fn {
965 ($field: ident) => {{
966 fn f(features: &Features) -> bool {
969 f as fn(&Features) -> bool
973 pub fn deprecated_attributes() -> Vec<&'static (Symbol, AttributeType,
974 AttributeTemplate, AttributeGate)> {
975 BUILTIN_ATTRIBUTES.iter().filter(|(.., gate)| gate.is_deprecated()).collect()
978 pub fn is_builtin_attr_name(name: ast::Name) -> bool {
979 BUILTIN_ATTRIBUTE_MAP.get(&name).is_some()
982 pub fn is_builtin_attr(attr: &ast::Attribute) -> bool {
983 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)).is_some()
986 /// Attributes that have a special meaning to rustc or rustdoc
987 pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
993 template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#),
999 template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#),
1005 template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#),
1011 template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#),
1015 (sym::macro_use, Normal, template!(Word, List: "name1, name2, ..."), Ungated),
1016 (sym::macro_export, Normal, template!(Word, List: "local_inner_macros"), Ungated),
1017 (sym::plugin_registrar, Normal, template!(Word), Ungated),
1019 (sym::cfg, Normal, template!(List: "predicate"), Ungated),
1020 (sym::cfg_attr, Normal, template!(List: "predicate, attr1, attr2, ..."), Ungated),
1021 (sym::main, Normal, template!(Word), Ungated),
1022 (sym::start, Normal, template!(Word), Ungated),
1023 (sym::repr, Normal, template!(List: "C, packed, ..."), Ungated),
1024 (sym::path, Normal, template!(NameValueStr: "file"), Ungated),
1025 (sym::automatically_derived, Normal, template!(Word), Ungated),
1026 (sym::no_mangle, Whitelisted, template!(Word), Ungated),
1027 (sym::no_link, Normal, template!(Word), Ungated),
1028 (sym::derive, Normal, template!(List: "Trait1, Trait2, ..."), Ungated),
1032 template!(Word, List: r#"expected = "reason"#, NameValueStr: "reason"),
1035 (sym::ignore, Normal, template!(Word, NameValueStr: "reason"), Ungated),
1036 (sym::no_implicit_prelude, Normal, template!(Word), Ungated),
1037 (sym::reexport_test_harness_main, Normal, template!(NameValueStr: "name"), Ungated),
1038 (sym::link_args, Normal, template!(NameValueStr: "args"), Gated(Stability::Unstable,
1040 "the `link_args` attribute is experimental and not \
1041 portable across platforms, it is recommended to \
1042 use `#[link(name = \"foo\")] instead",
1043 cfg_fn!(link_args))),
1044 (sym::macro_escape, Normal, template!(Word), Ungated),
1047 (sym::structural_match, Whitelisted, template!(Word), Gated(Stability::Unstable,
1048 sym::structural_match,
1049 "the semantics of constant patterns is \
1051 cfg_fn!(structural_match))),
1054 (sym::non_exhaustive, Whitelisted, template!(Word), Gated(Stability::Unstable,
1055 sym::non_exhaustive,
1056 "non exhaustive is an experimental feature",
1057 cfg_fn!(non_exhaustive))),
1060 (sym::marker, Normal, template!(Word), Gated(Stability::Unstable,
1061 sym::marker_trait_attr,
1062 "marker traits is an experimental feature",
1063 cfg_fn!(marker_trait_attr))),
1065 (sym::plugin, CrateLevel, template!(List: "name|name(args)"), Gated(Stability::Unstable,
1067 "compiler plugins are experimental \
1068 and possibly buggy",
1071 (sym::no_std, CrateLevel, template!(Word), Ungated),
1072 (sym::no_core, CrateLevel, template!(Word), Gated(Stability::Unstable,
1074 "no_core is experimental",
1076 (sym::lang, Normal, template!(NameValueStr: "name"), Gated(Stability::Unstable,
1078 "language items are subject to change",
1079 cfg_fn!(lang_items))),
1080 (sym::linkage, Whitelisted, template!(NameValueStr: "external|internal|..."),
1081 Gated(Stability::Unstable,
1083 "the `linkage` attribute is experimental \
1084 and not portable across platforms",
1086 (sym::thread_local, Whitelisted, template!(Word), Gated(Stability::Unstable,
1088 "`#[thread_local]` is an experimental feature, and does \
1089 not currently handle destructors",
1090 cfg_fn!(thread_local))),
1092 (sym::rustc_on_unimplemented, Whitelisted, template!(List:
1093 r#"/*opt*/ message = "...", /*opt*/ label = "...", /*opt*/ note = "...""#,
1094 NameValueStr: "message"),
1095 Gated(Stability::Unstable,
1096 sym::on_unimplemented,
1097 "the `#[rustc_on_unimplemented]` attribute \
1098 is an experimental feature",
1099 cfg_fn!(on_unimplemented))),
1100 (sym::rustc_const_unstable, Normal, template!(List: r#"feature = "name""#),
1101 Gated(Stability::Unstable,
1102 sym::rustc_const_unstable,
1103 "the `#[rustc_const_unstable]` attribute \
1104 is an internal feature",
1105 cfg_fn!(rustc_const_unstable))),
1106 (sym::global_allocator, Normal, template!(Word), Ungated),
1107 (sym::default_lib_allocator, Whitelisted, template!(Word), Gated(Stability::Unstable,
1108 sym::allocator_internals,
1109 "the `#[default_lib_allocator]` \
1110 attribute is an experimental feature",
1111 cfg_fn!(allocator_internals))),
1112 (sym::needs_allocator, Normal, template!(Word), Gated(Stability::Unstable,
1113 sym::allocator_internals,
1114 "the `#[needs_allocator]` \
1115 attribute is an experimental \
1117 cfg_fn!(allocator_internals))),
1118 (sym::panic_runtime, Whitelisted, template!(Word), Gated(Stability::Unstable,
1120 "the `#[panic_runtime]` attribute is \
1121 an experimental feature",
1122 cfg_fn!(panic_runtime))),
1123 (sym::needs_panic_runtime, Whitelisted, template!(Word), Gated(Stability::Unstable,
1124 sym::needs_panic_runtime,
1125 "the `#[needs_panic_runtime]` \
1126 attribute is an experimental \
1128 cfg_fn!(needs_panic_runtime))),
1129 (sym::rustc_outlives, Normal, template!(Word), Gated(Stability::Unstable,
1131 "the `#[rustc_outlives]` attribute \
1132 is just used for rustc unit tests \
1133 and will never be stable",
1134 cfg_fn!(rustc_attrs))),
1135 (sym::rustc_variance, Normal, template!(Word), Gated(Stability::Unstable,
1137 "the `#[rustc_variance]` attribute \
1138 is just used for rustc unit tests \
1139 and will never be stable",
1140 cfg_fn!(rustc_attrs))),
1141 (sym::rustc_layout, Normal, template!(List: "field1, field2, ..."),
1142 Gated(Stability::Unstable,
1144 "the `#[rustc_layout]` attribute \
1145 is just used for rustc unit tests \
1146 and will never be stable",
1147 cfg_fn!(rustc_attrs))),
1148 (sym::rustc_layout_scalar_valid_range_start, Whitelisted, template!(List: "value"),
1149 Gated(Stability::Unstable,
1151 "the `#[rustc_layout_scalar_valid_range_start]` attribute \
1152 is just used to enable niche optimizations in libcore \
1153 and will never be stable",
1154 cfg_fn!(rustc_attrs))),
1155 (sym::rustc_layout_scalar_valid_range_end, Whitelisted, template!(List: "value"),
1156 Gated(Stability::Unstable,
1158 "the `#[rustc_layout_scalar_valid_range_end]` attribute \
1159 is just used to enable niche optimizations in libcore \
1160 and will never be stable",
1161 cfg_fn!(rustc_attrs))),
1162 (sym::rustc_nonnull_optimization_guaranteed, Whitelisted, template!(Word),
1163 Gated(Stability::Unstable,
1165 "the `#[rustc_nonnull_optimization_guaranteed]` attribute \
1166 is just used to enable niche optimizations in libcore \
1167 and will never be stable",
1168 cfg_fn!(rustc_attrs))),
1169 (sym::rustc_regions, Normal, template!(Word), Gated(Stability::Unstable,
1171 "the `#[rustc_regions]` attribute \
1172 is just used for rustc unit tests \
1173 and will never be stable",
1174 cfg_fn!(rustc_attrs))),
1175 (sym::rustc_error, Whitelisted, template!(Word), Gated(Stability::Unstable,
1177 "the `#[rustc_error]` attribute \
1178 is just used for rustc unit tests \
1179 and will never be stable",
1180 cfg_fn!(rustc_attrs))),
1181 (sym::rustc_dump_user_substs, Whitelisted, template!(Word), Gated(Stability::Unstable,
1184 is just used for rustc unit tests \
1185 and will never be stable",
1186 cfg_fn!(rustc_attrs))),
1187 (sym::rustc_if_this_changed, Whitelisted, template!(Word, List: "DepNode"),
1188 Gated(Stability::Unstable,
1190 "the `#[rustc_if_this_changed]` attribute \
1191 is just used for rustc unit tests \
1192 and will never be stable",
1193 cfg_fn!(rustc_attrs))),
1194 (sym::rustc_then_this_would_need, Whitelisted, template!(List: "DepNode"),
1195 Gated(Stability::Unstable,
1197 "the `#[rustc_if_this_changed]` attribute \
1198 is just used for rustc unit tests \
1199 and will never be stable",
1200 cfg_fn!(rustc_attrs))),
1201 (sym::rustc_dirty, Whitelisted, template!(List: r#"cfg = "...", /*opt*/ label = "...",
1202 /*opt*/ except = "...""#),
1203 Gated(Stability::Unstable,
1205 "the `#[rustc_dirty]` attribute \
1206 is just used for rustc unit tests \
1207 and will never be stable",
1208 cfg_fn!(rustc_attrs))),
1209 (sym::rustc_clean, Whitelisted, template!(List: r#"cfg = "...", /*opt*/ label = "...",
1210 /*opt*/ except = "...""#),
1211 Gated(Stability::Unstable,
1213 "the `#[rustc_clean]` attribute \
1214 is just used for rustc unit tests \
1215 and will never be stable",
1216 cfg_fn!(rustc_attrs))),
1218 sym::rustc_partition_reused,
1220 template!(List: r#"cfg = "...", module = "...""#),
1222 Stability::Unstable,
1225 is just used for rustc unit tests \
1226 and will never be stable",
1227 cfg_fn!(rustc_attrs)
1231 sym::rustc_partition_codegened,
1233 template!(List: r#"cfg = "...", module = "...""#),
1235 Stability::Unstable,
1238 is just used for rustc unit tests \
1239 and will never be stable",
1240 cfg_fn!(rustc_attrs),
1243 (sym::rustc_expected_cgu_reuse, Whitelisted, template!(List: r#"cfg = "...", module = "...",
1245 Gated(Stability::Unstable,
1248 is just used for rustc unit tests \
1249 and will never be stable",
1250 cfg_fn!(rustc_attrs))),
1251 (sym::rustc_synthetic, Whitelisted, template!(Word), Gated(Stability::Unstable,
1254 is just used for rustc unit tests \
1255 and will never be stable",
1256 cfg_fn!(rustc_attrs))),
1257 (sym::rustc_symbol_name, Whitelisted, template!(Word), Gated(Stability::Unstable,
1259 "internal rustc attributes will never be stable",
1260 cfg_fn!(rustc_attrs))),
1261 (sym::rustc_def_path, Whitelisted, template!(Word), Gated(Stability::Unstable,
1263 "internal rustc attributes will never be stable",
1264 cfg_fn!(rustc_attrs))),
1265 (sym::rustc_mir, Whitelisted, template!(List: "arg1, arg2, ..."), Gated(Stability::Unstable,
1267 "the `#[rustc_mir]` attribute \
1268 is just used for rustc unit tests \
1269 and will never be stable",
1270 cfg_fn!(rustc_attrs))),
1272 sym::rustc_inherit_overflow_checks,
1276 Stability::Unstable,
1278 "the `#[rustc_inherit_overflow_checks]` \
1279 attribute is just used to control \
1280 overflow checking behavior of several \
1281 libcore functions that are inlined \
1282 across crates and will never be stable",
1283 cfg_fn!(rustc_attrs),
1287 (sym::rustc_dump_program_clauses, Whitelisted, template!(Word), Gated(Stability::Unstable,
1289 "the `#[rustc_dump_program_clauses]` \
1290 attribute is just used for rustc unit \
1291 tests and will never be stable",
1292 cfg_fn!(rustc_attrs))),
1293 (sym::rustc_dump_env_program_clauses, Whitelisted, template!(Word), Gated(Stability::Unstable,
1295 "the `#[rustc_dump_env_program_clauses]` \
1296 attribute is just used for rustc unit \
1297 tests and will never be stable",
1298 cfg_fn!(rustc_attrs))),
1299 (sym::rustc_object_lifetime_default, Whitelisted, template!(Word), Gated(Stability::Unstable,
1301 "the `#[rustc_object_lifetime_default]` \
1302 attribute is just used for rustc unit \
1303 tests and will never be stable",
1304 cfg_fn!(rustc_attrs))),
1305 (sym::rustc_test_marker, Normal, template!(Word), Gated(Stability::Unstable,
1307 "the `#[rustc_test_marker]` attribute \
1308 is used internally to track tests",
1309 cfg_fn!(rustc_attrs))),
1310 (sym::rustc_transparent_macro, Whitelisted, template!(Word), Gated(Stability::Unstable,
1312 "used internally for testing macro hygiene",
1313 cfg_fn!(rustc_attrs))),
1314 (sym::compiler_builtins, Whitelisted, template!(Word), Gated(Stability::Unstable,
1315 sym::compiler_builtins,
1316 "the `#[compiler_builtins]` attribute is used to \
1317 identify the `compiler_builtins` crate which \
1318 contains compiler-rt intrinsics and will never be \
1320 cfg_fn!(compiler_builtins))),
1321 (sym::sanitizer_runtime, Whitelisted, template!(Word), Gated(Stability::Unstable,
1322 sym::sanitizer_runtime,
1323 "the `#[sanitizer_runtime]` attribute is used to \
1324 identify crates that contain the runtime of a \
1325 sanitizer and will never be stable",
1326 cfg_fn!(sanitizer_runtime))),
1327 (sym::profiler_runtime, Whitelisted, template!(Word), Gated(Stability::Unstable,
1328 sym::profiler_runtime,
1329 "the `#[profiler_runtime]` attribute is used to \
1330 identify the `profiler_builtins` crate which \
1331 contains the profiler runtime and will never be \
1333 cfg_fn!(profiler_runtime))),
1335 (sym::allow_internal_unstable, Normal, template!(Word, List: "feat1, feat2, ..."),
1336 Gated(Stability::Unstable,
1337 sym::allow_internal_unstable,
1338 EXPLAIN_ALLOW_INTERNAL_UNSTABLE,
1339 cfg_fn!(allow_internal_unstable))),
1341 (sym::allow_internal_unsafe, Normal, template!(Word), Gated(Stability::Unstable,
1342 sym::allow_internal_unsafe,
1343 EXPLAIN_ALLOW_INTERNAL_UNSAFE,
1344 cfg_fn!(allow_internal_unsafe))),
1346 (sym::fundamental, Whitelisted, template!(Word), Gated(Stability::Unstable,
1348 "the `#[fundamental]` attribute \
1349 is an experimental feature",
1350 cfg_fn!(fundamental))),
1352 (sym::proc_macro_derive, Normal, template!(List: "TraitName, \
1353 /*opt*/ attributes(name1, name2, ...)"),
1356 (sym::rustc_copy_clone_marker, Whitelisted, template!(Word), Gated(Stability::Unstable,
1358 "internal implementation detail",
1359 cfg_fn!(rustc_attrs))),
1361 (sym::rustc_allocator, Whitelisted, template!(Word), Gated(Stability::Unstable,
1363 "internal implementation detail",
1364 cfg_fn!(rustc_attrs))),
1366 (sym::rustc_allocator_nounwind, Whitelisted, template!(Word), Gated(Stability::Unstable,
1368 "internal implementation detail",
1369 cfg_fn!(rustc_attrs))),
1371 (sym::rustc_doc_only_macro, Whitelisted, template!(Word), Gated(Stability::Unstable,
1373 "internal implementation detail",
1374 cfg_fn!(rustc_attrs))),
1376 (sym::rustc_promotable, Whitelisted, template!(Word), Gated(Stability::Unstable,
1378 "internal implementation detail",
1379 cfg_fn!(rustc_attrs))),
1381 (sym::rustc_allow_const_fn_ptr, Whitelisted, template!(Word), Gated(Stability::Unstable,
1383 "internal implementation detail",
1384 cfg_fn!(rustc_attrs))),
1386 (sym::rustc_dummy, Normal, template!(Word /* doesn't matter*/), Gated(Stability::Unstable,
1388 "used by the test suite",
1389 cfg_fn!(rustc_attrs))),
1391 // FIXME: #14408 whitelist docs since rustdoc looks at them
1395 template!(List: "hidden|inline|...", NameValueStr: "string"),
1399 // FIXME: #14406 these are processed in codegen, which happens after the
1401 (sym::cold, Whitelisted, template!(Word), Ungated),
1402 (sym::naked, Whitelisted, template!(Word), Gated(Stability::Unstable,
1403 sym::naked_functions,
1404 "the `#[naked]` attribute \
1405 is an experimental feature",
1406 cfg_fn!(naked_functions))),
1407 (sym::ffi_returns_twice, Whitelisted, template!(Word), Gated(Stability::Unstable,
1408 sym::ffi_returns_twice,
1409 "the `#[ffi_returns_twice]` attribute \
1410 is an experimental feature",
1411 cfg_fn!(ffi_returns_twice))),
1412 (sym::target_feature, Whitelisted, template!(List: r#"enable = "name""#), Ungated),
1413 (sym::export_name, Whitelisted, template!(NameValueStr: "name"), Ungated),
1414 (sym::inline, Whitelisted, template!(Word, List: "always|never"), Ungated),
1415 (sym::link, Whitelisted, template!(List: r#"name = "...", /*opt*/ kind = "dylib|static|...",
1416 /*opt*/ cfg = "...""#), Ungated),
1417 (sym::link_name, Whitelisted, template!(NameValueStr: "name"), Ungated),
1418 (sym::link_section, Whitelisted, template!(NameValueStr: "name"), Ungated),
1419 (sym::no_builtins, Whitelisted, template!(Word), Ungated),
1420 (sym::no_debug, Whitelisted, template!(Word), Gated(
1421 Stability::Deprecated("https://github.com/rust-lang/rust/issues/29721", None),
1423 "the `#[no_debug]` attribute was an experimental feature that has been \
1424 deprecated due to lack of demand",
1425 cfg_fn!(no_debug))),
1427 sym::omit_gdb_pretty_printer_section,
1431 Stability::Unstable,
1432 sym::omit_gdb_pretty_printer_section,
1433 "the `#[omit_gdb_pretty_printer_section]` \
1434 attribute is just used for the Rust test \
1436 cfg_fn!(omit_gdb_pretty_printer_section)
1439 (sym::unsafe_destructor_blind_to_params,
1442 Gated(Stability::Deprecated("https://github.com/rust-lang/rust/issues/34761",
1443 Some("replace this attribute with `#[may_dangle]`")),
1444 sym::dropck_parametricity,
1445 "unsafe_destructor_blind_to_params has been replaced by \
1446 may_dangle and will be removed in the future",
1447 cfg_fn!(dropck_parametricity))),
1451 Gated(Stability::Unstable,
1452 sym::dropck_eyepatch,
1453 "may_dangle has unstable semantics and may be removed in the future",
1454 cfg_fn!(dropck_eyepatch))),
1455 (sym::unwind, Whitelisted, template!(List: "allowed|aborts"), Gated(Stability::Unstable,
1456 sym::unwind_attributes,
1457 "#[unwind] is experimental",
1458 cfg_fn!(unwind_attributes))),
1459 (sym::used, Whitelisted, template!(Word), Ungated),
1462 (sym::prelude_import, Whitelisted, template!(Word), Gated(Stability::Unstable,
1463 sym::prelude_import,
1464 "`#[prelude_import]` is for use by rustc only",
1465 cfg_fn!(prelude_import))),
1467 // FIXME: #14407 these are only looked at on-demand so we can't
1468 // guarantee they'll have already been checked
1470 sym::rustc_deprecated,
1472 template!(List: r#"since = "version", reason = "...""#),
1475 (sym::must_use, Whitelisted, template!(Word, NameValueStr: "reason"), Ungated),
1479 template!(List: r#"feature = "name", since = "version""#),
1485 template!(List: r#"feature = "name", reason = "...", issue = "N""#),
1492 List: r#"/*opt*/ since = "version", /*opt*/ note = "reason""#,
1493 NameValueStr: "reason"
1498 (sym::rustc_paren_sugar, Normal, template!(Word), Gated(Stability::Unstable,
1499 sym::unboxed_closures,
1500 "unboxed_closures are still evolving",
1501 cfg_fn!(unboxed_closures))),
1503 (sym::windows_subsystem, Whitelisted, template!(NameValueStr: "windows|console"), Ungated),
1505 (sym::proc_macro_attribute, Normal, template!(Word), Ungated),
1506 (sym::proc_macro, Normal, template!(Word), Ungated),
1508 (sym::rustc_proc_macro_decls, Normal, template!(Word), Gated(Stability::Unstable,
1510 "used internally by rustc",
1511 cfg_fn!(rustc_attrs))),
1513 (sym::allow_fail, Normal, template!(Word), Gated(Stability::Unstable,
1515 "allow_fail attribute is currently unstable",
1516 cfg_fn!(allow_fail))),
1518 (sym::rustc_std_internal_symbol, Whitelisted, template!(Word), Gated(Stability::Unstable,
1520 "this is an internal attribute that will \
1522 cfg_fn!(rustc_attrs))),
1524 // whitelists "identity-like" conversion methods to suggest on type mismatch
1525 (sym::rustc_conversion_suggestion, Whitelisted, template!(Word), Gated(Stability::Unstable,
1527 "this is an internal attribute that will \
1529 cfg_fn!(rustc_attrs))),
1532 sym::rustc_args_required_const,
1534 template!(List: "N"),
1535 Gated(Stability::Unstable, sym::rustc_attrs, "never will be stable",
1536 cfg_fn!(rustc_attrs))
1539 (sym::panic_handler, Normal, template!(Word), Ungated),
1541 (sym::alloc_error_handler, Normal, template!(Word), Gated(Stability::Unstable,
1542 sym::alloc_error_handler,
1543 "#[alloc_error_handler] is an unstable feature",
1544 cfg_fn!(alloc_error_handler))),
1547 (sym::optimize, Whitelisted, template!(List: "size|speed"), Gated(Stability::Unstable,
1548 sym::optimize_attribute,
1549 "#[optimize] attribute is an unstable feature",
1550 cfg_fn!(optimize_attribute))),
1552 // Crate level attributes
1553 (sym::crate_name, CrateLevel, template!(NameValueStr: "name"), Ungated),
1554 (sym::crate_type, CrateLevel, template!(NameValueStr: "bin|lib|..."), Ungated),
1555 (sym::crate_id, CrateLevel, template!(NameValueStr: "ignored"), Ungated),
1556 (sym::feature, CrateLevel, template!(List: "name1, name1, ..."), Ungated),
1557 (sym::no_start, CrateLevel, template!(Word), Ungated),
1558 (sym::no_main, CrateLevel, template!(Word), Ungated),
1559 (sym::recursion_limit, CrateLevel, template!(NameValueStr: "N"), Ungated),
1560 (sym::type_length_limit, CrateLevel, template!(NameValueStr: "N"), Ungated),
1561 (sym::test_runner, CrateLevel, template!(List: "path"), Gated(Stability::Unstable,
1562 sym::custom_test_frameworks,
1563 EXPLAIN_CUSTOM_TEST_FRAMEWORKS,
1564 cfg_fn!(custom_test_frameworks))),
1567 pub type BuiltinAttribute = (Symbol, AttributeType, AttributeTemplate, AttributeGate);
1570 pub static ref BUILTIN_ATTRIBUTE_MAP: FxHashMap<Symbol, &'static BuiltinAttribute> = {
1571 let mut map = FxHashMap::default();
1572 for attr in BUILTIN_ATTRIBUTES.iter() {
1573 if map.insert(attr.0, attr).is_some() {
1574 panic!("duplicate builtin attribute `{}`", attr.0);
1581 // cfg(...)'s that are feature gated
1582 const GATED_CFGS: &[(Symbol, Symbol, fn(&Features) -> bool)] = &[
1583 // (name in cfg, feature, function to check if the feature is enabled)
1584 (sym::target_thread_local, sym::cfg_target_thread_local, cfg_fn!(cfg_target_thread_local)),
1585 (sym::target_has_atomic, sym::cfg_target_has_atomic, cfg_fn!(cfg_target_has_atomic)),
1586 (sym::rustdoc, sym::doc_cfg, cfg_fn!(doc_cfg)),
1590 pub struct GatedCfg {
1596 pub fn gate(cfg: &ast::MetaItem) -> Option<GatedCfg> {
1598 .position(|info| cfg.check_name(info.0))
1607 pub fn check_and_emit(&self, sess: &ParseSess, features: &Features) {
1608 let (cfg, feature, has_feature) = GATED_CFGS[self.index];
1609 if !has_feature(features) && !self.span.allows_unstable(feature) {
1610 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
1611 emit_feature_err(sess, feature, self.span, GateIssue::Language, &explain);
1616 struct Context<'a> {
1617 features: &'a Features,
1618 parse_sess: &'a ParseSess,
1619 plugin_attributes: &'a [(Symbol, AttributeType)],
1622 macro_rules! gate_feature_fn {
1623 ($cx: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr, $level: expr) => {{
1624 let (cx, has_feature, span,
1625 name, explain, level) = ($cx, $has_feature, $span, $name, $explain, $level);
1626 let has_feature: bool = has_feature(&$cx.features);
1627 debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
1628 if !has_feature && !span.allows_unstable($name) {
1629 leveled_feature_err(cx.parse_sess, name, span, GateIssue::Language, explain, level)
1635 macro_rules! gate_feature {
1636 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {
1637 gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
1638 sym::$feature, $explain, GateStrength::Hard)
1640 ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {
1641 gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
1642 sym::$feature, $explain, $level)
1646 impl<'a> Context<'a> {
1649 attr: &ast::Attribute,
1650 attr_info: Option<&BuiltinAttribute>,
1653 debug!("check_attribute(attr = {:?})", attr);
1654 if let Some(&(name, ty, _template, ref gateage)) = attr_info {
1655 if let Gated(_, name, desc, ref has_feature) = *gateage {
1656 if !attr.span.allows_unstable(name) {
1658 self, has_feature, attr.span, name, desc, GateStrength::Hard
1661 } else if name == sym::doc {
1662 if let Some(content) = attr.meta_item_list() {
1663 if content.iter().any(|c| c.check_name(sym::include)) {
1664 gate_feature!(self, external_doc, attr.span,
1665 "#[doc(include = \"...\")] is experimental"
1670 debug!("check_attribute: {:?} is builtin, {:?}, {:?}", attr.path, ty, gateage);
1673 for &(n, ty) in self.plugin_attributes {
1675 // Plugins can't gate attributes, so we don't check for it
1676 // unlike the code above; we only use this loop to
1677 // short-circuit to avoid the checks below.
1678 debug!("check_attribute: {:?} is registered by a plugin, {:?}", attr.path, ty);
1682 if !is_macro && !attr::is_known(attr) {
1683 // Only run the custom attribute lint during regular feature gate
1684 // checking. Macro gating runs before the plugin attributes are
1685 // registered, so we skip this in that case.
1686 let msg = format!("The attribute `{}` is currently unknown to the compiler and \
1687 may have meaning added to it in the future", attr.path);
1688 gate_feature!(self, custom_attribute, attr.span, &msg);
1693 pub fn check_attribute(attr: &ast::Attribute, parse_sess: &ParseSess, features: &Features) {
1694 let cx = Context { features, parse_sess, plugin_attributes: &[] };
1697 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name).map(|a| *a)),
1702 fn find_lang_feature_issue(feature: Symbol) -> Option<u32> {
1703 if let Some(info) = ACTIVE_FEATURES.iter().find(|t| t.0 == feature) {
1705 // FIXME (#28244): enforce that active features have issue numbers
1706 // assert!(issue.is_some())
1709 // search in Accepted, Removed, or Stable Removed features
1710 let found = ACCEPTED_FEATURES.iter().chain(REMOVED_FEATURES).chain(STABLE_REMOVED_FEATURES)
1711 .find(|t| t.0 == feature);
1713 Some(&(_, _, issue, _)) => issue,
1714 None => panic!("Feature `{}` is not declared anywhere", feature),
1719 pub enum GateIssue {
1721 Library(Option<u32>)
1724 #[derive(Debug, Copy, Clone, PartialEq)]
1725 pub enum GateStrength {
1726 /// A hard error. (Most feature gates should use this.)
1728 /// Only a warning. (Use this only as backwards-compatibility demands.)
1732 pub fn emit_feature_err(
1739 feature_err(sess, feature, span, issue, explain).emit();
1742 pub fn feature_err<'a, S: Into<MultiSpan>>(
1743 sess: &'a ParseSess,
1748 ) -> DiagnosticBuilder<'a> {
1749 leveled_feature_err(sess, feature, span, issue, explain, GateStrength::Hard)
1752 fn leveled_feature_err<'a, S: Into<MultiSpan>>(
1753 sess: &'a ParseSess,
1758 level: GateStrength,
1759 ) -> DiagnosticBuilder<'a> {
1760 let diag = &sess.span_diagnostic;
1762 let issue = match issue {
1763 GateIssue::Language => find_lang_feature_issue(feature),
1764 GateIssue::Library(lib) => lib,
1767 let mut err = match level {
1768 GateStrength::Hard => {
1769 diag.struct_span_err_with_code(span, explain, stringify_error_code!(E0658))
1771 GateStrength::Soft => diag.struct_span_warn(span, explain),
1775 None | Some(0) => {} // We still accept `0` as a stand-in for backwards compatibility
1778 "for more information, see https://github.com/rust-lang/rust/issues/{}",
1784 // #23973: do not suggest `#![feature(...)]` if we are in beta/stable
1785 if sess.unstable_features.is_nightly_build() {
1786 err.help(&format!("add #![feature({})] to the crate attributes to enable", feature));
1789 // If we're on stable and only emitting a "soft" warning, add a note to
1790 // clarify that the feature isn't "on" (rather than being on but
1792 if !sess.unstable_features.is_nightly_build() && level == GateStrength::Soft {
1793 err.help("a nightly build of the compiler is required to enable this feature");
1800 const EXPLAIN_BOX_SYNTAX: &str =
1801 "box expression syntax is experimental; you can call `Box::new` instead";
1803 pub const EXPLAIN_STMT_ATTR_SYNTAX: &str =
1804 "attributes on expressions are experimental";
1806 pub const EXPLAIN_ASM: &str =
1807 "inline assembly is not stable enough for use and is subject to change";
1809 pub const EXPLAIN_GLOBAL_ASM: &str =
1810 "`global_asm!` is not stable enough for use and is subject to change";
1812 pub const EXPLAIN_CUSTOM_TEST_FRAMEWORKS: &str =
1813 "custom test frameworks are an unstable feature";
1815 pub const EXPLAIN_LOG_SYNTAX: &str =
1816 "`log_syntax!` is not stable enough for use and is subject to change";
1818 pub const EXPLAIN_CONCAT_IDENTS: &str =
1819 "`concat_idents` is not stable enough for use and is subject to change";
1821 pub const EXPLAIN_FORMAT_ARGS_NL: &str =
1822 "`format_args_nl` is only for internal language use and is subject to change";
1824 pub const EXPLAIN_TRACE_MACROS: &str =
1825 "`trace_macros` is not stable enough for use and is subject to change";
1826 pub const EXPLAIN_ALLOW_INTERNAL_UNSTABLE: &str =
1827 "allow_internal_unstable side-steps feature gating and stability checks";
1828 pub const EXPLAIN_ALLOW_INTERNAL_UNSAFE: &str =
1829 "allow_internal_unsafe side-steps the unsafe_code lint";
1831 pub const EXPLAIN_UNSIZED_TUPLE_COERCION: &str =
1832 "unsized tuple coercion is not stable enough for use and is subject to change";
1834 struct PostExpansionVisitor<'a> {
1835 context: &'a Context<'a>,
1836 builtin_attributes: &'static FxHashMap<Symbol, &'static BuiltinAttribute>,
1839 macro_rules! gate_feature_post {
1840 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {{
1841 let (cx, span) = ($cx, $span);
1842 if !span.allows_unstable(sym::$feature) {
1843 gate_feature!(cx.context, $feature, span, $explain)
1846 ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {{
1847 let (cx, span) = ($cx, $span);
1848 if !span.allows_unstable(sym::$feature) {
1849 gate_feature!(cx.context, $feature, span, $explain, $level)
1854 impl<'a> PostExpansionVisitor<'a> {
1855 fn check_abi(&self, abi: Abi, span: Span) {
1857 Abi::RustIntrinsic => {
1858 gate_feature_post!(&self, intrinsics, span,
1859 "intrinsics are subject to change");
1861 Abi::PlatformIntrinsic => {
1862 gate_feature_post!(&self, platform_intrinsics, span,
1863 "platform intrinsics are experimental and possibly buggy");
1865 Abi::Vectorcall => {
1866 gate_feature_post!(&self, abi_vectorcall, span,
1867 "vectorcall is experimental and subject to change");
1870 gate_feature_post!(&self, abi_thiscall, span,
1871 "thiscall is experimental and subject to change");
1874 gate_feature_post!(&self, unboxed_closures, span,
1875 "rust-call ABI is subject to change");
1878 gate_feature_post!(&self, abi_ptx, span,
1879 "PTX ABIs are experimental and subject to change");
1881 Abi::Unadjusted => {
1882 gate_feature_post!(&self, abi_unadjusted, span,
1883 "unadjusted ABI is an implementation detail and perma-unstable");
1885 Abi::Msp430Interrupt => {
1886 gate_feature_post!(&self, abi_msp430_interrupt, span,
1887 "msp430-interrupt ABI is experimental and subject to change");
1889 Abi::X86Interrupt => {
1890 gate_feature_post!(&self, abi_x86_interrupt, span,
1891 "x86-interrupt ABI is experimental and subject to change");
1893 Abi::AmdGpuKernel => {
1894 gate_feature_post!(&self, abi_amdgpu_kernel, span,
1895 "amdgpu-kernel ABI is experimental and subject to change");
1910 fn check_builtin_attribute(&mut self, attr: &ast::Attribute, name: Symbol,
1911 template: AttributeTemplate) {
1912 // Some special attributes like `cfg` must be checked
1913 // before the generic check, so we skip them here.
1914 let should_skip = |name| name == sym::cfg;
1915 // Some of previously accepted forms were used in practice,
1916 // report them as warnings for now.
1917 let should_warn = |name| name == sym::doc || name == sym::ignore ||
1918 name == sym::inline || name == sym::link;
1920 match attr.parse_meta(self.context.parse_sess) {
1921 Ok(meta) => if !should_skip(name) && !template.compatible(&meta.node) {
1922 let error_msg = format!("malformed `{}` attribute input", name);
1923 let mut msg = "attribute must be of the form ".to_owned();
1924 let mut suggestions = vec![];
1925 let mut first = true;
1928 let code = format!("#[{}]", name);
1929 msg.push_str(&format!("`{}`", &code));
1930 suggestions.push(code);
1932 if let Some(descr) = template.list {
1934 msg.push_str(" or ");
1937 let code = format!("#[{}({})]", name, descr);
1938 msg.push_str(&format!("`{}`", &code));
1939 suggestions.push(code);
1941 if let Some(descr) = template.name_value_str {
1943 msg.push_str(" or ");
1945 let code = format!("#[{} = \"{}\"]", name, descr);
1946 msg.push_str(&format!("`{}`", &code));
1947 suggestions.push(code);
1949 if should_warn(name) {
1950 self.context.parse_sess.buffer_lint(
1951 BufferedEarlyLintId::IllFormedAttributeInput,
1957 self.context.parse_sess.span_diagnostic.struct_span_err(meta.span, &error_msg)
1960 if suggestions.len() == 1 {
1961 "must be of the form"
1963 "the following are the possible correct uses"
1965 suggestions.into_iter(),
1966 Applicability::HasPlaceholders,
1970 Err(mut err) => err.emit(),
1975 impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
1976 fn visit_attribute(&mut self, attr: &ast::Attribute) {
1977 let attr_info = attr.ident().and_then(|ident| {
1978 self.builtin_attributes.get(&ident.name).map(|a| *a)
1981 // Check for gated attributes.
1982 self.context.check_attribute(attr, attr_info, false);
1984 if attr.check_name(sym::doc) {
1985 if let Some(content) = attr.meta_item_list() {
1986 if content.len() == 1 && content[0].check_name(sym::cfg) {
1987 gate_feature_post!(&self, doc_cfg, attr.span,
1988 "#[doc(cfg(...))] is experimental"
1990 } else if content.iter().any(|c| c.check_name(sym::masked)) {
1991 gate_feature_post!(&self, doc_masked, attr.span,
1992 "#[doc(masked)] is experimental"
1994 } else if content.iter().any(|c| c.check_name(sym::spotlight)) {
1995 gate_feature_post!(&self, doc_spotlight, attr.span,
1996 "#[doc(spotlight)] is experimental"
1998 } else if content.iter().any(|c| c.check_name(sym::alias)) {
1999 gate_feature_post!(&self, doc_alias, attr.span,
2000 "#[doc(alias = \"...\")] is experimental"
2002 } else if content.iter().any(|c| c.check_name(sym::keyword)) {
2003 gate_feature_post!(&self, doc_keyword, attr.span,
2004 "#[doc(keyword = \"...\")] is experimental"
2011 // `rustc_dummy` doesn't have any restrictions specific to built-in attributes.
2012 Some(&(name, _, template, _)) if name != sym::rustc_dummy =>
2013 self.check_builtin_attribute(attr, name, template),
2014 _ => if let Some(TokenTree::Token(token)) = attr.tokens.trees().next() {
2015 if token == token::Eq {
2016 // All key-value attributes are restricted to meta-item syntax.
2017 attr.parse_meta(self.context.parse_sess).map_err(|mut err| err.emit()).ok();
2023 fn visit_name(&mut self, sp: Span, name: ast::Name) {
2024 if !name.as_str().is_ascii() {
2028 self.context.parse_sess.source_map().def_span(sp),
2029 "non-ascii idents are not fully supported"
2034 fn visit_item(&mut self, i: &'a ast::Item) {
2036 ast::ItemKind::ForeignMod(ref foreign_module) => {
2037 self.check_abi(foreign_module.abi, i.span);
2040 ast::ItemKind::Fn(..) => {
2041 if attr::contains_name(&i.attrs[..], sym::plugin_registrar) {
2042 gate_feature_post!(&self, plugin_registrar, i.span,
2043 "compiler plugins are experimental and possibly buggy");
2045 if attr::contains_name(&i.attrs[..], sym::start) {
2046 gate_feature_post!(&self, start, i.span,
2047 "a #[start] function is an experimental \
2048 feature whose signature may change \
2051 if attr::contains_name(&i.attrs[..], sym::main) {
2052 gate_feature_post!(&self, main, i.span,
2053 "declaration of a nonstandard #[main] \
2054 function may change over time, for now \
2055 a top-level `fn main()` is required");
2059 ast::ItemKind::Struct(..) => {
2060 for attr in attr::filter_by_name(&i.attrs[..], sym::repr) {
2061 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
2062 if item.check_name(sym::simd) {
2063 gate_feature_post!(&self, repr_simd, attr.span,
2064 "SIMD types are experimental and possibly buggy");
2070 ast::ItemKind::Enum(ast::EnumDef{ref variants, ..}, ..) => {
2071 for variant in variants {
2072 match (&variant.node.data, &variant.node.disr_expr) {
2073 (ast::VariantData::Unit(..), _) => {},
2074 (_, Some(disr_expr)) =>
2077 arbitrary_enum_discriminant,
2078 disr_expr.value.span,
2079 "discriminants on non-unit variants are experimental"),
2084 let has_feature = self.context.features.arbitrary_enum_discriminant;
2085 if !has_feature && !i.span.allows_unstable(sym::arbitrary_enum_discriminant) {
2086 Parser::maybe_report_invalid_custom_discriminants(
2087 self.context.parse_sess,
2093 ast::ItemKind::Impl(_, polarity, defaultness, _, _, _, _) => {
2094 if polarity == ast::ImplPolarity::Negative {
2095 gate_feature_post!(&self, optin_builtin_traits,
2097 "negative trait bounds are not yet fully implemented; \
2098 use marker types for now");
2101 if let ast::Defaultness::Default = defaultness {
2102 gate_feature_post!(&self, specialization,
2104 "specialization is unstable");
2108 ast::ItemKind::Trait(ast::IsAuto::Yes, ..) => {
2109 gate_feature_post!(&self, optin_builtin_traits,
2111 "auto traits are experimental and possibly buggy");
2114 ast::ItemKind::TraitAlias(..) => {
2119 "trait aliases are experimental"
2123 ast::ItemKind::MacroDef(ast::MacroDef { legacy: false, .. }) => {
2124 let msg = "`macro` is experimental";
2125 gate_feature_post!(&self, decl_macro, i.span, msg);
2128 ast::ItemKind::Existential(..) => {
2133 "existential types are unstable"
2140 visit::walk_item(self, i);
2143 fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
2145 ast::ForeignItemKind::Fn(..) |
2146 ast::ForeignItemKind::Static(..) => {
2147 let link_name = attr::first_attr_value_str_by_name(&i.attrs, sym::link_name);
2148 let links_to_llvm = match link_name {
2149 Some(val) => val.as_str().starts_with("llvm."),
2153 gate_feature_post!(&self, link_llvm_intrinsics, i.span,
2154 "linking to LLVM intrinsics is experimental");
2157 ast::ForeignItemKind::Ty => {
2158 gate_feature_post!(&self, extern_types, i.span,
2159 "extern types are experimental");
2161 ast::ForeignItemKind::Macro(..) => {}
2164 visit::walk_foreign_item(self, i)
2167 fn visit_ty(&mut self, ty: &'a ast::Ty) {
2169 ast::TyKind::BareFn(ref bare_fn_ty) => {
2170 self.check_abi(bare_fn_ty.abi, ty.span);
2172 ast::TyKind::Never => {
2173 gate_feature_post!(&self, never_type, ty.span,
2174 "The `!` type is experimental");
2178 visit::walk_ty(self, ty)
2181 fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FunctionRetTy) {
2182 if let ast::FunctionRetTy::Ty(ref output_ty) = *ret_ty {
2183 if let ast::TyKind::Never = output_ty.node {
2186 self.visit_ty(output_ty)
2191 fn visit_expr(&mut self, e: &'a ast::Expr) {
2193 ast::ExprKind::Box(_) => {
2194 gate_feature_post!(&self, box_syntax, e.span, EXPLAIN_BOX_SYNTAX);
2196 ast::ExprKind::Type(..) => {
2197 // To avoid noise about type ascription in common syntax errors, only emit if it
2198 // is the *only* error.
2199 if self.context.parse_sess.span_diagnostic.err_count() == 0 {
2200 gate_feature_post!(&self, type_ascription, e.span,
2201 "type ascription is experimental");
2204 ast::ExprKind::Yield(..) => {
2205 gate_feature_post!(&self, generators,
2207 "yield syntax is experimental");
2209 ast::ExprKind::TryBlock(_) => {
2210 gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
2212 ast::ExprKind::Block(_, opt_label) => {
2213 if let Some(label) = opt_label {
2214 gate_feature_post!(&self, label_break_value, label.ident.span,
2215 "labels on blocks are unstable");
2218 ast::ExprKind::Closure(_, ast::IsAsync::Async { .. }, ..) => {
2219 gate_feature_post!(&self, async_await, e.span, "async closures are unstable");
2221 ast::ExprKind::Async(..) => {
2222 gate_feature_post!(&self, async_await, e.span, "async blocks are unstable");
2224 ast::ExprKind::Await(origin, _) => {
2226 ast::AwaitOrigin::FieldLike =>
2227 gate_feature_post!(&self, async_await, e.span, "async/await is unstable"),
2228 ast::AwaitOrigin::MacroLike =>
2233 "`await!(<expr>)` macro syntax is unstable, and will soon be removed \
2234 in favor of `<expr>.await` syntax."
2240 visit::walk_expr(self, e)
2243 fn visit_arm(&mut self, arm: &'a ast::Arm) {
2244 visit::walk_arm(self, arm)
2247 fn visit_pat(&mut self, pattern: &'a ast::Pat) {
2248 match pattern.node {
2249 PatKind::Slice(_, Some(ref subslice), _) => {
2250 gate_feature_post!(&self, slice_patterns,
2252 "syntax for subslices in slice patterns is not yet stabilized");
2254 PatKind::Box(..) => {
2255 gate_feature_post!(&self, box_patterns,
2257 "box pattern syntax is experimental");
2259 PatKind::Range(_, _, Spanned { node: RangeEnd::Excluded, .. }) => {
2260 gate_feature_post!(&self, exclusive_range_pattern, pattern.span,
2261 "exclusive range pattern syntax is experimental");
2265 visit::walk_pat(self, pattern)
2268 fn visit_fn(&mut self,
2269 fn_kind: FnKind<'a>,
2270 fn_decl: &'a ast::FnDecl,
2273 if let Some(header) = fn_kind.header() {
2274 // Check for const fn and async fn declarations.
2275 if header.asyncness.node.is_async() {
2276 gate_feature_post!(&self, async_await, span, "async fn is unstable");
2279 // Stability of const fn methods are covered in
2280 // `visit_trait_item` and `visit_impl_item` below; this is
2281 // because default methods don't pass through this point.
2282 self.check_abi(header.abi, span);
2285 if fn_decl.c_variadic {
2286 gate_feature_post!(&self, c_variadic, span, "C-variadic functions are unstable");
2289 visit::walk_fn(self, fn_kind, fn_decl, span)
2292 fn visit_generic_param(&mut self, param: &'a GenericParam) {
2294 GenericParamKind::Const { .. } =>
2295 gate_feature_post!(&self, const_generics, param.ident.span,
2296 "const generics are unstable"),
2299 visit::walk_generic_param(self, param)
2302 fn visit_assoc_ty_constraint(&mut self, constraint: &'a AssocTyConstraint) {
2303 match constraint.kind {
2304 AssocTyConstraintKind::Bound { .. } =>
2305 gate_feature_post!(&self, associated_type_bounds, constraint.span,
2306 "associated type bounds are unstable"),
2309 visit::walk_assoc_ty_constraint(self, constraint)
2312 fn visit_trait_item(&mut self, ti: &'a ast::TraitItem) {
2314 ast::TraitItemKind::Method(ref sig, ref block) => {
2315 if block.is_none() {
2316 self.check_abi(sig.header.abi, ti.span);
2318 if sig.header.asyncness.node.is_async() {
2319 gate_feature_post!(&self, async_await, ti.span, "async fn is unstable");
2321 if sig.decl.c_variadic {
2322 gate_feature_post!(&self, c_variadic, ti.span,
2323 "C-variadic functions are unstable");
2325 if sig.header.constness.node == ast::Constness::Const {
2326 gate_feature_post!(&self, const_fn, ti.span, "const fn is unstable");
2329 ast::TraitItemKind::Type(_, ref default) => {
2330 // We use three if statements instead of something like match guards so that all
2331 // of these errors can be emitted if all cases apply.
2332 if default.is_some() {
2333 gate_feature_post!(&self, associated_type_defaults, ti.span,
2334 "associated type defaults are unstable");
2336 if !ti.generics.params.is_empty() {
2337 gate_feature_post!(&self, generic_associated_types, ti.span,
2338 "generic associated types are unstable");
2340 if !ti.generics.where_clause.predicates.is_empty() {
2341 gate_feature_post!(&self, generic_associated_types, ti.span,
2342 "where clauses on associated types are unstable");
2347 visit::walk_trait_item(self, ti)
2350 fn visit_impl_item(&mut self, ii: &'a ast::ImplItem) {
2351 if ii.defaultness == ast::Defaultness::Default {
2352 gate_feature_post!(&self, specialization,
2354 "specialization is unstable");
2358 ast::ImplItemKind::Method(..) => {}
2359 ast::ImplItemKind::Existential(..) => {
2364 "existential types are unstable"
2367 ast::ImplItemKind::Type(_) => {
2368 if !ii.generics.params.is_empty() {
2369 gate_feature_post!(&self, generic_associated_types, ii.span,
2370 "generic associated types are unstable");
2372 if !ii.generics.where_clause.predicates.is_empty() {
2373 gate_feature_post!(&self, generic_associated_types, ii.span,
2374 "where clauses on associated types are unstable");
2379 visit::walk_impl_item(self, ii)
2382 fn visit_vis(&mut self, vis: &'a ast::Visibility) {
2383 if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.node {
2384 gate_feature_post!(&self, crate_visibility_modifier, vis.span,
2385 "`crate` visibility modifier is experimental");
2387 visit::walk_vis(self, vis)
2391 pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
2392 crate_edition: Edition, allow_features: &Option<Vec<String>>) -> Features {
2393 fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) {
2394 let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
2395 if let Some(reason) = reason {
2396 err.span_note(span, reason);
2398 err.span_label(span, "feature has been removed");
2403 let mut features = Features::new();
2404 let mut edition_enabled_features = FxHashMap::default();
2406 for &edition in ALL_EDITIONS {
2407 if edition <= crate_edition {
2408 // The `crate_edition` implies its respective umbrella feature-gate
2409 // (i.e., `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX).
2410 edition_enabled_features.insert(edition.feature_name(), edition);
2414 for &(name, .., f_edition, set) in ACTIVE_FEATURES {
2415 if let Some(f_edition) = f_edition {
2416 if f_edition <= crate_edition {
2417 set(&mut features, DUMMY_SP);
2418 edition_enabled_features.insert(name, crate_edition);
2423 // Process the edition umbrella feature-gates first, to ensure
2424 // `edition_enabled_features` is completed before it's queried.
2425 for attr in krate_attrs {
2426 if !attr.check_name(sym::feature) {
2430 let list = match attr.meta_item_list() {
2440 let name = mi.name_or_empty();
2441 if INCOMPLETE_FEATURES.iter().any(|f| name == *f) {
2442 span_handler.struct_span_warn(
2445 "the feature `{}` is incomplete and may cause the compiler to crash",
2451 if let Some(edition) = ALL_EDITIONS.iter().find(|e| name == e.feature_name()) {
2452 if *edition <= crate_edition {
2456 for &(name, .., f_edition, set) in ACTIVE_FEATURES {
2457 if let Some(f_edition) = f_edition {
2458 if f_edition <= *edition {
2459 // FIXME(Manishearth) there is currently no way to set
2460 // lib features by edition
2461 set(&mut features, DUMMY_SP);
2462 edition_enabled_features.insert(name, *edition);
2470 for attr in krate_attrs {
2471 if !attr.check_name(sym::feature) {
2475 let list = match attr.meta_item_list() {
2480 let bad_input = |span| {
2481 struct_span_err!(span_handler, span, E0556, "malformed `feature` attribute input")
2485 let name = match mi.ident() {
2486 Some(ident) if mi.is_word() => ident.name,
2488 bad_input(mi.span()).span_suggestion(
2490 "expected just one word",
2491 format!("{}", ident.name),
2492 Applicability::MaybeIncorrect,
2497 bad_input(mi.span()).span_label(mi.span(), "expected just one word").emit();
2502 if let Some(edition) = edition_enabled_features.get(&name) {
2507 "the feature `{}` is included in the Rust {} edition",
2514 if ALL_EDITIONS.iter().any(|e| name == e.feature_name()) {
2515 // Handled in the separate loop above.
2519 let removed = REMOVED_FEATURES.iter().find(|f| name == f.0);
2520 let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.0);
2521 if let Some((.., reason)) = removed.or(stable_removed) {
2522 feature_removed(span_handler, mi.span(), *reason);
2526 if let Some((_, since, ..)) = ACCEPTED_FEATURES.iter().find(|f| name == f.0) {
2527 let since = Some(Symbol::intern(since));
2528 features.declared_lang_features.push((name, mi.span(), since));
2532 if let Some(allowed) = allow_features.as_ref() {
2533 if allowed.iter().find(|f| *f == name.as_str()).is_none() {
2534 span_err!(span_handler, mi.span(), E0725,
2535 "the feature `{}` is not in the list of allowed features",
2541 if let Some((.., set)) = ACTIVE_FEATURES.iter().find(|f| name == f.0) {
2542 set(&mut features, mi.span());
2543 features.declared_lang_features.push((name, mi.span(), None));
2547 features.declared_lib_features.push((name, mi.span()));
2554 pub fn check_crate(krate: &ast::Crate,
2556 features: &Features,
2557 plugin_attributes: &[(Symbol, AttributeType)],
2558 unstable: UnstableFeatures) {
2559 maybe_stage_features(&sess.span_diagnostic, krate, unstable);
2570 .for_each(|span| gate_feature!(
2574 "attributes on function parameters are unstable"
2581 .for_each(|span| gate_feature!(
2585 "`let` expressions in this position are experimental"
2588 let visitor = &mut PostExpansionVisitor {
2590 builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP,
2592 visit::walk_crate(visitor, krate);
2595 #[derive(Clone, Copy, Hash)]
2596 pub enum UnstableFeatures {
2597 /// Hard errors for unstable features are active, as on beta/stable channels.
2599 /// Allow features to be activated, as on nightly.
2601 /// Errors are bypassed for bootstrapping. This is required any time
2602 /// during the build that feature-related lints are set to warn or above
2603 /// because the build turns on warnings-as-errors and uses lots of unstable
2604 /// features. As a result, this is always required for building Rust itself.
2608 impl UnstableFeatures {
2609 pub fn from_environment() -> UnstableFeatures {
2610 // Whether this is a feature-staged build, i.e., on the beta or stable channel
2611 let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
2612 // Whether we should enable unstable features for bootstrapping
2613 let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok();
2614 match (disable_unstable_features, bootstrap) {
2615 (_, true) => UnstableFeatures::Cheat,
2616 (true, _) => UnstableFeatures::Disallow,
2617 (false, _) => UnstableFeatures::Allow
2621 pub fn is_nightly_build(&self) -> bool {
2623 UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
2629 fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate,
2630 unstable: UnstableFeatures) {
2631 let allow_features = match unstable {
2632 UnstableFeatures::Allow => true,
2633 UnstableFeatures::Disallow => false,
2634 UnstableFeatures::Cheat => true
2636 if !allow_features {
2637 for attr in &krate.attrs {
2638 if attr.check_name(sym::feature) {
2639 let release_channel = option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)");
2640 span_err!(span_handler, attr.span, E0554,
2641 "#![feature] may not be used on the {} release channel",