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