1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 //! This module implements the gating necessary for preventing certain compiler
14 //! features from being used by default. This module will crawl a pre-expanded
15 //! AST to ensure that there are no features which are used that are not
18 //! Features are enabled in programs via the crate-level attributes of
19 //! `#![feature(...)]` with a comma-separated list of features.
21 //! For the purpose of future feature-tracking, once code for detection of feature
22 //! gate usage is added, *do not remove it again* even once the feature
25 use self::AttributeType::*;
26 use self::AttributeGate::*;
28 use rustc_data_structures::fx::FxHashMap;
29 use rustc_target::spec::abi::Abi;
30 use ast::{self, NodeId, PatKind, RangeEnd};
33 use edition::{ALL_EDITIONS, Edition};
34 use syntax_pos::{Span, DUMMY_SP};
35 use errors::{DiagnosticBuilder, Handler};
36 use visit::{self, FnKind, Visitor};
38 use symbol::{keywords, Symbol};
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 &'static [(&'static str, &'static str, Option<u32>,
57 Option<Edition>, fn(&mut Features, Span))] =
58 &[$((stringify!($feature), $ver, $issue, $edition, set!($feature))),+];
60 /// A set of features to be used by later passes.
63 /// `#![feature]` attrs for language features, for error reporting
64 pub declared_lang_features: Vec<(Symbol, Span, Option<Symbol>)>,
65 /// `#![feature]` attrs for non-language (library) features
66 pub declared_lib_features: Vec<(Symbol, Span)>,
67 $(pub $feature: bool),+
71 pub fn new() -> Features {
73 declared_lang_features: Vec::new(),
74 declared_lib_features: Vec::new(),
79 pub fn walk_feature_fields<F>(&self, mut f: F)
80 where F: FnMut(&str, bool)
82 $(f(stringify!($feature), self.$feature);)+
85 pub fn use_extern_macros(&self) -> bool {
86 // A number of "advanced" macro features enable
87 // macro modularization (`use_extern_macros`) implicitly.
88 self.use_extern_macros || self.decl_macro ||
89 self.tool_attributes || self.custom_attribute ||
90 self.macros_in_extern || self.proc_macro_path_invoc ||
91 self.proc_macro_mod || self.proc_macro_expr ||
92 self.proc_macro_non_items || self.proc_macro_gen ||
93 self.stmt_expr_attributes || self.unrestricted_attribute_tokens
98 ($((removed, $feature: ident, $ver: expr, $issue: expr, None, $reason: expr),)+) => {
99 /// Represents unstable features which have since been removed (it was once Active)
100 const REMOVED_FEATURES: &[(&str, &str, Option<u32>, Option<&str>)] = &[
101 $((stringify!($feature), $ver, $issue, $reason)),+
105 ($((stable_removed, $feature: ident, $ver: expr, $issue: expr, None),)+) => {
106 /// Represents stable features which have since been removed (it was once Accepted)
107 const STABLE_REMOVED_FEATURES: &[(&str, &str, Option<u32>, Option<&str>)] = &[
108 $((stringify!($feature), $ver, $issue, None)),+
112 ($((accepted, $feature: ident, $ver: expr, $issue: expr, None),)+) => {
113 /// Those language feature has since been Accepted (it was once Active)
114 const ACCEPTED_FEATURES: &[(&str, &str, Option<u32>, Option<&str>)] = &[
115 $((stringify!($feature), $ver, $issue, None)),+
120 // If you change this, please modify src/doc/unstable-book as well.
122 // Don't ever remove anything from this list; set them to 'Removed'.
124 // The version numbers here correspond to the version in which the current status
125 // was set. This is most important for knowing when a particular feature became
128 // NB: tools/tidy/src/features.rs parses this information directly out of the
129 // source, so take care when modifying it.
132 (active, asm, "1.0.0", Some(29722), None),
133 (active, concat_idents, "1.0.0", Some(29599), None),
134 (active, link_args, "1.0.0", Some(29596), None),
135 (active, log_syntax, "1.0.0", Some(29598), None),
136 (active, non_ascii_idents, "1.0.0", Some(28979), None),
137 (active, plugin_registrar, "1.0.0", Some(29597), None),
138 (active, thread_local, "1.0.0", Some(29594), None),
139 (active, trace_macros, "1.0.0", Some(29598), None),
141 // rustc internal, for now:
142 (active, intrinsics, "1.0.0", None, None),
143 (active, lang_items, "1.0.0", None, None),
144 (active, format_args_nl, "1.29.0", None, None),
146 (active, link_llvm_intrinsics, "1.0.0", Some(29602), None),
147 (active, linkage, "1.0.0", Some(29603), None),
148 (active, quote, "1.0.0", Some(29601), None),
151 (active, rustc_diagnostic_macros, "1.0.0", None, None),
152 (active, rustc_const_unstable, "1.0.0", None, None),
153 (active, box_syntax, "1.0.0", Some(49733), None),
154 (active, unboxed_closures, "1.0.0", Some(29625), None),
156 (active, fundamental, "1.0.0", Some(29635), None),
157 (active, main, "1.0.0", Some(29634), None),
158 (active, needs_allocator, "1.4.0", Some(27389), None),
159 (active, on_unimplemented, "1.0.0", Some(29628), None),
160 (active, plugin, "1.0.0", Some(29597), None),
161 (active, simd_ffi, "1.0.0", Some(27731), None),
162 (active, start, "1.0.0", Some(29633), None),
163 (active, structural_match, "1.8.0", Some(31434), None),
164 (active, panic_runtime, "1.10.0", Some(32837), None),
165 (active, needs_panic_runtime, "1.10.0", Some(32837), None),
167 // OIBIT specific features
168 (active, optin_builtin_traits, "1.0.0", Some(13231), None),
170 // Allows use of #[staged_api]
172 (active, staged_api, "1.0.0", None, None),
174 // Allows using #![no_core]
175 (active, no_core, "1.3.0", Some(29639), None),
177 // Allows using `box` in patterns; RFC 469
178 (active, box_patterns, "1.0.0", Some(29641), None),
180 // Allows using the unsafe_destructor_blind_to_params attribute;
182 (active, dropck_parametricity, "1.3.0", Some(28498), None),
184 // Allows using the may_dangle attribute; RFC 1327
185 (active, dropck_eyepatch, "1.10.0", Some(34761), None),
187 // Allows the use of custom attributes; RFC 572
188 (active, custom_attribute, "1.0.0", Some(29642), None),
190 // Allows the use of #[derive(Anything)] as sugar for
191 // #[derive_Anything].
192 (active, custom_derive, "1.0.0", Some(29644), None),
194 // Allows the use of rustc_* attributes; RFC 572
195 (active, rustc_attrs, "1.0.0", Some(29642), None),
197 // Allows the use of non lexical lifetimes; RFC 2094
198 (active, nll, "1.0.0", Some(43234), None),
200 // Allows the use of #[allow_internal_unstable]. This is an
201 // attribute on macro_rules! and can't use the attribute handling
202 // below (it has to be checked before expansion possibly makes
203 // macros disappear).
206 (active, allow_internal_unstable, "1.0.0", None, None),
208 // Allows the use of #[allow_internal_unsafe]. This is an
209 // attribute on macro_rules! and can't use the attribute handling
210 // below (it has to be checked before expansion possibly makes
211 // macros disappear).
214 (active, allow_internal_unsafe, "1.0.0", None, None),
216 // #23121. Array patterns have some hazards yet.
217 (active, slice_patterns, "1.0.0", Some(23121), None),
219 // Allows the definition of `const fn` functions.
220 (active, const_fn, "1.2.0", Some(24111), None),
222 // Allows let bindings and destructuring in `const fn` functions and constants.
223 (active, const_let, "1.22.1", Some(48821), None),
225 // Allows accessing fields of unions inside const fn
226 (active, const_fn_union, "1.27.0", Some(51909), None),
228 // Allows casting raw pointers to `usize` during const eval
229 (active, const_raw_ptr_to_usize_cast, "1.27.0", Some(51910), None),
231 // Allows dereferencing raw pointers during const eval
232 (active, const_raw_ptr_deref, "1.27.0", Some(51911), None),
234 // Allows comparing raw pointers during const eval
235 (active, const_compare_raw_pointers, "1.27.0", Some(53020), None),
237 // Allows using #[prelude_import] on glob `use` items.
240 (active, prelude_import, "1.2.0", None, None),
242 // Allows default type parameters to influence type inference.
243 (active, default_type_parameter_fallback, "1.3.0", Some(27336), None),
245 // Allows associated type defaults
246 (active, associated_type_defaults, "1.2.0", Some(29661), None),
248 // allow `repr(simd)`, and importing the various simd intrinsics
249 (active, repr_simd, "1.4.0", Some(27731), None),
251 // allow `extern "platform-intrinsic" { ... }`
252 (active, platform_intrinsics, "1.4.0", Some(27731), None),
254 // allow `#[unwind(..)]`
255 // rustc internal for rust runtime
256 (active, unwind_attributes, "1.4.0", None, None),
258 // allow the use of `#[naked]` on functions.
259 (active, naked_functions, "1.9.0", Some(32408), None),
261 // allow `#[no_debug]`
262 (active, no_debug, "1.5.0", Some(29721), None),
264 // allow `#[omit_gdb_pretty_printer_section]`
266 (active, omit_gdb_pretty_printer_section, "1.5.0", None, None),
268 // Allows cfg(target_vendor = "...").
269 (active, cfg_target_vendor, "1.5.0", Some(29718), None),
271 // Allow attributes on expressions and non-item statements
272 (active, stmt_expr_attributes, "1.6.0", Some(15701), None),
274 // allow using type ascription in expressions
275 (active, type_ascription, "1.6.0", Some(23416), None),
277 // Allows cfg(target_thread_local)
278 (active, cfg_target_thread_local, "1.7.0", Some(29594), None),
281 (active, abi_vectorcall, "1.7.0", None, None),
284 (active, exclusive_range_pattern, "1.11.0", Some(37854), None),
286 // impl specialization (RFC 1210)
287 (active, specialization, "1.7.0", Some(31844), None),
289 // Allows cfg(target_has_atomic = "...").
290 (active, cfg_target_has_atomic, "1.9.0", Some(32976), None),
292 // The `!` type. Does not imply exhaustive_patterns (below) any more.
293 (active, never_type, "1.13.0", Some(35121), None),
295 // Allows exhaustive pattern matching on types that contain uninhabited types.
296 (active, exhaustive_patterns, "1.13.0", Some(51085), None),
298 // Allows all literals in attribute lists and values of key-value pairs.
299 (active, attr_literals, "1.13.0", Some(34981), None),
301 // Allows untagged unions `union U { ... }`
302 (active, untagged_unions, "1.13.0", Some(32836), None),
304 // Used to identify the `compiler_builtins` crate
306 (active, compiler_builtins, "1.13.0", None, None),
308 // Allows #[link(..., cfg(..))]
309 (active, link_cfg, "1.14.0", Some(37406), None),
311 (active, use_extern_macros, "1.15.0", Some(35896), Some(Edition::Edition2018)),
313 // `extern "ptx-*" fn()`
314 (active, abi_ptx, "1.15.0", Some(38788), None),
316 // The `repr(i128)` annotation for enums
317 (active, repr128, "1.16.0", Some(35118), None),
319 // The `unadjusted` ABI. Perma unstable.
321 (active, abi_unadjusted, "1.16.0", None, None),
323 // Declarative macros 2.0 (`macro`).
324 (active, decl_macro, "1.17.0", Some(39412), None),
326 // Allows #[link(kind="static-nobundle"...)]
327 (active, static_nobundle, "1.16.0", Some(37403), None),
329 // `extern "msp430-interrupt" fn()`
330 (active, abi_msp430_interrupt, "1.16.0", Some(38487), None),
332 // Used to identify crates that contain sanitizer runtimes
334 (active, sanitizer_runtime, "1.17.0", None, None),
336 // Used to identify crates that contain the profiler runtime
338 (active, profiler_runtime, "1.18.0", None, None),
340 // `extern "x86-interrupt" fn()`
341 (active, abi_x86_interrupt, "1.17.0", Some(40180), None),
343 // Allows the `catch {...}` expression
344 (active, catch_expr, "1.17.0", Some(31436), None),
346 // Used to preserve symbols (see llvm.used)
347 (active, used, "1.18.0", Some(40289), None),
349 // Allows module-level inline assembly by way of global_asm!()
350 (active, global_asm, "1.18.0", Some(35119), None),
352 // Allows overlapping impls of marker traits
353 (active, overlapping_marker_traits, "1.18.0", Some(29864), None),
355 // Allows use of the :vis macro fragment specifier
356 (active, macro_vis_matcher, "1.18.0", Some(41022), None),
359 (active, abi_thiscall, "1.19.0", None, None),
361 // Allows a test to fail without failing the whole suite
362 (active, allow_fail, "1.19.0", Some(42219), None),
364 // Allows unsized tuple coercion.
365 (active, unsized_tuple_coercion, "1.20.0", Some(42877), None),
368 (active, generators, "1.21.0", Some(43122), None),
371 (active, trait_alias, "1.24.0", Some(41517), None),
374 (active, allocator_internals, "1.20.0", None, None),
377 (active, doc_cfg, "1.21.0", Some(43781), None),
379 (active, doc_masked, "1.21.0", Some(44027), None),
381 (active, doc_spotlight, "1.22.0", Some(45040), None),
382 // #[doc(include="some-file")]
383 (active, external_doc, "1.22.0", Some(44732), None),
385 // Future-proofing enums/structs with #[non_exhaustive] attribute (RFC 2008)
386 (active, non_exhaustive, "1.22.0", Some(44109), None),
388 // `crate` as visibility modifier, synonymous to `pub(crate)`
389 (active, crate_visibility_modifier, "1.23.0", Some(45388), Some(Edition::Edition2018)),
392 (active, extern_types, "1.23.0", Some(43467), None),
394 // Allow trait methods with arbitrary self types
395 (active, arbitrary_self_types, "1.23.0", Some(44874), None),
398 (active, crate_in_paths, "1.23.0", Some(45477), Some(Edition::Edition2018)),
400 // In-band lifetime bindings (e.g. `fn foo(x: &'a u8) -> &'a u8`)
401 (active, in_band_lifetimes, "1.23.0", Some(44524), None),
403 // generic associated types (RFC 1598)
404 (active, generic_associated_types, "1.23.0", Some(44265), None),
406 // Resolve absolute paths as paths from other crates
407 (active, extern_absolute_paths, "1.24.0", Some(44660), Some(Edition::Edition2018)),
409 // `foo.rs` as an alternative to `foo/mod.rs`
410 (active, non_modrs_mods, "1.24.0", Some(44660), Some(Edition::Edition2018)),
413 (active, extern_in_paths, "1.23.0", Some(44660), None),
415 // Use `?` as the Kleene "at most one" operator
416 (active, macro_at_most_once_rep, "1.25.0", Some(48075), None),
418 // Infer outlives requirements; RFC 2093
419 (active, infer_outlives_requirements, "1.26.0", Some(44493), None),
421 // Infer static outlives requirements; RFC 2093
422 (active, infer_static_outlives_requirements, "1.26.0", Some(44493), None),
424 // Multiple patterns with `|` in `if let` and `while let`
425 (active, if_while_or_patterns, "1.26.0", Some(48215), None),
427 // Parentheses in patterns
428 (active, pattern_parentheses, "1.26.0", Some(51087), None),
430 // Allows `#[repr(packed)]` attribute on structs
431 (active, repr_packed, "1.26.0", Some(33158), None),
433 // `use path as _;` and `extern crate c as _;`
434 (active, underscore_imports, "1.26.0", Some(48216), None),
436 // Allows keywords to be escaped for use as identifiers
437 (active, raw_identifiers, "1.26.0", Some(48589), Some(Edition::Edition2018)),
439 // Allows macro invocations in `extern {}` blocks
440 (active, macros_in_extern, "1.27.0", Some(49476), None),
442 // `existential type`
443 (active, existential_type, "1.28.0", Some(34511), None),
445 // unstable #[target_feature] directives
446 (active, arm_target_feature, "1.27.0", Some(44839), None),
447 (active, aarch64_target_feature, "1.27.0", Some(44839), None),
448 (active, hexagon_target_feature, "1.27.0", Some(44839), None),
449 (active, powerpc_target_feature, "1.27.0", Some(44839), None),
450 (active, mips_target_feature, "1.27.0", Some(44839), None),
451 (active, avx512_target_feature, "1.27.0", Some(44839), None),
452 (active, mmx_target_feature, "1.27.0", Some(44839), None),
453 (active, sse4a_target_feature, "1.27.0", Some(44839), None),
454 (active, tbm_target_feature, "1.27.0", Some(44839), None),
455 (active, wasm_target_feature, "1.30.0", Some(44839), None),
457 // Allows macro invocations of the form `#[foo::bar]`
458 (active, proc_macro_path_invoc, "1.27.0", Some(38356), None),
460 // Allows macro invocations on modules expressions and statements and
461 // procedural macros to expand to non-items.
462 (active, proc_macro_mod, "1.27.0", Some(38356), None),
463 (active, proc_macro_expr, "1.27.0", Some(38356), None),
464 (active, proc_macro_non_items, "1.27.0", Some(38356), None),
465 (active, proc_macro_gen, "1.27.0", Some(38356), None),
467 // #[doc(alias = "...")]
468 (active, doc_alias, "1.27.0", Some(50146), None),
470 // Access to crate names passed via `--extern` through prelude
471 (active, extern_prelude, "1.27.0", Some(44660), Some(Edition::Edition2018)),
474 (active, tool_attributes, "1.25.0", Some(44690), None),
476 (active, tool_lints, "1.28.0", Some(44690), None),
478 // allow irrefutable patterns in if-let and while-let statements (RFC 2086)
479 (active, irrefutable_let_patterns, "1.27.0", Some(44495), None),
481 // Allows use of the :literal macro fragment specifier (RFC 1576)
482 (active, macro_literal_matcher, "1.27.0", Some(35625), None),
484 // inconsistent bounds in where clauses
485 (active, trivial_bounds, "1.28.0", Some(48214), None),
488 (active, label_break_value, "1.28.0", Some(48594), None),
490 // #[panic_implementation]
491 (active, panic_implementation, "1.28.0", Some(44489), None),
493 // #[doc(keyword = "...")]
494 (active, doc_keyword, "1.28.0", Some(51315), None),
496 // Allows async and await syntax
497 (active, async_await, "1.28.0", Some(50547), None),
499 // #[alloc_error_handler]
500 (active, alloc_error_handler, "1.29.0", Some(51540), None),
502 (active, abi_amdgpu_kernel, "1.29.0", Some(51575), None),
504 // impl<I:Iterator> Iterator for &mut Iterator
505 // impl Debug for Foo<'_>
506 (active, impl_header_lifetime_elision, "1.30.0", Some(15872), Some(Edition::Edition2018)),
508 // Support for arbitrary delimited token streams in non-macro attributes.
509 (active, unrestricted_attribute_tokens, "1.30.0", Some(44690), None),
511 // Allows `use x::y;` to resolve through `self::x`, not just `::x`.
512 (active, uniform_paths, "1.30.0", Some(53130), None),
516 (removed, import_shadowing, "1.0.0", None, None, None),
517 (removed, managed_boxes, "1.0.0", None, None, None),
518 // Allows use of unary negate on unsigned integers, e.g. -e for e: u8
519 (removed, negate_unsigned, "1.0.0", Some(29645), None, None),
520 (removed, reflect, "1.0.0", Some(27749), None, None),
521 // A way to temporarily opt out of opt in copy. This will *never* be accepted.
522 (removed, opt_out_copy, "1.0.0", None, None, None),
523 (removed, quad_precision_float, "1.0.0", None, None, None),
524 (removed, struct_inherit, "1.0.0", None, None, None),
525 (removed, test_removed_feature, "1.0.0", None, None, None),
526 (removed, visible_private_types, "1.0.0", None, None, None),
527 (removed, unsafe_no_drop_flag, "1.0.0", None, None, None),
528 // Allows using items which are missing stability attributes
530 (removed, unmarked_api, "1.0.0", None, None, None),
531 (removed, pushpop_unsafe, "1.2.0", None, None, None),
532 (removed, allocator, "1.0.0", None, None, None),
533 (removed, simd, "1.0.0", Some(27731), None,
534 Some("removed in favor of `#[repr(simd)]`")),
535 (removed, advanced_slice_patterns, "1.0.0", Some(23121), None,
536 Some("merged into `#![feature(slice_patterns)]`")),
537 (removed, macro_reexport, "1.0.0", Some(29638), None,
538 Some("subsumed by `#![feature(use_extern_macros)]` and `pub use`")),
542 (stable_removed, no_stack_check, "1.0.0", None, None),
546 (accepted, associated_types, "1.0.0", None, None),
547 // allow overloading augmented assignment operations like `a += b`
548 (accepted, augmented_assignments, "1.8.0", Some(28235), None),
549 // allow empty structs and enum variants with braces
550 (accepted, braced_empty_structs, "1.8.0", Some(29720), None),
551 // Allows indexing into constant arrays.
552 (accepted, const_indexing, "1.26.0", Some(29947), None),
553 (accepted, default_type_params, "1.0.0", None, None),
554 (accepted, globs, "1.0.0", None, None),
555 (accepted, if_let, "1.0.0", None, None),
556 // A temporary feature gate used to enable parser extensions needed
557 // to bootstrap fix for #5723.
558 (accepted, issue_5723_bootstrap, "1.0.0", None, None),
559 (accepted, macro_rules, "1.0.0", None, None),
560 // Allows using #![no_std]
561 (accepted, no_std, "1.6.0", None, None),
562 (accepted, slicing_syntax, "1.0.0", None, None),
563 (accepted, struct_variant, "1.0.0", None, None),
564 // These are used to test this portion of the compiler, they don't actually
566 (accepted, test_accepted_feature, "1.0.0", None, None),
567 (accepted, tuple_indexing, "1.0.0", None, None),
568 // Allows macros to appear in the type position.
569 (accepted, type_macros, "1.13.0", Some(27245), None),
570 (accepted, while_let, "1.0.0", None, None),
571 // Allows `#[deprecated]` attribute
572 (accepted, deprecated, "1.9.0", Some(29935), None),
574 (accepted, question_mark, "1.13.0", Some(31436), None),
575 // Allows `..` in tuple (struct) patterns
576 (accepted, dotdot_in_tuple_patterns, "1.14.0", Some(33627), None),
577 (accepted, item_like_imports, "1.15.0", Some(35120), None),
578 // Allows using `Self` and associated types in struct expressions and patterns.
579 (accepted, more_struct_aliases, "1.16.0", Some(37544), None),
580 // elide `'static` lifetimes in `static`s and `const`s
581 (accepted, static_in_const, "1.17.0", Some(35897), None),
582 // Allows field shorthands (`x` meaning `x: x`) in struct literal expressions.
583 (accepted, field_init_shorthand, "1.17.0", Some(37340), None),
584 // Allows the definition recursive static items.
585 (accepted, static_recursion, "1.17.0", Some(29719), None),
586 // pub(restricted) visibilities (RFC 1422)
587 (accepted, pub_restricted, "1.18.0", Some(32409), None),
588 // The #![windows_subsystem] attribute
589 (accepted, windows_subsystem, "1.18.0", Some(37499), None),
590 // Allows `break {expr}` with a value inside `loop`s.
591 (accepted, loop_break_value, "1.19.0", Some(37339), None),
592 // Permits numeric fields in struct expressions and patterns.
593 (accepted, relaxed_adts, "1.19.0", Some(35626), None),
594 // Coerces non capturing closures to function pointers
595 (accepted, closure_to_fn_coercion, "1.19.0", Some(39817), None),
596 // Allows attributes on struct literal fields.
597 (accepted, struct_field_attributes, "1.20.0", Some(38814), None),
598 // Allows the definition of associated constants in `trait` or `impl`
600 (accepted, associated_consts, "1.20.0", Some(29646), None),
601 // Usage of the `compile_error!` macro
602 (accepted, compile_error, "1.20.0", Some(40872), None),
603 // See rust-lang/rfcs#1414. Allows code like `let x: &'static u32 = &42` to work.
604 (accepted, rvalue_static_promotion, "1.21.0", Some(38865), None),
605 // Allow Drop types in constants (RFC 1440)
606 (accepted, drop_types_in_const, "1.22.0", Some(33156), None),
607 // Allows the sysV64 ABI to be specified on all platforms
608 // instead of just the platforms on which it is the C ABI
609 (accepted, abi_sysv64, "1.24.0", Some(36167), None),
610 // Allows `repr(align(16))` struct attribute (RFC 1358)
611 (accepted, repr_align, "1.25.0", Some(33626), None),
612 // allow '|' at beginning of match arms (RFC 1925)
613 (accepted, match_beginning_vert, "1.25.0", Some(44101), None),
614 // Nested groups in `use` (RFC 2128)
615 (accepted, use_nested_groups, "1.25.0", Some(44494), None),
617 (accepted, inclusive_range_syntax, "1.26.0", Some(28237), None),
618 // allow `..=` in patterns (RFC 1192)
619 (accepted, dotdoteq_in_patterns, "1.26.0", Some(28237), None),
620 // Termination trait in main (RFC 1937)
621 (accepted, termination_trait, "1.26.0", Some(43301), None),
622 // Copy/Clone closures (RFC 2132)
623 (accepted, clone_closures, "1.26.0", Some(44490), None),
624 (accepted, copy_closures, "1.26.0", Some(44490), None),
625 // Allows `impl Trait` in function arguments.
626 (accepted, universal_impl_trait, "1.26.0", Some(34511), None),
627 // Allows `impl Trait` in function return types.
628 (accepted, conservative_impl_trait, "1.26.0", Some(34511), None),
630 (accepted, i128_type, "1.26.0", Some(35118), None),
631 // Default match binding modes (RFC 2005)
632 (accepted, match_default_bindings, "1.26.0", Some(42640), None),
633 // allow `'_` placeholder lifetimes
634 (accepted, underscore_lifetimes, "1.26.0", Some(44524), None),
635 // Allows attributes on lifetime/type formal parameters in generics (RFC 1327)
636 (accepted, generic_param_attrs, "1.27.0", Some(48848), None),
637 // Allows cfg(target_feature = "...").
638 (accepted, cfg_target_feature, "1.27.0", Some(29717), None),
639 // Allows #[target_feature(...)]
640 (accepted, target_feature, "1.27.0", None, None),
641 // Trait object syntax with `dyn` prefix
642 (accepted, dyn_trait, "1.27.0", Some(44662), None),
643 // allow `#[must_use]` on functions; and, must-use operators (RFC 1940)
644 (accepted, fn_must_use, "1.27.0", Some(43302), None),
645 // Allows use of the :lifetime macro fragment specifier
646 (accepted, macro_lifetime_matcher, "1.27.0", Some(34303), None),
647 // Termination trait in tests (RFC 1937)
648 (accepted, termination_trait_test, "1.27.0", Some(48854), None),
649 // The #[global_allocator] attribute
650 (accepted, global_allocator, "1.28.0", Some(27389), None),
651 // Allows `#[repr(transparent)]` attribute on newtype structs
652 (accepted, repr_transparent, "1.28.0", Some(43036), None),
653 // Defining procedural macros in `proc-macro` crates
654 (accepted, proc_macro, "1.29.0", Some(38356), None),
657 // If you change this, please modify src/doc/unstable-book as well. You must
658 // move that documentation into the relevant place in the other docs, and
659 // remove the chapter on the flag.
661 #[derive(Copy, Clone, PartialEq, Debug)]
662 pub enum AttributeType {
663 /// Normal, builtin attribute that is consumed
664 /// by the compiler before the unused_attribute check
667 /// Builtin attribute that may not be consumed by the compiler
668 /// before the unused_attribute check. These attributes
669 /// will be ignored by the unused_attribute lint
672 /// Builtin attribute that is only allowed at the crate level
676 pub enum AttributeGate {
677 /// Is gated by a given feature gate, reason
678 /// and function to check if enabled
679 Gated(Stability, &'static str, &'static str, fn(&Features) -> bool),
681 /// Ungated attribute, can be used on all release channels
686 fn is_deprecated(&self) -> bool {
688 Gated(Stability::Deprecated(_), ..) => true,
694 #[derive(Copy, Clone, Debug)]
697 // Argument is tracking issue link.
698 Deprecated(&'static str),
702 impl ::std::fmt::Debug for AttributeGate {
703 fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
705 Gated(ref stab, name, expl, _) =>
706 write!(fmt, "Gated({:?}, {}, {})", stab, name, expl),
707 Ungated => write!(fmt, "Ungated")
712 macro_rules! cfg_fn {
713 ($field: ident) => {{
714 fn f(features: &Features) -> bool {
717 f as fn(&Features) -> bool
721 pub fn deprecated_attributes() -> Vec<&'static (&'static str, AttributeType, AttributeGate)> {
722 BUILTIN_ATTRIBUTES.iter().filter(|a| a.2.is_deprecated()).collect()
725 pub fn is_builtin_attr_name(name: ast::Name) -> bool {
726 BUILTIN_ATTRIBUTES.iter().any(|&(builtin_name, _, _)| name == builtin_name)
729 pub fn is_builtin_attr(attr: &ast::Attribute) -> bool {
730 BUILTIN_ATTRIBUTES.iter().any(|&(builtin_name, _, _)| attr.path == builtin_name)
733 // Attributes that have a special meaning to rustc or rustdoc
734 pub const BUILTIN_ATTRIBUTES: &'static [(&'static str, AttributeType, AttributeGate)] = &[
737 ("warn", Normal, Ungated),
738 ("allow", Normal, Ungated),
739 ("forbid", Normal, Ungated),
740 ("deny", Normal, Ungated),
742 ("macro_use", Normal, Ungated),
743 ("macro_export", Normal, Ungated),
744 ("plugin_registrar", Normal, Ungated),
746 ("cfg", Normal, Ungated),
747 ("cfg_attr", Normal, Ungated),
748 ("main", Normal, Ungated),
749 ("start", Normal, Ungated),
750 ("test", Normal, Ungated),
751 ("bench", Normal, Ungated),
752 ("repr", Normal, Ungated),
753 ("path", Normal, Ungated),
754 ("abi", Normal, Ungated),
755 ("automatically_derived", Normal, Ungated),
756 ("no_mangle", Normal, Ungated),
757 ("no_link", Normal, Ungated),
758 ("derive", Normal, Ungated),
759 ("should_panic", Normal, Ungated),
760 ("ignore", Normal, Ungated),
761 ("no_implicit_prelude", Normal, Ungated),
762 ("reexport_test_harness_main", Normal, Ungated),
763 ("link_args", Normal, Gated(Stability::Unstable,
765 "the `link_args` attribute is experimental and not \
766 portable across platforms, it is recommended to \
767 use `#[link(name = \"foo\")] instead",
768 cfg_fn!(link_args))),
769 ("macro_escape", Normal, Ungated),
772 ("structural_match", Whitelisted, Gated(Stability::Unstable,
774 "the semantics of constant patterns is \
776 cfg_fn!(structural_match))),
779 ("non_exhaustive", Whitelisted, Gated(Stability::Unstable,
781 "non exhaustive is an experimental feature",
782 cfg_fn!(non_exhaustive))),
784 ("plugin", CrateLevel, Gated(Stability::Unstable,
786 "compiler plugins are experimental \
790 ("no_std", CrateLevel, Ungated),
791 ("no_core", CrateLevel, Gated(Stability::Unstable,
793 "no_core is experimental",
795 ("lang", Normal, Gated(Stability::Unstable,
797 "language items are subject to change",
798 cfg_fn!(lang_items))),
799 ("linkage", Whitelisted, Gated(Stability::Unstable,
801 "the `linkage` attribute is experimental \
802 and not portable across platforms",
804 ("thread_local", Whitelisted, Gated(Stability::Unstable,
806 "`#[thread_local]` is an experimental feature, and does \
807 not currently handle destructors.",
808 cfg_fn!(thread_local))),
810 ("rustc_on_unimplemented", Normal, Gated(Stability::Unstable,
812 "the `#[rustc_on_unimplemented]` attribute \
813 is an experimental feature",
814 cfg_fn!(on_unimplemented))),
815 ("rustc_const_unstable", Normal, Gated(Stability::Unstable,
816 "rustc_const_unstable",
817 "the `#[rustc_const_unstable]` attribute \
818 is an internal feature",
819 cfg_fn!(rustc_const_unstable))),
820 ("global_allocator", Normal, Ungated),
821 ("default_lib_allocator", Whitelisted, Gated(Stability::Unstable,
822 "allocator_internals",
823 "the `#[default_lib_allocator]` \
824 attribute is an experimental feature",
825 cfg_fn!(allocator_internals))),
826 ("needs_allocator", Normal, Gated(Stability::Unstable,
827 "allocator_internals",
828 "the `#[needs_allocator]` \
829 attribute is an experimental \
831 cfg_fn!(allocator_internals))),
832 ("panic_runtime", Whitelisted, Gated(Stability::Unstable,
834 "the `#[panic_runtime]` attribute is \
835 an experimental feature",
836 cfg_fn!(panic_runtime))),
837 ("needs_panic_runtime", Whitelisted, Gated(Stability::Unstable,
838 "needs_panic_runtime",
839 "the `#[needs_panic_runtime]` \
840 attribute is an experimental \
842 cfg_fn!(needs_panic_runtime))),
843 ("rustc_outlives", Normal, Gated(Stability::Unstable,
845 "the `#[rustc_outlives]` attribute \
846 is just used for rustc unit tests \
847 and will never be stable",
848 cfg_fn!(rustc_attrs))),
849 ("rustc_variance", Normal, Gated(Stability::Unstable,
851 "the `#[rustc_variance]` attribute \
852 is just used for rustc unit tests \
853 and will never be stable",
854 cfg_fn!(rustc_attrs))),
855 ("rustc_regions", Normal, Gated(Stability::Unstable,
857 "the `#[rustc_regions]` attribute \
858 is just used for rustc unit tests \
859 and will never be stable",
860 cfg_fn!(rustc_attrs))),
861 ("rustc_error", Whitelisted, Gated(Stability::Unstable,
863 "the `#[rustc_error]` attribute \
864 is just used for rustc unit tests \
865 and will never be stable",
866 cfg_fn!(rustc_attrs))),
867 ("rustc_if_this_changed", Whitelisted, Gated(Stability::Unstable,
869 "the `#[rustc_if_this_changed]` attribute \
870 is just used for rustc unit tests \
871 and will never be stable",
872 cfg_fn!(rustc_attrs))),
873 ("rustc_then_this_would_need", Whitelisted, Gated(Stability::Unstable,
875 "the `#[rustc_if_this_changed]` attribute \
876 is just used for rustc unit tests \
877 and will never be stable",
878 cfg_fn!(rustc_attrs))),
879 ("rustc_dirty", Whitelisted, Gated(Stability::Unstable,
881 "the `#[rustc_dirty]` attribute \
882 is just used for rustc unit tests \
883 and will never be stable",
884 cfg_fn!(rustc_attrs))),
885 ("rustc_clean", Whitelisted, Gated(Stability::Unstable,
887 "the `#[rustc_clean]` attribute \
888 is just used for rustc unit tests \
889 and will never be stable",
890 cfg_fn!(rustc_attrs))),
891 ("rustc_partition_reused", Whitelisted, Gated(Stability::Unstable,
894 is just used for rustc unit tests \
895 and will never be stable",
896 cfg_fn!(rustc_attrs))),
897 ("rustc_partition_codegened", Whitelisted, Gated(Stability::Unstable,
900 is just used for rustc unit tests \
901 and will never be stable",
902 cfg_fn!(rustc_attrs))),
903 ("rustc_synthetic", Whitelisted, Gated(Stability::Unstable,
906 is just used for rustc unit tests \
907 and will never be stable",
908 cfg_fn!(rustc_attrs))),
909 ("rustc_symbol_name", Whitelisted, Gated(Stability::Unstable,
911 "internal rustc attributes will never be stable",
912 cfg_fn!(rustc_attrs))),
913 ("rustc_item_path", Whitelisted, Gated(Stability::Unstable,
915 "internal rustc attributes will never be stable",
916 cfg_fn!(rustc_attrs))),
917 ("rustc_mir", Whitelisted, Gated(Stability::Unstable,
919 "the `#[rustc_mir]` attribute \
920 is just used for rustc unit tests \
921 and will never be stable",
922 cfg_fn!(rustc_attrs))),
923 ("rustc_inherit_overflow_checks", Whitelisted, Gated(Stability::Unstable,
925 "the `#[rustc_inherit_overflow_checks]` \
926 attribute is just used to control \
927 overflow checking behavior of several \
928 libcore functions that are inlined \
929 across crates and will never be stable",
930 cfg_fn!(rustc_attrs))),
932 ("rustc_dump_program_clauses", Whitelisted, Gated(Stability::Unstable,
934 "the `#[rustc_dump_program_clauses]` \
935 attribute is just used for rustc unit \
936 tests and will never be stable",
937 cfg_fn!(rustc_attrs))),
940 ("nll", Whitelisted, Gated(Stability::Unstable,
942 "Non lexical lifetimes",
944 ("compiler_builtins", Whitelisted, Gated(Stability::Unstable,
946 "the `#[compiler_builtins]` attribute is used to \
947 identify the `compiler_builtins` crate which \
948 contains compiler-rt intrinsics and will never be \
950 cfg_fn!(compiler_builtins))),
951 ("sanitizer_runtime", Whitelisted, Gated(Stability::Unstable,
953 "the `#[sanitizer_runtime]` attribute is used to \
954 identify crates that contain the runtime of a \
955 sanitizer and will never be stable",
956 cfg_fn!(sanitizer_runtime))),
957 ("profiler_runtime", Whitelisted, Gated(Stability::Unstable,
959 "the `#[profiler_runtime]` attribute is used to \
960 identify the `profiler_builtins` crate which \
961 contains the profiler runtime and will never be \
963 cfg_fn!(profiler_runtime))),
965 ("allow_internal_unstable", Normal, Gated(Stability::Unstable,
966 "allow_internal_unstable",
967 EXPLAIN_ALLOW_INTERNAL_UNSTABLE,
968 cfg_fn!(allow_internal_unstable))),
970 ("allow_internal_unsafe", Normal, Gated(Stability::Unstable,
971 "allow_internal_unsafe",
972 EXPLAIN_ALLOW_INTERNAL_UNSAFE,
973 cfg_fn!(allow_internal_unsafe))),
975 ("fundamental", Whitelisted, Gated(Stability::Unstable,
977 "the `#[fundamental]` attribute \
978 is an experimental feature",
979 cfg_fn!(fundamental))),
981 ("proc_macro_derive", Normal, Ungated),
983 ("rustc_copy_clone_marker", Whitelisted, Gated(Stability::Unstable,
985 "internal implementation detail",
986 cfg_fn!(rustc_attrs))),
988 // FIXME: #14408 whitelist docs since rustdoc looks at them
989 ("doc", Whitelisted, Ungated),
991 // FIXME: #14406 these are processed in codegen, which happens after the
993 ("cold", Whitelisted, Ungated),
994 ("naked", Whitelisted, Gated(Stability::Unstable,
996 "the `#[naked]` attribute \
997 is an experimental feature",
998 cfg_fn!(naked_functions))),
999 ("target_feature", Whitelisted, Ungated),
1000 ("export_name", Whitelisted, Ungated),
1001 ("inline", Whitelisted, Ungated),
1002 ("link", Whitelisted, Ungated),
1003 ("link_name", Whitelisted, Ungated),
1004 ("link_section", Whitelisted, Ungated),
1005 ("no_builtins", Whitelisted, Ungated),
1006 ("no_mangle", Whitelisted, Ungated),
1007 ("no_debug", Whitelisted, Gated(
1008 Stability::Deprecated("https://github.com/rust-lang/rust/issues/29721"),
1010 "the `#[no_debug]` attribute was an experimental feature that has been \
1011 deprecated due to lack of demand",
1012 cfg_fn!(no_debug))),
1013 ("omit_gdb_pretty_printer_section", Whitelisted, Gated(Stability::Unstable,
1014 "omit_gdb_pretty_printer_section",
1015 "the `#[omit_gdb_pretty_printer_section]` \
1016 attribute is just used for the Rust test \
1018 cfg_fn!(omit_gdb_pretty_printer_section))),
1019 ("unsafe_destructor_blind_to_params",
1021 Gated(Stability::Deprecated("https://github.com/rust-lang/rust/issues/34761"),
1022 "dropck_parametricity",
1023 "unsafe_destructor_blind_to_params has been replaced by \
1024 may_dangle and will be removed in the future",
1025 cfg_fn!(dropck_parametricity))),
1028 Gated(Stability::Unstable,
1030 "may_dangle has unstable semantics and may be removed in the future",
1031 cfg_fn!(dropck_eyepatch))),
1032 ("unwind", Whitelisted, Gated(Stability::Unstable,
1033 "unwind_attributes",
1034 "#[unwind] is experimental",
1035 cfg_fn!(unwind_attributes))),
1036 ("used", Whitelisted, Gated(
1037 Stability::Unstable, "used",
1038 "the `#[used]` attribute is an experimental feature",
1042 ("prelude_import", Whitelisted, Gated(Stability::Unstable,
1044 "`#[prelude_import]` is for use by rustc only",
1045 cfg_fn!(prelude_import))),
1047 // FIXME: #14407 these are only looked at on-demand so we can't
1048 // guarantee they'll have already been checked
1049 ("rustc_deprecated", Whitelisted, Ungated),
1050 ("must_use", Whitelisted, Ungated),
1051 ("stable", Whitelisted, Ungated),
1052 ("unstable", Whitelisted, Ungated),
1053 ("deprecated", Normal, Ungated),
1055 ("rustc_paren_sugar", Normal, Gated(Stability::Unstable,
1057 "unboxed_closures are still evolving",
1058 cfg_fn!(unboxed_closures))),
1060 ("windows_subsystem", Whitelisted, Ungated),
1062 ("proc_macro_attribute", Normal, Ungated),
1063 ("proc_macro", Normal, Ungated),
1065 ("rustc_derive_registrar", Normal, Gated(Stability::Unstable,
1066 "rustc_derive_registrar",
1067 "used internally by rustc",
1068 cfg_fn!(rustc_attrs))),
1070 ("allow_fail", Normal, Gated(Stability::Unstable,
1072 "allow_fail attribute is currently unstable",
1073 cfg_fn!(allow_fail))),
1075 ("rustc_std_internal_symbol", Whitelisted, Gated(Stability::Unstable,
1077 "this is an internal attribute that will \
1079 cfg_fn!(rustc_attrs))),
1081 // whitelists "identity-like" conversion methods to suggest on type mismatch
1082 ("rustc_conversion_suggestion", Whitelisted, Gated(Stability::Unstable,
1084 "this is an internal attribute that will \
1086 cfg_fn!(rustc_attrs))),
1088 ("rustc_args_required_const", Whitelisted, Gated(Stability::Unstable,
1090 "never will be stable",
1091 cfg_fn!(rustc_attrs))),
1094 ("infer_outlives_requirements", Normal, Gated(Stability::Unstable,
1095 "infer_outlives_requirements",
1096 "infer outlives requirements is an experimental feature",
1097 cfg_fn!(infer_outlives_requirements))),
1100 ("infer_static_outlives_requirements", Normal, Gated(Stability::Unstable,
1101 "infer_static_outlives_requirements",
1102 "infer 'static lifetime requirements",
1103 cfg_fn!(infer_static_outlives_requirements))),
1106 ("panic_implementation", Normal, Gated(Stability::Unstable,
1107 "panic_implementation",
1108 "#[panic_implementation] is an unstable feature",
1109 cfg_fn!(panic_implementation))),
1111 ("alloc_error_handler", Normal, Gated(Stability::Unstable,
1112 "alloc_error_handler",
1113 "#[alloc_error_handler] is an unstable feature",
1114 cfg_fn!(alloc_error_handler))),
1116 // Crate level attributes
1117 ("crate_name", CrateLevel, Ungated),
1118 ("crate_type", CrateLevel, Ungated),
1119 ("crate_id", CrateLevel, Ungated),
1120 ("feature", CrateLevel, Ungated),
1121 ("no_start", CrateLevel, Ungated),
1122 ("no_main", CrateLevel, Ungated),
1123 ("no_builtins", CrateLevel, Ungated),
1124 ("recursion_limit", CrateLevel, Ungated),
1125 ("type_length_limit", CrateLevel, Ungated),
1128 // cfg(...)'s that are feature gated
1129 const GATED_CFGS: &[(&str, &str, fn(&Features) -> bool)] = &[
1130 // (name in cfg, feature, function to check if the feature is enabled)
1131 ("target_vendor", "cfg_target_vendor", cfg_fn!(cfg_target_vendor)),
1132 ("target_thread_local", "cfg_target_thread_local", cfg_fn!(cfg_target_thread_local)),
1133 ("target_has_atomic", "cfg_target_has_atomic", cfg_fn!(cfg_target_has_atomic)),
1137 pub struct GatedCfg {
1143 pub fn gate(cfg: &ast::MetaItem) -> Option<GatedCfg> {
1144 let name = cfg.name().as_str();
1146 .position(|info| info.0 == name)
1155 pub fn check_and_emit(&self, sess: &ParseSess, features: &Features) {
1156 let (cfg, feature, has_feature) = GATED_CFGS[self.index];
1157 if !has_feature(features) && !self.span.allows_unstable() {
1158 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
1159 emit_feature_err(sess, feature, self.span, GateIssue::Language, &explain);
1164 struct Context<'a> {
1165 features: &'a Features,
1166 parse_sess: &'a ParseSess,
1167 plugin_attributes: &'a [(String, AttributeType)],
1170 macro_rules! gate_feature_fn {
1171 ($cx: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr, $level: expr) => {{
1172 let (cx, has_feature, span,
1173 name, explain, level) = ($cx, $has_feature, $span, $name, $explain, $level);
1174 let has_feature: bool = has_feature(&$cx.features);
1175 debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
1176 if !has_feature && !span.allows_unstable() {
1177 leveled_feature_err(cx.parse_sess, name, span, GateIssue::Language, explain, level)
1183 macro_rules! gate_feature {
1184 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {
1185 gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
1186 stringify!($feature), $explain, GateStrength::Hard)
1188 ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {
1189 gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
1190 stringify!($feature), $explain, $level)
1194 impl<'a> Context<'a> {
1195 fn check_attribute(&self, attr: &ast::Attribute, is_macro: bool) {
1196 debug!("check_attribute(attr = {:?})", attr);
1197 let name = attr.name().as_str();
1198 for &(n, ty, ref gateage) in BUILTIN_ATTRIBUTES {
1200 if let Gated(_, name, desc, ref has_feature) = *gateage {
1201 gate_feature_fn!(self, has_feature, attr.span, name, desc, GateStrength::Hard);
1202 } else if name == "doc" {
1203 if let Some(content) = attr.meta_item_list() {
1204 if content.iter().any(|c| c.check_name("include")) {
1205 gate_feature!(self, external_doc, attr.span,
1206 "#[doc(include = \"...\")] is experimental"
1211 debug!("check_attribute: {:?} is builtin, {:?}, {:?}", attr.path, ty, gateage);
1215 for &(ref n, ref ty) in self.plugin_attributes {
1216 if attr.path == &**n {
1217 // Plugins can't gate attributes, so we don't check for it
1218 // unlike the code above; we only use this loop to
1219 // short-circuit to avoid the checks below
1220 debug!("check_attribute: {:?} is registered by a plugin, {:?}", attr.path, ty);
1224 if name.starts_with("rustc_") {
1225 gate_feature!(self, rustc_attrs, attr.span,
1226 "unless otherwise specified, attributes \
1227 with the prefix `rustc_` \
1228 are reserved for internal compiler diagnostics");
1229 } else if name.starts_with("derive_") {
1230 gate_feature!(self, custom_derive, attr.span, EXPLAIN_DERIVE_UNDERSCORE);
1231 } else if !attr::is_known(attr) {
1232 // Only run the custom attribute lint during regular
1233 // feature gate checking. Macro gating runs
1234 // before the plugin attributes are registered
1235 // so we skip this then
1237 let msg = format!("The attribute `{}` is currently unknown to the compiler and \
1238 may have meaning added to it in the future", attr.path);
1239 gate_feature!(self, custom_attribute, attr.span, &msg);
1245 pub fn check_attribute(attr: &ast::Attribute, parse_sess: &ParseSess, features: &Features) {
1246 let cx = Context { features: features, parse_sess: parse_sess, plugin_attributes: &[] };
1247 cx.check_attribute(attr, true);
1250 fn find_lang_feature_issue(feature: &str) -> Option<u32> {
1251 if let Some(info) = ACTIVE_FEATURES.iter().find(|t| t.0 == feature) {
1253 // FIXME (#28244): enforce that active features have issue numbers
1254 // assert!(issue.is_some())
1257 // search in Accepted, Removed, or Stable Removed features
1258 let found = ACCEPTED_FEATURES.iter().chain(REMOVED_FEATURES).chain(STABLE_REMOVED_FEATURES)
1259 .find(|t| t.0 == feature);
1261 Some(&(_, _, issue, _)) => issue,
1262 None => panic!("Feature `{}` is not declared anywhere", feature),
1267 pub enum GateIssue {
1269 Library(Option<u32>)
1272 #[derive(Debug, Copy, Clone, PartialEq)]
1273 pub enum GateStrength {
1274 /// A hard error. (Most feature gates should use this.)
1276 /// Only a warning. (Use this only as backwards-compatibility demands.)
1280 pub fn emit_feature_err(sess: &ParseSess, feature: &str, span: Span, issue: GateIssue,
1282 feature_err(sess, feature, span, issue, explain).emit();
1285 pub fn feature_err<'a>(sess: &'a ParseSess, feature: &str, span: Span, issue: GateIssue,
1286 explain: &str) -> DiagnosticBuilder<'a> {
1287 leveled_feature_err(sess, feature, span, issue, explain, GateStrength::Hard)
1290 fn leveled_feature_err<'a>(sess: &'a ParseSess, feature: &str, span: Span, issue: GateIssue,
1291 explain: &str, level: GateStrength) -> DiagnosticBuilder<'a> {
1292 let diag = &sess.span_diagnostic;
1294 let issue = match issue {
1295 GateIssue::Language => find_lang_feature_issue(feature),
1296 GateIssue::Library(lib) => lib,
1299 let explanation = match issue {
1300 None | Some(0) => explain.to_owned(),
1301 Some(n) => format!("{} (see issue #{})", explain, n)
1304 let mut err = match level {
1305 GateStrength::Hard => {
1306 diag.struct_span_err_with_code(span, &explanation, stringify_error_code!(E0658))
1308 GateStrength::Soft => diag.struct_span_warn(span, &explanation),
1311 // #23973: do not suggest `#![feature(...)]` if we are in beta/stable
1312 if sess.unstable_features.is_nightly_build() {
1313 err.help(&format!("add #![feature({})] to the \
1314 crate attributes to enable",
1318 // If we're on stable and only emitting a "soft" warning, add a note to
1319 // clarify that the feature isn't "on" (rather than being on but
1321 if !sess.unstable_features.is_nightly_build() && level == GateStrength::Soft {
1322 err.help("a nightly build of the compiler is required to enable this feature");
1329 const EXPLAIN_BOX_SYNTAX: &'static str =
1330 "box expression syntax is experimental; you can call `Box::new` instead.";
1332 pub const EXPLAIN_STMT_ATTR_SYNTAX: &'static str =
1333 "attributes on expressions are experimental.";
1335 pub const EXPLAIN_ASM: &'static str =
1336 "inline assembly is not stable enough for use and is subject to change";
1338 pub const EXPLAIN_GLOBAL_ASM: &'static str =
1339 "`global_asm!` is not stable enough for use and is subject to change";
1341 pub const EXPLAIN_LOG_SYNTAX: &'static str =
1342 "`log_syntax!` is not stable enough for use and is subject to change";
1344 pub const EXPLAIN_CONCAT_IDENTS: &'static str =
1345 "`concat_idents` is not stable enough for use and is subject to change";
1347 pub const EXPLAIN_FORMAT_ARGS_NL: &'static str =
1348 "`format_args_nl` is only for internal language use and is subject to change";
1350 pub const EXPLAIN_TRACE_MACROS: &'static str =
1351 "`trace_macros` is not stable enough for use and is subject to change";
1352 pub const EXPLAIN_ALLOW_INTERNAL_UNSTABLE: &'static str =
1353 "allow_internal_unstable side-steps feature gating and stability checks";
1354 pub const EXPLAIN_ALLOW_INTERNAL_UNSAFE: &'static str =
1355 "allow_internal_unsafe side-steps the unsafe_code lint";
1357 pub const EXPLAIN_CUSTOM_DERIVE: &'static str =
1358 "`#[derive]` for custom traits is deprecated and will be removed in the future.";
1360 pub const EXPLAIN_DEPR_CUSTOM_DERIVE: &'static str =
1361 "`#[derive]` for custom traits is deprecated and will be removed in the future. \
1362 Prefer using procedural macro custom derive.";
1364 pub const EXPLAIN_DERIVE_UNDERSCORE: &'static str =
1365 "attributes of the form `#[derive_*]` are reserved for the compiler";
1367 pub const EXPLAIN_VIS_MATCHER: &'static str =
1368 ":vis fragment specifier is experimental and subject to change";
1370 pub const EXPLAIN_LITERAL_MATCHER: &'static str =
1371 ":literal fragment specifier is experimental and subject to change";
1373 pub const EXPLAIN_UNSIZED_TUPLE_COERCION: &'static str =
1374 "unsized tuple coercion is not stable enough for use and is subject to change";
1376 pub const EXPLAIN_MACRO_AT_MOST_ONCE_REP: &'static str =
1377 "using the `?` macro Kleene operator for \"at most one\" repetition is unstable";
1379 struct PostExpansionVisitor<'a> {
1380 context: &'a Context<'a>,
1383 macro_rules! gate_feature_post {
1384 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {{
1385 let (cx, span) = ($cx, $span);
1386 if !span.allows_unstable() {
1387 gate_feature!(cx.context, $feature, span, $explain)
1390 ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {{
1391 let (cx, span) = ($cx, $span);
1392 if !span.allows_unstable() {
1393 gate_feature!(cx.context, $feature, span, $explain, $level)
1398 impl<'a> PostExpansionVisitor<'a> {
1399 fn check_abi(&self, abi: Abi, span: Span) {
1401 Abi::RustIntrinsic => {
1402 gate_feature_post!(&self, intrinsics, span,
1403 "intrinsics are subject to change");
1405 Abi::PlatformIntrinsic => {
1406 gate_feature_post!(&self, platform_intrinsics, span,
1407 "platform intrinsics are experimental and possibly buggy");
1409 Abi::Vectorcall => {
1410 gate_feature_post!(&self, abi_vectorcall, span,
1411 "vectorcall is experimental and subject to change");
1414 gate_feature_post!(&self, abi_thiscall, span,
1415 "thiscall is experimental and subject to change");
1418 gate_feature_post!(&self, unboxed_closures, span,
1419 "rust-call ABI is subject to change");
1422 gate_feature_post!(&self, abi_ptx, span,
1423 "PTX ABIs are experimental and subject to change");
1425 Abi::Unadjusted => {
1426 gate_feature_post!(&self, abi_unadjusted, span,
1427 "unadjusted ABI is an implementation detail and perma-unstable");
1429 Abi::Msp430Interrupt => {
1430 gate_feature_post!(&self, abi_msp430_interrupt, span,
1431 "msp430-interrupt ABI is experimental and subject to change");
1433 Abi::X86Interrupt => {
1434 gate_feature_post!(&self, abi_x86_interrupt, span,
1435 "x86-interrupt ABI is experimental and subject to change");
1437 Abi::AmdGpuKernel => {
1438 gate_feature_post!(&self, abi_amdgpu_kernel, span,
1439 "amdgpu-kernel ABI is experimental and subject to change");
1455 fn contains_novel_literal(item: &ast::MetaItem) -> bool {
1456 use ast::MetaItemKind::*;
1457 use ast::NestedMetaItemKind::*;
1461 NameValue(ref lit) => !lit.node.is_str(),
1462 List(ref list) => list.iter().any(|li| {
1464 MetaItem(ref mi) => contains_novel_literal(mi),
1471 impl<'a> PostExpansionVisitor<'a> {
1472 fn whole_crate_feature_gates(&mut self, _krate: &ast::Crate) {
1473 for &(ident, span) in &*self.context.parse_sess.non_modrs_mods.borrow() {
1474 if !span.allows_unstable() {
1475 let cx = &self.context;
1476 let level = GateStrength::Hard;
1477 let has_feature = cx.features.non_modrs_mods;
1478 let name = "non_modrs_mods";
1479 debug!("gate_feature(feature = {:?}, span = {:?}); has? {}",
1480 name, span, has_feature);
1482 if !has_feature && !span.allows_unstable() {
1483 leveled_feature_err(
1484 cx.parse_sess, name, span, GateIssue::Language,
1485 "mod statements in non-mod.rs files are unstable", level
1487 .help(&format!("on stable builds, rename this file to {}{}mod.rs",
1488 ident, path::MAIN_SEPARATOR))
1496 impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
1497 fn visit_attribute(&mut self, attr: &ast::Attribute) {
1498 if !attr.span.allows_unstable() {
1499 // check for gated attributes
1500 self.context.check_attribute(attr, false);
1503 if attr.check_name("doc") {
1504 if let Some(content) = attr.meta_item_list() {
1505 if content.len() == 1 && content[0].check_name("cfg") {
1506 gate_feature_post!(&self, doc_cfg, attr.span,
1507 "#[doc(cfg(...))] is experimental"
1509 } else if content.iter().any(|c| c.check_name("masked")) {
1510 gate_feature_post!(&self, doc_masked, attr.span,
1511 "#[doc(masked)] is experimental"
1513 } else if content.iter().any(|c| c.check_name("spotlight")) {
1514 gate_feature_post!(&self, doc_spotlight, attr.span,
1515 "#[doc(spotlight)] is experimental"
1517 } else if content.iter().any(|c| c.check_name("alias")) {
1518 gate_feature_post!(&self, doc_alias, attr.span,
1519 "#[doc(alias = \"...\")] is experimental"
1521 } else if content.iter().any(|c| c.check_name("keyword")) {
1522 gate_feature_post!(&self, doc_keyword, attr.span,
1523 "#[doc(keyword = \"...\")] is experimental"
1529 match attr.parse_meta(self.context.parse_sess) {
1531 // allow attr_literals in #[repr(align(x))] and #[repr(packed(n))]
1532 let mut allow_attr_literal = false;
1533 if attr.path == "repr" {
1534 if let Some(content) = meta.meta_item_list() {
1535 allow_attr_literal = content.iter().any(
1536 |c| c.check_name("align") || c.check_name("packed"));
1540 if !allow_attr_literal && contains_novel_literal(&meta) {
1541 gate_feature_post!(&self, attr_literals, attr.span,
1542 "non-string literals in attributes, or string \
1543 literals in top-level positions, are experimental");
1548 gate_feature_post!(&self, unrestricted_attribute_tokens, attr.span,
1549 "arbitrary tokens in non-macro attributes are unstable");
1554 fn visit_name(&mut self, sp: Span, name: ast::Name) {
1555 if !name.as_str().is_ascii() {
1556 gate_feature_post!(&self,
1558 self.context.parse_sess.codemap().def_span(sp),
1559 "non-ascii idents are not fully supported.");
1563 fn visit_use_tree(&mut self, use_tree: &'a ast::UseTree, id: NodeId, _nested: bool) {
1564 if let ast::UseTreeKind::Simple(Some(ident), ..) = use_tree.kind {
1565 if ident.name == "_" {
1566 gate_feature_post!(&self, underscore_imports, use_tree.span,
1567 "renaming imports with `_` is unstable");
1571 visit::walk_use_tree(self, use_tree, id);
1574 fn visit_item(&mut self, i: &'a ast::Item) {
1576 ast::ItemKind::ExternCrate(_) => {
1577 if i.ident.name == "_" {
1578 gate_feature_post!(&self, underscore_imports, i.span,
1579 "renaming extern crates with `_` is unstable");
1583 ast::ItemKind::ForeignMod(ref foreign_module) => {
1584 self.check_abi(foreign_module.abi, i.span);
1587 ast::ItemKind::Fn(..) => {
1588 if attr::contains_name(&i.attrs[..], "plugin_registrar") {
1589 gate_feature_post!(&self, plugin_registrar, i.span,
1590 "compiler plugins are experimental and possibly buggy");
1592 if attr::contains_name(&i.attrs[..], "start") {
1593 gate_feature_post!(&self, start, i.span,
1594 "a #[start] function is an experimental \
1595 feature whose signature may change \
1598 if attr::contains_name(&i.attrs[..], "main") {
1599 gate_feature_post!(&self, main, i.span,
1600 "declaration of a nonstandard #[main] \
1601 function may change over time, for now \
1602 a top-level `fn main()` is required");
1606 ast::ItemKind::Struct(..) => {
1607 if let Some(attr) = attr::find_by_name(&i.attrs[..], "repr") {
1608 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
1609 if item.check_name("simd") {
1610 gate_feature_post!(&self, repr_simd, attr.span,
1611 "SIMD types are experimental and possibly buggy");
1613 if let Some((name, _)) = item.name_value_literal() {
1614 if name == "packed" {
1615 gate_feature_post!(&self, repr_packed, attr.span,
1616 "the `#[repr(packed(n))]` attribute \
1624 ast::ItemKind::TraitAlias(..) => {
1625 gate_feature_post!(&self, trait_alias,
1627 "trait aliases are not yet fully implemented");
1630 ast::ItemKind::Impl(_, polarity, defaultness, _, _, _, _) => {
1631 if polarity == ast::ImplPolarity::Negative {
1632 gate_feature_post!(&self, optin_builtin_traits,
1634 "negative trait bounds are not yet fully implemented; \
1635 use marker types for now");
1638 if let ast::Defaultness::Default = defaultness {
1639 gate_feature_post!(&self, specialization,
1641 "specialization is unstable");
1645 ast::ItemKind::Trait(ast::IsAuto::Yes, ..) => {
1646 gate_feature_post!(&self, optin_builtin_traits,
1648 "auto traits are experimental and possibly buggy");
1651 ast::ItemKind::MacroDef(ast::MacroDef { legacy: false, .. }) => {
1652 let msg = "`macro` is experimental";
1653 gate_feature_post!(&self, decl_macro, i.span, msg);
1656 ast::ItemKind::Existential(..) => {
1661 "existential types are unstable"
1668 visit::walk_item(self, i);
1671 fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
1673 ast::ForeignItemKind::Fn(..) |
1674 ast::ForeignItemKind::Static(..) => {
1675 let link_name = attr::first_attr_value_str_by_name(&i.attrs, "link_name");
1676 let links_to_llvm = match link_name {
1677 Some(val) => val.as_str().starts_with("llvm."),
1681 gate_feature_post!(&self, link_llvm_intrinsics, i.span,
1682 "linking to LLVM intrinsics is experimental");
1685 ast::ForeignItemKind::Ty => {
1686 gate_feature_post!(&self, extern_types, i.span,
1687 "extern types are experimental");
1689 ast::ForeignItemKind::Macro(..) => {}
1692 visit::walk_foreign_item(self, i)
1695 fn visit_ty(&mut self, ty: &'a ast::Ty) {
1697 ast::TyKind::BareFn(ref bare_fn_ty) => {
1698 self.check_abi(bare_fn_ty.abi, ty.span);
1700 ast::TyKind::Never => {
1701 gate_feature_post!(&self, never_type, ty.span,
1702 "The `!` type is experimental");
1706 visit::walk_ty(self, ty)
1709 fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FunctionRetTy) {
1710 if let ast::FunctionRetTy::Ty(ref output_ty) = *ret_ty {
1711 if let ast::TyKind::Never = output_ty.node {
1714 self.visit_ty(output_ty)
1719 fn visit_expr(&mut self, e: &'a ast::Expr) {
1721 ast::ExprKind::Box(_) => {
1722 gate_feature_post!(&self, box_syntax, e.span, EXPLAIN_BOX_SYNTAX);
1724 ast::ExprKind::Type(..) => {
1725 gate_feature_post!(&self, type_ascription, e.span,
1726 "type ascription is experimental");
1728 ast::ExprKind::ObsoleteInPlace(..) => {
1729 // these get a hard error in ast-validation
1731 ast::ExprKind::Yield(..) => {
1732 gate_feature_post!(&self, generators,
1734 "yield syntax is experimental");
1736 ast::ExprKind::Catch(_) => {
1737 gate_feature_post!(&self, catch_expr, e.span, "`catch` expression is experimental");
1739 ast::ExprKind::IfLet(ref pats, ..) | ast::ExprKind::WhileLet(ref pats, ..) => {
1741 gate_feature_post!(&self, if_while_or_patterns, e.span,
1742 "multiple patterns in `if let` and `while let` are unstable");
1745 ast::ExprKind::Block(_, opt_label) => {
1746 if let Some(label) = opt_label {
1747 gate_feature_post!(&self, label_break_value, label.ident.span,
1748 "labels on blocks are unstable");
1751 ast::ExprKind::Closure(_, ast::IsAsync::Async { .. }, ..) => {
1752 gate_feature_post!(&self, async_await, e.span, "async closures are unstable");
1754 ast::ExprKind::Async(..) => {
1755 gate_feature_post!(&self, async_await, e.span, "async blocks are unstable");
1759 visit::walk_expr(self, e);
1762 fn visit_arm(&mut self, arm: &'a ast::Arm) {
1763 visit::walk_arm(self, arm)
1766 fn visit_pat(&mut self, pattern: &'a ast::Pat) {
1767 match pattern.node {
1768 PatKind::Slice(_, Some(ref subslice), _) => {
1769 gate_feature_post!(&self, slice_patterns,
1771 "syntax for subslices in slice patterns is not yet stabilized");
1773 PatKind::Box(..) => {
1774 gate_feature_post!(&self, box_patterns,
1776 "box pattern syntax is experimental");
1778 PatKind::Range(_, _, Spanned { node: RangeEnd::Excluded, .. }) => {
1779 gate_feature_post!(&self, exclusive_range_pattern, pattern.span,
1780 "exclusive range pattern syntax is experimental");
1782 PatKind::Paren(..) => {
1783 gate_feature_post!(&self, pattern_parentheses, pattern.span,
1784 "parentheses in patterns are unstable");
1788 visit::walk_pat(self, pattern)
1791 fn visit_fn(&mut self,
1792 fn_kind: FnKind<'a>,
1793 fn_decl: &'a ast::FnDecl,
1797 FnKind::ItemFn(_, header, _, _) => {
1798 // check for const fn and async fn declarations
1799 if header.asyncness.is_async() {
1800 gate_feature_post!(&self, async_await, span, "async fn is unstable");
1802 if header.constness.node == ast::Constness::Const {
1803 gate_feature_post!(&self, const_fn, span, "const fn is unstable");
1805 // stability of const fn methods are covered in
1806 // visit_trait_item and visit_impl_item below; this is
1807 // because default methods don't pass through this
1810 self.check_abi(header.abi, span);
1812 FnKind::Method(_, sig, _, _) => {
1813 self.check_abi(sig.header.abi, span);
1817 visit::walk_fn(self, fn_kind, fn_decl, span);
1820 fn visit_trait_item(&mut self, ti: &'a ast::TraitItem) {
1822 ast::TraitItemKind::Method(ref sig, ref block) => {
1823 if block.is_none() {
1824 self.check_abi(sig.header.abi, ti.span);
1826 if sig.header.constness.node == ast::Constness::Const {
1827 gate_feature_post!(&self, const_fn, ti.span, "const fn is unstable");
1830 ast::TraitItemKind::Type(_, ref default) => {
1831 // We use three if statements instead of something like match guards so that all
1832 // of these errors can be emitted if all cases apply.
1833 if default.is_some() {
1834 gate_feature_post!(&self, associated_type_defaults, ti.span,
1835 "associated type defaults are unstable");
1837 if !ti.generics.params.is_empty() {
1838 gate_feature_post!(&self, generic_associated_types, ti.span,
1839 "generic associated types are unstable");
1841 if !ti.generics.where_clause.predicates.is_empty() {
1842 gate_feature_post!(&self, generic_associated_types, ti.span,
1843 "where clauses on associated types are unstable");
1848 visit::walk_trait_item(self, ti);
1851 fn visit_impl_item(&mut self, ii: &'a ast::ImplItem) {
1852 if ii.defaultness == ast::Defaultness::Default {
1853 gate_feature_post!(&self, specialization,
1855 "specialization is unstable");
1859 ast::ImplItemKind::Method(ref sig, _) => {
1860 if sig.header.constness.node == ast::Constness::Const {
1861 gate_feature_post!(&self, const_fn, ii.span, "const fn is unstable");
1864 ast::ImplItemKind::Existential(..) => {
1869 "existential types are unstable"
1873 ast::ImplItemKind::Type(_) if !ii.generics.params.is_empty() => {
1874 gate_feature_post!(&self, generic_associated_types, ii.span,
1875 "generic associated types are unstable");
1879 visit::walk_impl_item(self, ii);
1882 fn visit_path(&mut self, path: &'a ast::Path, _id: NodeId) {
1883 for segment in &path.segments {
1884 // Identifiers we are going to check could come from a legacy macro (e.g. `#[test]`).
1885 // For such macros identifiers must have empty context, because this context is
1886 // used during name resolution and produced names must be unhygienic for compatibility.
1887 // On the other hand, we need the actual non-empty context for feature gate checking
1888 // because it's hygienic even for legacy macros. As previously stated, such context
1889 // cannot be kept in identifiers, so it's kept in paths instead and we take it from
1890 // there while keeping location info from the ident span.
1891 let span = segment.ident.span.with_ctxt(path.span.ctxt());
1892 if segment.ident.name == keywords::Crate.name() {
1893 gate_feature_post!(&self, crate_in_paths, span,
1894 "`crate` in paths is experimental");
1895 } else if segment.ident.name == keywords::Extern.name() {
1896 gate_feature_post!(&self, extern_in_paths, span,
1897 "`extern` in paths is experimental");
1901 visit::walk_path(self, path);
1904 fn visit_vis(&mut self, vis: &'a ast::Visibility) {
1905 if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.node {
1906 gate_feature_post!(&self, crate_visibility_modifier, vis.span,
1907 "`crate` visibility modifier is experimental");
1909 visit::walk_vis(self, vis);
1913 pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
1914 crate_edition: Edition) -> Features {
1915 fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) {
1916 let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
1917 if let Some(reason) = reason {
1918 err.span_note(span, reason);
1923 let mut features = Features::new();
1924 let mut edition_enabled_features = FxHashMap();
1926 for &(name, .., f_edition, set) in ACTIVE_FEATURES.iter() {
1927 if let Some(f_edition) = f_edition {
1928 if f_edition <= crate_edition {
1929 set(&mut features, DUMMY_SP);
1930 edition_enabled_features.insert(Symbol::intern(name), crate_edition);
1935 for attr in krate_attrs {
1936 if !attr.check_name("feature") {
1940 let list = match attr.meta_item_list() {
1943 span_err!(span_handler, attr.span, E0555,
1944 "malformed feature attribute, expected #![feature(...)]");
1950 let name = if let Some(word) = mi.word() {
1953 span_err!(span_handler, mi.span, E0556,
1954 "malformed feature, expected just one word");
1958 if let Some(edition) = ALL_EDITIONS.iter().find(|e| name == e.feature_name()) {
1959 if *edition <= crate_edition {
1963 for &(name, .., f_edition, set) in ACTIVE_FEATURES.iter() {
1964 if let Some(f_edition) = f_edition {
1965 if f_edition <= *edition {
1966 // FIXME(Manishearth) there is currently no way to set
1967 // lib features by edition
1968 set(&mut features, DUMMY_SP);
1969 edition_enabled_features.insert(Symbol::intern(name), *edition);
1977 if let Some((.., set)) = ACTIVE_FEATURES.iter().find(|f| name == f.0) {
1978 if let Some(edition) = edition_enabled_features.get(&name) {
1983 "the feature `{}` is included in the Rust {} edition",
1988 set(&mut features, mi.span);
1989 features.declared_lang_features.push((name, mi.span, None));
1994 let removed = REMOVED_FEATURES.iter().find(|f| name == f.0);
1995 let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.0);
1996 if let Some((.., reason)) = removed.or(stable_removed) {
1997 feature_removed(span_handler, mi.span, *reason);
2001 if let Some((_, since, ..)) = ACCEPTED_FEATURES.iter().find(|f| name == f.0) {
2002 let since = Some(Symbol::intern(since));
2003 features.declared_lang_features.push((name, mi.span, since));
2007 features.declared_lib_features.push((name, mi.span));
2014 pub fn check_crate(krate: &ast::Crate,
2016 features: &Features,
2017 plugin_attributes: &[(String, AttributeType)],
2018 unstable: UnstableFeatures) {
2019 maybe_stage_features(&sess.span_diagnostic, krate, unstable);
2026 if !features.raw_identifiers {
2027 for &span in sess.raw_identifier_spans.borrow().iter() {
2028 if !span.allows_unstable() {
2029 gate_feature!(&ctx, raw_identifiers, span,
2030 "raw identifiers are experimental and subject to change"
2036 let visitor = &mut PostExpansionVisitor { context: &ctx };
2037 visitor.whole_crate_feature_gates(krate);
2038 visit::walk_crate(visitor, krate);
2041 #[derive(Clone, Copy, Hash)]
2042 pub enum UnstableFeatures {
2043 /// Hard errors for unstable features are active, as on
2044 /// beta/stable channels.
2046 /// Allow features to be activated, as on nightly.
2048 /// Errors are bypassed for bootstrapping. This is required any time
2049 /// during the build that feature-related lints are set to warn or above
2050 /// because the build turns on warnings-as-errors and uses lots of unstable
2051 /// features. As a result, this is always required for building Rust itself.
2055 impl UnstableFeatures {
2056 pub fn from_environment() -> UnstableFeatures {
2057 // Whether this is a feature-staged build, i.e. on the beta or stable channel
2058 let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
2059 // Whether we should enable unstable features for bootstrapping
2060 let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok();
2061 match (disable_unstable_features, bootstrap) {
2062 (_, true) => UnstableFeatures::Cheat,
2063 (true, _) => UnstableFeatures::Disallow,
2064 (false, _) => UnstableFeatures::Allow
2068 pub fn is_nightly_build(&self) -> bool {
2070 UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
2076 fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate,
2077 unstable: UnstableFeatures) {
2078 let allow_features = match unstable {
2079 UnstableFeatures::Allow => true,
2080 UnstableFeatures::Disallow => false,
2081 UnstableFeatures::Cheat => true
2083 if !allow_features {
2084 for attr in &krate.attrs {
2085 if attr.check_name("feature") {
2086 let release_channel = option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)");
2087 span_err!(span_handler, attr.span, E0554,
2088 "#![feature] may not be used on the {} release channel",