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