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