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