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