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