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