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