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