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