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_data_structures::sync::Lock;
35 use rustc_target::spec::abi::Abi;
36 use syntax_pos::{Span, DUMMY_SP, MultiSpan};
38 use lazy_static::lazy_static;
44 fn f(features: &mut Features, _: Span) {
45 features.$field = true;
47 f as fn(&mut Features, Span)
51 macro_rules! declare_features {
52 ($((active, $feature: ident, $ver: expr, $issue: expr, $edition: expr),)+) => {
53 /// Represents active features that are currently being implemented or
54 /// currently being considered for addition/removal.
55 const ACTIVE_FEATURES:
56 &[(Symbol, &str, Option<u32>, Option<Edition>, fn(&mut Features, Span))] =
57 &[$((sym::$feature, $ver, $issue, $edition, set!($feature))),+];
59 /// A set of features to be used by later passes.
62 /// `#![feature]` attrs for language features, for error reporting
63 pub declared_lang_features: Vec<(Symbol, Span, Option<Symbol>)>,
64 /// `#![feature]` attrs for non-language (library) features
65 pub declared_lib_features: Vec<(Symbol, Span)>,
66 $(pub $feature: bool),+
70 pub fn new() -> Features {
72 declared_lang_features: Vec::new(),
73 declared_lib_features: Vec::new(),
78 pub fn walk_feature_fields<F>(&self, mut f: F)
79 where F: FnMut(&str, bool)
81 $(f(stringify!($feature), self.$feature);)+
86 ($((removed, $feature: ident, $ver: expr, $issue: expr, None, $reason: expr),)+) => {
87 /// Represents unstable features which have since been removed (it was once Active)
88 const REMOVED_FEATURES: &[(Symbol, &str, Option<u32>, Option<&str>)] = &[
89 $((sym::$feature, $ver, $issue, $reason)),+
93 ($((stable_removed, $feature: ident, $ver: expr, $issue: expr, None),)+) => {
94 /// Represents stable features which have since been removed (it was once Accepted)
95 const STABLE_REMOVED_FEATURES: &[(Symbol, &str, Option<u32>, Option<&str>)] = &[
96 $((sym::$feature, $ver, $issue, None)),+
100 ($((accepted, $feature: ident, $ver: expr, $issue: expr, None),)+) => {
101 /// Those language feature has since been Accepted (it was once Active)
102 const ACCEPTED_FEATURES: &[(Symbol, &str, Option<u32>, Option<&str>)] = &[
103 $((sym::$feature, $ver, $issue, None)),+
108 // If you change this, please modify `src/doc/unstable-book` as well.
110 // Don't ever remove anything from this list; set them to 'Removed'.
112 // The version numbers here correspond to the version in which the current status
113 // was set. This is most important for knowing when a particular feature became
116 // Note that the features are grouped into internal/user-facing and then
117 // sorted by version inside those groups. This is inforced with tidy.
119 // N.B., `tools/tidy/src/features.rs` parses this information directly out of the
120 // source, so take care when modifying it.
123 // -------------------------------------------------------------------------
124 // feature-group-start: internal feature gates
125 // -------------------------------------------------------------------------
127 // no-tracking-issue-start
129 // Allows using the `rust-intrinsic`'s "ABI".
130 (active, intrinsics, "1.0.0", None, None),
132 // Allows using `#[lang = ".."]` attribute for linking items to special compiler logic.
133 (active, lang_items, "1.0.0", None, None),
135 // Allows using the `#[stable]` and `#[unstable]` attributes.
136 (active, staged_api, "1.0.0", None, None),
138 // Allows using `#[allow_internal_unstable]`. This is an
139 // attribute on `macro_rules!` and can't use the attribute handling
140 // below (it has to be checked before expansion possibly makes
141 // macros disappear).
142 (active, allow_internal_unstable, "1.0.0", None, None),
144 // Allows using `#[allow_internal_unsafe]`. This is an
145 // attribute on `macro_rules!` and can't use the attribute handling
146 // below (it has to be checked before expansion possibly makes
147 // macros disappear).
148 (active, allow_internal_unsafe, "1.0.0", None, None),
150 // Allows using the macros:
151 // + `__diagnostic_used`
152 // + `__register_diagnostic`
153 // +`__build_diagnostic_array`
154 (active, rustc_diagnostic_macros, "1.0.0", None, None),
156 // Allows using `#[rustc_const_unstable(feature = "foo", ..)]` which
157 // lets a function to be `const` when opted into with `#![feature(foo)]`.
158 (active, rustc_const_unstable, "1.0.0", None, None),
160 // no-tracking-issue-end
162 // Allows using `#[link_name="llvm.*"]`.
163 (active, link_llvm_intrinsics, "1.0.0", Some(29602), None),
165 // Allows using `rustc_*` attributes (RFC 572).
166 (active, rustc_attrs, "1.0.0", Some(29642), None),
168 // Allows using `#[on_unimplemented(..)]` on traits.
169 (active, on_unimplemented, "1.0.0", Some(29628), None),
171 // Allows using the `box $expr` syntax.
172 (active, box_syntax, "1.0.0", Some(49733), None),
174 // Allows using `#[main]` to replace the entrypoint `#[lang = "start"]` calls.
175 (active, main, "1.0.0", Some(29634), None),
177 // Allows using `#[start]` on a function indicating that it is the program entrypoint.
178 (active, start, "1.0.0", Some(29633), None),
180 // Allows using the `#[fundamental]` attribute.
181 (active, fundamental, "1.0.0", Some(29635), None),
183 // Allows using the `rust-call` ABI.
184 (active, unboxed_closures, "1.0.0", Some(29625), None),
186 // Allows using the `#[linkage = ".."]` attribute.
187 (active, linkage, "1.0.0", Some(29603), None),
189 // Allows features specific to OIBIT (auto traits).
190 (active, optin_builtin_traits, "1.0.0", Some(13231), None),
192 // Allows using `box` in patterns (RFC 469).
193 (active, box_patterns, "1.0.0", Some(29641), None),
195 // no-tracking-issue-start
197 // Allows using `#[prelude_import]` on glob `use` items.
198 (active, prelude_import, "1.2.0", None, None),
200 // no-tracking-issue-end
202 // Allows using `#[unsafe_destructor_blind_to_params]` (RFC 1238).
203 (active, dropck_parametricity, "1.3.0", Some(28498), None),
205 // no-tracking-issue-start
207 // Allows using `#[omit_gdb_pretty_printer_section]`.
208 (active, omit_gdb_pretty_printer_section, "1.5.0", None, None),
210 // Allows using the `vectorcall` ABI.
211 (active, abi_vectorcall, "1.7.0", None, None),
213 // no-tracking-issue-end
215 // Allows using `#[structural_match]` which indicates that a type is structurally matchable.
216 (active, structural_match, "1.8.0", Some(31434), None),
218 // Allows using the `may_dangle` attribute (RFC 1327).
219 (active, dropck_eyepatch, "1.10.0", Some(34761), None),
221 // Allows using the `#![panic_runtime]` attribute.
222 (active, panic_runtime, "1.10.0", Some(32837), None),
224 // Allows declaring with `#![needs_panic_runtime]` that a panic runtime is needed.
225 (active, needs_panic_runtime, "1.10.0", Some(32837), None),
227 // no-tracking-issue-start
229 // Allows identifying the `compiler_builtins` crate.
230 (active, compiler_builtins, "1.13.0", None, None),
232 // Allows using the `unadjusted` ABI; perma-unstable.
233 (active, abi_unadjusted, "1.16.0", None, None),
235 // Allows identifying crates that contain sanitizer runtimes.
236 (active, sanitizer_runtime, "1.17.0", None, None),
238 // Used to identify crates that contain the profiler runtime.
239 (active, profiler_runtime, "1.18.0", None, None),
241 // Allows using the `thiscall` ABI.
242 (active, abi_thiscall, "1.19.0", None, None),
244 // Allows using `#![needs_allocator]`, an implementation detail of `#[global_allocator]`.
245 (active, allocator_internals, "1.20.0", None, None),
247 // Allows using the `format_args_nl` macro.
248 (active, format_args_nl, "1.29.0", None, None),
250 // no-tracking-issue-end
252 // Added for testing E0705; perma-unstable.
253 (active, test_2018_feature, "1.31.0", Some(0), Some(Edition::Edition2018)),
255 // -------------------------------------------------------------------------
256 // feature-group-end: internal feature gates
257 // -------------------------------------------------------------------------
259 // -------------------------------------------------------------------------
260 // feature-group-start: actual feature gates (target features)
261 // -------------------------------------------------------------------------
263 // FIXME: Document these and merge with the list below.
265 // Unstable `#[target_feature]` directives.
266 (active, arm_target_feature, "1.27.0", Some(44839), None),
267 (active, aarch64_target_feature, "1.27.0", Some(44839), None),
268 (active, hexagon_target_feature, "1.27.0", Some(44839), None),
269 (active, powerpc_target_feature, "1.27.0", Some(44839), None),
270 (active, mips_target_feature, "1.27.0", Some(44839), None),
271 (active, avx512_target_feature, "1.27.0", Some(44839), None),
272 (active, mmx_target_feature, "1.27.0", Some(44839), None),
273 (active, sse4a_target_feature, "1.27.0", Some(44839), None),
274 (active, tbm_target_feature, "1.27.0", Some(44839), None),
275 (active, wasm_target_feature, "1.30.0", Some(44839), None),
276 (active, adx_target_feature, "1.32.0", Some(44839), None),
277 (active, cmpxchg16b_target_feature, "1.32.0", Some(44839), None),
278 (active, movbe_target_feature, "1.34.0", Some(44839), None),
279 (active, rtm_target_feature, "1.35.0", Some(44839), None),
280 (active, f16c_target_feature, "1.36.0", Some(44839), None),
282 // -------------------------------------------------------------------------
283 // feature-group-end: actual feature gates (target features)
284 // -------------------------------------------------------------------------
286 // -------------------------------------------------------------------------
287 // feature-group-start: actual feature gates
288 // -------------------------------------------------------------------------
290 // Allows using `asm!` macro with which inline assembly can be embedded.
291 (active, asm, "1.0.0", Some(29722), None),
293 // Allows using the `concat_idents!` macro with which identifiers can be concatenated.
294 (active, concat_idents, "1.0.0", Some(29599), None),
296 // Allows using the `#[link_args]` attribute.
297 (active, link_args, "1.0.0", Some(29596), None),
299 // Allows defining identifiers beyond ASCII.
300 (active, non_ascii_idents, "1.0.0", Some(55467), None),
302 // Allows using `#[plugin_registrar]` on functions.
303 (active, plugin_registrar, "1.0.0", Some(29597), None),
305 // Allows using `#![plugin(myplugin)]`.
306 (active, plugin, "1.0.0", Some(29597), None),
308 // Allows using `#[thread_local]` on `static` items.
309 (active, thread_local, "1.0.0", Some(29594), None),
311 // Allows using the `log_syntax!` macro.
312 (active, log_syntax, "1.0.0", Some(29598), None),
314 // Allows using the `trace_macros!` macro.
315 (active, trace_macros, "1.0.0", Some(29598), None),
317 // Allows the use of SIMD types in functions declared in `extern` blocks.
318 (active, simd_ffi, "1.0.0", Some(27731), None),
320 // Allows using custom attributes (RFC 572).
321 (active, custom_attribute, "1.0.0", Some(29642), None),
323 // Allows using non lexical lifetimes (RFC 2094).
324 (active, nll, "1.0.0", Some(43234), None),
326 // Allows using slice patterns.
327 (active, slice_patterns, "1.0.0", Some(62254), None),
329 // Allows the definition of `const` functions with some advanced features.
330 (active, const_fn, "1.2.0", Some(57563), None),
332 // Allows associated type defaults.
333 (active, associated_type_defaults, "1.2.0", Some(29661), None),
335 // Allows `#![no_core]`.
336 (active, no_core, "1.3.0", Some(29639), None),
338 // Allows default type parameters to influence type inference.
339 (active, default_type_parameter_fallback, "1.3.0", Some(27336), None),
341 // Allows `repr(simd)` and importing the various simd intrinsics.
342 (active, repr_simd, "1.4.0", Some(27731), None),
344 // Allows `extern "platform-intrinsic" { ... }`.
345 (active, platform_intrinsics, "1.4.0", Some(27731), None),
347 // Allows `#[unwind(..)]`.
349 // Permits specifying whether a function should permit unwinding or abort on unwind.
350 (active, unwind_attributes, "1.4.0", Some(58760), None),
352 // Allows `#[no_debug]`.
353 (active, no_debug, "1.5.0", Some(29721), None),
355 // Allows attributes on expressions and non-item statements.
356 (active, stmt_expr_attributes, "1.6.0", Some(15701), None),
358 // Allows the use of type ascription in expressions.
359 (active, type_ascription, "1.6.0", Some(23416), None),
361 // Allows `cfg(target_thread_local)`.
362 (active, cfg_target_thread_local, "1.7.0", Some(29594), None),
364 // Allows specialization of implementations (RFC 1210).
365 (active, specialization, "1.7.0", Some(31844), None),
367 // Allows using `#[naked]` on functions.
368 (active, naked_functions, "1.9.0", Some(32408), None),
370 // Allows `cfg(target_has_atomic = "...")`.
371 (active, cfg_target_has_atomic, "1.9.0", Some(32976), None),
373 // Allows `X..Y` patterns.
374 (active, exclusive_range_pattern, "1.11.0", Some(37854), None),
376 // Allows the `!` type. Does not imply 'exhaustive_patterns' (below) any more.
377 (active, never_type, "1.13.0", Some(35121), None),
379 // Allows exhaustive pattern matching on types that contain uninhabited types.
380 (active, exhaustive_patterns, "1.13.0", Some(51085), None),
382 // Allows untagged unions `union U { ... }`.
383 (active, untagged_unions, "1.13.0", Some(32836), None),
385 // Allows `#[link(..., cfg(..))]`.
386 (active, link_cfg, "1.14.0", Some(37406), None),
388 // Allows `extern "ptx-*" fn()`.
389 (active, abi_ptx, "1.15.0", Some(38788), None),
391 // Allows the `#[repr(i128)]` attribute for enums.
392 (active, repr128, "1.16.0", Some(35118), None),
394 // Allows `#[link(kind="static-nobundle"...)]`.
395 (active, static_nobundle, "1.16.0", Some(37403), None),
397 // Allows `extern "msp430-interrupt" fn()`.
398 (active, abi_msp430_interrupt, "1.16.0", Some(38487), None),
400 // Allows declarative macros 2.0 (`macro`).
401 (active, decl_macro, "1.17.0", Some(39412), None),
403 // Allows `extern "x86-interrupt" fn()`.
404 (active, abi_x86_interrupt, "1.17.0", Some(40180), None),
406 // Allows module-level inline assembly by way of `global_asm!()`.
407 (active, global_asm, "1.18.0", Some(35119), None),
409 // Allows overlapping impls of marker traits.
410 (active, overlapping_marker_traits, "1.18.0", Some(29864), None),
412 // Allows a test to fail without failing the whole suite.
413 (active, allow_fail, "1.19.0", Some(46488), None),
415 // Allows unsized tuple coercion.
416 (active, unsized_tuple_coercion, "1.20.0", Some(42877), None),
418 // Allows defining generators.
419 (active, generators, "1.21.0", Some(43122), None),
421 // Allows `#[doc(cfg(...))]`.
422 (active, doc_cfg, "1.21.0", Some(43781), None),
424 // Allows `#[doc(masked)]`.
425 (active, doc_masked, "1.21.0", Some(44027), None),
427 // Allows `#[doc(spotlight)]`.
428 (active, doc_spotlight, "1.22.0", Some(45040), None),
430 // Allows `#[doc(include = "some-file")]`.
431 (active, external_doc, "1.22.0", Some(44732), None),
433 // Allows future-proofing enums/structs with the `#[non_exhaustive]` attribute (RFC 2008).
434 (active, non_exhaustive, "1.22.0", Some(44109), None),
436 // Allows using `crate` as visibility modifier, synonymous with `pub(crate)`.
437 (active, crate_visibility_modifier, "1.23.0", Some(53120), None),
439 // Allows defining `extern type`s.
440 (active, extern_types, "1.23.0", Some(43467), None),
442 // Allows trait methods with arbitrary self types.
443 (active, arbitrary_self_types, "1.23.0", Some(44874), None),
445 // Allows in-band quantification of lifetime bindings (e.g., `fn foo(x: &'a u8) -> &'a u8`).
446 (active, in_band_lifetimes, "1.23.0", Some(44524), None),
448 // Allows associated types to be generic, e.g., `type Foo<T>;` (RFC 1598).
449 (active, generic_associated_types, "1.23.0", Some(44265), None),
451 // Allows defining `trait X = A + B;` alias items.
452 (active, trait_alias, "1.24.0", Some(41517), None),
454 // Allows infering `'static` outlives requirements (RFC 2093).
455 (active, infer_static_outlives_requirements, "1.26.0", Some(54185), None),
457 // Allows macro invocations in `extern {}` blocks.
458 (active, macros_in_extern, "1.27.0", Some(49476), None),
460 // Allows accessing fields of unions inside `const` functions.
461 (active, const_fn_union, "1.27.0", Some(51909), None),
463 // Allows casting raw pointers to `usize` during const eval.
464 (active, const_raw_ptr_to_usize_cast, "1.27.0", Some(51910), None),
466 // Allows dereferencing raw pointers during const eval.
467 (active, const_raw_ptr_deref, "1.27.0", Some(51911), None),
469 // Allows comparing raw pointers during const eval.
470 (active, const_compare_raw_pointers, "1.27.0", Some(53020), None),
472 // Allows `#[doc(alias = "...")]`.
473 (active, doc_alias, "1.27.0", Some(50146), None),
475 // Allows defining `existential type`s.
476 (active, existential_type, "1.28.0", Some(34511), None),
478 // Allows inconsistent bounds in where clauses.
479 (active, trivial_bounds, "1.28.0", Some(48214), None),
481 // Allows `'a: { break 'a; }`.
482 (active, label_break_value, "1.28.0", Some(48594), None),
484 // Allows using `#[doc(keyword = "...")]`.
485 (active, doc_keyword, "1.28.0", Some(51315), None),
487 // Allows async and await syntax.
488 (active, async_await, "1.28.0", Some(50547), None),
490 // Allows await! macro-like syntax.
491 // This will likely be removed prior to stabilization of async/await.
492 (active, await_macro, "1.28.0", Some(50547), None),
494 // Allows reinterpretation of the bits of a value of one type as another type during const eval.
495 (active, const_transmute, "1.29.0", Some(53605), None),
497 // Allows using `try {...}` expressions.
498 (active, try_blocks, "1.29.0", Some(31436), None),
500 // Allows defining an `#[alloc_error_handler]`.
501 (active, alloc_error_handler, "1.29.0", Some(51540), None),
503 // Allows using the `amdgpu-kernel` ABI.
504 (active, abi_amdgpu_kernel, "1.29.0", Some(51575), None),
506 // Allows panicking during const eval (producing compile-time errors).
507 (active, const_panic, "1.30.0", Some(51999), None),
509 // Allows `#[marker]` on certain traits allowing overlapping implementations.
510 (active, marker_trait_attr, "1.30.0", Some(29864), None),
512 // Allows macro invocations on modules expressions and statements and
513 // procedural macros to expand to non-items.
514 (active, proc_macro_hygiene, "1.30.0", Some(54727), None),
516 // Allows unsized rvalues at arguments and parameters.
517 (active, unsized_locals, "1.30.0", Some(48055), None),
519 // Allows custom test frameworks with `#![test_runner]` and `#[test_case]`.
520 (active, custom_test_frameworks, "1.30.0", Some(50297), None),
522 // Allows non-builtin attributes in inner attribute position.
523 (active, custom_inner_attributes, "1.30.0", Some(54726), None),
525 // Allows mixing bind-by-move in patterns and references to those identifiers in guards.
526 (active, bind_by_move_pattern_guards, "1.30.0", Some(15287), None),
528 // Allows `impl Trait` in bindings (`let`, `const`, `static`).
529 (active, impl_trait_in_bindings, "1.30.0", Some(34511), None),
531 // Allows using `reason` in lint attributes and the `#[expect(lint)]` lint check.
532 (active, lint_reasons, "1.31.0", Some(54503), None),
534 // Allows exhaustive integer pattern matching on `usize` and `isize`.
535 (active, precise_pointer_size_matching, "1.32.0", Some(56354), None),
537 // Allows relaxing the coherence rules such that
538 // `impl<T> ForeignTrait<LocalType> for ForeignType<T> is permitted.
539 (active, re_rebalance_coherence, "1.32.0", Some(55437), None),
541 // Allows using `#[ffi_returns_twice]` on foreign functions.
542 (active, ffi_returns_twice, "1.34.0", Some(58314), None),
544 // Allows const generic types (e.g. `struct Foo<const N: usize>(...);`).
545 (active, const_generics, "1.34.0", Some(44580), None),
547 // Allows using `#[optimize(X)]`.
548 (active, optimize_attribute, "1.34.0", Some(54882), None),
550 // Allows using C-variadics.
551 (active, c_variadic, "1.34.0", Some(44930), None),
553 // Allows the user of associated type bounds.
554 (active, associated_type_bounds, "1.34.0", Some(52662), None),
556 // Attributes on formal function params.
557 (active, param_attrs, "1.36.0", Some(60406), None),
559 // Allows calling constructor functions in `const fn`.
560 (active, const_constructor, "1.37.0", Some(61456), None),
562 // Allows `if/while p && let q = r && ...` chains.
563 (active, let_chains, "1.37.0", Some(53667), None),
565 // #[repr(transparent)] on enums.
566 (active, transparent_enums, "1.37.0", Some(60405), None),
568 // #[repr(transparent)] on unions.
569 (active, transparent_unions, "1.37.0", Some(60405), None),
571 // Allows explicit discriminants on non-unit enum variants.
572 (active, arbitrary_enum_discriminant, "1.37.0", Some(60553), None),
574 // Allows `impl Trait` with multiple unrelated lifetimes.
575 (active, member_constraints, "1.37.0", Some(61977), None),
577 // Allows `async || body` closures.
578 (active, async_closure, "1.37.0", Some(62290), None),
580 // -------------------------------------------------------------------------
581 // feature-group-end: actual feature gates
582 // -------------------------------------------------------------------------
585 // Some features are known to be incomplete and using them is likely to have
586 // unanticipated results, such as compiler crashes. We warn the user about these
588 const INCOMPLETE_FEATURES: &[Symbol] = &[
589 sym::impl_trait_in_bindings,
590 sym::generic_associated_types,
596 // -------------------------------------------------------------------------
597 // feature-group-start: removed features
598 // -------------------------------------------------------------------------
600 (removed, import_shadowing, "1.0.0", None, None, None),
601 (removed, managed_boxes, "1.0.0", None, None, None),
602 // Allows use of unary negate on unsigned integers, e.g., -e for e: u8
603 (removed, negate_unsigned, "1.0.0", Some(29645), None, None),
604 (removed, reflect, "1.0.0", Some(27749), None, None),
605 // A way to temporarily opt out of opt in copy. This will *never* be accepted.
606 (removed, opt_out_copy, "1.0.0", None, None, None),
607 (removed, quad_precision_float, "1.0.0", None, None, None),
608 (removed, struct_inherit, "1.0.0", None, None, None),
609 (removed, test_removed_feature, "1.0.0", None, None, None),
610 (removed, visible_private_types, "1.0.0", None, None, None),
611 (removed, unsafe_no_drop_flag, "1.0.0", None, None, None),
612 // Allows using items which are missing stability attributes
613 (removed, unmarked_api, "1.0.0", None, None, None),
614 (removed, allocator, "1.0.0", None, None, None),
615 (removed, simd, "1.0.0", Some(27731), None,
616 Some("removed in favor of `#[repr(simd)]`")),
617 (removed, advanced_slice_patterns, "1.0.0", Some(62254), None,
618 Some("merged into `#![feature(slice_patterns)]`")),
619 (removed, macro_reexport, "1.0.0", Some(29638), None,
620 Some("subsumed by `pub use`")),
621 (removed, pushpop_unsafe, "1.2.0", None, None, None),
622 (removed, needs_allocator, "1.4.0", Some(27389), None,
623 Some("subsumed by `#![feature(allocator_internals)]`")),
624 (removed, proc_macro_mod, "1.27.0", Some(54727), None,
625 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
626 (removed, proc_macro_expr, "1.27.0", Some(54727), None,
627 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
628 (removed, proc_macro_non_items, "1.27.0", Some(54727), None,
629 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
630 (removed, proc_macro_gen, "1.27.0", Some(54727), None,
631 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
632 (removed, panic_implementation, "1.28.0", Some(44489), None,
633 Some("subsumed by `#[panic_handler]`")),
634 // Allows the use of `#[derive(Anything)]` as sugar for `#[derive_Anything]`.
635 (removed, custom_derive, "1.32.0", Some(29644), None,
636 Some("subsumed by `#[proc_macro_derive]`")),
637 // Paths of the form: `extern::foo::bar`
638 (removed, extern_in_paths, "1.33.0", Some(55600), None,
639 Some("subsumed by `::foo::bar` paths")),
640 (removed, quote, "1.33.0", Some(29601), None, None),
642 // -------------------------------------------------------------------------
643 // feature-group-end: removed features
644 // -------------------------------------------------------------------------
648 (stable_removed, no_stack_check, "1.0.0", None, None),
652 // -------------------------------------------------------------------------
653 // feature-group-start: for testing purposes
654 // -------------------------------------------------------------------------
656 // A temporary feature gate used to enable parser extensions needed
657 // to bootstrap fix for #5723.
658 (accepted, issue_5723_bootstrap, "1.0.0", None, None),
659 // These are used to test this portion of the compiler,
660 // they don't actually mean anything.
661 (accepted, test_accepted_feature, "1.0.0", None, None),
663 // -------------------------------------------------------------------------
664 // feature-group-end: for testing purposes
665 // -------------------------------------------------------------------------
667 // -------------------------------------------------------------------------
668 // feature-group-start: accepted features
669 // -------------------------------------------------------------------------
671 // Allows using associated `type`s in `trait`s.
672 (accepted, associated_types, "1.0.0", None, None),
673 // Allows using assigning a default type to type parameters in algebraic data type definitions.
674 (accepted, default_type_params, "1.0.0", None, None),
675 // FIXME: explain `globs`.
676 (accepted, globs, "1.0.0", None, None),
677 // Allows `macro_rules!` items.
678 (accepted, macro_rules, "1.0.0", None, None),
679 // Allows use of `&foo[a..b]` as a slicing syntax.
680 (accepted, slicing_syntax, "1.0.0", None, None),
681 // Allows struct variants `Foo { baz: u8, .. }` in enums (RFC 418).
682 (accepted, struct_variant, "1.0.0", None, None),
683 // Allows indexing tuples.
684 (accepted, tuple_indexing, "1.0.0", None, None),
685 // Allows the use of `if let` expressions.
686 (accepted, if_let, "1.0.0", None, None),
687 // Allows the use of `while let` expressions.
688 (accepted, while_let, "1.0.0", None, None),
689 // Allows using `#![no_std]`.
690 (accepted, no_std, "1.6.0", None, None),
691 // Allows overloading augmented assignment operations like `a += b`.
692 (accepted, augmented_assignments, "1.8.0", Some(28235), None),
693 // Allows empty structs and enum variants with braces.
694 (accepted, braced_empty_structs, "1.8.0", Some(29720), None),
695 // Allows `#[deprecated]` attribute.
696 (accepted, deprecated, "1.9.0", Some(29935), None),
697 // Allows macros to appear in the type position.
698 (accepted, type_macros, "1.13.0", Some(27245), None),
699 // Allows use of the postfix `?` operator in expressions.
700 (accepted, question_mark, "1.13.0", Some(31436), None),
701 // Allows `..` in tuple (struct) patterns.
702 (accepted, dotdot_in_tuple_patterns, "1.14.0", Some(33627), None),
703 // Allows some increased flexibility in the name resolution rules,
704 // especially around globs and shadowing (RFC 1560).
705 (accepted, item_like_imports, "1.15.0", Some(35120), None),
706 // Allows using `Self` and associated types in struct expressions and patterns.
707 (accepted, more_struct_aliases, "1.16.0", Some(37544), None),
708 // Allows elision of `'static` lifetimes in `static`s and `const`s.
709 (accepted, static_in_const, "1.17.0", Some(35897), None),
710 // Allows field shorthands (`x` meaning `x: x`) in struct literal expressions.
711 (accepted, field_init_shorthand, "1.17.0", Some(37340), None),
712 // Allows the definition recursive static items.
713 (accepted, static_recursion, "1.17.0", Some(29719), None),
714 // Allows `pub(restricted)` visibilities (RFC 1422).
715 (accepted, pub_restricted, "1.18.0", Some(32409), None),
716 // Allows `#![windows_subsystem]`.
717 (accepted, windows_subsystem, "1.18.0", Some(37499), None),
718 // Allows `break {expr}` with a value inside `loop`s.
719 (accepted, loop_break_value, "1.19.0", Some(37339), None),
720 // Allows numeric fields in struct expressions and patterns.
721 (accepted, relaxed_adts, "1.19.0", Some(35626), None),
722 // Allows coercing non capturing closures to function pointers.
723 (accepted, closure_to_fn_coercion, "1.19.0", Some(39817), None),
724 // Allows attributes on struct literal fields.
725 (accepted, struct_field_attributes, "1.20.0", Some(38814), None),
726 // Allows the definition of associated constants in `trait` or `impl` blocks.
727 (accepted, associated_consts, "1.20.0", Some(29646), None),
728 // Allows usage of the `compile_error!` macro.
729 (accepted, compile_error, "1.20.0", Some(40872), None),
730 // Allows code like `let x: &'static u32 = &42` to work (RFC 1414).
731 (accepted, rvalue_static_promotion, "1.21.0", Some(38865), None),
732 // Allows `Drop` types in constants (RFC 1440).
733 (accepted, drop_types_in_const, "1.22.0", Some(33156), None),
734 // Allows the sysV64 ABI to be specified on all platforms
735 // instead of just the platforms on which it is the C ABI.
736 (accepted, abi_sysv64, "1.24.0", Some(36167), None),
737 // Allows `repr(align(16))` struct attribute (RFC 1358).
738 (accepted, repr_align, "1.25.0", Some(33626), None),
739 // Allows '|' at beginning of match arms (RFC 1925).
740 (accepted, match_beginning_vert, "1.25.0", Some(44101), None),
741 // Allows nested groups in `use` items (RFC 2128).
742 (accepted, use_nested_groups, "1.25.0", Some(44494), None),
743 // Allows indexing into constant arrays.
744 (accepted, const_indexing, "1.26.0", Some(29947), None),
745 // Allows using `a..=b` and `..=b` as inclusive range syntaxes.
746 (accepted, inclusive_range_syntax, "1.26.0", Some(28237), None),
747 // Allows `..=` in patterns (RFC 1192).
748 (accepted, dotdoteq_in_patterns, "1.26.0", Some(28237), None),
749 // Allows `fn main()` with return types which implements `Termination` (RFC 1937).
750 (accepted, termination_trait, "1.26.0", Some(43301), None),
751 // Allows implementing `Clone` for closures where possible (RFC 2132).
752 (accepted, clone_closures, "1.26.0", Some(44490), None),
753 // Allows implementing `Copy` for closures where possible (RFC 2132).
754 (accepted, copy_closures, "1.26.0", Some(44490), None),
755 // Allows `impl Trait` in function arguments.
756 (accepted, universal_impl_trait, "1.26.0", Some(34511), None),
757 // Allows `impl Trait` in function return types.
758 (accepted, conservative_impl_trait, "1.26.0", Some(34511), None),
759 // Allows using the `u128` and `i128` types.
760 (accepted, i128_type, "1.26.0", Some(35118), None),
761 // Allows default match binding modes (RFC 2005).
762 (accepted, match_default_bindings, "1.26.0", Some(42640), None),
763 // Allows `'_` placeholder lifetimes.
764 (accepted, underscore_lifetimes, "1.26.0", Some(44524), None),
765 // Allows attributes on lifetime/type formal parameters in generics (RFC 1327).
766 (accepted, generic_param_attrs, "1.27.0", Some(48848), None),
767 // Allows `cfg(target_feature = "...")`.
768 (accepted, cfg_target_feature, "1.27.0", Some(29717), None),
769 // Allows `#[target_feature(...)]`.
770 (accepted, target_feature, "1.27.0", None, None),
771 // Allows using `dyn Trait` as a syntax for trait objects.
772 (accepted, dyn_trait, "1.27.0", Some(44662), None),
773 // Allows `#[must_use]` on functions, and introduces must-use operators (RFC 1940).
774 (accepted, fn_must_use, "1.27.0", Some(43302), None),
775 // Allows use of the `:lifetime` macro fragment specifier.
776 (accepted, macro_lifetime_matcher, "1.27.0", Some(34303), None),
777 // Allows `#[test]` functions where the return type implements `Termination` (RFC 1937).
778 (accepted, termination_trait_test, "1.27.0", Some(48854), None),
779 // Allows the `#[global_allocator]` attribute.
780 (accepted, global_allocator, "1.28.0", Some(27389), None),
781 // Allows `#[repr(transparent)]` attribute on newtype structs.
782 (accepted, repr_transparent, "1.28.0", Some(43036), None),
783 // Allows procedural macros in `proc-macro` crates.
784 (accepted, proc_macro, "1.29.0", Some(38356), None),
785 // Allows `foo.rs` as an alternative to `foo/mod.rs`.
786 (accepted, non_modrs_mods, "1.30.0", Some(44660), None),
787 // Allows use of the `:vis` macro fragment specifier
788 (accepted, macro_vis_matcher, "1.30.0", Some(41022), None),
789 // Allows importing and reexporting macros with `use`,
790 // enables macro modularization in general.
791 (accepted, use_extern_macros, "1.30.0", Some(35896), None),
792 // Allows keywords to be escaped for use as identifiers.
793 (accepted, raw_identifiers, "1.30.0", Some(48589), None),
794 // Allows attributes scoped to tools.
795 (accepted, tool_attributes, "1.30.0", Some(44690), None),
796 // Allows multi-segment paths in attributes and derives.
797 (accepted, proc_macro_path_invoc, "1.30.0", Some(38356), None),
798 // Allows all literals in attribute lists and values of key-value pairs.
799 (accepted, attr_literals, "1.30.0", Some(34981), None),
800 // Allows inferring outlives requirements (RFC 2093).
801 (accepted, infer_outlives_requirements, "1.30.0", Some(44493), None),
802 // Allows annotating functions conforming to `fn(&PanicInfo) -> !` with `#[panic_handler]`.
803 // This defines the behavior of panics.
804 (accepted, panic_handler, "1.30.0", Some(44489), None),
805 // Allows `#[used]` to preserve symbols (see llvm.used).
806 (accepted, used, "1.30.0", Some(40289), None),
807 // Allows `crate` in paths.
808 (accepted, crate_in_paths, "1.30.0", Some(45477), None),
809 // Allows resolving absolute paths as paths from other crates.
810 (accepted, extern_absolute_paths, "1.30.0", Some(44660), None),
811 // Allows access to crate names passed via `--extern` through prelude.
812 (accepted, extern_prelude, "1.30.0", Some(44660), None),
813 // Allows parentheses in patterns.
814 (accepted, pattern_parentheses, "1.31.0", Some(51087), None),
815 // Allows the definition of `const fn` functions.
816 (accepted, min_const_fn, "1.31.0", Some(53555), None),
817 // Allows scoped lints.
818 (accepted, tool_lints, "1.31.0", Some(44690), None),
819 // Allows lifetime elision in `impl` headers. For example:
820 // + `impl<I:Iterator> Iterator for &mut Iterator`
821 // + `impl Debug for Foo<'_>`
822 (accepted, impl_header_lifetime_elision, "1.31.0", Some(15872), None),
823 // Allows `extern crate foo as bar;`. This puts `bar` into extern prelude.
824 (accepted, extern_crate_item_prelude, "1.31.0", Some(55599), None),
825 // Allows use of the `:literal` macro fragment specifier (RFC 1576).
826 (accepted, macro_literal_matcher, "1.32.0", Some(35625), None),
827 // Allows use of `?` as the Kleene "at most one" operator in macros.
828 (accepted, macro_at_most_once_rep, "1.32.0", Some(48075), None),
829 // Allows `Self` struct constructor (RFC 2302).
830 (accepted, self_struct_ctor, "1.32.0", Some(51994), None),
831 // Allows `Self` in type definitions (RFC 2300).
832 (accepted, self_in_typedefs, "1.32.0", Some(49303), None),
833 // Allows `use x::y;` to search `x` in the current scope.
834 (accepted, uniform_paths, "1.32.0", Some(53130), None),
835 // Allows integer match exhaustiveness checking (RFC 2591).
836 (accepted, exhaustive_integer_patterns, "1.33.0", Some(50907), None),
837 // Allows `use path as _;` and `extern crate c as _;`.
838 (accepted, underscore_imports, "1.33.0", Some(48216), None),
839 // Allows `#[repr(packed(N))]` attribute on structs.
840 (accepted, repr_packed, "1.33.0", Some(33158), None),
841 // Allows irrefutable patterns in `if let` and `while let` statements (RFC 2086).
842 (accepted, irrefutable_let_patterns, "1.33.0", Some(44495), None),
843 // Allows calling `const unsafe fn` inside `unsafe` blocks in `const fn` functions.
844 (accepted, min_const_unsafe_fn, "1.33.0", Some(55607), None),
845 // Allows let bindings, assignments and destructuring in `const` functions and constants.
846 // As long as control flow is not implemented in const eval, `&&` and `||` may not be used
847 // at the same time as let bindings.
848 (accepted, const_let, "1.33.0", Some(48821), None),
849 // Allows `#[cfg_attr(predicate, multiple, attributes, here)]`.
850 (accepted, cfg_attr_multi, "1.33.0", Some(54881), None),
851 // Allows top level or-patterns (`p | q`) in `if let` and `while let`.
852 (accepted, if_while_or_patterns, "1.33.0", Some(48215), None),
853 // Allows `cfg(target_vendor = "...")`.
854 (accepted, cfg_target_vendor, "1.33.0", Some(29718), None),
855 // Allows `extern crate self as foo;`.
856 // This puts local crate root into extern prelude under name `foo`.
857 (accepted, extern_crate_self, "1.34.0", Some(56409), None),
858 // Allows arbitrary delimited token streams in non-macro attributes.
859 (accepted, unrestricted_attribute_tokens, "1.34.0", Some(55208), None),
860 // Allows paths to enum variants on type aliases including `Self`.
861 (accepted, type_alias_enum_variants, "1.37.0", Some(49683), None),
862 // Allows using `#[repr(align(X))]` on enums with equivalent semantics
863 // to wrapping an enum in a wrapper struct with `#[repr(align(X))]`.
864 (accepted, repr_align_enum, "1.37.0", Some(57996), None),
865 // Allows `const _: TYPE = VALUE`.
866 (accepted, underscore_const_names, "1.37.0", Some(54912), None),
868 // -------------------------------------------------------------------------
869 // feature-group-end: accepted features
870 // -------------------------------------------------------------------------
873 // If you change this, please modify `src/doc/unstable-book` as well. You must
874 // move that documentation into the relevant place in the other docs, and
875 // remove the chapter on the flag.
877 #[derive(Copy, Clone, PartialEq, Debug)]
878 pub enum AttributeType {
879 /// Normal, builtin attribute that is consumed
880 /// by the compiler before the unused_attribute check
883 /// Builtin attribute that may not be consumed by the compiler
884 /// before the unused_attribute check. These attributes
885 /// will be ignored by the unused_attribute lint
888 /// Builtin attribute that is only allowed at the crate level
892 pub enum AttributeGate {
893 /// Is gated by a given feature gate, reason
894 /// and function to check if enabled
895 Gated(Stability, Symbol, &'static str, fn(&Features) -> bool),
897 /// Ungated attribute, can be used on all release channels
901 /// A template that the attribute input must match.
902 /// Only top-level shape (`#[attr]` vs `#[attr(...)]` vs `#[attr = ...]`) is considered now.
903 #[derive(Clone, Copy)]
904 pub struct AttributeTemplate {
906 list: Option<&'static str>,
907 name_value_str: Option<&'static str>,
910 impl AttributeTemplate {
911 /// Checks that the given meta-item is compatible with this template.
912 fn compatible(&self, meta_item_kind: &ast::MetaItemKind) -> bool {
913 match meta_item_kind {
914 ast::MetaItemKind::Word => self.word,
915 ast::MetaItemKind::List(..) => self.list.is_some(),
916 ast::MetaItemKind::NameValue(lit) if lit.node.is_str() => self.name_value_str.is_some(),
917 ast::MetaItemKind::NameValue(..) => false,
922 /// A convenience macro for constructing attribute templates.
923 /// E.g., `template!(Word, List: "description")` means that the attribute
924 /// supports forms `#[attr]` and `#[attr(description)]`.
925 macro_rules! template {
926 (Word) => { template!(@ true, None, None) };
927 (List: $descr: expr) => { template!(@ false, Some($descr), None) };
928 (NameValueStr: $descr: expr) => { template!(@ false, None, Some($descr)) };
929 (Word, List: $descr: expr) => { template!(@ true, Some($descr), None) };
930 (Word, NameValueStr: $descr: expr) => { template!(@ true, None, Some($descr)) };
931 (List: $descr1: expr, NameValueStr: $descr2: expr) => {
932 template!(@ false, Some($descr1), Some($descr2))
934 (Word, List: $descr1: expr, NameValueStr: $descr2: expr) => {
935 template!(@ true, Some($descr1), Some($descr2))
937 (@ $word: expr, $list: expr, $name_value_str: expr) => { AttributeTemplate {
938 word: $word, list: $list, name_value_str: $name_value_str
943 fn is_deprecated(&self) -> bool {
945 Gated(Stability::Deprecated(_, _), ..) => true,
951 #[derive(Copy, Clone, Debug)]
954 // First argument is tracking issue link; second argument is an optional
955 // help message, which defaults to "remove this attribute"
956 Deprecated(&'static str, Option<&'static str>),
960 impl std::fmt::Debug for AttributeGate {
961 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
963 Gated(ref stab, name, expl, _) =>
964 write!(fmt, "Gated({:?}, {}, {})", stab, name, expl),
965 Ungated => write!(fmt, "Ungated")
970 macro_rules! cfg_fn {
971 ($field: ident) => {{
972 fn f(features: &Features) -> bool {
975 f as fn(&Features) -> bool
979 pub fn deprecated_attributes() -> Vec<&'static (Symbol, AttributeType,
980 AttributeTemplate, AttributeGate)> {
981 BUILTIN_ATTRIBUTES.iter().filter(|(.., gate)| gate.is_deprecated()).collect()
984 pub fn is_builtin_attr_name(name: ast::Name) -> bool {
985 BUILTIN_ATTRIBUTE_MAP.get(&name).is_some()
988 pub fn is_builtin_attr(attr: &ast::Attribute) -> bool {
989 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)).is_some()
992 /// Attributes that have a special meaning to rustc or rustdoc
993 pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
999 template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#),
1005 template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#),
1011 template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#),
1017 template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#),
1021 (sym::macro_use, Normal, template!(Word, List: "name1, name2, ..."), Ungated),
1022 (sym::macro_export, Normal, template!(Word, List: "local_inner_macros"), Ungated),
1023 (sym::plugin_registrar, Normal, template!(Word), Ungated),
1025 (sym::cfg, Normal, template!(List: "predicate"), Ungated),
1026 (sym::cfg_attr, Normal, template!(List: "predicate, attr1, attr2, ..."), Ungated),
1027 (sym::main, Normal, template!(Word), Ungated),
1028 (sym::start, Normal, template!(Word), Ungated),
1029 (sym::repr, Normal, template!(List: "C, packed, ..."), Ungated),
1030 (sym::path, Normal, template!(NameValueStr: "file"), Ungated),
1031 (sym::automatically_derived, Normal, template!(Word), Ungated),
1032 (sym::no_mangle, Whitelisted, template!(Word), Ungated),
1033 (sym::no_link, Normal, template!(Word), Ungated),
1034 (sym::derive, Normal, template!(List: "Trait1, Trait2, ..."), Ungated),
1038 template!(Word, List: r#"expected = "reason"#, NameValueStr: "reason"),
1041 (sym::ignore, Normal, template!(Word, NameValueStr: "reason"), Ungated),
1042 (sym::no_implicit_prelude, Normal, template!(Word), Ungated),
1043 (sym::reexport_test_harness_main, Normal, template!(NameValueStr: "name"), Ungated),
1044 (sym::link_args, Normal, template!(NameValueStr: "args"), Gated(Stability::Unstable,
1046 "the `link_args` attribute is experimental and not \
1047 portable across platforms, it is recommended to \
1048 use `#[link(name = \"foo\")] instead",
1049 cfg_fn!(link_args))),
1050 (sym::macro_escape, Normal, template!(Word), Ungated),
1053 (sym::structural_match, Whitelisted, template!(Word), Gated(Stability::Unstable,
1054 sym::structural_match,
1055 "the semantics of constant patterns is \
1057 cfg_fn!(structural_match))),
1060 (sym::non_exhaustive, Whitelisted, template!(Word), Gated(Stability::Unstable,
1061 sym::non_exhaustive,
1062 "non exhaustive is an experimental feature",
1063 cfg_fn!(non_exhaustive))),
1066 (sym::marker, Normal, template!(Word), Gated(Stability::Unstable,
1067 sym::marker_trait_attr,
1068 "marker traits is an experimental feature",
1069 cfg_fn!(marker_trait_attr))),
1071 (sym::plugin, CrateLevel, template!(List: "name|name(args)"), Gated(Stability::Unstable,
1073 "compiler plugins are experimental \
1074 and possibly buggy",
1077 (sym::no_std, CrateLevel, template!(Word), Ungated),
1078 (sym::no_core, CrateLevel, template!(Word), Gated(Stability::Unstable,
1080 "no_core is experimental",
1082 (sym::lang, Normal, template!(NameValueStr: "name"), Gated(Stability::Unstable,
1084 "language items are subject to change",
1085 cfg_fn!(lang_items))),
1086 (sym::linkage, Whitelisted, template!(NameValueStr: "external|internal|..."),
1087 Gated(Stability::Unstable,
1089 "the `linkage` attribute is experimental \
1090 and not portable across platforms",
1092 (sym::thread_local, Whitelisted, template!(Word), Gated(Stability::Unstable,
1094 "`#[thread_local]` is an experimental feature, and does \
1095 not currently handle destructors",
1096 cfg_fn!(thread_local))),
1098 (sym::rustc_on_unimplemented, Whitelisted, template!(List:
1099 r#"/*opt*/ message = "...", /*opt*/ label = "...", /*opt*/ note = "...""#,
1100 NameValueStr: "message"),
1101 Gated(Stability::Unstable,
1102 sym::on_unimplemented,
1103 "the `#[rustc_on_unimplemented]` attribute \
1104 is an experimental feature",
1105 cfg_fn!(on_unimplemented))),
1106 (sym::rustc_const_unstable, Normal, template!(List: r#"feature = "name""#),
1107 Gated(Stability::Unstable,
1108 sym::rustc_const_unstable,
1109 "the `#[rustc_const_unstable]` attribute \
1110 is an internal feature",
1111 cfg_fn!(rustc_const_unstable))),
1112 (sym::global_allocator, Normal, template!(Word), Ungated),
1113 (sym::default_lib_allocator, Whitelisted, template!(Word), Gated(Stability::Unstable,
1114 sym::allocator_internals,
1115 "the `#[default_lib_allocator]` \
1116 attribute is an experimental feature",
1117 cfg_fn!(allocator_internals))),
1118 (sym::needs_allocator, Normal, template!(Word), Gated(Stability::Unstable,
1119 sym::allocator_internals,
1120 "the `#[needs_allocator]` \
1121 attribute is an experimental \
1123 cfg_fn!(allocator_internals))),
1124 (sym::panic_runtime, Whitelisted, template!(Word), Gated(Stability::Unstable,
1126 "the `#[panic_runtime]` attribute is \
1127 an experimental feature",
1128 cfg_fn!(panic_runtime))),
1129 (sym::needs_panic_runtime, Whitelisted, template!(Word), Gated(Stability::Unstable,
1130 sym::needs_panic_runtime,
1131 "the `#[needs_panic_runtime]` \
1132 attribute is an experimental \
1134 cfg_fn!(needs_panic_runtime))),
1135 (sym::rustc_outlives, Normal, template!(Word), Gated(Stability::Unstable,
1137 "the `#[rustc_outlives]` attribute \
1138 is just used for rustc unit tests \
1139 and will never be stable",
1140 cfg_fn!(rustc_attrs))),
1141 (sym::rustc_variance, Normal, template!(Word), Gated(Stability::Unstable,
1143 "the `#[rustc_variance]` attribute \
1144 is just used for rustc unit tests \
1145 and will never be stable",
1146 cfg_fn!(rustc_attrs))),
1147 (sym::rustc_layout, Normal, template!(List: "field1, field2, ..."),
1148 Gated(Stability::Unstable,
1150 "the `#[rustc_layout]` attribute \
1151 is just used for rustc unit tests \
1152 and will never be stable",
1153 cfg_fn!(rustc_attrs))),
1154 (sym::rustc_layout_scalar_valid_range_start, Whitelisted, template!(List: "value"),
1155 Gated(Stability::Unstable,
1157 "the `#[rustc_layout_scalar_valid_range_start]` attribute \
1158 is just used to enable niche optimizations in libcore \
1159 and will never be stable",
1160 cfg_fn!(rustc_attrs))),
1161 (sym::rustc_layout_scalar_valid_range_end, Whitelisted, template!(List: "value"),
1162 Gated(Stability::Unstable,
1164 "the `#[rustc_layout_scalar_valid_range_end]` attribute \
1165 is just used to enable niche optimizations in libcore \
1166 and will never be stable",
1167 cfg_fn!(rustc_attrs))),
1168 (sym::rustc_nonnull_optimization_guaranteed, Whitelisted, template!(Word),
1169 Gated(Stability::Unstable,
1171 "the `#[rustc_nonnull_optimization_guaranteed]` attribute \
1172 is just used to enable niche optimizations in libcore \
1173 and will never be stable",
1174 cfg_fn!(rustc_attrs))),
1175 (sym::rustc_regions, Normal, template!(Word), Gated(Stability::Unstable,
1177 "the `#[rustc_regions]` attribute \
1178 is just used for rustc unit tests \
1179 and will never be stable",
1180 cfg_fn!(rustc_attrs))),
1181 (sym::rustc_error, Whitelisted, template!(Word), Gated(Stability::Unstable,
1183 "the `#[rustc_error]` attribute \
1184 is just used for rustc unit tests \
1185 and will never be stable",
1186 cfg_fn!(rustc_attrs))),
1187 (sym::rustc_dump_user_substs, Whitelisted, template!(Word), Gated(Stability::Unstable,
1190 is just used for rustc unit tests \
1191 and will never be stable",
1192 cfg_fn!(rustc_attrs))),
1193 (sym::rustc_if_this_changed, Whitelisted, template!(Word, List: "DepNode"),
1194 Gated(Stability::Unstable,
1196 "the `#[rustc_if_this_changed]` attribute \
1197 is just used for rustc unit tests \
1198 and will never be stable",
1199 cfg_fn!(rustc_attrs))),
1200 (sym::rustc_then_this_would_need, Whitelisted, template!(List: "DepNode"),
1201 Gated(Stability::Unstable,
1203 "the `#[rustc_if_this_changed]` attribute \
1204 is just used for rustc unit tests \
1205 and will never be stable",
1206 cfg_fn!(rustc_attrs))),
1207 (sym::rustc_dirty, Whitelisted, template!(List: r#"cfg = "...", /*opt*/ label = "...",
1208 /*opt*/ except = "...""#),
1209 Gated(Stability::Unstable,
1211 "the `#[rustc_dirty]` attribute \
1212 is just used for rustc unit tests \
1213 and will never be stable",
1214 cfg_fn!(rustc_attrs))),
1215 (sym::rustc_clean, Whitelisted, template!(List: r#"cfg = "...", /*opt*/ label = "...",
1216 /*opt*/ except = "...""#),
1217 Gated(Stability::Unstable,
1219 "the `#[rustc_clean]` attribute \
1220 is just used for rustc unit tests \
1221 and will never be stable",
1222 cfg_fn!(rustc_attrs))),
1224 sym::rustc_partition_reused,
1226 template!(List: r#"cfg = "...", module = "...""#),
1228 Stability::Unstable,
1231 is just used for rustc unit tests \
1232 and will never be stable",
1233 cfg_fn!(rustc_attrs)
1237 sym::rustc_partition_codegened,
1239 template!(List: r#"cfg = "...", module = "...""#),
1241 Stability::Unstable,
1244 is just used for rustc unit tests \
1245 and will never be stable",
1246 cfg_fn!(rustc_attrs),
1249 (sym::rustc_expected_cgu_reuse, Whitelisted, template!(List: r#"cfg = "...", module = "...",
1251 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_synthetic, Whitelisted, template!(Word), Gated(Stability::Unstable,
1260 is just used for rustc unit tests \
1261 and will never be stable",
1262 cfg_fn!(rustc_attrs))),
1263 (sym::rustc_symbol_name, Whitelisted, template!(Word), Gated(Stability::Unstable,
1265 "internal rustc attributes will never be stable",
1266 cfg_fn!(rustc_attrs))),
1267 (sym::rustc_def_path, Whitelisted, template!(Word), Gated(Stability::Unstable,
1269 "internal rustc attributes will never be stable",
1270 cfg_fn!(rustc_attrs))),
1271 (sym::rustc_mir, Whitelisted, template!(List: "arg1, arg2, ..."), Gated(Stability::Unstable,
1273 "the `#[rustc_mir]` attribute \
1274 is just used for rustc unit tests \
1275 and will never be stable",
1276 cfg_fn!(rustc_attrs))),
1278 sym::rustc_inherit_overflow_checks,
1282 Stability::Unstable,
1284 "the `#[rustc_inherit_overflow_checks]` \
1285 attribute is just used to control \
1286 overflow checking behavior of several \
1287 libcore functions that are inlined \
1288 across crates and will never be stable",
1289 cfg_fn!(rustc_attrs),
1293 (sym::rustc_dump_program_clauses, Whitelisted, template!(Word), Gated(Stability::Unstable,
1295 "the `#[rustc_dump_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_dump_env_program_clauses, Whitelisted, template!(Word), Gated(Stability::Unstable,
1301 "the `#[rustc_dump_env_program_clauses]` \
1302 attribute is just used for rustc unit \
1303 tests and will never be stable",
1304 cfg_fn!(rustc_attrs))),
1305 (sym::rustc_object_lifetime_default, Whitelisted, template!(Word), Gated(Stability::Unstable,
1307 "the `#[rustc_object_lifetime_default]` \
1308 attribute is just used for rustc unit \
1309 tests and will never be stable",
1310 cfg_fn!(rustc_attrs))),
1311 (sym::rustc_test_marker, Normal, template!(Word), Gated(Stability::Unstable,
1313 "the `#[rustc_test_marker]` attribute \
1314 is used internally to track tests",
1315 cfg_fn!(rustc_attrs))),
1316 (sym::rustc_transparent_macro, Whitelisted, template!(Word), Gated(Stability::Unstable,
1318 "used internally for testing macro hygiene",
1319 cfg_fn!(rustc_attrs))),
1320 (sym::compiler_builtins, Whitelisted, template!(Word), Gated(Stability::Unstable,
1321 sym::compiler_builtins,
1322 "the `#[compiler_builtins]` attribute is used to \
1323 identify the `compiler_builtins` crate which \
1324 contains compiler-rt intrinsics and will never be \
1326 cfg_fn!(compiler_builtins))),
1327 (sym::sanitizer_runtime, Whitelisted, template!(Word), Gated(Stability::Unstable,
1328 sym::sanitizer_runtime,
1329 "the `#[sanitizer_runtime]` attribute is used to \
1330 identify crates that contain the runtime of a \
1331 sanitizer and will never be stable",
1332 cfg_fn!(sanitizer_runtime))),
1333 (sym::profiler_runtime, Whitelisted, template!(Word), Gated(Stability::Unstable,
1334 sym::profiler_runtime,
1335 "the `#[profiler_runtime]` attribute is used to \
1336 identify the `profiler_builtins` crate which \
1337 contains the profiler runtime and will never be \
1339 cfg_fn!(profiler_runtime))),
1341 (sym::allow_internal_unstable, Normal, template!(Word, List: "feat1, feat2, ..."),
1342 Gated(Stability::Unstable,
1343 sym::allow_internal_unstable,
1344 EXPLAIN_ALLOW_INTERNAL_UNSTABLE,
1345 cfg_fn!(allow_internal_unstable))),
1347 (sym::allow_internal_unsafe, Normal, template!(Word), Gated(Stability::Unstable,
1348 sym::allow_internal_unsafe,
1349 EXPLAIN_ALLOW_INTERNAL_UNSAFE,
1350 cfg_fn!(allow_internal_unsafe))),
1352 (sym::fundamental, Whitelisted, template!(Word), Gated(Stability::Unstable,
1354 "the `#[fundamental]` attribute \
1355 is an experimental feature",
1356 cfg_fn!(fundamental))),
1358 (sym::proc_macro_derive, Normal, template!(List: "TraitName, \
1359 /*opt*/ attributes(name1, name2, ...)"),
1362 (sym::rustc_copy_clone_marker, Whitelisted, template!(Word), Gated(Stability::Unstable,
1364 "internal implementation detail",
1365 cfg_fn!(rustc_attrs))),
1367 (sym::rustc_allocator, Whitelisted, template!(Word), Gated(Stability::Unstable,
1369 "internal implementation detail",
1370 cfg_fn!(rustc_attrs))),
1372 (sym::rustc_allocator_nounwind, Whitelisted, template!(Word), Gated(Stability::Unstable,
1374 "internal implementation detail",
1375 cfg_fn!(rustc_attrs))),
1377 (sym::rustc_doc_only_macro, Whitelisted, template!(Word), Gated(Stability::Unstable,
1379 "internal implementation detail",
1380 cfg_fn!(rustc_attrs))),
1382 (sym::rustc_promotable, Whitelisted, template!(Word), Gated(Stability::Unstable,
1384 "internal implementation detail",
1385 cfg_fn!(rustc_attrs))),
1387 (sym::rustc_allow_const_fn_ptr, Whitelisted, template!(Word), Gated(Stability::Unstable,
1389 "internal implementation detail",
1390 cfg_fn!(rustc_attrs))),
1392 (sym::rustc_dummy, Normal, template!(Word /* doesn't matter*/), Gated(Stability::Unstable,
1394 "used by the test suite",
1395 cfg_fn!(rustc_attrs))),
1397 // FIXME: #14408 whitelist docs since rustdoc looks at them
1401 template!(List: "hidden|inline|...", NameValueStr: "string"),
1405 // FIXME: #14406 these are processed in codegen, which happens after the
1407 (sym::cold, Whitelisted, template!(Word), Ungated),
1408 (sym::naked, Whitelisted, template!(Word), Gated(Stability::Unstable,
1409 sym::naked_functions,
1410 "the `#[naked]` attribute \
1411 is an experimental feature",
1412 cfg_fn!(naked_functions))),
1413 (sym::ffi_returns_twice, Whitelisted, template!(Word), Gated(Stability::Unstable,
1414 sym::ffi_returns_twice,
1415 "the `#[ffi_returns_twice]` attribute \
1416 is an experimental feature",
1417 cfg_fn!(ffi_returns_twice))),
1418 (sym::target_feature, Whitelisted, template!(List: r#"enable = "name""#), Ungated),
1419 (sym::export_name, Whitelisted, template!(NameValueStr: "name"), Ungated),
1420 (sym::inline, Whitelisted, template!(Word, List: "always|never"), Ungated),
1421 (sym::link, Whitelisted, template!(List: r#"name = "...", /*opt*/ kind = "dylib|static|...",
1422 /*opt*/ cfg = "...""#), Ungated),
1423 (sym::link_name, Whitelisted, template!(NameValueStr: "name"), Ungated),
1424 (sym::link_section, Whitelisted, template!(NameValueStr: "name"), Ungated),
1425 (sym::no_builtins, Whitelisted, template!(Word), Ungated),
1426 (sym::no_debug, Whitelisted, template!(Word), Gated(
1427 Stability::Deprecated("https://github.com/rust-lang/rust/issues/29721", None),
1429 "the `#[no_debug]` attribute was an experimental feature that has been \
1430 deprecated due to lack of demand",
1431 cfg_fn!(no_debug))),
1433 sym::omit_gdb_pretty_printer_section,
1437 Stability::Unstable,
1438 sym::omit_gdb_pretty_printer_section,
1439 "the `#[omit_gdb_pretty_printer_section]` \
1440 attribute is just used for the Rust test \
1442 cfg_fn!(omit_gdb_pretty_printer_section)
1445 (sym::unsafe_destructor_blind_to_params,
1448 Gated(Stability::Deprecated("https://github.com/rust-lang/rust/issues/34761",
1449 Some("replace this attribute with `#[may_dangle]`")),
1450 sym::dropck_parametricity,
1451 "unsafe_destructor_blind_to_params has been replaced by \
1452 may_dangle and will be removed in the future",
1453 cfg_fn!(dropck_parametricity))),
1457 Gated(Stability::Unstable,
1458 sym::dropck_eyepatch,
1459 "may_dangle has unstable semantics and may be removed in the future",
1460 cfg_fn!(dropck_eyepatch))),
1461 (sym::unwind, Whitelisted, template!(List: "allowed|aborts"), Gated(Stability::Unstable,
1462 sym::unwind_attributes,
1463 "#[unwind] is experimental",
1464 cfg_fn!(unwind_attributes))),
1465 (sym::used, Whitelisted, template!(Word), Ungated),
1468 (sym::prelude_import, Whitelisted, template!(Word), Gated(Stability::Unstable,
1469 sym::prelude_import,
1470 "`#[prelude_import]` is for use by rustc only",
1471 cfg_fn!(prelude_import))),
1473 // FIXME: #14407 these are only looked at on-demand so we can't
1474 // guarantee they'll have already been checked
1476 sym::rustc_deprecated,
1478 template!(List: r#"since = "version", reason = "...""#),
1481 (sym::must_use, Whitelisted, template!(Word, NameValueStr: "reason"), Ungated),
1485 template!(List: r#"feature = "name", since = "version""#),
1491 template!(List: r#"feature = "name", reason = "...", issue = "N""#),
1498 List: r#"/*opt*/ since = "version", /*opt*/ note = "reason""#,
1499 NameValueStr: "reason"
1504 (sym::rustc_paren_sugar, Normal, template!(Word), Gated(Stability::Unstable,
1505 sym::unboxed_closures,
1506 "unboxed_closures are still evolving",
1507 cfg_fn!(unboxed_closures))),
1509 (sym::windows_subsystem, Whitelisted, template!(NameValueStr: "windows|console"), Ungated),
1511 (sym::proc_macro_attribute, Normal, template!(Word), Ungated),
1512 (sym::proc_macro, Normal, template!(Word), Ungated),
1514 (sym::rustc_proc_macro_decls, Normal, template!(Word), Gated(Stability::Unstable,
1516 "used internally by rustc",
1517 cfg_fn!(rustc_attrs))),
1519 (sym::allow_fail, Normal, template!(Word), Gated(Stability::Unstable,
1521 "allow_fail attribute is currently unstable",
1522 cfg_fn!(allow_fail))),
1524 (sym::rustc_std_internal_symbol, Whitelisted, template!(Word), Gated(Stability::Unstable,
1526 "this is an internal attribute that will \
1528 cfg_fn!(rustc_attrs))),
1530 // whitelists "identity-like" conversion methods to suggest on type mismatch
1531 (sym::rustc_conversion_suggestion, Whitelisted, template!(Word), Gated(Stability::Unstable,
1533 "this is an internal attribute that will \
1535 cfg_fn!(rustc_attrs))),
1538 sym::rustc_args_required_const,
1540 template!(List: "N"),
1541 Gated(Stability::Unstable, sym::rustc_attrs, "never will be stable",
1542 cfg_fn!(rustc_attrs))
1545 (sym::panic_handler, Normal, template!(Word), Ungated),
1547 (sym::alloc_error_handler, Normal, template!(Word), Gated(Stability::Unstable,
1548 sym::alloc_error_handler,
1549 "#[alloc_error_handler] is an unstable feature",
1550 cfg_fn!(alloc_error_handler))),
1553 (sym::optimize, Whitelisted, template!(List: "size|speed"), Gated(Stability::Unstable,
1554 sym::optimize_attribute,
1555 "#[optimize] attribute is an unstable feature",
1556 cfg_fn!(optimize_attribute))),
1558 // Crate level attributes
1559 (sym::crate_name, CrateLevel, template!(NameValueStr: "name"), Ungated),
1560 (sym::crate_type, CrateLevel, template!(NameValueStr: "bin|lib|..."), Ungated),
1561 (sym::crate_id, CrateLevel, template!(NameValueStr: "ignored"), Ungated),
1562 (sym::feature, CrateLevel, template!(List: "name1, name1, ..."), Ungated),
1563 (sym::no_start, CrateLevel, template!(Word), Ungated),
1564 (sym::no_main, CrateLevel, template!(Word), Ungated),
1565 (sym::recursion_limit, CrateLevel, template!(NameValueStr: "N"), Ungated),
1566 (sym::type_length_limit, CrateLevel, template!(NameValueStr: "N"), Ungated),
1567 (sym::test_runner, CrateLevel, template!(List: "path"), Gated(Stability::Unstable,
1568 sym::custom_test_frameworks,
1569 EXPLAIN_CUSTOM_TEST_FRAMEWORKS,
1570 cfg_fn!(custom_test_frameworks))),
1573 pub type BuiltinAttribute = (Symbol, AttributeType, AttributeTemplate, AttributeGate);
1576 pub static ref BUILTIN_ATTRIBUTE_MAP: FxHashMap<Symbol, &'static BuiltinAttribute> = {
1577 let mut map = FxHashMap::default();
1578 for attr in BUILTIN_ATTRIBUTES.iter() {
1579 if map.insert(attr.0, attr).is_some() {
1580 panic!("duplicate builtin attribute `{}`", attr.0);
1587 // cfg(...)'s that are feature gated
1588 const GATED_CFGS: &[(Symbol, Symbol, fn(&Features) -> bool)] = &[
1589 // (name in cfg, feature, function to check if the feature is enabled)
1590 (sym::target_thread_local, sym::cfg_target_thread_local, cfg_fn!(cfg_target_thread_local)),
1591 (sym::target_has_atomic, sym::cfg_target_has_atomic, cfg_fn!(cfg_target_has_atomic)),
1592 (sym::rustdoc, sym::doc_cfg, cfg_fn!(doc_cfg)),
1596 pub struct GatedCfg {
1602 pub fn gate(cfg: &ast::MetaItem) -> Option<GatedCfg> {
1604 .position(|info| cfg.check_name(info.0))
1613 pub fn check_and_emit(&self, sess: &ParseSess, features: &Features) {
1614 let (cfg, feature, has_feature) = GATED_CFGS[self.index];
1615 if !has_feature(features) && !self.span.allows_unstable(feature) {
1616 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
1617 emit_feature_err(sess, feature, self.span, GateIssue::Language, &explain);
1622 struct Context<'a> {
1623 features: &'a Features,
1624 parse_sess: &'a ParseSess,
1625 plugin_attributes: &'a [(Symbol, AttributeType)],
1628 macro_rules! gate_feature_fn {
1629 ($cx: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr, $level: expr) => {{
1630 let (cx, has_feature, span,
1631 name, explain, level) = ($cx, $has_feature, $span, $name, $explain, $level);
1632 let has_feature: bool = has_feature(&$cx.features);
1633 debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
1634 if !has_feature && !span.allows_unstable($name) {
1635 leveled_feature_err(cx.parse_sess, name, span, GateIssue::Language, explain, level)
1641 macro_rules! gate_feature {
1642 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {
1643 gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
1644 sym::$feature, $explain, GateStrength::Hard)
1646 ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {
1647 gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
1648 sym::$feature, $explain, $level)
1652 impl<'a> Context<'a> {
1655 attr: &ast::Attribute,
1656 attr_info: Option<&BuiltinAttribute>,
1659 debug!("check_attribute(attr = {:?})", attr);
1660 if let Some(&(name, ty, _template, ref gateage)) = attr_info {
1661 if let Gated(_, name, desc, ref has_feature) = *gateage {
1662 if !attr.span.allows_unstable(name) {
1664 self, has_feature, attr.span, name, desc, GateStrength::Hard
1667 } else if name == sym::doc {
1668 if let Some(content) = attr.meta_item_list() {
1669 if content.iter().any(|c| c.check_name(sym::include)) {
1670 gate_feature!(self, external_doc, attr.span,
1671 "#[doc(include = \"...\")] is experimental"
1676 debug!("check_attribute: {:?} is builtin, {:?}, {:?}", attr.path, ty, gateage);
1679 for segment in &attr.path.segments {
1680 if segment.ident.as_str().starts_with("rustc") {
1681 let msg = "attributes starting with `rustc` are \
1682 reserved for use by the `rustc` compiler";
1683 gate_feature!(self, rustc_attrs, segment.ident.span, msg);
1687 for &(n, ty) in self.plugin_attributes {
1689 // Plugins can't gate attributes, so we don't check for it
1690 // unlike the code above; we only use this loop to
1691 // short-circuit to avoid the checks below.
1692 debug!("check_attribute: {:?} is registered by a plugin, {:?}", attr.path, ty);
1696 if !is_macro && !attr::is_known(attr) {
1697 // Only run the custom attribute lint during regular feature gate
1698 // checking. Macro gating runs before the plugin attributes are
1699 // registered, so we skip this in that case.
1700 let msg = format!("The attribute `{}` is currently unknown to the compiler and \
1701 may have meaning added to it in the future", attr.path);
1702 gate_feature!(self, custom_attribute, attr.span, &msg);
1707 pub fn check_attribute(attr: &ast::Attribute, parse_sess: &ParseSess, features: &Features) {
1708 let cx = Context { features, parse_sess, plugin_attributes: &[] };
1711 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name).map(|a| *a)),
1716 fn find_lang_feature_issue(feature: Symbol) -> Option<u32> {
1717 if let Some(info) = ACTIVE_FEATURES.iter().find(|t| t.0 == feature) {
1719 // FIXME (#28244): enforce that active features have issue numbers
1720 // assert!(issue.is_some())
1723 // search in Accepted, Removed, or Stable Removed features
1724 let found = ACCEPTED_FEATURES.iter().chain(REMOVED_FEATURES).chain(STABLE_REMOVED_FEATURES)
1725 .find(|t| t.0 == feature);
1727 Some(&(_, _, issue, _)) => issue,
1728 None => panic!("Feature `{}` is not declared anywhere", feature),
1733 pub enum GateIssue {
1735 Library(Option<u32>)
1738 #[derive(Debug, Copy, Clone, PartialEq)]
1739 pub enum GateStrength {
1740 /// A hard error. (Most feature gates should use this.)
1742 /// Only a warning. (Use this only as backwards-compatibility demands.)
1746 pub fn emit_feature_err(
1753 feature_err(sess, feature, span, issue, explain).emit();
1756 pub fn feature_err<'a, S: Into<MultiSpan>>(
1757 sess: &'a ParseSess,
1762 ) -> DiagnosticBuilder<'a> {
1763 leveled_feature_err(sess, feature, span, issue, explain, GateStrength::Hard)
1766 fn leveled_feature_err<'a, S: Into<MultiSpan>>(
1767 sess: &'a ParseSess,
1772 level: GateStrength,
1773 ) -> DiagnosticBuilder<'a> {
1774 let diag = &sess.span_diagnostic;
1776 let issue = match issue {
1777 GateIssue::Language => find_lang_feature_issue(feature),
1778 GateIssue::Library(lib) => lib,
1781 let mut err = match level {
1782 GateStrength::Hard => {
1783 diag.struct_span_err_with_code(span, explain, stringify_error_code!(E0658))
1785 GateStrength::Soft => diag.struct_span_warn(span, explain),
1789 None | Some(0) => {} // We still accept `0` as a stand-in for backwards compatibility
1792 "for more information, see https://github.com/rust-lang/rust/issues/{}",
1798 // #23973: do not suggest `#![feature(...)]` if we are in beta/stable
1799 if sess.unstable_features.is_nightly_build() {
1800 err.help(&format!("add #![feature({})] to the crate attributes to enable", feature));
1803 // If we're on stable and only emitting a "soft" warning, add a note to
1804 // clarify that the feature isn't "on" (rather than being on but
1806 if !sess.unstable_features.is_nightly_build() && level == GateStrength::Soft {
1807 err.help("a nightly build of the compiler is required to enable this feature");
1814 const EXPLAIN_BOX_SYNTAX: &str =
1815 "box expression syntax is experimental; you can call `Box::new` instead";
1817 pub const EXPLAIN_STMT_ATTR_SYNTAX: &str =
1818 "attributes on expressions are experimental";
1820 pub const EXPLAIN_ASM: &str =
1821 "inline assembly is not stable enough for use and is subject to change";
1823 pub const EXPLAIN_GLOBAL_ASM: &str =
1824 "`global_asm!` is not stable enough for use and is subject to change";
1826 pub const EXPLAIN_CUSTOM_TEST_FRAMEWORKS: &str =
1827 "custom test frameworks are an unstable feature";
1829 pub const EXPLAIN_LOG_SYNTAX: &str =
1830 "`log_syntax!` is not stable enough for use and is subject to change";
1832 pub const EXPLAIN_CONCAT_IDENTS: &str =
1833 "`concat_idents` is not stable enough for use and is subject to change";
1835 pub const EXPLAIN_FORMAT_ARGS_NL: &str =
1836 "`format_args_nl` is only for internal language use and is subject to change";
1838 pub const EXPLAIN_TRACE_MACROS: &str =
1839 "`trace_macros` is not stable enough for use and is subject to change";
1840 pub const EXPLAIN_ALLOW_INTERNAL_UNSTABLE: &str =
1841 "allow_internal_unstable side-steps feature gating and stability checks";
1842 pub const EXPLAIN_ALLOW_INTERNAL_UNSAFE: &str =
1843 "allow_internal_unsafe side-steps the unsafe_code lint";
1845 pub const EXPLAIN_UNSIZED_TUPLE_COERCION: &str =
1846 "unsized tuple coercion is not stable enough for use and is subject to change";
1848 struct PostExpansionVisitor<'a> {
1849 context: &'a Context<'a>,
1850 builtin_attributes: &'static FxHashMap<Symbol, &'static BuiltinAttribute>,
1853 macro_rules! gate_feature_post {
1854 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {{
1855 let (cx, span) = ($cx, $span);
1856 if !span.allows_unstable(sym::$feature) {
1857 gate_feature!(cx.context, $feature, span, $explain)
1860 ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {{
1861 let (cx, span) = ($cx, $span);
1862 if !span.allows_unstable(sym::$feature) {
1863 gate_feature!(cx.context, $feature, span, $explain, $level)
1868 impl<'a> PostExpansionVisitor<'a> {
1869 fn check_abi(&self, abi: Abi, span: Span) {
1871 Abi::RustIntrinsic => {
1872 gate_feature_post!(&self, intrinsics, span,
1873 "intrinsics are subject to change");
1875 Abi::PlatformIntrinsic => {
1876 gate_feature_post!(&self, platform_intrinsics, span,
1877 "platform intrinsics are experimental and possibly buggy");
1879 Abi::Vectorcall => {
1880 gate_feature_post!(&self, abi_vectorcall, span,
1881 "vectorcall is experimental and subject to change");
1884 gate_feature_post!(&self, abi_thiscall, span,
1885 "thiscall is experimental and subject to change");
1888 gate_feature_post!(&self, unboxed_closures, span,
1889 "rust-call ABI is subject to change");
1892 gate_feature_post!(&self, abi_ptx, span,
1893 "PTX ABIs are experimental and subject to change");
1895 Abi::Unadjusted => {
1896 gate_feature_post!(&self, abi_unadjusted, span,
1897 "unadjusted ABI is an implementation detail and perma-unstable");
1899 Abi::Msp430Interrupt => {
1900 gate_feature_post!(&self, abi_msp430_interrupt, span,
1901 "msp430-interrupt ABI is experimental and subject to change");
1903 Abi::X86Interrupt => {
1904 gate_feature_post!(&self, abi_x86_interrupt, span,
1905 "x86-interrupt ABI is experimental and subject to change");
1907 Abi::AmdGpuKernel => {
1908 gate_feature_post!(&self, abi_amdgpu_kernel, span,
1909 "amdgpu-kernel ABI is experimental and subject to change");
1924 fn check_builtin_attribute(&mut self, attr: &ast::Attribute, name: Symbol,
1925 template: AttributeTemplate) {
1926 // Some special attributes like `cfg` must be checked
1927 // before the generic check, so we skip them here.
1928 let should_skip = |name| name == sym::cfg;
1929 // Some of previously accepted forms were used in practice,
1930 // report them as warnings for now.
1931 let should_warn = |name| name == sym::doc || name == sym::ignore ||
1932 name == sym::inline || name == sym::link;
1934 match attr.parse_meta(self.context.parse_sess) {
1935 Ok(meta) => if !should_skip(name) && !template.compatible(&meta.node) {
1936 let error_msg = format!("malformed `{}` attribute input", name);
1937 let mut msg = "attribute must be of the form ".to_owned();
1938 let mut suggestions = vec![];
1939 let mut first = true;
1942 let code = format!("#[{}]", name);
1943 msg.push_str(&format!("`{}`", &code));
1944 suggestions.push(code);
1946 if let Some(descr) = template.list {
1948 msg.push_str(" or ");
1951 let code = format!("#[{}({})]", name, descr);
1952 msg.push_str(&format!("`{}`", &code));
1953 suggestions.push(code);
1955 if let Some(descr) = template.name_value_str {
1957 msg.push_str(" or ");
1959 let code = format!("#[{} = \"{}\"]", name, descr);
1960 msg.push_str(&format!("`{}`", &code));
1961 suggestions.push(code);
1963 if should_warn(name) {
1964 self.context.parse_sess.buffer_lint(
1965 BufferedEarlyLintId::IllFormedAttributeInput,
1971 self.context.parse_sess.span_diagnostic.struct_span_err(meta.span, &error_msg)
1974 if suggestions.len() == 1 {
1975 "must be of the form"
1977 "the following are the possible correct uses"
1979 suggestions.into_iter(),
1980 Applicability::HasPlaceholders,
1984 Err(mut err) => err.emit(),
1989 impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
1990 fn visit_attribute(&mut self, attr: &ast::Attribute) {
1991 let attr_info = attr.ident().and_then(|ident| {
1992 self.builtin_attributes.get(&ident.name).map(|a| *a)
1995 // Check for gated attributes.
1996 self.context.check_attribute(attr, attr_info, false);
1998 if attr.check_name(sym::doc) {
1999 if let Some(content) = attr.meta_item_list() {
2000 if content.len() == 1 && content[0].check_name(sym::cfg) {
2001 gate_feature_post!(&self, doc_cfg, attr.span,
2002 "#[doc(cfg(...))] is experimental"
2004 } else if content.iter().any(|c| c.check_name(sym::masked)) {
2005 gate_feature_post!(&self, doc_masked, attr.span,
2006 "#[doc(masked)] is experimental"
2008 } else if content.iter().any(|c| c.check_name(sym::spotlight)) {
2009 gate_feature_post!(&self, doc_spotlight, attr.span,
2010 "#[doc(spotlight)] is experimental"
2012 } else if content.iter().any(|c| c.check_name(sym::alias)) {
2013 gate_feature_post!(&self, doc_alias, attr.span,
2014 "#[doc(alias = \"...\")] is experimental"
2016 } else if content.iter().any(|c| c.check_name(sym::keyword)) {
2017 gate_feature_post!(&self, doc_keyword, attr.span,
2018 "#[doc(keyword = \"...\")] is experimental"
2025 // `rustc_dummy` doesn't have any restrictions specific to built-in attributes.
2026 Some(&(name, _, template, _)) if name != sym::rustc_dummy =>
2027 self.check_builtin_attribute(attr, name, template),
2028 _ => if let Some(TokenTree::Token(token)) = attr.tokens.trees().next() {
2029 if token == token::Eq {
2030 // All key-value attributes are restricted to meta-item syntax.
2031 attr.parse_meta(self.context.parse_sess).map_err(|mut err| err.emit()).ok();
2037 fn visit_name(&mut self, sp: Span, name: ast::Name) {
2038 if !name.as_str().is_ascii() {
2042 self.context.parse_sess.source_map().def_span(sp),
2043 "non-ascii idents are not fully supported"
2048 fn visit_item(&mut self, i: &'a ast::Item) {
2050 ast::ItemKind::ForeignMod(ref foreign_module) => {
2051 self.check_abi(foreign_module.abi, i.span);
2054 ast::ItemKind::Fn(..) => {
2055 if attr::contains_name(&i.attrs[..], sym::plugin_registrar) {
2056 gate_feature_post!(&self, plugin_registrar, i.span,
2057 "compiler plugins are experimental and possibly buggy");
2059 if attr::contains_name(&i.attrs[..], sym::start) {
2060 gate_feature_post!(&self, start, i.span,
2061 "a #[start] function is an experimental \
2062 feature whose signature may change \
2065 if attr::contains_name(&i.attrs[..], sym::main) {
2066 gate_feature_post!(&self, main, i.span,
2067 "declaration of a nonstandard #[main] \
2068 function may change over time, for now \
2069 a top-level `fn main()` is required");
2073 ast::ItemKind::Struct(..) => {
2074 for attr in attr::filter_by_name(&i.attrs[..], sym::repr) {
2075 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
2076 if item.check_name(sym::simd) {
2077 gate_feature_post!(&self, repr_simd, attr.span,
2078 "SIMD types are experimental and possibly buggy");
2084 ast::ItemKind::Enum(ast::EnumDef{ref variants, ..}, ..) => {
2085 for variant in variants {
2086 match (&variant.node.data, &variant.node.disr_expr) {
2087 (ast::VariantData::Unit(..), _) => {},
2088 (_, Some(disr_expr)) =>
2091 arbitrary_enum_discriminant,
2092 disr_expr.value.span,
2093 "discriminants on non-unit variants are experimental"),
2098 let has_feature = self.context.features.arbitrary_enum_discriminant;
2099 if !has_feature && !i.span.allows_unstable(sym::arbitrary_enum_discriminant) {
2100 Parser::maybe_report_invalid_custom_discriminants(
2101 self.context.parse_sess,
2107 ast::ItemKind::Impl(_, polarity, defaultness, _, _, _, _) => {
2108 if polarity == ast::ImplPolarity::Negative {
2109 gate_feature_post!(&self, optin_builtin_traits,
2111 "negative trait bounds are not yet fully implemented; \
2112 use marker types for now");
2115 if let ast::Defaultness::Default = defaultness {
2116 gate_feature_post!(&self, specialization,
2118 "specialization is unstable");
2122 ast::ItemKind::Trait(ast::IsAuto::Yes, ..) => {
2123 gate_feature_post!(&self, optin_builtin_traits,
2125 "auto traits are experimental and possibly buggy");
2128 ast::ItemKind::TraitAlias(..) => {
2133 "trait aliases are experimental"
2137 ast::ItemKind::MacroDef(ast::MacroDef { legacy: false, .. }) => {
2138 let msg = "`macro` is experimental";
2139 gate_feature_post!(&self, decl_macro, i.span, msg);
2142 ast::ItemKind::Existential(..) => {
2147 "existential types are unstable"
2154 visit::walk_item(self, i);
2157 fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
2159 ast::ForeignItemKind::Fn(..) |
2160 ast::ForeignItemKind::Static(..) => {
2161 let link_name = attr::first_attr_value_str_by_name(&i.attrs, sym::link_name);
2162 let links_to_llvm = match link_name {
2163 Some(val) => val.as_str().starts_with("llvm."),
2167 gate_feature_post!(&self, link_llvm_intrinsics, i.span,
2168 "linking to LLVM intrinsics is experimental");
2171 ast::ForeignItemKind::Ty => {
2172 gate_feature_post!(&self, extern_types, i.span,
2173 "extern types are experimental");
2175 ast::ForeignItemKind::Macro(..) => {}
2178 visit::walk_foreign_item(self, i)
2181 fn visit_ty(&mut self, ty: &'a ast::Ty) {
2183 ast::TyKind::BareFn(ref bare_fn_ty) => {
2184 self.check_abi(bare_fn_ty.abi, ty.span);
2186 ast::TyKind::Never => {
2187 gate_feature_post!(&self, never_type, ty.span,
2188 "The `!` type is experimental");
2192 visit::walk_ty(self, ty)
2195 fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FunctionRetTy) {
2196 if let ast::FunctionRetTy::Ty(ref output_ty) = *ret_ty {
2197 if let ast::TyKind::Never = output_ty.node {
2200 self.visit_ty(output_ty)
2205 fn visit_expr(&mut self, e: &'a ast::Expr) {
2207 ast::ExprKind::Box(_) => {
2208 gate_feature_post!(&self, box_syntax, e.span, EXPLAIN_BOX_SYNTAX);
2210 ast::ExprKind::Type(..) => {
2211 // To avoid noise about type ascription in common syntax errors, only emit if it
2212 // is the *only* error.
2213 if self.context.parse_sess.span_diagnostic.err_count() == 0 {
2214 gate_feature_post!(&self, type_ascription, e.span,
2215 "type ascription is experimental");
2218 ast::ExprKind::Yield(..) => {
2219 gate_feature_post!(&self, generators,
2221 "yield syntax is experimental");
2223 ast::ExprKind::TryBlock(_) => {
2224 gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
2226 ast::ExprKind::Block(_, opt_label) => {
2227 if let Some(label) = opt_label {
2228 gate_feature_post!(&self, label_break_value, label.ident.span,
2229 "labels on blocks are unstable");
2232 ast::ExprKind::Async(..) => {
2233 gate_feature_post!(&self, async_await, e.span, "async blocks are unstable");
2235 ast::ExprKind::Await(origin, _) => {
2237 ast::AwaitOrigin::FieldLike =>
2238 gate_feature_post!(&self, async_await, e.span, "async/await is unstable"),
2239 ast::AwaitOrigin::MacroLike =>
2244 "`await!(<expr>)` macro syntax is unstable, and will soon be removed \
2245 in favor of `<expr>.await` syntax."
2251 visit::walk_expr(self, e)
2254 fn visit_arm(&mut self, arm: &'a ast::Arm) {
2255 visit::walk_arm(self, arm)
2258 fn visit_pat(&mut self, pattern: &'a ast::Pat) {
2259 match pattern.node {
2260 PatKind::Slice(_, Some(ref subslice), _) => {
2261 gate_feature_post!(&self, slice_patterns,
2263 "syntax for subslices in slice patterns is not yet stabilized");
2265 PatKind::Box(..) => {
2266 gate_feature_post!(&self, box_patterns,
2268 "box pattern syntax is experimental");
2270 PatKind::Range(_, _, Spanned { node: RangeEnd::Excluded, .. }) => {
2271 gate_feature_post!(&self, exclusive_range_pattern, pattern.span,
2272 "exclusive range pattern syntax is experimental");
2276 visit::walk_pat(self, pattern)
2279 fn visit_fn(&mut self,
2280 fn_kind: FnKind<'a>,
2281 fn_decl: &'a ast::FnDecl,
2284 if let Some(header) = fn_kind.header() {
2285 // Check for const fn and async fn declarations.
2286 if header.asyncness.node.is_async() {
2287 gate_feature_post!(&self, async_await, span, "async fn is unstable");
2290 // Stability of const fn methods are covered in
2291 // `visit_trait_item` and `visit_impl_item` below; this is
2292 // because default methods don't pass through this point.
2293 self.check_abi(header.abi, span);
2296 if fn_decl.c_variadic {
2297 gate_feature_post!(&self, c_variadic, span, "C-variadic functions are unstable");
2300 visit::walk_fn(self, fn_kind, fn_decl, span)
2303 fn visit_generic_param(&mut self, param: &'a GenericParam) {
2305 GenericParamKind::Const { .. } =>
2306 gate_feature_post!(&self, const_generics, param.ident.span,
2307 "const generics are unstable"),
2310 visit::walk_generic_param(self, param)
2313 fn visit_assoc_ty_constraint(&mut self, constraint: &'a AssocTyConstraint) {
2314 match constraint.kind {
2315 AssocTyConstraintKind::Bound { .. } =>
2316 gate_feature_post!(&self, associated_type_bounds, constraint.span,
2317 "associated type bounds are unstable"),
2320 visit::walk_assoc_ty_constraint(self, constraint)
2323 fn visit_trait_item(&mut self, ti: &'a ast::TraitItem) {
2325 ast::TraitItemKind::Method(ref sig, ref block) => {
2326 if block.is_none() {
2327 self.check_abi(sig.header.abi, ti.span);
2329 if sig.header.asyncness.node.is_async() {
2330 gate_feature_post!(&self, async_await, ti.span, "async fn is unstable");
2332 if sig.decl.c_variadic {
2333 gate_feature_post!(&self, c_variadic, ti.span,
2334 "C-variadic functions are unstable");
2336 if sig.header.constness.node == ast::Constness::Const {
2337 gate_feature_post!(&self, const_fn, ti.span, "const fn is unstable");
2340 ast::TraitItemKind::Type(_, ref default) => {
2341 // We use three if statements instead of something like match guards so that all
2342 // of these errors can be emitted if all cases apply.
2343 if default.is_some() {
2344 gate_feature_post!(&self, associated_type_defaults, ti.span,
2345 "associated type defaults are unstable");
2347 if !ti.generics.params.is_empty() {
2348 gate_feature_post!(&self, generic_associated_types, ti.span,
2349 "generic associated types are unstable");
2351 if !ti.generics.where_clause.predicates.is_empty() {
2352 gate_feature_post!(&self, generic_associated_types, ti.span,
2353 "where clauses on associated types are unstable");
2358 visit::walk_trait_item(self, ti)
2361 fn visit_impl_item(&mut self, ii: &'a ast::ImplItem) {
2362 if ii.defaultness == ast::Defaultness::Default {
2363 gate_feature_post!(&self, specialization,
2365 "specialization is unstable");
2369 ast::ImplItemKind::Method(..) => {}
2370 ast::ImplItemKind::Existential(..) => {
2375 "existential types are unstable"
2378 ast::ImplItemKind::Type(_) => {
2379 if !ii.generics.params.is_empty() {
2380 gate_feature_post!(&self, generic_associated_types, ii.span,
2381 "generic associated types are unstable");
2383 if !ii.generics.where_clause.predicates.is_empty() {
2384 gate_feature_post!(&self, generic_associated_types, ii.span,
2385 "where clauses on associated types are unstable");
2390 visit::walk_impl_item(self, ii)
2393 fn visit_vis(&mut self, vis: &'a ast::Visibility) {
2394 if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.node {
2395 gate_feature_post!(&self, crate_visibility_modifier, vis.span,
2396 "`crate` visibility modifier is experimental");
2398 visit::walk_vis(self, vis)
2402 pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
2403 crate_edition: Edition, allow_features: &Option<Vec<String>>) -> Features {
2404 fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) {
2405 let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
2406 if let Some(reason) = reason {
2407 err.span_note(span, reason);
2409 err.span_label(span, "feature has been removed");
2414 let mut features = Features::new();
2415 let mut edition_enabled_features = FxHashMap::default();
2417 for &edition in ALL_EDITIONS {
2418 if edition <= crate_edition {
2419 // The `crate_edition` implies its respective umbrella feature-gate
2420 // (i.e., `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX).
2421 edition_enabled_features.insert(edition.feature_name(), edition);
2425 for &(name, .., f_edition, set) in ACTIVE_FEATURES {
2426 if let Some(f_edition) = f_edition {
2427 if f_edition <= crate_edition {
2428 set(&mut features, DUMMY_SP);
2429 edition_enabled_features.insert(name, crate_edition);
2434 // Process the edition umbrella feature-gates first, to ensure
2435 // `edition_enabled_features` is completed before it's queried.
2436 for attr in krate_attrs {
2437 if !attr.check_name(sym::feature) {
2441 let list = match attr.meta_item_list() {
2451 let name = mi.name_or_empty();
2452 if INCOMPLETE_FEATURES.iter().any(|f| name == *f) {
2453 span_handler.struct_span_warn(
2456 "the feature `{}` is incomplete and may cause the compiler to crash",
2462 if let Some(edition) = ALL_EDITIONS.iter().find(|e| name == e.feature_name()) {
2463 if *edition <= crate_edition {
2467 for &(name, .., f_edition, set) in ACTIVE_FEATURES {
2468 if let Some(f_edition) = f_edition {
2469 if f_edition <= *edition {
2470 // FIXME(Manishearth) there is currently no way to set
2471 // lib features by edition
2472 set(&mut features, DUMMY_SP);
2473 edition_enabled_features.insert(name, *edition);
2481 for attr in krate_attrs {
2482 if !attr.check_name(sym::feature) {
2486 let list = match attr.meta_item_list() {
2491 let bad_input = |span| {
2492 struct_span_err!(span_handler, span, E0556, "malformed `feature` attribute input")
2496 let name = match mi.ident() {
2497 Some(ident) if mi.is_word() => ident.name,
2499 bad_input(mi.span()).span_suggestion(
2501 "expected just one word",
2502 format!("{}", ident.name),
2503 Applicability::MaybeIncorrect,
2508 bad_input(mi.span()).span_label(mi.span(), "expected just one word").emit();
2513 if let Some(edition) = edition_enabled_features.get(&name) {
2518 "the feature `{}` is included in the Rust {} edition",
2525 if ALL_EDITIONS.iter().any(|e| name == e.feature_name()) {
2526 // Handled in the separate loop above.
2530 let removed = REMOVED_FEATURES.iter().find(|f| name == f.0);
2531 let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.0);
2532 if let Some((.., reason)) = removed.or(stable_removed) {
2533 feature_removed(span_handler, mi.span(), *reason);
2537 if let Some((_, since, ..)) = ACCEPTED_FEATURES.iter().find(|f| name == f.0) {
2538 let since = Some(Symbol::intern(since));
2539 features.declared_lang_features.push((name, mi.span(), since));
2543 if let Some(allowed) = allow_features.as_ref() {
2544 if allowed.iter().find(|f| *f == name.as_str()).is_none() {
2545 span_err!(span_handler, mi.span(), E0725,
2546 "the feature `{}` is not in the list of allowed features",
2552 if let Some((.., set)) = ACTIVE_FEATURES.iter().find(|f| name == f.0) {
2553 set(&mut features, mi.span());
2554 features.declared_lang_features.push((name, mi.span(), None));
2558 features.declared_lib_features.push((name, mi.span()));
2565 fn for_each_in_lock<T>(vec: &Lock<Vec<T>>, f: impl Fn(&T)) {
2566 vec.borrow().iter().for_each(f);
2569 pub fn check_crate(krate: &ast::Crate,
2571 features: &Features,
2572 plugin_attributes: &[(Symbol, AttributeType)],
2573 unstable: UnstableFeatures) {
2574 maybe_stage_features(&sess.span_diagnostic, krate, unstable);
2581 for_each_in_lock(&sess.param_attr_spans, |span| gate_feature!(
2585 "attributes on function parameters are unstable"
2588 for_each_in_lock(&sess.let_chains_spans, |span| gate_feature!(
2592 "`let` expressions in this position are experimental"
2595 for_each_in_lock(&sess.async_closure_spans, |span| gate_feature!(
2599 "async closures are unstable"
2602 let visitor = &mut PostExpansionVisitor {
2604 builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP,
2606 visit::walk_crate(visitor, krate);
2609 #[derive(Clone, Copy, Hash)]
2610 pub enum UnstableFeatures {
2611 /// Hard errors for unstable features are active, as on beta/stable channels.
2613 /// Allow features to be activated, as on nightly.
2615 /// Errors are bypassed for bootstrapping. This is required any time
2616 /// during the build that feature-related lints are set to warn or above
2617 /// because the build turns on warnings-as-errors and uses lots of unstable
2618 /// features. As a result, this is always required for building Rust itself.
2622 impl UnstableFeatures {
2623 pub fn from_environment() -> UnstableFeatures {
2624 // Whether this is a feature-staged build, i.e., on the beta or stable channel
2625 let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
2626 // Whether we should enable unstable features for bootstrapping
2627 let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok();
2628 match (disable_unstable_features, bootstrap) {
2629 (_, true) => UnstableFeatures::Cheat,
2630 (true, _) => UnstableFeatures::Disallow,
2631 (false, _) => UnstableFeatures::Allow
2635 pub fn is_nightly_build(&self) -> bool {
2637 UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
2643 fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate,
2644 unstable: UnstableFeatures) {
2645 let allow_features = match unstable {
2646 UnstableFeatures::Allow => true,
2647 UnstableFeatures::Disallow => false,
2648 UnstableFeatures::Cheat => true
2650 if !allow_features {
2651 for attr in &krate.attrs {
2652 if attr.check_name(sym::feature) {
2653 let release_channel = option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)");
2654 span_err!(span_handler, attr.span, E0554,
2655 "#![feature] may not be used on the {} release channel",