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