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