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