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