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