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};
32 use source_map::Spanned;
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};
43 // The const_fn feature also enables the min_const_fn feature, because `min_const_fn` allows
44 // the declaration `const fn`, but the `const_fn` feature gate enables things inside those
45 // functions that we do not want to expose to the user for now.
47 fn f(features: &mut Features, _: Span) {
48 features.const_fn = true;
49 features.min_const_fn = true;
51 f as fn(&mut Features, Span)
54 fn f(features: &mut Features, _: Span) {
55 features.$field = true;
57 f as fn(&mut Features, Span)
61 macro_rules! declare_features {
62 ($((active, $feature: ident, $ver: expr, $issue: expr, $edition: expr),)+) => {
63 /// Represents active features that are currently being implemented or
64 /// currently being considered for addition/removal.
65 const ACTIVE_FEATURES:
66 &'static [(&'static str, &'static str, Option<u32>,
67 Option<Edition>, fn(&mut Features, Span))] =
68 &[$((stringify!($feature), $ver, $issue, $edition, set!($feature))),+];
70 /// A set of features to be used by later passes.
73 /// `#![feature]` attrs for language features, for error reporting
74 pub declared_lang_features: Vec<(Symbol, Span, Option<Symbol>)>,
75 /// `#![feature]` attrs for non-language (library) features
76 pub declared_lib_features: Vec<(Symbol, Span)>,
77 $(pub $feature: bool),+
81 pub fn new() -> Features {
83 declared_lang_features: Vec::new(),
84 declared_lib_features: Vec::new(),
89 pub fn walk_feature_fields<F>(&self, mut f: F)
90 where F: FnMut(&str, bool)
92 $(f(stringify!($feature), self.$feature);)+
97 ($((removed, $feature: ident, $ver: expr, $issue: expr, None, $reason: expr),)+) => {
98 /// Represents unstable features which have since been removed (it was once Active)
99 const REMOVED_FEATURES: &[(&str, &str, Option<u32>, Option<&str>)] = &[
100 $((stringify!($feature), $ver, $issue, $reason)),+
104 ($((stable_removed, $feature: ident, $ver: expr, $issue: expr, None),)+) => {
105 /// Represents stable features which have since been removed (it was once Accepted)
106 const STABLE_REMOVED_FEATURES: &[(&str, &str, Option<u32>, Option<&str>)] = &[
107 $((stringify!($feature), $ver, $issue, None)),+
111 ($((accepted, $feature: ident, $ver: expr, $issue: expr, None),)+) => {
112 /// Those language feature has since been Accepted (it was once Active)
113 const ACCEPTED_FEATURES: &[(&str, &str, Option<u32>, Option<&str>)] = &[
114 $((stringify!($feature), $ver, $issue, None)),+
119 // If you change this, please modify src/doc/unstable-book as well.
121 // Don't ever remove anything from this list; set them to 'Removed'.
123 // The version numbers here correspond to the version in which the current status
124 // was set. This is most important for knowing when a particular feature became
127 // NB: tools/tidy/src/features.rs parses this information directly out of the
128 // source, so take care when modifying it.
131 (active, asm, "1.0.0", Some(29722), None),
132 (active, concat_idents, "1.0.0", Some(29599), None),
133 (active, link_args, "1.0.0", Some(29596), None),
134 (active, log_syntax, "1.0.0", Some(29598), None),
135 (active, non_ascii_idents, "1.0.0", Some(28979), None),
136 (active, plugin_registrar, "1.0.0", Some(29597), None),
137 (active, thread_local, "1.0.0", Some(29594), None),
138 (active, trace_macros, "1.0.0", Some(29598), None),
140 // rustc internal, for now
141 (active, intrinsics, "1.0.0", None, None),
142 (active, lang_items, "1.0.0", None, None),
143 (active, format_args_nl, "1.29.0", None, None),
145 (active, link_llvm_intrinsics, "1.0.0", Some(29602), None),
146 (active, linkage, "1.0.0", Some(29603), None),
147 (active, quote, "1.0.0", Some(29601), None),
150 (active, rustc_diagnostic_macros, "1.0.0", None, None),
151 (active, rustc_const_unstable, "1.0.0", None, None),
152 (active, box_syntax, "1.0.0", Some(49733), None),
153 (active, unboxed_closures, "1.0.0", Some(29625), None),
155 (active, fundamental, "1.0.0", Some(29635), None),
156 (active, main, "1.0.0", Some(29634), None),
157 (active, needs_allocator, "1.4.0", Some(27389), None),
158 (active, on_unimplemented, "1.0.0", Some(29628), None),
159 (active, plugin, "1.0.0", Some(29597), None),
160 (active, simd_ffi, "1.0.0", Some(27731), None),
161 (active, start, "1.0.0", Some(29633), None),
162 (active, structural_match, "1.8.0", Some(31434), None),
163 (active, panic_runtime, "1.10.0", Some(32837), None),
164 (active, needs_panic_runtime, "1.10.0", Some(32837), None),
166 // OIBIT specific features
167 (active, optin_builtin_traits, "1.0.0", Some(13231), None),
169 // 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 with some advanced features.
220 (active, const_fn, "1.2.0", Some(24111), None),
222 // Allows the definition of `const fn` functions.
223 (active, min_const_fn, "1.30.0", Some(53555), None),
225 // Allows let bindings and destructuring in `const fn` functions and constants.
226 (active, const_let, "1.22.1", Some(48821), None),
228 // Allows accessing fields of unions inside const fn.
229 (active, const_fn_union, "1.27.0", Some(51909), None),
231 // Allows casting raw pointers to `usize` during const eval.
232 (active, const_raw_ptr_to_usize_cast, "1.27.0", Some(51910), None),
234 // Allows dereferencing raw pointers during const eval.
235 (active, const_raw_ptr_deref, "1.27.0", Some(51911), None),
237 // Allows reinterpretation of the bits of a value of one type as another type during const eval.
238 (active, const_transmute, "1.29.0", Some(53605), None),
240 // Allows comparing raw pointers during const eval.
241 (active, const_compare_raw_pointers, "1.27.0", Some(53020), None),
243 // Allows panicking during const eval (produces compile-time errors)
244 (active, const_panic, "1.30.0", Some(51999), None),
246 // Allows using #[prelude_import] on glob `use` items.
249 (active, prelude_import, "1.2.0", None, None),
251 // Allows default type parameters to influence type inference.
252 (active, default_type_parameter_fallback, "1.3.0", Some(27336), None),
254 // Allows associated type defaults
255 (active, associated_type_defaults, "1.2.0", Some(29661), None),
257 // Allows `repr(simd)`, and importing the various simd intrinsics
258 (active, repr_simd, "1.4.0", Some(27731), None),
260 // Allows `extern "platform-intrinsic" { ... }`
261 (active, platform_intrinsics, "1.4.0", Some(27731), None),
263 // Allows `#[unwind(..)]`
264 // rustc internal for rust runtime
265 (active, unwind_attributes, "1.4.0", None, None),
267 // Allows the use of `#[naked]` on functions.
268 (active, naked_functions, "1.9.0", Some(32408), None),
270 // Allows `#[no_debug]`
271 (active, no_debug, "1.5.0", Some(29721), None),
273 // Allows `#[omit_gdb_pretty_printer_section]`
276 (active, omit_gdb_pretty_printer_section, "1.5.0", None, None),
278 // Allows cfg(target_vendor = "...").
279 (active, cfg_target_vendor, "1.5.0", Some(29718), None),
281 // Allow attributes on expressions and non-item statements
282 (active, stmt_expr_attributes, "1.6.0", Some(15701), None),
284 // allow using type ascription in expressions
285 (active, type_ascription, "1.6.0", Some(23416), None),
287 // Allows cfg(target_thread_local)
288 (active, cfg_target_thread_local, "1.7.0", Some(29594), None),
291 (active, abi_vectorcall, "1.7.0", None, None),
294 (active, exclusive_range_pattern, "1.11.0", Some(37854), None),
296 // impl specialization (RFC 1210)
297 (active, specialization, "1.7.0", Some(31844), None),
299 // Allows cfg(target_has_atomic = "...").
300 (active, cfg_target_has_atomic, "1.9.0", Some(32976), None),
302 // The `!` type. Does not imply exhaustive_patterns (below) any more.
303 (active, never_type, "1.13.0", Some(35121), None),
305 // Allows exhaustive pattern matching on types that contain uninhabited types
306 (active, exhaustive_patterns, "1.13.0", Some(51085), None),
308 // Allows untagged unions `union U { ... }`
309 (active, untagged_unions, "1.13.0", Some(32836), None),
311 // Used to identify the `compiler_builtins` crate
313 (active, compiler_builtins, "1.13.0", None, None),
315 // Allows #[link(..., cfg(..))]
316 (active, link_cfg, "1.14.0", Some(37406), None),
318 // `extern "ptx-*" fn()`
319 (active, abi_ptx, "1.15.0", Some(38788), None),
321 // The `repr(i128)` annotation for enums
322 (active, repr128, "1.16.0", Some(35118), None),
324 // The `unadjusted` ABI. Perma unstable.
326 (active, abi_unadjusted, "1.16.0", None, None),
328 // Declarative macros 2.0 (`macro`).
329 (active, decl_macro, "1.17.0", Some(39412), None),
331 // Allows #[link(kind="static-nobundle"...)]
332 (active, static_nobundle, "1.16.0", Some(37403), None),
334 // `extern "msp430-interrupt" fn()`
335 (active, abi_msp430_interrupt, "1.16.0", Some(38487), None),
337 // Used to identify crates that contain sanitizer runtimes
339 (active, sanitizer_runtime, "1.17.0", None, None),
341 // Used to identify crates that contain the profiler runtime
344 (active, profiler_runtime, "1.18.0", None, None),
346 // `extern "x86-interrupt" fn()`
347 (active, abi_x86_interrupt, "1.17.0", Some(40180), None),
349 // Allows the `try {...}` expression
350 (active, try_blocks, "1.29.0", Some(31436), None),
352 // Allows module-level inline assembly by way of global_asm!()
353 (active, global_asm, "1.18.0", Some(35119), None),
355 // Allows overlapping impls of marker traits
356 (active, overlapping_marker_traits, "1.18.0", Some(29864), 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), None),
392 (active, extern_types, "1.23.0", Some(43467), None),
394 // Allows trait methods with arbitrary self types
395 (active, arbitrary_self_types, "1.23.0", Some(44874), None),
397 // In-band lifetime bindings (e.g. `fn foo(x: &'a u8) -> &'a u8`)
398 (active, in_band_lifetimes, "1.23.0", Some(44524), None),
400 // Generic associated types (RFC 1598)
401 (active, generic_associated_types, "1.23.0", Some(44265), None),
404 (active, extern_in_paths, "1.23.0", Some(44660), None),
406 // Use `?` as the Kleene "at most one" operator
407 (active, macro_at_most_once_rep, "1.25.0", Some(48075), None),
409 // Infer static outlives requirements; RFC 2093
410 (active, infer_static_outlives_requirements, "1.26.0", Some(44493), None),
412 // Multiple patterns with `|` in `if let` and `while let`
413 (active, if_while_or_patterns, "1.26.0", Some(48215), None),
415 // Parentheses in patterns
416 (active, pattern_parentheses, "1.26.0", Some(51087), None),
418 // Allows `#[repr(packed)]` attribute on structs
419 (active, repr_packed, "1.26.0", Some(33158), None),
421 // `use path as _;` and `extern crate c as _;`
422 (active, underscore_imports, "1.26.0", Some(48216), None),
424 // Allows macro invocations in `extern {}` blocks
425 (active, macros_in_extern, "1.27.0", Some(49476), None),
427 // `existential type`
428 (active, existential_type, "1.28.0", Some(34511), None),
430 // unstable #[target_feature] directives
431 (active, arm_target_feature, "1.27.0", Some(44839), None),
432 (active, aarch64_target_feature, "1.27.0", Some(44839), None),
433 (active, hexagon_target_feature, "1.27.0", Some(44839), None),
434 (active, powerpc_target_feature, "1.27.0", Some(44839), None),
435 (active, mips_target_feature, "1.27.0", Some(44839), None),
436 (active, avx512_target_feature, "1.27.0", Some(44839), None),
437 (active, mmx_target_feature, "1.27.0", Some(44839), None),
438 (active, sse4a_target_feature, "1.27.0", Some(44839), None),
439 (active, tbm_target_feature, "1.27.0", Some(44839), None),
440 (active, wasm_target_feature, "1.30.0", Some(44839), None),
442 // Allows macro invocations on modules expressions and statements and
443 // procedural macros to expand to non-items.
444 (active, proc_macro_mod, "1.27.0", Some(38356), None),
445 (active, proc_macro_expr, "1.27.0", Some(38356), None),
446 (active, proc_macro_non_items, "1.27.0", Some(38356), None),
447 (active, proc_macro_gen, "1.27.0", Some(38356), None),
449 // #[doc(alias = "...")]
450 (active, doc_alias, "1.27.0", Some(50146), None),
453 (active, tool_lints, "1.28.0", Some(44690), None),
455 // Allows irrefutable patterns in if-let and while-let statements (RFC 2086)
456 (active, irrefutable_let_patterns, "1.27.0", Some(44495), None),
458 // Allows use of the :literal macro fragment specifier (RFC 1576)
459 (active, macro_literal_matcher, "1.27.0", Some(35625), None),
461 // inconsistent bounds in where clauses
462 (active, trivial_bounds, "1.28.0", Some(48214), None),
465 (active, label_break_value, "1.28.0", Some(48594), None),
467 // Integer match exhaustiveness checking
468 (active, exhaustive_integer_patterns, "1.30.0", Some(50907), None),
470 // RFC 2070: #[panic_implementation] / #[panic_handler]
471 (active, panic_implementation, "1.28.0", Some(44489), None),
473 // #[doc(keyword = "...")]
474 (active, doc_keyword, "1.28.0", Some(51315), None),
476 // Allows async and await syntax
477 (active, async_await, "1.28.0", Some(50547), None),
479 // #[alloc_error_handler]
480 (active, alloc_error_handler, "1.29.0", Some(51540), None),
482 (active, abi_amdgpu_kernel, "1.29.0", Some(51575), None),
484 // impl<I:Iterator> Iterator for &mut Iterator
485 // impl Debug for Foo<'_>
486 (active, impl_header_lifetime_elision, "1.30.0", Some(15872), Some(Edition::Edition2018)),
488 // Support for arbitrary delimited token streams in non-macro attributes
489 (active, unrestricted_attribute_tokens, "1.30.0", Some(44690), None),
491 // Allows `use x::y;` to resolve through `self::x`, not just `::x`
492 (active, uniform_paths, "1.30.0", Some(53130), None),
494 // Allows `Self` in type definitions
495 (active, self_in_typedefs, "1.30.0", Some(49303), None),
497 // unsized rvalues at arguments and parameters
498 (active, unsized_locals, "1.30.0", Some(48055), None),
502 (active, custom_test_frameworks, "1.30.0", Some(50297), None),
504 // Non-builtin attributes in inner attribute position
505 (active, custom_inner_attributes, "1.30.0", Some(38356), None),
507 // Self struct constructor (RFC 2302)
508 (active, self_struct_ctor, "1.31.0", Some(51994), None),
510 // allow mixing of bind-by-move in patterns and references to
511 // those identifiers in guards, *if* we are using MIR-borrowck
512 // (aka NLL). Essentially this means you need to be on
513 // edition:2018 or later.
514 (active, bind_by_move_pattern_guards, "1.30.0", Some(15287), None),
518 (removed, import_shadowing, "1.0.0", None, None, None),
519 (removed, managed_boxes, "1.0.0", None, None, None),
520 // Allows use of unary negate on unsigned integers, e.g. -e for e: u8
521 (removed, negate_unsigned, "1.0.0", Some(29645), None, None),
522 (removed, reflect, "1.0.0", Some(27749), None, None),
523 // A way to temporarily opt out of opt in copy. This will *never* be accepted.
524 (removed, opt_out_copy, "1.0.0", None, None, None),
525 (removed, quad_precision_float, "1.0.0", None, None, None),
526 (removed, struct_inherit, "1.0.0", None, None, None),
527 (removed, test_removed_feature, "1.0.0", None, None, None),
528 (removed, visible_private_types, "1.0.0", None, None, None),
529 (removed, unsafe_no_drop_flag, "1.0.0", None, None, None),
530 // Allows using items which are missing stability attributes
532 (removed, unmarked_api, "1.0.0", None, None, None),
533 (removed, pushpop_unsafe, "1.2.0", None, None, None),
534 (removed, allocator, "1.0.0", None, None, None),
535 (removed, simd, "1.0.0", Some(27731), None,
536 Some("removed in favor of `#[repr(simd)]`")),
537 (removed, advanced_slice_patterns, "1.0.0", Some(23121), None,
538 Some("merged into `#![feature(slice_patterns)]`")),
539 (removed, macro_reexport, "1.0.0", Some(29638), None,
540 Some("subsumed by `pub use`")),
544 (stable_removed, no_stack_check, "1.0.0", None, None),
548 (accepted, associated_types, "1.0.0", None, None),
549 // allow overloading augmented assignment operations like `a += b`
550 (accepted, augmented_assignments, "1.8.0", Some(28235), None),
551 // allow empty structs and enum variants with braces
552 (accepted, braced_empty_structs, "1.8.0", Some(29720), None),
553 // Allows indexing into constant arrays.
554 (accepted, const_indexing, "1.26.0", Some(29947), None),
555 (accepted, default_type_params, "1.0.0", None, None),
556 (accepted, globs, "1.0.0", None, None),
557 (accepted, if_let, "1.0.0", None, None),
558 // A temporary feature gate used to enable parser extensions needed
559 // to bootstrap fix for #5723.
560 (accepted, issue_5723_bootstrap, "1.0.0", None, None),
561 (accepted, macro_rules, "1.0.0", None, None),
562 // Allows using #![no_std]
563 (accepted, no_std, "1.6.0", None, None),
564 (accepted, slicing_syntax, "1.0.0", None, None),
565 (accepted, struct_variant, "1.0.0", None, None),
566 // These are used to test this portion of the compiler, they don't actually
568 (accepted, test_accepted_feature, "1.0.0", None, None),
569 (accepted, tuple_indexing, "1.0.0", None, None),
570 // Allows macros to appear in the type position.
571 (accepted, type_macros, "1.13.0", Some(27245), None),
572 (accepted, while_let, "1.0.0", None, None),
573 // Allows `#[deprecated]` attribute
574 (accepted, deprecated, "1.9.0", Some(29935), None),
576 (accepted, question_mark, "1.13.0", Some(31436), None),
577 // Allows `..` in tuple (struct) patterns
578 (accepted, dotdot_in_tuple_patterns, "1.14.0", Some(33627), None),
579 (accepted, item_like_imports, "1.15.0", Some(35120), None),
580 // Allows using `Self` and associated types in struct expressions and patterns.
581 (accepted, more_struct_aliases, "1.16.0", Some(37544), None),
582 // elide `'static` lifetimes in `static`s and `const`s
583 (accepted, static_in_const, "1.17.0", Some(35897), None),
584 // Allows field shorthands (`x` meaning `x: x`) in struct literal expressions.
585 (accepted, field_init_shorthand, "1.17.0", Some(37340), None),
586 // Allows the definition recursive static items.
587 (accepted, static_recursion, "1.17.0", Some(29719), None),
588 // pub(restricted) visibilities (RFC 1422)
589 (accepted, pub_restricted, "1.18.0", Some(32409), None),
590 // The #![windows_subsystem] attribute
591 (accepted, windows_subsystem, "1.18.0", Some(37499), None),
592 // Allows `break {expr}` with a value inside `loop`s.
593 (accepted, loop_break_value, "1.19.0", Some(37339), None),
594 // Permits numeric fields in struct expressions and patterns.
595 (accepted, relaxed_adts, "1.19.0", Some(35626), None),
596 // Coerces non capturing closures to function pointers
597 (accepted, closure_to_fn_coercion, "1.19.0", Some(39817), None),
598 // Allows attributes on struct literal fields.
599 (accepted, struct_field_attributes, "1.20.0", Some(38814), None),
600 // Allows the definition of associated constants in `trait` or `impl`
602 (accepted, associated_consts, "1.20.0", Some(29646), None),
603 // Usage of the `compile_error!` macro
604 (accepted, compile_error, "1.20.0", Some(40872), None),
605 // See rust-lang/rfcs#1414. Allows code like `let x: &'static u32 = &42` to work.
606 (accepted, rvalue_static_promotion, "1.21.0", Some(38865), None),
607 // Allow Drop types in constants (RFC 1440)
608 (accepted, drop_types_in_const, "1.22.0", Some(33156), None),
609 // Allows the sysV64 ABI to be specified on all platforms
610 // instead of just the platforms on which it is the C ABI
611 (accepted, abi_sysv64, "1.24.0", Some(36167), None),
612 // Allows `repr(align(16))` struct attribute (RFC 1358)
613 (accepted, repr_align, "1.25.0", Some(33626), None),
614 // allow '|' at beginning of match arms (RFC 1925)
615 (accepted, match_beginning_vert, "1.25.0", Some(44101), None),
616 // Nested groups in `use` (RFC 2128)
617 (accepted, use_nested_groups, "1.25.0", Some(44494), None),
619 (accepted, inclusive_range_syntax, "1.26.0", Some(28237), None),
620 // allow `..=` in patterns (RFC 1192)
621 (accepted, dotdoteq_in_patterns, "1.26.0", Some(28237), None),
622 // Termination trait in main (RFC 1937)
623 (accepted, termination_trait, "1.26.0", Some(43301), None),
624 // Copy/Clone closures (RFC 2132)
625 (accepted, clone_closures, "1.26.0", Some(44490), None),
626 (accepted, copy_closures, "1.26.0", Some(44490), None),
627 // Allows `impl Trait` in function arguments.
628 (accepted, universal_impl_trait, "1.26.0", Some(34511), None),
629 // Allows `impl Trait` in function return types.
630 (accepted, conservative_impl_trait, "1.26.0", Some(34511), None),
632 (accepted, i128_type, "1.26.0", Some(35118), None),
633 // Default match binding modes (RFC 2005)
634 (accepted, match_default_bindings, "1.26.0", Some(42640), None),
635 // allow `'_` placeholder lifetimes
636 (accepted, underscore_lifetimes, "1.26.0", Some(44524), None),
637 // Allows attributes on lifetime/type formal parameters in generics (RFC 1327)
638 (accepted, generic_param_attrs, "1.27.0", Some(48848), None),
639 // Allows cfg(target_feature = "...").
640 (accepted, cfg_target_feature, "1.27.0", Some(29717), None),
641 // Allows #[target_feature(...)]
642 (accepted, target_feature, "1.27.0", None, None),
643 // Trait object syntax with `dyn` prefix
644 (accepted, dyn_trait, "1.27.0", Some(44662), None),
645 // allow `#[must_use]` on functions; and, must-use operators (RFC 1940)
646 (accepted, fn_must_use, "1.27.0", Some(43302), None),
647 // Allows use of the :lifetime macro fragment specifier
648 (accepted, macro_lifetime_matcher, "1.27.0", Some(34303), None),
649 // Termination trait in tests (RFC 1937)
650 (accepted, termination_trait_test, "1.27.0", Some(48854), None),
651 // The #[global_allocator] attribute
652 (accepted, global_allocator, "1.28.0", Some(27389), None),
653 // Allows `#[repr(transparent)]` attribute on newtype structs
654 (accepted, repr_transparent, "1.28.0", Some(43036), None),
655 // Defining procedural macros in `proc-macro` crates
656 (accepted, proc_macro, "1.29.0", Some(38356), None),
657 // `foo.rs` as an alternative to `foo/mod.rs`
658 (accepted, non_modrs_mods, "1.30.0", Some(44660), None),
659 // Allows use of the :vis macro fragment specifier
660 (accepted, macro_vis_matcher, "1.30.0", Some(41022), None),
661 // Allows importing and reexporting macros with `use`,
662 // enables macro modularization in general.
663 (accepted, use_extern_macros, "1.30.0", Some(35896), None),
664 // Allows keywords to be escaped for use as identifiers
665 (accepted, raw_identifiers, "1.30.0", Some(48589), None),
666 // Attributes scoped to tools
667 (accepted, tool_attributes, "1.30.0", Some(44690), None),
668 // Allows multi-segment paths in attributes and derives
669 (accepted, proc_macro_path_invoc, "1.30.0", Some(38356), None),
670 // Allows all literals in attribute lists and values of key-value pairs.
671 (accepted, attr_literals, "1.30.0", Some(34981), None),
672 // Infer outlives requirements; RFC 2093
673 (accepted, infer_outlives_requirements, "1.30.0", Some(44493), None),
674 (accepted, panic_handler, "1.30.0", Some(44489), None),
675 // Used to preserve symbols (see llvm.used)
676 (accepted, used, "1.30.0", Some(40289), None),
678 (accepted, crate_in_paths, "1.30.0", Some(45477), None),
679 // Resolve absolute paths as paths from other crates
680 (accepted, extern_absolute_paths, "1.30.0", Some(44660), None),
681 // Access to crate names passed via `--extern` through prelude
682 (accepted, extern_prelude, "1.30.0", Some(44660), None),
685 // If you change this, please modify src/doc/unstable-book as well. You must
686 // move that documentation into the relevant place in the other docs, and
687 // remove the chapter on the flag.
689 #[derive(Copy, Clone, PartialEq, Debug)]
690 pub enum AttributeType {
691 /// Normal, builtin attribute that is consumed
692 /// by the compiler before the unused_attribute check
695 /// Builtin attribute that may not be consumed by the compiler
696 /// before the unused_attribute check. These attributes
697 /// will be ignored by the unused_attribute lint
700 /// Builtin attribute that is only allowed at the crate level
704 pub enum AttributeGate {
705 /// Is gated by a given feature gate, reason
706 /// and function to check if enabled
707 Gated(Stability, &'static str, &'static str, fn(&Features) -> bool),
709 /// Ungated attribute, can be used on all release channels
714 fn is_deprecated(&self) -> bool {
716 Gated(Stability::Deprecated(_, _), ..) => true,
722 #[derive(Copy, Clone, Debug)]
725 // First argument is tracking issue link; second argument is an optional
726 // help message, which defaults to "remove this attribute"
727 Deprecated(&'static str, Option<&'static str>),
731 impl ::std::fmt::Debug for AttributeGate {
732 fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
734 Gated(ref stab, name, expl, _) =>
735 write!(fmt, "Gated({:?}, {}, {})", stab, name, expl),
736 Ungated => write!(fmt, "Ungated")
741 macro_rules! cfg_fn {
742 ($field: ident) => {{
743 fn f(features: &Features) -> bool {
746 f as fn(&Features) -> bool
750 pub fn deprecated_attributes() -> Vec<&'static (&'static str, AttributeType, AttributeGate)> {
751 BUILTIN_ATTRIBUTES.iter().filter(|a| a.2.is_deprecated()).collect()
754 pub fn is_builtin_attr_name(name: ast::Name) -> bool {
755 BUILTIN_ATTRIBUTES.iter().any(|&(builtin_name, _, _)| name == builtin_name)
758 pub fn is_builtin_attr(attr: &ast::Attribute) -> bool {
759 BUILTIN_ATTRIBUTES.iter().any(|&(builtin_name, _, _)| attr.path == builtin_name)
762 // Attributes that have a special meaning to rustc or rustdoc
763 pub const BUILTIN_ATTRIBUTES: &'static [(&'static str, AttributeType, AttributeGate)] = &[
766 ("warn", Normal, Ungated),
767 ("allow", Normal, Ungated),
768 ("forbid", Normal, Ungated),
769 ("deny", Normal, Ungated),
771 ("macro_use", Normal, Ungated),
772 ("macro_export", Normal, Ungated),
773 ("plugin_registrar", Normal, Ungated),
775 ("cfg", Normal, Ungated),
776 ("cfg_attr", Normal, Ungated),
777 ("main", Normal, Ungated),
778 ("start", Normal, Ungated),
779 ("repr", Normal, Ungated),
780 ("path", Normal, Ungated),
781 ("abi", Normal, Ungated),
782 ("automatically_derived", Normal, Ungated),
783 ("no_mangle", Normal, Ungated),
784 ("no_link", Normal, Ungated),
785 ("derive", Normal, Ungated),
786 ("should_panic", Normal, Ungated),
787 ("ignore", Normal, Ungated),
788 ("no_implicit_prelude", Normal, Ungated),
789 ("reexport_test_harness_main", Normal, Ungated),
790 ("link_args", Normal, Gated(Stability::Unstable,
792 "the `link_args` attribute is experimental and not \
793 portable across platforms, it is recommended to \
794 use `#[link(name = \"foo\")] instead",
795 cfg_fn!(link_args))),
796 ("macro_escape", Normal, Ungated),
799 ("structural_match", Whitelisted, Gated(Stability::Unstable,
801 "the semantics of constant patterns is \
803 cfg_fn!(structural_match))),
806 ("non_exhaustive", Whitelisted, Gated(Stability::Unstable,
808 "non exhaustive is an experimental feature",
809 cfg_fn!(non_exhaustive))),
811 ("plugin", CrateLevel, Gated(Stability::Unstable,
813 "compiler plugins are experimental \
817 ("no_std", CrateLevel, Ungated),
818 ("no_core", CrateLevel, Gated(Stability::Unstable,
820 "no_core is experimental",
822 ("lang", Normal, Gated(Stability::Unstable,
824 "language items are subject to change",
825 cfg_fn!(lang_items))),
826 ("linkage", Whitelisted, Gated(Stability::Unstable,
828 "the `linkage` attribute is experimental \
829 and not portable across platforms",
831 ("thread_local", Whitelisted, Gated(Stability::Unstable,
833 "`#[thread_local]` is an experimental feature, and does \
834 not currently handle destructors.",
835 cfg_fn!(thread_local))),
837 ("rustc_on_unimplemented", Normal, Gated(Stability::Unstable,
839 "the `#[rustc_on_unimplemented]` attribute \
840 is an experimental feature",
841 cfg_fn!(on_unimplemented))),
842 ("rustc_const_unstable", Normal, Gated(Stability::Unstable,
843 "rustc_const_unstable",
844 "the `#[rustc_const_unstable]` attribute \
845 is an internal feature",
846 cfg_fn!(rustc_const_unstable))),
847 ("global_allocator", Normal, Ungated),
848 ("default_lib_allocator", Whitelisted, Gated(Stability::Unstable,
849 "allocator_internals",
850 "the `#[default_lib_allocator]` \
851 attribute is an experimental feature",
852 cfg_fn!(allocator_internals))),
853 ("needs_allocator", Normal, Gated(Stability::Unstable,
854 "allocator_internals",
855 "the `#[needs_allocator]` \
856 attribute is an experimental \
858 cfg_fn!(allocator_internals))),
859 ("panic_runtime", Whitelisted, Gated(Stability::Unstable,
861 "the `#[panic_runtime]` attribute is \
862 an experimental feature",
863 cfg_fn!(panic_runtime))),
864 ("needs_panic_runtime", Whitelisted, Gated(Stability::Unstable,
865 "needs_panic_runtime",
866 "the `#[needs_panic_runtime]` \
867 attribute is an experimental \
869 cfg_fn!(needs_panic_runtime))),
870 ("rustc_outlives", Normal, Gated(Stability::Unstable,
872 "the `#[rustc_outlives]` attribute \
873 is just used for rustc unit tests \
874 and will never be stable",
875 cfg_fn!(rustc_attrs))),
876 ("rustc_variance", Normal, Gated(Stability::Unstable,
878 "the `#[rustc_variance]` attribute \
879 is just used for rustc unit tests \
880 and will never be stable",
881 cfg_fn!(rustc_attrs))),
882 ("rustc_regions", Normal, Gated(Stability::Unstable,
884 "the `#[rustc_regions]` attribute \
885 is just used for rustc unit tests \
886 and will never be stable",
887 cfg_fn!(rustc_attrs))),
888 ("rustc_error", Whitelisted, Gated(Stability::Unstable,
890 "the `#[rustc_error]` attribute \
891 is just used for rustc unit tests \
892 and will never be stable",
893 cfg_fn!(rustc_attrs))),
894 ("rustc_dump_user_substs", Whitelisted, Gated(Stability::Unstable,
897 is just used for rustc unit tests \
898 and will never be stable",
899 cfg_fn!(rustc_attrs))),
900 ("rustc_if_this_changed", Whitelisted, Gated(Stability::Unstable,
902 "the `#[rustc_if_this_changed]` attribute \
903 is just used for rustc unit tests \
904 and will never be stable",
905 cfg_fn!(rustc_attrs))),
906 ("rustc_then_this_would_need", Whitelisted, Gated(Stability::Unstable,
908 "the `#[rustc_if_this_changed]` attribute \
909 is just used for rustc unit tests \
910 and will never be stable",
911 cfg_fn!(rustc_attrs))),
912 ("rustc_dirty", Whitelisted, Gated(Stability::Unstable,
914 "the `#[rustc_dirty]` attribute \
915 is just used for rustc unit tests \
916 and will never be stable",
917 cfg_fn!(rustc_attrs))),
918 ("rustc_clean", Whitelisted, Gated(Stability::Unstable,
920 "the `#[rustc_clean]` attribute \
921 is just used for rustc unit tests \
922 and will never be stable",
923 cfg_fn!(rustc_attrs))),
924 ("rustc_partition_reused", Whitelisted, Gated(Stability::Unstable,
927 is just used for rustc unit tests \
928 and will never be stable",
929 cfg_fn!(rustc_attrs))),
930 ("rustc_partition_codegened", Whitelisted, Gated(Stability::Unstable,
933 is just used for rustc unit tests \
934 and will never be stable",
935 cfg_fn!(rustc_attrs))),
936 ("rustc_synthetic", Whitelisted, Gated(Stability::Unstable,
939 is just used for rustc unit tests \
940 and will never be stable",
941 cfg_fn!(rustc_attrs))),
942 ("rustc_symbol_name", Whitelisted, Gated(Stability::Unstable,
944 "internal rustc attributes will never be stable",
945 cfg_fn!(rustc_attrs))),
946 ("rustc_item_path", Whitelisted, Gated(Stability::Unstable,
948 "internal rustc attributes will never be stable",
949 cfg_fn!(rustc_attrs))),
950 ("rustc_mir", Whitelisted, Gated(Stability::Unstable,
952 "the `#[rustc_mir]` attribute \
953 is just used for rustc unit tests \
954 and will never be stable",
955 cfg_fn!(rustc_attrs))),
956 ("rustc_inherit_overflow_checks", Whitelisted, Gated(Stability::Unstable,
958 "the `#[rustc_inherit_overflow_checks]` \
959 attribute is just used to control \
960 overflow checking behavior of several \
961 libcore functions that are inlined \
962 across crates and will never be stable",
963 cfg_fn!(rustc_attrs))),
965 ("rustc_dump_program_clauses", Whitelisted, Gated(Stability::Unstable,
967 "the `#[rustc_dump_program_clauses]` \
968 attribute is just used for rustc unit \
969 tests and will never be stable",
970 cfg_fn!(rustc_attrs))),
971 ("rustc_test_marker", Normal, Gated(Stability::Unstable,
973 "the `#[rustc_test_marker]` attribute \
974 is used internally to track tests",
975 cfg_fn!(rustc_attrs))),
976 ("rustc_test_marker2", Normal, Gated(Stability::Unstable,
978 "temporarily used by rustc to report some errors",
979 cfg_fn!(rustc_attrs))),
980 ("rustc_transparent_macro", Whitelisted, Gated(Stability::Unstable,
982 "used internally for testing macro hygiene",
983 cfg_fn!(rustc_attrs))),
986 ("nll", Whitelisted, Gated(Stability::Unstable,
988 "Non lexical lifetimes",
990 ("compiler_builtins", Whitelisted, Gated(Stability::Unstable,
992 "the `#[compiler_builtins]` attribute is used to \
993 identify the `compiler_builtins` crate which \
994 contains compiler-rt intrinsics and will never be \
996 cfg_fn!(compiler_builtins))),
997 ("sanitizer_runtime", Whitelisted, Gated(Stability::Unstable,
999 "the `#[sanitizer_runtime]` attribute is used to \
1000 identify crates that contain the runtime of a \
1001 sanitizer and will never be stable",
1002 cfg_fn!(sanitizer_runtime))),
1003 ("profiler_runtime", Whitelisted, Gated(Stability::Unstable,
1005 "the `#[profiler_runtime]` attribute is used to \
1006 identify the `profiler_builtins` crate which \
1007 contains the profiler runtime and will never be \
1009 cfg_fn!(profiler_runtime))),
1011 ("allow_internal_unstable", Normal, Gated(Stability::Unstable,
1012 "allow_internal_unstable",
1013 EXPLAIN_ALLOW_INTERNAL_UNSTABLE,
1014 cfg_fn!(allow_internal_unstable))),
1016 ("allow_internal_unsafe", Normal, Gated(Stability::Unstable,
1017 "allow_internal_unsafe",
1018 EXPLAIN_ALLOW_INTERNAL_UNSAFE,
1019 cfg_fn!(allow_internal_unsafe))),
1021 ("fundamental", Whitelisted, Gated(Stability::Unstable,
1023 "the `#[fundamental]` attribute \
1024 is an experimental feature",
1025 cfg_fn!(fundamental))),
1027 ("proc_macro_derive", Normal, Ungated),
1029 ("rustc_copy_clone_marker", Whitelisted, Gated(Stability::Unstable,
1031 "internal implementation detail",
1032 cfg_fn!(rustc_attrs))),
1034 // FIXME: #14408 whitelist docs since rustdoc looks at them
1035 ("doc", Whitelisted, Ungated),
1037 // FIXME: #14406 these are processed in codegen, which happens after the
1039 ("cold", Whitelisted, Ungated),
1040 ("naked", Whitelisted, Gated(Stability::Unstable,
1042 "the `#[naked]` attribute \
1043 is an experimental feature",
1044 cfg_fn!(naked_functions))),
1045 ("target_feature", Whitelisted, Ungated),
1046 ("export_name", Whitelisted, Ungated),
1047 ("inline", Whitelisted, Ungated),
1048 ("link", Whitelisted, Ungated),
1049 ("link_name", Whitelisted, Ungated),
1050 ("link_section", Whitelisted, Ungated),
1051 ("no_builtins", Whitelisted, Ungated),
1052 ("no_mangle", Whitelisted, Ungated),
1053 ("no_debug", Whitelisted, Gated(
1054 Stability::Deprecated("https://github.com/rust-lang/rust/issues/29721", None),
1056 "the `#[no_debug]` attribute was an experimental feature that has been \
1057 deprecated due to lack of demand",
1058 cfg_fn!(no_debug))),
1059 ("omit_gdb_pretty_printer_section", Whitelisted, Gated(Stability::Unstable,
1060 "omit_gdb_pretty_printer_section",
1061 "the `#[omit_gdb_pretty_printer_section]` \
1062 attribute is just used for the Rust test \
1064 cfg_fn!(omit_gdb_pretty_printer_section))),
1065 ("unsafe_destructor_blind_to_params",
1067 Gated(Stability::Deprecated("https://github.com/rust-lang/rust/issues/34761",
1068 Some("replace this attribute with `#[may_dangle]`")),
1069 "dropck_parametricity",
1070 "unsafe_destructor_blind_to_params has been replaced by \
1071 may_dangle and will be removed in the future",
1072 cfg_fn!(dropck_parametricity))),
1075 Gated(Stability::Unstable,
1077 "may_dangle has unstable semantics and may be removed in the future",
1078 cfg_fn!(dropck_eyepatch))),
1079 ("unwind", Whitelisted, Gated(Stability::Unstable,
1080 "unwind_attributes",
1081 "#[unwind] is experimental",
1082 cfg_fn!(unwind_attributes))),
1083 ("used", Whitelisted, Ungated),
1086 ("prelude_import", Whitelisted, Gated(Stability::Unstable,
1088 "`#[prelude_import]` is for use by rustc only",
1089 cfg_fn!(prelude_import))),
1091 // FIXME: #14407 these are only looked at on-demand so we can't
1092 // guarantee they'll have already been checked
1093 ("rustc_deprecated", Whitelisted, Ungated),
1094 ("must_use", Whitelisted, Ungated),
1095 ("stable", Whitelisted, Ungated),
1096 ("unstable", Whitelisted, Ungated),
1097 ("deprecated", Normal, Ungated),
1099 ("rustc_paren_sugar", Normal, Gated(Stability::Unstable,
1101 "unboxed_closures are still evolving",
1102 cfg_fn!(unboxed_closures))),
1104 ("windows_subsystem", Whitelisted, Ungated),
1106 ("proc_macro_attribute", Normal, Ungated),
1107 ("proc_macro", Normal, Ungated),
1109 ("rustc_derive_registrar", Normal, Gated(Stability::Unstable,
1110 "rustc_derive_registrar",
1111 "used internally by rustc",
1112 cfg_fn!(rustc_attrs))),
1114 ("allow_fail", Normal, Gated(Stability::Unstable,
1116 "allow_fail attribute is currently unstable",
1117 cfg_fn!(allow_fail))),
1119 ("rustc_std_internal_symbol", Whitelisted, Gated(Stability::Unstable,
1121 "this is an internal attribute that will \
1123 cfg_fn!(rustc_attrs))),
1125 // whitelists "identity-like" conversion methods to suggest on type mismatch
1126 ("rustc_conversion_suggestion", Whitelisted, Gated(Stability::Unstable,
1128 "this is an internal attribute that will \
1130 cfg_fn!(rustc_attrs))),
1132 ("rustc_args_required_const", Whitelisted, Gated(Stability::Unstable,
1134 "never will be stable",
1135 cfg_fn!(rustc_attrs))),
1138 ("infer_static_outlives_requirements", Normal, Gated(Stability::Unstable,
1139 "infer_static_outlives_requirements",
1140 "infer 'static lifetime requirements",
1141 cfg_fn!(infer_static_outlives_requirements))),
1143 // RFC 2070 (deprecated attribute name)
1144 ("panic_implementation",
1146 Gated(Stability::Deprecated("https://github.com/rust-lang/rust/issues/44489\
1147 #issuecomment-415140224",
1148 Some("replace this attribute with `#[panic_handler]`")),
1149 "panic_implementation",
1150 "this attribute was renamed to `panic_handler`",
1151 cfg_fn!(panic_implementation))),
1154 ("panic_handler", Normal, Ungated),
1156 ("alloc_error_handler", Normal, Gated(Stability::Unstable,
1157 "alloc_error_handler",
1158 "#[alloc_error_handler] is an unstable feature",
1159 cfg_fn!(alloc_error_handler))),
1161 // Crate level attributes
1162 ("crate_name", CrateLevel, Ungated),
1163 ("crate_type", CrateLevel, Ungated),
1164 ("crate_id", CrateLevel, Ungated),
1165 ("feature", CrateLevel, Ungated),
1166 ("no_start", CrateLevel, Ungated),
1167 ("no_main", CrateLevel, Ungated),
1168 ("no_builtins", CrateLevel, Ungated),
1169 ("recursion_limit", CrateLevel, Ungated),
1170 ("type_length_limit", CrateLevel, Ungated),
1171 ("test_runner", CrateLevel, Gated(Stability::Unstable,
1172 "custom_test_frameworks",
1173 EXPLAIN_CUSTOM_TEST_FRAMEWORKS,
1174 cfg_fn!(custom_test_frameworks))),
1177 // cfg(...)'s that are feature gated
1178 const GATED_CFGS: &[(&str, &str, fn(&Features) -> bool)] = &[
1179 // (name in cfg, feature, function to check if the feature is enabled)
1180 ("target_vendor", "cfg_target_vendor", cfg_fn!(cfg_target_vendor)),
1181 ("target_thread_local", "cfg_target_thread_local", cfg_fn!(cfg_target_thread_local)),
1182 ("target_has_atomic", "cfg_target_has_atomic", cfg_fn!(cfg_target_has_atomic)),
1183 ("rustdoc", "doc_cfg", cfg_fn!(doc_cfg)),
1187 pub struct GatedCfg {
1193 pub fn gate(cfg: &ast::MetaItem) -> Option<GatedCfg> {
1194 let name = cfg.name().as_str();
1196 .position(|info| info.0 == name)
1205 pub fn check_and_emit(&self, sess: &ParseSess, features: &Features) {
1206 let (cfg, feature, has_feature) = GATED_CFGS[self.index];
1207 if !has_feature(features) && !self.span.allows_unstable() {
1208 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
1209 emit_feature_err(sess, feature, self.span, GateIssue::Language, &explain);
1214 struct Context<'a> {
1215 features: &'a Features,
1216 parse_sess: &'a ParseSess,
1217 plugin_attributes: &'a [(String, AttributeType)],
1220 macro_rules! gate_feature_fn {
1221 ($cx: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr, $level: expr) => {{
1222 let (cx, has_feature, span,
1223 name, explain, level) = ($cx, $has_feature, $span, $name, $explain, $level);
1224 let has_feature: bool = has_feature(&$cx.features);
1225 debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
1226 if !has_feature && !span.allows_unstable() {
1227 leveled_feature_err(cx.parse_sess, name, span, GateIssue::Language, explain, level)
1233 macro_rules! gate_feature {
1234 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {
1235 gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
1236 stringify!($feature), $explain, GateStrength::Hard)
1238 ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {
1239 gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
1240 stringify!($feature), $explain, $level)
1244 impl<'a> Context<'a> {
1245 fn check_attribute(&self, attr: &ast::Attribute, is_macro: bool) {
1246 debug!("check_attribute(attr = {:?})", attr);
1247 let name = attr.name().as_str();
1248 for &(n, ty, ref gateage) in BUILTIN_ATTRIBUTES {
1250 if let Gated(_, name, desc, ref has_feature) = *gateage {
1251 gate_feature_fn!(self, has_feature, attr.span, name, desc, GateStrength::Hard);
1252 } else if name == "doc" {
1253 if let Some(content) = attr.meta_item_list() {
1254 if content.iter().any(|c| c.check_name("include")) {
1255 gate_feature!(self, external_doc, attr.span,
1256 "#[doc(include = \"...\")] is experimental"
1261 debug!("check_attribute: {:?} is builtin, {:?}, {:?}", attr.path, ty, gateage);
1265 for &(ref n, ref ty) in self.plugin_attributes {
1266 if attr.path == &**n {
1267 // Plugins can't gate attributes, so we don't check for it
1268 // unlike the code above; we only use this loop to
1269 // short-circuit to avoid the checks below
1270 debug!("check_attribute: {:?} is registered by a plugin, {:?}", attr.path, ty);
1274 if name.starts_with("rustc_") {
1275 gate_feature!(self, rustc_attrs, attr.span,
1276 "unless otherwise specified, attributes \
1277 with the prefix `rustc_` \
1278 are reserved for internal compiler diagnostics");
1279 } else if name.starts_with("derive_") {
1280 gate_feature!(self, custom_derive, attr.span, EXPLAIN_DERIVE_UNDERSCORE);
1281 } else if !attr::is_known(attr) {
1282 // Only run the custom attribute lint during regular
1283 // feature gate checking. Macro gating runs
1284 // before the plugin attributes are registered
1285 // so we skip this then
1287 let msg = format!("The attribute `{}` is currently unknown to the compiler and \
1288 may have meaning added to it in the future", attr.path);
1289 gate_feature!(self, custom_attribute, attr.span, &msg);
1295 pub fn check_attribute(attr: &ast::Attribute, parse_sess: &ParseSess, features: &Features) {
1296 let cx = Context { features: features, parse_sess: parse_sess, plugin_attributes: &[] };
1297 cx.check_attribute(attr, true);
1300 fn find_lang_feature_issue(feature: &str) -> Option<u32> {
1301 if let Some(info) = ACTIVE_FEATURES.iter().find(|t| t.0 == feature) {
1303 // FIXME (#28244): enforce that active features have issue numbers
1304 // assert!(issue.is_some())
1307 // search in Accepted, Removed, or Stable Removed features
1308 let found = ACCEPTED_FEATURES.iter().chain(REMOVED_FEATURES).chain(STABLE_REMOVED_FEATURES)
1309 .find(|t| t.0 == feature);
1311 Some(&(_, _, issue, _)) => issue,
1312 None => panic!("Feature `{}` is not declared anywhere", feature),
1317 pub enum GateIssue {
1319 Library(Option<u32>)
1322 #[derive(Debug, Copy, Clone, PartialEq)]
1323 pub enum GateStrength {
1324 /// A hard error. (Most feature gates should use this.)
1326 /// Only a warning. (Use this only as backwards-compatibility demands.)
1330 pub fn emit_feature_err(sess: &ParseSess, feature: &str, span: Span, issue: GateIssue,
1332 feature_err(sess, feature, span, issue, explain).emit();
1335 pub fn feature_err<'a>(sess: &'a ParseSess, feature: &str, span: Span, issue: GateIssue,
1336 explain: &str) -> DiagnosticBuilder<'a> {
1337 leveled_feature_err(sess, feature, span, issue, explain, GateStrength::Hard)
1340 fn leveled_feature_err<'a>(sess: &'a ParseSess, feature: &str, span: Span, issue: GateIssue,
1341 explain: &str, level: GateStrength) -> DiagnosticBuilder<'a> {
1342 let diag = &sess.span_diagnostic;
1344 let issue = match issue {
1345 GateIssue::Language => find_lang_feature_issue(feature),
1346 GateIssue::Library(lib) => lib,
1349 let explanation = match issue {
1350 None | Some(0) => explain.to_owned(),
1351 Some(n) => format!("{} (see issue #{})", explain, n)
1354 let mut err = match level {
1355 GateStrength::Hard => {
1356 diag.struct_span_err_with_code(span, &explanation, stringify_error_code!(E0658))
1358 GateStrength::Soft => diag.struct_span_warn(span, &explanation),
1361 // #23973: do not suggest `#![feature(...)]` if we are in beta/stable
1362 if sess.unstable_features.is_nightly_build() {
1363 err.help(&format!("add #![feature({})] to the \
1364 crate attributes to enable",
1368 // If we're on stable and only emitting a "soft" warning, add a note to
1369 // clarify that the feature isn't "on" (rather than being on but
1371 if !sess.unstable_features.is_nightly_build() && level == GateStrength::Soft {
1372 err.help("a nightly build of the compiler is required to enable this feature");
1379 const EXPLAIN_BOX_SYNTAX: &'static str =
1380 "box expression syntax is experimental; you can call `Box::new` instead.";
1382 pub const EXPLAIN_STMT_ATTR_SYNTAX: &'static str =
1383 "attributes on expressions are experimental.";
1385 pub const EXPLAIN_ASM: &'static str =
1386 "inline assembly is not stable enough for use and is subject to change";
1388 pub const EXPLAIN_GLOBAL_ASM: &'static str =
1389 "`global_asm!` is not stable enough for use and is subject to change";
1391 pub const EXPLAIN_CUSTOM_TEST_FRAMEWORKS: &'static str =
1392 "custom test frameworks are an unstable feature";
1394 pub const EXPLAIN_LOG_SYNTAX: &'static str =
1395 "`log_syntax!` is not stable enough for use and is subject to change";
1397 pub const EXPLAIN_CONCAT_IDENTS: &'static str =
1398 "`concat_idents` is not stable enough for use and is subject to change";
1400 pub const EXPLAIN_FORMAT_ARGS_NL: &'static str =
1401 "`format_args_nl` is only for internal language use and is subject to change";
1403 pub const EXPLAIN_TRACE_MACROS: &'static str =
1404 "`trace_macros` is not stable enough for use and is subject to change";
1405 pub const EXPLAIN_ALLOW_INTERNAL_UNSTABLE: &'static str =
1406 "allow_internal_unstable side-steps feature gating and stability checks";
1407 pub const EXPLAIN_ALLOW_INTERNAL_UNSAFE: &'static str =
1408 "allow_internal_unsafe side-steps the unsafe_code lint";
1410 pub const EXPLAIN_CUSTOM_DERIVE: &'static str =
1411 "`#[derive]` for custom traits is deprecated and will be removed in the future.";
1413 pub const EXPLAIN_DEPR_CUSTOM_DERIVE: &'static str =
1414 "`#[derive]` for custom traits is deprecated and will be removed in the future. \
1415 Prefer using procedural macro custom derive.";
1417 pub const EXPLAIN_DERIVE_UNDERSCORE: &'static str =
1418 "attributes of the form `#[derive_*]` are reserved for the compiler";
1420 pub const EXPLAIN_LITERAL_MATCHER: &'static str =
1421 ":literal fragment specifier is experimental and subject to change";
1423 pub const EXPLAIN_UNSIZED_TUPLE_COERCION: &'static str =
1424 "unsized tuple coercion is not stable enough for use and is subject to change";
1426 pub const EXPLAIN_MACRO_AT_MOST_ONCE_REP: &'static str =
1427 "using the `?` macro Kleene operator for \"at most one\" repetition is unstable";
1429 struct PostExpansionVisitor<'a> {
1430 context: &'a Context<'a>,
1433 macro_rules! gate_feature_post {
1434 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {{
1435 let (cx, span) = ($cx, $span);
1436 if !span.allows_unstable() {
1437 gate_feature!(cx.context, $feature, span, $explain)
1440 ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {{
1441 let (cx, span) = ($cx, $span);
1442 if !span.allows_unstable() {
1443 gate_feature!(cx.context, $feature, span, $explain, $level)
1448 impl<'a> PostExpansionVisitor<'a> {
1449 fn check_abi(&self, abi: Abi, span: Span) {
1451 Abi::RustIntrinsic => {
1452 gate_feature_post!(&self, intrinsics, span,
1453 "intrinsics are subject to change");
1455 Abi::PlatformIntrinsic => {
1456 gate_feature_post!(&self, platform_intrinsics, span,
1457 "platform intrinsics are experimental and possibly buggy");
1459 Abi::Vectorcall => {
1460 gate_feature_post!(&self, abi_vectorcall, span,
1461 "vectorcall is experimental and subject to change");
1464 gate_feature_post!(&self, abi_thiscall, span,
1465 "thiscall is experimental and subject to change");
1468 gate_feature_post!(&self, unboxed_closures, span,
1469 "rust-call ABI is subject to change");
1472 gate_feature_post!(&self, abi_ptx, span,
1473 "PTX ABIs are experimental and subject to change");
1475 Abi::Unadjusted => {
1476 gate_feature_post!(&self, abi_unadjusted, span,
1477 "unadjusted ABI is an implementation detail and perma-unstable");
1479 Abi::Msp430Interrupt => {
1480 gate_feature_post!(&self, abi_msp430_interrupt, span,
1481 "msp430-interrupt ABI is experimental and subject to change");
1483 Abi::X86Interrupt => {
1484 gate_feature_post!(&self, abi_x86_interrupt, span,
1485 "x86-interrupt ABI is experimental and subject to change");
1487 Abi::AmdGpuKernel => {
1488 gate_feature_post!(&self, abi_amdgpu_kernel, span,
1489 "amdgpu-kernel ABI is experimental and subject to change");
1505 impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
1506 fn visit_attribute(&mut self, attr: &ast::Attribute) {
1507 if !attr.span.allows_unstable() {
1508 // check for gated attributes
1509 self.context.check_attribute(attr, false);
1512 if attr.check_name("doc") {
1513 if let Some(content) = attr.meta_item_list() {
1514 if content.len() == 1 && content[0].check_name("cfg") {
1515 gate_feature_post!(&self, doc_cfg, attr.span,
1516 "#[doc(cfg(...))] is experimental"
1518 } else if content.iter().any(|c| c.check_name("masked")) {
1519 gate_feature_post!(&self, doc_masked, attr.span,
1520 "#[doc(masked)] is experimental"
1522 } else if content.iter().any(|c| c.check_name("spotlight")) {
1523 gate_feature_post!(&self, doc_spotlight, attr.span,
1524 "#[doc(spotlight)] is experimental"
1526 } else if content.iter().any(|c| c.check_name("alias")) {
1527 gate_feature_post!(&self, doc_alias, attr.span,
1528 "#[doc(alias = \"...\")] is experimental"
1530 } else if content.iter().any(|c| c.check_name("keyword")) {
1531 gate_feature_post!(&self, doc_keyword, attr.span,
1532 "#[doc(keyword = \"...\")] is experimental"
1538 if !self.context.features.unrestricted_attribute_tokens {
1539 // Unfortunately, `parse_meta` cannot be called speculatively
1540 // because it can report errors by itself, so we have to call it
1541 // only if the feature is disabled.
1542 if let Err(mut err) = attr.parse_meta(self.context.parse_sess) {
1543 err.help("try enabling `#![feature(unrestricted_attribute_tokens)]`").emit()
1548 fn visit_name(&mut self, sp: Span, name: ast::Name) {
1549 if !name.as_str().is_ascii() {
1550 gate_feature_post!(&self,
1552 self.context.parse_sess.source_map().def_span(sp),
1553 "non-ascii idents are not fully supported.");
1557 fn visit_use_tree(&mut self, use_tree: &'a ast::UseTree, id: NodeId, _nested: bool) {
1558 if let ast::UseTreeKind::Simple(Some(ident), ..) = use_tree.kind {
1559 if ident.name == "_" {
1560 gate_feature_post!(&self, underscore_imports, use_tree.span,
1561 "renaming imports with `_` is unstable");
1565 visit::walk_use_tree(self, use_tree, id);
1568 fn visit_item(&mut self, i: &'a ast::Item) {
1570 ast::ItemKind::ExternCrate(_) => {
1571 if i.ident.name == "_" {
1572 gate_feature_post!(&self, underscore_imports, i.span,
1573 "renaming extern crates with `_` is unstable");
1577 ast::ItemKind::ForeignMod(ref foreign_module) => {
1578 self.check_abi(foreign_module.abi, i.span);
1581 ast::ItemKind::Fn(..) => {
1582 if attr::contains_name(&i.attrs[..], "plugin_registrar") {
1583 gate_feature_post!(&self, plugin_registrar, i.span,
1584 "compiler plugins are experimental and possibly buggy");
1586 if attr::contains_name(&i.attrs[..], "start") {
1587 gate_feature_post!(&self, start, i.span,
1588 "a #[start] function is an experimental \
1589 feature whose signature may change \
1592 if attr::contains_name(&i.attrs[..], "main") {
1593 gate_feature_post!(&self, main, i.span,
1594 "declaration of a nonstandard #[main] \
1595 function may change over time, for now \
1596 a top-level `fn main()` is required");
1600 ast::ItemKind::Struct(..) => {
1601 if let Some(attr) = attr::find_by_name(&i.attrs[..], "repr") {
1602 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
1603 if item.check_name("simd") {
1604 gate_feature_post!(&self, repr_simd, attr.span,
1605 "SIMD types are experimental and possibly buggy");
1607 if let Some((name, _)) = item.name_value_literal() {
1608 if name == "packed" {
1609 gate_feature_post!(&self, repr_packed, attr.span,
1610 "the `#[repr(packed(n))]` attribute \
1618 ast::ItemKind::TraitAlias(..) => {
1619 gate_feature_post!(&self, trait_alias,
1621 "trait aliases are not yet fully implemented");
1624 ast::ItemKind::Impl(_, polarity, defaultness, _, _, _, _) => {
1625 if polarity == ast::ImplPolarity::Negative {
1626 gate_feature_post!(&self, optin_builtin_traits,
1628 "negative trait bounds are not yet fully implemented; \
1629 use marker types for now");
1632 if let ast::Defaultness::Default = defaultness {
1633 gate_feature_post!(&self, specialization,
1635 "specialization is unstable");
1639 ast::ItemKind::Trait(ast::IsAuto::Yes, ..) => {
1640 gate_feature_post!(&self, optin_builtin_traits,
1642 "auto traits are experimental and possibly buggy");
1645 ast::ItemKind::MacroDef(ast::MacroDef { legacy: false, .. }) => {
1646 let msg = "`macro` is experimental";
1647 gate_feature_post!(&self, decl_macro, i.span, msg);
1650 ast::ItemKind::Existential(..) => {
1655 "existential types are unstable"
1662 visit::walk_item(self, i);
1665 fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
1667 ast::ForeignItemKind::Fn(..) |
1668 ast::ForeignItemKind::Static(..) => {
1669 let link_name = attr::first_attr_value_str_by_name(&i.attrs, "link_name");
1670 let links_to_llvm = match link_name {
1671 Some(val) => val.as_str().starts_with("llvm."),
1675 gate_feature_post!(&self, link_llvm_intrinsics, i.span,
1676 "linking to LLVM intrinsics is experimental");
1679 ast::ForeignItemKind::Ty => {
1680 gate_feature_post!(&self, extern_types, i.span,
1681 "extern types are experimental");
1683 ast::ForeignItemKind::Macro(..) => {}
1686 visit::walk_foreign_item(self, i)
1689 fn visit_ty(&mut self, ty: &'a ast::Ty) {
1691 ast::TyKind::BareFn(ref bare_fn_ty) => {
1692 self.check_abi(bare_fn_ty.abi, ty.span);
1694 ast::TyKind::Never => {
1695 gate_feature_post!(&self, never_type, ty.span,
1696 "The `!` type is experimental");
1700 visit::walk_ty(self, ty)
1703 fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FunctionRetTy) {
1704 if let ast::FunctionRetTy::Ty(ref output_ty) = *ret_ty {
1705 if let ast::TyKind::Never = output_ty.node {
1708 self.visit_ty(output_ty)
1713 fn visit_expr(&mut self, e: &'a ast::Expr) {
1715 ast::ExprKind::Box(_) => {
1716 gate_feature_post!(&self, box_syntax, e.span, EXPLAIN_BOX_SYNTAX);
1718 ast::ExprKind::Type(..) => {
1719 gate_feature_post!(&self, type_ascription, e.span,
1720 "type ascription is experimental");
1722 ast::ExprKind::ObsoleteInPlace(..) => {
1723 // these get a hard error in ast-validation
1725 ast::ExprKind::Yield(..) => {
1726 gate_feature_post!(&self, generators,
1728 "yield syntax is experimental");
1730 ast::ExprKind::TryBlock(_) => {
1731 gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
1733 ast::ExprKind::IfLet(ref pats, ..) | ast::ExprKind::WhileLet(ref pats, ..) => {
1735 gate_feature_post!(&self, if_while_or_patterns, e.span,
1736 "multiple patterns in `if let` and `while let` are unstable");
1739 ast::ExprKind::Block(_, opt_label) => {
1740 if let Some(label) = opt_label {
1741 gate_feature_post!(&self, label_break_value, label.ident.span,
1742 "labels on blocks are unstable");
1745 ast::ExprKind::Closure(_, ast::IsAsync::Async { .. }, ..) => {
1746 gate_feature_post!(&self, async_await, e.span, "async closures are unstable");
1748 ast::ExprKind::Async(..) => {
1749 gate_feature_post!(&self, async_await, e.span, "async blocks are unstable");
1753 visit::walk_expr(self, e);
1756 fn visit_arm(&mut self, arm: &'a ast::Arm) {
1757 visit::walk_arm(self, arm)
1760 fn visit_pat(&mut self, pattern: &'a ast::Pat) {
1761 match pattern.node {
1762 PatKind::Slice(_, Some(ref subslice), _) => {
1763 gate_feature_post!(&self, slice_patterns,
1765 "syntax for subslices in slice patterns is not yet stabilized");
1767 PatKind::Box(..) => {
1768 gate_feature_post!(&self, box_patterns,
1770 "box pattern syntax is experimental");
1772 PatKind::Range(_, _, Spanned { node: RangeEnd::Excluded, .. }) => {
1773 gate_feature_post!(&self, exclusive_range_pattern, pattern.span,
1774 "exclusive range pattern syntax is experimental");
1776 PatKind::Paren(..) => {
1777 gate_feature_post!(&self, pattern_parentheses, pattern.span,
1778 "parentheses in patterns are unstable");
1782 visit::walk_pat(self, pattern)
1785 fn visit_fn(&mut self,
1786 fn_kind: FnKind<'a>,
1787 fn_decl: &'a ast::FnDecl,
1791 FnKind::ItemFn(_, header, _, _) => {
1792 // check for const fn and async fn declarations
1793 if header.asyncness.is_async() {
1794 gate_feature_post!(&self, async_await, span, "async fn is unstable");
1796 if header.constness.node == ast::Constness::Const {
1797 gate_feature_post!(&self, min_const_fn, span, "const fn is unstable");
1799 // stability of const fn methods are covered in
1800 // visit_trait_item and visit_impl_item below; this is
1801 // because default methods don't pass through this
1804 self.check_abi(header.abi, span);
1806 FnKind::Method(_, sig, _, _) => {
1807 self.check_abi(sig.header.abi, span);
1811 visit::walk_fn(self, fn_kind, fn_decl, span);
1814 fn visit_trait_item(&mut self, ti: &'a ast::TraitItem) {
1816 ast::TraitItemKind::Method(ref sig, ref block) => {
1817 if block.is_none() {
1818 self.check_abi(sig.header.abi, ti.span);
1820 if sig.header.constness.node == ast::Constness::Const {
1821 gate_feature_post!(&self, const_fn, ti.span, "const fn is unstable");
1824 ast::TraitItemKind::Type(_, ref default) => {
1825 // We use three if statements instead of something like match guards so that all
1826 // of these errors can be emitted if all cases apply.
1827 if default.is_some() {
1828 gate_feature_post!(&self, associated_type_defaults, ti.span,
1829 "associated type defaults are unstable");
1831 if !ti.generics.params.is_empty() {
1832 gate_feature_post!(&self, generic_associated_types, ti.span,
1833 "generic associated types are unstable");
1835 if !ti.generics.where_clause.predicates.is_empty() {
1836 gate_feature_post!(&self, generic_associated_types, ti.span,
1837 "where clauses on associated types are unstable");
1842 visit::walk_trait_item(self, ti);
1845 fn visit_impl_item(&mut self, ii: &'a ast::ImplItem) {
1846 if ii.defaultness == ast::Defaultness::Default {
1847 gate_feature_post!(&self, specialization,
1849 "specialization is unstable");
1853 ast::ImplItemKind::Method(ref sig, _) => {
1854 if sig.header.constness.node == ast::Constness::Const {
1855 gate_feature_post!(&self, min_const_fn, ii.span, "const fn is unstable");
1858 ast::ImplItemKind::Existential(..) => {
1863 "existential types are unstable"
1866 ast::ImplItemKind::Type(_) => {
1867 if !ii.generics.params.is_empty() {
1868 gate_feature_post!(&self, generic_associated_types, ii.span,
1869 "generic associated types are unstable");
1871 if !ii.generics.where_clause.predicates.is_empty() {
1872 gate_feature_post!(&self, generic_associated_types, ii.span,
1873 "where clauses on associated types are unstable");
1878 visit::walk_impl_item(self, ii);
1881 fn visit_path(&mut self, path: &'a ast::Path, _id: NodeId) {
1882 for segment in &path.segments {
1883 // Identifiers we are going to check could come from a legacy macro (e.g. `#[test]`).
1884 // For such macros identifiers must have empty context, because this context is
1885 // used during name resolution and produced names must be unhygienic for compatibility.
1886 // On the other hand, we need the actual non-empty context for feature gate checking
1887 // because it's hygienic even for legacy macros. As previously stated, such context
1888 // cannot be kept in identifiers, so it's kept in paths instead and we take it from
1889 // there while keeping location info from the ident span.
1890 let span = segment.ident.span.with_ctxt(path.span.ctxt());
1891 if segment.ident.name == keywords::Extern.name() {
1892 gate_feature_post!(&self, extern_in_paths, span,
1893 "`extern` in paths is experimental");
1897 visit::walk_path(self, path);
1900 fn visit_vis(&mut self, vis: &'a ast::Visibility) {
1901 if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.node {
1902 gate_feature_post!(&self, crate_visibility_modifier, vis.span,
1903 "`crate` visibility modifier is experimental");
1905 visit::walk_vis(self, vis);
1909 pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
1910 crate_edition: Edition) -> Features {
1911 fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) {
1912 let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
1913 if let Some(reason) = reason {
1914 err.span_note(span, reason);
1919 // Some features are known to be incomplete and using them is likely to have
1920 // unanticipated results, such as compiler crashes. We warn the user about these
1922 let incomplete_features = ["generic_associated_types"];
1924 let mut features = Features::new();
1925 let mut edition_enabled_features = FxHashMap();
1927 for &edition in ALL_EDITIONS {
1928 if edition <= crate_edition {
1929 // The `crate_edition` implies its respective umbrella feature-gate
1930 // (i.e. `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX).
1931 edition_enabled_features.insert(Symbol::intern(edition.feature_name()), edition);
1935 for &(name, .., f_edition, set) in ACTIVE_FEATURES {
1936 if let Some(f_edition) = f_edition {
1937 if f_edition <= crate_edition {
1938 set(&mut features, DUMMY_SP);
1939 edition_enabled_features.insert(Symbol::intern(name), crate_edition);
1944 // Process the edition umbrella feature-gates first, to ensure
1945 // `edition_enabled_features` is completed before it's queried.
1946 for attr in krate_attrs {
1947 if !attr.check_name("feature") {
1951 let list = match attr.meta_item_list() {
1957 let name = if let Some(word) = mi.word() {
1963 if incomplete_features.iter().any(|f| *f == name.as_str()) {
1964 span_handler.struct_span_warn(
1967 "the feature `{}` is incomplete and may cause the compiler to crash",
1973 if let Some(edition) = ALL_EDITIONS.iter().find(|e| name == e.feature_name()) {
1974 if *edition <= crate_edition {
1978 for &(name, .., f_edition, set) in ACTIVE_FEATURES {
1979 if let Some(f_edition) = f_edition {
1980 if f_edition <= *edition {
1981 // FIXME(Manishearth) there is currently no way to set
1982 // lib features by edition
1983 set(&mut features, DUMMY_SP);
1984 edition_enabled_features.insert(Symbol::intern(name), *edition);
1992 for attr in krate_attrs {
1993 if !attr.check_name("feature") {
1997 let list = match attr.meta_item_list() {
2000 span_err!(span_handler, attr.span, E0555,
2001 "malformed feature attribute, expected #![feature(...)]");
2007 let name = if let Some(word) = mi.word() {
2010 span_err!(span_handler, mi.span, E0556,
2011 "malformed feature, expected just one word");
2015 if let Some(edition) = edition_enabled_features.get(&name) {
2020 "the feature `{}` is included in the Rust {} edition",
2027 if ALL_EDITIONS.iter().any(|e| name == e.feature_name()) {
2028 // Handled in the separate loop above.
2032 if let Some((.., set)) = ACTIVE_FEATURES.iter().find(|f| name == f.0) {
2033 set(&mut features, mi.span);
2034 features.declared_lang_features.push((name, mi.span, None));
2038 let removed = REMOVED_FEATURES.iter().find(|f| name == f.0);
2039 let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.0);
2040 if let Some((.., reason)) = removed.or(stable_removed) {
2041 feature_removed(span_handler, mi.span, *reason);
2045 if let Some((_, since, ..)) = ACCEPTED_FEATURES.iter().find(|f| name == f.0) {
2046 let since = Some(Symbol::intern(since));
2047 features.declared_lang_features.push((name, mi.span, since));
2051 features.declared_lib_features.push((name, mi.span));
2058 pub fn check_crate(krate: &ast::Crate,
2060 features: &Features,
2061 plugin_attributes: &[(String, AttributeType)],
2062 unstable: UnstableFeatures) {
2063 maybe_stage_features(&sess.span_diagnostic, krate, unstable);
2070 let visitor = &mut PostExpansionVisitor { context: &ctx };
2071 visit::walk_crate(visitor, krate);
2074 #[derive(Clone, Copy, Hash)]
2075 pub enum UnstableFeatures {
2076 /// Hard errors for unstable features are active, as on
2077 /// beta/stable channels.
2079 /// Allow features to be activated, as on nightly.
2081 /// Errors are bypassed for bootstrapping. This is required any time
2082 /// during the build that feature-related lints are set to warn or above
2083 /// because the build turns on warnings-as-errors and uses lots of unstable
2084 /// features. As a result, this is always required for building Rust itself.
2088 impl UnstableFeatures {
2089 pub fn from_environment() -> UnstableFeatures {
2090 // Whether this is a feature-staged build, i.e. on the beta or stable channel
2091 let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
2092 // Whether we should enable unstable features for bootstrapping
2093 let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok();
2094 match (disable_unstable_features, bootstrap) {
2095 (_, true) => UnstableFeatures::Cheat,
2096 (true, _) => UnstableFeatures::Disallow,
2097 (false, _) => UnstableFeatures::Allow
2101 pub fn is_nightly_build(&self) -> bool {
2103 UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
2109 fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate,
2110 unstable: UnstableFeatures) {
2111 let allow_features = match unstable {
2112 UnstableFeatures::Allow => true,
2113 UnstableFeatures::Disallow => false,
2114 UnstableFeatures::Cheat => true
2116 if !allow_features {
2117 for attr in &krate.attrs {
2118 if attr.check_name("feature") {
2119 let release_channel = option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)");
2120 span_err!(span_handler, attr.span, E0554,
2121 "#![feature] may not be used on the {} release channel",