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