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