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::*;
29 use ast::{self, NodeId, PatKind, RangeEnd};
31 use edition::{ALL_EDITIONS, Edition};
33 use syntax_pos::{Span, DUMMY_SP};
34 use errors::{DiagnosticBuilder, Handler, FatalError};
35 use visit::{self, FnKind, Visitor};
37 use symbol::{keywords, Symbol};
43 fn f(features: &mut Features, span: Span) {
44 features.declared_lib_features.push((Symbol::intern("proc_macro"), span));
45 features.proc_macro = true;
47 f as fn(&mut Features, Span)
50 fn f(features: &mut Features, _: Span) {
51 features.$field = true;
53 f as fn(&mut Features, Span)
57 macro_rules! declare_features {
58 ($((active, $feature: ident, $ver: expr, $issue: expr, $edition: expr),)+) => {
59 /// Represents active features that are currently being implemented or
60 /// currently being considered for addition/removal.
61 const ACTIVE_FEATURES:
62 &'static [(&'static str, &'static str, Option<u32>,
63 Option<Edition>, fn(&mut Features, Span))] =
64 &[$((stringify!($feature), $ver, $issue, $edition, set!($feature))),+];
66 /// A set of features to be used by later passes.
69 /// `#![feature]` attrs for stable language features, for error reporting
70 pub declared_stable_lang_features: Vec<(Symbol, Span)>,
71 /// `#![feature]` attrs for non-language (library) features
72 pub declared_lib_features: Vec<(Symbol, Span)>,
73 $(pub $feature: bool),+
77 pub fn new() -> Features {
79 declared_stable_lang_features: Vec::new(),
80 declared_lib_features: Vec::new(),
85 pub fn walk_feature_fields<F>(&self, mut f: F)
86 where F: FnMut(&str, bool)
88 $(f(stringify!($feature), self.$feature);)+
93 ($((removed, $feature: ident, $ver: expr, $issue: expr, None),)+) => {
94 /// Represents unstable features which have since been removed (it was once Active)
95 const REMOVED_FEATURES: &'static [(&'static str, &'static str, Option<u32>)] = &[
96 $((stringify!($feature), $ver, $issue)),+
100 ($((stable_removed, $feature: ident, $ver: expr, $issue: expr, None),)+) => {
101 /// Represents stable features which have since been removed (it was once Accepted)
102 const STABLE_REMOVED_FEATURES: &'static [(&'static str, &'static str, Option<u32>)] = &[
103 $((stringify!($feature), $ver, $issue)),+
107 ($((accepted, $feature: ident, $ver: expr, $issue: expr, None),)+) => {
108 /// Those language feature has since been Accepted (it was once Active)
109 const ACCEPTED_FEATURES: &'static [(&'static str, &'static str, Option<u32>)] = &[
110 $((stringify!($feature), $ver, $issue)),+
115 // If you change this, please modify src/doc/unstable-book as well.
117 // Don't ever remove anything from this list; set them to 'Removed'.
119 // The version numbers here correspond to the version in which the current status
120 // was set. This is most important for knowing when a particular feature became
123 // NB: tools/tidy/src/features.rs parses this information directly out of the
124 // source, so take care when modifying it.
127 (active, asm, "1.0.0", Some(29722), None),
128 (active, concat_idents, "1.0.0", Some(29599), None),
129 (active, link_args, "1.0.0", Some(29596), None),
130 (active, log_syntax, "1.0.0", Some(29598), None),
131 (active, non_ascii_idents, "1.0.0", Some(28979), None),
132 (active, plugin_registrar, "1.0.0", Some(29597), None),
133 (active, thread_local, "1.0.0", Some(29594), None),
134 (active, trace_macros, "1.0.0", Some(29598), None),
136 // rustc internal, for now:
137 (active, intrinsics, "1.0.0", None, None),
138 (active, lang_items, "1.0.0", None, None),
140 (active, link_llvm_intrinsics, "1.0.0", Some(29602), None),
141 (active, linkage, "1.0.0", Some(29603), None),
142 (active, quote, "1.0.0", Some(29601), None),
146 (active, rustc_diagnostic_macros, "1.0.0", None, None),
147 (active, rustc_const_unstable, "1.0.0", None, None),
148 (active, box_syntax, "1.0.0", Some(27779), None),
149 (active, unboxed_closures, "1.0.0", Some(29625), None),
151 (active, fundamental, "1.0.0", Some(29635), None),
152 (active, main, "1.0.0", Some(29634), None),
153 (active, needs_allocator, "1.4.0", Some(27389), None),
154 (active, on_unimplemented, "1.0.0", Some(29628), None),
155 (active, plugin, "1.0.0", Some(29597), None),
156 (active, simd_ffi, "1.0.0", Some(27731), None),
157 (active, start, "1.0.0", Some(29633), None),
158 (active, structural_match, "1.8.0", Some(31434), None),
159 (active, panic_runtime, "1.10.0", Some(32837), None),
160 (active, needs_panic_runtime, "1.10.0", Some(32837), None),
162 // OIBIT specific features
163 (active, optin_builtin_traits, "1.0.0", Some(13231), None),
165 // macro re-export needs more discussion and stabilization
166 (active, macro_reexport, "1.0.0", Some(29638), None),
168 // Allows use of #[staged_api]
170 (active, staged_api, "1.0.0", None, None),
172 // Allows using #![no_core]
173 (active, no_core, "1.3.0", Some(29639), None),
175 // Allows using `box` in patterns; RFC 469
176 (active, box_patterns, "1.0.0", Some(29641), None),
178 // Allows using the unsafe_destructor_blind_to_params attribute;
180 (active, dropck_parametricity, "1.3.0", Some(28498), None),
182 // Allows using the may_dangle attribute; RFC 1327
183 (active, dropck_eyepatch, "1.10.0", Some(34761), None),
185 // Allows the use of custom attributes; RFC 572
186 (active, custom_attribute, "1.0.0", Some(29642), None),
188 // Allows the use of #[derive(Anything)] as sugar for
189 // #[derive_Anything].
190 (active, custom_derive, "1.0.0", Some(29644), None),
192 // Allows the use of rustc_* attributes; RFC 572
193 (active, rustc_attrs, "1.0.0", Some(29642), None),
195 // Allows the use of non lexical lifetimes; RFC 2094
196 (active, nll, "1.0.0", Some(43234), Some(Edition::Edition2018)),
198 // Allows the use of #[allow_internal_unstable]. This is an
199 // attribute on macro_rules! and can't use the attribute handling
200 // below (it has to be checked before expansion possibly makes
201 // macros disappear).
204 (active, allow_internal_unstable, "1.0.0", None, None),
206 // Allows the use of #[allow_internal_unsafe]. This is an
207 // attribute on macro_rules! and can't use the attribute handling
208 // below (it has to be checked before expansion possibly makes
209 // macros disappear).
212 (active, allow_internal_unsafe, "1.0.0", None, None),
214 // #23121. Array patterns have some hazards yet.
215 (active, slice_patterns, "1.0.0", Some(23121), None),
217 // Allows the definition of `const fn` functions.
218 (active, const_fn, "1.2.0", Some(24111), None),
220 // Allows using #[prelude_import] on glob `use` items.
223 (active, prelude_import, "1.2.0", None, None),
225 // Allows default type parameters to influence type inference.
226 (active, default_type_parameter_fallback, "1.3.0", Some(27336), None),
228 // Allows associated type defaults
229 (active, associated_type_defaults, "1.2.0", Some(29661), None),
231 // allow `repr(simd)`, and importing the various simd intrinsics
232 (active, repr_simd, "1.4.0", Some(27731), None),
234 // Allows cfg(target_feature = "...").
235 (active, cfg_target_feature, "1.4.0", Some(29717), None),
237 // allow `extern "platform-intrinsic" { ... }`
238 (active, platform_intrinsics, "1.4.0", Some(27731), None),
240 // allow `#[unwind(..)]`
241 // rust runtime internal
242 (active, unwind_attributes, "1.4.0", None, None),
244 // allow the use of `#[naked]` on functions.
245 (active, naked_functions, "1.9.0", Some(32408), None),
247 // allow `#[no_debug]`
248 (active, no_debug, "1.5.0", Some(29721), None),
250 // allow `#[omit_gdb_pretty_printer_section]`
252 (active, omit_gdb_pretty_printer_section, "1.5.0", None, None),
254 // Allows cfg(target_vendor = "...").
255 (active, cfg_target_vendor, "1.5.0", Some(29718), None),
257 // Allow attributes on expressions and non-item statements
258 (active, stmt_expr_attributes, "1.6.0", Some(15701), None),
260 // allow using type ascription in expressions
261 (active, type_ascription, "1.6.0", Some(23416), None),
263 // Allows cfg(target_thread_local)
264 (active, cfg_target_thread_local, "1.7.0", Some(29594), None),
267 (active, abi_vectorcall, "1.7.0", None, None),
270 (active, exclusive_range_pattern, "1.11.0", Some(37854), None),
272 // impl specialization (RFC 1210)
273 (active, specialization, "1.7.0", Some(31844), None),
275 // Allows cfg(target_has_atomic = "...").
276 (active, cfg_target_has_atomic, "1.9.0", Some(32976), None),
278 // Allows exhaustive pattern matching on types that contain uninhabited types.
279 (active, exhaustive_patterns, "1.13.0", None, None),
281 // Allows all literals in attribute lists and values of key-value pairs.
282 (active, attr_literals, "1.13.0", Some(34981), None),
284 // Allows untagged unions `union U { ... }`
285 (active, untagged_unions, "1.13.0", Some(32836), None),
287 // Used to identify the `compiler_builtins` crate
289 (active, compiler_builtins, "1.13.0", None, None),
291 // Allows #[link(..., cfg(..))]
292 (active, link_cfg, "1.14.0", Some(37406), None),
294 (active, use_extern_macros, "1.15.0", Some(35896), None),
296 // Allows #[target_feature(...)]
297 (active, target_feature, "1.15.0", None, None),
299 // `extern "ptx-*" fn()`
300 (active, abi_ptx, "1.15.0", None, None),
302 // The `repr(i128)` annotation for enums
303 (active, repr128, "1.16.0", Some(35118), None),
305 // The `unadjusted` ABI. Perma unstable.
306 (active, abi_unadjusted, "1.16.0", None, None),
308 // Procedural macros 2.0.
309 (active, proc_macro, "1.16.0", Some(38356), None),
311 // Declarative macros 2.0 (`macro`).
312 (active, decl_macro, "1.17.0", Some(39412), None),
314 // Allows #[link(kind="static-nobundle"...]
315 (active, static_nobundle, "1.16.0", Some(37403), None),
317 // `extern "msp430-interrupt" fn()`
318 (active, abi_msp430_interrupt, "1.16.0", Some(38487), None),
320 // Used to identify crates that contain sanitizer runtimes
322 (active, sanitizer_runtime, "1.17.0", None, None),
324 // Used to identify crates that contain the profiler runtime
326 (active, profiler_runtime, "1.18.0", None, None),
328 // `extern "x86-interrupt" fn()`
329 (active, abi_x86_interrupt, "1.17.0", Some(40180), None),
332 // Allows the `catch {...}` expression
333 (active, catch_expr, "1.17.0", Some(31436), None),
335 // Used to preserve symbols (see llvm.used)
336 (active, used, "1.18.0", Some(40289), None),
338 // Allows module-level inline assembly by way of global_asm!()
339 (active, global_asm, "1.18.0", Some(35119), None),
341 // Allows overlapping impls of marker traits
342 (active, overlapping_marker_traits, "1.18.0", Some(29864), None),
344 // Allows use of the :vis macro fragment specifier
345 (active, macro_vis_matcher, "1.18.0", Some(41022), None),
348 (active, abi_thiscall, "1.19.0", None, None),
350 // Allows a test to fail without failing the whole suite
351 (active, allow_fail, "1.19.0", Some(42219), None),
353 // Allows unsized tuple coercion.
354 (active, unsized_tuple_coercion, "1.20.0", Some(42877), None),
357 (active, generators, "1.21.0", None, None),
360 (active, trait_alias, "1.24.0", Some(41517), None),
362 // global allocators and their internals
363 (active, global_allocator, "1.20.0", None, None),
364 (active, allocator_internals, "1.20.0", None, None),
367 (active, doc_cfg, "1.21.0", Some(43781), None),
369 (active, doc_masked, "1.21.0", Some(44027), None),
371 (active, doc_spotlight, "1.22.0", Some(45040), None),
372 // #[doc(include="some-file")]
373 (active, external_doc, "1.22.0", Some(44732), None),
375 // allow `#[must_use]` on functions and comparison operators (RFC 1940)
376 (active, fn_must_use, "1.21.0", Some(43302), None),
378 // Future-proofing enums/structs with #[non_exhaustive] attribute (RFC 2008)
379 (active, non_exhaustive, "1.22.0", Some(44109), None),
381 // allow `'_` placeholder lifetimes
382 (active, underscore_lifetimes, "1.22.0", Some(44524), None),
384 // Default match binding modes (RFC 2005)
385 (active, match_default_bindings, "1.22.0", Some(42640), None),
387 // Trait object syntax with `dyn` prefix
388 (active, dyn_trait, "1.22.0", Some(44662), Some(Edition::Edition2018)),
390 // `crate` as visibility modifier, synonymous to `pub(crate)`
391 (active, crate_visibility_modifier, "1.23.0", Some(45388), Some(Edition::Edition2018)),
394 (active, extern_types, "1.23.0", Some(43467), None),
396 // Allow trait methods with arbitrary self types
397 (active, arbitrary_self_types, "1.23.0", Some(44874), None),
400 (active, crate_in_paths, "1.23.0", Some(45477), Some(Edition::Edition2018)),
402 // In-band lifetime bindings (e.g. `fn foo(x: &'a u8) -> &'a u8`)
403 (active, in_band_lifetimes, "1.23.0", Some(44524), Some(Edition::Edition2018)),
405 // generic associated types (RFC 1598)
406 (active, generic_associated_types, "1.23.0", Some(44265), None),
408 // Resolve absolute paths as paths from other crates
409 (active, extern_absolute_paths, "1.24.0", Some(44660), None),
411 // `foo.rs` as an alternative to `foo/mod.rs`
412 (active, non_modrs_mods, "1.24.0", Some(44660), Some(Edition::Edition2018)),
414 // Termination trait in tests (RFC 1937)
415 (active, termination_trait_test, "1.24.0", Some(48854), Some(Edition::Edition2018)),
417 // Allows use of the :lifetime macro fragment specifier
418 (active, macro_lifetime_matcher, "1.24.0", Some(46895), None),
421 (active, extern_in_paths, "1.23.0", Some(44660), None),
423 // Allows `#[repr(transparent)]` attribute on newtype structs
424 (active, repr_transparent, "1.25.0", Some(43036), None),
426 // Use `?` as the Kleene "at most one" operator
427 (active, macro_at_most_once_rep, "1.25.0", Some(48075), None),
429 // Multiple patterns with `|` in `if let` and `while let`
430 (active, if_while_or_patterns, "1.26.0", Some(48215), None),
432 // Parentheses in patterns
433 (active, pattern_parentheses, "1.26.0", None, None),
435 // `use path as _;` and `extern crate c as _;`
436 (active, underscore_imports, "1.26.0", Some(48216), None),
438 // The #[wasm_custom_section] attribute
439 (active, wasm_custom_section, "1.26.0", None, None),
441 // The #![wasm_import_module] attribute
442 (active, wasm_import_module, "1.26.0", None, None),
444 // Allows keywords to be escaped for use as identifiers
445 (active, raw_identifiers, "1.26.0", Some(48589), None),
447 // Allows macro invocations in `extern {}` blocks
448 (active, macros_in_extern, "1.27.0", Some(49476), None),
452 (removed, import_shadowing, "1.0.0", None, None),
453 (removed, managed_boxes, "1.0.0", None, None),
454 // Allows use of unary negate on unsigned integers, e.g. -e for e: u8
455 (removed, negate_unsigned, "1.0.0", Some(29645), None),
456 (removed, reflect, "1.0.0", Some(27749), None),
457 // A way to temporarily opt out of opt in copy. This will *never* be accepted.
458 (removed, opt_out_copy, "1.0.0", None, None),
459 (removed, quad_precision_float, "1.0.0", None, None),
460 (removed, struct_inherit, "1.0.0", None, None),
461 (removed, test_removed_feature, "1.0.0", None, None),
462 (removed, visible_private_types, "1.0.0", None, None),
463 (removed, unsafe_no_drop_flag, "1.0.0", None, None),
464 // Allows using items which are missing stability attributes
466 (removed, unmarked_api, "1.0.0", None, None),
467 (removed, pushpop_unsafe, "1.2.0", None, None),
468 (removed, allocator, "1.0.0", None, None),
469 // Allows the `#[simd]` attribute -- removed in favor of `#[repr(simd)]`
470 (removed, simd, "1.0.0", Some(27731), None),
471 // Merged into `slice_patterns`
472 (removed, advanced_slice_patterns, "1.0.0", Some(23121), None),
476 (stable_removed, no_stack_check, "1.0.0", None, None),
480 (accepted, associated_types, "1.0.0", None, None),
481 // allow overloading augmented assignment operations like `a += b`
482 (accepted, augmented_assignments, "1.8.0", Some(28235), None),
483 // allow empty structs and enum variants with braces
484 (accepted, braced_empty_structs, "1.8.0", Some(29720), None),
485 // Allows indexing into constant arrays.
486 (accepted, const_indexing, "1.24.0", Some(29947), None),
487 (accepted, default_type_params, "1.0.0", None, None),
488 (accepted, globs, "1.0.0", None, None),
489 (accepted, if_let, "1.0.0", None, None),
490 // A temporary feature gate used to enable parser extensions needed
491 // to bootstrap fix for #5723.
492 (accepted, issue_5723_bootstrap, "1.0.0", None, None),
493 (accepted, macro_rules, "1.0.0", None, None),
494 // Allows using #![no_std]
495 (accepted, no_std, "1.6.0", None, None),
496 (accepted, slicing_syntax, "1.0.0", None, None),
497 (accepted, struct_variant, "1.0.0", None, None),
498 // These are used to test this portion of the compiler, they don't actually
500 (accepted, test_accepted_feature, "1.0.0", None, None),
501 (accepted, tuple_indexing, "1.0.0", None, None),
502 // Allows macros to appear in the type position.
503 (accepted, type_macros, "1.13.0", Some(27245), None),
504 (accepted, while_let, "1.0.0", None, None),
505 // Allows `#[deprecated]` attribute
506 (accepted, deprecated, "1.9.0", Some(29935), None),
508 (accepted, question_mark, "1.13.0", Some(31436), None),
509 // Allows `..` in tuple (struct) patterns
510 (accepted, dotdot_in_tuple_patterns, "1.14.0", Some(33627), None),
511 (accepted, item_like_imports, "1.15.0", Some(35120), None),
512 // Allows using `Self` and associated types in struct expressions and patterns.
513 (accepted, more_struct_aliases, "1.16.0", Some(37544), None),
514 // elide `'static` lifetimes in `static`s and `const`s
515 (accepted, static_in_const, "1.17.0", Some(35897), None),
516 // Allows field shorthands (`x` meaning `x: x`) in struct literal expressions.
517 (accepted, field_init_shorthand, "1.17.0", Some(37340), None),
518 // Allows the definition recursive static items.
519 (accepted, static_recursion, "1.17.0", Some(29719), None),
520 // pub(restricted) visibilities (RFC 1422)
521 (accepted, pub_restricted, "1.18.0", Some(32409), None),
522 // The #![windows_subsystem] attribute
523 (accepted, windows_subsystem, "1.18.0", Some(37499), None),
524 // Allows `break {expr}` with a value inside `loop`s.
525 (accepted, loop_break_value, "1.19.0", Some(37339), None),
526 // Permits numeric fields in struct expressions and patterns.
527 (accepted, relaxed_adts, "1.19.0", Some(35626), None),
528 // Coerces non capturing closures to function pointers
529 (accepted, closure_to_fn_coercion, "1.19.0", Some(39817), None),
530 // Allows attributes on struct literal fields.
531 (accepted, struct_field_attributes, "1.20.0", Some(38814), None),
532 // Allows the definition of associated constants in `trait` or `impl`
534 (accepted, associated_consts, "1.20.0", Some(29646), None),
535 // Usage of the `compile_error!` macro
536 (accepted, compile_error, "1.20.0", Some(40872), None),
537 // See rust-lang/rfcs#1414. Allows code like `let x: &'static u32 = &42` to work.
538 (accepted, rvalue_static_promotion, "1.21.0", Some(38865), None),
539 // Allow Drop types in constants (RFC 1440)
540 (accepted, drop_types_in_const, "1.22.0", Some(33156), None),
541 // Allows the sysV64 ABI to be specified on all platforms
542 // instead of just the platforms on which it is the C ABI
543 (accepted, abi_sysv64, "1.24.0", Some(36167), None),
544 // Allows `repr(align(16))` struct attribute (RFC 1358)
545 (accepted, repr_align, "1.25.0", Some(33626), None),
546 // allow '|' at beginning of match arms (RFC 1925)
547 (accepted, match_beginning_vert, "1.25.0", Some(44101), None),
548 // Nested groups in `use` (RFC 2128)
549 (accepted, use_nested_groups, "1.25.0", Some(44494), None),
551 (accepted, inclusive_range_syntax, "1.26.0", Some(28237), None),
552 // allow `..=` in patterns (RFC 1192)
553 (accepted, dotdoteq_in_patterns, "1.26.0", Some(28237), None),
554 // Termination trait in main (RFC 1937)
555 (accepted, termination_trait, "1.26.0", Some(43301), None),
556 // Copy/Clone closures (RFC 2132)
557 (accepted, clone_closures, "1.26.0", Some(44490), None),
558 (accepted, copy_closures, "1.26.0", Some(44490), None),
559 // Allows `impl Trait` in function arguments.
560 (accepted, universal_impl_trait, "1.26.0", Some(34511), None),
561 // Allows `impl Trait` in function return types.
562 (accepted, conservative_impl_trait, "1.26.0", Some(34511), None),
564 (accepted, i128_type, "1.26.0", Some(35118), None),
565 // Default match binding modes (RFC 2005)
566 (accepted, match_default_bindings, "1.26.0", Some(42640), None),
567 // allow `'_` placeholder lifetimes
568 (accepted, underscore_lifetimes, "1.26.0", Some(44524), None),
569 // Allows attributes on lifetime/type formal parameters in generics (RFC 1327)
570 (accepted, generic_param_attrs, "1.26.0", Some(48848), None),
573 // If you change this, please modify src/doc/unstable-book as well. You must
574 // move that documentation into the relevant place in the other docs, and
575 // remove the chapter on the flag.
577 #[derive(PartialEq, Copy, Clone, Debug)]
578 pub enum AttributeType {
579 /// Normal, builtin attribute that is consumed
580 /// by the compiler before the unused_attribute check
583 /// Builtin attribute that may not be consumed by the compiler
584 /// before the unused_attribute check. These attributes
585 /// will be ignored by the unused_attribute lint
588 /// Builtin attribute that is only allowed at the crate level
592 pub enum AttributeGate {
593 /// Is gated by a given feature gate, reason
594 /// and function to check if enabled
595 Gated(Stability, &'static str, &'static str, fn(&Features) -> bool),
597 /// Ungated attribute, can be used on all release channels
602 fn is_deprecated(&self) -> bool {
604 Gated(Stability::Deprecated(_), ..) => true,
610 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
613 // Argument is tracking issue link.
614 Deprecated(&'static str),
618 impl ::std::fmt::Debug for AttributeGate {
619 fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
621 Gated(ref stab, name, expl, _) =>
622 write!(fmt, "Gated({:?}, {}, {})", stab, name, expl),
623 Ungated => write!(fmt, "Ungated")
628 macro_rules! cfg_fn {
629 ($field: ident) => {{
630 fn f(features: &Features) -> bool {
633 f as fn(&Features) -> bool
637 pub fn deprecated_attributes() -> Vec<&'static (&'static str, AttributeType, AttributeGate)> {
638 BUILTIN_ATTRIBUTES.iter().filter(|a| a.2.is_deprecated()).collect()
641 pub fn is_builtin_attr(attr: &ast::Attribute) -> bool {
642 BUILTIN_ATTRIBUTES.iter().any(|&(builtin_name, _, _)| attr.check_name(builtin_name))
645 // Attributes that have a special meaning to rustc or rustdoc
646 pub const BUILTIN_ATTRIBUTES: &'static [(&'static str, AttributeType, AttributeGate)] = &[
649 ("warn", Normal, Ungated),
650 ("allow", Normal, Ungated),
651 ("forbid", Normal, Ungated),
652 ("deny", Normal, Ungated),
654 ("macro_reexport", Normal, Ungated),
655 ("macro_use", Normal, Ungated),
656 ("macro_export", Normal, Ungated),
657 ("plugin_registrar", Normal, Ungated),
659 ("cfg", Normal, Ungated),
660 ("cfg_attr", Normal, Ungated),
661 ("main", Normal, Ungated),
662 ("start", Normal, Ungated),
663 ("test", Normal, Ungated),
664 ("bench", Normal, Ungated),
665 ("repr", Normal, Ungated),
666 ("path", Normal, Ungated),
667 ("abi", Normal, Ungated),
668 ("automatically_derived", Normal, Ungated),
669 ("no_mangle", Normal, Ungated),
670 ("no_link", Normal, Ungated),
671 ("derive", Normal, Ungated),
672 ("should_panic", Normal, Ungated),
673 ("ignore", Normal, Ungated),
674 ("no_implicit_prelude", Normal, Ungated),
675 ("reexport_test_harness_main", Normal, Ungated),
676 ("link_args", Normal, Gated(Stability::Unstable,
678 "the `link_args` attribute is experimental and not \
679 portable across platforms, it is recommended to \
680 use `#[link(name = \"foo\")] instead",
681 cfg_fn!(link_args))),
682 ("macro_escape", Normal, Ungated),
685 ("structural_match", Whitelisted, Gated(Stability::Unstable,
687 "the semantics of constant patterns is \
689 cfg_fn!(structural_match))),
692 ("non_exhaustive", Whitelisted, Gated(Stability::Unstable,
694 "non exhaustive is an experimental feature",
695 cfg_fn!(non_exhaustive))),
697 ("plugin", CrateLevel, Gated(Stability::Unstable,
699 "compiler plugins are experimental \
703 ("no_std", CrateLevel, Ungated),
704 ("no_core", CrateLevel, Gated(Stability::Unstable,
706 "no_core is experimental",
708 ("lang", Normal, Gated(Stability::Unstable,
710 "language items are subject to change",
711 cfg_fn!(lang_items))),
712 ("linkage", Whitelisted, Gated(Stability::Unstable,
714 "the `linkage` attribute is experimental \
715 and not portable across platforms",
717 ("thread_local", Whitelisted, Gated(Stability::Unstable,
719 "`#[thread_local]` is an experimental feature, and does \
720 not currently handle destructors.",
721 cfg_fn!(thread_local))),
723 ("rustc_on_unimplemented", Normal, Gated(Stability::Unstable,
725 "the `#[rustc_on_unimplemented]` attribute \
726 is an experimental feature",
727 cfg_fn!(on_unimplemented))),
728 ("rustc_const_unstable", Normal, Gated(Stability::Unstable,
729 "rustc_const_unstable",
730 "the `#[rustc_const_unstable]` attribute \
731 is an internal feature",
732 cfg_fn!(rustc_const_unstable))),
733 ("global_allocator", Normal, Gated(Stability::Unstable,
735 "the `#[global_allocator]` attribute is \
736 an experimental feature",
737 cfg_fn!(global_allocator))),
738 ("default_lib_allocator", Whitelisted, Gated(Stability::Unstable,
739 "allocator_internals",
740 "the `#[default_lib_allocator]` \
741 attribute is an experimental feature",
742 cfg_fn!(allocator_internals))),
743 ("needs_allocator", Normal, Gated(Stability::Unstable,
744 "allocator_internals",
745 "the `#[needs_allocator]` \
746 attribute is an experimental \
748 cfg_fn!(allocator_internals))),
749 ("panic_runtime", Whitelisted, Gated(Stability::Unstable,
751 "the `#[panic_runtime]` attribute is \
752 an experimental feature",
753 cfg_fn!(panic_runtime))),
754 ("needs_panic_runtime", Whitelisted, Gated(Stability::Unstable,
755 "needs_panic_runtime",
756 "the `#[needs_panic_runtime]` \
757 attribute is an experimental \
759 cfg_fn!(needs_panic_runtime))),
760 ("rustc_variance", Normal, Gated(Stability::Unstable,
762 "the `#[rustc_variance]` attribute \
763 is just used for rustc unit tests \
764 and will never be stable",
765 cfg_fn!(rustc_attrs))),
766 ("rustc_regions", Normal, Gated(Stability::Unstable,
768 "the `#[rustc_regions]` attribute \
769 is just used for rustc unit tests \
770 and will never be stable",
771 cfg_fn!(rustc_attrs))),
772 ("rustc_error", Whitelisted, Gated(Stability::Unstable,
774 "the `#[rustc_error]` attribute \
775 is just used for rustc unit tests \
776 and will never be stable",
777 cfg_fn!(rustc_attrs))),
778 ("rustc_if_this_changed", Whitelisted, Gated(Stability::Unstable,
780 "the `#[rustc_if_this_changed]` attribute \
781 is just used for rustc unit tests \
782 and will never be stable",
783 cfg_fn!(rustc_attrs))),
784 ("rustc_then_this_would_need", Whitelisted, Gated(Stability::Unstable,
786 "the `#[rustc_if_this_changed]` attribute \
787 is just used for rustc unit tests \
788 and will never be stable",
789 cfg_fn!(rustc_attrs))),
790 ("rustc_dirty", Whitelisted, Gated(Stability::Unstable,
792 "the `#[rustc_dirty]` attribute \
793 is just used for rustc unit tests \
794 and will never be stable",
795 cfg_fn!(rustc_attrs))),
796 ("rustc_clean", Whitelisted, Gated(Stability::Unstable,
798 "the `#[rustc_clean]` attribute \
799 is just used for rustc unit tests \
800 and will never be stable",
801 cfg_fn!(rustc_attrs))),
802 ("rustc_partition_reused", Whitelisted, Gated(Stability::Unstable,
805 is just used for rustc unit tests \
806 and will never be stable",
807 cfg_fn!(rustc_attrs))),
808 ("rustc_partition_translated", Whitelisted, Gated(Stability::Unstable,
811 is just used for rustc unit tests \
812 and will never be stable",
813 cfg_fn!(rustc_attrs))),
814 ("rustc_serialize_exclude_null", Normal, Gated(Stability::Unstable,
816 "the `#[rustc_serialize_exclude_null]` attribute \
817 is an internal-only feature",
818 cfg_fn!(rustc_attrs))),
819 ("rustc_synthetic", Whitelisted, Gated(Stability::Unstable,
822 is just used for rustc unit tests \
823 and will never be stable",
824 cfg_fn!(rustc_attrs))),
825 ("rustc_symbol_name", Whitelisted, Gated(Stability::Unstable,
827 "internal rustc attributes will never be stable",
828 cfg_fn!(rustc_attrs))),
829 ("rustc_item_path", Whitelisted, Gated(Stability::Unstable,
831 "internal rustc attributes will never be stable",
832 cfg_fn!(rustc_attrs))),
833 ("rustc_mir", Whitelisted, Gated(Stability::Unstable,
835 "the `#[rustc_mir]` attribute \
836 is just used for rustc unit tests \
837 and will never be stable",
838 cfg_fn!(rustc_attrs))),
839 ("rustc_inherit_overflow_checks", Whitelisted, Gated(Stability::Unstable,
841 "the `#[rustc_inherit_overflow_checks]` \
842 attribute is just used to control \
843 overflow checking behavior of several \
844 libcore functions that are inlined \
845 across crates and will never be stable",
846 cfg_fn!(rustc_attrs))),
848 ("rustc_dump_program_clauses", Whitelisted, Gated(Stability::Unstable,
850 "the `#[rustc_dump_program_clauses]` \
851 attribute is just used for rustc unit \
852 tests and will never be stable",
853 cfg_fn!(rustc_attrs))),
856 ("nll", Whitelisted, Gated(Stability::Unstable,
858 "Non lexical lifetimes",
860 ("compiler_builtins", Whitelisted, Gated(Stability::Unstable,
862 "the `#[compiler_builtins]` attribute is used to \
863 identify the `compiler_builtins` crate which \
864 contains compiler-rt intrinsics and will never be \
866 cfg_fn!(compiler_builtins))),
867 ("sanitizer_runtime", Whitelisted, Gated(Stability::Unstable,
869 "the `#[sanitizer_runtime]` attribute is used to \
870 identify crates that contain the runtime of a \
871 sanitizer and will never be stable",
872 cfg_fn!(sanitizer_runtime))),
873 ("profiler_runtime", Whitelisted, Gated(Stability::Unstable,
875 "the `#[profiler_runtime]` attribute is used to \
876 identify the `profiler_builtins` crate which \
877 contains the profiler runtime and will never be \
879 cfg_fn!(profiler_runtime))),
881 ("allow_internal_unstable", Normal, Gated(Stability::Unstable,
882 "allow_internal_unstable",
883 EXPLAIN_ALLOW_INTERNAL_UNSTABLE,
884 cfg_fn!(allow_internal_unstable))),
886 ("allow_internal_unsafe", Normal, Gated(Stability::Unstable,
887 "allow_internal_unsafe",
888 EXPLAIN_ALLOW_INTERNAL_UNSAFE,
889 cfg_fn!(allow_internal_unsafe))),
891 ("fundamental", Whitelisted, Gated(Stability::Unstable,
893 "the `#[fundamental]` attribute \
894 is an experimental feature",
895 cfg_fn!(fundamental))),
897 ("proc_macro_derive", Normal, Ungated),
899 ("rustc_copy_clone_marker", Whitelisted, Gated(Stability::Unstable,
901 "internal implementation detail",
902 cfg_fn!(rustc_attrs))),
904 // FIXME: #14408 whitelist docs since rustdoc looks at them
905 ("doc", Whitelisted, Ungated),
907 // FIXME: #14406 these are processed in trans, which happens after the
909 ("cold", Whitelisted, Ungated),
910 ("naked", Whitelisted, Gated(Stability::Unstable,
912 "the `#[naked]` attribute \
913 is an experimental feature",
914 cfg_fn!(naked_functions))),
915 ("target_feature", Whitelisted, Gated(
916 Stability::Unstable, "target_feature",
917 "the `#[target_feature]` attribute is an experimental feature",
918 cfg_fn!(target_feature))),
919 ("export_name", Whitelisted, Ungated),
920 ("inline", Whitelisted, Ungated),
921 ("link", Whitelisted, Ungated),
922 ("link_name", Whitelisted, Ungated),
923 ("link_section", Whitelisted, Ungated),
924 ("no_builtins", Whitelisted, Ungated),
925 ("no_mangle", Whitelisted, Ungated),
926 ("no_debug", Whitelisted, Gated(
927 Stability::Deprecated("https://github.com/rust-lang/rust/issues/29721"),
929 "the `#[no_debug]` attribute was an experimental feature that has been \
930 deprecated due to lack of demand",
932 ("wasm_import_module", Normal, Gated(Stability::Unstable,
933 "wasm_import_module",
934 "experimental attribute",
935 cfg_fn!(wasm_import_module))),
936 ("omit_gdb_pretty_printer_section", Whitelisted, Gated(Stability::Unstable,
937 "omit_gdb_pretty_printer_section",
938 "the `#[omit_gdb_pretty_printer_section]` \
939 attribute is just used for the Rust test \
941 cfg_fn!(omit_gdb_pretty_printer_section))),
942 ("unsafe_destructor_blind_to_params",
944 Gated(Stability::Deprecated("https://github.com/rust-lang/rust/issues/34761"),
945 "dropck_parametricity",
946 "unsafe_destructor_blind_to_params has been replaced by \
947 may_dangle and will be removed in the future",
948 cfg_fn!(dropck_parametricity))),
951 Gated(Stability::Unstable,
953 "may_dangle has unstable semantics and may be removed in the future",
954 cfg_fn!(dropck_eyepatch))),
955 ("unwind", Whitelisted, Gated(Stability::Unstable,
957 "#[unwind] is experimental",
958 cfg_fn!(unwind_attributes))),
959 ("used", Whitelisted, Gated(
960 Stability::Unstable, "used",
961 "the `#[used]` attribute is an experimental feature",
965 ("prelude_import", Whitelisted, Gated(Stability::Unstable,
967 "`#[prelude_import]` is for use by rustc only",
968 cfg_fn!(prelude_import))),
970 // FIXME: #14407 these are only looked at on-demand so we can't
971 // guarantee they'll have already been checked
972 ("rustc_deprecated", Whitelisted, Ungated),
973 ("must_use", Whitelisted, Ungated),
974 ("stable", Whitelisted, Ungated),
975 ("unstable", Whitelisted, Ungated),
976 ("deprecated", Normal, Ungated),
978 ("rustc_paren_sugar", Normal, Gated(Stability::Unstable,
980 "unboxed_closures are still evolving",
981 cfg_fn!(unboxed_closures))),
983 ("windows_subsystem", Whitelisted, Ungated),
985 ("proc_macro_attribute", Normal, Gated(Stability::Unstable,
987 "attribute proc macros are currently unstable",
988 cfg_fn!(proc_macro))),
990 ("proc_macro", Normal, Gated(Stability::Unstable,
992 "function-like proc macros are currently unstable",
993 cfg_fn!(proc_macro))),
995 ("rustc_derive_registrar", Normal, Gated(Stability::Unstable,
996 "rustc_derive_registrar",
997 "used internally by rustc",
998 cfg_fn!(rustc_attrs))),
1000 ("allow_fail", Normal, Gated(Stability::Unstable,
1002 "allow_fail attribute is currently unstable",
1003 cfg_fn!(allow_fail))),
1005 ("rustc_std_internal_symbol", Whitelisted, Gated(Stability::Unstable,
1007 "this is an internal attribute that will \
1009 cfg_fn!(rustc_attrs))),
1011 // whitelists "identity-like" conversion methods to suggest on type mismatch
1012 ("rustc_conversion_suggestion", Whitelisted, Gated(Stability::Unstable,
1014 "this is an internal attribute that will \
1016 cfg_fn!(rustc_attrs))),
1018 ("rustc_args_required_const", Whitelisted, Gated(Stability::Unstable,
1020 "never will be stable",
1021 cfg_fn!(rustc_attrs))),
1023 ("wasm_custom_section", Whitelisted, Gated(Stability::Unstable,
1024 "wasm_custom_section",
1025 "attribute is currently unstable",
1026 cfg_fn!(wasm_custom_section))),
1028 // Crate level attributes
1029 ("crate_name", CrateLevel, Ungated),
1030 ("crate_type", CrateLevel, Ungated),
1031 ("crate_id", CrateLevel, Ungated),
1032 ("feature", CrateLevel, Ungated),
1033 ("no_start", CrateLevel, Ungated),
1034 ("no_main", CrateLevel, Ungated),
1035 ("no_builtins", CrateLevel, Ungated),
1036 ("recursion_limit", CrateLevel, Ungated),
1037 ("type_length_limit", CrateLevel, Ungated),
1040 // cfg(...)'s that are feature gated
1041 const GATED_CFGS: &[(&str, &str, fn(&Features) -> bool)] = &[
1042 // (name in cfg, feature, function to check if the feature is enabled)
1043 ("target_feature", "cfg_target_feature", cfg_fn!(cfg_target_feature)),
1044 ("target_vendor", "cfg_target_vendor", cfg_fn!(cfg_target_vendor)),
1045 ("target_thread_local", "cfg_target_thread_local", cfg_fn!(cfg_target_thread_local)),
1046 ("target_has_atomic", "cfg_target_has_atomic", cfg_fn!(cfg_target_has_atomic)),
1049 #[derive(Debug, Eq, PartialEq)]
1050 pub struct GatedCfg {
1056 pub fn gate(cfg: &ast::MetaItem) -> Option<GatedCfg> {
1057 let name = cfg.name().as_str();
1059 .position(|info| info.0 == name)
1068 pub fn check_and_emit(&self, sess: &ParseSess, features: &Features) {
1069 let (cfg, feature, has_feature) = GATED_CFGS[self.index];
1070 if !has_feature(features) && !self.span.allows_unstable() {
1071 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
1072 emit_feature_err(sess, feature, self.span, GateIssue::Language, &explain);
1077 struct Context<'a> {
1078 features: &'a Features,
1079 parse_sess: &'a ParseSess,
1080 plugin_attributes: &'a [(String, AttributeType)],
1083 macro_rules! gate_feature_fn {
1084 ($cx: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr, $level: expr) => {{
1085 let (cx, has_feature, span,
1086 name, explain, level) = ($cx, $has_feature, $span, $name, $explain, $level);
1087 let has_feature: bool = has_feature(&$cx.features);
1088 debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
1089 if !has_feature && !span.allows_unstable() {
1090 leveled_feature_err(cx.parse_sess, name, span, GateIssue::Language, explain, level)
1096 macro_rules! gate_feature {
1097 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {
1098 gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
1099 stringify!($feature), $explain, GateStrength::Hard)
1101 ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {
1102 gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
1103 stringify!($feature), $explain, $level)
1107 impl<'a> Context<'a> {
1108 fn check_attribute(&self, attr: &ast::Attribute, is_macro: bool) {
1109 debug!("check_attribute(attr = {:?})", attr);
1110 let name = unwrap_or!(attr.name(), return).as_str();
1111 for &(n, ty, ref gateage) in BUILTIN_ATTRIBUTES {
1113 if let Gated(_, name, desc, ref has_feature) = *gateage {
1114 gate_feature_fn!(self, has_feature, attr.span, name, desc, GateStrength::Hard);
1115 } else if name == "doc" {
1116 if let Some(content) = attr.meta_item_list() {
1117 if content.iter().any(|c| c.check_name("include")) {
1118 gate_feature!(self, external_doc, attr.span,
1119 "#[doc(include = \"...\")] is experimental"
1124 debug!("check_attribute: {:?} is builtin, {:?}, {:?}", attr.path, ty, gateage);
1128 for &(ref n, ref ty) in self.plugin_attributes {
1129 if attr.path == &**n {
1130 // Plugins can't gate attributes, so we don't check for it
1131 // unlike the code above; we only use this loop to
1132 // short-circuit to avoid the checks below
1133 debug!("check_attribute: {:?} is registered by a plugin, {:?}", attr.path, ty);
1137 if name.starts_with("rustc_") {
1138 gate_feature!(self, rustc_attrs, attr.span,
1139 "unless otherwise specified, attributes \
1140 with the prefix `rustc_` \
1141 are reserved for internal compiler diagnostics");
1142 } else if name.starts_with("derive_") {
1143 gate_feature!(self, custom_derive, attr.span, EXPLAIN_DERIVE_UNDERSCORE);
1144 } else if !attr::is_known(attr) {
1145 // Only run the custom attribute lint during regular
1146 // feature gate checking. Macro gating runs
1147 // before the plugin attributes are registered
1148 // so we skip this then
1150 gate_feature!(self, custom_attribute, attr.span,
1151 &format!("The attribute `{}` is currently \
1152 unknown to the compiler and \
1154 added to it in the future",
1161 pub fn check_attribute(attr: &ast::Attribute, parse_sess: &ParseSess, features: &Features) {
1162 let cx = Context { features: features, parse_sess: parse_sess, plugin_attributes: &[] };
1163 cx.check_attribute(attr, true);
1166 pub fn find_lang_feature_accepted_version(feature: &str) -> Option<&'static str> {
1167 ACCEPTED_FEATURES.iter().find(|t| t.0 == feature).map(|t| t.1)
1170 fn find_lang_feature_issue(feature: &str) -> Option<u32> {
1171 if let Some(info) = ACTIVE_FEATURES.iter().find(|t| t.0 == feature) {
1173 // FIXME (#28244): enforce that active features have issue numbers
1174 // assert!(issue.is_some())
1177 // search in Accepted, Removed, or Stable Removed features
1178 let found = ACCEPTED_FEATURES.iter().chain(REMOVED_FEATURES).chain(STABLE_REMOVED_FEATURES)
1179 .find(|t| t.0 == feature);
1181 Some(&(_, _, issue)) => issue,
1182 None => panic!("Feature `{}` is not declared anywhere", feature),
1187 pub enum GateIssue {
1189 Library(Option<u32>)
1192 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
1193 pub enum GateStrength {
1194 /// A hard error. (Most feature gates should use this.)
1196 /// Only a warning. (Use this only as backwards-compatibility demands.)
1200 pub fn emit_feature_err(sess: &ParseSess, feature: &str, span: Span, issue: GateIssue,
1202 feature_err(sess, feature, span, issue, explain).emit();
1205 pub fn feature_err<'a>(sess: &'a ParseSess, feature: &str, span: Span, issue: GateIssue,
1206 explain: &str) -> DiagnosticBuilder<'a> {
1207 leveled_feature_err(sess, feature, span, issue, explain, GateStrength::Hard)
1210 fn leveled_feature_err<'a>(sess: &'a ParseSess, feature: &str, span: Span, issue: GateIssue,
1211 explain: &str, level: GateStrength) -> DiagnosticBuilder<'a> {
1212 let diag = &sess.span_diagnostic;
1214 let issue = match issue {
1215 GateIssue::Language => find_lang_feature_issue(feature),
1216 GateIssue::Library(lib) => lib,
1219 let explanation = if let Some(n) = issue {
1220 format!("{} (see issue #{})", explain, n)
1225 let mut err = match level {
1226 GateStrength::Hard => {
1227 diag.struct_span_err_with_code(span, &explanation, stringify_error_code!(E0658))
1229 GateStrength::Soft => diag.struct_span_warn(span, &explanation),
1232 // #23973: do not suggest `#![feature(...)]` if we are in beta/stable
1233 if sess.unstable_features.is_nightly_build() {
1234 err.help(&format!("add #![feature({})] to the \
1235 crate attributes to enable",
1239 // If we're on stable and only emitting a "soft" warning, add a note to
1240 // clarify that the feature isn't "on" (rather than being on but
1242 if !sess.unstable_features.is_nightly_build() && level == GateStrength::Soft {
1243 err.help("a nightly build of the compiler is required to enable this feature");
1250 const EXPLAIN_BOX_SYNTAX: &'static str =
1251 "box expression syntax is experimental; you can call `Box::new` instead.";
1253 pub const EXPLAIN_STMT_ATTR_SYNTAX: &'static str =
1254 "attributes on expressions are experimental.";
1256 pub const EXPLAIN_ASM: &'static str =
1257 "inline assembly is not stable enough for use and is subject to change";
1259 pub const EXPLAIN_GLOBAL_ASM: &'static str =
1260 "`global_asm!` is not stable enough for use and is subject to change";
1262 pub const EXPLAIN_LOG_SYNTAX: &'static str =
1263 "`log_syntax!` is not stable enough for use and is subject to change";
1265 pub const EXPLAIN_CONCAT_IDENTS: &'static str =
1266 "`concat_idents` is not stable enough for use and is subject to change";
1268 pub const EXPLAIN_TRACE_MACROS: &'static str =
1269 "`trace_macros` is not stable enough for use and is subject to change";
1270 pub const EXPLAIN_ALLOW_INTERNAL_UNSTABLE: &'static str =
1271 "allow_internal_unstable side-steps feature gating and stability checks";
1272 pub const EXPLAIN_ALLOW_INTERNAL_UNSAFE: &'static str =
1273 "allow_internal_unsafe side-steps the unsafe_code lint";
1275 pub const EXPLAIN_CUSTOM_DERIVE: &'static str =
1276 "`#[derive]` for custom traits is deprecated and will be removed in the future.";
1278 pub const EXPLAIN_DEPR_CUSTOM_DERIVE: &'static str =
1279 "`#[derive]` for custom traits is deprecated and will be removed in the future. \
1280 Prefer using procedural macro custom derive.";
1282 pub const EXPLAIN_DERIVE_UNDERSCORE: &'static str =
1283 "attributes of the form `#[derive_*]` are reserved for the compiler";
1285 pub const EXPLAIN_VIS_MATCHER: &'static str =
1286 ":vis fragment specifier is experimental and subject to change";
1288 pub const EXPLAIN_LIFETIME_MATCHER: &'static str =
1289 ":lifetime fragment specifier is experimental and subject to change";
1291 pub const EXPLAIN_UNSIZED_TUPLE_COERCION: &'static str =
1292 "Unsized tuple coercion is not stable enough for use and is subject to change";
1294 pub const EXPLAIN_MACRO_AT_MOST_ONCE_REP: &'static str =
1295 "Using the `?` macro Kleene operator for \"at most one\" repetition is unstable";
1297 pub const EXPLAIN_MACROS_IN_EXTERN: &'static str =
1298 "Macro invocations in `extern {}` blocks are experimental.";
1300 // mention proc-macros when enabled
1301 pub const EXPLAIN_PROC_MACROS_IN_EXTERN: &'static str =
1302 "Macro and proc-macro invocations in `extern {}` blocks are experimental.";
1304 struct PostExpansionVisitor<'a> {
1305 context: &'a Context<'a>,
1308 macro_rules! gate_feature_post {
1309 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {{
1310 let (cx, span) = ($cx, $span);
1311 if !span.allows_unstable() {
1312 gate_feature!(cx.context, $feature, span, $explain)
1315 ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {{
1316 let (cx, span) = ($cx, $span);
1317 if !span.allows_unstable() {
1318 gate_feature!(cx.context, $feature, span, $explain, $level)
1323 impl<'a> PostExpansionVisitor<'a> {
1324 fn check_abi(&self, abi: Abi, span: Span) {
1326 Abi::RustIntrinsic => {
1327 gate_feature_post!(&self, intrinsics, span,
1328 "intrinsics are subject to change");
1330 Abi::PlatformIntrinsic => {
1331 gate_feature_post!(&self, platform_intrinsics, span,
1332 "platform intrinsics are experimental and possibly buggy");
1334 Abi::Vectorcall => {
1335 gate_feature_post!(&self, abi_vectorcall, span,
1336 "vectorcall is experimental and subject to change");
1339 gate_feature_post!(&self, abi_thiscall, span,
1340 "thiscall is experimental and subject to change");
1343 gate_feature_post!(&self, unboxed_closures, span,
1344 "rust-call ABI is subject to change");
1347 gate_feature_post!(&self, abi_ptx, span,
1348 "PTX ABIs are experimental and subject to change");
1350 Abi::Unadjusted => {
1351 gate_feature_post!(&self, abi_unadjusted, span,
1352 "unadjusted ABI is an implementation detail and perma-unstable");
1354 Abi::Msp430Interrupt => {
1355 gate_feature_post!(&self, abi_msp430_interrupt, span,
1356 "msp430-interrupt ABI is experimental and subject to change");
1358 Abi::X86Interrupt => {
1359 gate_feature_post!(&self, abi_x86_interrupt, span,
1360 "x86-interrupt ABI is experimental and subject to change");
1376 fn contains_novel_literal(item: &ast::MetaItem) -> bool {
1377 use ast::MetaItemKind::*;
1378 use ast::NestedMetaItemKind::*;
1382 NameValue(ref lit) => !lit.node.is_str(),
1383 List(ref list) => list.iter().any(|li| {
1385 MetaItem(ref mi) => contains_novel_literal(mi),
1392 impl<'a> PostExpansionVisitor<'a> {
1393 fn whole_crate_feature_gates(&mut self, _krate: &ast::Crate) {
1394 for &(ident, span) in &*self.context.parse_sess.non_modrs_mods.borrow() {
1395 if !span.allows_unstable() {
1396 let cx = &self.context;
1397 let level = GateStrength::Hard;
1398 let has_feature = cx.features.non_modrs_mods;
1399 let name = "non_modrs_mods";
1400 debug!("gate_feature(feature = {:?}, span = {:?}); has? {}",
1401 name, span, has_feature);
1403 if !has_feature && !span.allows_unstable() {
1404 leveled_feature_err(
1405 cx.parse_sess, name, span, GateIssue::Language,
1406 "mod statements in non-mod.rs files are unstable", level
1408 .help(&format!("on stable builds, rename this file to {}{}mod.rs",
1409 ident, path::MAIN_SEPARATOR))
1417 impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
1418 fn visit_attribute(&mut self, attr: &ast::Attribute) {
1419 if !attr.span.allows_unstable() {
1420 // check for gated attributes
1421 self.context.check_attribute(attr, false);
1424 if attr.check_name("doc") {
1425 if let Some(content) = attr.meta_item_list() {
1426 if content.len() == 1 && content[0].check_name("cfg") {
1427 gate_feature_post!(&self, doc_cfg, attr.span,
1428 "#[doc(cfg(...))] is experimental"
1430 } else if content.iter().any(|c| c.check_name("masked")) {
1431 gate_feature_post!(&self, doc_masked, attr.span,
1432 "#[doc(masked)] is experimental"
1434 } else if content.iter().any(|c| c.check_name("spotlight")) {
1435 gate_feature_post!(&self, doc_spotlight, attr.span,
1436 "#[doc(spotlight)] is experimental"
1442 // allow attr_literals in #[repr(align(x))]
1443 let mut is_repr_align = false;
1444 if attr.path == "repr" {
1445 if let Some(content) = attr.meta_item_list() {
1446 is_repr_align = content.iter().any(|c| c.check_name("align"));
1450 if self.context.features.proc_macro && attr::is_known(attr) {
1455 let meta = panictry!(attr.parse_meta(self.context.parse_sess));
1456 if contains_novel_literal(&meta) {
1457 gate_feature_post!(&self, attr_literals, attr.span,
1458 "non-string literals in attributes, or string \
1459 literals in top-level positions, are experimental");
1464 fn visit_name(&mut self, sp: Span, name: ast::Name) {
1465 if !name.as_str().is_ascii() {
1466 gate_feature_post!(&self,
1468 self.context.parse_sess.codemap().def_span(sp),
1469 "non-ascii idents are not fully supported.");
1473 fn visit_use_tree(&mut self, use_tree: &'a ast::UseTree, id: NodeId, _nested: bool) {
1474 if let ast::UseTreeKind::Simple(Some(ident)) = use_tree.kind {
1475 if ident.name == "_" {
1476 gate_feature_post!(&self, underscore_imports, use_tree.span,
1477 "renaming imports with `_` is unstable");
1481 visit::walk_use_tree(self, use_tree, id);
1484 fn visit_item(&mut self, i: &'a ast::Item) {
1486 ast::ItemKind::ExternCrate(_) => {
1487 if i.ident.name == "_" {
1488 gate_feature_post!(&self, underscore_imports, i.span,
1489 "renaming extern crates with `_` is unstable");
1491 if let Some(attr) = attr::find_by_name(&i.attrs[..], "macro_reexport") {
1492 gate_feature_post!(&self, macro_reexport, attr.span,
1493 "macros re-exports are experimental \
1494 and possibly buggy");
1498 ast::ItemKind::ForeignMod(ref foreign_module) => {
1499 self.check_abi(foreign_module.abi, i.span);
1502 ast::ItemKind::Fn(..) => {
1503 if attr::contains_name(&i.attrs[..], "plugin_registrar") {
1504 gate_feature_post!(&self, plugin_registrar, i.span,
1505 "compiler plugins are experimental and possibly buggy");
1507 if attr::contains_name(&i.attrs[..], "start") {
1508 gate_feature_post!(&self, start, i.span,
1509 "a #[start] function is an experimental \
1510 feature whose signature may change \
1513 if attr::contains_name(&i.attrs[..], "main") {
1514 gate_feature_post!(&self, main, i.span,
1515 "declaration of a nonstandard #[main] \
1516 function may change over time, for now \
1517 a top-level `fn main()` is required");
1519 if let Some(attr) = attr::find_by_name(&i.attrs[..], "must_use") {
1520 gate_feature_post!(&self, fn_must_use, attr.span,
1521 "`#[must_use]` on functions is experimental",
1522 GateStrength::Soft);
1526 ast::ItemKind::Struct(..) => {
1527 if let Some(attr) = attr::find_by_name(&i.attrs[..], "repr") {
1528 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
1529 if item.check_name("simd") {
1530 gate_feature_post!(&self, repr_simd, attr.span,
1531 "SIMD types are experimental and possibly buggy");
1533 if item.check_name("transparent") {
1534 gate_feature_post!(&self, repr_transparent, attr.span,
1535 "the `#[repr(transparent)]` attribute \
1542 ast::ItemKind::TraitAlias(..) => {
1543 gate_feature_post!(&self, trait_alias,
1545 "trait aliases are not yet fully implemented");
1548 ast::ItemKind::Impl(_, polarity, defaultness, _, _, _, ref impl_items) => {
1549 if polarity == ast::ImplPolarity::Negative {
1550 gate_feature_post!(&self, optin_builtin_traits,
1552 "negative trait bounds are not yet fully implemented; \
1553 use marker types for now");
1556 if let ast::Defaultness::Default = defaultness {
1557 gate_feature_post!(&self, specialization,
1559 "specialization is unstable");
1562 for impl_item in impl_items {
1563 if let ast::ImplItemKind::Method(..) = impl_item.node {
1564 if let Some(attr) = attr::find_by_name(&impl_item.attrs[..], "must_use") {
1565 gate_feature_post!(&self, fn_must_use, attr.span,
1566 "`#[must_use]` on methods is experimental",
1567 GateStrength::Soft);
1573 ast::ItemKind::Trait(ast::IsAuto::Yes, ..) => {
1574 gate_feature_post!(&self, optin_builtin_traits,
1576 "auto traits are experimental and possibly buggy");
1579 ast::ItemKind::MacroDef(ast::MacroDef { legacy: false, .. }) => {
1580 let msg = "`macro` is experimental";
1581 gate_feature_post!(&self, decl_macro, i.span, msg);
1587 visit::walk_item(self, i);
1590 fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
1592 ast::ForeignItemKind::Fn(..) |
1593 ast::ForeignItemKind::Static(..) => {
1594 let link_name = attr::first_attr_value_str_by_name(&i.attrs, "link_name");
1595 let links_to_llvm = match link_name {
1596 Some(val) => val.as_str().starts_with("llvm."),
1600 gate_feature_post!(&self, link_llvm_intrinsics, i.span,
1601 "linking to LLVM intrinsics is experimental");
1604 ast::ForeignItemKind::Ty => {
1605 gate_feature_post!(&self, extern_types, i.span,
1606 "extern types are experimental");
1608 ast::ForeignItemKind::Macro(..) => {}
1611 visit::walk_foreign_item(self, i)
1614 fn visit_ty(&mut self, ty: &'a ast::Ty) {
1616 ast::TyKind::BareFn(ref bare_fn_ty) => {
1617 self.check_abi(bare_fn_ty.abi, ty.span);
1619 ast::TyKind::TraitObject(_, ast::TraitObjectSyntax::Dyn) => {
1620 gate_feature_post!(&self, dyn_trait, ty.span,
1621 "`dyn Trait` syntax is unstable");
1625 visit::walk_ty(self, ty)
1628 fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FunctionRetTy) {
1629 if let ast::FunctionRetTy::Ty(ref output_ty) = *ret_ty {
1630 if output_ty.node != ast::TyKind::Never {
1631 self.visit_ty(output_ty)
1636 fn visit_expr(&mut self, e: &'a ast::Expr) {
1638 ast::ExprKind::Box(_) => {
1639 gate_feature_post!(&self, box_syntax, e.span, EXPLAIN_BOX_SYNTAX);
1641 ast::ExprKind::Type(..) => {
1642 gate_feature_post!(&self, type_ascription, e.span,
1643 "type ascription is experimental");
1645 ast::ExprKind::Yield(..) => {
1646 gate_feature_post!(&self, generators,
1648 "yield syntax is experimental");
1650 ast::ExprKind::Catch(_) => {
1651 gate_feature_post!(&self, catch_expr, e.span, "`catch` expression is experimental");
1653 ast::ExprKind::IfLet(ref pats, ..) | ast::ExprKind::WhileLet(ref pats, ..) => {
1655 gate_feature_post!(&self, if_while_or_patterns, e.span,
1656 "multiple patterns in `if let` and `while let` are unstable");
1661 visit::walk_expr(self, e);
1664 fn visit_arm(&mut self, arm: &'a ast::Arm) {
1665 visit::walk_arm(self, arm)
1668 fn visit_pat(&mut self, pattern: &'a ast::Pat) {
1669 match pattern.node {
1670 PatKind::Slice(_, Some(ref subslice), _) => {
1671 gate_feature_post!(&self, slice_patterns,
1673 "syntax for subslices in slice patterns is not yet stabilized");
1675 PatKind::Box(..) => {
1676 gate_feature_post!(&self, box_patterns,
1678 "box pattern syntax is experimental");
1680 PatKind::Range(_, _, RangeEnd::Excluded) => {
1681 gate_feature_post!(&self, exclusive_range_pattern, pattern.span,
1682 "exclusive range pattern syntax is experimental");
1684 PatKind::Paren(..) => {
1685 gate_feature_post!(&self, pattern_parentheses, pattern.span,
1686 "parentheses in patterns are unstable");
1690 visit::walk_pat(self, pattern)
1693 fn visit_fn(&mut self,
1694 fn_kind: FnKind<'a>,
1695 fn_decl: &'a ast::FnDecl,
1698 // check for const fn declarations
1699 if let FnKind::ItemFn(_, _, Spanned { node: ast::Constness::Const, .. }, _, _, _) =
1701 gate_feature_post!(&self, const_fn, span, "const fn is unstable");
1703 // stability of const fn methods are covered in
1704 // visit_trait_item and visit_impl_item below; this is
1705 // because default methods don't pass through this
1709 FnKind::ItemFn(_, _, _, abi, _, _) |
1710 FnKind::Method(_, &ast::MethodSig { abi, .. }, _, _) => {
1711 self.check_abi(abi, span);
1715 visit::walk_fn(self, fn_kind, fn_decl, span);
1718 fn visit_trait_item(&mut self, ti: &'a ast::TraitItem) {
1720 ast::TraitItemKind::Method(ref sig, ref block) => {
1721 if block.is_none() {
1722 self.check_abi(sig.abi, ti.span);
1724 if sig.constness.node == ast::Constness::Const {
1725 gate_feature_post!(&self, const_fn, ti.span, "const fn is unstable");
1728 ast::TraitItemKind::Type(_, ref default) => {
1729 // We use two if statements instead of something like match guards so that both
1730 // of these errors can be emitted if both cases apply.
1731 if default.is_some() {
1732 gate_feature_post!(&self, associated_type_defaults, ti.span,
1733 "associated type defaults are unstable");
1735 if ti.generics.is_parameterized() {
1736 gate_feature_post!(&self, generic_associated_types, ti.span,
1737 "generic associated types are unstable");
1742 visit::walk_trait_item(self, ti);
1745 fn visit_impl_item(&mut self, ii: &'a ast::ImplItem) {
1746 if ii.defaultness == ast::Defaultness::Default {
1747 gate_feature_post!(&self, specialization,
1749 "specialization is unstable");
1753 ast::ImplItemKind::Method(ref sig, _) => {
1754 if sig.constness.node == ast::Constness::Const {
1755 gate_feature_post!(&self, const_fn, ii.span, "const fn is unstable");
1758 ast::ImplItemKind::Type(_) if ii.generics.is_parameterized() => {
1759 gate_feature_post!(&self, generic_associated_types, ii.span,
1760 "generic associated types are unstable");
1764 visit::walk_impl_item(self, ii);
1767 fn visit_path(&mut self, path: &'a ast::Path, _id: NodeId) {
1768 for segment in &path.segments {
1769 if segment.identifier.name == keywords::Crate.name() {
1770 gate_feature_post!(&self, crate_in_paths, segment.span,
1771 "`crate` in paths is experimental");
1772 } else if segment.identifier.name == keywords::Extern.name() {
1773 gate_feature_post!(&self, extern_in_paths, segment.span,
1774 "`extern` in paths is experimental");
1778 visit::walk_path(self, path);
1781 fn visit_vis(&mut self, vis: &'a ast::Visibility) {
1782 if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.node {
1783 gate_feature_post!(&self, crate_visibility_modifier, vis.span,
1784 "`crate` visibility modifier is experimental");
1786 visit::walk_vis(self, vis);
1790 pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
1791 crate_edition: Edition) -> Features {
1792 fn feature_removed(span_handler: &Handler, span: Span) {
1793 span_err!(span_handler, span, E0557, "feature has been removed");
1796 let mut features = Features::new();
1798 let mut feature_checker = FeatureChecker::default();
1800 for attr in krate_attrs {
1801 if !attr.check_name("feature") {
1805 match attr.meta_item_list() {
1807 span_err!(span_handler, attr.span, E0555,
1808 "malformed feature attribute, expected #![feature(...)]");
1813 let name = if let Some(word) = mi.word() {
1816 span_err!(span_handler, mi.span, E0556,
1817 "malformed feature, expected just one word");
1821 if let Some(&(_, _, _, _, set)) = ACTIVE_FEATURES.iter()
1822 .find(|& &(n, ..)| name == n) {
1823 set(&mut features, mi.span);
1824 feature_checker.collect(&features, mi.span);
1826 else if let Some(&(_, _, _)) = REMOVED_FEATURES.iter()
1827 .find(|& &(n, _, _)| name == n)
1828 .or_else(|| STABLE_REMOVED_FEATURES.iter()
1829 .find(|& &(n, _, _)| name == n)) {
1830 feature_removed(span_handler, mi.span);
1832 else if let Some(&(_, _, _)) = ACCEPTED_FEATURES.iter()
1833 .find(|& &(n, _, _)| name == n) {
1834 features.declared_stable_lang_features.push((name, mi.span));
1835 } else if let Some(&edition) = ALL_EDITIONS.iter()
1836 .find(|e| name == e.feature_name()) {
1837 if edition <= crate_edition {
1838 feature_removed(span_handler, mi.span);
1840 for &(.., f_edition, set) in ACTIVE_FEATURES.iter() {
1841 if let Some(f_edition) = f_edition {
1842 if edition >= f_edition {
1843 // FIXME(Manishearth) there is currently no way to set
1844 // lib features by edition
1845 set(&mut features, DUMMY_SP);
1851 features.declared_lib_features.push((name, mi.span));
1858 feature_checker.check(span_handler);
1863 /// A collector for mutually exclusive and interdependent features and their flag spans.
1865 struct FeatureChecker {
1866 proc_macro: Option<Span>,
1867 custom_attribute: Option<Span>,
1870 impl FeatureChecker {
1871 // If this method turns out to be a hotspot due to branching,
1872 // the branching can be eliminated by modifying `set!()` to set these spans
1873 // only for the features that need to be checked for mutual exclusion.
1874 fn collect(&mut self, features: &Features, span: Span) {
1875 if features.proc_macro {
1876 // If self.proc_macro is None, set to Some(span)
1877 self.proc_macro = self.proc_macro.or(Some(span));
1880 if features.custom_attribute {
1881 self.custom_attribute = self.custom_attribute.or(Some(span));
1885 fn check(self, handler: &Handler) {
1886 if let (Some(pm_span), Some(ca_span)) = (self.proc_macro, self.custom_attribute) {
1887 handler.struct_span_err(pm_span, "Cannot use `#![feature(proc_macro)]` and \
1888 `#![feature(custom_attribute)] at the same time")
1889 .span_note(ca_span, "`#![feature(custom_attribute)]` declared here")
1897 pub fn check_crate(krate: &ast::Crate,
1899 features: &Features,
1900 plugin_attributes: &[(String, AttributeType)],
1901 unstable: UnstableFeatures) {
1902 maybe_stage_features(&sess.span_diagnostic, krate, unstable);
1909 if !features.raw_identifiers {
1910 for &span in sess.raw_identifier_spans.borrow().iter() {
1911 if !span.allows_unstable() {
1912 gate_feature!(&ctx, raw_identifiers, span,
1913 "raw identifiers are experimental and subject to change"
1919 let visitor = &mut PostExpansionVisitor { context: &ctx };
1920 visitor.whole_crate_feature_gates(krate);
1921 visit::walk_crate(visitor, krate);
1924 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
1925 pub enum UnstableFeatures {
1926 /// Hard errors for unstable features are active, as on
1927 /// beta/stable channels.
1929 /// Allow features to be activated, as on nightly.
1931 /// Errors are bypassed for bootstrapping. This is required any time
1932 /// during the build that feature-related lints are set to warn or above
1933 /// because the build turns on warnings-as-errors and uses lots of unstable
1934 /// features. As a result, this is always required for building Rust itself.
1938 impl UnstableFeatures {
1939 pub fn from_environment() -> UnstableFeatures {
1940 // Whether this is a feature-staged build, i.e. on the beta or stable channel
1941 let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
1942 // Whether we should enable unstable features for bootstrapping
1943 let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok();
1944 match (disable_unstable_features, bootstrap) {
1945 (_, true) => UnstableFeatures::Cheat,
1946 (true, _) => UnstableFeatures::Disallow,
1947 (false, _) => UnstableFeatures::Allow
1951 pub fn is_nightly_build(&self) -> bool {
1953 UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
1959 fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate,
1960 unstable: UnstableFeatures) {
1961 let allow_features = match unstable {
1962 UnstableFeatures::Allow => true,
1963 UnstableFeatures::Disallow => false,
1964 UnstableFeatures::Cheat => true
1966 if !allow_features {
1967 for attr in &krate.attrs {
1968 if attr.check_name("feature") {
1969 let release_channel = option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)");
1970 span_err!(span_handler, attr.span, E0554,
1971 "#![feature] may not be used on the {} release channel",