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