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