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