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