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