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