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