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