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