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