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