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