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