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