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