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