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