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