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