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