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