]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/feature_gate.rs
Feature gate trivial bounds
[rust.git] / src / libsyntax / feature_gate.rs
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.
4 //
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.
10
11 //! Feature gating
12 //!
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
16 //! enabled.
17 //!
18 //! Features are enabled in programs via the crate-level attributes of
19 //! `#![feature(...)]` with a comma-separated list of features.
20 //!
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
23 //! becomes stable.
24
25 use self::AttributeType::*;
26 use self::AttributeGate::*;
27
28 use rustc_target::spec::abi::Abi;
29 use ast::{self, NodeId, PatKind, RangeEnd};
30 use attr;
31 use edition::{ALL_EDITIONS, Edition};
32 use codemap::Spanned;
33 use syntax_pos::{Span, DUMMY_SP};
34 use errors::{DiagnosticBuilder, Handler, FatalError};
35 use visit::{self, FnKind, Visitor};
36 use parse::ParseSess;
37 use symbol::{keywords, Symbol};
38
39 use std::{env, path};
40
41 macro_rules! set {
42     (proc_macro) => {{
43         fn f(features: &mut Features, span: Span) {
44             features.declared_lib_features.push((Symbol::intern("proc_macro"), span));
45             features.proc_macro = true;
46         }
47         f as fn(&mut Features, Span)
48     }};
49     ($field: ident) => {{
50         fn f(features: &mut Features, _: Span) {
51             features.$field = true;
52         }
53         f as fn(&mut Features, Span)
54     }}
55 }
56
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))),+];
65
66         /// A set of features to be used by later passes.
67         #[derive(Clone)]
68         pub struct Features {
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),+
74         }
75
76         impl Features {
77             pub fn new() -> Features {
78                 Features {
79                     declared_stable_lang_features: Vec::new(),
80                     declared_lib_features: Vec::new(),
81                     $($feature: false),+
82                 }
83             }
84
85             pub fn walk_feature_fields<F>(&self, mut f: F)
86                 where F: FnMut(&str, bool)
87             {
88                 $(f(stringify!($feature), self.$feature);)+
89             }
90         }
91     };
92
93     ($((removed, $feature: ident, $ver: expr, $issue: expr, None, $reason: expr),)+) => {
94         /// Represents unstable features which have since been removed (it was once Active)
95         const REMOVED_FEATURES: &[(&str, &str, Option<u32>, Option<&str>)] = &[
96             $((stringify!($feature), $ver, $issue, $reason)),+
97         ];
98     };
99
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: &[(&str, &str, Option<u32>, Option<&str>)] = &[
103             $((stringify!($feature), $ver, $issue, None)),+
104         ];
105     };
106
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: &[(&str, &str, Option<u32>, Option<&str>)] = &[
110             $((stringify!($feature), $ver, $issue, None)),+
111         ];
112     }
113 }
114
115 // If you change this, please modify src/doc/unstable-book as well.
116 //
117 // Don't ever remove anything from this list; set them to 'Removed'.
118 //
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
121 // stable (active).
122 //
123 // NB: tools/tidy/src/features.rs parses this information directly out of the
124 // source, so take care when modifying it.
125
126 declare_features! (
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),
135
136     // rustc internal, for now:
137     (active, intrinsics, "1.0.0", None, None),
138     (active, lang_items, "1.0.0", None, None),
139
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),
143
144
145     // rustc internal
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),
150
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),
161
162     // OIBIT specific features
163     (active, optin_builtin_traits, "1.0.0", Some(13231), None),
164
165     // Allows use of #[staged_api]
166     // rustc internal
167     (active, staged_api, "1.0.0", None, None),
168
169     // Allows using #![no_core]
170     (active, no_core, "1.3.0", Some(29639), None),
171
172     // Allows using `box` in patterns; RFC 469
173     (active, box_patterns, "1.0.0", Some(29641), None),
174
175     // Allows using the unsafe_destructor_blind_to_params attribute;
176     // RFC 1238
177     (active, dropck_parametricity, "1.3.0", Some(28498), None),
178
179     // Allows using the may_dangle attribute; RFC 1327
180     (active, dropck_eyepatch, "1.10.0", Some(34761), None),
181
182     // Allows the use of custom attributes; RFC 572
183     (active, custom_attribute, "1.0.0", Some(29642), None),
184
185     // Allows the use of #[derive(Anything)] as sugar for
186     // #[derive_Anything].
187     (active, custom_derive, "1.0.0", Some(29644), None),
188
189     // Allows the use of rustc_* attributes; RFC 572
190     (active, rustc_attrs, "1.0.0", Some(29642), None),
191
192     // Allows the use of non lexical lifetimes; RFC 2094
193     (active, nll, "1.0.0", Some(43234), None),
194
195     // Allows the use of #[allow_internal_unstable]. This is an
196     // attribute on macro_rules! and can't use the attribute handling
197     // below (it has to be checked before expansion possibly makes
198     // macros disappear).
199     //
200     // rustc internal
201     (active, allow_internal_unstable, "1.0.0", None, None),
202
203     // Allows the use of #[allow_internal_unsafe]. This is an
204     // attribute on macro_rules! and can't use the attribute handling
205     // below (it has to be checked before expansion possibly makes
206     // macros disappear).
207     //
208     // rustc internal
209     (active, allow_internal_unsafe, "1.0.0", None, None),
210
211     // #23121. Array patterns have some hazards yet.
212     (active, slice_patterns, "1.0.0", Some(23121), None),
213
214     // Allows the definition of `const fn` functions.
215     (active, const_fn, "1.2.0", Some(24111), None),
216
217     // Allows using #[prelude_import] on glob `use` items.
218     //
219     // rustc internal
220     (active, prelude_import, "1.2.0", None, None),
221
222     // Allows default type parameters to influence type inference.
223     (active, default_type_parameter_fallback, "1.3.0", Some(27336), None),
224
225     // Allows associated type defaults
226     (active, associated_type_defaults, "1.2.0", Some(29661), None),
227
228     // allow `repr(simd)`, and importing the various simd intrinsics
229     (active, repr_simd, "1.4.0", Some(27731), None),
230
231     // allow `extern "platform-intrinsic" { ... }`
232     (active, platform_intrinsics, "1.4.0", Some(27731), None),
233
234     // allow `#[unwind(..)]`
235     // rust runtime internal
236     (active, unwind_attributes, "1.4.0", None, None),
237
238     // allow the use of `#[naked]` on functions.
239     (active, naked_functions, "1.9.0", Some(32408), None),
240
241     // allow `#[no_debug]`
242     (active, no_debug, "1.5.0", Some(29721), None),
243
244     // allow `#[omit_gdb_pretty_printer_section]`
245     // rustc internal.
246     (active, omit_gdb_pretty_printer_section, "1.5.0", None, None),
247
248     // Allows cfg(target_vendor = "...").
249     (active, cfg_target_vendor, "1.5.0", Some(29718), None),
250
251     // Allow attributes on expressions and non-item statements
252     (active, stmt_expr_attributes, "1.6.0", Some(15701), None),
253
254     // allow using type ascription in expressions
255     (active, type_ascription, "1.6.0", Some(23416), None),
256
257     // Allows cfg(target_thread_local)
258     (active, cfg_target_thread_local, "1.7.0", Some(29594), None),
259
260     // rustc internal
261     (active, abi_vectorcall, "1.7.0", None, None),
262
263     // X..Y patterns
264     (active, exclusive_range_pattern, "1.11.0", Some(37854), None),
265
266     // impl specialization (RFC 1210)
267     (active, specialization, "1.7.0", Some(31844), None),
268
269     // Allows cfg(target_has_atomic = "...").
270     (active, cfg_target_has_atomic, "1.9.0", Some(32976), None),
271
272     // The `!` type. Does not imply exhaustive_patterns (below) any more.
273     (active, never_type, "1.13.0", Some(35121), None),
274
275     // Allows exhaustive pattern matching on types that contain uninhabited types.
276     (active, exhaustive_patterns, "1.13.0", None, None),
277
278     // Allows all literals in attribute lists and values of key-value pairs.
279     (active, attr_literals, "1.13.0", Some(34981), None),
280
281     // Allows untagged unions `union U { ... }`
282     (active, untagged_unions, "1.13.0", Some(32836), None),
283
284     // Used to identify the `compiler_builtins` crate
285     // rustc internal
286     (active, compiler_builtins, "1.13.0", None, None),
287
288     // Allows #[link(..., cfg(..))]
289     (active, link_cfg, "1.14.0", Some(37406), None),
290
291     (active, use_extern_macros, "1.15.0", Some(35896), None),
292
293     // `extern "ptx-*" fn()`
294     (active, abi_ptx, "1.15.0", None, None),
295
296     // The `repr(i128)` annotation for enums
297     (active, repr128, "1.16.0", Some(35118), None),
298
299     // The `unadjusted` ABI. Perma unstable.
300     (active, abi_unadjusted, "1.16.0", None, None),
301
302     // Procedural macros 2.0.
303     (active, proc_macro, "1.16.0", Some(38356), Some(Edition::Edition2018)),
304
305     // Declarative macros 2.0 (`macro`).
306     (active, decl_macro, "1.17.0", Some(39412), None),
307
308     // Allows #[link(kind="static-nobundle"...]
309     (active, static_nobundle, "1.16.0", Some(37403), None),
310
311     // `extern "msp430-interrupt" fn()`
312     (active, abi_msp430_interrupt, "1.16.0", Some(38487), None),
313
314     // Used to identify crates that contain sanitizer runtimes
315     // rustc internal
316     (active, sanitizer_runtime, "1.17.0", None, None),
317
318     // Used to identify crates that contain the profiler runtime
319     // rustc internal
320     (active, profiler_runtime, "1.18.0", None, None),
321
322     // `extern "x86-interrupt" fn()`
323     (active, abi_x86_interrupt, "1.17.0", Some(40180), None),
324
325
326     // Allows the `catch {...}` expression
327     (active, catch_expr, "1.17.0", Some(31436), Some(Edition::Edition2018)),
328
329     // Used to preserve symbols (see llvm.used)
330     (active, used, "1.18.0", Some(40289), None),
331
332     // Allows module-level inline assembly by way of global_asm!()
333     (active, global_asm, "1.18.0", Some(35119), None),
334
335     // Allows overlapping impls of marker traits
336     (active, overlapping_marker_traits, "1.18.0", Some(29864), None),
337
338     // Allows use of the :vis macro fragment specifier
339     (active, macro_vis_matcher, "1.18.0", Some(41022), None),
340
341     // rustc internal
342     (active, abi_thiscall, "1.19.0", None, None),
343
344     // Allows a test to fail without failing the whole suite
345     (active, allow_fail, "1.19.0", Some(42219), None),
346
347     // Allows unsized tuple coercion.
348     (active, unsized_tuple_coercion, "1.20.0", Some(42877), None),
349
350     // Generators
351     (active, generators, "1.21.0", None, None),
352
353     // Trait aliases
354     (active, trait_alias, "1.24.0", Some(41517), None),
355
356     // global allocators and their internals
357     (active, global_allocator, "1.20.0", None, None),
358     (active, allocator_internals, "1.20.0", None, None),
359
360     // #[doc(cfg(...))]
361     (active, doc_cfg, "1.21.0", Some(43781), None),
362     // #[doc(masked)]
363     (active, doc_masked, "1.21.0", Some(44027), None),
364     // #[doc(spotlight)]
365     (active, doc_spotlight, "1.22.0", Some(45040), None),
366     // #[doc(include="some-file")]
367     (active, external_doc, "1.22.0", Some(44732), None),
368
369     // Future-proofing enums/structs with #[non_exhaustive] attribute (RFC 2008)
370     (active, non_exhaustive, "1.22.0", Some(44109), None),
371
372     // `crate` as visibility modifier, synonymous to `pub(crate)`
373     (active, crate_visibility_modifier, "1.23.0", Some(45388), Some(Edition::Edition2018)),
374
375     // extern types
376     (active, extern_types, "1.23.0", Some(43467), None),
377
378     // Allow trait methods with arbitrary self types
379     (active, arbitrary_self_types, "1.23.0", Some(44874), None),
380
381     // `crate` in paths
382     (active, crate_in_paths, "1.23.0", Some(45477), Some(Edition::Edition2018)),
383
384     // In-band lifetime bindings (e.g. `fn foo(x: &'a u8) -> &'a u8`)
385     (active, in_band_lifetimes, "1.23.0", Some(44524), Some(Edition::Edition2018)),
386
387     // generic associated types (RFC 1598)
388     (active, generic_associated_types, "1.23.0", Some(44265), None),
389
390     // Resolve absolute paths as paths from other crates
391     (active, extern_absolute_paths, "1.24.0", Some(44660), Some(Edition::Edition2018)),
392
393     // `foo.rs` as an alternative to `foo/mod.rs`
394     (active, non_modrs_mods, "1.24.0", Some(44660), Some(Edition::Edition2018)),
395
396     // Termination trait in tests (RFC 1937)
397     (active, termination_trait_test, "1.24.0", Some(48854), Some(Edition::Edition2018)),
398
399     // `extern` in paths
400     (active, extern_in_paths, "1.23.0", Some(44660), None),
401
402     // Allows `#[repr(transparent)]` attribute on newtype structs
403     (active, repr_transparent, "1.25.0", Some(43036), None),
404
405     // Use `?` as the Kleene "at most one" operator
406     (active, macro_at_most_once_rep, "1.25.0", Some(48075), None),
407
408     // Infer outlives requirements; RFC 2093
409     (active, infer_outlives_requirements, "1.26.0", Some(44493), None),
410
411     // Multiple patterns with `|` in `if let` and `while let`
412     (active, if_while_or_patterns, "1.26.0", Some(48215), None),
413
414     // Parentheses in patterns
415     (active, pattern_parentheses, "1.26.0", None, None),
416
417     // Allows `#[repr(packed)]` attribute on structs
418     (active, repr_packed, "1.26.0", Some(33158), None),
419
420     // `use path as _;` and `extern crate c as _;`
421     (active, underscore_imports, "1.26.0", Some(48216), None),
422
423     // The #[wasm_custom_section] attribute
424     (active, wasm_custom_section, "1.26.0", None, None),
425
426     // The #![wasm_import_module] attribute
427     (active, wasm_import_module, "1.26.0", None, None),
428
429     // Allows keywords to be escaped for use as identifiers
430     (active, raw_identifiers, "1.26.0", Some(48589), None),
431
432     // Allows macro invocations in `extern {}` blocks
433     (active, macros_in_extern, "1.27.0", Some(49476), None),
434
435     // unstable #[target_feature] directives
436     (active, arm_target_feature, "1.27.0", None, None),
437     (active, aarch64_target_feature, "1.27.0", None, None),
438     (active, hexagon_target_feature, "1.27.0", None, None),
439     (active, powerpc_target_feature, "1.27.0", None, None),
440     (active, mips_target_feature, "1.27.0", None, None),
441     (active, avx512_target_feature, "1.27.0", None, None),
442     (active, mmx_target_feature, "1.27.0", None, None),
443     (active, sse4a_target_feature, "1.27.0", None, None),
444     (active, tbm_target_feature, "1.27.0", None, None),
445
446     // Allows macro invocations of the form `#[foo::bar]`
447     (active, proc_macro_path_invoc, "1.27.0", None, None),
448
449     // Allows macro invocations on modules expressions and statements and
450     // procedural macros to expand to non-items.
451     (active, proc_macro_mod, "1.27.0", None, None),
452     (active, proc_macro_expr, "1.27.0", None, None),
453     (active, proc_macro_non_items, "1.27.0", None, None),
454
455     // #[doc(alias = "...")]
456     (active, doc_alias, "1.27.0", Some(50146), None),
457
458     // Access to crate names passed via `--extern` through prelude
459     (active, extern_prelude, "1.27.0", Some(44660), Some(Edition::Edition2018)),
460
461     // Scoped attributes
462     (active, tool_attributes, "1.25.0", Some(44690), None),
463
464     // Allows use of the :literal macro fragment specifier (RFC 1576)
465     (active, macro_literal_matcher, "1.27.0", Some(35625), None),
466
467     // inconsistent bounds in where clauses
468     (active, trivial_bounds, "1.28.0", Some(48214), None),
469 );
470
471 declare_features! (
472     (removed, import_shadowing, "1.0.0", None, None, None),
473     (removed, managed_boxes, "1.0.0", None, None, None),
474     // Allows use of unary negate on unsigned integers, e.g. -e for e: u8
475     (removed, negate_unsigned, "1.0.0", Some(29645), None, None),
476     (removed, reflect, "1.0.0", Some(27749), None, None),
477     // A way to temporarily opt out of opt in copy. This will *never* be accepted.
478     (removed, opt_out_copy, "1.0.0", None, None, None),
479     (removed, quad_precision_float, "1.0.0", None, None, None),
480     (removed, struct_inherit, "1.0.0", None, None, None),
481     (removed, test_removed_feature, "1.0.0", None, None, None),
482     (removed, visible_private_types, "1.0.0", None, None, None),
483     (removed, unsafe_no_drop_flag, "1.0.0", None, None, None),
484     // Allows using items which are missing stability attributes
485     // rustc internal
486     (removed, unmarked_api, "1.0.0", None, None, None),
487     (removed, pushpop_unsafe, "1.2.0", None, None, None),
488     (removed, allocator, "1.0.0", None, None, None),
489     (removed, simd, "1.0.0", Some(27731), None,
490      Some("removed in favor of `#[repr(simd)]`")),
491     (removed, advanced_slice_patterns, "1.0.0", Some(23121), None,
492      Some("merged into `#![feature(slice_patterns)]`")),
493     (removed, macro_reexport, "1.0.0", Some(29638), None,
494      Some("subsumed by `#![feature(use_extern_macros)]` and `pub use`")),
495 );
496
497 declare_features! (
498     (stable_removed, no_stack_check, "1.0.0", None, None),
499 );
500
501 declare_features! (
502     (accepted, associated_types, "1.0.0", None, None),
503     // allow overloading augmented assignment operations like `a += b`
504     (accepted, augmented_assignments, "1.8.0", Some(28235), None),
505     // allow empty structs and enum variants with braces
506     (accepted, braced_empty_structs, "1.8.0", Some(29720), None),
507     // Allows indexing into constant arrays.
508     (accepted, const_indexing, "1.26.0", Some(29947), None),
509     (accepted, default_type_params, "1.0.0", None, None),
510     (accepted, globs, "1.0.0", None, None),
511     (accepted, if_let, "1.0.0", None, None),
512     // A temporary feature gate used to enable parser extensions needed
513     // to bootstrap fix for #5723.
514     (accepted, issue_5723_bootstrap, "1.0.0", None, None),
515     (accepted, macro_rules, "1.0.0", None, None),
516     // Allows using #![no_std]
517     (accepted, no_std, "1.6.0", None, None),
518     (accepted, slicing_syntax, "1.0.0", None, None),
519     (accepted, struct_variant, "1.0.0", None, None),
520     // These are used to test this portion of the compiler, they don't actually
521     // mean anything
522     (accepted, test_accepted_feature, "1.0.0", None, None),
523     (accepted, tuple_indexing, "1.0.0", None, None),
524     // Allows macros to appear in the type position.
525     (accepted, type_macros, "1.13.0", Some(27245), None),
526     (accepted, while_let, "1.0.0", None, None),
527     // Allows `#[deprecated]` attribute
528     (accepted, deprecated, "1.9.0", Some(29935), None),
529     // `expr?`
530     (accepted, question_mark, "1.13.0", Some(31436), None),
531     // Allows `..` in tuple (struct) patterns
532     (accepted, dotdot_in_tuple_patterns, "1.14.0", Some(33627), None),
533     (accepted, item_like_imports, "1.15.0", Some(35120), None),
534     // Allows using `Self` and associated types in struct expressions and patterns.
535     (accepted, more_struct_aliases, "1.16.0", Some(37544), None),
536     // elide `'static` lifetimes in `static`s and `const`s
537     (accepted, static_in_const, "1.17.0", Some(35897), None),
538     // Allows field shorthands (`x` meaning `x: x`) in struct literal expressions.
539     (accepted, field_init_shorthand, "1.17.0", Some(37340), None),
540     // Allows the definition recursive static items.
541     (accepted, static_recursion, "1.17.0", Some(29719), None),
542     // pub(restricted) visibilities (RFC 1422)
543     (accepted, pub_restricted, "1.18.0", Some(32409), None),
544     // The #![windows_subsystem] attribute
545     (accepted, windows_subsystem, "1.18.0", Some(37499), None),
546     // Allows `break {expr}` with a value inside `loop`s.
547     (accepted, loop_break_value, "1.19.0", Some(37339), None),
548     // Permits numeric fields in struct expressions and patterns.
549     (accepted, relaxed_adts, "1.19.0", Some(35626), None),
550     // Coerces non capturing closures to function pointers
551     (accepted, closure_to_fn_coercion, "1.19.0", Some(39817), None),
552     // Allows attributes on struct literal fields.
553     (accepted, struct_field_attributes, "1.20.0", Some(38814), None),
554     // Allows the definition of associated constants in `trait` or `impl`
555     // blocks.
556     (accepted, associated_consts, "1.20.0", Some(29646), None),
557     // Usage of the `compile_error!` macro
558     (accepted, compile_error, "1.20.0", Some(40872), None),
559     // See rust-lang/rfcs#1414. Allows code like `let x: &'static u32 = &42` to work.
560     (accepted, rvalue_static_promotion, "1.21.0", Some(38865), None),
561     // Allow Drop types in constants (RFC 1440)
562     (accepted, drop_types_in_const, "1.22.0", Some(33156), None),
563     // Allows the sysV64 ABI to be specified on all platforms
564     // instead of just the platforms on which it is the C ABI
565     (accepted, abi_sysv64, "1.24.0", Some(36167), None),
566     // Allows `repr(align(16))` struct attribute (RFC 1358)
567     (accepted, repr_align, "1.25.0", Some(33626), None),
568     // allow '|' at beginning of match arms (RFC 1925)
569     (accepted, match_beginning_vert, "1.25.0", Some(44101), None),
570     // Nested groups in `use` (RFC 2128)
571     (accepted, use_nested_groups, "1.25.0", Some(44494), None),
572     // a..=b and ..=b
573     (accepted, inclusive_range_syntax, "1.26.0", Some(28237), None),
574     // allow `..=` in patterns (RFC 1192)
575     (accepted, dotdoteq_in_patterns, "1.26.0", Some(28237), None),
576     // Termination trait in main (RFC 1937)
577     (accepted, termination_trait, "1.26.0", Some(43301), None),
578     // Copy/Clone closures (RFC 2132)
579     (accepted, clone_closures, "1.26.0", Some(44490), None),
580     (accepted, copy_closures, "1.26.0", Some(44490), None),
581     // Allows `impl Trait` in function arguments.
582     (accepted, universal_impl_trait, "1.26.0", Some(34511), None),
583     // Allows `impl Trait` in function return types.
584     (accepted, conservative_impl_trait, "1.26.0", Some(34511), None),
585     // The `i128` type
586     (accepted, i128_type, "1.26.0", Some(35118), None),
587     // Default match binding modes (RFC 2005)
588     (accepted, match_default_bindings, "1.26.0", Some(42640), None),
589     // allow `'_` placeholder lifetimes
590     (accepted, underscore_lifetimes, "1.26.0", Some(44524), None),
591     // Allows attributes on lifetime/type formal parameters in generics (RFC 1327)
592     (accepted, generic_param_attrs, "1.26.0", Some(48848), None),
593     // Allows cfg(target_feature = "...").
594     (accepted, cfg_target_feature, "1.27.0", Some(29717), None),
595     // Allows #[target_feature(...)]
596     (accepted, target_feature, "1.27.0", None, None),
597     // Trait object syntax with `dyn` prefix
598     (accepted, dyn_trait, "1.27.0", Some(44662), None),
599     // allow `#[must_use]` on functions; and, must-use operators (RFC 1940)
600     (accepted, fn_must_use, "1.27.0", Some(43302), None),
601     // Allows use of the :lifetime macro fragment specifier
602     (accepted, macro_lifetime_matcher, "1.27.0", Some(34303), None),
603 );
604
605 // If you change this, please modify src/doc/unstable-book as well. You must
606 // move that documentation into the relevant place in the other docs, and
607 // remove the chapter on the flag.
608
609 #[derive(PartialEq, Copy, Clone, Debug)]
610 pub enum AttributeType {
611     /// Normal, builtin attribute that is consumed
612     /// by the compiler before the unused_attribute check
613     Normal,
614
615     /// Builtin attribute that may not be consumed by the compiler
616     /// before the unused_attribute check. These attributes
617     /// will be ignored by the unused_attribute lint
618     Whitelisted,
619
620     /// Builtin attribute that is only allowed at the crate level
621     CrateLevel,
622 }
623
624 pub enum AttributeGate {
625     /// Is gated by a given feature gate, reason
626     /// and function to check if enabled
627     Gated(Stability, &'static str, &'static str, fn(&Features) -> bool),
628
629     /// Ungated attribute, can be used on all release channels
630     Ungated,
631 }
632
633 impl AttributeGate {
634     fn is_deprecated(&self) -> bool {
635         match *self {
636             Gated(Stability::Deprecated(_), ..) => true,
637             _ => false,
638         }
639     }
640 }
641
642 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
643 pub enum Stability {
644     Unstable,
645     // Argument is tracking issue link.
646     Deprecated(&'static str),
647 }
648
649 // fn() is not Debug
650 impl ::std::fmt::Debug for AttributeGate {
651     fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
652         match *self {
653             Gated(ref stab, name, expl, _) =>
654                 write!(fmt, "Gated({:?}, {}, {})", stab, name, expl),
655             Ungated => write!(fmt, "Ungated")
656         }
657     }
658 }
659
660 macro_rules! cfg_fn {
661     ($field: ident) => {{
662         fn f(features: &Features) -> bool {
663             features.$field
664         }
665         f as fn(&Features) -> bool
666     }}
667 }
668
669 pub fn deprecated_attributes() -> Vec<&'static (&'static str, AttributeType, AttributeGate)> {
670     BUILTIN_ATTRIBUTES.iter().filter(|a| a.2.is_deprecated()).collect()
671 }
672
673 pub fn is_builtin_attr(attr: &ast::Attribute) -> bool {
674     BUILTIN_ATTRIBUTES.iter().any(|&(builtin_name, _, _)| attr.check_name(builtin_name))
675 }
676
677 // Attributes that have a special meaning to rustc or rustdoc
678 pub const BUILTIN_ATTRIBUTES: &'static [(&'static str, AttributeType, AttributeGate)] = &[
679     // Normal attributes
680
681     ("warn", Normal, Ungated),
682     ("allow", Normal, Ungated),
683     ("forbid", Normal, Ungated),
684     ("deny", Normal, Ungated),
685
686     ("macro_use", Normal, Ungated),
687     ("macro_export", Normal, Ungated),
688     ("plugin_registrar", Normal, Ungated),
689
690     ("cfg", Normal, Ungated),
691     ("cfg_attr", Normal, Ungated),
692     ("main", Normal, Ungated),
693     ("start", Normal, Ungated),
694     ("test", Normal, Ungated),
695     ("bench", Normal, Ungated),
696     ("repr", Normal, Ungated),
697     ("path", Normal, Ungated),
698     ("abi", Normal, Ungated),
699     ("automatically_derived", Normal, Ungated),
700     ("no_mangle", Normal, Ungated),
701     ("no_link", Normal, Ungated),
702     ("derive", Normal, Ungated),
703     ("should_panic", Normal, Ungated),
704     ("ignore", Normal, Ungated),
705     ("no_implicit_prelude", Normal, Ungated),
706     ("reexport_test_harness_main", Normal, Ungated),
707     ("link_args", Normal, Gated(Stability::Unstable,
708                                 "link_args",
709                                 "the `link_args` attribute is experimental and not \
710                                  portable across platforms, it is recommended to \
711                                  use `#[link(name = \"foo\")] instead",
712                                 cfg_fn!(link_args))),
713     ("macro_escape", Normal, Ungated),
714
715     // RFC #1445.
716     ("structural_match", Whitelisted, Gated(Stability::Unstable,
717                                             "structural_match",
718                                             "the semantics of constant patterns is \
719                                              not yet settled",
720                                             cfg_fn!(structural_match))),
721
722     // RFC #2008
723     ("non_exhaustive", Whitelisted, Gated(Stability::Unstable,
724                                           "non_exhaustive",
725                                           "non exhaustive is an experimental feature",
726                                           cfg_fn!(non_exhaustive))),
727
728     ("plugin", CrateLevel, Gated(Stability::Unstable,
729                                  "plugin",
730                                  "compiler plugins are experimental \
731                                   and possibly buggy",
732                                  cfg_fn!(plugin))),
733
734     ("no_std", CrateLevel, Ungated),
735     ("no_core", CrateLevel, Gated(Stability::Unstable,
736                                   "no_core",
737                                   "no_core is experimental",
738                                   cfg_fn!(no_core))),
739     ("lang", Normal, Gated(Stability::Unstable,
740                            "lang_items",
741                            "language items are subject to change",
742                            cfg_fn!(lang_items))),
743     ("linkage", Whitelisted, Gated(Stability::Unstable,
744                                    "linkage",
745                                    "the `linkage` attribute is experimental \
746                                     and not portable across platforms",
747                                    cfg_fn!(linkage))),
748     ("thread_local", Whitelisted, Gated(Stability::Unstable,
749                                         "thread_local",
750                                         "`#[thread_local]` is an experimental feature, and does \
751                                          not currently handle destructors.",
752                                         cfg_fn!(thread_local))),
753
754     ("rustc_on_unimplemented", Normal, Gated(Stability::Unstable,
755                                              "on_unimplemented",
756                                              "the `#[rustc_on_unimplemented]` attribute \
757                                               is an experimental feature",
758                                              cfg_fn!(on_unimplemented))),
759     ("rustc_const_unstable", Normal, Gated(Stability::Unstable,
760                                              "rustc_const_unstable",
761                                              "the `#[rustc_const_unstable]` attribute \
762                                               is an internal feature",
763                                              cfg_fn!(rustc_const_unstable))),
764     ("global_allocator", Normal, Gated(Stability::Unstable,
765                                        "global_allocator",
766                                        "the `#[global_allocator]` attribute is \
767                                         an experimental feature",
768                                        cfg_fn!(global_allocator))),
769     ("default_lib_allocator", Whitelisted, Gated(Stability::Unstable,
770                                             "allocator_internals",
771                                             "the `#[default_lib_allocator]` \
772                                              attribute is an experimental feature",
773                                             cfg_fn!(allocator_internals))),
774     ("needs_allocator", Normal, Gated(Stability::Unstable,
775                                       "allocator_internals",
776                                       "the `#[needs_allocator]` \
777                                        attribute is an experimental \
778                                        feature",
779                                       cfg_fn!(allocator_internals))),
780     ("panic_runtime", Whitelisted, Gated(Stability::Unstable,
781                                          "panic_runtime",
782                                          "the `#[panic_runtime]` attribute is \
783                                           an experimental feature",
784                                          cfg_fn!(panic_runtime))),
785     ("needs_panic_runtime", Whitelisted, Gated(Stability::Unstable,
786                                                "needs_panic_runtime",
787                                                "the `#[needs_panic_runtime]` \
788                                                 attribute is an experimental \
789                                                 feature",
790                                                cfg_fn!(needs_panic_runtime))),
791     ("rustc_variance", Normal, Gated(Stability::Unstable,
792                                      "rustc_attrs",
793                                      "the `#[rustc_variance]` attribute \
794                                       is just used for rustc unit tests \
795                                       and will never be stable",
796                                      cfg_fn!(rustc_attrs))),
797     ("rustc_regions", Normal, Gated(Stability::Unstable,
798                                     "rustc_attrs",
799                                     "the `#[rustc_regions]` attribute \
800                                      is just used for rustc unit tests \
801                                      and will never be stable",
802                                     cfg_fn!(rustc_attrs))),
803     ("rustc_error", Whitelisted, Gated(Stability::Unstable,
804                                        "rustc_attrs",
805                                        "the `#[rustc_error]` attribute \
806                                         is just used for rustc unit tests \
807                                         and will never be stable",
808                                        cfg_fn!(rustc_attrs))),
809     ("rustc_if_this_changed", Whitelisted, Gated(Stability::Unstable,
810                                                  "rustc_attrs",
811                                                  "the `#[rustc_if_this_changed]` attribute \
812                                                   is just used for rustc unit tests \
813                                                   and will never be stable",
814                                                  cfg_fn!(rustc_attrs))),
815     ("rustc_then_this_would_need", Whitelisted, Gated(Stability::Unstable,
816                                                       "rustc_attrs",
817                                                       "the `#[rustc_if_this_changed]` attribute \
818                                                        is just used for rustc unit tests \
819                                                        and will never be stable",
820                                                       cfg_fn!(rustc_attrs))),
821     ("rustc_dirty", Whitelisted, Gated(Stability::Unstable,
822                                        "rustc_attrs",
823                                        "the `#[rustc_dirty]` attribute \
824                                         is just used for rustc unit tests \
825                                         and will never be stable",
826                                        cfg_fn!(rustc_attrs))),
827     ("rustc_clean", Whitelisted, Gated(Stability::Unstable,
828                                        "rustc_attrs",
829                                        "the `#[rustc_clean]` attribute \
830                                         is just used for rustc unit tests \
831                                         and will never be stable",
832                                        cfg_fn!(rustc_attrs))),
833     ("rustc_partition_reused", Whitelisted, Gated(Stability::Unstable,
834                                                   "rustc_attrs",
835                                                   "this attribute \
836                                                    is just used for rustc unit tests \
837                                                    and will never be stable",
838                                                   cfg_fn!(rustc_attrs))),
839     ("rustc_partition_translated", Whitelisted, Gated(Stability::Unstable,
840                                                       "rustc_attrs",
841                                                       "this attribute \
842                                                        is just used for rustc unit tests \
843                                                        and will never be stable",
844                                                       cfg_fn!(rustc_attrs))),
845     ("rustc_serialize_exclude_null", Normal, Gated(Stability::Unstable,
846                                              "rustc_attrs",
847                                              "the `#[rustc_serialize_exclude_null]` attribute \
848                                               is an internal-only feature",
849                                              cfg_fn!(rustc_attrs))),
850     ("rustc_synthetic", Whitelisted, Gated(Stability::Unstable,
851                                                       "rustc_attrs",
852                                                       "this attribute \
853                                                        is just used for rustc unit tests \
854                                                        and will never be stable",
855                                                       cfg_fn!(rustc_attrs))),
856     ("rustc_symbol_name", Whitelisted, Gated(Stability::Unstable,
857                                              "rustc_attrs",
858                                              "internal rustc attributes will never be stable",
859                                              cfg_fn!(rustc_attrs))),
860     ("rustc_item_path", Whitelisted, Gated(Stability::Unstable,
861                                            "rustc_attrs",
862                                            "internal rustc attributes will never be stable",
863                                            cfg_fn!(rustc_attrs))),
864     ("rustc_mir", Whitelisted, Gated(Stability::Unstable,
865                                      "rustc_attrs",
866                                      "the `#[rustc_mir]` attribute \
867                                       is just used for rustc unit tests \
868                                       and will never be stable",
869                                      cfg_fn!(rustc_attrs))),
870     ("rustc_inherit_overflow_checks", Whitelisted, Gated(Stability::Unstable,
871                                                          "rustc_attrs",
872                                                          "the `#[rustc_inherit_overflow_checks]` \
873                                                           attribute is just used to control \
874                                                           overflow checking behavior of several \
875                                                           libcore functions that are inlined \
876                                                           across crates and will never be stable",
877                                                           cfg_fn!(rustc_attrs))),
878
879     ("rustc_dump_program_clauses", Whitelisted, Gated(Stability::Unstable,
880                                                      "rustc_attrs",
881                                                      "the `#[rustc_dump_program_clauses]` \
882                                                       attribute is just used for rustc unit \
883                                                       tests and will never be stable",
884                                                      cfg_fn!(rustc_attrs))),
885
886     // RFC #2094
887     ("nll", Whitelisted, Gated(Stability::Unstable,
888                                "nll",
889                                "Non lexical lifetimes",
890                                cfg_fn!(nll))),
891     ("compiler_builtins", Whitelisted, Gated(Stability::Unstable,
892                                              "compiler_builtins",
893                                              "the `#[compiler_builtins]` attribute is used to \
894                                               identify the `compiler_builtins` crate which \
895                                               contains compiler-rt intrinsics and will never be \
896                                               stable",
897                                           cfg_fn!(compiler_builtins))),
898     ("sanitizer_runtime", Whitelisted, Gated(Stability::Unstable,
899                                              "sanitizer_runtime",
900                                              "the `#[sanitizer_runtime]` attribute is used to \
901                                               identify crates that contain the runtime of a \
902                                               sanitizer and will never be stable",
903                                              cfg_fn!(sanitizer_runtime))),
904     ("profiler_runtime", Whitelisted, Gated(Stability::Unstable,
905                                              "profiler_runtime",
906                                              "the `#[profiler_runtime]` attribute is used to \
907                                               identify the `profiler_builtins` crate which \
908                                               contains the profiler runtime and will never be \
909                                               stable",
910                                              cfg_fn!(profiler_runtime))),
911
912     ("allow_internal_unstable", Normal, Gated(Stability::Unstable,
913                                               "allow_internal_unstable",
914                                               EXPLAIN_ALLOW_INTERNAL_UNSTABLE,
915                                               cfg_fn!(allow_internal_unstable))),
916
917     ("allow_internal_unsafe", Normal, Gated(Stability::Unstable,
918                                             "allow_internal_unsafe",
919                                             EXPLAIN_ALLOW_INTERNAL_UNSAFE,
920                                             cfg_fn!(allow_internal_unsafe))),
921
922     ("fundamental", Whitelisted, Gated(Stability::Unstable,
923                                        "fundamental",
924                                        "the `#[fundamental]` attribute \
925                                         is an experimental feature",
926                                        cfg_fn!(fundamental))),
927
928     ("proc_macro_derive", Normal, Ungated),
929
930     ("rustc_copy_clone_marker", Whitelisted, Gated(Stability::Unstable,
931                                                    "rustc_attrs",
932                                                    "internal implementation detail",
933                                                    cfg_fn!(rustc_attrs))),
934
935     // FIXME: #14408 whitelist docs since rustdoc looks at them
936     ("doc", Whitelisted, Ungated),
937
938     // FIXME: #14406 these are processed in trans, which happens after the
939     // lint pass
940     ("cold", Whitelisted, Ungated),
941     ("naked", Whitelisted, Gated(Stability::Unstable,
942                                  "naked_functions",
943                                  "the `#[naked]` attribute \
944                                   is an experimental feature",
945                                  cfg_fn!(naked_functions))),
946     ("target_feature", Whitelisted, Ungated),
947     ("export_name", Whitelisted, Ungated),
948     ("inline", Whitelisted, Ungated),
949     ("link", Whitelisted, Ungated),
950     ("link_name", Whitelisted, Ungated),
951     ("link_section", Whitelisted, Ungated),
952     ("no_builtins", Whitelisted, Ungated),
953     ("no_mangle", Whitelisted, Ungated),
954     ("no_debug", Whitelisted, Gated(
955         Stability::Deprecated("https://github.com/rust-lang/rust/issues/29721"),
956         "no_debug",
957         "the `#[no_debug]` attribute was an experimental feature that has been \
958          deprecated due to lack of demand",
959         cfg_fn!(no_debug))),
960     ("wasm_import_module", Normal, Gated(Stability::Unstable,
961                                  "wasm_import_module",
962                                  "experimental attribute",
963                                  cfg_fn!(wasm_import_module))),
964     ("omit_gdb_pretty_printer_section", Whitelisted, Gated(Stability::Unstable,
965                                                        "omit_gdb_pretty_printer_section",
966                                                        "the `#[omit_gdb_pretty_printer_section]` \
967                                                         attribute is just used for the Rust test \
968                                                         suite",
969                                                        cfg_fn!(omit_gdb_pretty_printer_section))),
970     ("unsafe_destructor_blind_to_params",
971      Normal,
972      Gated(Stability::Deprecated("https://github.com/rust-lang/rust/issues/34761"),
973            "dropck_parametricity",
974            "unsafe_destructor_blind_to_params has been replaced by \
975             may_dangle and will be removed in the future",
976            cfg_fn!(dropck_parametricity))),
977     ("may_dangle",
978      Normal,
979      Gated(Stability::Unstable,
980            "dropck_eyepatch",
981            "may_dangle has unstable semantics and may be removed in the future",
982            cfg_fn!(dropck_eyepatch))),
983     ("unwind", Whitelisted, Gated(Stability::Unstable,
984                                   "unwind_attributes",
985                                   "#[unwind] is experimental",
986                                   cfg_fn!(unwind_attributes))),
987     ("used", Whitelisted, Gated(
988         Stability::Unstable, "used",
989         "the `#[used]` attribute is an experimental feature",
990         cfg_fn!(used))),
991
992     // used in resolve
993     ("prelude_import", Whitelisted, Gated(Stability::Unstable,
994                                           "prelude_import",
995                                           "`#[prelude_import]` is for use by rustc only",
996                                           cfg_fn!(prelude_import))),
997
998     // FIXME: #14407 these are only looked at on-demand so we can't
999     // guarantee they'll have already been checked
1000     ("rustc_deprecated", Whitelisted, Ungated),
1001     ("must_use", Whitelisted, Ungated),
1002     ("stable", Whitelisted, Ungated),
1003     ("unstable", Whitelisted, Ungated),
1004     ("deprecated", Normal, Ungated),
1005
1006     ("rustc_paren_sugar", Normal, Gated(Stability::Unstable,
1007                                         "unboxed_closures",
1008                                         "unboxed_closures are still evolving",
1009                                         cfg_fn!(unboxed_closures))),
1010
1011     ("windows_subsystem", Whitelisted, Ungated),
1012
1013     ("proc_macro_attribute", Normal, Gated(Stability::Unstable,
1014                                            "proc_macro",
1015                                            "attribute proc macros are currently unstable",
1016                                            cfg_fn!(proc_macro))),
1017
1018     ("proc_macro", Normal, Gated(Stability::Unstable,
1019                                  "proc_macro",
1020                                  "function-like proc macros are currently unstable",
1021                                  cfg_fn!(proc_macro))),
1022
1023     ("rustc_derive_registrar", Normal, Gated(Stability::Unstable,
1024                                              "rustc_derive_registrar",
1025                                              "used internally by rustc",
1026                                              cfg_fn!(rustc_attrs))),
1027
1028     ("allow_fail", Normal, Gated(Stability::Unstable,
1029                                  "allow_fail",
1030                                  "allow_fail attribute is currently unstable",
1031                                  cfg_fn!(allow_fail))),
1032
1033     ("rustc_std_internal_symbol", Whitelisted, Gated(Stability::Unstable,
1034                                      "rustc_attrs",
1035                                      "this is an internal attribute that will \
1036                                       never be stable",
1037                                      cfg_fn!(rustc_attrs))),
1038
1039     // whitelists "identity-like" conversion methods to suggest on type mismatch
1040     ("rustc_conversion_suggestion", Whitelisted, Gated(Stability::Unstable,
1041                                                        "rustc_attrs",
1042                                                        "this is an internal attribute that will \
1043                                                         never be stable",
1044                                                        cfg_fn!(rustc_attrs))),
1045
1046     ("rustc_args_required_const", Whitelisted, Gated(Stability::Unstable,
1047                                  "rustc_attrs",
1048                                  "never will be stable",
1049                                  cfg_fn!(rustc_attrs))),
1050
1051     // RFC #2093
1052     ("infer_outlives_requirements", Normal, Gated(Stability::Unstable,
1053                                    "infer_outlives_requirements",
1054                                    "infer outlives requirements is an experimental feature",
1055                                    cfg_fn!(infer_outlives_requirements))),
1056
1057     ("wasm_custom_section", Whitelisted, Gated(Stability::Unstable,
1058                                  "wasm_custom_section",
1059                                  "attribute is currently unstable",
1060                                  cfg_fn!(wasm_custom_section))),
1061
1062     // Crate level attributes
1063     ("crate_name", CrateLevel, Ungated),
1064     ("crate_type", CrateLevel, Ungated),
1065     ("crate_id", CrateLevel, Ungated),
1066     ("feature", CrateLevel, Ungated),
1067     ("no_start", CrateLevel, Ungated),
1068     ("no_main", CrateLevel, Ungated),
1069     ("no_builtins", CrateLevel, Ungated),
1070     ("recursion_limit", CrateLevel, Ungated),
1071     ("type_length_limit", CrateLevel, Ungated),
1072 ];
1073
1074 // cfg(...)'s that are feature gated
1075 const GATED_CFGS: &[(&str, &str, fn(&Features) -> bool)] = &[
1076     // (name in cfg, feature, function to check if the feature is enabled)
1077     ("target_vendor", "cfg_target_vendor", cfg_fn!(cfg_target_vendor)),
1078     ("target_thread_local", "cfg_target_thread_local", cfg_fn!(cfg_target_thread_local)),
1079     ("target_has_atomic", "cfg_target_has_atomic", cfg_fn!(cfg_target_has_atomic)),
1080 ];
1081
1082 #[derive(Debug, Eq, PartialEq)]
1083 pub struct GatedCfg {
1084     span: Span,
1085     index: usize,
1086 }
1087
1088 impl GatedCfg {
1089     pub fn gate(cfg: &ast::MetaItem) -> Option<GatedCfg> {
1090         let name = cfg.name().as_str();
1091         GATED_CFGS.iter()
1092                   .position(|info| info.0 == name)
1093                   .map(|idx| {
1094                       GatedCfg {
1095                           span: cfg.span,
1096                           index: idx
1097                       }
1098                   })
1099     }
1100
1101     pub fn check_and_emit(&self, sess: &ParseSess, features: &Features) {
1102         let (cfg, feature, has_feature) = GATED_CFGS[self.index];
1103         if !has_feature(features) && !self.span.allows_unstable() {
1104             let explain = format!("`cfg({})` is experimental and subject to change", cfg);
1105             emit_feature_err(sess, feature, self.span, GateIssue::Language, &explain);
1106         }
1107     }
1108 }
1109
1110 struct Context<'a> {
1111     features: &'a Features,
1112     parse_sess: &'a ParseSess,
1113     plugin_attributes: &'a [(String, AttributeType)],
1114 }
1115
1116 macro_rules! gate_feature_fn {
1117     ($cx: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr, $level: expr) => {{
1118         let (cx, has_feature, span,
1119              name, explain, level) = ($cx, $has_feature, $span, $name, $explain, $level);
1120         let has_feature: bool = has_feature(&$cx.features);
1121         debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
1122         if !has_feature && !span.allows_unstable() {
1123             leveled_feature_err(cx.parse_sess, name, span, GateIssue::Language, explain, level)
1124                 .emit();
1125         }
1126     }}
1127 }
1128
1129 macro_rules! gate_feature {
1130     ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {
1131         gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
1132                          stringify!($feature), $explain, GateStrength::Hard)
1133     };
1134     ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {
1135         gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
1136                          stringify!($feature), $explain, $level)
1137     };
1138 }
1139
1140 impl<'a> Context<'a> {
1141     fn check_attribute(&self, attr: &ast::Attribute, is_macro: bool) {
1142         debug!("check_attribute(attr = {:?})", attr);
1143         let name = attr.name().as_str();
1144         for &(n, ty, ref gateage) in BUILTIN_ATTRIBUTES {
1145             if name == n {
1146                 if let Gated(_, name, desc, ref has_feature) = *gateage {
1147                     gate_feature_fn!(self, has_feature, attr.span, name, desc, GateStrength::Hard);
1148                 } else if name == "doc" {
1149                     if let Some(content) = attr.meta_item_list() {
1150                         if content.iter().any(|c| c.check_name("include")) {
1151                             gate_feature!(self, external_doc, attr.span,
1152                                 "#[doc(include = \"...\")] is experimental"
1153                             );
1154                         }
1155                     }
1156                 }
1157                 debug!("check_attribute: {:?} is builtin, {:?}, {:?}", attr.path, ty, gateage);
1158                 return;
1159             }
1160         }
1161         for &(ref n, ref ty) in self.plugin_attributes {
1162             if attr.path == &**n {
1163                 // Plugins can't gate attributes, so we don't check for it
1164                 // unlike the code above; we only use this loop to
1165                 // short-circuit to avoid the checks below
1166                 debug!("check_attribute: {:?} is registered by a plugin, {:?}", attr.path, ty);
1167                 return;
1168             }
1169         }
1170         if name.starts_with("rustc_") {
1171             gate_feature!(self, rustc_attrs, attr.span,
1172                           "unless otherwise specified, attributes \
1173                            with the prefix `rustc_` \
1174                            are reserved for internal compiler diagnostics");
1175         } else if name.starts_with("derive_") {
1176             gate_feature!(self, custom_derive, attr.span, EXPLAIN_DERIVE_UNDERSCORE);
1177         } else if !attr::is_known(attr) {
1178             // Only run the custom attribute lint during regular
1179             // feature gate checking. Macro gating runs
1180             // before the plugin attributes are registered
1181             // so we skip this then
1182             if !is_macro {
1183                 if attr.is_scoped() {
1184                     gate_feature!(self, tool_attributes, attr.span,
1185                                   &format!("scoped attribute `{}` is experimental", attr.path));
1186                     if attr::is_known_tool(attr) {
1187                         attr::mark_used(attr);
1188                     } else {
1189                         span_err!(
1190                             self.parse_sess.span_diagnostic,
1191                             attr.span,
1192                             E0694,
1193                             "an unknown tool name found in scoped attribute: `{}`.",
1194                             attr.path
1195                         );
1196                     }
1197                 } else {
1198                     gate_feature!(self, custom_attribute, attr.span,
1199                                   &format!("The attribute `{}` is currently \
1200                                             unknown to the compiler and \
1201                                             may have meaning \
1202                                             added to it in the future",
1203                                            attr.path));
1204                 }
1205             }
1206         }
1207     }
1208 }
1209
1210 pub fn check_attribute(attr: &ast::Attribute, parse_sess: &ParseSess, features: &Features) {
1211     let cx = Context { features: features, parse_sess: parse_sess, plugin_attributes: &[] };
1212     cx.check_attribute(attr, true);
1213 }
1214
1215 pub fn find_lang_feature_accepted_version(feature: &str) -> Option<&'static str> {
1216     ACCEPTED_FEATURES.iter().find(|t| t.0 == feature).map(|t| t.1)
1217 }
1218
1219 fn find_lang_feature_issue(feature: &str) -> Option<u32> {
1220     if let Some(info) = ACTIVE_FEATURES.iter().find(|t| t.0 == feature) {
1221         let issue = info.2;
1222         // FIXME (#28244): enforce that active features have issue numbers
1223         // assert!(issue.is_some())
1224         issue
1225     } else {
1226         // search in Accepted, Removed, or Stable Removed features
1227         let found = ACCEPTED_FEATURES.iter().chain(REMOVED_FEATURES).chain(STABLE_REMOVED_FEATURES)
1228             .find(|t| t.0 == feature);
1229         match found {
1230             Some(&(_, _, issue, _)) => issue,
1231             None => panic!("Feature `{}` is not declared anywhere", feature),
1232         }
1233     }
1234 }
1235
1236 pub enum GateIssue {
1237     Language,
1238     Library(Option<u32>)
1239 }
1240
1241 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
1242 pub enum GateStrength {
1243     /// A hard error. (Most feature gates should use this.)
1244     Hard,
1245     /// Only a warning. (Use this only as backwards-compatibility demands.)
1246     Soft,
1247 }
1248
1249 pub fn emit_feature_err(sess: &ParseSess, feature: &str, span: Span, issue: GateIssue,
1250                         explain: &str) {
1251     feature_err(sess, feature, span, issue, explain).emit();
1252 }
1253
1254 pub fn feature_err<'a>(sess: &'a ParseSess, feature: &str, span: Span, issue: GateIssue,
1255                        explain: &str) -> DiagnosticBuilder<'a> {
1256     leveled_feature_err(sess, feature, span, issue, explain, GateStrength::Hard)
1257 }
1258
1259 fn leveled_feature_err<'a>(sess: &'a ParseSess, feature: &str, span: Span, issue: GateIssue,
1260                            explain: &str, level: GateStrength) -> DiagnosticBuilder<'a> {
1261     let diag = &sess.span_diagnostic;
1262
1263     let issue = match issue {
1264         GateIssue::Language => find_lang_feature_issue(feature),
1265         GateIssue::Library(lib) => lib,
1266     };
1267
1268     let explanation = match issue {
1269         None | Some(0) => explain.to_owned(),
1270         Some(n) => format!("{} (see issue #{})", explain, n)
1271     };
1272
1273     let mut err = match level {
1274         GateStrength::Hard => {
1275             diag.struct_span_err_with_code(span, &explanation, stringify_error_code!(E0658))
1276         }
1277         GateStrength::Soft => diag.struct_span_warn(span, &explanation),
1278     };
1279
1280     // #23973: do not suggest `#![feature(...)]` if we are in beta/stable
1281     if sess.unstable_features.is_nightly_build() {
1282         err.help(&format!("add #![feature({})] to the \
1283                            crate attributes to enable",
1284                           feature));
1285     }
1286
1287     // If we're on stable and only emitting a "soft" warning, add a note to
1288     // clarify that the feature isn't "on" (rather than being on but
1289     // warning-worthy).
1290     if !sess.unstable_features.is_nightly_build() && level == GateStrength::Soft {
1291         err.help("a nightly build of the compiler is required to enable this feature");
1292     }
1293
1294     err
1295
1296 }
1297
1298 const EXPLAIN_BOX_SYNTAX: &'static str =
1299     "box expression syntax is experimental; you can call `Box::new` instead.";
1300
1301 pub const EXPLAIN_STMT_ATTR_SYNTAX: &'static str =
1302     "attributes on expressions are experimental.";
1303
1304 pub const EXPLAIN_ASM: &'static str =
1305     "inline assembly is not stable enough for use and is subject to change";
1306
1307 pub const EXPLAIN_GLOBAL_ASM: &'static str =
1308     "`global_asm!` is not stable enough for use and is subject to change";
1309
1310 pub const EXPLAIN_LOG_SYNTAX: &'static str =
1311     "`log_syntax!` is not stable enough for use and is subject to change";
1312
1313 pub const EXPLAIN_CONCAT_IDENTS: &'static str =
1314     "`concat_idents` is not stable enough for use and is subject to change";
1315
1316 pub const EXPLAIN_TRACE_MACROS: &'static str =
1317     "`trace_macros` is not stable enough for use and is subject to change";
1318 pub const EXPLAIN_ALLOW_INTERNAL_UNSTABLE: &'static str =
1319     "allow_internal_unstable side-steps feature gating and stability checks";
1320 pub const EXPLAIN_ALLOW_INTERNAL_UNSAFE: &'static str =
1321     "allow_internal_unsafe side-steps the unsafe_code lint";
1322
1323 pub const EXPLAIN_CUSTOM_DERIVE: &'static str =
1324     "`#[derive]` for custom traits is deprecated and will be removed in the future.";
1325
1326 pub const EXPLAIN_DEPR_CUSTOM_DERIVE: &'static str =
1327     "`#[derive]` for custom traits is deprecated and will be removed in the future. \
1328     Prefer using procedural macro custom derive.";
1329
1330 pub const EXPLAIN_DERIVE_UNDERSCORE: &'static str =
1331     "attributes of the form `#[derive_*]` are reserved for the compiler";
1332
1333 pub const EXPLAIN_VIS_MATCHER: &'static str =
1334     ":vis fragment specifier is experimental and subject to change";
1335
1336 pub const EXPLAIN_LITERAL_MATCHER: &'static str =
1337     ":literal fragment specifier is experimental and subject to change";
1338
1339 pub const EXPLAIN_UNSIZED_TUPLE_COERCION: &'static str =
1340     "Unsized tuple coercion is not stable enough for use and is subject to change";
1341
1342 pub const EXPLAIN_MACRO_AT_MOST_ONCE_REP: &'static str =
1343     "Using the `?` macro Kleene operator for \"at most one\" repetition is unstable";
1344
1345 pub const EXPLAIN_MACROS_IN_EXTERN: &'static str =
1346     "Macro invocations in `extern {}` blocks are experimental.";
1347
1348 // mention proc-macros when enabled
1349 pub const EXPLAIN_PROC_MACROS_IN_EXTERN: &'static str =
1350     "Macro and proc-macro invocations in `extern {}` blocks are experimental.";
1351
1352 struct PostExpansionVisitor<'a> {
1353     context: &'a Context<'a>,
1354 }
1355
1356 macro_rules! gate_feature_post {
1357     ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {{
1358         let (cx, span) = ($cx, $span);
1359         if !span.allows_unstable() {
1360             gate_feature!(cx.context, $feature, span, $explain)
1361         }
1362     }};
1363     ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {{
1364         let (cx, span) = ($cx, $span);
1365         if !span.allows_unstable() {
1366             gate_feature!(cx.context, $feature, span, $explain, $level)
1367         }
1368     }}
1369 }
1370
1371 impl<'a> PostExpansionVisitor<'a> {
1372     fn check_abi(&self, abi: Abi, span: Span) {
1373         match abi {
1374             Abi::RustIntrinsic => {
1375                 gate_feature_post!(&self, intrinsics, span,
1376                                    "intrinsics are subject to change");
1377             },
1378             Abi::PlatformIntrinsic => {
1379                 gate_feature_post!(&self, platform_intrinsics, span,
1380                                    "platform intrinsics are experimental and possibly buggy");
1381             },
1382             Abi::Vectorcall => {
1383                 gate_feature_post!(&self, abi_vectorcall, span,
1384                                    "vectorcall is experimental and subject to change");
1385             },
1386             Abi::Thiscall => {
1387                 gate_feature_post!(&self, abi_thiscall, span,
1388                                    "thiscall is experimental and subject to change");
1389             },
1390             Abi::RustCall => {
1391                 gate_feature_post!(&self, unboxed_closures, span,
1392                                    "rust-call ABI is subject to change");
1393             },
1394             Abi::PtxKernel => {
1395                 gate_feature_post!(&self, abi_ptx, span,
1396                                    "PTX ABIs are experimental and subject to change");
1397             },
1398             Abi::Unadjusted => {
1399                 gate_feature_post!(&self, abi_unadjusted, span,
1400                                    "unadjusted ABI is an implementation detail and perma-unstable");
1401             },
1402             Abi::Msp430Interrupt => {
1403                 gate_feature_post!(&self, abi_msp430_interrupt, span,
1404                                    "msp430-interrupt ABI is experimental and subject to change");
1405             },
1406             Abi::X86Interrupt => {
1407                 gate_feature_post!(&self, abi_x86_interrupt, span,
1408                                    "x86-interrupt ABI is experimental and subject to change");
1409             },
1410             // Stable
1411             Abi::Cdecl |
1412             Abi::Stdcall |
1413             Abi::Fastcall |
1414             Abi::Aapcs |
1415             Abi::Win64 |
1416             Abi::SysV64 |
1417             Abi::Rust |
1418             Abi::C |
1419             Abi::System => {}
1420         }
1421     }
1422 }
1423
1424 fn contains_novel_literal(item: &ast::MetaItem) -> bool {
1425     use ast::MetaItemKind::*;
1426     use ast::NestedMetaItemKind::*;
1427
1428     match item.node {
1429         Word => false,
1430         NameValue(ref lit) => !lit.node.is_str(),
1431         List(ref list) => list.iter().any(|li| {
1432             match li.node {
1433                 MetaItem(ref mi) => contains_novel_literal(mi),
1434                 Literal(_) => true,
1435             }
1436         }),
1437     }
1438 }
1439
1440 impl<'a> PostExpansionVisitor<'a> {
1441     fn whole_crate_feature_gates(&mut self, _krate: &ast::Crate) {
1442         for &(ident, span) in &*self.context.parse_sess.non_modrs_mods.borrow() {
1443             if !span.allows_unstable() {
1444                 let cx = &self.context;
1445                 let level = GateStrength::Hard;
1446                 let has_feature = cx.features.non_modrs_mods;
1447                 let name = "non_modrs_mods";
1448                 debug!("gate_feature(feature = {:?}, span = {:?}); has? {}",
1449                         name, span, has_feature);
1450
1451                 if !has_feature && !span.allows_unstable() {
1452                     leveled_feature_err(
1453                         cx.parse_sess, name, span, GateIssue::Language,
1454                         "mod statements in non-mod.rs files are unstable", level
1455                     )
1456                     .help(&format!("on stable builds, rename this file to {}{}mod.rs",
1457                                    ident, path::MAIN_SEPARATOR))
1458                     .emit();
1459                 }
1460             }
1461         }
1462     }
1463 }
1464
1465 impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
1466     fn visit_attribute(&mut self, attr: &ast::Attribute) {
1467         if !attr.span.allows_unstable() {
1468             // check for gated attributes
1469             self.context.check_attribute(attr, false);
1470         }
1471
1472         if attr.check_name("doc") {
1473             if let Some(content) = attr.meta_item_list() {
1474                 if content.len() == 1 && content[0].check_name("cfg") {
1475                     gate_feature_post!(&self, doc_cfg, attr.span,
1476                         "#[doc(cfg(...))] is experimental"
1477                     );
1478                 } else if content.iter().any(|c| c.check_name("masked")) {
1479                     gate_feature_post!(&self, doc_masked, attr.span,
1480                         "#[doc(masked)] is experimental"
1481                     );
1482                 } else if content.iter().any(|c| c.check_name("spotlight")) {
1483                     gate_feature_post!(&self, doc_spotlight, attr.span,
1484                         "#[doc(spotlight)] is experimental"
1485                     );
1486                 } else if content.iter().any(|c| c.check_name("alias")) {
1487                     gate_feature_post!(&self, doc_alias, attr.span,
1488                         "#[doc(alias = \"...\")] is experimental"
1489                     );
1490                 }
1491             }
1492         }
1493
1494         // allow attr_literals in #[repr(align(x))] and #[repr(packed(n))]
1495         let mut allow_attr_literal = false;
1496         if attr.path == "repr" {
1497             if let Some(content) = attr.meta_item_list() {
1498                 allow_attr_literal = content.iter().any(
1499                     |c| c.check_name("align") || c.check_name("packed"));
1500             }
1501         }
1502
1503         if self.context.features.proc_macro && attr::is_known(attr) {
1504             return
1505         }
1506
1507         if !allow_attr_literal {
1508             let meta = panictry!(attr.parse_meta(self.context.parse_sess));
1509             if contains_novel_literal(&meta) {
1510                 gate_feature_post!(&self, attr_literals, attr.span,
1511                                    "non-string literals in attributes, or string \
1512                                    literals in top-level positions, are experimental");
1513             }
1514         }
1515     }
1516
1517     fn visit_name(&mut self, sp: Span, name: ast::Name) {
1518         if !name.as_str().is_ascii() {
1519             gate_feature_post!(&self,
1520                                non_ascii_idents,
1521                                self.context.parse_sess.codemap().def_span(sp),
1522                                "non-ascii idents are not fully supported.");
1523         }
1524     }
1525
1526     fn visit_use_tree(&mut self, use_tree: &'a ast::UseTree, id: NodeId, _nested: bool) {
1527         if let ast::UseTreeKind::Simple(Some(ident)) = use_tree.kind {
1528             if ident.name == "_" {
1529                 gate_feature_post!(&self, underscore_imports, use_tree.span,
1530                                    "renaming imports with `_` is unstable");
1531             }
1532         }
1533
1534         visit::walk_use_tree(self, use_tree, id);
1535     }
1536
1537     fn visit_item(&mut self, i: &'a ast::Item) {
1538         match i.node {
1539             ast::ItemKind::ExternCrate(_) => {
1540                 if i.ident.name == "_" {
1541                     gate_feature_post!(&self, underscore_imports, i.span,
1542                                        "renaming extern crates with `_` is unstable");
1543                 }
1544             }
1545
1546             ast::ItemKind::ForeignMod(ref foreign_module) => {
1547                 self.check_abi(foreign_module.abi, i.span);
1548             }
1549
1550             ast::ItemKind::Fn(..) => {
1551                 if attr::contains_name(&i.attrs[..], "plugin_registrar") {
1552                     gate_feature_post!(&self, plugin_registrar, i.span,
1553                                        "compiler plugins are experimental and possibly buggy");
1554                 }
1555                 if attr::contains_name(&i.attrs[..], "start") {
1556                     gate_feature_post!(&self, start, i.span,
1557                                       "a #[start] function is an experimental \
1558                                        feature whose signature may change \
1559                                        over time");
1560                 }
1561                 if attr::contains_name(&i.attrs[..], "main") {
1562                     gate_feature_post!(&self, main, i.span,
1563                                        "declaration of a nonstandard #[main] \
1564                                         function may change over time, for now \
1565                                         a top-level `fn main()` is required");
1566                 }
1567             }
1568
1569             ast::ItemKind::Struct(..) => {
1570                 if let Some(attr) = attr::find_by_name(&i.attrs[..], "repr") {
1571                     for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
1572                         if item.check_name("simd") {
1573                             gate_feature_post!(&self, repr_simd, attr.span,
1574                                                "SIMD types are experimental and possibly buggy");
1575                         }
1576                         if item.check_name("transparent") {
1577                             gate_feature_post!(&self, repr_transparent, attr.span,
1578                                                "the `#[repr(transparent)]` attribute \
1579                                                is experimental");
1580                         }
1581                         if let Some((name, _)) = item.name_value_literal() {
1582                             if name == "packed" {
1583                                 gate_feature_post!(&self, repr_packed, attr.span,
1584                                                    "the `#[repr(packed(n))]` attribute \
1585                                                    is experimental");
1586                             }
1587                         }
1588                     }
1589                 }
1590             }
1591
1592             ast::ItemKind::TraitAlias(..) => {
1593                 gate_feature_post!(&self, trait_alias,
1594                                    i.span,
1595                                    "trait aliases are not yet fully implemented");
1596             }
1597
1598             ast::ItemKind::Impl(_, polarity, defaultness, _, _, _, _) => {
1599                 if polarity == ast::ImplPolarity::Negative {
1600                     gate_feature_post!(&self, optin_builtin_traits,
1601                                        i.span,
1602                                        "negative trait bounds are not yet fully implemented; \
1603                                         use marker types for now");
1604                 }
1605
1606                 if let ast::Defaultness::Default = defaultness {
1607                     gate_feature_post!(&self, specialization,
1608                                        i.span,
1609                                        "specialization is unstable");
1610                 }
1611             }
1612
1613             ast::ItemKind::Trait(ast::IsAuto::Yes, ..) => {
1614                 gate_feature_post!(&self, optin_builtin_traits,
1615                                    i.span,
1616                                    "auto traits are experimental and possibly buggy");
1617             }
1618
1619             ast::ItemKind::MacroDef(ast::MacroDef { legacy: false, .. }) => {
1620                 let msg = "`macro` is experimental";
1621                 gate_feature_post!(&self, decl_macro, i.span, msg);
1622             }
1623
1624             _ => {}
1625         }
1626
1627         visit::walk_item(self, i);
1628     }
1629
1630     fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
1631         match i.node {
1632             ast::ForeignItemKind::Fn(..) |
1633             ast::ForeignItemKind::Static(..) => {
1634                 let link_name = attr::first_attr_value_str_by_name(&i.attrs, "link_name");
1635                 let links_to_llvm = match link_name {
1636                     Some(val) => val.as_str().starts_with("llvm."),
1637                     _ => false
1638                 };
1639                 if links_to_llvm {
1640                     gate_feature_post!(&self, link_llvm_intrinsics, i.span,
1641                                        "linking to LLVM intrinsics is experimental");
1642                 }
1643             }
1644             ast::ForeignItemKind::Ty => {
1645                     gate_feature_post!(&self, extern_types, i.span,
1646                                        "extern types are experimental");
1647             }
1648             ast::ForeignItemKind::Macro(..) => {}
1649         }
1650
1651         visit::walk_foreign_item(self, i)
1652     }
1653
1654     fn visit_ty(&mut self, ty: &'a ast::Ty) {
1655         match ty.node {
1656             ast::TyKind::BareFn(ref bare_fn_ty) => {
1657                 self.check_abi(bare_fn_ty.abi, ty.span);
1658             }
1659             ast::TyKind::Never => {
1660                 gate_feature_post!(&self, never_type, ty.span,
1661                                    "The `!` type is experimental");
1662             }
1663             _ => {}
1664         }
1665         visit::walk_ty(self, ty)
1666     }
1667
1668     fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FunctionRetTy) {
1669         if let ast::FunctionRetTy::Ty(ref output_ty) = *ret_ty {
1670             if output_ty.node != ast::TyKind::Never {
1671                 self.visit_ty(output_ty)
1672             }
1673         }
1674     }
1675
1676     fn visit_expr(&mut self, e: &'a ast::Expr) {
1677         match e.node {
1678             ast::ExprKind::Box(_) => {
1679                 gate_feature_post!(&self, box_syntax, e.span, EXPLAIN_BOX_SYNTAX);
1680             }
1681             ast::ExprKind::Type(..) => {
1682                 gate_feature_post!(&self, type_ascription, e.span,
1683                                   "type ascription is experimental");
1684             }
1685             ast::ExprKind::Yield(..) => {
1686                 gate_feature_post!(&self, generators,
1687                                   e.span,
1688                                   "yield syntax is experimental");
1689             }
1690             ast::ExprKind::Catch(_) => {
1691                 gate_feature_post!(&self, catch_expr, e.span, "`catch` expression is experimental");
1692             }
1693             ast::ExprKind::IfLet(ref pats, ..) | ast::ExprKind::WhileLet(ref pats, ..) => {
1694                 if pats.len() > 1 {
1695                     gate_feature_post!(&self, if_while_or_patterns, e.span,
1696                                     "multiple patterns in `if let` and `while let` are unstable");
1697                 }
1698             }
1699             _ => {}
1700         }
1701         visit::walk_expr(self, e);
1702     }
1703
1704     fn visit_arm(&mut self, arm: &'a ast::Arm) {
1705         visit::walk_arm(self, arm)
1706     }
1707
1708     fn visit_pat(&mut self, pattern: &'a ast::Pat) {
1709         match pattern.node {
1710             PatKind::Slice(_, Some(ref subslice), _) => {
1711                 gate_feature_post!(&self, slice_patterns,
1712                                    subslice.span,
1713                                    "syntax for subslices in slice patterns is not yet stabilized");
1714             }
1715             PatKind::Box(..) => {
1716                 gate_feature_post!(&self, box_patterns,
1717                                   pattern.span,
1718                                   "box pattern syntax is experimental");
1719             }
1720             PatKind::Range(_, _, RangeEnd::Excluded) => {
1721                 gate_feature_post!(&self, exclusive_range_pattern, pattern.span,
1722                                    "exclusive range pattern syntax is experimental");
1723             }
1724             PatKind::Paren(..) => {
1725                 gate_feature_post!(&self, pattern_parentheses, pattern.span,
1726                                    "parentheses in patterns are unstable");
1727             }
1728             _ => {}
1729         }
1730         visit::walk_pat(self, pattern)
1731     }
1732
1733     fn visit_fn(&mut self,
1734                 fn_kind: FnKind<'a>,
1735                 fn_decl: &'a ast::FnDecl,
1736                 span: Span,
1737                 _node_id: NodeId) {
1738         // check for const fn declarations
1739         if let FnKind::ItemFn(_, _, Spanned { node: ast::Constness::Const, .. }, _, _, _) =
1740             fn_kind {
1741             gate_feature_post!(&self, const_fn, span, "const fn is unstable");
1742         }
1743         // stability of const fn methods are covered in
1744         // visit_trait_item and visit_impl_item below; this is
1745         // because default methods don't pass through this
1746         // point.
1747
1748         match fn_kind {
1749             FnKind::ItemFn(_, _, _, abi, _, _) |
1750             FnKind::Method(_, &ast::MethodSig { abi, .. }, _, _) => {
1751                 self.check_abi(abi, span);
1752             }
1753             _ => {}
1754         }
1755         visit::walk_fn(self, fn_kind, fn_decl, span);
1756     }
1757
1758     fn visit_trait_item(&mut self, ti: &'a ast::TraitItem) {
1759         match ti.node {
1760             ast::TraitItemKind::Method(ref sig, ref block) => {
1761                 if block.is_none() {
1762                     self.check_abi(sig.abi, ti.span);
1763                 }
1764                 if sig.constness.node == ast::Constness::Const {
1765                     gate_feature_post!(&self, const_fn, ti.span, "const fn is unstable");
1766                 }
1767             }
1768             ast::TraitItemKind::Type(_, ref default) => {
1769                 // We use three if statements instead of something like match guards so that all
1770                 // of these errors can be emitted if all cases apply.
1771                 if default.is_some() {
1772                     gate_feature_post!(&self, associated_type_defaults, ti.span,
1773                                        "associated type defaults are unstable");
1774                 }
1775                 if ti.generics.is_parameterized() {
1776                     gate_feature_post!(&self, generic_associated_types, ti.span,
1777                                        "generic associated types are unstable");
1778                 }
1779                 if !ti.generics.where_clause.predicates.is_empty() {
1780                     gate_feature_post!(&self, generic_associated_types, ti.span,
1781                                        "where clauses on associated types are unstable");
1782                 }
1783             }
1784             _ => {}
1785         }
1786         visit::walk_trait_item(self, ti);
1787     }
1788
1789     fn visit_impl_item(&mut self, ii: &'a ast::ImplItem) {
1790         if ii.defaultness == ast::Defaultness::Default {
1791             gate_feature_post!(&self, specialization,
1792                               ii.span,
1793                               "specialization is unstable");
1794         }
1795
1796         match ii.node {
1797             ast::ImplItemKind::Method(ref sig, _) => {
1798                 if sig.constness.node == ast::Constness::Const {
1799                     gate_feature_post!(&self, const_fn, ii.span, "const fn is unstable");
1800                 }
1801             }
1802             ast::ImplItemKind::Type(_) if ii.generics.is_parameterized() => {
1803                 gate_feature_post!(&self, generic_associated_types, ii.span,
1804                                    "generic associated types are unstable");
1805             }
1806             _ => {}
1807         }
1808         visit::walk_impl_item(self, ii);
1809     }
1810
1811     fn visit_path(&mut self, path: &'a ast::Path, _id: NodeId) {
1812         for segment in &path.segments {
1813             // Identifiers we are going to check could come from a legacy macro (e.g. `#[test]`).
1814             // For such macros identifiers must have empty context, because this context is
1815             // used during name resolution and produced names must be unhygienic for compatibility.
1816             // On the other hand, we need the actual non-empty context for feature gate checking
1817             // because it's hygienic even for legacy macros. As previously stated, such context
1818             // cannot be kept in identifiers, so it's kept in paths instead and we take it from
1819             // there while keeping location info from the ident span.
1820             let span = segment.ident.span.with_ctxt(path.span.ctxt());
1821             if segment.ident.name == keywords::Crate.name() {
1822                 gate_feature_post!(&self, crate_in_paths, span,
1823                                    "`crate` in paths is experimental");
1824             } else if segment.ident.name == keywords::Extern.name() {
1825                 gate_feature_post!(&self, extern_in_paths, span,
1826                                    "`extern` in paths is experimental");
1827             }
1828         }
1829
1830         visit::walk_path(self, path);
1831     }
1832
1833     fn visit_vis(&mut self, vis: &'a ast::Visibility) {
1834         if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.node {
1835             gate_feature_post!(&self, crate_visibility_modifier, vis.span,
1836                                "`crate` visibility modifier is experimental");
1837         }
1838         visit::walk_vis(self, vis);
1839     }
1840 }
1841
1842 pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
1843                     crate_edition: Edition) -> Features {
1844     fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) {
1845         let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
1846         if let Some(reason) = reason {
1847             err.span_note(span, reason);
1848         }
1849         err.emit();
1850     }
1851
1852     let mut features = Features::new();
1853
1854     let mut feature_checker = FeatureChecker::default();
1855
1856     for &(.., f_edition, set) in ACTIVE_FEATURES.iter() {
1857         if let Some(f_edition) = f_edition {
1858             if f_edition <= crate_edition {
1859                 set(&mut features, DUMMY_SP);
1860             }
1861         }
1862     }
1863
1864     for attr in krate_attrs {
1865         if !attr.check_name("feature") {
1866             continue
1867         }
1868
1869         let list = match attr.meta_item_list() {
1870             Some(list) => list,
1871             None => {
1872                 span_err!(span_handler, attr.span, E0555,
1873                           "malformed feature attribute, expected #![feature(...)]");
1874                 continue
1875             }
1876         };
1877
1878         for mi in list {
1879             let name = if let Some(word) = mi.word() {
1880                 word.name()
1881             } else {
1882                 span_err!(span_handler, mi.span, E0556,
1883                           "malformed feature, expected just one word");
1884                 continue
1885             };
1886
1887             if let Some((.., set)) = ACTIVE_FEATURES.iter().find(|f| name == f.0) {
1888                 set(&mut features, mi.span);
1889                 feature_checker.collect(&features, mi.span);
1890                 continue
1891             }
1892
1893             let removed = REMOVED_FEATURES.iter().find(|f| name == f.0);
1894             let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.0);
1895             if let Some((.., reason)) = removed.or(stable_removed) {
1896                 feature_removed(span_handler, mi.span, *reason);
1897                 continue
1898             }
1899
1900             if ACCEPTED_FEATURES.iter().any(|f| name == f.0) {
1901                 features.declared_stable_lang_features.push((name, mi.span));
1902                 continue
1903             }
1904
1905             if let Some(edition) = ALL_EDITIONS.iter().find(|e| name == e.feature_name()) {
1906                 if *edition <= crate_edition {
1907                     continue
1908                 }
1909
1910                 for &(.., f_edition, set) in ACTIVE_FEATURES.iter() {
1911                     if let Some(f_edition) = f_edition {
1912                         if *edition >= f_edition {
1913                             // FIXME(Manishearth) there is currently no way to set
1914                             // lib features by edition
1915                             set(&mut features, DUMMY_SP);
1916                         }
1917                     }
1918                 }
1919
1920                 continue
1921             }
1922
1923             features.declared_lib_features.push((name, mi.span));
1924         }
1925     }
1926
1927     feature_checker.check(span_handler);
1928
1929     features
1930 }
1931
1932 /// A collector for mutually exclusive and interdependent features and their flag spans.
1933 #[derive(Default)]
1934 struct FeatureChecker {
1935     proc_macro: Option<Span>,
1936     custom_attribute: Option<Span>,
1937 }
1938
1939 impl FeatureChecker {
1940     // If this method turns out to be a hotspot due to branching,
1941     // the branching can be eliminated by modifying `set!()` to set these spans
1942     // only for the features that need to be checked for mutual exclusion.
1943     fn collect(&mut self, features: &Features, span: Span) {
1944         if features.proc_macro {
1945             // If self.proc_macro is None, set to Some(span)
1946             self.proc_macro = self.proc_macro.or(Some(span));
1947         }
1948
1949         if features.custom_attribute {
1950             self.custom_attribute = self.custom_attribute.or(Some(span));
1951         }
1952     }
1953
1954     fn check(self, handler: &Handler) {
1955         if let (Some(pm_span), Some(ca_span)) = (self.proc_macro, self.custom_attribute) {
1956             handler.struct_span_err(pm_span, "Cannot use `#![feature(proc_macro)]` and \
1957                                               `#![feature(custom_attribute)] at the same time")
1958                 .span_note(ca_span, "`#![feature(custom_attribute)]` declared here")
1959                 .emit();
1960
1961             FatalError.raise();
1962         }
1963     }
1964 }
1965
1966 pub fn check_crate(krate: &ast::Crate,
1967                    sess: &ParseSess,
1968                    features: &Features,
1969                    plugin_attributes: &[(String, AttributeType)],
1970                    unstable: UnstableFeatures) {
1971     maybe_stage_features(&sess.span_diagnostic, krate, unstable);
1972     let ctx = Context {
1973         features,
1974         parse_sess: sess,
1975         plugin_attributes,
1976     };
1977
1978     if !features.raw_identifiers {
1979         for &span in sess.raw_identifier_spans.borrow().iter() {
1980             if !span.allows_unstable() {
1981                 gate_feature!(&ctx, raw_identifiers, span,
1982                     "raw identifiers are experimental and subject to change"
1983                 );
1984             }
1985         }
1986     }
1987
1988     let visitor = &mut PostExpansionVisitor { context: &ctx };
1989     visitor.whole_crate_feature_gates(krate);
1990     visit::walk_crate(visitor, krate);
1991 }
1992
1993 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
1994 pub enum UnstableFeatures {
1995     /// Hard errors for unstable features are active, as on
1996     /// beta/stable channels.
1997     Disallow,
1998     /// Allow features to be activated, as on nightly.
1999     Allow,
2000     /// Errors are bypassed for bootstrapping. This is required any time
2001     /// during the build that feature-related lints are set to warn or above
2002     /// because the build turns on warnings-as-errors and uses lots of unstable
2003     /// features. As a result, this is always required for building Rust itself.
2004     Cheat
2005 }
2006
2007 impl UnstableFeatures {
2008     pub fn from_environment() -> UnstableFeatures {
2009         // Whether this is a feature-staged build, i.e. on the beta or stable channel
2010         let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
2011         // Whether we should enable unstable features for bootstrapping
2012         let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok();
2013         match (disable_unstable_features, bootstrap) {
2014             (_, true) => UnstableFeatures::Cheat,
2015             (true, _) => UnstableFeatures::Disallow,
2016             (false, _) => UnstableFeatures::Allow
2017         }
2018     }
2019
2020     pub fn is_nightly_build(&self) -> bool {
2021         match *self {
2022             UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
2023             _ => false,
2024         }
2025     }
2026 }
2027
2028 fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate,
2029                         unstable: UnstableFeatures) {
2030     let allow_features = match unstable {
2031         UnstableFeatures::Allow => true,
2032         UnstableFeatures::Disallow => false,
2033         UnstableFeatures::Cheat => true
2034     };
2035     if !allow_features {
2036         for attr in &krate.attrs {
2037             if attr.check_name("feature") {
2038                 let release_channel = option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)");
2039                 span_err!(span_handler, attr.span, E0554,
2040                           "#![feature] may not be used on the {} release channel",
2041                           release_channel);
2042             }
2043         }
2044     }
2045 }