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