]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/feature_gate/check.rs
TAIT: feature gate recursive locations
[rust.git] / src / libsyntax / feature_gate / check.rs
1 use super::{active::{ACTIVE_FEATURES, Features}, Feature, State as FeatureState};
2 use super::accepted::ACCEPTED_FEATURES;
3 use super::removed::{REMOVED_FEATURES, STABLE_REMOVED_FEATURES};
4 use super::builtin_attrs::{AttributeGate, BUILTIN_ATTRIBUTE_MAP};
5
6 use crate::ast::{self, AssocTyConstraint, AssocTyConstraintKind, NodeId};
7 use crate::ast::{GenericParam, GenericParamKind, PatKind, RangeEnd, VariantData};
8 use crate::attr;
9 use crate::source_map::Spanned;
10 use crate::edition::{ALL_EDITIONS, Edition};
11 use crate::visit::{self, FnKind, Visitor};
12 use crate::sess::ParseSess;
13 use crate::symbol::{Symbol, sym};
14
15 use errors::{Applicability, DiagnosticBuilder, Handler};
16 use rustc_data_structures::fx::FxHashMap;
17 use syntax_pos::{Span, DUMMY_SP, MultiSpan};
18 use log::debug;
19
20 use std::env;
21 use std::num::NonZeroU32;
22
23 #[derive(Copy, Clone, Debug)]
24 pub enum Stability {
25     Unstable,
26     // First argument is tracking issue link; second argument is an optional
27     // help message, which defaults to "remove this attribute"
28     Deprecated(&'static str, Option<&'static str>),
29 }
30
31 macro_rules! gate_feature_fn {
32     ($cx: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr, $level: expr) => {{
33         let (cx, has_feature, span,
34              name, explain, level) = (&*$cx, $has_feature, $span, $name, $explain, $level);
35         let has_feature: bool = has_feature(&$cx.features);
36         debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
37         if !has_feature && !span.allows_unstable($name) {
38             leveled_feature_err(cx.parse_sess, name, span, GateIssue::Language, explain, level)
39                 .emit();
40         }
41     }}
42 }
43
44 macro_rules! gate_feature {
45     ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {
46         gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
47                          sym::$feature, $explain, GateStrength::Hard)
48     };
49     ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {
50         gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
51                          sym::$feature, $explain, $level)
52     };
53 }
54
55 pub fn check_attribute(attr: &ast::Attribute, parse_sess: &ParseSess, features: &Features) {
56     PostExpansionVisitor { parse_sess, features }.visit_attribute(attr)
57 }
58
59 fn find_lang_feature_issue(feature: Symbol) -> Option<NonZeroU32> {
60     if let Some(info) = ACTIVE_FEATURES.iter().find(|t| t.name == feature) {
61         // FIXME (#28244): enforce that active features have issue numbers
62         // assert!(info.issue().is_some())
63         info.issue()
64     } else {
65         // search in Accepted, Removed, or Stable Removed features
66         let found = ACCEPTED_FEATURES
67             .iter()
68             .chain(REMOVED_FEATURES)
69             .chain(STABLE_REMOVED_FEATURES)
70             .find(|t| t.name == feature);
71         match found {
72             Some(found) => found.issue(),
73             None => panic!("feature `{}` is not declared anywhere", feature),
74         }
75     }
76 }
77
78 pub enum GateIssue {
79     Language,
80     Library(Option<NonZeroU32>)
81 }
82
83 #[derive(Debug, Copy, Clone, PartialEq)]
84 pub enum GateStrength {
85     /// A hard error. (Most feature gates should use this.)
86     Hard,
87     /// Only a warning. (Use this only as backwards-compatibility demands.)
88     Soft,
89 }
90
91 pub fn emit_feature_err(
92     sess: &ParseSess,
93     feature: Symbol,
94     span: Span,
95     issue: GateIssue,
96     explain: &str,
97 ) {
98     feature_err(sess, feature, span, issue, explain).emit();
99 }
100
101 pub fn feature_err<'a, S: Into<MultiSpan>>(
102     sess: &'a ParseSess,
103     feature: Symbol,
104     span: S,
105     issue: GateIssue,
106     explain: &str,
107 ) -> DiagnosticBuilder<'a> {
108     leveled_feature_err(sess, feature, span, issue, explain, GateStrength::Hard)
109 }
110
111 fn leveled_feature_err<'a, S: Into<MultiSpan>>(
112     sess: &'a ParseSess,
113     feature: Symbol,
114     span: S,
115     issue: GateIssue,
116     explain: &str,
117     level: GateStrength,
118 ) -> DiagnosticBuilder<'a> {
119     let diag = &sess.span_diagnostic;
120
121     let issue = match issue {
122         GateIssue::Language => find_lang_feature_issue(feature),
123         GateIssue::Library(lib) => lib,
124     };
125
126     let mut err = match level {
127         GateStrength::Hard => {
128             diag.struct_span_err_with_code(span, explain, stringify_error_code!(E0658))
129         }
130         GateStrength::Soft => diag.struct_span_warn(span, explain),
131     };
132
133     if let Some(n) = issue {
134         err.note(&format!(
135             "for more information, see https://github.com/rust-lang/rust/issues/{}",
136             n,
137         ));
138     }
139
140     // #23973: do not suggest `#![feature(...)]` if we are in beta/stable
141     if sess.unstable_features.is_nightly_build() {
142         err.help(&format!("add `#![feature({})]` to the crate attributes to enable", feature));
143     }
144
145     // If we're on stable and only emitting a "soft" warning, add a note to
146     // clarify that the feature isn't "on" (rather than being on but
147     // warning-worthy).
148     if !sess.unstable_features.is_nightly_build() && level == GateStrength::Soft {
149         err.help("a nightly build of the compiler is required to enable this feature");
150     }
151
152     err
153
154 }
155
156 const EXPLAIN_BOX_SYNTAX: &str =
157     "box expression syntax is experimental; you can call `Box::new` instead";
158
159 pub const EXPLAIN_STMT_ATTR_SYNTAX: &str =
160     "attributes on expressions are experimental";
161
162 pub const EXPLAIN_ALLOW_INTERNAL_UNSTABLE: &str =
163     "allow_internal_unstable side-steps feature gating and stability checks";
164 pub const EXPLAIN_ALLOW_INTERNAL_UNSAFE: &str =
165     "allow_internal_unsafe side-steps the unsafe_code lint";
166
167 pub const EXPLAIN_UNSIZED_TUPLE_COERCION: &str =
168     "unsized tuple coercion is not stable enough for use and is subject to change";
169
170 struct PostExpansionVisitor<'a> {
171     parse_sess: &'a ParseSess,
172     features: &'a Features,
173 }
174
175 macro_rules! gate_feature_post {
176     ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {{
177         let (cx, span) = ($cx, $span);
178         if !span.allows_unstable(sym::$feature) {
179             gate_feature!(cx, $feature, span, $explain)
180         }
181     }};
182     ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {{
183         let (cx, span) = ($cx, $span);
184         if !span.allows_unstable(sym::$feature) {
185             gate_feature!(cx, $feature, span, $explain, $level)
186         }
187     }}
188 }
189
190 impl<'a> PostExpansionVisitor<'a> {
191     fn check_abi(&self, abi: ast::Abi) {
192         let ast::Abi { symbol, span } = abi;
193
194         match &*symbol.as_str() {
195             // Stable
196             "Rust" |
197             "C" |
198             "cdecl" |
199             "stdcall" |
200             "fastcall" |
201             "aapcs" |
202             "win64" |
203             "sysv64" |
204             "system" => {}
205             "rust-intrinsic" => {
206                 gate_feature_post!(&self, intrinsics, span,
207                                    "intrinsics are subject to change");
208             },
209             "platform-intrinsic" => {
210                 gate_feature_post!(&self, platform_intrinsics, span,
211                                    "platform intrinsics are experimental and possibly buggy");
212             },
213             "vectorcall" => {
214                 gate_feature_post!(&self, abi_vectorcall, span,
215                                    "vectorcall is experimental and subject to change");
216             },
217             "thiscall" => {
218                 gate_feature_post!(&self, abi_thiscall, span,
219                                    "thiscall is experimental and subject to change");
220             },
221             "rust-call" => {
222                 gate_feature_post!(&self, unboxed_closures, span,
223                                    "rust-call ABI is subject to change");
224             },
225             "ptx-kernel" => {
226                 gate_feature_post!(&self, abi_ptx, span,
227                                    "PTX ABIs are experimental and subject to change");
228             },
229             "unadjusted" => {
230                 gate_feature_post!(&self, abi_unadjusted, span,
231                                    "unadjusted ABI is an implementation detail and perma-unstable");
232             },
233             "msp430-interrupt" => {
234                 gate_feature_post!(&self, abi_msp430_interrupt, span,
235                                    "msp430-interrupt ABI is experimental and subject to change");
236             },
237             "x86-interrupt" => {
238                 gate_feature_post!(&self, abi_x86_interrupt, span,
239                                    "x86-interrupt ABI is experimental and subject to change");
240             },
241             "amdgpu-kernel" => {
242                 gate_feature_post!(&self, abi_amdgpu_kernel, span,
243                                    "amdgpu-kernel ABI is experimental and subject to change");
244             },
245             "efiapi" => {
246                 gate_feature_post!(&self, abi_efiapi, span,
247                                    "efiapi ABI is experimental and subject to change");
248             },
249             abi => {
250                 self.parse_sess.span_diagnostic.delay_span_bug(
251                     span,
252                     &format!("unrecognized ABI not caught in lowering: {}", abi),
253                 )
254             }
255         }
256     }
257
258     fn maybe_report_invalid_custom_discriminants(&self, variants: &[ast::Variant]) {
259         let has_fields = variants.iter().any(|variant| match variant.data {
260             VariantData::Tuple(..) | VariantData::Struct(..) => true,
261             VariantData::Unit(..) => false,
262         });
263
264         let discriminant_spans = variants.iter().filter(|variant| match variant.data {
265             VariantData::Tuple(..) | VariantData::Struct(..) => false,
266             VariantData::Unit(..) => true,
267         })
268         .filter_map(|variant| variant.disr_expr.as_ref().map(|c| c.value.span))
269         .collect::<Vec<_>>();
270
271         if !discriminant_spans.is_empty() && has_fields {
272             let mut err = feature_err(
273                 self.parse_sess,
274                 sym::arbitrary_enum_discriminant,
275                 discriminant_spans.clone(),
276                 crate::feature_gate::GateIssue::Language,
277                 "custom discriminant values are not allowed in enums with tuple or struct variants",
278             );
279             for sp in discriminant_spans {
280                 err.span_label(sp, "disallowed custom discriminant");
281             }
282             for variant in variants.iter() {
283                 match &variant.data {
284                     VariantData::Struct(..) => {
285                         err.span_label(
286                             variant.span,
287                             "struct variant defined here",
288                         );
289                     }
290                     VariantData::Tuple(..) => {
291                         err.span_label(
292                             variant.span,
293                             "tuple variant defined here",
294                         );
295                     }
296                     VariantData::Unit(..) => {}
297                 }
298             }
299             err.emit();
300         }
301     }
302
303     fn check_gat(&self, generics: &ast::Generics, span: Span) {
304         if !generics.params.is_empty() {
305             gate_feature_post!(
306                 &self,
307                 generic_associated_types,
308                 span,
309                 "generic associated types are unstable"
310             );
311         }
312         if !generics.where_clause.predicates.is_empty() {
313             gate_feature_post!(
314                 &self,
315                 generic_associated_types,
316                 span,
317                 "where clauses on associated types are unstable"
318             );
319         }
320     }
321
322     /// Feature gate `impl Trait` inside `type Alias = $type_expr;`.
323     fn check_impl_trait(&self, ty: &ast::Ty) {
324         struct ImplTraitVisitor<'a> {
325             vis: &'a PostExpansionVisitor<'a>,
326         }
327         impl Visitor<'_> for ImplTraitVisitor<'_> {
328             fn visit_ty(&mut self, ty: &ast::Ty) {
329                 if let ast::TyKind::ImplTrait(..) = ty.kind {
330                     gate_feature_post!(
331                         &self.vis,
332                         type_alias_impl_trait,
333                         ty.span,
334                         "`impl Trait` in type aliases is unstable"
335                     );
336                 }
337                 visit::walk_ty(self, ty);
338             }
339         }
340         ImplTraitVisitor { vis: self }.visit_ty(ty);
341     }
342 }
343
344 impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
345     fn visit_attribute(&mut self, attr: &ast::Attribute) {
346         let attr_info =
347             attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)).map(|a| **a);
348         // Check feature gates for built-in attributes.
349         if let Some((.., AttributeGate::Gated(_, name, descr, has_feature))) = attr_info {
350             gate_feature_fn!(self, has_feature, attr.span, name, descr, GateStrength::Hard);
351         }
352         // Check unstable flavors of the `#[doc]` attribute.
353         if attr.check_name(sym::doc) {
354             for nested_meta in attr.meta_item_list().unwrap_or_default() {
355                 macro_rules! gate_doc { ($($name:ident => $feature:ident)*) => {
356                     $(if nested_meta.check_name(sym::$name) {
357                         let msg = concat!("`#[doc(", stringify!($name), ")]` is experimental");
358                         gate_feature!(self, $feature, attr.span, msg);
359                     })*
360                 }}
361
362                 gate_doc!(
363                     include => external_doc
364                     cfg => doc_cfg
365                     masked => doc_masked
366                     spotlight => doc_spotlight
367                     alias => doc_alias
368                     keyword => doc_keyword
369                 );
370             }
371         }
372     }
373
374     fn visit_name(&mut self, sp: Span, name: ast::Name) {
375         if !name.as_str().is_ascii() {
376             gate_feature_post!(
377                 &self,
378                 non_ascii_idents,
379                 self.parse_sess.source_map().def_span(sp),
380                 "non-ascii idents are not fully supported"
381             );
382         }
383     }
384
385     fn visit_item(&mut self, i: &'a ast::Item) {
386         match i.kind {
387             ast::ItemKind::ForeignMod(ref foreign_module) => {
388                 self.check_abi(foreign_module.abi);
389             }
390
391             ast::ItemKind::Fn(..) => {
392                 if attr::contains_name(&i.attrs[..], sym::plugin_registrar) {
393                     gate_feature_post!(&self, plugin_registrar, i.span,
394                                        "compiler plugins are experimental and possibly buggy");
395                 }
396                 if attr::contains_name(&i.attrs[..], sym::start) {
397                     gate_feature_post!(&self, start, i.span,
398                                       "a `#[start]` function is an experimental \
399                                        feature whose signature may change \
400                                        over time");
401                 }
402                 if attr::contains_name(&i.attrs[..], sym::main) {
403                     gate_feature_post!(&self, main, i.span,
404                                        "declaration of a non-standard `#[main]` \
405                                         function may change over time, for now \
406                                         a top-level `fn main()` is required");
407                 }
408             }
409
410             ast::ItemKind::Struct(..) => {
411                 for attr in attr::filter_by_name(&i.attrs[..], sym::repr) {
412                     for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
413                         if item.check_name(sym::simd) {
414                             gate_feature_post!(&self, repr_simd, attr.span,
415                                                "SIMD types are experimental and possibly buggy");
416                         }
417                     }
418                 }
419             }
420
421             ast::ItemKind::Enum(ast::EnumDef{ref variants, ..}, ..) => {
422                 for variant in variants {
423                     match (&variant.data, &variant.disr_expr) {
424                         (ast::VariantData::Unit(..), _) => {},
425                         (_, Some(disr_expr)) =>
426                             gate_feature_post!(
427                                 &self,
428                                 arbitrary_enum_discriminant,
429                                 disr_expr.value.span,
430                                 "discriminants on non-unit variants are experimental"),
431                         _ => {},
432                     }
433                 }
434
435                 let has_feature = self.features.arbitrary_enum_discriminant;
436                 if !has_feature && !i.span.allows_unstable(sym::arbitrary_enum_discriminant) {
437                     self.maybe_report_invalid_custom_discriminants(&variants);
438                 }
439             }
440
441             ast::ItemKind::Impl(_, polarity, defaultness, ..) => {
442                 if polarity == ast::ImplPolarity::Negative {
443                     gate_feature_post!(&self, optin_builtin_traits,
444                                        i.span,
445                                        "negative trait bounds are not yet fully implemented; \
446                                         use marker types for now");
447                 }
448
449                 if let ast::Defaultness::Default = defaultness {
450                     gate_feature_post!(&self, specialization,
451                                        i.span,
452                                        "specialization is unstable");
453                 }
454             }
455
456             ast::ItemKind::Trait(ast::IsAuto::Yes, ..) => {
457                 gate_feature_post!(&self, optin_builtin_traits,
458                                    i.span,
459                                    "auto traits are experimental and possibly buggy");
460             }
461
462             ast::ItemKind::TraitAlias(..) => {
463                 gate_feature_post!(
464                     &self,
465                     trait_alias,
466                     i.span,
467                     "trait aliases are experimental"
468                 );
469             }
470
471             ast::ItemKind::MacroDef(ast::MacroDef { legacy: false, .. }) => {
472                 let msg = "`macro` is experimental";
473                 gate_feature_post!(&self, decl_macro, i.span, msg);
474             }
475
476             ast::ItemKind::TyAlias(ref ty, ..) => self.check_impl_trait(&ty),
477
478             _ => {}
479         }
480
481         visit::walk_item(self, i);
482     }
483
484     fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
485         match i.kind {
486             ast::ForeignItemKind::Fn(..) |
487             ast::ForeignItemKind::Static(..) => {
488                 let link_name = attr::first_attr_value_str_by_name(&i.attrs, sym::link_name);
489                 let links_to_llvm = match link_name {
490                     Some(val) => val.as_str().starts_with("llvm."),
491                     _ => false
492                 };
493                 if links_to_llvm {
494                     gate_feature_post!(&self, link_llvm_intrinsics, i.span,
495                                        "linking to LLVM intrinsics is experimental");
496                 }
497             }
498             ast::ForeignItemKind::Ty => {
499                     gate_feature_post!(&self, extern_types, i.span,
500                                        "extern types are experimental");
501             }
502             ast::ForeignItemKind::Macro(..) => {}
503         }
504
505         visit::walk_foreign_item(self, i)
506     }
507
508     fn visit_ty(&mut self, ty: &'a ast::Ty) {
509         match ty.kind {
510             ast::TyKind::BareFn(ref bare_fn_ty) => {
511                 self.check_abi(bare_fn_ty.abi);
512             }
513             ast::TyKind::Never => {
514                 gate_feature_post!(&self, never_type, ty.span,
515                                    "The `!` type is experimental");
516             }
517             _ => {}
518         }
519         visit::walk_ty(self, ty)
520     }
521
522     fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FunctionRetTy) {
523         if let ast::FunctionRetTy::Ty(ref output_ty) = *ret_ty {
524             if let ast::TyKind::Never = output_ty.kind {
525                 // Do nothing.
526             } else {
527                 self.visit_ty(output_ty)
528             }
529         }
530     }
531
532     fn visit_expr(&mut self, e: &'a ast::Expr) {
533         match e.kind {
534             ast::ExprKind::Box(_) => {
535                 gate_feature_post!(&self, box_syntax, e.span, EXPLAIN_BOX_SYNTAX);
536             }
537             ast::ExprKind::Type(..) => {
538                 // To avoid noise about type ascription in common syntax errors, only emit if it
539                 // is the *only* error.
540                 if self.parse_sess.span_diagnostic.err_count() == 0 {
541                     gate_feature_post!(&self, type_ascription, e.span,
542                                        "type ascription is experimental");
543                 }
544             }
545             ast::ExprKind::TryBlock(_) => {
546                 gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
547             }
548             ast::ExprKind::Block(_, opt_label) => {
549                 if let Some(label) = opt_label {
550                     gate_feature_post!(&self, label_break_value, label.ident.span,
551                                     "labels on blocks are unstable");
552                 }
553             }
554             _ => {}
555         }
556         visit::walk_expr(self, e)
557     }
558
559     fn visit_arm(&mut self, arm: &'a ast::Arm) {
560         visit::walk_arm(self, arm)
561     }
562
563     fn visit_pat(&mut self, pattern: &'a ast::Pat) {
564         match &pattern.kind {
565             PatKind::Slice(pats) => {
566                 for pat in &*pats {
567                     let span = pat.span;
568                     let inner_pat = match &pat.kind {
569                         PatKind::Ident(.., Some(pat)) => pat,
570                         _ => pat,
571                     };
572                     if inner_pat.is_rest() {
573                         gate_feature_post!(
574                             &self,
575                             slice_patterns,
576                             span,
577                             "subslice patterns are unstable"
578                         );
579                     }
580                 }
581             }
582             PatKind::Box(..) => {
583                 gate_feature_post!(&self, box_patterns,
584                                   pattern.span,
585                                   "box pattern syntax is experimental");
586             }
587             PatKind::Range(_, _, Spanned { node: RangeEnd::Excluded, .. }) => {
588                 gate_feature_post!(&self, exclusive_range_pattern, pattern.span,
589                                    "exclusive range pattern syntax is experimental");
590             }
591             _ => {}
592         }
593         visit::walk_pat(self, pattern)
594     }
595
596     fn visit_fn(&mut self,
597                 fn_kind: FnKind<'a>,
598                 fn_decl: &'a ast::FnDecl,
599                 span: Span,
600                 _node_id: NodeId) {
601         if let Some(header) = fn_kind.header() {
602             // Stability of const fn methods are covered in
603             // `visit_trait_item` and `visit_impl_item` below; this is
604             // because default methods don't pass through this point.
605             self.check_abi(header.abi);
606         }
607
608         if fn_decl.c_variadic() {
609             gate_feature_post!(&self, c_variadic, span, "C-variadic functions are unstable");
610         }
611
612         visit::walk_fn(self, fn_kind, fn_decl, span)
613     }
614
615     fn visit_generic_param(&mut self, param: &'a GenericParam) {
616         match param.kind {
617             GenericParamKind::Const { .. } =>
618                 gate_feature_post!(&self, const_generics, param.ident.span,
619                     "const generics are unstable"),
620             _ => {}
621         }
622         visit::walk_generic_param(self, param)
623     }
624
625     fn visit_assoc_ty_constraint(&mut self, constraint: &'a AssocTyConstraint) {
626         match constraint.kind {
627             AssocTyConstraintKind::Bound { .. } =>
628                 gate_feature_post!(&self, associated_type_bounds, constraint.span,
629                     "associated type bounds are unstable"),
630             _ => {}
631         }
632         visit::walk_assoc_ty_constraint(self, constraint)
633     }
634
635     fn visit_trait_item(&mut self, ti: &'a ast::TraitItem) {
636         match ti.kind {
637             ast::TraitItemKind::Method(ref sig, ref block) => {
638                 if block.is_none() {
639                     self.check_abi(sig.header.abi);
640                 }
641                 if sig.decl.c_variadic() {
642                     gate_feature_post!(&self, c_variadic, ti.span,
643                                        "C-variadic functions are unstable");
644                 }
645                 if sig.header.constness.node == ast::Constness::Const {
646                     gate_feature_post!(&self, const_fn, ti.span, "const fn is unstable");
647                 }
648             }
649             ast::TraitItemKind::Type(_, ref default) => {
650                 if let Some(ty) = default {
651                     self.check_impl_trait(ty);
652                     gate_feature_post!(&self, associated_type_defaults, ti.span,
653                                        "associated type defaults are unstable");
654                 }
655                 self.check_gat(&ti.generics, ti.span);
656             }
657             _ => {}
658         }
659         visit::walk_trait_item(self, ti)
660     }
661
662     fn visit_impl_item(&mut self, ii: &'a ast::ImplItem) {
663         if ii.defaultness == ast::Defaultness::Default {
664             gate_feature_post!(&self, specialization,
665                               ii.span,
666                               "specialization is unstable");
667         }
668
669         match ii.kind {
670             ast::ImplItemKind::Method(ref sig, _) => {
671                 if sig.decl.c_variadic() {
672                     gate_feature_post!(&self, c_variadic, ii.span,
673                                        "C-variadic functions are unstable");
674                 }
675             }
676             ast::ImplItemKind::TyAlias(ref ty) => {
677                 self.check_impl_trait(ty);
678                 self.check_gat(&ii.generics, ii.span);
679             }
680             _ => {}
681         }
682         visit::walk_impl_item(self, ii)
683     }
684
685     fn visit_vis(&mut self, vis: &'a ast::Visibility) {
686         if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.node {
687             gate_feature_post!(&self, crate_visibility_modifier, vis.span,
688                                "`crate` visibility modifier is experimental");
689         }
690         visit::walk_vis(self, vis)
691     }
692 }
693
694 pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
695                     crate_edition: Edition, allow_features: &Option<Vec<String>>) -> Features {
696     fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) {
697         let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
698         if let Some(reason) = reason {
699             err.span_note(span, reason);
700         } else {
701             err.span_label(span, "feature has been removed");
702         }
703         err.emit();
704     }
705
706     let mut features = Features::new();
707     let mut edition_enabled_features = FxHashMap::default();
708
709     for &edition in ALL_EDITIONS {
710         if edition <= crate_edition {
711             // The `crate_edition` implies its respective umbrella feature-gate
712             // (i.e., `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX).
713             edition_enabled_features.insert(edition.feature_name(), edition);
714         }
715     }
716
717     for feature in active_features_up_to(crate_edition) {
718         feature.set(&mut features, DUMMY_SP);
719         edition_enabled_features.insert(feature.name, crate_edition);
720     }
721
722     // Process the edition umbrella feature-gates first, to ensure
723     // `edition_enabled_features` is completed before it's queried.
724     for attr in krate_attrs {
725         if !attr.check_name(sym::feature) {
726             continue
727         }
728
729         let list = match attr.meta_item_list() {
730             Some(list) => list,
731             None => continue,
732         };
733
734         for mi in list {
735             if !mi.is_word() {
736                 continue;
737             }
738
739             let name = mi.name_or_empty();
740
741             let edition = ALL_EDITIONS.iter().find(|e| name == e.feature_name()).copied();
742             if let Some(edition) = edition {
743                 if edition <= crate_edition {
744                     continue;
745                 }
746
747                 for feature in active_features_up_to(edition) {
748                     // FIXME(Manishearth) there is currently no way to set
749                     // lib features by edition
750                     feature.set(&mut features, DUMMY_SP);
751                     edition_enabled_features.insert(feature.name, edition);
752                 }
753             }
754         }
755     }
756
757     for attr in krate_attrs {
758         if !attr.check_name(sym::feature) {
759             continue
760         }
761
762         let list = match attr.meta_item_list() {
763             Some(list) => list,
764             None => continue,
765         };
766
767         let bad_input = |span| {
768             struct_span_err!(span_handler, span, E0556, "malformed `feature` attribute input")
769         };
770
771         for mi in list {
772             let name = match mi.ident() {
773                 Some(ident) if mi.is_word() => ident.name,
774                 Some(ident) => {
775                     bad_input(mi.span()).span_suggestion(
776                         mi.span(),
777                         "expected just one word",
778                         format!("{}", ident.name),
779                         Applicability::MaybeIncorrect,
780                     ).emit();
781                     continue
782                 }
783                 None => {
784                     bad_input(mi.span()).span_label(mi.span(), "expected just one word").emit();
785                     continue
786                 }
787             };
788
789             if let Some(edition) = edition_enabled_features.get(&name) {
790                 struct_span_warn!(
791                     span_handler,
792                     mi.span(),
793                     E0705,
794                     "the feature `{}` is included in the Rust {} edition",
795                     name,
796                     edition,
797                 ).emit();
798                 continue;
799             }
800
801             if ALL_EDITIONS.iter().any(|e| name == e.feature_name()) {
802                 // Handled in the separate loop above.
803                 continue;
804             }
805
806             let removed = REMOVED_FEATURES.iter().find(|f| name == f.name);
807             let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.name);
808             if let Some(Feature { state, .. }) = removed.or(stable_removed) {
809                 if let FeatureState::Removed { reason }
810                 | FeatureState::Stabilized { reason } = state
811                 {
812                     feature_removed(span_handler, mi.span(), *reason);
813                     continue;
814                 }
815             }
816
817             if let Some(Feature { since, .. }) = ACCEPTED_FEATURES.iter().find(|f| name == f.name) {
818                 let since = Some(Symbol::intern(since));
819                 features.declared_lang_features.push((name, mi.span(), since));
820                 continue;
821             }
822
823             if let Some(allowed) = allow_features.as_ref() {
824                 if allowed.iter().find(|&f| name.as_str() == *f).is_none() {
825                     span_err!(span_handler, mi.span(), E0725,
826                               "the feature `{}` is not in the list of allowed features",
827                               name);
828                     continue;
829                 }
830             }
831
832             if let Some(f) = ACTIVE_FEATURES.iter().find(|f| name == f.name) {
833                 f.set(&mut features, mi.span());
834                 features.declared_lang_features.push((name, mi.span(), None));
835                 continue;
836             }
837
838             features.declared_lib_features.push((name, mi.span()));
839         }
840     }
841
842     features
843 }
844
845 fn active_features_up_to(edition: Edition) -> impl Iterator<Item=&'static Feature> {
846     ACTIVE_FEATURES.iter()
847     .filter(move |feature| {
848         if let Some(feature_edition) = feature.edition {
849             feature_edition <= edition
850         } else {
851             false
852         }
853     })
854 }
855
856 pub fn check_crate(krate: &ast::Crate,
857                    parse_sess: &ParseSess,
858                    features: &Features,
859                    unstable: UnstableFeatures) {
860     maybe_stage_features(&parse_sess.span_diagnostic, krate, unstable);
861     let mut visitor = PostExpansionVisitor { parse_sess, features };
862
863     let spans = parse_sess.gated_spans.spans.borrow();
864     macro_rules! gate_all {
865         ($gate:ident, $msg:literal) => {
866             for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
867                 gate_feature!(&visitor, $gate, *span, $msg);
868             }
869         }
870     }
871     gate_all!(let_chains, "`let` expressions in this position are experimental");
872     gate_all!(async_closure, "async closures are unstable");
873     gate_all!(generators, "yield syntax is experimental");
874     gate_all!(or_patterns, "or-patterns syntax is experimental");
875     gate_all!(const_extern_fn, "`const extern fn` definitions are unstable");
876
877     // All uses of `gate_all!` below this point were added in #65742,
878     // and subsequently disabled (with the non-early gating readded).
879     macro_rules! gate_all {
880         ($gate:ident, $msg:literal) => {
881             // FIXME(eddyb) do something more useful than always
882             // disabling these uses of early feature-gatings.
883             if false {
884                 for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
885                     gate_feature!(&visitor, $gate, *span, $msg);
886                 }
887             }
888         }
889     }
890
891     gate_all!(trait_alias, "trait aliases are experimental");
892     gate_all!(associated_type_bounds, "associated type bounds are unstable");
893     gate_all!(crate_visibility_modifier, "`crate` visibility modifier is experimental");
894     gate_all!(const_generics, "const generics are unstable");
895     gate_all!(decl_macro, "`macro` is experimental");
896     gate_all!(box_patterns, "box pattern syntax is experimental");
897     gate_all!(exclusive_range_pattern, "exclusive range pattern syntax is experimental");
898     gate_all!(try_blocks, "`try` blocks are unstable");
899     gate_all!(label_break_value, "labels on blocks are unstable");
900     gate_all!(box_syntax, "box expression syntax is experimental; you can call `Box::new` instead");
901     // To avoid noise about type ascription in common syntax errors,
902     // only emit if it is the *only* error. (Also check it last.)
903     if parse_sess.span_diagnostic.err_count() == 0 {
904         gate_all!(type_ascription, "type ascription is experimental");
905     }
906
907     visit::walk_crate(&mut visitor, krate);
908 }
909
910 #[derive(Clone, Copy, Hash)]
911 pub enum UnstableFeatures {
912     /// Hard errors for unstable features are active, as on beta/stable channels.
913     Disallow,
914     /// Allow features to be activated, as on nightly.
915     Allow,
916     /// Errors are bypassed for bootstrapping. This is required any time
917     /// during the build that feature-related lints are set to warn or above
918     /// because the build turns on warnings-as-errors and uses lots of unstable
919     /// features. As a result, this is always required for building Rust itself.
920     Cheat
921 }
922
923 impl UnstableFeatures {
924     pub fn from_environment() -> UnstableFeatures {
925         // `true` if this is a feature-staged build, i.e., on the beta or stable channel.
926         let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
927         // `true` if we should enable unstable features for bootstrapping.
928         let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok();
929         match (disable_unstable_features, bootstrap) {
930             (_, true) => UnstableFeatures::Cheat,
931             (true, _) => UnstableFeatures::Disallow,
932             (false, _) => UnstableFeatures::Allow
933         }
934     }
935
936     pub fn is_nightly_build(&self) -> bool {
937         match *self {
938             UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
939             UnstableFeatures::Disallow => false,
940         }
941     }
942 }
943
944 fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate, unstable: UnstableFeatures) {
945     if !unstable.is_nightly_build() {
946         for attr in krate.attrs.iter().filter(|attr| attr.check_name(sym::feature)) {
947             span_err!(
948                 span_handler, attr.span, E0554,
949                 "`#![feature]` may not be used on the {} release channel",
950                 option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)")
951             );
952         }
953     }
954 }