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